Django REST Framework: overriding getqueryset sometimes returns a doubled queryset; Django Rest Framework doesn't serialize SerializerMethodField; Django REST Framework - getqueryset: 'MyModel' object has no attribute 'model' Django Rest Framework view getqueryset is called twice; Django REST Framework, working with list of objects after getqueryset.
Django’s serialization framework provides a mechanism for “translating” Djangomodels into other formats. Usually these other formats will be text-based andused for sending Django data over a wire, but it’s possible for aserializer to handle any format (text-based or not).
See also
If you just want to get some data from your tables into a serializedform, you could use the
dumpdata
management command.Serializing data¶
At the highest level, you can serialize data like this:
The arguments to the
serialize
function are the format to serialize the datato (see Serialization formats) and aQuerySet
to serialize. (Actually, the secondargument can be any iterator that yields Django model instances, but it’llalmost always be a QuerySet).django.core.serializers.
get_serializer
(format)¶
You can also use a serializer object directly:
This is useful if you want to serialize data directly to a file-like object(which includes an
HttpResponse
):Note
Calling
get_serializer()
with an unknownformat will raise adjango.core.serializers.SerializerDoesNotExist
exception.Subset of fields¶
If you only want a subset of fields to be serialized, you canspecify a
fields
argument to the serializer:In this example, only the
name
and size
attributes of each model willbe serialized. The primary key is always serialized as the pk
element in theresulting output; it never appears in the fields
part.Note
Depending on your model, you may find that it is not possible todeserialize a model that only serializes a subset of its fields. If aserialized object doesn’t specify all the fields that are required by amodel, the deserializer will not be able to save deserialized instances.
Inherited models¶
If you have a model that is defined using an abstract base class, you don’t have to do anything special to serializethat model. Call the serializer on the object (or objects) that you want toserialize, and the output will be a complete representation of the serializedobject.
However, if you have a model that uses multi-table inheritance, you also need to serialize all of the base classesfor the model. This is because only the fields that are locally defined on themodel will be serialized. For example, consider the following models:
If you only serialize the Restaurant model:
the fields on the serialized output will only contain the
serves_hot_dogs
attribute. The name
attribute of the base class will be ignored.In order to fully serialize your
Restaurant
instances, you will need toserialize the Place
models as well:Deserializing data¶
Deserializing data is very similar to serializing it:
As you can see, the
deserialize
function takes the same format argument asserialize
, a string or stream of data, and returns an iterator.However, here it gets slightly complicated. The objects returned by the
deserialize
iterator aren’t regular Django objects. Instead, they arespecial DeserializedObject
instances that wrap a created – but unsaved –object and any associated relationship data.Calling
DeserializedObject.save()
saves the object to the database.Note
If the
pk
attribute in the serialized data doesn’t exist or isnull, a new instance will be saved to the database.This ensures that deserializing is a non-destructive operation even if thedata in your serialized representation doesn’t match what’s currently in thedatabase. Usually, working with these
DeserializedObject
instances lookssomething like:In other words, the usual use is to examine the deserialized objects to makesure that they are “appropriate” for saving before doing so. Of course, if youtrust your data source you can instead save the object directly and move on.
The Django object itself can be inspected as
deserialized_object.object
.If fields in the serialized data do not exist on a model, aDeserializationError
will be raised unless the ignorenonexistent
argument is passed in as True
:Serialization formats¶
Django supports a number of serialization formats, some of which require youto install third-party Python modules:
Identifier | Information |
---|---|
xml | Serializes to and from a simple XML dialect. |
json | Serializes to and from JSON. |
yaml | Serializes to YAML (YAML Ain’t a Markup Language). Thisserializer is only available if PyYAML is installed. |
XML¶
The basic XML serialization format looks like this:
The whole collection of objects that is either serialized or deserialized isrepresented by a
<django-objects>
-tag which contains multiple<object>
-elements. Each such object has two attributes: “pk” and “model”,the latter being represented by the name of the app (“sessions”) and thelowercase name of the model (“session”) separated by a dot.Each field of the object is serialized as a
<field>
-element sporting thefields “type” and “name”. The text content of the element represents the valuethat should be stored.Foreign keys and other relational fields are treated a little bit differently:
In this example we specify that the
auth.Permission
object with the PK 27has a foreign key to the contenttypes.ContentType
instance with the PK 9.ManyToMany-relations are exported for the model that binds them. For instance,the
auth.User
model has such a relation to the auth.Permission
model:This example links the given user with the permission models with PKs 46 and 47.
Control characters
If the content to be serialized contains control characters that are notaccepted in the XML 1.0 standard, the serialization will fail with a
ValueError
exception. Read also the W3C’s explanation of HTML,XHTML, XML and Control Codes.JSON¶
When staying with the same example data as before it would be serialized asJSON in the following way:
The formatting here is a bit simpler than with XML. The whole collectionis just represented as an array and the objects are represented by JSON objectswith three properties: “pk”, “model” and “fields”. “fields” is again an objectcontaining each field’s name and value as property and property-valuerespectively.
Foreign keys have the PK of the linked object as property value.ManyToMany-relations are serialized for the model that defines them and arerepresented as a list of PKs.
Be aware that not all Django output can be passed unmodified to
json
.For example, if you have some custom type in an object to be serialized, you’llhave to write a custom json
encoder for it. Something like this willwork:You can then pass
cls=LazyEncoder
to the serializers.serialize()
function:Also note that GeoDjango provides a customized GeoJSON serializer.
DjangoJSONEncoder
¶
- class
django.core.serializers.json.
DjangoJSONEncoder
¶
The JSON serializer uses
DjangoJSONEncoder
for encoding. A subclass ofJSONEncoder
, it handles these additional types:datetime
- A string of the form
YYYY-MM-DDTHH:mm:ss.sssZ
orYYYY-MM-DDTHH:mm:ss.sss+HH:MM
as defined in ECMA-262. date
- A string of the form
YYYY-MM-DD
as defined in ECMA-262. time
- A string of the form
HH:MM:ss.sss
as defined in ECMA-262. timedelta
- A string representing a duration as defined in ISO-8601. For example,
timedelta(days=1,hours=2,seconds=3.4)
is represented as'P1DT02H00M03.400000S'
. Decimal
,Promise
(django.utils.functional.lazy()
objects),UUID
- A string representation of the object.
YAML¶
YAML serialization looks quite similar to JSON. The object list is serializedas a sequence mappings with the keys “pk”, “model” and “fields”. Each field isagain a mapping with the key being name of the field and the value the value:
Referential fields are again represented by the PK or sequence of PKs.
Natural keys¶
The default serialization strategy for foreign keys and many-to-many relationsis to serialize the value of the primary key(s) of the objects in the relation.This strategy works well for most objects, but it can cause difficulty in somecircumstances.
Consider the case of a list of objects that have a foreign key referencing
ContentType
. If you’re going toserialize an object that refers to a content type, then you need to have a wayto refer to that content type to begin with. Since ContentType
objects areautomatically created by Django during the database synchronization process,the primary key of a given content type isn’t easy to predict; it willdepend on how and when migrate
was executed. This is true for allmodels which automatically generate objects, notably includingPermission
,Group
, andUser
.Warning
You should never include automatically generated objects in a fixture orother serialized data. By chance, the primary keys in the fixturemay match those in the database and loading the fixture willhave no effect. In the more likely case that they don’t match, the fixtureloading will fail with an
IntegrityError
.There is also the matter of convenience. An integer id isn’t alwaysthe most convenient way to refer to an object; sometimes, amore natural reference would be helpful.
It is for these reasons that Django provides natural keys. A naturalkey is a tuple of values that can be used to uniquely identify anobject instance without using the primary key value.
Deserialization of natural keys¶
Consider the following two models:
Ordinarily, serialized data for
Book
would use an integer to refer tothe author. For example, in JSON, a Book might be serialized as:This isn’t a particularly natural way to refer to an author. Itrequires that you know the primary key value for the author; it alsorequires that this primary key value is stable and predictable.
However, if we add natural key handling to Person, the fixture becomesmuch more humane. To add natural key handling, you define a defaultManager for Person with a
get_by_natural_key()
method. In the caseof a Person, a good natural key might be the pair of first and lastname:Now books can use that natural key to refer to
Person
objects:When you try to load this serialized data, Django will use the
get_by_natural_key()
method to resolve ['Douglas','Adams']
into the primary key of an actual Person
object.Note
Whatever fields you use for a natural key must be able to uniquelyidentify an object. This will usually mean that your model willhave a uniqueness clause (either unique=True on a single field, or
unique_together
over multiple fields) for the field or fieldsin your natural key. However, uniqueness doesn’t need to beenforced at the database level. If you are certain that a set offields will be effectively unique, you can still use those fieldsas a natural key.Deserialization of objects with no primary key will always check whether themodel’s manager has a
get_by_natural_key()
method and if so, use it topopulate the deserialized object’s primary key.Serialization of natural keys¶
So how do you get Django to emit a natural key when serializing an object?Firstly, you need to add another method – this time to the model itself:
That method should always return a natural key tuple – in thisexample,
(firstname,lastname)
. Then, when you callserializers.serialize()
, you provide use_natural_foreign_keys=True
or use_natural_primary_keys=True
arguments:When
use_natural_foreign_keys=True
is specified, Django will use thenatural_key()
method to serialize any foreign key reference to objectsof the type that defines the method.When
use_natural_primary_keys=True
is specified, Django will not provide theprimary key in the serialized data of this object since it can be calculatedduring deserialization:This can be useful when you need to load serialized data into an existingdatabase and you cannot guarantee that the serialized primary key value is notalready in use, and do not need to ensure that deserialized objects retain thesame primary keys.
If you are using
dumpdata
to generate serialized data, use thedumpdata--natural-foreign
and dumpdata--natural-primary
command line flags to generate natural keys.Note
You don’t need to define both
natural_key()
andget_by_natural_key()
. If you don’t want Django to outputnatural keys during serialization, but you want to retain theability to load natural keys, then you can opt to not implementthe natural_key()
method.Conversely, if (for some strange reason) you want Django to outputnatural keys during serialization, but not be able to load thosekey values, just don’t define the
get_by_natural_key()
method.Natural keys and forward references¶
Sometimes when you use natural foreign keys you’ll need to deserialize data wherean object has a foreign key referencing another object that hasn’t yet beendeserialized. This is called a “forward reference”.
For instance, suppose you have the following objects in your fixture:
In order to handle this situation, you need to pass
handle_forward_references=True
to serializers.deserialize()
. This willset the deferred_fields
attribute on the DeserializedObject
instances.You’ll need to keep track of DeserializedObject
instances where thisattribute isn’t None
and later call save_deferred_fields()
on them.Typical usage looks like this:
For this to work, the
ForeignKey
on the referencing model must havenull=True
.Dependencies during serialization¶
It’s often possible to avoid explicitly having to handle forward references bytaking care with the ordering of objects within a fixture.
To help with this, calls to
dumpdata
that use the dumpdata--natural-foreign
option will serialize any model with a natural_key()
method before serializing standard primary key objects.However, this may not always be enough. If your natural key refers toanother object (by using a foreign key or natural key to another objectas part of a natural key), then you need to be able to ensure thatthe objects on which a natural key depends occur in the serialized databefore the natural key requires them.
To control this ordering, you can define dependencies on your
natural_key()
methods. You do this by setting a dependencies
attribute on the natural_key()
method itself.For example, let’s add a natural key to the
Book
model from theexample above:The natural key for a
Book
is a combination of its name and itsauthor. This means that Person
must be serialized before Book
.To define this dependency, we add one extra line:This definition ensures that all
Person
objects are serialized beforeany Book
objects. In turn, any object referencing Book
will beserialized after both Person
and Book
have been serialized. Tag: python,django,many-to-many,django-rest-framework
Trying to access my json page I get this error!
I have a Many to Many relationship with my models:
And these serializers:
How can I get round this? RelatedManager tells me something is disagreeing with my M2M link, but why/how? I couldn't see anything here about Attribute Errors.
This question seems related, but setting
many=False
doesn't do anything.In that question they set
many=False
. You do have a Many-to-Many, so set many=True
It's that simple.In fact if you look closely, that's how the example shows you to do it:
See how the tracks listing field has the
many=True
attribute? Do that.How to change the IP address of Amazon EC2 instance using boto library
python,amazon-web-services,boto
Make sure you have set properly with ~/.boto and connect to aws, have the boto module ready in python. If not, go through this first: Getting Started with Boto For example, you need assign a new EIP 54.12.23.34 to the instance i-12345678 Make sure, EIP has been allocated(existed) and you...
How can I resolve my variable's unexpected output?
django,python-2.7
Remove the comma on your first line of code, this turns it into a tuple optional_message = form.cleaned_data['optional_message'], should be optional_message = form.cleaned_data['optional_message'] ...
Python - Opening and changing large text files
python,replace,out-of-memory,large-files
You need to read one bite per iteration, analyze it and then write to another file or to sys.stdout. Try this code: mesh = open('file.mesh', 'r') mesh_out = open('file-1.mesh', 'w') c = mesh.read(1) if c: mesh_out.write('{') else: exit(0) while True: c = mesh.read(1) if c ': break if c...
Using counter on array for one value while keeping index of other values
python,collections
To count how often one value occurs and at the same time you want to select those values, you'd simply select those values and count how many you selected: fruits = [f for f in foods if f[0] 'fruit'] fruit_count = len(fruits) If you need to do this for...
Using .update with nested Serializer to post Image
django,rest,django-models,django-rest-framework,imagefield
As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...
How to check for multiple attributes in a list
python,python-2.7
You can create a set holding the different IDs and then compare the size of that set to the total number of quests. The difference tells you how many IDs are duplicated. Same for names. Something like this (untested): def test_quests(quests): num_total = len(quests) different_ids = len(set((q.ID for q in...
How does the class_weight parameter in scikit-learn work?
python,scikit-learn
First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level)...
Count function counting only last line of my list
python,python-2.7
I don't know what you are exactly trying to achieve but if you are trying to count R and K in the string there are more elegant ways to achieve it. But for your reference I had modified your code. N = int(raw_input()) s = [] for i in range(N):...
SyntaxError: invalid syntax?
python,syntax
Check the code before the print line for errors. This can be caused by an error in a previous line; for example: def x(): y = [ print 'hello' x() This produces the following error: File 'E:Pythontest.py', line 14 print 'hello' ^ SyntaxError: invalid syntax When clearly the error is...
In sklearn, does a fitted pipeline reapply every transform?
python,scikit-learn,pipeline,feature-selection
The pipeline calls transform on the preprocessing and feature selection steps if you call pl.predict. That means that the features selected in training will be selected from the test data (the only thing that makes sense here). It is unclear what you mean by 'apply' here. Nothing new will be...
how to enable a entry by clicking a button in Tkinter?
python,tkinter
You need to use the configure method of each widget: def rakhi(): entry1.configure(state='normal') entry2.configure(state='normal') ...
Spring-integration scripting with Python
python,spring-integration,jython
This is a bug in Spring Integration; I have opened a JIRA Issue. if (variables != null) { result = scriptEngine.eval(script, new SimpleBindings(variables)); } else { result = scriptEngine.eval(script); } When the first branch of the if test is taken, the result variable is added to the SimpleBindings object, and...
Pandas Dataframe Complex Calculation
python,python-2.7,pandas,dataframes
I believe the following does what you want: In [24]: df['New_Col'] = df['ActualCitations']/pd.rolling_sum(df['totalPubs'].shift(), window=2) df Out[24]: Year totalPubs ActualCitations New_Col 0 1994 71 191.002034 NaN 1 1995 77 2763.911781 NaN 2 1996 69 2022.374474 13.664692 3 1997 78 3393.094951 23.240376 So the above uses rolling_sum and shift to generate the...
How do variables inside python modules work?
python,module,python-module
The convention is to declare constants in modules as variables written in upper-case (Python style guide: https://www.python.org/dev/peps/pep-0008/#global-variable-names). But there's no way to prevent someone else to re-declare such a variable -- thus ignoring conventions -- when importing a module. There are two ways of working around this when importing modules...
Django block inclusion not working. What did I miss?
django,django-templates
Django templates do not use inclusion so much as template inheritance. The idea is you set up a hierarchy of templates, specializing some common thing. For instance: you could have a base.html that has some basic page structure, common to all pages of your website. you could then have a...
The event loop is already running
python,python-3.x,pyqt,pyqt4
I think the problem is with your start.py file. You have a function refreshgui which re imports start.py import will run every part of the code in the file. It is customary to wrap the main functionality in an 'if __name__ '__main__': to prevent code from being run on...
Matplotlib: Plot the result of an SQL query
python,sql,matplotlib,plot
Take this for a starter code : import numpy as np import matplotlib.pyplot as plt from sqlalchemy import create_engine import _mssql fig = plt.figure() ax = fig.add_subplot(111) engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') ## the data data =...
trying to understand LSH through the sample python code
python,similarity,locality-sensitive-hash
a. It's a left shift: https://docs.python.org/2/reference/expressions.html#shifting-operations It shifts the bits one to the left. b. Note that ^ is not the 'to the power of' but 'bitwise XOR' in Python. c. As the comment states: it defines 'number of bits per signature' as 2**10 → 1024 d. The lines calculate...
Sum of two variables in RobotFramework
python,automated-tests,robotframework
By default variables are string in Robot. So your first two statements are assigning strings like 'xx,yy' to your vars. Then 'evaluate' just execute your statement as Python would do. So, adding your two strings with commas will produce a list: $ python >>> 1,2+3,4 (1, 5, 4) So you...
How to use template within Django template?
python,html,django,templates,django-1.4
You can use the include tag in order to supply the included template with a consistent variable name: For example: parent.html <div> <div> {% include 'templates/child.html' with list_item=mylist.0 t=50 only %} </div> </div> child.html {{ list_item.text|truncatewords:t }} UPDATE: As spectras recommended, you can use the...
Create angular page in Django to consume data from JSON
angularjs,django,django-templates
You can add the angular app as a simple template view in Django views.py def index(request): return render(request, 'yourhtml.html', {}) urls.py .... url(r'^your_url/$', views.index), .... Then the index.html file can have your angular code...
How do I read this list and parse it?
python,list
Your list contains one dictionary you can access the data inside like this : >>> yourlist[0]['popularity'] 2354 [0] for the first item in the list (the dictionary). ['popularity'] to get the value associated to the key 'popularity' in the dictionary....
Python: can't access newly defined environment variables
python,bash,environment-variables
After updating your .bashrc, perform source ~/.bashrc to apply the changes. Also, merge the two BONSAI-related calls into one: export BONSAI=/home/me/Utils/bonsai_v3.2 UPDATE: It was actually an attempt to update the environment for some Eclipse-based IDE. This is a different usecase altogether. It should be described in the Eclipse help. Also,...
sys.argv in a windows environment
python,windows,python-3.x
You are calling the script wrong Bring up a cmd (command line prompt) and type: cd C:/Users/user/PycharmProjects/helloWorld/ module_using_sys.py we are arguments And you will get the correct output....
Calling function and passing arguments multiple times
python,function,loops
a,b,c = 1,2,3 while i<n: a,b,c = myfunction(a,b,c) i +=1 ...
Identify that a string could be a datetime object
python,regex,algorithm,python-2.7,datetime
What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...
Create an exe with Python 3.4 using cx_Freeze
python,python-3.4,cx-freeze
Since you want to convert python script to exe have a look at py2exe
Twilio Client Python not Working in IOS Browser
javascript,python,ios,flask,twilio
Twilio developer evangelist here. Twilio Client uses WebRTC and falls back to Flash in order to make web browsers into phones. Unfortunately Safari on iOS supports neither WebRTC nor Flash so Twilio Client cannot work within any browser on iOS. It is possible to build an iOS application to use...
Python: histogram/ binning data from 2 arrays.
python,histogram,large-files
if you only need to do this for a handful of points, you could do something like this. If intensites and radius are numpy arrays of your data: bin_width = 0.1 # Depending on how narrow you want your bins def get_avg(rad): average_intensity = intensities[(radius>=rad-bin_width/2.) & (radius<rad+bin_width/2.)].mean() return average_intensities #...
Strange Behavior: Floating Point Error after Appending to List
python,python-2.7,behavior
Short answer: your correct doesn't work. Long answer: The binary floating-point formats in ubiquitous use in modern computers and programming languages cannot represent most numbers like 0.1, just like no terminating decimal representation can represent 1/3. Instead, when you write 0.1 in your source code, Python automatically translates this to...
Peewee: reducing where conditionals break after a certain length
python,peewee
Try ...where(SomeTable.BIN.in_(big_list)) PeeWee has restrictions as to what can be used in their where clause in order to work with the library. http://docs.peewee-orm.com/en/latest/peewee/querying.html#query-operators...
Sort when values are None or empty strings python
python,list,sorting,null
If you want the None and ' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be...
How to remove structure with python from this case?python,python-2.7
It's complicated to use regex, a stupid way I suggested: def remove_table(s): left_index = s.find('<table>') if -1 left_index: return s right_index = s.find('</table>', left_index) return s[:left_index] + remove_table(s[right_index + 8:]) There may be some blank lines inside the result....
SQLAlchemy. 2 different relationships for 1 column
python,sqlalchemy
I'm afraid you can't do it like this. I suggest you have just one relationship users and validate the insert queries.
Callable in model field not called upon adding new object through Django admin
django,django-models,django-admin
![Django Serialize Dict Object Has No Attribute Meta Django Serialize Dict Object Has No Attribute Meta](/uploads/1/2/6/3/126379907/679277401.png)
Try: when_first_upload = models.DateTimeField(default=datetime.datetime.now) You need the callable itself, not the result returned by it....
Pandas - Dropping multiple empty columns
python,pandas
You can just subscript the columns: df = df[df.columns[:11]] This will return just the first 11 columns or you can do: df.drop(df.columns[11:], axis=1) To drop all the columns after the 11th one....
odoo v8 - Field(s) `arch` failed against a constraint: Invalid view definition
python,xml,view,odoo,add-on
You have made silly mistake in defining _columns. _colums is not valid dictionary name for fields structure. Replace this by _columns and restart service and update module. ...
![Django Serialize Dict Object Has No Attribute Meta Django Serialize Dict Object Has No Attribute Meta](/uploads/1/2/6/3/126379907/552162188.png)
Parse text from a .txt file using csv module
python,python-2.7,parsing,csv
How about using Regular Expression def get_info(string_to_search): res_dict = {} import re find_type = re.compile('Type:[s]*[w]*') res = find_type.search(string_to_search) res_dict['Type'] = res.group(0).split(':')[1].strip() find_Status = re.compile('Status:[s]*[w]*') res = find_Status.search(string_to_search) res_dict['Status'] = res.group(0).split(':')[1].strip() find_date = re.compile('Date:[s]*[/0-9]*') res = find_date.search(string_to_search) res_dict['Date'] = res.group(0).split(':')[1].strip() res_dict['description'] =...
Django: html without CSS and the right text
python,html,css,django,url
Are you using the {% load staticfiles %} in your templates?
How to put an image on another image in python, using ImageTk?
python,user-interface,tkinter
Just use photoshop or G.I.M.P.. I assure you, doing it that way will be much simpler and less redundant than essentially getting Tkinter to photo edit for you (not to mention what you're talking about is just bad practice when it comes to coding) Anyways, I guess if you really...
Find the tf-idf score of specific words in documents using sklearn
python,scikit-learn,tf-idf
Yes. See .vocabulary_ on your fitted/transformed TF-IDF vectorizer. In [1]: from sklearn.datasets import fetch_20newsgroups In [2]: data = fetch_20newsgroups(categories=['rec.autos']) In [3]: from sklearn.feature_extraction.text import TfidfVectorizer In [4]: cv = TfidfVectorizer() In [5]: X = cv.fit_transform(data.data) In [6]: cv.vocabulary_ It is a dictionary of the form: {word : column index in...
group indices of list in list of lists
python,list
Use collections.OrderedDict: from collections import OrderedDict od = OrderedDict() lst = [2, 0, 1, 1, 3, 2, 1, 2] for i, x in enumerate(lst): od.setdefault(x, []).append(i) ... >>> od.values() [[0, 5, 7], [1], [2, 3, 6], [4]] ...
Inserting a variable in MongoDB specifying _id field
python,mongodb,pymongo
Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...
Python recursive function not recursing
python,recursion
Afraid I don't know much about python, but I can probably help you with the algorithm. The encoding process repeats the following: multiply the current total by 17 add a value (a = 1, b = 2, ..., z = 26) for the next letter to the total So at...
represent an index inside a list as x,y in python
python,list,numpy,multidimensional-array
According to documentation of numpy.reshape , it returns a new array object with the new shape specified by the parameters (given that, with the new shape, the amount of elements in the array remain unchanged) , without changing the shape of the original object, so when you are calling the...
Displaying a 32-bit image with NaN values (ImageJ)
python,image-processing,imagej
The display range of your image might not be set correctly. Try outputImp.resetDisplayRange() or outputImp.setDisplayRange(Stats.min, Stats.max) See the ImagePlus javadoc for more info....
Replace nodejs for python?
python,node.js,webserver
You might want to have a look at Tornado. It is well-documented and features built-in support for WebSockets. If you want to steer clear of the Tornado-framework, there are several Python implementations of Socket.io. Good luck!...
Python Popen - wait vs communicate vs CalledProcessError
python,python-2.7,error-handling,popen
about the deadlock: It is safe to use stdout=PIPE and wait() together iff you read from the pipe. .communicate() does the reading and calls wait() for you about the memory: if the output can be unlimited then you should not use .communicate() that accumulates all output in memory. what...