title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Is there any methods to combine the two function to one
39,405,840
<p>how to use recursion to combine the two function to one ?I know it's an answer of "move_zeros", But here I post just want to learn how to use recursion and solve problems with recursion.</p> <p>func 1</p> <pre><code>def move_zeross(array): for i in range(len(array)): if array[i] is not False and array[...
-1
2016-09-09T07:13:48Z
39,406,272
<p>If you just want to move all zeros in the list to the end, try:</p> <pre><code>def move_zeros(array): result = [x for x in array if x is not 0] return result + [0]*(len(array)-len(result)) </code></pre> <p>Using recursion:</p> <pre><code>def move_zeros(array, n=None): if n is None: n = len(arr...
1
2016-09-09T07:38:25Z
[ "python", "recursion", "runtime-error" ]
Is there any methods to combine the two function to one
39,405,840
<p>how to use recursion to combine the two function to one ?I know it's an answer of "move_zeros", But here I post just want to learn how to use recursion and solve problems with recursion.</p> <p>func 1</p> <pre><code>def move_zeross(array): for i in range(len(array)): if array[i] is not False and array[...
-1
2016-09-09T07:13:48Z
39,418,203
<p>A different recursive approach:</p> <pre><code>def move_zeros(array): if array: head, tail = array[0], move_zeros(array[1:]) if head is 0: array = tail array.append(head) else: array = [head] array.extend(tail) return array </code></p...
1
2016-09-09T19:03:40Z
[ "python", "recursion", "runtime-error" ]
What does .only django queryset really do?
39,405,853
<p>I heard in the Django documentation it optimizes so I did a little bit of experimentation. So I did this:</p> <pre><code>&gt;&gt;&gt; x = Artist.objects.only('id').filter() &gt;&gt;&gt; print x.query SELECT "store_artist"."id" FROM "store_artist" &gt;&gt;&gt; y = Artist.objects.filter() &gt;&gt;&gt; print y.query ...
1
2016-09-09T07:14:31Z
39,405,893
<p>It does only query the fields you give it, but then it still returns instances of that model. So when you ask for a different field, you would have made a second query to get the name</p>
1
2016-09-09T07:16:39Z
[ "python", "django" ]
What does .only django queryset really do?
39,405,853
<p>I heard in the Django documentation it optimizes so I did a little bit of experimentation. So I did this:</p> <pre><code>&gt;&gt;&gt; x = Artist.objects.only('id').filter() &gt;&gt;&gt; print x.query SELECT "store_artist"."id" FROM "store_artist" &gt;&gt;&gt; y = Artist.objects.filter() &gt;&gt;&gt; print y.query ...
1
2016-09-09T07:14:31Z
39,406,244
<p>The .only method returns you a queryset which is not appendable, if you want a new queryset you have to make an another query to get that. This method is useful when you have a very large dataset and you want a only field for all your processing in the business logic. In your case i will suggest to use defer() metho...
1
2016-09-09T07:36:54Z
[ "python", "django" ]
Printing indices of 3-dimensional variable in PuLP for scheduling
39,405,875
<p>I am working with SolverStudio (Excel add-in) and PuLP (Python-based optimization language) to create a tool that assigns students to working places.</p> <p>This is the variable whose indices I want to print:</p> <p><code># Decision variable, =1 if student s is assigned to working place w on day d; 0 otherwise Ass...
0
2016-09-09T07:15:33Z
39,407,685
<p>Found the mistake myself in the meantime:</p> <p><code>for w in Working_places: for d in Days: for s in Students: if Assignment[s][w][d].varValue == 1: Schedule[w,d] = Name[s]</code></p>
0
2016-09-09T08:59:24Z
[ "python", "optimization", "scheduling", "pulp" ]
How to increase the performance of gae query?
39,405,891
<p>I have implemented a logic of querying a table and for each entity in that particular table, I have to lookup another table.</p> <p>For, ex.</p> <p>My code looks like,</p> <pre><code>query = ndb.gql("select * from Foo where user = :1", user.key) stories, next_cursor, more = query.fetch_page(size, start_cursor=cu...
0
2016-09-09T07:16:30Z
39,406,179
<p>I don't know whole structure of your project, but...</p> <p>You can do something like that:</p> <pre><code>class Story(ndb.Model): images = ndb.KeyProperty(kind=Image, repeated=True) user = ndb.KeyProperty(kind=User) </code></pre> <p>and every time user will add new image update it (<code>images</code> pr...
1
2016-09-09T07:33:02Z
[ "python", "performance", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
How to increase the performance of gae query?
39,405,891
<p>I have implemented a logic of querying a table and for each entity in that particular table, I have to lookup another table.</p> <p>For, ex.</p> <p>My code looks like,</p> <pre><code>query = ndb.gql("select * from Foo where user = :1", user.key) stories, next_cursor, more = query.fetch_page(size, start_cursor=cu...
0
2016-09-09T07:16:30Z
39,406,572
<p>You can add a property to each Story that contains a list of Image ids. I assume that this list rarely changes. Then you can easily <code>get_multi</code> all images related to a story without any queries.</p> <p>You may also consider to <code>get_multi</code> all images for all stories, returned by your query, in ...
2
2016-09-09T07:55:37Z
[ "python", "performance", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
How to increase the performance of gae query?
39,405,891
<p>I have implemented a logic of querying a table and for each entity in that particular table, I have to lookup another table.</p> <p>For, ex.</p> <p>My code looks like,</p> <pre><code>query = ndb.gql("select * from Foo where user = :1", user.key) stories, next_cursor, more = query.fetch_page(size, start_cursor=cu...
0
2016-09-09T07:16:30Z
39,683,994
<p>You will want to look at NDB batch async API</p> <pre><code> @ndb.tasklet def get_stories(user_key): stories = yield Story.query(Story.user_key == user_key).fetch_async() futs = [ item.key.get_async() for item in stories] result = yield futs raise ndb.Return(result) get_stories(u...
1
2016-09-25T06:13:51Z
[ "python", "performance", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
Pandas: Is there a way to use something like 'droplevel' and in process, rename the the other level using the dropped level labels as prefix/suffix?
39,405,971
<p>Screenshot of the query below:</p> <p><a href="http://i.stack.imgur.com/dGNAV.png" rel="nofollow"><img src="http://i.stack.imgur.com/dGNAV.png" alt="Groupby Query"></a></p> <p>Is there a way to easily drop the upper level column index and a have a single level with labels such as <code>points_prev_amax</code>, <co...
4
2016-09-09T07:21:44Z
39,405,994
<p>Use <code>list comprehension</code> for set new column names:</p> <pre><code>df.columns = ['_'.join(col) for col in df.columns] </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,2,2,1], 'B':[4,5,6,4], 'C':[7,8,9,1], 'D':[1,3,5,9]}) print (d...
4
2016-09-09T07:23:00Z
[ "python", "pandas", "rename", "multiple-columns", "multi-index" ]
Pandas: Is there a way to use something like 'droplevel' and in process, rename the the other level using the dropped level labels as prefix/suffix?
39,405,971
<p>Screenshot of the query below:</p> <p><a href="http://i.stack.imgur.com/dGNAV.png" rel="nofollow"><img src="http://i.stack.imgur.com/dGNAV.png" alt="Groupby Query"></a></p> <p>Is there a way to easily drop the upper level column index and a have a single level with labels such as <code>points_prev_amax</code>, <co...
4
2016-09-09T07:21:44Z
39,407,292
<p>Using @jezrael's setup</p> <pre><code>df = pd.DataFrame({'A':[1,2,2,1], 'B':[4,5,6,4], 'C':[7,8,9,1], 'D':[1,3,5,9]}) df = df.groupby('A').agg([max, min]) </code></pre> <hr> <p>Assign new columns with</p> <pre><code>from itertools import starmap def flat...
3
2016-09-09T08:38:13Z
[ "python", "pandas", "rename", "multiple-columns", "multi-index" ]
How to play music using pygame (Python)
39,406,020
<p>I am trying to play an .mp3 file using pygame. Here is my code:</p> <pre><code>import pygame pygame.init() pygame.mixer.init() pygame.mixer.music.load('MSM.mp3') pygame.mixer.music.play(0) pygame.event.wait() </code></pre> <p>This however does not actually play the file. The audio file is located within the sam...
0
2016-09-09T07:24:32Z
39,407,388
<p>The pyGame docs suggest using the pygame.mixer.pre_init() method before the top-level pygame.init() on some platforms.</p> <blockquote> <p>"Some platforms require the pygame.mixer module for loading and playing sounds module to be initialized after the display modules have initialized. The top level pygame.in...
1
2016-09-09T08:43:48Z
[ "python", "pygame", "music" ]
Managing contents of requirements.txt for a Python virtual environment
39,406,177
<p>So I am creating a brand new Flask app from scratch.As all good developers do,my first step was to create a virtual environment.</p> <p>The first thing I install in the virtual environment is Flask==0.11.1.Flask installs its following dependencies:</p> <blockquote> <ul> <li>click==6.6</li> <li>itsdangerous==...
0
2016-09-09T07:32:53Z
39,406,391
<p>You can (from your active virtual environment) do the following</p> <pre><code>pip freeze &gt; requirements.txt </code></pre> <p>which'll automatically take care of all libraries/modules available in your project.</p> <p>The next developer would only have to issue:</p> <pre><code>pip install -r requirements.txt ...
1
2016-09-09T07:45:26Z
[ "python", "pip", "virtualenv", "requirements.txt" ]
Managing contents of requirements.txt for a Python virtual environment
39,406,177
<p>So I am creating a brand new Flask app from scratch.As all good developers do,my first step was to create a virtual environment.</p> <p>The first thing I install in the virtual environment is Flask==0.11.1.Flask installs its following dependencies:</p> <blockquote> <ul> <li>click==6.6</li> <li>itsdangerous==...
0
2016-09-09T07:32:53Z
39,406,537
<p>Both approaches are valid and work. But there is a little difference. When you enter all the dependencies in the <code>requirements.txt</code> you will be able to pin the versions of them. If you leave them out, there might be a later update and if Flask has something like <code>Werkzeug&gt;=0.11</code> in it's depe...
1
2016-09-09T07:53:26Z
[ "python", "pip", "virtualenv", "requirements.txt" ]
Managing contents of requirements.txt for a Python virtual environment
39,406,177
<p>So I am creating a brand new Flask app from scratch.As all good developers do,my first step was to create a virtual environment.</p> <p>The first thing I install in the virtual environment is Flask==0.11.1.Flask installs its following dependencies:</p> <blockquote> <ul> <li>click==6.6</li> <li>itsdangerous==...
0
2016-09-09T07:32:53Z
39,408,792
<ol> <li>activate virtualenv</li> <li>go to you project root directory</li> <li><p>get all the packages along with dependencies in requirements.txt</p> <pre><code>pip freeze &gt; requirements.txt </code></pre></li> <li><p>you dont have to worry anything else apart from making sure next person installs the requirements...
1
2016-09-09T09:53:51Z
[ "python", "pip", "virtualenv", "requirements.txt" ]
ImportError: No module name rest_framework
39,406,526
<p>I have both python 2.7 and 3.5 installed. While creating a django project, I selected Python 3.5 as my python interpreter. And I also installed rest framework but I find this error while running my django project. Help</p> <pre><code>Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; ...
0
2016-09-09T07:52:45Z
39,406,690
<p>Oh sorry. I executed the command <code>python manage.py runserver</code> instead of <code>python3 manage.py runserver</code></p> <p>Working fine now.</p>
0
2016-09-09T08:02:11Z
[ "python", "django", "django-rest-framework" ]
sklearn function transformer in pipeline
39,406,539
<p>Writing my first pipeline for sk-learn I stumbled upon some issues when only a subset of columns is put into a pipeline:</p> <pre><code>mydf = pd.DataFrame({'classLabel':[0,0,0,1,1,0,0,0], 'categorical':[7,8,9,5,7,5,6,4], 'numeric1':[7,8,9,5,7,5,6,4], 'numeri...
0
2016-09-09T07:53:27Z
39,429,857
<p><code>FunctionTransformer</code> is used to "lift" a function to a transformation which I think can help with some data cleaning steps. Imagine you have a mostly numeric array and you want to transform it with a Transformer that that will error out if it gets a <code>nan</code> (like <code>Normalize</code>). You mig...
1
2016-09-10T19:31:08Z
[ "python", "scikit-learn", "pipeline", "transformer" ]
Convert a text list to numbers?
39,406,754
<p>I am trying to use <code>float()</code> to convert the following list to numbers. But it always says <code>ValueError: could not convert string to float</code>.</p> <p>I understand that this error occurs when there is something in text that cannot be treated as a number. But my list seems okay.</p> <pre><code>a = ...
-1
2016-09-09T08:05:59Z
39,406,815
<pre><code>a = ['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3'] b = [float(x) for x in a] </code></pre> <p>Works perfectly.</p> <pre><code>['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3'] b = [float...
0
2016-09-09T08:09:22Z
[ "python", "list", "text" ]
Convert a text list to numbers?
39,406,754
<p>I am trying to use <code>float()</code> to convert the following list to numbers. But it always says <code>ValueError: could not convert string to float</code>.</p> <p>I understand that this error occurs when there is something in text that cannot be treated as a number. But my list seems okay.</p> <pre><code>a = ...
-1
2016-09-09T08:05:59Z
39,406,960
<p>you can convert list using </p> <p>if you have any string in your list then you get error message <code>ValueError: could not convert string to float</code> like that </p> <pre><code>&gt;&gt;&gt; a = ['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3'] &gt;&g...
-1
2016-09-09T08:19:09Z
[ "python", "list", "text" ]
Convert a text list to numbers?
39,406,754
<p>I am trying to use <code>float()</code> to convert the following list to numbers. But it always says <code>ValueError: could not convert string to float</code>.</p> <p>I understand that this error occurs when there is something in text that cannot be treated as a number. But my list seems okay.</p> <pre><code>a = ...
-1
2016-09-09T08:05:59Z
39,407,099
<p>The list you have posted is perfectly ok with your method.</p> <ul> <li><p>Either you have <code>a</code> already define to a string and don't have a pointed to that list. </p></li> <li><p>The list contains a number. </p></li> </ul> <p>Just to verify try</p> <pre><code>map(int,a) #if no errors you have all number...
0
2016-09-09T08:26:46Z
[ "python", "list", "text" ]
Convert a text list to numbers?
39,406,754
<p>I am trying to use <code>float()</code> to convert the following list to numbers. But it always says <code>ValueError: could not convert string to float</code>.</p> <p>I understand that this error occurs when there is something in text that cannot be treated as a number. But my list seems okay.</p> <pre><code>a = ...
-1
2016-09-09T08:05:59Z
39,408,499
<p>The problem is exactly what the Traceback log says: Could not convert string to float</p> <ol> <li>If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.</li> <li>If you have a string with non-numerical characters, the conversion will fail and give...
0
2016-09-09T09:39:59Z
[ "python", "list", "text" ]
PyQtGraph and numpy realtime plot
39,406,768
<p>I am currently making a project that reads 8 sensors and plots real time graphs. I have used Matplotlib but it was slow so I switched to pyqtgraph. It is comparatively very fast. I have refered to the documentations and designed a simple code that plots live data. The only problem I am facing is the diskspace and c...
1
2016-09-09T08:07:10Z
39,407,942
<p>So if you want to replace your list with an <code>np.array</code> you will face one major issue: It is not directly possible to append data to an array the same way as with a list. One possibility is to use e.g. <code>np.hstack</code>, <code>np.vstack</code>, <code>np.column_stack</code> or <code>np.row_stack</code>...
0
2016-09-09T09:11:59Z
[ "python", "arrays", "numpy" ]
UnificationEngine: Unable to send Requests via Python using TLS or SSL
39,406,836
<p>I am attempting to use a Raspberry Pi 3 (Model B) to send Requests by Python to the Unification Engine. With SSL/TLS verification disabled, the request happens normally, but I need to get SSL/TLS working with it.</p> <p>The below code is meant to force a session to use TLSv1 for the purpose of sending Python Reques...
0
2016-09-09T08:10:54Z
39,423,774
<p>Looks like the certificate verification isn't done correctly. Have a look at: <a href="https://the.randomengineer.com/2014/01/29/using-ssl-wrap_socket-for-secure-sockets-in-python/" rel="nofollow">https://the.randomengineer.com/2014/01/29/using-ssl-wrap_socket-for-secure-sockets-in-python/</a> <a href="https://urlli...
0
2016-09-10T07:34:10Z
[ "python", "ssl", "python-requests", "unificationengine" ]
How to fix broken pipe in Chat server using socket in Python after first request?
39,406,906
<p>I am playing with socket and tried to create simple chat server with only one client connection. Code and output as follows.</p> <p>echo_server.py</p> <pre><code>import socket host = '' port = 4538 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog)...
0
2016-09-09T08:15:23Z
39,407,033
<p><code>recv</code> returns empty string when the client is closes the connection, not <code>None</code> or <code>0</code>. Since empty string is a False condition, simply use <code>if data:</code> or <code>if not data:</code>.</p> <p>And, as @JonClements pointed out, use an <code>except</code> instead of a <code>fi...
1
2016-09-09T08:22:28Z
[ "python", "sockets", "broken-pipe" ]
ctypes pass an array of byte
39,407,115
<p>I want to call this C function from a DLL in python2.7</p> <pre><code>uint8_t DLL_CONV Mag(uint8_t *t1, uint8_t *t2, uint8_t *t3); </code></pre> <p>This function write data to the arrays sent by reference.</p> <p>This is my python code so far</p> <pre><code>_mag = hDLL.Mag #_mag.argtypes =[ctypes.POINTER(ctypes....
0
2016-09-09T08:27:41Z
39,411,766
<p>I undefined <code>argtypes</code> and just send the arrays like so</p> <pre><code>s = _mag( (t1), (t2), (t3) ) </code></pre>
0
2016-09-09T12:35:58Z
[ "python", "dll", "ctypes" ]
Django model migration added two unwanted fields when using AbstractBaseUser class
39,407,225
<p>Django 1.9<br> Python 3.4 </p> <p>I created a custom Users model using AbstractBaseUser class. Below is the code.</p> <pre><code>class UserModel(AbstractBaseUser): # custom user class SYSTEM = 0 TENANT = 1 parent_type_choices = ( (SYSTEM, 'System'), ...
0
2016-09-09T08:33:36Z
39,407,294
<p>You inherited from <code>AbstractBaseUser</code> class which provides these fields. You can not remove them. Check <a href="https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#specifying-a-custom-user-model" rel="nofollow">Django doc</a> for more info</p>
0
2016-09-09T08:38:17Z
[ "python", "mysql", "django", "django-models" ]
Hard time with my Dice game
39,407,282
<p>I have a problem with my dice game. Every time I run it it says incorrect even if I guess the number right. There is the code, and a screenshot of when i got it right: <a href="https://gyazo.com/87400aab5747a05c77415a816952b26d" rel="nofollow">https://gyazo.com/87400aab5747a05c77415a816952b26d</a></p> <pre><code>im...
-1
2016-09-09T08:37:32Z
39,407,356
<p>That is probably because you read in something which by default will be a type string, and your number is an integer datatype. So "6" won't be equal number 6. You should do some conversion before the comparison if I'm right.</p>
-1
2016-09-09T08:42:03Z
[ "python", "pycharm" ]
Hard time with my Dice game
39,407,282
<p>I have a problem with my dice game. Every time I run it it says incorrect even if I guess the number right. There is the code, and a screenshot of when i got it right: <a href="https://gyazo.com/87400aab5747a05c77415a816952b26d" rel="nofollow">https://gyazo.com/87400aab5747a05c77415a816952b26d</a></p> <pre><code>im...
-1
2016-09-09T08:37:32Z
39,407,393
<p>If you convert <code>ask</code> to an integer, it will work fine:</p> <pre><code>import random ask = int(input(": ")) # input returns a string for i in range(1): dice = random.randint(1, 6) print(dice) if ask == random: print("correct") else: print("incorrect") </code></pre>
1
2016-09-09T08:43:54Z
[ "python", "pycharm" ]
Put image into Google App Engine Datastore
39,407,305
<p>I'm currently building a blog using Google App Engine and Python and I'd like to create a column for my posts table where to store an image. How can I upload an Image from my pc and store it into the database?</p>
0
2016-09-09T08:38:42Z
39,407,467
<p>The Datastore is not optimized for storing images. A better option is to store it in <a href="https://cloud.google.com/storage/" rel="nofollow">Google Cloud Storage</a>. You App Engine project will get a default bucket in GCS when you enable it, and you can use your dev console to upload files to this bucket manuall...
1
2016-09-09T08:47:43Z
[ "python", "database", "google-app-engine" ]
Plotting animate 3d graph from file.txt
39,407,327
<p>I'm trying to plot a 3D animate Graph taking the data from file.txt. I got a issue with the animation function, such as when I'm introducing new coordinate on txt file the plot doesn't update by itself. The code is the following:</p> <pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as ...
0
2016-09-09T08:40:01Z
39,408,480
<pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation np.set_printoptions(threshold=np.inf) fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') def init(): global points points = np.loadtxt('Prova.txt') def ...
0
2016-09-09T09:39:06Z
[ "python", "numpy", "animation", "matplotlib" ]
Recent entries from each category in django model
39,407,414
<p>I need to show in the template most recent entries from each category is the Instarama, Facebook, Twitter. Here my solution, but it does not work.</p> <p>My get_queryset method but isn't working:</p> <pre><code>def get_queryset(self): return super(OnlineManager, self).get_queryset().filter(is_online=True).orde...
3
2016-09-09T08:44:39Z
39,408,327
<pre><code>def get_queryset(self): super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('- id')annotate(Count('social_channel'))[‌​0] </code></pre>
3
2016-09-09T09:31:26Z
[ "python", "django", "model", "django-queryset", "categories" ]
Recent entries from each category in django model
39,407,414
<p>I need to show in the template most recent entries from each category is the Instarama, Facebook, Twitter. Here my solution, but it does not work.</p> <p>My get_queryset method but isn't working:</p> <pre><code>def get_queryset(self): return super(OnlineManager, self).get_queryset().filter(is_online=True).orde...
3
2016-09-09T08:44:39Z
39,409,436
<p>Try this:</p> <pre><code>def get_queryset(self): query = super(OnlineManager, self).get_queryset() query = query.filter(is_online=True).order_by('social_channel', '-id').distinct('social_channel') return query </code></pre> <p>it should return the most recent entry for each <code>social_chanel</code></...
0
2016-09-09T10:27:20Z
[ "python", "django", "model", "django-queryset", "categories" ]
How to check a text contains \
39,407,438
<pre><code>def check(text): pattern = re.compile(r'\\') rv = re.match(pattern, text) if rv: return True else: return False print check('\mi') # True print check('\ni') # False </code></pre> <p>Actually,I want text contains '\' is illegal.</p> <p>But '\n', '\b',etc, python treats them ...
0
2016-09-09T08:45:46Z
39,408,105
<pre><code>def check(text): rv = re.search('(\\\\)|(\\\n)', string) if rv: return True else: return False string = "\mi" print check(string) string = "\ni" print check(string) </code></pre> <p>Result:</p> <blockquote> <blockquote> <blockquote> <p>=============================...
0
2016-09-09T09:19:44Z
[ "python" ]
How to check a text contains \
39,407,438
<pre><code>def check(text): pattern = re.compile(r'\\') rv = re.match(pattern, text) if rv: return True else: return False print check('\mi') # True print check('\ni') # False </code></pre> <p>Actually,I want text contains '\' is illegal.</p> <p>But '\n', '\b',etc, python treats them ...
0
2016-09-09T08:45:46Z
39,409,594
<p>Why would you need or want to use a regex for this?</p> <pre><code> return '\\' in text </code></pre>
1
2016-09-09T10:35:11Z
[ "python" ]
Calling Fortran routines in scipy.special in a function jitted with numba
39,407,585
<p>Is there a way to directly or indirectly call the Fortran routines that can be found here <a href="https://github.com/scipy/scipy/tree/master/scipy/special/cdflib" rel="nofollow">https://github.com/scipy/scipy/tree/master/scipy/special/cdflib</a> and that are used by <code>scipy.stats</code> from a function that is ...
2
2016-09-09T08:53:23Z
39,409,736
<p>I would take a look at <a href="https://github.com/QuantEcon/rvlib" rel="nofollow">rvlib</a>, which uses Numba and CFFI to call RMath, which is the standalone C library that R uses to calculate statistical distributions. The functions it provides should be callable by Numba in <code>nopython</code> mode. Take a look...
2
2016-09-09T10:42:10Z
[ "python", "numba" ]
scipy.interpolate leads to ImportError
39,407,640
<p>my setup is</p> <pre><code>import cartopy.crs as ccrs import matplotlib.pyplot as plt </code></pre> <p>I have scipy <code>0.17</code> and cartopy '0.14.2'.</p> <p>All I'm trying to do is</p> <pre><code>plt.axes(projection=ccrs.PlateCarree()) </code></pre> <p>and it leads to this:</p> <pre><code>Traceback (most...
0
2016-09-09T08:56:48Z
39,409,175
<p>It turned out to be a problem with the <code>scipy</code> installation coming from <code>conda</code>. Creating a new environment and freshly installing <code>scipy</code> solved the issue.</p>
0
2016-09-09T10:14:26Z
[ "python", "scipy" ]
Logical operator binding of AND and OR in Python
39,407,674
<p>Yesterday while constructing a conditional statement I ran into what seems to me to be a strange precedence rule. The statement I had was</p> <pre><code>if not condition_1 or not condition_2 and not condition_3: </code></pre> <p>I found that</p> <pre><code>if True or True and False: # Evaluates to true and en...
0
2016-09-09T08:58:55Z
39,407,704
<p>From python wiki :</p> <blockquote> <p>The expression <a href="https://docs.python.org/2/reference/expressions.html#and" rel="nofollow"><strong>x and y</strong></a> first evaluates x; if x is false, its <strong>value</strong> is returned; otherwise, y is evaluated and the resulting <strong>value</strong> is retur...
1
2016-09-09T09:00:06Z
[ "python", "logical-operators" ]
Logical operator binding of AND and OR in Python
39,407,674
<p>Yesterday while constructing a conditional statement I ran into what seems to me to be a strange precedence rule. The statement I had was</p> <pre><code>if not condition_1 or not condition_2 and not condition_3: </code></pre> <p>I found that</p> <pre><code>if True or True and False: # Evaluates to true and en...
0
2016-09-09T08:58:55Z
39,407,874
<p>As you said <code>and</code> has a higher preference, so your expression with parenthesis will be exactly what you said:</p> <pre><code>if (True) or (True and False) </code></pre> <p>Since <code>True or (anything)</code> will be <code>True</code> regardless anything here, the result will be <code>True</code>. Even...
0
2016-09-09T09:08:03Z
[ "python", "logical-operators" ]
Make 2 functions run at the same time and in parallel?
39,407,680
<p>I have an array</p> <pre><code>myArray = array(url1,url2,...,url90) </code></pre> <p>I want to execute this commande 3 times in parallel</p> <p><code>scrapy crawl mySpider -a links=url</code></p> <p>and each time with 1 url,</p> <pre><code>scrapy crawl mySpider -a links=url1 scrapy crawl mySpider -a links=url2 ...
1
2016-09-09T08:59:18Z
39,407,885
<p>When you write <code>target = func1(url)</code> you actually runnig <code>func1</code> and passing result to <code>Thread</code> (not a reference do the function). This means functions are run on the loop not in the seperate thread.</p> <p>You need to rewrite it like that:</p> <pre><code>if __name__ == '__main__':...
2
2016-09-09T09:08:29Z
[ "python", "parallel-processing", "scrapy", "ipython-parallel" ]
Error from QTableView selectionChanged
39,407,717
<p>If I try to get the signal when my tableview changes, Python raises this error:</p> <pre><code>Traceback (most recent call last): File "UIreadresultwindow.py", line 361, in &lt;module&gt; ui.setupUi(ReadResultWindow) File "UIreadresultwindow.py", line 113, in setupUi self.tableEntity.selectionModel().se...
0
2016-09-09T09:01:12Z
39,423,916
<p>you must first set the model. So you can do something like this:</p> <pre><code>self.tableEntity = QtWidgets.QTableView(self.centralWidget) self.tableEntity.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) </code></pre> <p>you can set one of this models: <code>{ NoSelection, SingleSelection, MultiSelect...
0
2016-09-10T07:53:49Z
[ "python", "pyqt", "qtableview", "selectionchanged" ]
Error from QTableView selectionChanged
39,407,717
<p>If I try to get the signal when my tableview changes, Python raises this error:</p> <pre><code>Traceback (most recent call last): File "UIreadresultwindow.py", line 361, in &lt;module&gt; ui.setupUi(ReadResultWindow) File "UIreadresultwindow.py", line 113, in setupUi self.tableEntity.selectionModel().se...
0
2016-09-09T09:01:12Z
39,427,668
<p>The reason why you get that error is that you did not set the model on the table before trying to access the selection-model. The best way to fix this is to move the model setup code out of <code>on_open_file</code> and into <code>setupUi</code>. The <code>on_open_file</code> then just needs to clear the model befor...
1
2016-09-10T15:36:47Z
[ "python", "pyqt", "qtableview", "selectionchanged" ]
How to check if the parameter exist in python
39,407,725
<p>I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range</p> <p>Something like this:</p> <pre><co...
0
2016-09-09T09:01:32Z
39,407,768
<pre><code>if len(sys.argv) &gt;= 2: print(sys.argv[1]) else: print("No parameter has been included") </code></pre> <p>For more complex command line interfaces there is the <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>argparse</code></a> module in Python's standard library - b...
0
2016-09-09T09:03:44Z
[ "python", "linux" ]
How to check if the parameter exist in python
39,407,725
<p>I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range</p> <p>Something like this:</p> <pre><co...
0
2016-09-09T09:01:32Z
39,407,897
<pre><code>import sys try: print sys.argv[1] except IndexError: print "No parameter has been included" </code></pre>
0
2016-09-09T09:09:27Z
[ "python", "linux" ]
How to check if the parameter exist in python
39,407,725
<p>I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range</p> <p>Something like this:</p> <pre><co...
0
2016-09-09T09:01:32Z
39,408,049
<p>You can check the lenght </p> <pre><code>if len(sys.argv) &gt; 1: ... </code></pre> <p>Or the try/except</p> <pre><code>try: sys.argv[1] except IndexError as ie: print("Exception : {0}".format(ie)) </code></pre>
1
2016-09-09T09:17:26Z
[ "python", "linux" ]
How to check if the parameter exist in python
39,407,725
<p>I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range</p> <p>Something like this:</p> <pre><co...
0
2016-09-09T09:01:32Z
39,408,184
<pre><code>import sys print sys.argv[0] # will print your file name if len(sys.argv) &gt; 1: print sys.argv[1]; else: print "No parameter has been included" </code></pre> <p>OR</p> <pre><code>import sys try: print sys.argv[1] except IndexError, e: print "No parameter has been included" </code></pre>
0
2016-09-09T09:24:30Z
[ "python", "linux" ]
How to check if the parameter exist in python
39,407,725
<p>I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range</p> <p>Something like this:</p> <pre><co...
0
2016-09-09T09:01:32Z
39,408,855
<p>Just for fun, you can also use <code>getopt</code> which provides you a way of predefining the options that are acceptable using the unix <code>getopt</code> conventions.</p> <pre><code>import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], "hvxrc:s:", ["help", "config=", "section="]) except get...
0
2016-09-09T09:57:06Z
[ "python", "linux" ]
Two list with string. Pick random from each list and fuse them together with %s in Python
39,407,737
<p>I have 2 list defined:</p> <pre><code> lunchQuote=['ska vi ta %s?','ska vi dra ned till %s?','jag tänkte käka på %s, ska du med?','På %s är det mysigt, ska vi ta där?'] lunchBTH=['thairestaurangen vid korsningen','det är lite mysigt i fiket jämte demolabbet','Indiska','Pappa curry','boden uppe på parke...
0
2016-09-09T09:02:13Z
39,407,794
<p>The best way is using <code>format</code> method, defining <code>lunchQuote</code> as follow</p> <pre><code>import random lunchQuote=['ska vi ta {}?', 'ska vi dra ned till {}?', 'jag tänkte käka på {}, ska du med?', 'På {} är det mysigt, ska vi ta där?'] lunchBTH=['thairestaurangen vid korsningen', 'det är...
1
2016-09-09T09:04:43Z
[ "python", "list", "python-3.x" ]
Change a filename?
39,407,983
<p>I have some files in a folder named like this <code>test_1999.0000_seconds.vtk</code>. What I would like to do is to is to change the name of the file to <code>test_1999.0000.vtk</code>.</p>
1
2016-09-09T09:13:59Z
39,408,012
<p>You can use <a href="https://docs.python.org/2/library/os.html#os.rename" rel="nofollow"><code>os.rename</code></a></p> <pre><code>os.rename("test_1999.0000_seconds.vtk", "test_1999.0000.vtk") </code></pre>
3
2016-09-09T09:15:22Z
[ "python" ]
Change a filename?
39,407,983
<p>I have some files in a folder named like this <code>test_1999.0000_seconds.vtk</code>. What I would like to do is to is to change the name of the file to <code>test_1999.0000.vtk</code>.</p>
1
2016-09-09T09:13:59Z
39,409,354
<pre><code>import os currentPath = os.getcwd() # get the current working directory unWantedString = "_seconds" matchingFiles =[] for path, subdirs, files in os.walk(currentPath): for f in files: if f.endswith(".vtk"): # To group the vtk files matchingFiles.append(path+"\\"+ f) # print ma...
0
2016-09-09T10:22:40Z
[ "python" ]
Get code from module in Excel
39,408,029
<p>I have a number of workbooks that have Macros which point to a particular SQL server using a connection string embedded in the code. We've migrated to a new SQL server so I need to go through these and alter the connection string to look at the new server in each of the Macros that explicitly mentions it. </p> <p>C...
0
2016-09-09T09:16:09Z
39,408,543
<p>Got it- there's a Lines method in the CodeModule object that allows you to take a selection based on a starting and ending line. Using this in conjunction with the CountOfLines property allows you to get the whole thing.</p> <pre><code>for vbc in wb.VBProject.VBComponents: print(vbc.Name + ":\n" + vbc.CodeModul...
0
2016-09-09T09:42:39Z
[ "python", "excel", "vba", "excel-vba", "pywin32" ]
Concatenate values of 2 columns into 1 (equivalent of R's paste)
39,408,038
<p>Example data in python 3.5:</p> <pre><code>import pandas as pd df=pd.DataFrame({"A":["x","y","z","t","f"], "B":[1,2,1,2,4]}) </code></pre> <p>This gives me a dataframe with 2 columns "A" and "B". I then want to add a third column "C" that contains the value of "A" and "B" concatenated and separated...
1
2016-09-09T09:16:45Z
39,408,073
<p>You can just add the columns together but for 'B' you need to cast the type using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype(str)</code></a>:</p> <pre><code>In [115]: df['C'] = df['A'] + '_' + df['B'].astype(str) df Out[115]: A B C 0...
2
2016-09-09T09:18:32Z
[ "python", "pandas" ]
detect closed eyes after it closed 3 seconds
39,408,039
<p>I want to detect closed eyes after it closed 3 seconds using openCV in python . But when I used time.sleep(1) to count time, the entire program is stopped . But the program must be run continuously to dectect close eyes. I think that can be used thread in python</p> <pre><code> def get_frame(self): success, i...
-2
2016-09-09T09:16:49Z
39,408,245
<p>Try to change </p> <pre><code>if(i % 3 == 0){ #eyes close in 3 seconds print "Warning" } </code></pre> <p>to</p> <pre><code>if i % 3 == 0: #eyes close in 3 seconds print "Warning" </code></pre>
0
2016-09-09T09:27:37Z
[ "python", "opencv" ]
SafeConfigParser: sections and environment variables
39,408,101
<p>(<em>Using Python 3.4.3</em>)</p> <p>I want to use environment variables in my config file and I read that I should use <code>SafeConfigParser</code> with <code>os.environ</code> as parameter to achieve it.</p> <pre><code>[test] mytest = %(HOME)s/.config/my_folder </code></pre> <p>Since I need to get all the opti...
1
2016-09-09T09:19:34Z
39,411,344
<p>If I have understood your question and what you want to do correctly, you can avoid the problem by <strong><em>not</em></strong> supplying <code>os.environ</code> as parameter to <code>SafeConfigParser</code>. Instead use it as the <code>vars</code> keyword argument's value when you actually retrieve values using t...
1
2016-09-09T12:13:18Z
[ "python", "environment-variables", "python-3.4", "configparser" ]
How to remove a subset of a data frame in Python?
39,408,109
<p>My dataframe df is 3020x4. I'd like to remove a subset df1 20x4 out of the original. In other words, I just want to get the difference whose shape is 3000x4. I tried the below but it did not work. It returned exactly df. Would you please help? Thanks.</p> <pre><code>new_df = df.drop(df1) </code></pre>
0
2016-09-09T09:19:50Z
39,408,460
<p>As you seem to be unable to post a representative example I will demonstrate one approach using <code>merge</code> with param <code>indicator=True</code>:</p> <p>So generate some data:</p> <pre><code>In [116]: df = pd.DataFrame(np.random.randn(5,3), columns=list('abc')) df Out[116]: a b ...
0
2016-09-09T09:37:51Z
[ "python", "pandas", "subset" ]
how to convert string array of mixed data types
39,408,231
<p>Let's say I have read and loaded a file into a 2D matrix of mixed data as strings(an example has been provided below)</p> <pre><code># an example row of the matrix ['529997' '46623448' '2122110124' '2310' '2054' '2' '66' '' '2010/11/03-12:42:08' '26' 'CLEARING' '781' '30' '3' '0' '0' '1'] </code></pre> <p>I want t...
0
2016-09-09T09:26:46Z
39,408,868
<p>Here is a one linear with list comprehension:</p> <pre><code>In [24]: from datetime import datetime In [25]: func = lambda x: datetime.strptime(x, "%Y/%m/%d-%H:%M:%S") In [26]: [{8:func, 10:str}.get(ind)(item) if ind in {8, 10} else int(item or '0') for ind, item in enumerate(lst)] Out[26]: [529997, 46623448, 21...
2
2016-09-09T09:58:12Z
[ "python", "arrays", "numpy", "converter", "mixed" ]
how to convert string array of mixed data types
39,408,231
<p>Let's say I have read and loaded a file into a 2D matrix of mixed data as strings(an example has been provided below)</p> <pre><code># an example row of the matrix ['529997' '46623448' '2122110124' '2310' '2054' '2' '66' '' '2010/11/03-12:42:08' '26' 'CLEARING' '781' '30' '3' '0' '0' '1'] </code></pre> <p>I want t...
0
2016-09-09T09:26:46Z
39,409,177
<p>I like clear code like this:</p> <pre><code>from datetime import datetime input_row = ['529997', '46623448', '2122110124', '2310', '2054', '2', '66', '', '2010/11/03-12:42:08', '26', 'CLEARING', '781', '30', '3', '0', '0', '1'] _date = lambda x: datetime.strptime(x, "%Y/%m/%d-%H:%M:%S") ...
1
2016-09-09T10:14:27Z
[ "python", "arrays", "numpy", "converter", "mixed" ]
how to convert string array of mixed data types
39,408,231
<p>Let's say I have read and loaded a file into a 2D matrix of mixed data as strings(an example has been provided below)</p> <pre><code># an example row of the matrix ['529997' '46623448' '2122110124' '2310' '2054' '2' '66' '' '2010/11/03-12:42:08' '26' 'CLEARING' '781' '30' '3' '0' '0' '1'] </code></pre> <p>I want t...
0
2016-09-09T09:26:46Z
39,415,194
<p>I have developed the following function to convert the 4.5m rows of the matrix, the invalid data type exception is also taken into consideration too. Although it can be improved with parallelizing the process, but it did the job OK for me, for what it worth, I am going to post it here.</p> <pre><code>def cnvt_data(...
1
2016-09-09T15:38:32Z
[ "python", "arrays", "numpy", "converter", "mixed" ]
how to convert string array of mixed data types
39,408,231
<p>Let's say I have read and loaded a file into a 2D matrix of mixed data as strings(an example has been provided below)</p> <pre><code># an example row of the matrix ['529997' '46623448' '2122110124' '2310' '2054' '2' '66' '' '2010/11/03-12:42:08' '26' 'CLEARING' '781' '30' '3' '0' '0' '1'] </code></pre> <p>I want t...
0
2016-09-09T09:26:46Z
39,416,366
<p>Usually when people ask about reading <code>csv</code> files we ask for a sample of the file. I've attempted to reconstruct your line from the string list:</p> <pre><code>In [590]: txt Out[590]: b'529997, 46623448, 2122110124, 2310, 2054, 2, 66, , 2010/11/03-12:42:08, 26, CLEARING, 781, 30, 3, 0, 0, 1' </code></pr...
1
2016-09-09T16:52:38Z
[ "python", "arrays", "numpy", "converter", "mixed" ]
Shifting from python to pypy
39,408,265
<p>I am currently working on a project where the source files are all written in python. The files/modules are currently being run on a python interpreter(CPython). I want to use PyPy interpreter instead as i see it is much more efficient. Is there way how I can change the interpreter from the CMakeLists.txt file so th...
-1
2016-09-09T09:28:28Z
39,409,092
<p>When it needs python interpreter, <code>CMakeLists.txt</code> usually uses <a href="https://cmake.org/cmake/help/v3.0/module/FindPythonInterp.html" rel="nofollow">find_package(PythonInterp)</a>, which searches python executable and sets <code>PYTHON_EXECUTABLE</code> to the path where it is located.</p> <p>You may ...
1
2016-09-09T10:10:57Z
[ "python", "cmake", "pypy" ]
Cannot understand the 32-bit encoding of the "Python" string
39,408,341
<p>I am reading the <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Unicode HOWTO</a> of the Python docs to start to really understand Unicode. At the <a href="https://docs.python.org/2/howto/unicode.html#encodings" rel="nofollow">Encodings Paragraph</a> it shows a representation of the "Python" s...
0
2016-09-09T09:32:09Z
39,408,459
<p>A 32-bit integers array consists of, well, 32-bit integers.</p> <p>A byte is 8 bits, so each character necessarily consists of 4 bytes.</p> <p>The number is 0x00000050, which is translated into four bytes. You could order them <code>0x50 0x00 0x00 0x00</code> (byte representing most significant numbers at the end ...
2
2016-09-09T09:37:51Z
[ "python", "unicode" ]
Cannot understand the 32-bit encoding of the "Python" string
39,408,341
<p>I am reading the <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Unicode HOWTO</a> of the Python docs to start to really understand Unicode. At the <a href="https://docs.python.org/2/howto/unicode.html#encodings" rel="nofollow">Encodings Paragraph</a> it shows a representation of the "Python" s...
0
2016-09-09T09:32:09Z
39,408,527
<p>The reason why there are so many zeroes there is because all of those letters are contained in the ASCII set, i.e. occupies one byte (two characters in hexadecimal notation). Unicode encodings are compatible with ASCII like that.</p> <p>The rest is just filler of the remaining 3 bytes.</p> <p>It is kind of like ta...
1
2016-09-09T09:41:37Z
[ "python", "unicode" ]
P4Python: use multiple threads that request perforce information at the same time
39,408,378
<p>I've been working on a "crawler" of sorts that goes through our repository, and lists directories and files as it goes. For every directory it enounters, it creates a thread that does the same for that directory and so on, recursively. Effectively this creates a very short-lived thread for every directory encountere...
0
2016-09-09T09:34:07Z
39,413,906
<p>I found out how to do this (it's infuriatingly simple, as with all simple solutions to overly complicated problems):</p> <p>To build a data model that contains <code>Dir</code> and <code>File</code> classes representing a whole depot with thousands of files, just call <code>p4.run("files", "-e", path + "\\...")</co...
1
2016-09-09T14:26:51Z
[ "python", "multithreading", "perforce", "p4python" ]
Change next list element during iteration?
39,408,404
<p>Imagine you have a list of points in the 2D-space. I am trying to find symmetric points.</p> <p>For doing that I iterate over my list of points and apply symmetry operations. So suppose I apply one of these operations to the first point and after this operation it is equal to other point in the list. These 2 points...
0
2016-09-09T09:35:17Z
39,408,626
<p>In general it is a bad idea to remove values from a list you are iterating over. There are, however, another ways to skip the symmetric points. For example, you can check for each point if you have seen a symmetric one before:</p> <pre><code>for i, point in enumerate(points): if symmetric(point) not in points[:...
1
2016-09-09T09:47:00Z
[ "python", "python-2.7", "loops", "iterator" ]
Change next list element during iteration?
39,408,404
<p>Imagine you have a list of points in the 2D-space. I am trying to find symmetric points.</p> <p>For doing that I iterate over my list of points and apply symmetry operations. So suppose I apply one of these operations to the first point and after this operation it is equal to other point in the list. These 2 points...
0
2016-09-09T09:35:17Z
39,408,710
<p>Whatever symmetric points turn out to be True add them to a set, since set maintains unique elements and look up is <code>O(1)</code> you can use if <code>point not in set</code> condition. </p> <pre><code>if point not in s: #test for symmetry if symmetric: s.add(point) </code></pre>
1
2016-09-09T09:50:18Z
[ "python", "python-2.7", "loops", "iterator" ]
Unable to upgrade Scipy using PIP
39,408,409
<p>I try to upgrade Scipy using PIP on Ubuntu 16.04 but always receive this error. I'm not sure what is going on. The progress reaches 99% and then stops, and spits out this error.</p> <p>I've tried upgrading pip but the same error still occurs.</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/p...
1
2016-09-09T09:35:36Z
39,408,478
<p>Try to disable the cache during install using</p> <pre><code>pip install --no-cache-dir packageName </code></pre> <p>where packageName is <code>scipy</code> in this case</p>
2
2016-09-09T09:38:42Z
[ "python", "ubuntu", "scipy", "pip" ]
SQLAlchemy mapping table columns with filters
39,408,458
<p>I have a table in PostgreSQL that includes information about documents. Lets say something like that:</p> <pre><code>table: doc id (int) name (string) type (int) </code></pre> <p><strong>type</strong> is a category for a document (e.g. 1 - passport, 2 - insurance etc.). Also I have different tables with additiona...
1
2016-09-09T09:37:50Z
39,412,686
<p>If I understood you correctly, you wish to have an <a href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#mapping-class-inheritance-hierarchies" rel="nofollow">inheritance hierarchy</a> based on <code>DocMapping</code> with <code>DocMapping.type</code> as the polymorphic identity. Since you have not prov...
3
2016-09-09T13:28:01Z
[ "python", "postgresql", "flask", "sqlalchemy", "flask-admin" ]
Trying to implement a simple edit distance module
39,408,514
<p>This is the code for the function :</p> <pre><code>def populateConfusionMatrix(word,errword): dp = [[0]*(len(errword)+1) for i in range(len(word)+1)] m = len(word)+1; n = len(errword)+1; for i in range(m): for j in range(n): dp[i][0] = i; dp[0][j] = j; for i in ra...
0
2016-09-09T09:40:50Z
39,409,553
<p>Your code is really difficult to understand, but the problem is definitely in these lines:</p> <pre><code>if dis[3]!=0 : dp[i][j] = min(dp[0:4]) else : dp[i][j] = min(dp[0:3]) </code></pre> <p>Since your list <code>dp</code> has the value:</p> <pre><code>[[0, 1, 2, 3, 4, 5, 6], [1, 0, 0, 0, 0, 0, 0], [2, ...
0
2016-09-09T10:33:14Z
[ "python" ]
updating EmbeddedDocument in Document with Flask - Mongoengine mongoengine.errors.OperationError
39,408,614
<p>I am developing a project with flask and mongodb(mongoengine drive). The application uses Note model as a embeddedDocument for User Modal.</p> <pre><code>class User(db.Document, UserMixin): fields like created_at, content, slug etc... notes = db.ListField(db.EmbeddedDocumentField('Note')) class Note(db.Doc...
-1
2016-09-09T09:46:20Z
39,409,903
<p>You have a few issues here:</p> <ul> <li>You can use (in the most recent versions of mongoengine) an <a href="http://mongoengine-odm.readthedocs.io/apireference.html#mongoengine.fields.EmbeddedDocumentListField" rel="nofollow">EmbeddedDocumentListField</a></li> <li>The <code>Note</code>class needs to inherit Embedd...
0
2016-09-09T10:50:37Z
[ "python", "mongodb", "flask", "mongoengine" ]
Sort etree before writing
39,408,706
<p>I am trying to make an xml with python and etree. Now I want to sort the xml before wring it. Is this possible, and if yes, how?</p> <pre><code>objm = json.loads(response.text) newRoot = ET.Element("root") tree = ET.ElementTree(newRoot) i=0 while i &lt; len(objm): newItem = ET.Subelement(newRoot, "item") S...
0
2016-09-09T09:49:58Z
39,411,459
<p>Found the solution:</p> <pre><code>objm = json.loads(response.text) objm = sorted(objm, key=lambda k: k.get('Start_date', 0), reverse=False) newRoot = ET.Element("root") tree = ET.ElementTree(newRoot) i=0 while i &lt; len(objm): newItem = ET.Subelement(newRoot, "item") Start_date = datetime.strptime(objm[...
0
2016-09-09T12:19:56Z
[ "python", "sorting", "elementtree" ]
Django: filtering expected content type?
39,408,715
<p>Django offers a way to restrict the accepted methods using the <code>@request_http_method</code> decorator, so if a particular view can only respond to a GET request we can do:</p> <pre><code>@require_http_methods(['GET']) def only_get(request): pass </code></pre> <p>Otherwise we get a 403 (FORBIDDEN) response...
0
2016-09-09T09:50:22Z
39,408,796
<p>I do not think that Django has something similar for Content-Type, but you can easily write your Middleware, that would drop requests with wrong Content-Type and then use decorator_from_middleware option.</p> <p>If you use Django 1.10:</p> <pre><code>class AllowedContentTypes(object): def __init__(self, get_r...
0
2016-09-09T09:54:11Z
[ "python", "django" ]
How to connect to redis?
39,408,722
<pre><code>CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } </code></pre> <p>I am trying to connect to redis to save my object in it, bu...
0
2016-09-09T09:50:33Z
39,409,324
<p>First start the redis server. Your OS will provide a mechanism to do that, e.g. on some Linuxes you could use <code>systemctl start redis</code>, or <code>/etc/init.d/redis start</code> or similar. Or you could just start it directly with:</p> <pre><code>$ redis-server </code></pre> <p>which will run it as a foreg...
2
2016-09-09T10:20:47Z
[ "python", "django", "redis" ]
How to connect to redis?
39,408,722
<pre><code>CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } </code></pre> <p>I am trying to connect to redis to save my object in it, bu...
0
2016-09-09T09:50:33Z
39,612,792
<p>if your redis is password protected, you should have a config like this:</p> <pre><code>CACHES.update({ "redis": { "BACKEND": "redis_cache.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "PASSWORD": "XXXXXXXXXXX", "CLIENT_CLASS": "redis_c...
1
2016-09-21T09:36:35Z
[ "python", "django", "redis" ]
Using the same Embedding for Encoder and Decoder in seq2seq
39,408,828
<p>I am building an translation-machine based on the the seq2seq-class. The class assumes different vocabularies for the encoder and the decoder part. Thus also it expects different embeddings for the two.</p> <p>However, I am trying to use this inside a single language. Thus I would like the two embeddings to be one....
0
2016-09-09T09:55:34Z
39,418,862
<p>You can use a reusing variable scope when you call the function which creates the second embedding. If you use a scope with the same name and set reuse=True the embedding will be reused. The documentation on <a href="https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html" rel="nofollow">sharing ...
0
2016-09-09T19:53:34Z
[ "python", "tensorflow" ]
How to override Django Admin
39,408,860
<p>I have two models Restaurant and Details. The superuser assigns each restaurant a user.When that user logs into admin i want only those Details associated with that user's Restaurant to be shown,and he should be able to edit them as well. I tried to override admin's queryset function but to no success.Any help would...
0
2016-09-09T09:57:43Z
39,408,963
<p>The method you need to override is called <code>get_queryset</code>, not <code>queryset</code>.</p>
0
2016-09-09T10:03:14Z
[ "python", "django", "override", "admin" ]
Summary data for pandas dataframe
39,408,938
<p><code>Describe()</code> doesn't do exactly what I'd like - so I'm rolling my own version.</p> <p>The following works fine apart from the final metric 'Num Unique Values' which is returning numbers but they are not correct - I guess I'm using apply incorrectly?</p> <pre><code>pd.DataFrame({ 'Max':d.max(), ...
1
2016-09-09T10:02:13Z
39,408,983
<p>For me it works nice:</p> <pre><code>print(df.apply(lambda x: x.nunique())) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,2,2,1], 'B':[4,5,6,4], 'C':[7,8,9,1], 'D':[1,3,5,9]}) print (df) A B C D 0 1 4 7 1 1 2 5 8 3 2 2 6...
1
2016-09-09T10:04:28Z
[ "python", "pandas" ]
How to force recompile of py source in site-packages?
39,409,084
<p>If I edit source of an installed package and delete the .pyc when I restart an app that uses it there is no new pyc generated in place indicating there is a cache elsewhere.</p> <p>How do I force the update to source to be taken into account?</p>
1
2016-09-09T10:10:33Z
39,409,288
<p>Go to the directory of the <code>.py</code> file and run <code>python -m compileall .</code>.</p>
1
2016-09-09T10:19:20Z
[ "python", "python-2.7", "package" ]
What actually get_Object() takes as a parameter in Fabook SDK?
39,409,170
<p>I want to send friend name as a user in <code>get_object()</code>in below code for getting his public posts. But I am getting error</p> <blockquote> <p>raise GraphAPIError(result) facebook.GraphAPIError: (#803) Cannot query users by their username (tayyab.rasheed.545)</p> </blockquote> <pre><code>user = 'tayya...
-1
2016-09-09T10:13:48Z
39,409,222
<p>It is not possible to get public posts of any user. Even for you own public posts, you need to authorized yourself with the <code>user_posts</code> permission.</p> <p>Edit: Please don´t change your question, especially when there is an answer already. CBroes answer is correct. You are not supposed to get any data ...
0
2016-09-09T10:16:37Z
[ "python", "facebook", "facebook-graph-api" ]
What actually get_Object() takes as a parameter in Fabook SDK?
39,409,170
<p>I want to send friend name as a user in <code>get_object()</code>in below code for getting his public posts. But I am getting error</p> <blockquote> <p>raise GraphAPIError(result) facebook.GraphAPIError: (#803) Cannot query users by their username (tayyab.rasheed.545)</p> </blockquote> <pre><code>user = 'tayya...
-1
2016-09-09T10:13:48Z
39,409,869
<blockquote> <p>Why is the error?</p> </blockquote> <p>Because Facebook removed the username field from the API with v2.0, and as the error message says, you can not query user profiles by their username any more.</p> <blockquote> <p><code>BillGates</code> and <code>me</code> is working fine then why not `tayyab....
1
2016-09-09T10:48:31Z
[ "python", "facebook", "facebook-graph-api" ]
Create two aggregate columns by Group By Pandas
39,409,180
<p>I'm new to DataFrames and I want to group multiple columns and then sum and keep a count on the last column. e.g.</p> <pre><code>s = pd.DataFrame(np.matrix([[1, 2,3,4], [3, 4,7,6],[3,4,5,6],[1,2,3,7]]), columns=['a', 'b', 'c', 'd']) a b c d 0 1 2 3 4 1 3 4 7 6 2 3 4 5 6 3 1 2 3 7 </code></pre...
1
2016-09-09T10:14:28Z
39,409,213
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a>, or shorter version <code>agg</code>:</p> <pre><code>print (s.groupby(by=["a", "b", "c"])["d"].agg([sum, 'count'])) #print (s.groupby(by=["a", "b", "c"])["...
1
2016-09-09T10:16:10Z
[ "python", "pandas", "dataframe", "group-by", "aggregate-functions" ]
How to plot a stacked histogram with two arrays in python
39,409,187
<p>I am trying to create a stacked histogram showing the clump thickness for malignant and benign tumors, with the malignant class colored red and the benign class colored blue. </p> <p>I got the clump_thickness_array and benign_or_malignant_array. The benign_or_malignant_array consists of 2s and 4s.</p> <ol> <li>If ...
1
2016-09-09T10:14:49Z
39,411,881
<p>to obtain a stacked histogram using lists of different length for each group, you need to assemble a list of lists. This is what you are doing with your <code>tmp</code> variable. However, I think you are using the wrong indexes in your for loop. Above, you state that you want to label your data according to the var...
1
2016-09-09T12:42:38Z
[ "python", "matplotlib", "histogram" ]
Create a virtualenv from another virtualenv
39,409,380
<p>Can we create a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> from an existing virtualenv in order to inherit the installed libraries?</p> <p>In detail:</p> <p>I first create a "reference" virtualenv, and add libraries (with versions fixed):</p> <pre><code>virtualenv ref source ref...
0
2016-09-09T10:24:09Z
39,409,459
<p>when you install the second virtualenv you have to add <code>--system-site-packages</code> flag.</p> <pre><code>virtualenv -p ref/bin/python myapp --system-site-packages </code></pre>
0
2016-09-09T10:28:26Z
[ "python", "virtualenv" ]
Create a virtualenv from another virtualenv
39,409,380
<p>Can we create a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> from an existing virtualenv in order to inherit the installed libraries?</p> <p>In detail:</p> <p>I first create a "reference" virtualenv, and add libraries (with versions fixed):</p> <pre><code>virtualenv ref source ref...
0
2016-09-09T10:24:09Z
39,409,609
<p>The <code>pip</code> version <code>1.4.1</code> was bundle with an old version of <code>virtualenv</code>. For example the one shipped with Ubuntu 14.04. You should remove that from your system and install the most recent version of <code>virtualenv</code>.</p> <pre><code>pip install virtualenv </code></pre> <p>Th...
0
2016-09-09T10:35:33Z
[ "python", "virtualenv" ]
Create a virtualenv from another virtualenv
39,409,380
<p>Can we create a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> from an existing virtualenv in order to inherit the installed libraries?</p> <p>In detail:</p> <p>I first create a "reference" virtualenv, and add libraries (with versions fixed):</p> <pre><code>virtualenv ref source ref...
0
2016-09-09T10:24:09Z
39,410,201
<p>I think your problem can be solved differently. With use of <code>PYTHONPATH</code>. First we create <code>ref</code> virtaulenv and install all needed packages here</p> <pre><code>$ virtualenv ref $ source ref/bin/activate $ pip install pep8 $ pip list &gt; pep8 (1.7.0) &gt; pip (8.1.2) &gt; setuptools (26.1.1) &g...
0
2016-09-09T11:08:47Z
[ "python", "virtualenv" ]
Create a virtualenv from another virtualenv
39,409,380
<p>Can we create a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> from an existing virtualenv in order to inherit the installed libraries?</p> <p>In detail:</p> <p>I first create a "reference" virtualenv, and add libraries (with versions fixed):</p> <pre><code>virtualenv ref source ref...
0
2016-09-09T10:24:09Z
39,410,319
<p>You may <code>freeze</code> list of packages from one env:</p> <pre><code>(ref) user@host:~/dir$ pip freeze &gt; ref-packages.txt </code></pre> <p>Then install them:</p> <pre><code>(use) user@host:~/dir$ pip install -r ref-packages.txt </code></pre>
0
2016-09-09T11:15:12Z
[ "python", "virtualenv" ]
How to fill a knapsack table when using recursive dynamic programming
39,409,443
<p><strong>* NOT HOMEWORK *</strong></p> <p>I have implemented the knapsack in python and am successfully getting the best value however I would like to expand the problem to fill a table with all appropriate values for a knapsack table of all weights and items.</p> <p>I've implemented it in python which I'm new to s...
3
2016-09-09T10:27:40Z
39,410,689
<p>In your recursive algorithm you just can't get full filled table, because this step skip a lot:</p> <pre><code>return max(knapsack(i - 1, W), values[i] + knapsack(i - 1, W - weights[i])) </code></pre> <p>I can sudgest you this solution:</p> <pre><code>def knapsack(i, W): global weights, values, table, counter...
1
2016-09-09T11:35:43Z
[ "python", "recursion", "dynamic-programming", "knapsack-problem", "bottom-up" ]
Pandas DataFrame, smart apply of a complex function to groupby result
39,409,500
<p>I have a <code>pandas.DataFrame</code> with 3 columns of type <code>str</code> and <code>n</code> other columns of type <code>float64</code>.</p> <p>I need to group rows by one of the three <code>str</code> columns and apply a function <code>myComplexFunc()</code> which will reduce `̀N rows to one row.</p> <p><c...
1
2016-09-09T10:30:25Z
39,409,706
<p>You can filter DataFrame by <code>dtype</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow"><code>select_dtypes</code></a>, but then need aggreagate by <code>Series</code> <code>df.A</code>:</p> <pre><code>def myComplexFunc(rows): return r...
0
2016-09-09T10:41:12Z
[ "python", "string", "pandas", "dataframe", "group-by" ]
Populating DataFrame from tuple with different size
39,409,544
<p>I have data that is spread over the day. I clustered it and then i calculated the ratio (weight) of each cluster per hour (not all the clusters exists in all hours). (dataframe time_df ) </p> <pre><code> cluster Date 0 1 2014-02-28 14:24:59.535000+02:00 1 1 2014-02-28 14:26...
1
2016-09-09T10:32:43Z
39,410,123
<p>I think you can use:</p> <pre><code>import pandas as pd import numpy as np time_df = pd.DataFrame({'cluster': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 1, 7: 2}, 'Date': {0: pd.Timestamp('2014-02-28 12:24:59.535000'), 1: pd.Timestamp('2014-02-28 12:26:35.0190...
1
2016-09-09T11:03:36Z
[ "python", "list", "pandas", "dataframe", "pivot-table" ]
Populating DataFrame from tuple with different size
39,409,544
<p>I have data that is spread over the day. I clustered it and then i calculated the ratio (weight) of each cluster per hour (not all the clusters exists in all hours). (dataframe time_df ) </p> <pre><code> cluster Date 0 1 2014-02-28 14:24:59.535000+02:00 1 1 2014-02-28 14:26...
1
2016-09-09T10:32:43Z
39,478,682
<pre><code>import pandas as pd import numpy as np time_df = pd.DataFrame({'cluster': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 1, 7: 2}, 'Date': {0: pd.Timestamp('2014-02-28 12:24:59.535000'), 1: pd.Timestamp('2014-02-28 12:26:35.019000'), ...
0
2016-09-13T20:43:11Z
[ "python", "list", "pandas", "dataframe", "pivot-table" ]
Python3 Beautiful Soup get HTML tag anchor
39,409,545
<p>I am trying to use BS4 and Python to save and replace the content of the first <code>&lt;translate&gt;</code> tag in a HTML file.</p> <p>Now I am trying to do something like this:</p> <pre><code>translate_bs4 = bs4_object.find('translate') translate_key = '{{ key }}' translate_initial = str(title_bs4) translate_bs...
2
2016-09-09T10:32:46Z
39,410,209
<p>Try this:</p> <pre><code>translate_bs4 = bs4_object.find('translate') translate_initial = translate_bs4.decode_contents(formatter="html") </code></pre>
1
2016-09-09T11:09:25Z
[ "python", "html", "beautifulsoup" ]
Django: no module named http_utils
39,409,581
<p>I created a new <code>utils</code> package and an <code>http_utils</code> file with some decorators and HTTP utility functions in there. I imported them wherever I am using them and the IDE reports no errors, and I also added the <code>utils</code> module to the <code>INSTALLED_APPS</code> list.</p> <p>However, whe...
0
2016-09-09T10:34:32Z
39,409,980
<p>Make sure the package is correct (Include <strong>init</strong>.py file).</p> <p>Make sure there are no other utils files in the same directory level. That is if you are importing from utils import http_utils from views.py, there should not be a utils.py in the same folder. Conflict occurs because of that.</p> <p>...
0
2016-09-09T10:55:09Z
[ "python", "django" ]
Django: no module named http_utils
39,409,581
<p>I created a new <code>utils</code> package and an <code>http_utils</code> file with some decorators and HTTP utility functions in there. I imported them wherever I am using them and the IDE reports no errors, and I also added the <code>utils</code> module to the <code>INSTALLED_APPS</code> list.</p> <p>However, whe...
0
2016-09-09T10:34:32Z
39,418,949
<p>As stared by Arundas above, since there is a utils.py file I suggest renaming the module to something such as <code>utilities</code>, and also make sure you have a <strong>__init__.py</strong> file in that directory.</p> <pre><code>from utilities.http_utils import class_name </code></pre>
0
2016-09-09T20:00:22Z
[ "python", "django" ]
Correlation heatmap
39,409,866
<p>I want to represent correlation matrix using a heatmap. There is something called <a href="http://www.sthda.com/english/wiki/visualize-correlation-matrix-using-correlogram" rel="nofollow">correlogram</a> in R, but I don't think there's such a thing in Python.</p> <p>How can I do this? The values go from -1 to 1, fo...
0
2016-09-09T10:48:19Z
39,409,968
<p>You can use <a href="http://matplotlib.org/index.html" rel="nofollow">matplotlib</a> for this. There's a similar question which shows how you can achieve what you want: <a href="http://stackoverflow.com/questions/33282368/plotting-a-2d-heatmap-with-matplotlib">Plotting a 2D heatmap with Matplotlib</a></p>
1
2016-09-09T10:54:33Z
[ "python" ]
Correlation heatmap
39,409,866
<p>I want to represent correlation matrix using a heatmap. There is something called <a href="http://www.sthda.com/english/wiki/visualize-correlation-matrix-using-correlogram" rel="nofollow">correlogram</a> in R, but I don't think there's such a thing in Python.</p> <p>How can I do this? The values go from -1 to 1, fo...
0
2016-09-09T10:48:19Z
39,410,167
<ol> <li>Use the 'jet' colormap for a transition between blue and red.</li> <li>Use <code>pcolor()</code> with the <code>vmin</code>, <code>vmax</code> parameters.</li> </ol> <p>It is detailed in this answer: <a href="http://stackoverflow.com/a/3376734/21974">http://stackoverflow.com/a/3376734/21974</a></p>
1
2016-09-09T11:06:31Z
[ "python" ]
Exiting out of a program through a menu option
39,409,882
<p>I need to say first and foremost, I am just learning Python. </p> <p>I am making a simple python program that has a menu option for exiting the program by using a function I called exit. I have tried making the exit function just call break, but I am getting an error when the exit function is called.</p> <p>Any ...
1
2016-09-09T10:49:24Z
39,410,221
<p>Use the <code>sys.exit</code> method:</p> <pre><code>import sys def exit(): sys.exit() </code></pre> <p>That's the proper way to terminate your program.</p> <p>You can also use <code>os._exit</code> the same way.</p>
0
2016-09-09T11:10:18Z
[ "python", "menu", "exit" ]
Exiting out of a program through a menu option
39,409,882
<p>I need to say first and foremost, I am just learning Python. </p> <p>I am making a simple python program that has a menu option for exiting the program by using a function I called exit. I have tried making the exit function just call break, but I am getting an error when the exit function is called.</p> <p>Any ...
1
2016-09-09T10:49:24Z
39,410,356
<p><code>break</code> is for breaking out of <code>for</code> or <code>while</code> loops, but it must be called from within the loop. I'm guessing that you expect the <code>break</code> to break out of your program's main event loop from an event handler, and that is not going to work because, as aforementioned, the <...
0
2016-09-09T11:17:05Z
[ "python", "menu", "exit" ]
Exiting out of a program through a menu option
39,409,882
<p>I need to say first and foremost, I am just learning Python. </p> <p>I am making a simple python program that has a menu option for exiting the program by using a function I called exit. I have tried making the exit function just call break, but I am getting an error when the exit function is called.</p> <p>Any ...
1
2016-09-09T10:49:24Z
39,411,744
<p>Just forget about your own <code>exit()</code> function. You can simply do:</p> <pre><code>from sys import exit </code></pre> <p>And the <code>exit()</code> function from <code>sys</code> module will do the job.<br> It's also worth to know what happens under the hood. Function <code>sys.exit()</code> actually thro...
0
2016-09-09T12:34:42Z
[ "python", "menu", "exit" ]
pexpect : Is there any way to prevent input overrun while using pexpect?
39,409,892
<p>Using pexpect, I am connecting to a linux machine console which is a machine with limited capabilities. When I spawn a connection and try to execute command using send or sendline I get error saying <code>"ttyAMA0: 1 input overrun(s)"</code></p> <p>This is probably happening because <code>pexpect</code> sending inp...
0
2016-09-09T10:49:53Z
39,796,140
<p>Disclaimer: This is a workaround than actual solution to buffer overrun problem. Did following steps:</p> <ol> <li>Before calling python script having pexpect, set baud rate to match with the console/telnet connect using stty. E.g. <code>stty speed 50</code></li> <li>Spawn new shell in pexpect and set <code>delayb...
0
2016-09-30T16:32:41Z
[ "python", "linux", "expect", "tty", "pexpect" ]
Sentence clustering
39,409,981
<p>I have a huge number of names from different sources.</p> <ol> <li>I need to extract all the groups (part of the names), which repeat from one to another. In the example below program should locate: Post, Office, Post Office.</li> <li>I need to get popularity count.</li> </ol> <p>So I want to extract a sorted by p...
-1
2016-09-09T10:55:12Z
39,425,953
<p>You are not looking for clustering (and that is probably why "all of them suck" for @andrewmatte).</p> <p>What you are looking for is <em>word counting</em> (or more precisely, n-gram-counting). Which is actually a much easier problem. Thst is why you won't be finding any library for that...</p> <p>Well, actually ...
0
2016-09-10T12:11:54Z
[ "python", "machine-learning", "cluster-analysis" ]
Sentence clustering
39,409,981
<p>I have a huge number of names from different sources.</p> <ol> <li>I need to extract all the groups (part of the names), which repeat from one to another. In the example below program should locate: Post, Office, Post Office.</li> <li>I need to get popularity count.</li> </ol> <p>So I want to extract a sorted by p...
-1
2016-09-09T10:55:12Z
39,426,291
<p>Are you looking for something like this?</p> <pre><code>workspace={} with open('names.txt','r') as f: for name in f: if len(name): # makes sure line isnt empty if name in workspace: workspace[name]+=1 else: workspace[name]=1 for name in workspace: print "{}: {}".format(name,wor...
0
2016-09-10T12:56:51Z
[ "python", "machine-learning", "cluster-analysis" ]
PyQT: PushButton receives commands while disabled
39,410,037
<p>I came across this problem and tried to break it down to the simplest code I could imagine: I created a GUI using Qt Designer V4.8.7 that only consists of a single pushButton with all default settings. It's called 'Test2.ui'. When the button is pressed, it's supposed to get disabled, print something in the terminal ...
1
2016-09-09T10:58:11Z
39,419,176
<p>Your example code will not work because the test function blocks the gui. Whilst it is blocking, the button's disabled state is not updated properly, and so the <code>clicked</code> signal can still be emitted. The best way to avoid blocking the gui is to do the work in a separate thread:</p> <pre><code>class Worke...
0
2016-09-09T20:21:41Z
[ "python", "qt", "pyqt", "pyqt4", "qpushbutton" ]
Reading fortran binary (streaming access) with np.fromfile or open & struct
39,410,053
<p>The following Fortran code:</p> <pre><code>INTEGER*2 :: i, Array_A(32) Array_A(:) = (/ (i, i=0, 31) /) OPEN (unit=11, file = 'binary2.dat', form='unformatted', access='stream') Do i=1,32 WRITE(11) Array_A(i) End Do CLOSE (11) </code></pre> <p>Produces streaming binary output with numbers from 0 t...
1
2016-09-09T10:59:25Z
39,410,638
<p>The problem is in open file mode. Default it is 'text'. Change this mode to binary:</p> <pre><code>with open("binary2.dat", 'rb') as f: content = np.fromfile(f, dtype=np.int16) </code></pre> <p>and all the numbers will be readed successfull. See Dive in to Python chapter <a href="http://www.diveintopython3.net...
3
2016-09-09T11:32:53Z
[ "python", "io", "binary", "hex" ]