In QuickFix, how can I get the name of the tag from the tag number using Python? For example, for OrdStatus, how do I convert tag number 5 to the String "OrdStatus_CANCELED"?
.NET:
If you are using QuickFIX/N, you can achieve this using a DataDictionary instance with whatever data source you want (e.g., FIX42.xml). Note that you can get the DataDictionary instance associated with a given Session or the application itself with Session's properties SessionDataDictionary and ApplicationDataDictionary, respectively.
Consider this trivial C# program:
namespace QuickFixTests
{
using System;
using QuickFix;
using QuickFix.DataDictionary;
using QuickFix.Fields;
class Program
{
static void Main(string[] args)
{
var qfm = new Message();
qfm.SetField(new OrdStatus('4'));
var ordStatus = qfm.GetField(Tags.OrdStatus);
var dd = new DataDictionary("FIX42.xml");
Console.WriteLine(dd.FieldsByTag[39].EnumDict[ordStatus]); // Prints CANCELED
}
}
}
C++/Python:
The C++ DataDictionary class has a method getValueName:
bool getValueName( int field, const std::string& value, std::string& name ) const
{
ValueToName::const_iterator i = m_valueNames.find( std::make_pair(field, value) );
if(i == m_valueNames.end()) return false;
name = i->second;
return true;
}
The following snippets (with comments added) from one of the Python DataDictionary unit tests show how to use getValueName given a DataDictionary instance.
# Create a DataDictionary
def setUp(self):
self.object = fix.DataDictionary()
# Add a dummy value
self.object.addValueName( 23, "BOO", "VALUE_23_BOO" )
# Test that the dummy value's name in the dictionary matches what was set
self.assertEquals( "VALUE_23_BOO", self.object.getValueName(23, "BOO", "")
Related
Im currently having hard time on mutation enum Argument.
Below are my code for Mutation:
class CreatePerson(graphene.Mutation):
foo = graphene.String()
def mutate(self, info, **kwargs):
return CreatePerson(foo='foo')
class Arguments:
enum_arg = graphene.Argument(graphene.Enum.from_enum(EnumArg))
Enum class:
from enum import Enum
class EnumArg(Enum):
Baz = 0
Bar = 1
Spam = 2
Egg = 3
Command using POSTMAN:
{
"query": "mutation": {createPerson(enumArg=1) { foo }}
}
But I end up this error message:
"message": "Argument \"enumArg\" has invalid value 1.
Expected type \"EnumArg\", found 1.",
I also tried giving enumArg=\"Bar\" on the createPerson mutation and the error still persists.
When defining an enum, we can assign an arbitrary value to each enum value in the enum. However, this value is only used internally by the GraphQL service itself. For example, if the type of a field's argument is the enum, this value will be passed to the field's resolver as the argument value. However, when composing a GraphQL document, the enum value must always be referred to by it's name, not it's value.
mutation {
createPerson(enumArg: Bar) {
foo
}
}
enum defined in backend is:
enum Gender {
MALE
FEMALE
}
I am using Vue for frontend so passing data to the mutation from Vue can be done like this.
I have defined gender as a string in my local state of the component as:
data(){
return {
gender: ''
}
}
The method from Vue is:
async handleEditProfile () {
const response = await this.$apollo.mutate({
query: EDIT_PROFILE,
variables: {
nameAsInPan: this.nameAsInPan,
gender: this.gender,
dateOfBirth: this.dateOfBirth
}
})
}
mutation used above EDIT_PROFILE:
gql`mutation editProfile($name: String!, $email: String!,$phone: String!, $gender: Gender!, $dateOfBirth: String!) {
editProfile (profileInput:{name: $name, email: $email, phone: $phone, gender: $gender, dateOfBirth: $dateOfBirth}){
id
email
phone
firstName
lastName
nameAsInPan
gender
dateOfBirth
}
}
`
use the enum variable name as defined in the mutation and send it to Graphql, like I have used gender As
$gender: Gender! in gql mutation. You don't have to worry about sending data as enum, just send it as String otherwise you will have to face JSON error, Graphql will take care of the value you send as a string (like 'MALE' or 'FEMALE') just don't forget to mention that gender is type of Gender(which is enum) in gql mutation as I did above.
Please read my answer on this link Link for reference
I want to create a BigTable DeleteFromRow mutation. The proto for the Mutation and the DeleteFromRow look like this:
oneof mutation {
// Set a cell's value.
SetCell set_cell = 1;
// Deletes cells from a column.
DeleteFromColumn delete_from_column = 2;
// Deletes cells from a column family.
DeleteFromFamily delete_from_family = 3;
// Deletes cells from the entire row.
DeleteFromRow delete_from_row = 4;
}
}
message DeleteFromRow {
}
In Python, you cannot directly instantiate a DeleteFromRow object and set the delete_from_row field of the Mutation to that object.
So this does not work:
request = bigtable_pb2.MutateRowRequest(table_name='tablename', row_key=row_key)
mutation = request.mutations.add()
mutation.delete_from_row = data_pb2.Mutation.DeleteFromRow()
As raised by other SO users (see this question), that results in a
AttributeError: Assignment not allowed to composite field "delete_from_row" in protocol message object.
According to the protobuf docs, you should set a oneof field by setting one of the child fields. So a DeleteFromFamily mutation should be created this way:
mutation.delete_from_family.family_name = 'some_family'
However, how do I do that for the DeleteFromRow message that has no fields?
You can use Message.SetInParent:
Mark this as present in the parent.
This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.
Example:
message Msg {
oneof kind {
int64 int_field = 1;
EmptyMsg msg_field = 1;
}
}
message EmptyMsg {}
msg = Msg()
print(msg.WhichOneof('kind')) # None
msg.msg_field # No-op (return EmptyMsg but don't set oneof field)
print(msg.WhichOneof('kind')) # None
msg.msg_field.SetInParent()
print(v.WhichOneof('kind')) # msg_field
You can initiate the DeleteFromRow object and create a mutation with the keyword argument delete_from_row:
dfr = data_pb2.Mutation.DeleteFromRow()
mutation = data_pb2.Mutation(delete_from_row=dfr)
While you cannot add or append this mutation to the repeated mutations field of a request (although it appears to me that that is what the docs says here), you can extend it:
request = bigtable_pb2.MutateRowRequest(table_name='tablename', row_key=row_key)
request.mutations.extend([mutation])
Making form with deform and whould like to change the pageShema class depending on the choices made by the user.
Ex. if he selects option 1 from selectwidget, show him one set of fields, if case of other choice - another.
How to do this?
You can use jquery and select with the "name" attribute.
Also, you can use the jquery "parent()" function to get the container of the input you are interested in showing/hiding.
For instance, in your schema do something like:
# This is the "<select>"
choices = (('yes','Yes'),
('no', 'No'))
bar = colander.SchemaNode(colander.String(),
widget=deform.widget.SelectWidget(values=choices))
# This is the input that should appear only when the "yes" value is selected
foo = colander.SchemaNode(colander.String())
Then, in your template, add somethig like:
<script>
$( document ).ready(function() {
// ensure that the "foo" input starts hidden
var target = $("input[name=foo]").parent().parent();
target.hide();
$("select[name=bar]").on('change', function(){
var valueSelected = this.value;
if (valueSelected == "yes") {
target.show();
} else {
target.hide();
}
});
});
</script>
I need some advice. Two questions, does something already exist for this, what modules should I use to develop this.
I have some structures that come from an XML file. I want to represent them in Python Classes (maybe using a factory to create a class per structure). But I want these classes to have a function that will emit the structure as a C Struct.
From my research ctypes seems like the recommended thing to use to represent the structures in Python classes, but I don't see any methods for anything that will emit C Stucts for the creation of a header file.
From OP's comment I think the minimal solution a set of helper functions instead of classes. the xmltodict library makes it easy to turn the XML data into nested dictionaries, more or less like JSON. A set of helpers that parse the contents and generate appropriate C-struct strings is all that's really needed. If you can work with dictionaries :
{
"name": "my_struct",
"members": {
[
"name": "intmember",
"ctype": "int"
},
{
"name": "floatmember",
"ctype": "float"
}
]
}
You can do something like:
from string import Template
struct_template_string = '''
typedef $structname struct {
$defs
} $structname;
'''
struct_template = Template(struct_template_string)
member_template = Template(" $ctype $name;")
def spec_to_struct(spec_dict):
structname = spec_dict['name']
member_data = spec_dict['members']
members = [member_template.substitute(d) for d in member_data]
return struct_template.substitute(structname = structname, defs = "\n".join(members))
Which will produce something like:
typedef my_struct struct {
int intmember;
float floatmember;
} my_struct;
I'd try to get it working with basic functions first before trying to build up a class scaffold. It would be pretty easy to hide the details in a class using property descriptors:
class data_property(object):
def __init__(self, path, wrapper = None):
self.path = path
self.wrapper = wrapper
def __get__(self, instance, owner):
result = instance[self.path]
if self.wrapper:
if hasattr(result, '__iter__'):
return [self.wrapper(**i) for i in result]
return self.wrapper(**result)
return result
class MemberWrapper(dict):
name = data_property('name')
type = data_property('ctype')
class StructWrapper(dict):
name = data_property('name')
members = data_property('members', MemberWrapper )
test = StructWrapper(**example)
print test.name
print test.members
for member in test.members:
print member.type, member.name
# my_struct
# [{'name': 'intmember', 'ctype': 'int'}, {'name': 'floatmember', 'ctype': 'float'}]
# int intmember
# float floatmember
I'm new to Python so forgive me if I'm not even using the right terminology... I'm using Python 3.2 and I'm trying to figure out whether I can decorate a class property with some declarative-style information.
In my mind it would look like this:
class MyTestClass:
def __init__(self, foo):
self.foo = foo
#property
#somedeclarativeInfo("ABC",123)
def radius(self):
return self.__foo
#radius.setter
def radius(self, foo):
self.__foo = foo
There are then two different things I'd want to do with the class:
A - Be able to interact with the foo property just like any other property (simple gets and sets)
B - Be able to dynamically find properties on a particular class that are decorated with this descriptor and be able to pull out the "ABC" and 123 values, etc.
I think maybe I should be creating a descriptor to accomplish what I want, but I'm not sure if I'm on the right track, or if this can be done.
Since my background is .Net I whipped up the following example to show what I want to do, in case that helps anyone understand my goal:
using System;
using System.Reflection;
namespace SampleWithProperties
{
public class MyCustomAttribute : Attribute
{
public string Val1;
public string Val2;
public MyCustomAttribute(string val1,string val2)
{
Val2 = val2;
Val1 = val1;
}
}
public class Foo
{
[MyCustomAttribute("abc","def")]
public string PropertyA { get; set; }
[MyCustomAttribute("xyz","X")]
public int PropertyB { get; set; }
public string PropertyC { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Show that we can figure out which properties have the custom attribute,
// and that we can get the values for Val1 and Val2
foreach(PropertyInfo propertyInfo in typeof(Foo).GetProperties())
{
Console.WriteLine("Found a property named "+propertyInfo.Name);
foreach(Attribute attribute in propertyInfo.GetCustomAttributes(
attributeType:typeof(MyCustomAttribute),inherit:true))
{
Console.WriteLine("Found a MyCustomAttribute on the property.");
MyCustomAttribute myCustomAttribute = attribute as MyCustomAttribute;
Console.WriteLine("Val1 = " + myCustomAttribute.Val1);
Console.WriteLine("Val2 = " + myCustomAttribute.Val2);
}
Console.WriteLine();
}
// Show that the properties can be used like normal
Foo foo = new Foo {PropertyA = "X", PropertyB = 2, PropertyC = "Z"};
Console.WriteLine("Created an instance of Foo just for fun. Its property values are "+
foo.PropertyA+","+foo.PropertyB+","+foo.PropertyC);
}
}
}
Can this be done?
There is no simple way to do what you want with properties. You can't simply set attributes on or get attributes from items protected by a property.
def declarativeInfo(*args, **kwargs):
def wrapper(obj):
for arg in args:
setattr(obj, arg, arg)
for k, v in kwargs:
setattr(obj, k, v)
return obj
return wrapper
class MyTestClass:
def __init__(self, foo):
print MyTestClass.__dict__
self.radius = self.Radius('foo')
#declarativeInfo(bar="ABC",baz=123)
class Radius(object):
def __init__(self, foo):
self.value = foo
a = MyTestClass('foo')
print a.radius.value
print a.radius.a
is the easiest way to do this. You can always, of course, make value a property.
If you really want radius to be a normal property, you can store the information elsewhere in a dict and retrieve it from self.propdict or something.
OK, I wrote this question when I was first getting started with Python. I now know how to do in Python exactly what the .Net sample code I posted did. Granted, the biggest thing I didn't realize when I originally posted the question was that descriptors alter the behavior of your attributes/properties(whatever you call them). Nonetheless, we can still allow these attributes to act like properties (and not change their behavior) yet put some metadata on them with the decorator. I'm currently implementing some protocol serialization/deserialization stuff where this is going to come in handy.
class MyCustomDescriptor:
def __init__(self,val1,val2):d
self._val1 = val1
self._val2 = val2
#property
def val1(self): return self._val1
#property
def val2(self): return self._val2
def __call__(self,decorated_method_reference):
self._decorated_method_reference = decorated_method_reference
return self
def __get__(self,instance,type=None):
if not instance:
return self
return self._decorated_method_reference(instance)
class Foo:
def __init__(self,attribute_a_value,attribute_b_value,attribute_c_value):
self._attribute_a_value = attribute_a_value
self._attribute_b_value = attribute_b_value
self._attribute_c_value = attribute_c_value
#MyCustomDescriptor(val1="abc",val2="def")
def attribute_a(self): return self._attribute_a_value
#MyCustomDescriptor(val1="xyz",val2="X")
def attribute_b(self): return self._attribute_b_value
#property
def attribute_c(self): return self._attribute_c_value
# Show that by inspecting class Foo we can figure out which attribute are marked with MyCustomDescriptor and that
# we can get the values for val1 and val2. We don't even need an instance of Foo to do this. The class itself is sufficient.
print("Inspecting class Foo. Looking for attributes marked with MyCustomDescriptor...")
for attribute_name in dir(Foo):
attribute_as_object = getattr(Foo,attribute_name)
if type(attribute_as_object) == MyCustomDescriptor:
print("attribute "+attribute_name+" is decorated with MyCustomDescriptor. val1="+attribute_as_object.val1+" val2="+attribute_as_object.val2)
# Show that the properties on Foo work like normal properties. Note that I skipped implementing setters but could have done so.
foo_instance = Foo(attribute_a_value="X",attribute_b_value=2,attribute_c_value="Z")
print("Created an instance of Foo just for fun. It's property values are "+str(foo_instance.attribute_a)+", "+str(foo_instance.attribute_b)+", "+str(foo_instance.attribute_c))
The output is:
Inspecting class Foo.
Looking for attributes marked with MyCustomDescriptor...
attribute attribute_a is decorated with MyCustomDescriptor.
val1=abc val2=def
attribute attribute_b is decorated with MyCustomDescriptor.
val1=xyz val2=X
Created an instance of Foo just for fun.
It's property values are X, 2, Z