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
Django Left Outer Join
38,060,232
<p>I have a website where users can see a list of movies, and create reviews for them.</p> <p>The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score.</p> <p>...
13
2016-06-27T17:52:43Z
38,132,258
<p>This is how I would do it. Two queries, not one:</p> <pre><code>class Topic(models.Model): #... @property def user_value(self): try: return self.user_records[0].value except IndexError: #This topic does not have #a review by the request.user ...
5
2016-06-30T20:01:54Z
[ "python", "django", "django-models", "orm" ]
Django Left Outer Join
38,060,232
<p>I have a website where users can see a list of movies, and create reviews for them.</p> <p>The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score.</p> <p>...
13
2016-06-27T17:52:43Z
38,133,913
<p>The solution is inspired by <a href="http://stackoverflow.com/a/38108285/448474">trinchet's answer</a></p> <pre><code>&gt;&gt;&gt; qs = Topic.objects.annotate( ... f=Max(Case(When(record__user=johnny, then=F('record__value')))) ... ) &gt;&gt;&gt; print(qs.values_list('name', 'f')) [(u'A', 1), (u'B', None), ...
5
2016-06-30T21:57:22Z
[ "python", "django", "django-models", "orm" ]
Django Left Outer Join
38,060,232
<p>I have a website where users can see a list of movies, and create reviews for them.</p> <p>The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score.</p> <p>...
13
2016-06-27T17:52:43Z
38,156,098
<blockquote> <p>What I essentially want is this</p> <pre><code>select * from bar_topic left join (select topic_id as tid, value from bar_record where user_id = 1) on tid = bar_topic.id </code></pre> </blockquote> <p>...or, perhaps this equivalent which avoids a subquery...</p> <pre><code>select * from bar_topic le...
3
2016-07-02T03:02:54Z
[ "python", "django", "django-models", "orm" ]
member-wise operations on two dicts
38,060,292
<p>How would you implement operations like element-wise <code>max</code>, <code>min</code>, <code>avg</code>, <code>+</code>, etc. for dictionaries?</p> <p>As an example:</p> <pre><code>def max_dict(d1, d2): ''' @return the maximum member value for each key &gt;&gt;&gt; a = {3: 4, 4: 7}; b = {3: 5, 4: 6}; max...
0
2016-06-27T17:56:36Z
38,060,351
<blockquote> <p>Is this a sensible way to do it?</p> </blockquote> <p>Yeah. I'd probably use a dict comprehension, but the loop works fine.</p> <blockquote> <p>Is there some built-in function to simplify this?</p> </blockquote> <p>No.</p> <blockquote> <p>Should <code>+</code>, <code>avg</code>, etc. be implem...
3
2016-06-27T18:00:12Z
[ "python", "dictionary", "max" ]
member-wise operations on two dicts
38,060,292
<p>How would you implement operations like element-wise <code>max</code>, <code>min</code>, <code>avg</code>, <code>+</code>, etc. for dictionaries?</p> <p>As an example:</p> <pre><code>def max_dict(d1, d2): ''' @return the maximum member value for each key &gt;&gt;&gt; a = {3: 4, 4: 7}; b = {3: 5, 4: 6}; max...
0
2016-06-27T17:56:36Z
38,060,381
<p>Like this:</p> <pre><code>d1 = {1:2, 3:4} d2 = {1:-8, 3:10} print {k:min(v, d2[k]) for k,v in d1.items()} </code></pre> <p>This uses Python's <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary comprehension</a> syntax.</p> <p>If the dictionaries have distinct k...
2
2016-06-27T18:02:25Z
[ "python", "dictionary", "max" ]
member-wise operations on two dicts
38,060,292
<p>How would you implement operations like element-wise <code>max</code>, <code>min</code>, <code>avg</code>, <code>+</code>, etc. for dictionaries?</p> <p>As an example:</p> <pre><code>def max_dict(d1, d2): ''' @return the maximum member value for each key &gt;&gt;&gt; a = {3: 4, 4: 7}; b = {3: 5, 4: 6}; max...
0
2016-06-27T17:56:36Z
38,061,017
<p>This one is generalizable to an arbitrary number of dicts, any function you can apply to a list, and dicts with different keys:</p> <pre><code>def agg_dicts(func, *args): keys = [] for d in args: keys += list(d.keys()) keys = set(keys) out = {} for key in keys: vals = [d[key] fo...
1
2016-06-27T18:41:19Z
[ "python", "dictionary", "max" ]
Do I authenticate at database level, at Flask User level, or both?
38,060,380
<p>I have an MS-SQL deployed on AWS RDS, that I'm writing a Flask front end for. I've been following some intro Flask tutorials, all of which seem to pass the DB credentials in the connection string URI. I'm following the tutorial here:</p> <p><a href="https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a...
0
2016-06-27T18:02:18Z
38,061,482
<p>The tutorial you are using uses Flask-Sqlalchemy to abstract the database setup stuff, that's why you don't see engine.connect().</p> <p>Frameworks like Flask-Sqlalchemy are designed around the idea that you create a connection pool to the database on launch, and share that pool amongst your various worker threads....
1
2016-06-27T19:11:27Z
[ "python", "authentication", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Query from more than one table Python Mysql Connector
38,060,383
<p>I have the following sql query:</p> <pre><code>SELECT pc.patente, cs.cpc_group_codigo_cpc_group FROM patente_pc pc , patente_cpc cpc, cpc_subgroup cs, cpc_group cg WHERE pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND cpc.cpc = cs.codigo_cpc_subgroup AND cs.cpc_...
0
2016-06-27T18:02:34Z
38,060,537
<p>The variables in your <code>for</code> loop: <code>(pc.patente, cs.cpc_group_codigo_cpc_group)</code> are user defined; the names used do not have anything to do with the names from the query. Thus, you can call them whatever you want. You may consider using <code>(pc__patente, cs__cpc_group_codigo_cpc_group)</cod...
0
2016-06-27T18:13:04Z
[ "python", "mysql", "connector" ]
Query from more than one table Python Mysql Connector
38,060,383
<p>I have the following sql query:</p> <pre><code>SELECT pc.patente, cs.cpc_group_codigo_cpc_group FROM patente_pc pc , patente_cpc cpc, cpc_subgroup cs, cpc_group cg WHERE pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND cpc.cpc = cs.codigo_cpc_subgroup AND cs.cpc_...
0
2016-06-27T18:02:34Z
38,060,565
<p>Got it, sorry for the post.. Searching in <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html</a> I learned a few attributes of the cursor, and using th...
0
2016-06-27T18:15:11Z
[ "python", "mysql", "connector" ]
How to get general user information with SteamID64?
38,060,386
<p>I am having problem with doing simple things using Steams 64 bit id. </p> <p>How can i use SteamAPI to get the general information? like displaying name, username, location.</p> <p>I used SteamAuth to make my social authentication on website, which only has the function, that gets the id.</p> <p>Example:</p> <pr...
0
2016-06-27T18:02:39Z
38,114,770
<p>There are a whole lot of WebAPI methods to get details about a Steam user. You seem to be looking for <a href="https://lab.xpaw.me/steam_api_documentation.html#ISteamUser_GetPlayerSummaries_v2" rel="nofollow">GetPlayerSummaries</a>.</p> <p>You'll need an <a href="https://steamcommunity.com/dev/apikey" rel="nofollow...
0
2016-06-30T05:40:34Z
[ "python", "steam", "steam-web-api" ]
numpy: fromfile for gzipped file
38,060,450
<p>I am using <code>numpy.fromfile</code> to construct an array which I can pass to the <code>pandas.DataFrame</code> constructor</p> <pre><code>import numpy as np import pandas as pd def read_best_file(file, **kwargs): ''' Loads best price data into a dataframe ''' names = [ 'time', 'bid_size', 'bi...
0
2016-06-27T18:07:46Z
38,061,619
<p><code>open.gzip()</code> doesn't return a true <code>file</code> object. It's duck one .. it walks like a duck, sounds like a duck, but isn't quite a duck per <code>numpy</code>. So <code>numpy</code> is being strict (since much is written in lower level C code, it might require an actual file descriptor.)</p> <p...
0
2016-06-27T19:19:33Z
[ "python", "numpy" ]
Checking out a branch with GitPython. making commits, and then switching back to the previous branch
38,060,456
<p>I'm using the <a href="https://github.com/gitpython-developers/GitPython" rel="nofollow">GitPython</a> library to do some simple Git manipulation and I'd like to checkout a branch, make a commit, and then checkout the previous branch. The docs are a little confusing on how to do this. So far, I have this:</p> <pre>...
0
2016-06-27T18:08:06Z
38,061,339
<p>From <a href="http://gitpython.readthedocs.io/en/stable/tutorial.html" rel="nofollow">http://gitpython.readthedocs.io/en/stable/tutorial.html</a> </p> <p>Switching Branches</p> <p>To switch between branches similar to git checkout, you effectively need to point your HEAD symbolic reference to the new branch and r...
1
2016-06-27T19:00:43Z
[ "python", "git" ]
Concatenate two pandas DataFrames without duplicating row ids?
38,060,486
<p>I have two <code>pandas</code> <code>DataFrames</code>. They have the same columns, and so I want to take the data from each and put it into a larger <code>DataFrame</code>. The issue is that the number that identifies each row is copied verbatim, while I want it to update intelligently.</p> <p>Here's what I have:<...
0
2016-06-27T18:09:49Z
38,060,578
<p>Use <code>concat</code> with <code>ignore_index=True</code>:</p> <pre><code>&gt;&gt;&gt; pandas.concat([df_one, df_two], ignore_index=True) animal color 0 cat black 1 dog brown 2 fish red 3 bird blue </code></pre>
3
2016-06-27T18:16:04Z
[ "python", "pandas", "dataframe" ]
Concatenate two pandas DataFrames without duplicating row ids?
38,060,486
<p>I have two <code>pandas</code> <code>DataFrames</code>. They have the same columns, and so I want to take the data from each and put it into a larger <code>DataFrame</code>. The issue is that the number that identifies each row is copied verbatim, while I want it to update intelligently.</p> <p>Here's what I have:<...
0
2016-06-27T18:09:49Z
38,060,605
<p>I like @BrenBarn's answer. You could alternately do:</p> <pre><code>&gt;&gt;&gt; df_concat = pd.concat([df_one, df_two]).reset_index(drop=True) &gt;&gt;&gt; df_concat animal color 0 cat black 1 dog brown 2 fish red 3 bird blue </code></pre>
1
2016-06-27T18:17:23Z
[ "python", "pandas", "dataframe" ]
XGBoost predictions output not binary?
38,060,493
<p>i'm trying to run a very simple example where XGBoost takes some data and do a binary classification. The <a href="https://github.com/dmlc/xgboost/blob/master/doc/parameter.md#learning-task-parameters" rel="nofollow">documentation</a> says that xgboost outputs the probabilities when "binary:logistic" is used </p> <...
0
2016-06-27T18:10:28Z
38,060,547
<p>Yes, it is the probability of getting 1. To get it as a binary value, just check whether it is greater or less than 0.5.</p>
0
2016-06-27T18:13:48Z
[ "python", "machine-learning", "xgboost" ]
how to use speech-recognition of mac from within python
38,060,614
<p>There is this awesome threat, showing how to use the say-command from mac within python: <a href="http://stackoverflow.com/questions/12758591/python-text-to-speech-in-macintosh">Python Text to Speech in Macintosh</a></p> <p>Is there anything similar for the speech-recognition? I would like to use the german speech-...
2
2016-06-27T18:17:54Z
38,060,723
<p>This would work and the SpeechRecognition package will handle German </p> <pre><code>import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) </code></pre>
3
2016-06-27T18:24:19Z
[ "python", "osx", "terminal", "speech-recognition" ]
how to use speech-recognition of mac from within python
38,060,614
<p>There is this awesome threat, showing how to use the say-command from mac within python: <a href="http://stackoverflow.com/questions/12758591/python-text-to-speech-in-macintosh">Python Text to Speech in Macintosh</a></p> <p>Is there anything similar for the speech-recognition? I would like to use the german speech-...
2
2016-06-27T18:17:54Z
38,092,725
<p>Great! Thanks for your help. To use google with german, simply add language="de"</p> <pre><code>import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) print("Google Speech Recognition thinks you said " + r.recognize_google(audio...
0
2016-06-29T07:11:53Z
[ "python", "osx", "terminal", "speech-recognition" ]
Odoo 8 open treeview from wizard
38,060,628
<p>I have a wizard that research and add the result to a table and I created a treeview that read the items in this table. I want my wizard to open that treeview once the research is done but I can't find a way to redirect to a specific view from python. Anyone have an idea?</p> <p>My module is called <strong>sale_rec...
1
2016-06-27T18:18:37Z
38,067,150
<p>Suppose there is one button in wizard when you click on that button it will open tree view of particular model.</p> <p>In wizard button should looks like,</p> <pre><code>&lt;button class="oe_inline oe_stat_button" name="open_tree_view" type="object" icon="fa-pencil"&gt; Open Tree View &lt;/button&gt; </code></pre...
0
2016-06-28T04:37:03Z
[ "python", "xml", "openerp", "odoo-8" ]
django : TemplateDoesNotExist
38,060,639
<p>I have the "TemplateDoesNotExist" error. I already read severals answers about this problem, but it still does not work. There is some part of my settings.py file : </p> <pre><code>import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) </code></pre> <p>fews lines after : </p> <pre><cod...
0
2016-06-27T18:19:15Z
38,060,653
<p>You are putting the code that meant to be executed in a string. Replace:</p> <pre><code>'DIRS': ["os.path.join(BASE_DIR, 'templates')"], </code></pre> <p>with:</p> <pre><code>'DIRS': [os.path.join(BASE_DIR, 'templates')], </code></pre>
4
2016-06-27T18:20:00Z
[ "python", "django" ]
Compare two dictionaries with various data types as values
38,060,641
<p>It is best to show by an example. I'm taking the "properties" field from a matplotlib plot. It is a dictionary with different keys and values.</p> <pre><code>keys = gca().properties().keys ax1 = gca().properties() </code></pre> <p>Then I'm plotting something else and I take another instance</p> <pre><code>ax2 = g...
0
2016-06-27T18:19:31Z
38,061,827
<p>The problem is that <code>numpy</code> arrays do not support being converted to <code>bool</code>, so the problem is not the <code>!=</code> comparison but the fact that the <code>if</code> statement is trying to convert the obejct to <code>bool</code> to see whether it is <code>True</code> or <code>False</code> and...
1
2016-06-27T19:32:26Z
[ "python", "matplotlib" ]
Compare two dictionaries with various data types as values
38,060,641
<p>It is best to show by an example. I'm taking the "properties" field from a matplotlib plot. It is a dictionary with different keys and values.</p> <pre><code>keys = gca().properties().keys ax1 = gca().properties() </code></pre> <p>Then I'm plotting something else and I take another instance</p> <pre><code>ax2 = g...
0
2016-06-27T18:19:31Z
38,270,594
<p>There seem to be know builtin <code>deepdiff</code> function that takes two objects and go into all their child methods to find the differences. Build your own function.</p>
0
2016-07-08T15:39:40Z
[ "python", "matplotlib" ]
Displaying linked database results in single HTML table
38,060,735
<p>I have several database tables that are linked by foreign keys (you'll have to forgive the basic examples here, I'm having trouble copy/pasting out of my development env right now). </p> <pre><code># models.py class Task(models.Model): details = models.ForeignKey(Details) task = models.CharField(max_length...
1
2016-06-27T18:24:55Z
38,212,348
<p>I didn't realize that I could iterate through an object and add each of those items to a list. I was able to solve my own problem like so:</p> <pre><code>all = [] task = Tasks.objects.get(id=1) all.append(task) activities = Activities.objects.filter(task_id=task) for activity in activities: all.append(activi...
0
2016-07-05T20:40:30Z
[ "python", "django", "django-templates", "html-table" ]
Python - Copy element
38,060,738
<p>I've been practicing Python watching tutorials and reading books and I'm struggling with the <code>copy</code> function. I'm trying to copy an <code>ID</code> that gets populated into an <em>element box</em>, so I locate the element and try to copy it but doesn't work. :(</p> <pre><code>alert = driver.switch_to_ale...
0
2016-06-27T18:25:02Z
38,062,054
<blockquote> <p>A WebElement instance has no copy2 attribute in Python selenium bindings. – alecxe 1 hour ago</p> </blockquote> <p>Thank you Alexcxe for this answer</p> <p>The resolution: Originally what I had wanted to do was copy the text in an element field and save it for later use. What I have done now to ...
0
2016-06-27T19:45:54Z
[ "python", "selenium", "elements" ]
Python's equivalent for define_method
38,060,773
<p>I have this code in ruby:</p> <pre><code>class Package def initialize(name) @name = name @elements = [] end [:type, :block].each do |bindtype| define_method "get_#{bindtype}_by_name" do |name| get_by_name(name, bindtype) end end def get_by_name(name, bindtype=nil) @elements.each do |e...
2
2016-06-27T18:26:56Z
38,060,823
<p>You were almost there; bind the <code>bindtype</code> value as a default value for the function argument, and you want to call <code>get_by_name()</code> on <code>self</code>:</p> <pre><code>for bindtype in bindtypes: def _in_bindtype(self, name, bindtype=bindtype): self.get_by_name(name, bindtype) ...
2
2016-06-27T18:30:09Z
[ "python", "ruby" ]
Trying to find frequent patterns in a sequence python
38,060,783
<p>I am trying to find frequent ( ordered or unordered) patterns in a column. The column contains numeric IDs. for eg: s=[1 2 3 4 1 2 6 7 8 2 1 10 11]</p> <p>Here 1 2 or 2 1 taking as a same case is the most frequent set. </p> <p>Please help me to solve this problem, I could think of apriori, FP algorithms but I don'...
0
2016-06-27T18:27:45Z
38,061,355
<p>There are a couple of business decisions you have to take before you will have a normal algorithm. The first and the most important decision is what size of the set do you want. Clearly if you have <code>{a, b, ... x}</code> is the most frequent set, then every subset (like <code>{a, x}</code> or <code>{c, d, y}</co...
0
2016-06-27T19:01:29Z
[ "python", "algorithm", "pattern-matching", "sequence", "apriori" ]
Trying to find frequent patterns in a sequence python
38,060,783
<p>I am trying to find frequent ( ordered or unordered) patterns in a column. The column contains numeric IDs. for eg: s=[1 2 3 4 1 2 6 7 8 2 1 10 11]</p> <p>Here 1 2 or 2 1 taking as a same case is the most frequent set. </p> <p>Please help me to solve this problem, I could think of apriori, FP algorithms but I don'...
0
2016-06-27T18:27:45Z
38,064,589
<p>I can think of a brute force approach.But it is not not efficient.It will be something like:</p> <pre><code>a) Calculate the powerset of the given sequence (it will be completed in exponential time). This will include duplicate occurrences of subsets as well. b) Iterate over the subsets and calculate the frequency ...
0
2016-06-27T23:08:07Z
[ "python", "algorithm", "pattern-matching", "sequence", "apriori" ]
How do you make a list of random numbers
38,060,788
<p>I'm working with python to create a game that the computer will pick numbers from 1 to 10 and the player can choose which numbers they want to keep or delete..The sum of the random numbers must add up to 21 and the player has only 10 tries.What would be the code I use to create the list of random numbers to equal 21...
-1
2016-06-27T18:28:02Z
38,061,201
<p>You can create a list of random values, just call <code>random.randint</code> and <code>append</code> the result to a list. A contrived example:</p> <pre><code>import random values = [] # list to hold accepted values for _ in range(10): # aka "do the following ten times" card_value = random.randint(1,10) # d...
0
2016-06-27T18:52:56Z
[ "python", "list", "python-2.7", "random", "numbers" ]
How do you make a list of random numbers
38,060,788
<p>I'm working with python to create a game that the computer will pick numbers from 1 to 10 and the player can choose which numbers they want to keep or delete..The sum of the random numbers must add up to 21 and the player has only 10 tries.What would be the code I use to create the list of random numbers to equal 21...
-1
2016-06-27T18:28:02Z
38,062,069
<p>So i have fix your code like this:</p> <pre><code>import random import time # name = raw_input("Hello, What's your name?") # changed this to this: name = raw_input("Hello, What's your name? ") print "Welcome," ,name, "Time to play Catch 21!" time.sleep(1) tries = 0 # tries_remaining = 10 # you don't need this it's ...
0
2016-06-27T19:46:36Z
[ "python", "list", "python-2.7", "random", "numbers" ]
Package not found error on windows in python-docx?
38,060,809
<p>I'm getting an error when I try to access files from my working directory. This is not a duplicate of @dsphoebe 's question, because the file I try to open is certainly a .docx file and for whatever reason, I can't open it.</p> <pre><code>rootdir = 'C:\\Users\\me\\Documents\\Python\\mydocs\\' for subdir, dirs, file...
1
2016-06-27T18:29:28Z
38,062,507
<p>Where are you using the <code>rootdir</code> variable? </p> <p>If <code>docx</code> is just trying to open 'my doc.docx' by concatenating that string with the current dir it might not be properly escaping the space character in the filename.</p> <p>Try using <code>os.path.join()</code>:</p> <pre><code>import os.p...
2
2016-06-27T20:18:04Z
[ "python", "python-docx" ]
Tensorflow: what is tf.contrib? And where can I find the source code for `tf.contrib.layers.sparse_column_with_hash_bucket`?
38,060,825
<p>Looking at the example <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">here</a> from the tensorflow master branch, and I want to find the source for <code>tf.contrib.layers.sparse_column_with_hash_bucket</code>. </p> <p>Seems like some ...
1
2016-06-27T18:30:12Z
38,062,223
<p>The source is here:</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/feature_column.py#L365" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/feature_column.py#L365</a></p> <p>In general, tf.contr...
5
2016-06-27T19:56:49Z
[ "python", "tensorflow" ]
Calling a class method on a dict object: AttributeError: 'dict' object has no attribute 'get_keyval'
38,060,858
<p>Is it possible to get the key value of the <code>filter_dict</code> object kind of that <code>filter_dict.get_keyval("author")</code>?:</p> <pre><code>import json class Config(dict): def open_json_file(self, json_string): load_dict = json.loads(json_string) return load_dict def get_keyval(...
-1
2016-06-27T18:32:02Z
38,060,944
<p>The type of the object returned by <code>Config().open_json_file</code> is not <code>Config</code>, but the plain dict returned by <code>json.loads</code>. Basically, <code>Config</code> is not a class, but just a collection of functions coded as methods. What you want is probably this:</p> <pre><code>import json ...
1
2016-06-27T18:36:50Z
[ "python", "json", "python-3.x", "dictionary", "inheritance" ]
Solving multiple PDEs in Fipy
38,060,887
<p>I'm trying to solve a system of partial differential equations in Python, using <a href="http://www.ctcms.nist.gov/fipy/index.html" rel="nofollow">Fipy</a>. I have a system of at least 3 PDEs. </p> <p>I was wondering which approach is best for solving such a system? Fipy supports both <a href="http://www.ctcms.nist...
2
2016-06-27T18:33:44Z
38,080,321
<p>Generally, coupled will achieve better convergence than uncoupled. However, the more equations that are coupled, the larger the matrix that must be built, so coupled may require too much memory for particularly large problems.</p> <p>There is no limit to how many equations may be coupled.</p> <p>Even when coupling...
1
2016-06-28T15:25:43Z
[ "python", "numpy", "scipy", "pde", "fipy" ]
Escape reserved keyword in Python [Protocol Buffer autogenerated class]
38,060,895
<p>so I'm sort of in a fix. I'm using Google protocol buffers, and it just so happens that one of the fields in the schema is named "from". I'm using python, so everytime I try to access it, I get a syntax error. [ex - SomeClass.from -> Syntax error ]</p> <p>Is there anyway to somehow access the field without using ...
2
2016-06-27T18:34:00Z
38,061,021
<p>After you pull your data, you can always save the <code>from</code> into <code>from_</code> (the pythonic way of avoiding namespace clashes) by using the <code>getattr(var, "from")</code> statement; Ie</p> <pre><code>SomeClass # is a protocol-buffer SomeClass.from_ = getattr(SomeClass, "from") </code></pre> <p>And...
1
2016-06-27T18:41:28Z
[ "python", "protocol-buffers" ]
TransportError 400 Elasticsearch with huge list of terms
38,060,945
<p>Search with small list of terms gives what i want</p> <pre><code>In [29]: small_list Out[29]: [8096, 8105, 8114, 8116, 8128, 8130] In [30]: sqs.filter(id__in=small_list) Out[30]: [&lt;SearchResult: web.listing (pk=u'8128')&gt;, &lt;SearchResult: web.listing (pk=u'8130')&gt;, &lt;SearchResult: web.listing (pk=u'811...
2
2016-06-27T18:36:51Z
38,073,310
<p>By default elasticsearch is a limit on the query terms limited to 1024.</p> <p>below query works for you</p> <pre><code>sqs.filter(id__in=big_list[:1024]) </code></pre> <p>more info <a href="https://groups.google.com/forum/#!topic/elasticsearch/LqywKHKWbeI" rel="nofollow">https://groups.google.com/forum/#!topic/e...
1
2016-06-28T10:11:24Z
[ "python", "django", "elasticsearch", "django-haystack" ]
How to transform vector into unit vector in Tensorflow
38,061,080
<p>This is a pretty simple question that I just can't seem to figure out. I am working with an an output tensor of shape [100, 250]. I want to be able to access the 250 Dimensional array at any spot along the hundred and modify them separately. The tensorflow mathematical tools that I've found either do element-wise...
2
2016-06-27T18:45:21Z
38,086,647
<p>There is no real trick here, you can do as in numpy.<br> The only thing to make sure is that <code>norm</code> is of shape <code>[100, 1]</code> so that it broadcasts well in the division <code>x / norm</code>.</p> <pre class="lang-py prettyprint-override"><code>x = tf.placeholder(tf.float32, [100, 250]) norm = tf...
2
2016-06-28T21:31:15Z
[ "python", "numpy", "tensorflow" ]
Why does yielding an item in a function give different output than printing the item?
38,061,106
<p>I wrote this function to read a list of words representing a number and pair 1-9 digits with multipliers.</p> <pre><code>def listpairs(element): pair = [] for word in enumerate(element): pair.append(word[1]) if word[1] in denoms: yield pair pair.clear() if wor...
0
2016-06-27T18:46:42Z
38,061,282
<h2>Solution</h2> <p>Your are yielding the same list all the time. Replace:</p> <pre><code>pair.clear() </code></pre> <p>with:</p> <pre><code>pair = [] </code></pre> <p>To get new list.</p> <p>Example:</p> <pre><code>from string import digits denoms = ['hundred', 'ten'] def listpairs(element): pair = [] ...
1
2016-06-27T18:57:05Z
[ "python", "yield" ]
Are there any complex sklearn models with partial_fit or similar for online learning?
38,061,235
<p>I am looking for a Python online learning/incremental learning algorithm of 'reasonable' complexity. </p> <p>In Scikit-learn I have found a few algorithms with the <code>partial_fit</code> method, namely <code>['BernoulliNB', 'GaussianNB', 'MiniBatchKMeans', 'MultinomialNB', 'PassiveAggressiveClassifier', PassiveAg...
-3
2016-06-27T18:54:40Z
38,061,552
<p>One general approach is to combine a <strong>Linear-Classifier</strong> with some <strong>Kernel-Approximation</strong> techniques, e.g.:</p> <ul> <li>SGD-based SVM/Logistic Regression with: <ul> <li><a href="http://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html" rel="nofollow...
1
2016-06-27T19:16:15Z
[ "python", "machine-learning", "scikit-learn" ]
Matplotlib graphic image to base64
38,061,267
<p><strong>Problem :</strong> Need to transform a graphic image of matplotlib to a base64 image</p> <p><strong>Current Solution :</strong> Save the matplot image in a cache folder and read it with read() method and then convert to base64</p> <p><strong>New Problem : Annoyance :</strong> Need a workaround so I dont ne...
0
2016-06-27T18:56:24Z
38,061,400
<pre><code>import cStringIO my_stringIObytes = cStringIO.StringIO() plt.savefig(my_stringIObytes, format='jpg') my_stringIObytes.seek(0) my_base64_jpgData = base64.b64encode(my_stringIObytes.read()) </code></pre> <p>I think at least ... based on the documentation <a href="http://matplotlib.org/api/pyplot_api.html#matp...
1
2016-06-27T19:04:49Z
[ "python", "python-2.7", "matplotlib" ]
Workflow for making edits to Python package?
38,061,320
<p>I'd like to add a few features to a package (<a href="https://github.com/scikit-learn-contrib/lightning" rel="nofollow">https://github.com/scikit-learn-contrib/lightning</a>), but am unsure of the proper approach, especially since much of the source is in Cython.</p> <p>From other posts, I've gathered that for maki...
0
2016-06-27T18:59:28Z
38,061,434
<p>Many possible answers to this one. My preference is to clone the source into a directory, create a symbolic link to the python module folder, and include the symbolic link in my PYTHONPATH environment variable.</p>
0
2016-06-27T19:07:16Z
[ "python" ]
ImportError: No module named 'pandas'
38,061,426
<p>I am trying to learn pandas and I haven't been able to import it into my code.</p> <p>I have looked at other answers on this site and none of them have worked. </p> <p>I just installed anaconda and installed everything through conda.</p> <p>Here is a sample script that I am trying to run. </p> <pre><code>import ...
0
2016-06-27T19:06:46Z
38,061,554
<p><a href="https://packaging.python.org/en/latest/installing/" rel="nofollow">Here</a> is the basic documentation on how to instal python packages.</p> <p>For OS and Linux users, the following command ought to work:</p> <pre><code>pip install pandas </code></pre>
2
2016-06-27T19:16:20Z
[ "python", "pandas" ]
ImportError: No module named 'pandas'
38,061,426
<p>I am trying to learn pandas and I haven't been able to import it into my code.</p> <p>I have looked at other answers on this site and none of them have worked. </p> <p>I just installed anaconda and installed everything through conda.</p> <p>Here is a sample script that I am trying to run. </p> <pre><code>import ...
0
2016-06-27T19:06:46Z
38,061,570
<p>I wanted to add this as a comment but Im not special enough yet in the eyes of stackoverflow.</p> <p>Some modules need to be separately installed into your libraries folder of your python directory.Using pip (<a href="https://pip.pypa.io/en/stable/" rel="nofollow">https://pip.pypa.io/en/stable/</a>) is helpful for ...
0
2016-06-27T19:17:26Z
[ "python", "pandas" ]
ImportError: No module named 'pandas'
38,061,426
<p>I am trying to learn pandas and I haven't been able to import it into my code.</p> <p>I have looked at other answers on this site and none of them have worked. </p> <p>I just installed anaconda and installed everything through conda.</p> <p>Here is a sample script that I am trying to run. </p> <pre><code>import ...
0
2016-06-27T19:06:46Z
39,145,104
<p>I had the same problem for a long time. Today I tried a whole day and it finally worked. Below is the steps how I did it. I don't have theory for why the problem exist and how it is solved. I just know the following steps helped me get <code>pandas</code> going. </p> <p>A. <a href="http://conda.pydata.org/miniconda...
0
2016-08-25T12:17:12Z
[ "python", "pandas" ]
SymPy lambdify with dot()
38,061,465
<p>Take an undefined function that happens to be named <code>dot</code>, and make it part of <code>lambdify</code>:</p> <pre><code>import numpy import sympy class dot(sympy.Function): pass x = sympy.Symbol('x') a = sympy.Matrix([1, 0, 0]) f = sympy.lambdify(x, dot(a.T, x)) x = numpy.array([3, 2, 1]) print(f...
2
2016-06-27T19:10:23Z
38,062,362
<p>I'm not a <code>sympy</code> user however quoting the documentation for <a href="http://docs.sympy.org/latest/modules/utilities/lambdify.html?highlight=lambdify#sympy.utilities.lambdify.lambdify" rel="nofollow"><code>lambdify</code></a> it says:</p> <blockquote> <p>If not specified differently by the user, <stron...
2
2016-06-27T20:06:18Z
[ "python", "matrix", "sympy" ]
Error pip installing getch Python3.5
38,061,518
<p>I'm running Fedora 24. I want to import the getch module on Python 3.5.2 (which I think is already installed, however when I run python -V, it says Python 2.7.11)</p> <p>When I enter pip install getch I get this:</p> <pre><code>Collecting getch Downloading getch-1.0.tar.gz Installing collected packages: getch ...
1
2016-06-27T19:13:53Z
38,078,387
<p>Ok, so this is how I fixed it:</p> <pre><code>sudo dnf install python3-devel </code></pre> <p>Instead of:</p> <pre><code>sudo dnf install python-devel </code></pre> <p>After hours of research, now it seems so silly.</p> <p>Thank you</p>
1
2016-06-28T14:03:27Z
[ "python", "pip", "getch" ]
Bisect keep indexes of inserted items
38,061,553
<p>I am using the bisect module to keep a list sorted while inserting numbers. Lets say I have am going to insert three numbers <code>9, 2, 5</code> in this order. The last state of this list would be obviously <code>[2, 5, 9]</code>, however, is there any chance that I can find the index list that numbers are inserted...
0
2016-06-27T19:16:19Z
38,063,200
<p><code>insort</code> has no idea in what order the items were inserted. You'll have to add that logic yourself. One way to do so could be to insert 2-tuples consisting of the value and the index:</p> <pre><code>bisect.insort(lst, (9, 0)) bisect.insort(lst, (2, 1)) bisect.insort(lst, (5, 2)) </code></pre> <p>You wou...
0
2016-06-27T21:02:50Z
[ "python", "sorting", "bisection" ]
How to skip a line of (raw) input, Python 3
38,061,578
<p>I am completing the following <a href="https://www.hackerrank.com/challenges/sets" rel="nofollow">HackerRank challenge</a>. I am fed the following input: </p> <pre><code>4 2 4 5 9 4 2 4 11 12 </code></pre> <p>Let's say though I just want the 2nd and 4th lines of input (and assume all input will look like this). At...
0
2016-06-27T19:17:47Z
38,061,622
<p>Loop over the <a href="https://docs.python.org/3/library/sys.html#sys.stdin" rel="nofollow"><code>sys.stdin</code> object</a>; it is a regular file and supports iteration. You can use an <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice()</code> object<...
1
2016-06-27T19:19:45Z
[ "python", "python-3.x" ]
Getting list value's length in dictionary
38,061,620
<p>Like let's say my list is </p> <pre><code>["Hello","My","Name","is","python"] </code></pre> <p>Can we make this like </p> <pre><code>{"Hello":5,"My":2,"Name":4,"is":2,"python":6} </code></pre> <p>I'm trying to make a programming challenge and finding the words. But to faster the procces if it finds all lengths s...
1
2016-06-27T19:19:34Z
38,061,657
<p>Use a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dictionary comprehension</a> along with <a href="https://docs.python.org/2/library/functions.html#len" rel="nofollow"><code>len</code></a> function. See <a href="http://stackoverflow.com/questions/14507591/python-dictionary-comprehension">this<...
6
2016-06-27T19:21:22Z
[ "python", "list", "dictionary" ]
Python ImportLib 'No Module Named'
38,061,639
<p>I'm trying to use a variable as a module to import from in Python.</p> <p>Using ImportLib I have been successfully able to find the test...</p> <pre><code>sys.path.insert(0, sys.path[0] + '\\tests') tool_name = selected_tool.split(".")[0] selected_module = importlib.import_module("script1") print(selected_module) ...
0
2016-06-27T19:20:15Z
38,061,857
<p>Import statements are not sensitive to variables! Their content are treated as literals</p> <p>An example:</p> <pre><code>urllib = "foo" from urllib import parse # loads "urllib.parse", not "foo.parse" print(parse) </code></pre> <p>Note that <code>from my_module import my_func</code> will simply bind <code>my_m...
1
2016-06-27T19:33:48Z
[ "python", "python-importlib" ]
Removing blank spaces from a CSV file without creating a new file
38,061,642
<p>I have blank spaces in a csv sheet that I want to get rid of it. </p> <p>After searching for hours I realized that this is the code for it:</p> <pre><code>input = open('file.txt', 'wb') output = open('new_file.txt', 'wb') writer = csv.writer(output) for row in csv.reader(input): if any(field.strip() for field ...
2
2016-06-27T19:20:22Z
38,061,790
<p>You can first extract the valid rows and overwrite the file afterwards, provided your file is not too big and thus the rows can fit in the memory entirely</p> <pre><code>with open('file.txt', 'rb') as inp: valid_rows = [row for row in csv.reader(inp) if any(field.strip() for field in row)] with open('file.txt'...
2
2016-06-27T19:29:50Z
[ "python", "python-2.7", "csv" ]
How to place a jpeg into tkinter (python3.4)?
38,061,672
<p>I am trying to make a tkinter code that can generate a window with an image on it. This is the area that keeps giving me an error:</p> <pre><code>window=tk.Tk() window.geometry('1100x900') window.title('Hello World') lab1= tk.Label(window, text='Input the desired delay time') btn=tk.Button(window, text='Go to new w...
1
2016-06-27T19:22:11Z
38,061,927
<p>You need to add 2 lines as following (I commented the lines in question)</p> <pre><code>imgset=Image.open(imgpath) # Convert imgset to a Tkinter-compatible image object photo = ImageTk.PhotoImage(imgset) img = tk.Label(window, image=photo) # Keep a reference to the image img.image = photo img.pack() </code></pre>...
0
2016-06-27T19:38:20Z
[ "python", "python-3.x", "tkinter" ]
iteraing and comparing values in txt file python
38,061,691
<p>I have multiple files in a folder containing two columns of information: wavenumber and intensity: </p> <pre><code>500.21506 0.01093 500.45613 0.02135 500.69720 0.01043 500.93826 0.01997 501.17933 0.01335 501.42040 0.01579 501.66147 0.01749 501.90253 0.01256 502.14360 0.02054 502.38467 0.01011 502.62574 0.02108 502...
-1
2016-06-27T19:23:20Z
38,061,761
<p>This will work for any text file. You could read more about reading in data <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">here</a></p> <pre><code>import glob x = [] for filename in glob.iglob('/Path_to_File/*.txt'): x.append(filename) wave_list = [] for...
0
2016-06-27T19:28:21Z
[ "python", "loops", "io", "comparison", "iteration" ]
JSON to text file using Python
38,061,742
<p>I have searched for a solution regarding this issue and I have not found one that I can understand. I am new to Python and need basic help understanding why I get the error message: TypeError: is not JSON serializable.</p> <pre><code>import requests import json r = requests.get("http://api.bls.gov/publicAPI/v2/ti...
1
2016-06-27T19:26:53Z
38,061,824
<p>You don't need to convert it to/from json. Just keep it as text.</p> <pre><code>import requests r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005") with open("C:\Users\mhoward2\Documents\Python Scripts\Output.txt", "w") as outfile: outfile.write(r.text) </code></pre>
2
2016-06-27T19:32:02Z
[ "python", "json", "python-requests" ]
JSON to text file using Python
38,061,742
<p>I have searched for a solution regarding this issue and I have not found one that I can understand. I am new to Python and need basic help understanding why I get the error message: TypeError: is not JSON serializable.</p> <pre><code>import requests import json r = requests.get("http://api.bls.gov/publicAPI/v2/ti...
1
2016-06-27T19:26:53Z
38,061,832
<p>You need to call <em>.json()</em> and <code>dump</code> or just write the content:</p> <pre><code>r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005") with open("C:\Users\mhoward2\Documents\Python Scripts\Output.txt", "w") as outfile: outfile.write(r.content) </code></pre> ...
1
2016-06-27T19:32:43Z
[ "python", "json", "python-requests" ]
Using multiple ranges with the for-loop in PYTHON
38,061,767
<p>I don't understand of using the multiple ranges in the for-loop as follows.</p> <pre><code>for n in range(1,21) + range(30,100,10): # do something </code></pre> <p>I googled but still not find out. Any help would be appreciated. </p>
-3
2016-06-27T19:28:36Z
38,061,874
<p>Each range expression returns a list: <code>range(1,21)</code> returns <code>[1,2,...,20]</code>, and <code>range(30,100,10)</code> returns <code>[30,40,...,90]</code>. The <code>+</code> operator concatenates the two lists, so <code>range(1,21) + range(30,100,10)</code> evaluates to <code>[1,2,...,20,30,40,...,90]<...
2
2016-06-27T19:34:53Z
[ "python", "range" ]
Using multiple ranges with the for-loop in PYTHON
38,061,767
<p>I don't understand of using the multiple ranges in the for-loop as follows.</p> <pre><code>for n in range(1,21) + range(30,100,10): # do something </code></pre> <p>I googled but still not find out. Any help would be appreciated. </p>
-3
2016-06-27T19:28:36Z
38,061,884
<p>In <em>Python 2.7</em>, you can add <code>range</code>s because the result of calling <code>range(something)</code> <a href="https://docs.python.org/2.7/library/functions.html?highlight=range#range" rel="nofollow">is a list</a>, and lists <a href="https://docs.python.org/2.7/library/stdtypes.html#typesseq" rel="nofo...
3
2016-06-27T19:35:27Z
[ "python", "range" ]
Using multiple ranges with the for-loop in PYTHON
38,061,767
<p>I don't understand of using the multiple ranges in the for-loop as follows.</p> <pre><code>for n in range(1,21) + range(30,100,10): # do something </code></pre> <p>I googled but still not find out. Any help would be appreciated. </p>
-3
2016-06-27T19:28:36Z
38,061,910
<p>with three arguments, range() is as follows:</p> <p>range(start, stop, step)</p>
-1
2016-06-27T19:37:12Z
[ "python", "range" ]
Use Python API to conditionally update ElasticSearch document
38,061,772
<p>I am trying to update a document (by appending elements to a list), or create if it does not exists. For example, I want the document with <code>id == Donald_Duck</code> to add the elements of the list <code>suggestions</code>, if not present already.</p> <pre><code>name = 'Donald_Duck' suggestions = ['Donald', 'Do...
0
2016-06-27T19:29:11Z
38,062,106
<p>You have some typo in your body:</p> <pre><code>body = { "script": "ctx._source.text += new_suggestions", "params": { "new_suggestions" : suggestions}, "upsert": { "text": suggestions } } </code></pre> <p>Plus, are you sure you have enabled the scripting for updates. Please read <a href="ht...
1
2016-06-27T19:48:34Z
[ "python", "elasticsearch", "mappings" ]
Login Django not working
38,061,799
<p>I just created a login with Django, but it doesn't want to work. The script should redirect to start.html if the user login correctly. But Django just reload the page writing the username and the passwort in the url.</p> <p>view.py</p> <pre><code>from django.shortcuts import render, get_object_or_404 from django.h...
0
2016-06-27T19:30:06Z
38,061,826
<p>Change <code>&lt;form type="post"&gt;</code> to <code>&lt;form method="post"&gt;</code> in index.html.</p>
1
2016-06-27T19:32:21Z
[ "python", "django", "django-login" ]
Login Django not working
38,061,799
<p>I just created a login with Django, but it doesn't want to work. The script should redirect to start.html if the user login correctly. But Django just reload the page writing the username and the passwort in the url.</p> <p>view.py</p> <pre><code>from django.shortcuts import render, get_object_or_404 from django.h...
0
2016-06-27T19:30:06Z
38,061,846
<p>Class-based views don't recognise a "user_login" method. It should be called just "post".</p>
0
2016-06-27T19:33:12Z
[ "python", "django", "django-login" ]
Python sampling a dataframe
38,061,876
<p>I have an existing datafram 'products': </p> <pre> Nr Product Verkoopprijs 0 1 Product A 1111 1 2 Product B 1320 2 3 Product C 727 3 4 Product D 783 4 5 Product E 1431 5 6 Product F 421 6 7 Product G 611 7 8 P...
1
2016-06-27T19:34:56Z
38,062,416
<p>This answer belongs to @user1669710, if they choose to post an answer, select it as such.</p> <p>Make sure to use <code>replace=True</code> because you're asking to take more random draws than there are things to draw from.</p> <pre><code>df.sample(10000, replace=True) </code></pre> <p>For display purposes.</p> ...
1
2016-06-27T20:10:44Z
[ "python", "numpy", "pandas" ]
How do I read a file in python and numpy and create an output file without having to manually change the name of the input file in the code?
38,062,147
<p>I want to read a text file which has an arbitrary amount of columns with numbers. </p> <p>I want to manipulate the data and then create an output file. </p> <p>My code is :</p> <pre><code>import numpy as np array=np.loadtxt('filename.txt') #multiply first column by 2 array[:,0]=array[:,0]*2 savetxt('filename...
-2
2016-06-27T19:51:25Z
38,062,221
<p>Use the package glob, it will take all the files in a directory with a certain type of extension and allow you to use their data. Essentially you will just have a folder you drop your text files into before running the program. </p> <pre><code>import glob x = [] for filename in glob.iglob('/Path_to_Directory/*.txt'...
0
2016-06-27T19:56:37Z
[ "python", "arrays", "numpy" ]
How do I read a file in python and numpy and create an output file without having to manually change the name of the input file in the code?
38,062,147
<p>I want to read a text file which has an arbitrary amount of columns with numbers. </p> <p>I want to manipulate the data and then create an output file. </p> <p>My code is :</p> <pre><code>import numpy as np array=np.loadtxt('filename.txt') #multiply first column by 2 array[:,0]=array[:,0]*2 savetxt('filename...
-2
2016-06-27T19:51:25Z
38,062,225
<pre><code>import sys import numpy as np fname1 = sys.argv[1] fname2 = sys.argv[2] arr = np.loadtxt(fname1) np.savetxt(fname2, arr * 2) </code></pre> <p>then run your code:</p> <pre><code>python myscript.py inputfile.txt outputfile.txt </code></pre>
0
2016-06-27T19:56:55Z
[ "python", "arrays", "numpy" ]
How do I read a file in python and numpy and create an output file without having to manually change the name of the input file in the code?
38,062,147
<p>I want to read a text file which has an arbitrary amount of columns with numbers. </p> <p>I want to manipulate the data and then create an output file. </p> <p>My code is :</p> <pre><code>import numpy as np array=np.loadtxt('filename.txt') #multiply first column by 2 array[:,0]=array[:,0]*2 savetxt('filename...
-2
2016-06-27T19:51:25Z
38,062,366
<p>Just assign the filename to a variable, and use that in the function calls.</p> <pre><code>import numpy as np filename = 'filename.txt' # or get it from input data=np.loadtxt(filename) data[:,0]=data[:,0]*2 np.savetxt(filename, data) # reuse the filename variable (string) </code></pre>
0
2016-06-27T20:06:39Z
[ "python", "arrays", "numpy" ]
Accessing multidimensional matrices in python
38,062,399
<pre><code>sumc=0 t = int(input()) while t : x = input().split() n = int(x[0]) k = int(x[1]) e = int(x[2]) m = int(x[3]) suma = [0]*(n-1) Matrix = [] for i in range(n-1): Matrix.append([]) for j in range(e): p = int(input()) Matrix[i].append(p) ...
0
2016-06-27T20:09:01Z
38,062,424
<p>Your loop:</p> <pre><code>for i in range(n-1): Matrix.append([]) for j in range(e): p = int(input()) Matrix[i].append(p) </code></pre> <p>adds <code>n-1</code> elements to <code>Matrix</code>. Since python is 0 indexed, this means that the highest index in <code>Matrix</code> is <code>n-2<...
1
2016-06-27T20:11:07Z
[ "python", "arrays", "multidimensional-array" ]
Why doesn't fit_transform work in this sklearn Pipeline example?
38,062,403
<p>I an new to sklearn Pipeline and following a sample code. I saw in other examples that we can do <code>pipeline.fit_transform(train_X)</code>, so I tried the same thing on the pipeline here <code>pipeline.fit_transform(X)</code>, but it gave me an error </p> <p>" return self.fit(X, **fit_params).transform(X)</p>...
0
2016-06-27T20:09:14Z
38,067,789
<p>You get an error in the above example because you also need to pass the labels to your pipeline. You should be calling <code>pipeline.fit_transform(X,y)</code>. The last step in your <code>pipeline</code> is a classifier, <code>SVC</code> and the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm....
0
2016-06-28T05:33:13Z
[ "python", "scikit-learn" ]
Efficient usage of tensors in python-numpy
38,062,458
<p>I require an <code>m</code>-dimensional <code>np.ndarray</code> lattice structure, denoted by <code>arr</code>, with the following properties where <code>m</code> and <code>n</code> are constants (e.g. <code>m=3</code>,<code>n=50</code>):</p> <ul> <li><code>arr.shape == (n, n, n, ..., n)</code> where <code>n in ran...
0
2016-06-27T20:13:26Z
38,062,599
<p>NumPy always stores the actual <a href="http://docs.scipy.org/doc/numpy/reference/internals.html#internal-organization-of-numpy-arrays" rel="nofollow">data in a 1D array</a>. The multi-dimensionality comes from the <code>ndarray</code> object. So no need to overload <code>__getitem__()</code> and <code>__setitem__()...
0
2016-06-27T20:24:18Z
[ "python", "arrays", "memory", "optimization", "data-structures" ]
The exe file generated by PyInstaller does not work
38,062,579
<p>PyInstaller previously worked very well. However, after installing Jupyter, the new generated exe files by PyInstaller did not work,for instance, warning no module named Tkinter. If uninstall Jupyter and generate the exe file by PyInstaller again, the new exe file works well.</p> <p>Is there any conflict between t...
0
2016-06-27T20:23:04Z
38,467,283
<p>Solved by changing the modules' order.</p> <p>Old order: from Tkinter import * import tkFileDialog import matplotlib.pyplot as plt import numpy as np import PIL.Image import pylab from matplotlib.colors import LightSource, Normalize,LinearSegmentedColormap</p> <p>New order: import matplotlib.pyplot as plt import n...
0
2016-07-19T19:49:08Z
[ "python", "pyinstaller" ]
Subprocess returning No such file or directory for file that exists
38,062,607
<p>I have a snippet of code that is attempting to submit an audio file for transcription to the bing speech api using SpeechRecognition (available in PyPi):</p> <pre><code>filename = 'part' + str(entry['srcID']) + '.flac' with open(filename, 'w') as filehandle: harkclient.getSeparatedAudio(handle=filehandle, srcID...
1
2016-06-27T20:25:05Z
38,067,963
<p>Posting the answer for this one as per the full code snippet: </p> <p><a href="https://github.com/Uberi/speech_recognition/blob/master/speech_recognition/__init__.py#L195" rel="nofollow">https://github.com/Uberi/speech_recognition/blob/master/speech_recognition/<strong>init</strong>.py#L195</a></p> <p>the flac enc...
1
2016-06-28T05:47:20Z
[ "python", "file", "subprocess", "tornado" ]
Python - Optimizing Memory Usage in Calculations
38,062,643
<p>I have a log file with about 50,000+ lines. Each line contains information pertaining to a worker and a job ID that a worker has "worked" on in a single day. For example,</p> <pre><code> 12:36:04.357 WorkerID: ABCD has worked on JobID: EFGH </code></pre> <p>Jobs do not disappear after being "worked on" and a worke...
2
2016-06-27T20:27:02Z
38,062,835
<p>You could avoid adding <code>workID</code> in the dict of lists. Just create a dict of ints set to 0 and +=1 each time, since the key is already <code>workID</code>. That would save memory. Same thing for the dict of dict of set or something. Just forget the set as there will never be more than 1 value in that. Just...
0
2016-06-27T20:39:02Z
[ "python", "python-3.x", "memory" ]
errors with python script using GRASS GIS API
38,062,678
<p>i have standalone install GRASS from official web site, and i using python 2.7 32b and windows 10. i trying to works with python api from GRASS GIS 7.0.4. but i have import errors.</p> <p>some imports work i can import in the python ide and some imports not works and i cant to using.</p> <p>first i read this post...
1
2016-06-27T20:29:46Z
38,083,027
<p>The <code>import grass.scripts</code> is a typo. You need to use <code>import grass.script</code> because that's the name of the module.</p> <p>The import <code>from pygrass.modules import Module</code> causes <code>No module named pygrass.modules</code> because there is no such module. The name for the module is <...
0
2016-06-28T17:50:16Z
[ "python", "python-2.7", "api", "grass" ]
In Django, when I run migrate I get the error : accounts_userinfo.user_id may not be NULL
38,062,709
<p>Whenever I run python manage.py migrate accounts I get the error code : django.db.utils.IntegrityError: accounts_userinfo.user_id may not be NULL</p> <p>I believe this is caused by me linking a model with more user information, with the django user model. This is my models.py</p> <pre><code>class UserInfo(models.M...
1
2016-06-27T20:31:46Z
38,062,737
<p>Foreign keys cannot be null by default. You either need to make it nullable:</p> <pre><code>class UserInfo(models.Model): c_name = models.CharField(max_length=120) c_site = models.CharField(max_length=120) link = models.ForeignKey(User, null = True) </code></pre> <p>Or set a default:</p> <pre><code>cl...
2
2016-06-27T20:33:31Z
[ "python", "django", "django-models", "django-forms", "web-frameworks" ]
parse txt file to 2 csv files
38,062,733
<p>Hi I already have working code for parsing <code>*.txt</code> with such pattern:</p> <pre><code>... 0.00001 0.00280 0.00022 ... </code></pre> <p>into <code>*.csv</code> file</p> <p>I do it with this:</p> <pre><code>in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\n') f = open(csv_file, 'wb') out_csv = csv...
1
2016-06-27T20:33:18Z
38,062,927
<p>A tested example:</p> <pre><code>import csv, os txt_file = '/path/to/in.txt' in_txt = csv.reader(open(txt_file, 'rb'), delimiter='@') out_file1 = '/path/to/out1.txt' out_file2 = '/path/to/out2.txt' with open(out_file1, 'wb') as fou1, open(out_file2, 'wb') as fou2: for one, two in in_txt: fou1.write(one...
1
2016-06-27T20:45:27Z
[ "python", "csv", "parsing", "pandas" ]
parse txt file to 2 csv files
38,062,733
<p>Hi I already have working code for parsing <code>*.txt</code> with such pattern:</p> <pre><code>... 0.00001 0.00280 0.00022 ... </code></pre> <p>into <code>*.csv</code> file</p> <p>I do it with this:</p> <pre><code>in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\n') f = open(csv_file, 'wb') out_csv = csv...
1
2016-06-27T20:33:18Z
38,063,357
<p>here is a <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">pandas</a> approach which will work for any number of columns (just in case...):</p> <pre><code>import pandas as pd in_fn = '/path/to/in.csv' out_fn_pattern = '/path/to/out_{}.csv' # parse CSV to DataFrame df = pd.read_csv(i...
1
2016-06-27T21:13:50Z
[ "python", "csv", "parsing", "pandas" ]
Why won't my character jump in pygame/python
38,062,747
<p>This is my first Pygame game that I'm making.</p> <p>I am planning on making a 2 player fighting game with basic squares/blocks.</p> <p>I am now trying to implement jumping into the first character and in my eyes all the logic looks correct and I have got no errors at the moment. However, when I try pressing <code...
0
2016-06-27T20:34:11Z
38,062,980
<p>When you press w to jump, the game will change the value of <code>y_change</code> to <code>-5</code> as intended. When the event queue has been processed, it goes on to this block:</p> <pre><code>if y &lt;= 480: onGround = False else: onGround = True if onGround == False: y_change = 5 if onGround ==...
3
2016-06-27T20:49:08Z
[ "python", "pygame" ]
Why is there an unexpected keyword argument error for this Django API call?
38,062,784
<p>I am following the Django-Restful tutorial <a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses/" rel="nofollow">here</a>, and I have the following code written</p> <p>in views.py:</p> <pre><code>from snippets.models import Snippet from snipp...
2
2016-06-27T20:36:17Z
38,080,703
<p>The issue was that I had duplicate functions in the <code>views.py</code> file with different decorators that were near the bottom. Removing them solved the issue.</p>
0
2016-06-28T15:43:51Z
[ "python", "django", "django-rest-framework", "typeerror", "keyword-argument" ]
Treat regular expression between dashes
38,062,800
<p>Could you help me to use "sub" to change the numbers of these expressions:</p> <blockquote> <p>&amp;AFL-03-123456</p> <p>&amp;AFL-01-12345</p> <p>&amp;AFL-02-123</p> <p>context: samsung-j7-duos-dual-chip-desbloqueado-oi-android-5.1-tela-5.5-16gb-wi-fi-4g-camera-13mp-branco&amp;AFL-03-171644black</p...
-3
2016-06-27T20:37:03Z
38,063,350
<p><code>(?&lt;=&amp;AFL-\d\d-)(\d+)</code> Will match the digits you want to replace, using a positive lookbehind, which ensures <code>&amp;AFL-XX-</code> is there, but does not match them.</p> <p>Combine this with <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">re.sub()</a></p> <p><code>re...
0
2016-06-27T21:13:32Z
[ "python", "regex", "hyphen" ]
how can two methods in same class can access it members in python
38,062,865
<pre><code>class boy: """Details""" def __init___(self): print("Details") def name(self,x,y,z): a=x.title() + ' ' b=y.title() + ' ' c=z.title() nam = a + b + c print(nam) def age(self,nu): f = int(num) if f&gt;18: return 1 else: print("\nSorry you must be at leas...
-1
2016-06-27T20:41:36Z
38,062,992
<p>Add class members into your <code>__init__</code>, like this:</p> <pre><code>def __init___(self,x, y, z): self.x = x self.y = y self.z = z print("Details") </code></pre>
0
2016-06-27T20:50:00Z
[ "python" ]
how can two methods in same class can access it members in python
38,062,865
<pre><code>class boy: """Details""" def __init___(self): print("Details") def name(self,x,y,z): a=x.title() + ' ' b=y.title() + ' ' c=z.title() nam = a + b + c print(nam) def age(self,nu): f = int(num) if f&gt;18: return 1 else: print("\nSorry you must be at leas...
-1
2016-06-27T20:41:36Z
38,063,070
<pre><code>class boy(): def __init___(self, num): self.age = int(num) num = raw_input("Enter the age :") inp = boy(num) if inp.age &lt; 18: .... </code></pre> <p>Your class should work like this. The way you wrote it, <code>inp</code> has no age attribute to evaluate. But as pointed out in the com...
0
2016-06-27T20:54:52Z
[ "python" ]
How can you change duplicates of tuples in a list in python 2.7?
38,062,941
<p>If you have 4 lists and zip them to a list in Python you get list with 4 tuples.For ex:</p> <pre><code>a=['0','0','2','3','7','6'] b=['4','4','4','5','6','7'] c=[2,2,3,4,5,5] m=['m1','m2','m3','m4','m5','m6'] g=(zip(a,b,c,m)) </code></pre> <p>Where <code>g =</code>[<code>('0', '4', 2, 'm1'), ('0', '4', 2, 'm2'), (...
0
2016-06-27T20:46:30Z
38,063,310
<p>Iterate over the list and use <code>enumerate</code> to keep track of the indice, when you find one with duplicates change the value at that indice:</p> <pre><code>for i, tup in enumerate(g): if str(tup[2]) in tup[:2]: g[i][2]+=0.01 </code></pre>
0
2016-06-27T21:11:19Z
[ "python", "list", "python-2.7" ]
Find size of each compiled module in Python virtualenv?
38,063,014
<p>I have inherited a bloated Django project that is deployed through Heroku and which includes a lot of large libraries (including numpy, scipy, etc). It appears the previous developer froze his whole virtual environment and I am doing my best to prune dependencies that aren't used. </p> <p>After the need for install...
0
2016-06-27T20:51:45Z
38,063,975
<p>Assuming that you have a virtual environment set up and all your dependencies are in <code>site-packages</code>, you can get close by simply doing:</p> <pre><code>du -sh /path/to/site-packages/* | sort -hr </code></pre> <p>Here's the output on my machine:</p> <pre><code>29M .../site-packages/django 7.0M .....
2
2016-06-27T22:07:21Z
[ "python", "django", "heroku", "virtualenv" ]
Python 2.7 subprocess returns nothing, exact command works in console
38,063,035
<p>I'm trying to execute the <code>strings</code> command inside of a Python script. I had it working for awhile, but mysteriously, it doesn't return anything when I use <code>subprocess.Popen</code> anymore.</p> <p>Called from terminal</p> <pre><code>strings /path/to/.bashrc # You may uncomment the following lines i...
0
2016-06-27T20:52:33Z
38,063,297
<p>From the <a href="https://docs.python.org/2/library/subprocess.html#popen-constructor" rel="nofollow">subprocess documentation</a>:</p> <blockquote> <p>The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a s...
2
2016-06-27T21:10:18Z
[ "python", "python-2.7", "console", "subprocess" ]
How to use raw_input in a socket
38,063,042
<p>Just before I say anything, if you are confused about the title it means to say I used this bit of code: <code>cmd, addr = sock.accept()</code> how could I use that code for the clients to see the raw_input, Here's my code:</p> <pre><code>from socket import * sock = socket(AF_INET, SOCK_STREAM) HOST = "0.0.0.0" PO...
1
2016-06-27T20:52:52Z
38,063,261
<p>[Converting my comment to an answer]</p> <p>There are two applications here (possibly on two different machines). One application opens a server socket and listens for the connection. Upon a connection from another process (client), it sends the string <code>Welcome to server ...</code>.</p> <p>The second applicat...
0
2016-06-27T21:08:04Z
[ "python", "sockets", "input", "tcp" ]
Pygame/Pip installation issues
38,063,079
<p>Recently I've been interested in pygame, and installed pygame-1.9.2a0-cp34-none-win32 on my 64-bit ASUS windows computer.</p> <p>I saved it to C:/python34/Scripts.</p> <p>From that directory, in cmd, I ran the line "pip install pygame-1.9.2a0-cp34-none-win32"</p> <p>and got this error:<br> Microsoft Windows [Vers...
0
2016-06-27T20:55:27Z
38,063,516
<p>Where did you download the module from? If its not precompiled pip will not be able to install without the correct version of Microsoft Visual Studio install, and most likely a bunch of other prerequisites.</p> <p>My guess is that you downloaded a compiled version from a site such as this well known one <a href="h...
1
2016-06-27T21:26:41Z
[ "python" ]
A general solution for dealing with abbreviations
38,063,129
<h2>Problem?</h2> <p>Given the input sentence:<br> <code>Hello, Mr. Anderson.</code> </p> <p>The default sentence tokenizer (punkt, and the nltk sample pickle), turns this into:<br> Sentence 1: <code>Hello, Mr</code><br> Sentence 2: <code>Anderson</code> </p> <p>When it should really remain as it was. </p> <h2>Wh...
2
2016-06-27T20:58:56Z
38,063,704
<p>You can take a reactionary, exclusionary tack: anything that is at least two letters and not a legal word, followed by a period, <em>must</em> be an abbreviation. Would your text corpus allow this? The drawbacks are typos, other misspellings, gratuitous use of SMS, slang, or other words not "officially" recognized...
1
2016-06-27T21:40:23Z
[ "python", "nltk" ]
Django OpenStack Horizon - Admin templates are not rendering properly
38,063,133
<p>Upon creating my own panel in OpenStack Horizon I am unable to properly view the admin panels (Overview panel: Pie Charts not appearing, Instances: Unable to generate Instance but can view possible instances to choose from). This occurs when my new panel is 'enabled' within the enabled folder. The panel that Ive add...
1
2016-06-27T20:59:11Z
38,110,637
<p>I had stored static variables in settings.py to access in a custom dashboard. As a result the Horizon dashboards were broken. The static variables should be store elsewhere.</p>
0
2016-06-29T21:50:11Z
[ "python", "django", "openstack", "openstack-horizon", "horizon" ]
return value from a event-binded function
38,063,402
<p>I'm trying to write a function which can wait for me to press anykey and then return my mouse position. I'm confused about how to get my xy value from key(event) function and return them with get_mouse_pixel().</p> <pre><code>from Tkinter import * import win32api def get_mouse_pixel(): x,y = 0,0 root = Tk...
0
2016-06-27T21:16:46Z
38,063,814
<p>Since you're using inner functions and you give them values, you have to tell your inner function (<code>key()</code>) that the <code>x</code> and <code>y</code> you're setting aren't new variables, they're the ones in the outer scope. You can do that with the <code>nonlocal</code> keyword in python3 (eg <code>nonlo...
1
2016-06-27T21:51:22Z
[ "python", "events", "tkinter" ]
Computer-vision: How to remove debris when counting cells?
38,063,419
<p>I am attempting to use python to count some cells in an image. I am more or less following the tutorial <a href="http://pythonvision.org/basic-tutorial/" rel="nofollow">here</a>. After a thresholding step, I find the regional maximas and count them. This works very well for counting nuclei, however there are some f...
1
2016-06-27T21:18:02Z
38,069,174
<p>I think you have to start at the original image, to identify false positives. Mark the locations of dead cells and other false positives, and record the geometric properties of the blobs they produce. If the properties like size can show a clear difference, then you can distinguish them easily.</p> <p>Another optio...
0
2016-06-28T06:59:54Z
[ "python", "computer-vision", "mahotas" ]
How to extract json attribute in Xpath?
38,063,420
<p>I want to extract json data in the html attribute. This is my xpah: I got null so far. The link is <a href="https://wefunder.com/beta.bionics" rel="nofollow">https://wefunder.com/beta.bionics</a></p> <pre><code>response.xpath('//*[@id="sb-site"]/div/div[4]/*[name()="wf:loader"]/@company-json').extract() </code></pr...
-1
2016-06-27T21:18:05Z
38,063,555
<p>You don't have to specify the tag name here at all - just get an <em>element having the <code>company-json</code> attribute</em>. Demo using Scrapy (I recognized the syntax):</p> <pre><code>$ scrapy shell https://wefunder.com/beta.bionics &gt;&gt;&gt; response.xpath("//*[@company-json]/@company-json").extract_first...
0
2016-06-27T21:29:16Z
[ "python", "xpath", "web-scraping", "scrapy" ]
Return lists using csv reader
38,063,455
<p>this is my code. it works fine if I print the variables but if i return them and try to print them somewhere else only the last element gets printed.</p> <pre><code>def train_data(fname): #load csv training files with open (fname) as train: reader = csv.DictReader(train, delimiter='\t') for...
0
2016-06-27T21:20:38Z
38,063,478
<p>You're only returning one thing. Try putting things in a list and returning the list:</p> <pre><code>def train_data(fname): peptides = [] alleles = [] scores = [] #load csv training files with open (fname) as train: reader = csv.DictReader(train, delimiter='\t') for row in reade...
0
2016-06-27T21:23:04Z
[ "python", "python-3.x", "csv" ]
Return lists using csv reader
38,063,455
<p>this is my code. it works fine if I print the variables but if i return them and try to print them somewhere else only the last element gets printed.</p> <pre><code>def train_data(fname): #load csv training files with open (fname) as train: reader = csv.DictReader(train, delimiter='\t') for...
0
2016-06-27T21:20:38Z
38,063,494
<p>You have to make <strong>peptide, allele, score</strong> visible outside the <code>With</code> scope otherwise you will always get <code>[None,None,None]</code> array:</p> <pre><code> def train_data(fname): #load csv training files peptide= [] allele= [] score = [] with open (fname) as train: ...
0
2016-06-27T21:24:41Z
[ "python", "python-3.x", "csv" ]
Return lists using csv reader
38,063,455
<p>this is my code. it works fine if I print the variables but if i return them and try to print them somewhere else only the last element gets printed.</p> <pre><code>def train_data(fname): #load csv training files with open (fname) as train: reader = csv.DictReader(train, delimiter='\t') for...
0
2016-06-27T21:20:38Z
38,063,753
<p>Printing the variable <strong>s</strong> will only print the score variable. </p> <p>Try: </p> <pre><code>print(p, a, s) </code></pre> <p>If you would like the output to look like the above csv file: </p> <pre><code>print(zip(p, a, s)) </code></pre>
0
2016-06-27T21:45:27Z
[ "python", "python-3.x", "csv" ]
Logging with WSGI server and flask application
38,063,508
<p>I am using wsgi server to spawn the servers for my web application. I am having problem with information logging. </p> <p>This is how I am running the app</p> <pre><code>from gevent import monkey; monkey.patch_all() from logging.handlers import RotatingFileHandler import logging from app import app # this imports ...
1
2016-06-27T21:26:02Z
38,064,220
<p>According to the <a href="http://www.gevent.org/gevent.pywsgi.html" rel="nofollow">gevent uwsgi documentation</a> you need to pass your log handler object to the WSGIServer object at creation:</p> <blockquote> <p><strong>log</strong> – If given, an object with a write method to which request (access) logs will ...
2
2016-06-27T22:31:00Z
[ "python", "logging", "flask", "wsgi", "gevent" ]
Django: cannot import name check_password
38,063,531
<p>I'm trying to set up a custom user model, but I'm getting the following error on my login page when trying to authenticate a member</p> <p><code>ImportError at /members/login/ cannot import name check_password </code></p> <p>I know the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/auth/#django.contrib...
0
2016-06-27T21:27:30Z
38,063,567
<p>You seem a bit confused about functions and methods. <code>check_password</code> is a method on the auth.models.User class; you can't just import it on its own. And you don't use it anyway; you call the - completely separate - <code>check_password</code> method on your own Member class; there's no need to import any...
0
2016-06-27T21:30:35Z
[ "python", "django" ]
pyspark: merge (outer-join) two data frames
38,063,657
<p>I have the following two data frames:</p> <pre><code>DF1: Id | field_A | field_B | field_C | field_D 1 | cat | 12 | black | 11 2 | dog | 128 | white | 19 3 | dog | 35 | yellow | 20 4 | dog | 21 | brown | 4 5 | bird | 10 | blue | 7 ...
0
2016-06-27T21:36:52Z
38,063,734
<p>try this:</p> <pre><code>new_df = df1.join(df2, on=['field_B', 'field_C', 'field_D'], how='left_outer') </code></pre>
1
2016-06-27T21:43:30Z
[ "python", "pyspark", "spark-dataframe" ]
MySQLdb - when to commit and execute?
38,063,784
<p>I'm using MySQLdb in Python 2, and I have a question about executing queries into the database. Say I have some connection <code>con</code>, and I instantiate a cursor with <code>cur = con.cursor()</code>. Which of the following is the proper way to commit changes to the database? Bonus points if you could explain t...
1
2016-06-27T21:48:54Z
38,064,334
<p>for <code>MySQLdb</code>, I'd probably do something like this:</p> <pre><code>import contextlib connection = get_connection_somehow() with contextlib.closing(connection) as con: with con as cursor: cursor.execute(query1) with con as cursor: cursor.execute(query2) ... </code></pre> <p>A...
0
2016-06-27T22:41:14Z
[ "python", "mysql", "database", "mysql-python" ]
Python: Subtract Minute off Time Variable in Filename within Try/Except Loop
38,063,806
<p>I'm trying to use Python to post a file dropped into a shared folder each night via API. All the posting code works -- the only thing I can't quite get is Python automatically grabbing the file name and uploading it to the SFTP.</p> <p>The file's naming convention is: <code>fileYYMMDDHHMM.txt</code> (all two-digits...
0
2016-06-27T21:50:49Z
38,063,950
<p>So, since your comment has cleared up that it'll be consistent and always newest, you can use some neat little tricks.</p> <p>First, the <code>os</code> module has a command named <code>os.listdir(path)</code>- this will give you the filenames of files in the given directory ("/Users/Ryan" above). Since the start i...
1
2016-06-27T22:05:24Z
[ "python", "for-loop", "filenames", "try-except" ]
Python ctypes create_string_buffer() Error 0xC0000005
38,063,899
<p>I have a named pipe server with a main loop where I am reading data from a pipe:</p> <pre><code>while True: bytes_available = DWORD() ret_code = windll.kernel32.PeekNamedPipe(pipe, None, 0, None, byref(bytes_available)) if ret_code == 0 and windll.kernel32.GetLastError() == ERROR_BROKEN_PIPE...
1
2016-06-27T21:59:29Z
38,086,090
<p>windll.kernel32.PeekNamedPipe() call in your code seems to be missing an argument, there should be six; see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365779(v=vs.85).aspx" rel="nofollow">msdn</a></p> <p>Omitting an argument essentially caused undefined behaviour.</p>
1
2016-06-28T20:51:34Z
[ "python", "ctypes", "access-violation" ]
Numeric value directly after backreference
38,063,982
<p>I'm trying to use <code>re.sub</code> on a string with a numeric value directly after a numeric backreference. That is, if my replacement value is <code>15.00</code> and my backreference is <code>\1</code>, my replacement string would look like:</p> <p><code>\115.00</code>, which as expected will throw an <code>err...
2
2016-06-27T22:08:12Z
38,064,010
<p>Use an unambiguous backreference syntax <code>\g&lt;1&gt;</code>. See <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> reference:</p> <blockquote> <p><code>\g&lt;number&gt;</code> uses the corresponding group number; <code>\g&lt;2&gt;</code> is therefore equivalent...
4
2016-06-27T22:10:49Z
[ "python", "regex" ]
add selected columns of a nd-array
38,064,016
<p>I have a 3d array, which, when printed in given way, </p> <pre><code>for i in range(5): print("======="+str(i)+"=========") for k in range(5): dos2[i][k]=atom[i][k][:5] print(dos2[i][k][:]) </code></pre> <p>looks like:</p> <pre><code>=======0========= 0[-4.052, 0.0, 0.0, 0.0, 0.0] 1[-3.995...
0
2016-06-27T22:11:52Z
38,064,257
<p>This is a bit of a guess, but I think you want to sum over <code>axis=0</code>:</p> <p>I like to use a mix of shapes so it is clearer that we are doing:</p> <pre><code>In [558]: atom=np.arange(3*4*5).reshape(3,4,5) In [559]: atom Out[559]: array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, ...
1
2016-06-27T22:34:19Z
[ "python", "numpy" ]
Identify symbols in string
38,064,044
<p>I am implementing a simple DSL. I have the following input string:</p> <pre><code>txt = 'Hi, my name is &lt;&lt;name&gt;&gt;. I was born in &lt;&lt;city&gt;&gt;.' </code></pre> <p>And I have the following data:</p> <pre><code>{ 'name': 'John', 'city': 'Paris', 'more': 'xxx', 'data': 'yyy', ... } </code...
1
2016-06-27T22:14:12Z
38,064,149
<p>Yes, this is a perfect target for regexp. Find the begin/end quotation marks, replace them with braces, and extract the symbol names into a list. Do you have a solid description of legal symbols? You'll want a search such as</p> <pre><code>/\&lt;\&lt;([a-zA-Z]+[a-zA-Z0-9_]*)\&gt;\&gt;/ </code></pre> <p>For clas...
2
2016-06-27T22:24:31Z
[ "python", "tokenize" ]