Passing and receiving dictionary of dictionary of parameters - python

Using AFNetworking, In my iPhone application I'd like to pass in the NSDictionary of parameters a dictionary of parameters like so:
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
for (int courseIdx=0; courseIdx < courses.count; courseIdx++)
{
parameters[courseIdx] = [[NSMutableDictionary alloc] init];
parameters[courseIdx]["courseID"] = courses[courseIdx].courseID;
parameters[courseIdx]["courseRate"] = courses[courseIdx].courseRate;
parameters[courseIdx]["profRate"] = courses[courseIdx].profRate;
}
then on the server side using python I'd like to extract these parameters... once I extract the dictionary (or Array of Dictionaries) I know how to extract the values...The Problem I don't know how to extract the inner dictionaries from the exterior on so I'd be able to run in a loop
if request.method == 'POST':
request_data=json.loads(request.POST['request'])
????
for param_data in ???
course_id = param_data['courseID']
...

Related

In google bigquery, how to use javascript UDF using google python client

I am writing a query in bigquery using standard SQL and javascript UDF. I am able to implement this using WebUI and bigquery command line tool but my requirement is to make this query using google python client. Not able to achieve this. Please can someone help.
from google.cloud import bigquery
bigquery_client = bigquery.Client()
client = bigquery.Client()
query_results = client.run_sync_query("""
CREATE TEMPORARY FUNCTION CategoriesToNumerical(a array<STRING>,b array<STRING>)
RETURNS string
LANGUAGE js AS """
var values = {};
var counter = 0;
for(i=0;i<a.length;i++)
{ var temp;
temp = a[i];
a[i] = counter;
values[temp] = counter;
counter ++;
}
for(i=0;i<b.length;i++)
{
for(var key in values)
{
if(b[i] == key)
{
b[i] = values[key];
}
}
}
return b;
""";
SELECT
CategoriesToNumerical(ARRAY(SELECT DISTINCT ProspectStage from lsq.lsq_dest),ARRAY(SELECT ProspectStage from lsq.lsq_dest)) as prospectstageds
;""")
query_results.use_legacy_sql = False
query_results.run()
page_token = None
while True:
rows1, total_rows, page_token = query_results.fetch_data(
max_results=100,
page_token=page_token)
for row1 in rows1:
print "row",row1
if not page_token:
break
This is not working for me.Please can someone help with how should I be going about it.
The problem seems to be you have here 2 sets of conflicting """. Replace one of these sets for a triple ''', and the code should work.
So instead of
query_results = client.run_sync_query("""
CREATE TEMPORARY FUNCTION CategoriesToNumerical(a array<STRING>,b array<STRING>)
RETURNS string
LANGUAGE js AS """
javacript code
"""
SELECT *
FROM
"""
write
query_results = client.run_sync_query('''
CREATE TEMPORARY FUNCTION CategoriesToNumerical(a array<STRING>,b array<STRING>)
RETURNS string
LANGUAGE js AS """
javacript code
"""
SELECT *
FROM
'''

Django serializing separate variables into json

I have min max variables that are a result of query on model
args.aggregate(Min('price'))
args.aggregate(Max('price'))
returning the serialized data like this
return HttpResponse(json.dumps([{"maxPrice":args.aggregate(Max('price')),
"minPrice":args.aggregate(Min('price'))}]), content_type ='application/json')
the result looks like this:
minPrice = {
"price__min" = 110;
};
maxPrice = {
"price__max" = 36000;
};
and extracting the data looks like this
...
success:^(AFHTTPRequestOperation *operation, id responseObject){
NSDictionary *elements = responseObject;
int minPrice = elements[0][#"minPrice"][#"price__min"];
}
The Question: how to change the django/python code in order for the objective-c code to look like this: int minPrice = elements[#"minPrice"];
data = args.aggregate(minPrice=Min('price'), maxPrice=Max('price'))
return HttpResponse(json.dumps(data), content_type='application/json')
data variable is a dictionary with "minPrice" and "maxPrice" keys.
Dump to JSON a dictionary instead of a list:
values = args.aggregate(Min('price'), Max('price'))
return HttpResponse(json.dumps({'maxPrice': values['price__max'],
'minPrice': values['price__min']}),
content_type ='application/json')
Well you could do something like this to rearrange the json dump:
data = {'maxPrice': args.aggregate(Max('price'))['price__max'],
'minPrice': args.aggregate(Min('price'))['price__min']}
return HttpResponse(json.dumps(data), content_type ='application/json')
That should give you a json dict of that form '{"maxPrice": xxx, "minPrice": yyy}'.

Tag number to Name string

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", "")

How to use couchdb-python to call a view with a list of keys?

I have this ViewDefinition:
""" Models id."""
models = ViewDefinition('models', 'by_authors', """
function(doc) {
if (doc.type == "definition") {
for (var i = 0; i < doc.authors.length; i++) {
var author = doc.authors[i];
emit(author, doc._id);
}
}
}""")
I am calling it like so:
models = []
for principal in principals:
models += [d.value for d in views.models(self._db)[principal].rows]
return list(set(models))
How can I ask for a list of keys instead and call it like:
models = [d.value for d in views.models(self._db)[*principals].rows]
Well the solution is quite simple also I had to read the source code to be able to find it.
models = [d.value for d in views.models(self._db, keys=principals).rows]

Ajax to Python Pyramid data

So far, I have managed to take a bunch of HTML elements for whose contentEditable attribute is True and join their id's and HTML data together to make an Ajax data string. I can get the serialized data back to the server, no problem. For example,
$(document).ready(function(){
$("#save").click(function(){
var ajax_string = ''
$( "[contenteditable=True]" ).each(function( intIndex ){
ajax_string = ajax_string + '&' + $("[contenteditable=True]")[intIndex].id + ':' + $(this).html();
});
$.ajax({
type:"POST",
url:"/episode_edit/{{ episode.ID_Episode }}",
data:ajax_string,
success:function(result){
<!--alert( ajax_string );-->
}
});
});
});
On the server:
for r in request.params: print r
I get strings:
AltTitle:some Alt Title
PrintTitle:The Print Title
Notes:A bunch o' notes.
My dilema now is that I need to convert each request.param string into a dictionary object, so I can map it back to my database model. I can think of some very ugly ways of doing this, but what is the best way?
You say you want to convert each request.param string into a dictionary object, but is that what you meant? It looks like each string is just a key/value pair.
You can pretty simply create a dictionary from those values using:
opts = {}
for r in request.params:
parts = r.split(':', 1)
if len(parts) == 2:
opts[parts[0]] = parts[1]
else:
# some error condition

Categories

Resources