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
How to improve python import speed?
39,100,391
<p>This question has been asked many times on SO (for instance <a href="http://stackoverflow.com/q/16373510/2612235">here</a>), but there is no real answer yet.</p> <p>I am writing a short command line tool that renders templates. It is frigged using a Makefile: </p> <pre><code>i = $(wildcard *.in) o = $(patsubst %.i...
0
2016-08-23T11:50:33Z
39,100,698
<p>It is not quite easy, but you could turn your program into one that sits in the background and processes commands to process a file.</p> <p>Another program could feed the processing commands to it and thus make the real start quite easy.</p>
3
2016-08-23T12:05:33Z
[ "python", "performance", "python-import" ]
How to improve python import speed?
39,100,391
<p>This question has been asked many times on SO (for instance <a href="http://stackoverflow.com/q/16373510/2612235">here</a>), but there is no real answer yet.</p> <p>I am writing a short command line tool that renders templates. It is frigged using a Makefile: </p> <pre><code>i = $(wildcard *.in) o = $(patsubst %.i...
0
2016-08-23T11:50:33Z
39,100,929
<p>Write the template part as a separate process. The first time "script.py" is run it would launch this separate process. Once the process exists it can be passed the input/output filenames via a named pipe. If the process gets no input for x seconds, it automatically exits. How big x is depends on what your needs...
1
2016-08-23T12:15:46Z
[ "python", "performance", "python-import" ]
Why do 4 different languages give 4 different results here?
39,100,460
<p>Consider this (all commands run on an 64bit Arch Linux system):</p> <ul> <li><p>Perl (v5.24.0)</p> <pre><code>$ perl -le 'print 10190150730169267102/1000%10' 6 </code></pre></li> <li><p><code>awk</code> (GNU Awk 4.1.3)</p> <pre><code>$ awk 'BEGIN{print 10190150730169267102/1000%10}' 6 </code></pre></li> <li><p>R ...
5
2016-08-23T11:54:05Z
39,100,909
<p>I can answer only for the difference between python 2 and python 3. "/" is integer division in python 2 while it is real division in python 3 (that's where the <code>.0</code> in python 3 comes from. The output is floating point.</p> <p>To summarize:</p> <ul> <li><p>Python 2</p> <pre><code>10190150730169267102/10...
3
2016-08-23T12:14:59Z
[ "python", "perl", "awk", "rounding", "long-integer" ]
Why do 4 different languages give 4 different results here?
39,100,460
<p>Consider this (all commands run on an 64bit Arch Linux system):</p> <ul> <li><p>Perl (v5.24.0)</p> <pre><code>$ perl -le 'print 10190150730169267102/1000%10' 6 </code></pre></li> <li><p><code>awk</code> (GNU Awk 4.1.3)</p> <pre><code>$ awk 'BEGIN{print 10190150730169267102/1000%10}' 6 </code></pre></li> <li><p>R ...
5
2016-08-23T11:54:05Z
39,106,941
<p>You're seeing different results for two reasons:</p> <ol> <li><p>The division step is doing two different things: in some of the languages you tried, it represents <em>integer</em> division, which discards the fractional part of the result and just keeps the integer part. In others it represents actual mathematical...
9
2016-08-23T17:01:27Z
[ "python", "perl", "awk", "rounding", "long-integer" ]
Why do 4 different languages give 4 different results here?
39,100,460
<p>Consider this (all commands run on an 64bit Arch Linux system):</p> <ul> <li><p>Perl (v5.24.0)</p> <pre><code>$ perl -le 'print 10190150730169267102/1000%10' 6 </code></pre></li> <li><p><code>awk</code> (GNU Awk 4.1.3)</p> <pre><code>$ awk 'BEGIN{print 10190150730169267102/1000%10}' 6 </code></pre></li> <li><p>R ...
5
2016-08-23T11:54:05Z
39,215,829
<p>in perl6</p> <pre><code>➜ ~ perl6 -e 'say(10190150730169267102 div 1000 mod 10)' 7 ➜ ~ perl6 -e 'say(10190150730169267102/1000%10)' 7.102 </code></pre> <p>so, If you are not sure which language is correct, try to ask Perl6. :)</p>
1
2016-08-29T21:58:38Z
[ "python", "perl", "awk", "rounding", "long-integer" ]
GAE/P: Implementing Exponential backoff for RPC calls
39,100,535
<p>I know that exponential backoff is a good thing when RPC calls fail. So far in my GAE/P app I have implemented exponential backoff by using the task queue:</p> <pre><code>deferred.defer(function_that_makes_RPC_call) </code></pre> <p>If the function that does the RPC call raises an exception, then the exponential ...
1
2016-08-23T11:57:56Z
39,101,667
<p>In particular for the <code>DeadlineExceededError</code> in attempts to enqueue a deferred task I'd just do back2back retries instead of using an exponential backoff - the attempts will be spaced 5s apart due to the deadline interval expiration itself anyways, which gives a max of 12 retries before the request itsel...
1
2016-08-23T12:47:59Z
[ "python", "google-app-engine", "rpc" ]
Print multiple statements on one line for input
39,100,542
<p>How do I allow the user to input values and receive the answer, whilst keeping the values of "x + xy + y" on one line?</p> <pre><code>print("Calculator") x = input("") xy = input("") y = input("") if xy == "+": print(x+y) elif xy == "-": print(x-y) elif xy == "*": print(x*y) elif xy == "/": print(x...
-2
2016-08-23T11:58:20Z
39,100,912
<p>I'd suggest using a single <code>input</code> statement and then using a simple <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regular expression</a> to parse the string into <code>x</code>, <code>y</code> and the operator. For example, this pattern: <code>(\d+)\s*([-+*/])\s*(\d+)</code>. Here, <...
1
2016-08-23T12:15:09Z
[ "python" ]
Print multiple statements on one line for input
39,100,542
<p>How do I allow the user to input values and receive the answer, whilst keeping the values of "x + xy + y" on one line?</p> <pre><code>print("Calculator") x = input("") xy = input("") y = input("") if xy == "+": print(x+y) elif xy == "-": print(x-y) elif xy == "*": print(x*y) elif xy == "/": print(x...
-2
2016-08-23T11:58:20Z
39,100,997
<p>Here's another possibility.</p> <pre><code>raw = raw_input("Calculator: ") raw1 = raw.split(" ") x = int(raw1[0]) xy = raw1[1] y = int(raw1[2]) if xy == "+": print raw, "=", x + y elif xy == "-": print raw, "=", x-y elif xy == "/": print raw, "=", x/y elif xy == "*": print raw, "=", x*y </code></p...
0
2016-08-23T12:18:15Z
[ "python" ]
Print multiple statements on one line for input
39,100,542
<p>How do I allow the user to input values and receive the answer, whilst keeping the values of "x + xy + y" on one line?</p> <pre><code>print("Calculator") x = input("") xy = input("") y = input("") if xy == "+": print(x+y) elif xy == "-": print(x-y) elif xy == "*": print(x*y) elif xy == "/": print(x...
-2
2016-08-23T11:58:20Z
39,101,133
<p>You can get input like this:</p> <pre><code>cal = input("Calculator: ").strip().split() x, xy, y = int(cal[0]), cal[1], int(cal[2]) </code></pre> <p>Then you can process your input data.</p>
0
2016-08-23T12:23:52Z
[ "python" ]
Python: print a string spanning to a given width, but first part left-aligned and second part right-aligned
39,100,548
<p>I would like to output something like:</p> <pre><code>===&gt;&gt;&gt; [FINISHED] Building sources: bla (1h:20m:30s) ===&gt;&gt;&gt; [FINISHED] Building sources: The brown fox jumped... (7h:05m:00s) </code></pre> <p>That is, a string filling a width of <code>N</code> characte...
-3
2016-08-23T11:58:44Z
39,100,754
<p>assuming you know the width of the line you can use <code>'{:n}'.format(string)</code> to fill the string up to n-length with spaces. This does not shorten the string if it is longer than n, as you state will never be the case.</p> <pre><code>'===&gt;&gt;&gt; [FINISHED] Building sources: {:35} ({})'.format('bla', '...
1
2016-08-23T12:08:20Z
[ "python", "string", "format", "text-alignment" ]
Python: print a string spanning to a given width, but first part left-aligned and second part right-aligned
39,100,548
<p>I would like to output something like:</p> <pre><code>===&gt;&gt;&gt; [FINISHED] Building sources: bla (1h:20m:30s) ===&gt;&gt;&gt; [FINISHED] Building sources: The brown fox jumped... (7h:05m:00s) </code></pre> <p>That is, a string filling a width of <code>N</code> characte...
-3
2016-08-23T11:58:44Z
39,100,972
<p>Just one way, adding the right number of spaces...</p> <pre><code>&gt;&gt;&gt; for a, b in ('fsad', 'trwe'), ('gregrfgsd', '5435234523554'): print a + ' ' * (50 - len(a + b)) + b fsad trwe gregrfgsd 5435234523554 </code></pre>
1
2016-08-23T12:17:16Z
[ "python", "string", "format", "text-alignment" ]
Skip new line while printing with ternary operator in python
39,100,721
<p>To print a statement and to prevent going into the new line one could simply add a comma in the end:</p> <pre><code>print "text", </code></pre> <p>But how can I do the same using a ternary operator? This one causes invalid syntax:</p> <pre><code>print ("A", if True else "B", ) </code></pre>
1
2016-08-23T12:07:09Z
39,100,859
<p>Instead of using just ugly hacks, we can define function called below as <code>special_print</code> which every print locates in the same line:</p> <pre><code>import sys def special_print(value): sys.stdout.write(value) special_print('ab') special_print('cd') </code></pre> <p>Result:</p> <pre><code>abcd <...
1
2016-08-23T12:12:50Z
[ "python", "python-2.7" ]
Skip new line while printing with ternary operator in python
39,100,721
<p>To print a statement and to prevent going into the new line one could simply add a comma in the end:</p> <pre><code>print "text", </code></pre> <p>But how can I do the same using a ternary operator? This one causes invalid syntax:</p> <pre><code>print ("A", if True else "B", ) </code></pre>
1
2016-08-23T12:07:09Z
39,100,869
<p>You can use the <code>or</code> operator as well, like this:</p> <pre><code>a = None b = 12 print a or b, print "is a number" # prints: 12 is a number </code></pre> <p>Just note that the expression above is evaluated <strong>lazily</strong>, meaning that if <code>bool(a)</code> is <code>False</code>, <code>print</...
0
2016-08-23T12:13:13Z
[ "python", "python-2.7" ]
Skip new line while printing with ternary operator in python
39,100,721
<p>To print a statement and to prevent going into the new line one could simply add a comma in the end:</p> <pre><code>print "text", </code></pre> <p>But how can I do the same using a ternary operator? This one causes invalid syntax:</p> <pre><code>print ("A", if True else "B", ) </code></pre>
1
2016-08-23T12:07:09Z
39,100,946
<pre><code>print "A" if True else "B", print "Hi" </code></pre> <p><strong>Output: A Hi</strong></p>
1
2016-08-23T12:16:14Z
[ "python", "python-2.7" ]
Skip new line while printing with ternary operator in python
39,100,721
<p>To print a statement and to prevent going into the new line one could simply add a comma in the end:</p> <pre><code>print "text", </code></pre> <p>But how can I do the same using a ternary operator? This one causes invalid syntax:</p> <pre><code>print ("A", if True else "B", ) </code></pre>
1
2016-08-23T12:07:09Z
39,101,007
<p>I guess you can look at it this as one statement:</p> <pre><code>"A" if True else "B" </code></pre> <p>Then your print statement becomes:</p> <pre><code>print "A" if True else "B", </code></pre> <p>That should print "A" without the newline character (or "B" if the condition is <code>False</code>). </p>
1
2016-08-23T12:18:34Z
[ "python", "python-2.7" ]
Skip new line while printing with ternary operator in python
39,100,721
<p>To print a statement and to prevent going into the new line one could simply add a comma in the end:</p> <pre><code>print "text", </code></pre> <p>But how can I do the same using a ternary operator? This one causes invalid syntax:</p> <pre><code>print ("A", if True else "B", ) </code></pre>
1
2016-08-23T12:07:09Z
39,101,034
<blockquote> <p>[...] to prevent going into the new line one could simply add a comma in the end</p> </blockquote> <p>The solution is in your question already. One could simply add a comma in the end:</p> <pre><code>print "A" if True else "B", </code></pre> <hr> <p>However Python 3 has been out for closer to a <s...
5
2016-08-23T12:19:40Z
[ "python", "python-2.7" ]
Optimal way to check all fields in a json data?
39,100,856
<pre class="lang-none prettyprint-override"><code>data = {u'name': None, u'region': None, u'id': u'test1', u'code': None, u'city': None, u'first_name': None, u'state_or_province': None, u'primary_phone': None, u'data2': [{u'status': u'deleted', u'name': u'b1', u'id': u'b1', u'modified_at': u'201...
-1
2016-08-23T12:12:34Z
39,101,700
<p><strong>Python 3.x Code:</strong></p> <pre><code>for key, value in parsed_json[0].items(): if value == "": print(key + " value is empty.") </code></pre> <p>Note: This code does not differentiate error messages by key (each one gets the same error message) and has not been properly escaped. If you're getting ...
0
2016-08-23T12:49:24Z
[ "python", "json", "list", "dictionary", "data-structures" ]
Optimal way to check all fields in a json data?
39,100,856
<pre class="lang-none prettyprint-override"><code>data = {u'name': None, u'region': None, u'id': u'test1', u'code': None, u'city': None, u'first_name': None, u'state_or_province': None, u'primary_phone': None, u'data2': [{u'status': u'deleted', u'name': u'b1', u'id': u'b1', u'modified_at': u'201...
-1
2016-08-23T12:12:34Z
39,102,699
<p>To get a filtered dictionary containing only empty values, you could do this:</p> <p><strong>Python 2.x</strong></p> <p>empty_values = {k:v for k,v in data.iteritems() if not v}</p> <p><strong>Python 3.x</strong></p> <p>empty_values = {k:v for k,v in data.items() if not v}</p>
0
2016-08-23T13:32:39Z
[ "python", "json", "list", "dictionary", "data-structures" ]
Optimal way to check all fields in a json data?
39,100,856
<pre class="lang-none prettyprint-override"><code>data = {u'name': None, u'region': None, u'id': u'test1', u'code': None, u'city': None, u'first_name': None, u'state_or_province': None, u'primary_phone': None, u'data2': [{u'status': u'deleted', u'name': u'b1', u'id': u'b1', u'modified_at': u'201...
-1
2016-08-23T12:12:34Z
39,104,064
<p>Since a JSON object is a recursive data-structure, probably the easiest way to to do what you want is recursively:</p> <pre><code>def verify(key, value): if not value: print('"{}" is not present'.format(key)) elif isinstance(value, dict): for k, v in value.items(): verify(k, v) ...
0
2016-08-23T14:32:42Z
[ "python", "json", "list", "dictionary", "data-structures" ]
How do I release memory used by a pandas dataframe?
39,100,971
<p>I have a really large csv file that I opened in pandas as follows....</p> <pre><code>import pandas df = pandas.read_csv('large_txt_file.txt') </code></pre> <p>Once I do this my memory usage increases by 2GB, which is expected because this file contains millions of rows. My problem comes when I need to release thi...
10
2016-08-23T12:17:10Z
39,101,264
<p><code>del df</code> will not be deleted if there are any reference to the <code>df</code> at the time of deletion. So you need to to delete all the references to it with <code>del df</code> to release the memory. </p> <p>So all the instances bound to df should be deleted to trigger garbage collection.</p> <p>Use <...
0
2016-08-23T12:29:48Z
[ "python", "pandas", "memory" ]
How do I release memory used by a pandas dataframe?
39,100,971
<p>I have a really large csv file that I opened in pandas as follows....</p> <pre><code>import pandas df = pandas.read_csv('large_txt_file.txt') </code></pre> <p>Once I do this my memory usage increases by 2GB, which is expected because this file contains millions of rows. My problem comes when I need to release thi...
10
2016-08-23T12:17:10Z
39,101,287
<p>As noted in the comments, there are some things to try: <code>gc.collect</code> (@EdChum) may clear stuff, for example. At least from my experience, these things sometimes work and often don't. </p> <p>There is one thing that always works, however, because it is done at the OS, not language, level.</p> <p>Suppose ...
4
2016-08-23T12:31:01Z
[ "python", "pandas", "memory" ]
How do I release memory used by a pandas dataframe?
39,100,971
<p>I have a really large csv file that I opened in pandas as follows....</p> <pre><code>import pandas df = pandas.read_csv('large_txt_file.txt') </code></pre> <p>Once I do this my memory usage increases by 2GB, which is expected because this file contains millions of rows. My problem comes when I need to release thi...
10
2016-08-23T12:17:10Z
39,377,643
<p>Reducing memory usage in Python is difficult, because <a href="http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm" rel="nofollow">Python does not actually release memory back to the operating system</a>. If you delete objects, then the memory is available to new Python obje...
1
2016-09-07T19:25:24Z
[ "python", "pandas", "memory" ]
How to fix Arabic unicode in a list
39,100,987
<p>I made a database containing Arabic words and when I fetch the data and print it it's OK and works well and prints:</p> <pre><code>مشاعر‬ مودة </code></pre> <p>But when I loop into that database and turn it out to a list then print that list to see whats happening, I get this:</p> <pre><code> ['\...
0
2016-08-23T12:17:44Z
39,113,322
<p>Found ...</p> <pre><code>import re cors.execute("SELECT * FROM DictContents") self.AraList = [] for raw in cors.fetchall(): rawAra = raw[1] cleanit = re.compile('\w+.*') cleanone = cleanit .search(rawAra) if cleanone: print(cleanone.group()) # prints the clean strings : مشاعر...
0
2016-08-24T02:03:49Z
[ "python", "python-3.x" ]
when I use scipy.optimize.linprog,How can I restrict x be a int
39,101,137
<p>When I solve the problem of Linear Programming, like in the following formula, <strong>I want the result of x all to be int type</strong></p> <p>Consider the following problem:</p> <p>Minimize: <code>f = -1*x[0] + 4*x[1]</code></p> <p>Subject to: </p> <pre><code>-3*x[0] + 1*x[1] &lt;= 6 1*x[0] + 2*x[1] &lt;=...
0
2016-08-23T12:24:01Z
39,101,617
<p>From the <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.linprog.html">docs</a>:</p> <blockquote> <p>method : str, optional Type of solver. At this time only ‘simplex’ is supported.</p> </blockquote> <p>Simplex cannot handle integrality constraints so you cannot solve int...
5
2016-08-23T12:45:32Z
[ "python", "scipy" ]
add new plot to existing figure
39,101,203
<p>I have a script with some plots ( see example code). After some other things i want to add a new plot to an existing one. But when i try that it add the plot by the last created figure(now fig2). I can't figure out how to change that...</p> <pre><code>import matplotlib.pylab as plt import numpy as np n = 10 x1 = n...
-3
2016-08-23T12:26:42Z
39,106,673
<p>Since your code is not runnable without errors I'll provide a sample snippet showing how to plot several data in same graph/diagram:</p> <pre><code>import matplotlib.pyplot as plt xvals = [i for i in range(0, 10)] yvals1 = [i**2 for i in range(0, 10)] yvals2 = [i**3 for i in range(0, 10)] f, ax = plt.subplots(1) ...
1
2016-08-23T16:45:16Z
[ "python", "matplotlib", "plot" ]
Initially populate FileField in Django-Form
39,101,231
<p>I have a model that describes a Webpage. The <code>source_upload</code> field represents a screenshot of the webpage. </p> <p>For adding site-objects to my application, I use a django class-based <code>CreateView</code>. This works really well. </p> <p>Now I'm trying to add a semi-automatic way of adding sites. Yo...
2
2016-08-23T12:28:27Z
39,101,582
<p>This is because the value of FileField, as used by your form, isn't just the path to the file - it's an instance of FieldFile (see <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#djang...
1
2016-08-23T12:44:01Z
[ "python", "django", "django-class-based-views" ]
Why isn't the HTML I get from BeautifulSoup the same as the one I see when I inspect element?
39,101,335
<p>I am making a username scraper and I really can't understand why the HTML is 'disappearing' when I parse it. Let's take this site for example: <a href="http://www.lolking.net/leaderboards#/eune/1" rel="nofollow">http://www.lolking.net/leaderboards#/eune/1</a></p> <p><a href="http://i.stack.imgur.com/q5LwE.png" rel...
2
2016-08-23T12:33:38Z
39,101,540
<p>This site needs JavaScript to work. JavaScript is used to populate the table by forming a web request, which probably points to a back-end API. This means that the "raw" HTML, without the effects of any JavaScript, has an empty table.</p> <p>We can actually see this empty table in the background if we visit the sit...
1
2016-08-23T12:41:56Z
[ "python", "html", "beautifulsoup" ]
Why isn't the HTML I get from BeautifulSoup the same as the one I see when I inspect element?
39,101,335
<p>I am making a username scraper and I really can't understand why the HTML is 'disappearing' when I parse it. Let's take this site for example: <a href="http://www.lolking.net/leaderboards#/eune/1" rel="nofollow">http://www.lolking.net/leaderboards#/eune/1</a></p> <p><a href="http://i.stack.imgur.com/q5LwE.png" rel...
2
2016-08-23T12:33:38Z
39,101,626
<p>As you can see in Chrome Dev Tools, the site sends 2 XHR requests to get the data, and displays it by using JavaScript.</p> <p>Since <code>BeautifulSoup</code> is an HTML <strong>parser</strong>. It will not execute JavaScript. You should use a tool like <a href="http://selenium-python.readthedocs.org/" rel="nofoll...
0
2016-08-23T12:46:07Z
[ "python", "html", "beautifulsoup" ]
Why isn't the HTML I get from BeautifulSoup the same as the one I see when I inspect element?
39,101,335
<p>I am making a username scraper and I really can't understand why the HTML is 'disappearing' when I parse it. Let's take this site for example: <a href="http://www.lolking.net/leaderboards#/eune/1" rel="nofollow">http://www.lolking.net/leaderboards#/eune/1</a></p> <p><a href="http://i.stack.imgur.com/q5LwE.png" rel...
2
2016-08-23T12:33:38Z
39,102,210
<p>You can get all the data in <em>json</em> format, ll you need to do is parse a value from script tag inside the original page source and pass it to "<a href="http://www.lolking.net/leaderboards/some_value_here/eune/1.json" rel="nofollow">http://www.lolking.net/leaderboards/some_value_here/eune/1.json</a>":</p> <pr...
1
2016-08-23T13:11:10Z
[ "python", "html", "beautifulsoup" ]
ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:
39,101,488
<p>I am very new to Python and Django and is currently busy learning myself through tutorials on www.djangoproject.com. I am using PyCharm and working on OS X El Capitan. I have imported a project from github and created a virtual environment for the project interpretor based on Python 3.5.1. In the vm I installed djan...
0
2016-08-23T12:39:41Z
39,101,550
<p>You do not have path to a log file for some reason (/Users/deon/Documents/PyCharmProjects/Developments/deonproject/log). Make sure that all directories exist (if no, create them) and create an empty <code>debug.log</code> log file (just in case).</p> <p>What happens is there is some problem with your code happening...
0
2016-08-23T12:42:12Z
[ "python", "django", "pycharm" ]
TypeError: unorderable types: NoneType() > int()
39,101,535
<p>I am new to python3, and am getting the following error trying to read earthquake data from last day!!</p> <pre><code>Traceback (most recent call last): File "Z:\Python learning\Up and run\Exercise Files\Ch5\jsondata_finished.py", line 54, in &lt;module&gt; main() File "Z:\Python learning\Up and run\Exercis...
0
2016-08-23T12:41:50Z
39,101,613
<p>Use <code>and</code> instead of <code>&amp;</code>. Also, use <code>is not None</code> to check if object is not <code>None</code> instead of <code>!= None</code></p>
1
2016-08-23T12:45:24Z
[ "python", "python-3.x" ]
BigQuery script failing for large file
39,101,602
<p>I am trying to load a json file to <strong>GoogleBigquery</strong> using the script at <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/api/load_data_by_post.py" rel="nofollow">https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/api/load_data_by_po...
0
2016-08-23T12:44:51Z
39,111,367
<p>When handling large files don't use streaming, but batch load: Streaming will easily handle up to 100,000 rows per second. That's pretty good for streaming, but not for loading large files.</p> <p>The sample code linked is doing the right thing (batch instead of streaming), so what we see is a different problem: Th...
2
2016-08-23T22:02:18Z
[ "python", "json", "google-bigquery" ]
Django: ValueError: Unable to configure handler - [Errno 2]
39,101,715
<p>I am very new to Python and Django and is currently busy learning myself through tutorials on www.djangoproject.com. I am using PyCharm and working on OS X El Capitan. I have imported a project from GitHub and created a virtual environment for the project interpreter based on Python 3.5.1. In the vm I installed djan...
-1
2016-08-23T12:49:59Z
39,138,528
<p>I managed to fix it. The log directory was not created because it was excluded in the .gitignore file. I completely forgot to look what was excluded :). I created the directory manually and now it passed the error. Deon</p>
0
2016-08-25T06:51:52Z
[ "python", "django", "pycharm" ]
Using python to ssh into multiple servers and grab the file with the same postfix
39,101,719
<p>I normally use a bash script to grab all the files onto local machine and use <code>glob</code> to process all the files. Just wondering what would be the best way to use python (instead of another bash script) to ssh into each server and process those files?</p> <p>My current program runs as </p> <pre><code> for ...
0
2016-08-23T12:50:08Z
39,101,822
<p>The simplest way to do it is to use paramico_scp to use ssh copy from the remote server (<a href="http://stackoverflow.com/questions/250283/how-to-scp-in-python">How to scp in python?</a>)</p> <p>If you are not allowed to download any libraries, you can create SSH key pair so that connecting to server does not requ...
0
2016-08-23T12:54:39Z
[ "python", "bash", "ssh" ]
Using python to ssh into multiple servers and grab the file with the same postfix
39,101,719
<p>I normally use a bash script to grab all the files onto local machine and use <code>glob</code> to process all the files. Just wondering what would be the best way to use python (instead of another bash script) to ssh into each server and process those files?</p> <p>My current program runs as </p> <pre><code> for ...
0
2016-08-23T12:50:08Z
39,102,308
<p>Looks like you want to use a local Python script remotely. This has been <a href="http://stackoverflow.com/a/22915340/482382">answered here</a>.</p>
0
2016-08-23T13:14:50Z
[ "python", "bash", "ssh" ]
Problems with python versions and environemnts on os x el captain
39,101,818
<p>I'm learning python and I'm using OS X. I've installed anaconda 3 and set up env called testenv with python 3.5. Then I activated recently created env and installed several packages such as numpy, pandas and opencv3. Nevertheless, when I run python shell and type "import numpy" I get the following errors:</p> <pre>...
0
2016-08-23T12:54:26Z
39,116,954
<blockquote> <p>File "/usr/local/lib/python2.7/site-packages/numpy/<strong>init</strong>.py", line 180, in </p> </blockquote> <p>Python is picking up the packages from the system's Python packages and not from the packages installed in your virtualenv i.e. <code>testenv</code>.</p> <p>Be sure that you have activa...
0
2016-08-24T07:27:06Z
[ "python", "osx" ]
Port Modbus RTU CRC to python from C#
39,101,926
<p>I'm trying to port the CRC calculation function for Modbus RTU from C# to Python.</p> <p><strong>C#</strong> </p> <pre><code>private static ushort CRC(byte[] data) { ushort crc = 0xFFFF; for (int pos = 0; pos &lt; data.Length; pos++) { crc ^= (UInt16)data[pos]; for (int i = 8; i != 0; i...
0
2016-08-23T12:58:18Z
39,102,893
<p>Your inner loop uses the size of the data array instead of a fixed 8 iterations. Try this:</p> <pre><code>def calc_crc(data): crc = 0xFFFF for pos in data: crc ^= pos for i in range(8): if ((crc &amp; 1) != 0): crc &gt;&gt;= 1 crc ^= 0xA001 ...
1
2016-08-23T13:41:32Z
[ "c#", "python", "crc", "modbus" ]
pandas views vs copy : the docs says "nobody knows"?
39,101,933
<p>There's lots of questions on StackOverflow about chained indexing and whether a particular operation makes a view or a copy. (for instance, <a href="http://stackoverflow.com/questions/23296282/what-rules-does-pandas-use-to-generate-a-view-vs-a-copy">here</a> or <a href="http://stackoverflow.com/questions/17960511/pa...
1
2016-08-23T12:58:37Z
39,102,097
<p>Here's the core bit of documentation that I think you may have missed:</p> <blockquote> <p>Outside of simple cases, it’s very hard to predict whether it will return a view or a copy (it depends on the memory layout of the array, about which <em>pandas</em> makes no guarantees)</p> </blockquote> <p>So there's a...
4
2016-08-23T13:05:40Z
[ "python", "pandas" ]
pandas views vs copy : the docs says "nobody knows"?
39,101,933
<p>There's lots of questions on StackOverflow about chained indexing and whether a particular operation makes a view or a copy. (for instance, <a href="http://stackoverflow.com/questions/23296282/what-rules-does-pandas-use-to-generate-a-view-vs-a-copy">here</a> or <a href="http://stackoverflow.com/questions/17960511/pa...
1
2016-08-23T12:58:37Z
39,103,999
<p>I think I can demonstrate something to clarify your situation, in your example, initially it will be a view but once you try to modify by adding a column it turns into a copy. You can test this by looking at the attribute <code>._is_view</code>:</p> <pre><code>In [29]: df = pd.DataFrame(np.random.randn(5,3), column...
5
2016-08-23T14:29:36Z
[ "python", "pandas" ]
How to call all functions with name starting with given prefix?
39,102,240
<p>In Python how to write such a function which will call all functions in current file with given prefix?</p> <p>For example:</p> <pre><code>def prepare(self): # ??? to call prepare_1, prepare_2 def prepare_1(self): def prepare_2(self): </code></pre> <p>How to write <code>prepare</code> so it will call all func...
2
2016-08-23T13:12:28Z
39,102,335
<p>Use <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow">globals</a> to access global namespace, <a href="https://docs.python.org/2/library/stdtypes.html?highlight=iteritems#dict.iteritems" rel="nofollow">dict.iteritems</a> to iterate over it and <a href="https://docs.python.org/2/librar...
5
2016-08-23T13:15:56Z
[ "python" ]
How to call all functions with name starting with given prefix?
39,102,240
<p>In Python how to write such a function which will call all functions in current file with given prefix?</p> <p>For example:</p> <pre><code>def prepare(self): # ??? to call prepare_1, prepare_2 def prepare_1(self): def prepare_2(self): </code></pre> <p>How to write <code>prepare</code> so it will call all func...
2
2016-08-23T13:12:28Z
39,102,405
<p>If these functions are methods of a class, use <code>dir(self)</code> to list all attributes of <code>self</code>.</p> <pre><code>class C: def prepare(self): print(dir(self)) for name in dir(self): if name.startswith('prepare_'): method = getattr(self, name) ...
2
2016-08-23T13:19:29Z
[ "python" ]
How to call all functions with name starting with given prefix?
39,102,240
<p>In Python how to write such a function which will call all functions in current file with given prefix?</p> <p>For example:</p> <pre><code>def prepare(self): # ??? to call prepare_1, prepare_2 def prepare_1(self): def prepare_2(self): </code></pre> <p>How to write <code>prepare</code> so it will call all func...
2
2016-08-23T13:12:28Z
39,102,834
<p>It's been asked for, so here's a quick hack:</p> <pre><code>import functools class FunctionGroup(object): """ Defines a function group as a list of functions that can be executed sequentially from a single call to the function group. Use @func_group.add def my_func(...): ...
1
2016-08-23T13:38:55Z
[ "python" ]
Project not finding my reusable app's admin template override
39,102,242
<p>I have a reusable app with a directory structure like this:</p> <pre><code>myapp/ myapp/ views.py models.py ...etc templates/ myapp/ template1.html ...etc admin/ index.html test/ ...testing stuff setup.py ...etc </code></pre> <p>I'm overriding the <c...
0
2016-08-23T13:12:32Z
39,113,815
<p>Django's template loader looks for templates in the order that apps are defined in <code>INSTALLED_APPS</code>. In your case you must have defined <code>django.contrib.admin</code> ahead of your app, so Django will always look there first and use the first template it finds. </p> <p>Change it so that your app is fi...
1
2016-08-24T03:13:11Z
[ "python", "django", "django-templates", "django-admin" ]
Numpy: array > 5 yields "The truth value of an array with more than one element is ambiguous"
39,102,439
<p>I know that in numpy you can't simply do conditionals on arrays as it doesn't know how to treat them and that this error is a result of that, however in my case my code is a lot simpler. I have:</p> <pre><code># H and _H are 3x3 arrays with hand-assigned values # uv1 is 3x57600 array of coordinates, hand assigned i...
1
2016-08-23T13:21:14Z
39,102,802
<p>I recreated your code with random variables. But it works fine here:</p> <pre><code>import numpy as np H = np.random.rand(3,3)*10 _H = np.random.rand(3,3)*10 uv1 = np.random.rand(3,57600)*10 HH = np.dot(_H,np.linalg.inv(H)) new_uv = np.dot(HH,uv1) du = uv1[0,:] * new_uv[2,:] u = new_uv[0,:] - du u_greater_5 = u &gt...
1
2016-08-23T13:37:03Z
[ "python", "numpy" ]
Numpy: array > 5 yields "The truth value of an array with more than one element is ambiguous"
39,102,439
<p>I know that in numpy you can't simply do conditionals on arrays as it doesn't know how to treat them and that this error is a result of that, however in my case my code is a lot simpler. I have:</p> <pre><code># H and _H are 3x3 arrays with hand-assigned values # uv1 is 3x57600 array of coordinates, hand assigned i...
1
2016-08-23T13:21:14Z
39,104,866
<p>I suspect that <code>u</code> is a one-dimensional array of <em>objects</em>, and the objects are themselves one-dimensional numpy arrays with length 3. I can reproduce the behavior you report as follows. First, create a one-dimensional array of objects (length 3), and fill it with numpy arrays:</p> <pre><code>In...
4
2016-08-23T15:10:59Z
[ "python", "numpy" ]
language file dosen't load automaticaly in Django
39,102,538
<p>I'm using python3 and Django 1.10 for my application, and I am kind of new to Django. I'm planning to have many languages for Django admin panel. As I follow the rules in Django documentation, I find out that I have to use a middleware for localization... Here are my settings:</p> <pre><code>MIDDLEWARE = [ 'dja...
1
2016-08-23T13:25:56Z
40,140,545
<p>I have a similar working setup, the main difference seems to be that I'm using <code>ugettext_lazy</code>. That's because I need to translate these strings in my models or settings when they were accessed, rather than when they were called (which would happen only once: they would only be evaluated on server startup...
1
2016-10-19T20:04:30Z
[ "python", "django", "python-3.x", "multilingual" ]
Pandas apply function to unique values in column
39,102,563
<p>I've been stuck on a Pandas problem and I can't seem to figure it out. I have a dataframe like this:</p> <pre><code>ref, value, rule, result, new_column a100, 25, high, fail, nan a100, 25, high, pass, nan a100, 25, medium, fail, nan a100, 25, medium, pass, nan a101, 15, high, fail, nan a101, 15, high, pass, nan a10...
-1
2016-08-23T13:27:21Z
39,102,649
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a>:</p> <pre><code>print (df) ref value rule result new_column 0 a100 25 high pass NaN 1 a100 25 high fail ...
1
2016-08-23T13:30:30Z
[ "python", "pandas", "dataframe", "unique", "condition" ]
Allow Python.app on El Captain (OS X)
39,102,571
<p><a href="http://i.stack.imgur.com/WKi5J.png" rel="nofollow"><img src="http://i.stack.imgur.com/WKi5J.png" alt="enter image description here"></a></p> <p>I'm using a <code>python</code> executable in a <strong>virtual environment</strong>. I tried doing the whole <code>codesign</code> thing as described <a href="htt...
11
2016-08-23T13:27:34Z
39,244,070
<p><strong>Why is that happening?</strong></p> <p>So the <code>python</code> executables in El Capitan spawns <code>.../Python.framework/Versions/2.7/Resources/Python.app</code> + some extra magic. The problem is that the framework bundle doesn't have its own signature, and it uses signatures of parent application bin...
2
2016-08-31T08:08:51Z
[ "python", "osx" ]
python Unicode decode error when accessing records of OrderedDict
39,102,647
<p>using python 3.5.2 on windows (32), I'm reading a DBF file which returns me an OrderedDict.</p> <pre><code>from dbfread import DBF Table = DBF('FME.DBF') for record in Table: print(record) </code></pre> <p>When accessing the first record all is ok until I reach a record which contains diacritics:</p> <pre><cod...
1
2016-08-23T13:30:28Z
39,102,922
<p><code>dbfread</code> failed to detect the correct encoding from your DBF file. From the <a href="https://dbfread.readthedocs.io/en/latest/introduction.html#character-encodings" rel="nofollow"><em>Character Encodings</em> section of the documentation</a>:</p> <blockquote> <p><code>dbfread</code> will try to detect...
0
2016-08-23T13:42:37Z
[ "python", "unicode", "ordereddictionary" ]
Converting Julia JuMP to Python PuLP
39,102,846
<p>I stumbled upon a piece of software that I'd like to convert from Julia to Python (don't have much experience with Julia). The main problem I'm having is I don't understand exactly what is going on in the section I've marked with comments #PROBLEM BELOW/ABOVE</p> <p>skaters_teams is a 180 x 10 matrix (180 skaters ...
-2
2016-08-23T13:39:14Z
39,108,725
<p>After playing around with it for a bit longer I found a solution. In case anyone has similar issues with pulp and jump here is what I used.</p> <pre><code>for i in range(num_teams): m += sum(x * st[i] for x,st in zip (skaters_lineup, skaters_teams[:])) &gt;= used_team[i] m += sum(x * st[i] for x,st in zip ...
1
2016-08-23T18:54:31Z
[ "python", "julia-lang", "pulp", "julia-jump" ]
PyCharm set pattern for newly created file
39,102,868
<p>Every time when I create <code>.py</code> file in django project, I need to add two strings </p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals </code></pre> <p>Is there any way to set some pattern for newly created python files in PyCharm?</p>
2
2016-08-23T13:40:30Z
39,103,414
<p>File->settings->Editor->File and Code Templates->Python Script</p> <p><img src="http://i.stack.imgur.com/uCmiQ.png" alt="enter image description here"></p>
3
2016-08-23T14:03:11Z
[ "python", "pycharm", "jetbrains" ]
Connect and present data from two different tables in django
39,102,912
<p>I'm trying to easily present data from two different tables (classes). I have an <code>Environment</code> class with all the environments details and a <code>Changes</code> class which contain history changes on all my environments.</p> <p>My view is currently showing all my <code>Environment</code> details. I want...
0
2016-08-23T13:42:12Z
39,103,269
<p>You can write a method on System to return the last change for an item:</p> <pre><code>def last_change(self): return self.changes_set.order_by('-date').first() </code></pre> <p>Now you can indeed call <code>system.last_change</code> in the template.</p>
1
2016-08-23T13:57:14Z
[ "python", "django", "django-models" ]
Matplotlib Stacked Histogram Bin Width
39,102,918
<p>When creating a stacked histogram in Matplotlib I noticed that the bin widths shrink. In this simple example:</p> <pre><code>import numpy as np import matplotlib import matplotlib.pylab as plt #Create histograms and plots fig = plt.figure() gs = matplotlib.gridspec.GridSpec(1, 2) h1 = fig.add_subplot(gs[0]) h2 = f...
0
2016-08-23T13:42:26Z
39,104,417
<p>If the first argument of a <code>ax.hist</code>-call is a list of lists (or a 2d numpy-array or a combination of the two) it will automatically make the bins smaller. The <code>rwidth</code> parameter of the <code>ax.hist</code>-call is the parameter that determines the bin-width. Setting it to 1 will do what you wa...
0
2016-08-23T14:49:53Z
[ "python", "matplotlib" ]
Send email with Office365 python library `python-o365`
39,103,057
<p>Ok So ive been able to send mail and read mail but I am now trying to attach an attachment to the mail and it doesnt seem to append the document as expected. I dont get any errors but I also dont get the mail if I attempt to add the attachment.</p> <p>The library im using is <a href="https://github.com/Narcolapser/...
0
2016-08-23T13:48:31Z
39,160,843
<p>Please debug this way</p> <pre><code>att = Attachment(path=path) att.save(path) m.attachments.append(att) </code></pre>
0
2016-08-26T07:35:43Z
[ "python", "office365" ]
Adding a new row to a MultiIndex pandas DataFrame with both values and lists
39,103,060
<p>I have a MultiIndex <code>DataFrame</code>:</p> <pre><code> predicted_y actual_y predicted_full actual_full subj_id org_clip 123 3 2 5 [1, 2, 3] [4, 5, 6] </code></pre> <p>That I wish to add a new row to:</p> <pre><...
2
2016-08-23T13:48:34Z
39,103,254
<p>Make at least one of the sublists an array of dtype <code>object</code>:</p> <pre><code>In [27]: df.loc[('321', 4),['predicted_y', 'actual_y', 'predicted_full', 'actual_full']] = ( [20, 50, np.array((10, 20, 30), dtype='O'), [40, 50, 60]]) In [28]: df Out[28]: predicted_y actual_y pre...
2
2016-08-23T13:56:49Z
[ "python", "python-3.x", "pandas", "dataframe", "multi-index" ]
Adding a new row to a MultiIndex pandas DataFrame with both values and lists
39,103,060
<p>I have a MultiIndex <code>DataFrame</code>:</p> <pre><code> predicted_y actual_y predicted_full actual_full subj_id org_clip 123 3 2 5 [1, 2, 3] [4, 5, 6] </code></pre> <p>That I wish to add a new row to:</p> <pre><...
2
2016-08-23T13:48:34Z
39,103,475
<p>You can let <code>pd.Series</code> handle the <code>dtypes</code></p> <pre><code>row_to_append = pd.Series([20, 50, [10, 20, 30], [40, 50, 60]]) cols = ['predicted_y', 'actual_y', 'predicted_full', 'actual_full'] df.loc[(321, 4), cols] = row_to_append.values df </code></pre> <p><a href="http://i.stack.imgur.com/n...
3
2016-08-23T14:05:49Z
[ "python", "python-3.x", "pandas", "dataframe", "multi-index" ]
when exporting my data into csv, my output is in disorder maybe because of tabs and whitespaces
39,103,075
<pre><code>class Job(Item): a_title = Field() b_url = Field() c_date = Field() d_pub = Field() class stage(Spider): name = 'jobs' start_urls = ['http://www.stagiaire.com/offres-stages.html/'] def parse(self, response): for i in response.css('.info-offre'): title = i....
1
2016-08-23T13:49:45Z
39,110,723
<p>Since you are not using scrapy ItemLoader's you put concrete lists to your results where you are probably expecting single elements. To fix this use <code>extract_first()</code> instead of <code>extract()</code> to get only the first xpath selection.</p> <p>In your case it should be:</p> <pre><code>title = i.css('...
1
2016-08-23T21:10:46Z
[ "python", "web-scraping", "scrapy" ]
Data manipulation in Pandas/Python
39,103,090
<p>It seems to be simple data manipulation operation. But I am stuck at this.</p> <p>I have a recommendation dataset for a campaign. </p> <pre><code>Masteruserid content 1 100 1 101 1 102 2 100 2 101 2 110 </code></pre> <p>Now for each user we...
2
2016-08-23T13:50:11Z
39,103,962
<pre><code>def add_content(df, gc, k=5): n = len(df) gcs = set(gc.squeeze()) if n &lt; k: choices = list(gcs.difference(df.content)) mc = np.random.choice(choices, k - n, replace=False) ids = np.repeat(df.Masteruserid.iloc[-1], k - n) data = dict(Masteruserid=ids, content=mc)...
2
2016-08-23T14:27:45Z
[ "python", "pandas" ]
Data manipulation in Pandas/Python
39,103,090
<p>It seems to be simple data manipulation operation. But I am stuck at this.</p> <p>I have a recommendation dataset for a campaign. </p> <pre><code>Masteruserid content 1 100 1 101 1 102 2 100 2 101 2 110 </code></pre> <p>Now for each user we...
2
2016-08-23T13:50:11Z
39,106,711
<p>Try this, using this as recs list, </p> <pre><code>df2['global_content'] 0 100 1 300 2 301 3 101 4 400 5 500 6 401 7 501 recs = pd.DataFrame() recs['content'] = df.groupby('Masteruserid')['content'].apply(lambda x: list(x) + np.random.choice(df2[~df2.isin(list(x))].dropna().values.flatten(...
0
2016-08-23T16:47:36Z
[ "python", "pandas" ]
pandas DataFrame combine_first method converts boolean in floats
39,103,144
<p>I'm running into a strange issue where combine_first method is causing values stored as bool to be upcasted into float64s. Example:</p> <pre><code>In [1]: import pandas as pd In [2]: df1 = pd.DataFrame({"a": [True]}) In [3]: df2 = pd.DataFrame({"b": ['test']}) In [4]: df2.combine_first(df1) Out[4]: a b ...
3
2016-08-23T13:52:43Z
39,104,484
<p>Somewhere along the chain of events to get to a combined dataframe, potential missing values had to be addressed. I'm aware that nothing is missing in your example. <code>None</code> and <code>np.nan</code> are not <code>int</code>, or <code>bool</code>. So in order to have a common <code>dtype</code> that contai...
5
2016-08-23T14:53:07Z
[ "python", "pandas", "dataframe" ]
ord function in python2.7 and python 3.4 are different?
39,103,164
<p>I have been running a script where I use the <code>ord()</code> function and for whatever the reason in python 2.7, it accepts the unicode string character just as it requires and outputs an integer.</p> <p>In python 3.4, this is not so much the case. This is the output of error that is being produced : </p> <pre>...
1
2016-08-23T13:53:27Z
39,103,245
<p>You are passing in an <em>integer</em> to <code>ord()</code> in Python 3. That's because you are iterating over a <code>bytes</code> object in Python 3 (the first element in the tuple return value from <a href="https://docs.python.org/3/library/socket.html#socket.socket.recvfrom" rel="nofollow"><code>socket.recvfrom...
5
2016-08-23T13:56:34Z
[ "python", "python-2.7", "python-3.x" ]
ord function in python2.7 and python 3.4 are different?
39,103,164
<p>I have been running a script where I use the <code>ord()</code> function and for whatever the reason in python 2.7, it accepts the unicode string character just as it requires and outputs an integer.</p> <p>In python 3.4, this is not so much the case. This is the output of error that is being produced : </p> <pre>...
1
2016-08-23T13:53:27Z
39,103,293
<p>I think the difference is that in Python 3 the <code>sock.recvfrom(...)</code> call returns bytes while Python 2.7 recvfrom returns a string. So <code>ord</code> did not change but what is being passed to ord has changed. </p> <p><a href="https://docs.python.org/2.7/library/socket.html#socket.socket.recvfrom" rel="...
1
2016-08-23T13:58:47Z
[ "python", "python-2.7", "python-3.x" ]
Declaring a Python list of expressions without evaluating each
39,103,207
<p>I have a large number of arithmetic expressions that I store in a list. For example</p> <pre><code>exp_list = [exp1, exp2, ...,exp10000] </code></pre> <p>I also have indices of the few expressions I need to evaluate.</p> <pre><code>inds = [ind1,ind2,...,ind10] exp_selected = [exp_list[i] for i in inds ] </code><...
0
2016-08-23T13:55:08Z
39,103,338
<p>If those expressions share some pattern and can be created 'mid-air' it would be better to use generator instead of just creating the list. Especially if you don't need to remember the results, but just check if any (or all) of them are true/false.</p>
0
2016-08-23T14:00:25Z
[ "python", "list" ]
Declaring a Python list of expressions without evaluating each
39,103,207
<p>I have a large number of arithmetic expressions that I store in a list. For example</p> <pre><code>exp_list = [exp1, exp2, ...,exp10000] </code></pre> <p>I also have indices of the few expressions I need to evaluate.</p> <pre><code>inds = [ind1,ind2,...,ind10] exp_selected = [exp_list[i] for i in inds ] </code><...
0
2016-08-23T13:55:08Z
39,103,788
<p>Suppose you decide to store you expressions as lambdas (to avoid them being immediately evaluated) then you could selectively evaluate them with a simple list comprehension:</p> <pre><code>exp_list = [lambda: 1+2, lambda: 3+4, lambda: 5+6, lambda: 7+8] inds = [1, 3] print [exp() for i, exp in enumerate(exp_list) if...
1
2016-08-23T14:19:07Z
[ "python", "list" ]
Calculate values w/ statsmodels given a formula and parameters
39,103,234
<p>I have fitted a model given a Poly-3 function and extracted the found parameters</p> <pre><code>model = smf.ols(formula='A ~ B + I(B ** 2.0) + I(B ** 3.0)', data=sp) poly_3 = model.fit() params = poly_3.params.values </code></pre> <p>I want to save the params for later use since I don't want to train the model eac...
1
2016-08-23T13:56:08Z
39,195,186
<p>please refer to this <a href="http://stackoverflow.com/questions/16420407/python-statsmodels-ols-how-to-save-learned-model-to-file">Python statsmodels OLS: how to save learned model to file</a> you can save your model results to a pickle file, then load the model from the pickle file and use it to predict.</p> <p>...
0
2016-08-28T19:51:02Z
[ "python", "pandas", "statsmodels" ]
How to import own angularjs javascript files automatically / dynamically?
39,103,289
<p>I am trying to construct a web application using a REST API and an Angular Frontend. Apart from importing all the Angular JS framework files and extensions I also have to add script tags for every single javascript file I wrote on my own (which will be a lot for all the controllers). I have heard about different so...
0
2016-08-23T13:58:40Z
39,104,479
<p>You can use webpack to compile a bunch of files together - it doesn't have to be a single page application. This will also solve the reference order issue.</p> <p>This page explains very well different methodologies: <a href="https://webpack.github.io/docs/motivation.html" rel="nofollow">https://webpack.github.io/d...
1
2016-08-23T14:52:57Z
[ "javascript", "python", "angularjs", "rest" ]
Python 3.5 CSV reading multiline field issue
39,103,307
<p>I am trying to parse a CSV file, which has multi-line string in one of the fields (field 6). I can read the field fine, but when I try to process each line from that field, it gives me one character on a new line at a time instead of a line at a time. Any ideas what am I doing wrong?</p> <pre><code>def lookup(ip, r...
0
2016-08-23T13:59:13Z
39,103,524
<p>When you are using </p> <blockquote> <p>for subnet in row[5]:</p> <pre><code> print(subnet) </code></pre> </blockquote> <p>You are iterating over a string, which returns a single char each time.</p> <p>It would be more helpful if you could give us an example to see exactly what do you mean.</p>
0
2016-08-23T14:07:50Z
[ "python", "csv", "reader" ]
Python 3.5 CSV reading multiline field issue
39,103,307
<p>I am trying to parse a CSV file, which has multi-line string in one of the fields (field 6). I can read the field fine, but when I try to process each line from that field, it gives me one character on a new line at a time instead of a line at a time. Any ideas what am I doing wrong?</p> <pre><code>def lookup(ip, r...
0
2016-08-23T13:59:13Z
39,103,540
<p>well it makes sense, since each element in row is a string, and when you iterate a string you get one character at a time.</p> <p>you can split the string to get your desired result:</p> <pre><code>for row in l: for subnet in row[5].split('\r\n'): print(subnet) </code></pre> <p>note:</p> <p>\r\n mean...
1
2016-08-23T14:08:32Z
[ "python", "csv", "reader" ]
Call js function in python to use document.getElementById
39,103,321
<p>I've recently asked about a way to call a js function in python. People gave me advice such as using js2py, or pyv8, but the problem is that it does not allow me to use the following js command: </p> <pre><code>document.getElementById("example"); </code></pre> <p>So my question is: Is there a way to call js from a...
1
2016-08-23T13:59:43Z
39,103,584
<p><em>If calling js function in python</em> means: <em>How can I select node with specific id?</em>, then you can use BeautifulSoup for it:</p> <pre><code>from bs4 import BeautifulSoup html_doc = "&lt;html&gt;&lt;head&gt;&lt;title&gt;&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;div id='example'&gt;&lt;/body&gt;&lt;/ht...
1
2016-08-23T14:10:36Z
[ "javascript", "python", "socket.io", "getelementbyid", "django-socketio" ]
Find all the div tags find class = "post-" followed by some numbers?
39,103,486
<p>I want to find all the div tags with class = "post-some number some text " There are multiple div tags e.g.</p> <pre><code>&lt;div class="post-3562 some text"&gt; &lt;div class="post-some text"&gt; &lt;div class="post-some text"&gt; &lt;div class="post-1324 some text"&gt; &lt;div class="post-4540 some text"&gt; &lt...
1
2016-08-23T14:06:19Z
39,104,614
<p>The following Regex will match your test cases:</p> <pre><code>/&lt;div +class= *"post-\d+.*&gt;/g </code></pre> <p>Regex Tester link: <a href="https://regex101.com/r/cX1qZ7/1" rel="nofollow">https://regex101.com/r/cX1qZ7/1</a></p>
-1
2016-08-23T15:00:03Z
[ "python", "regex", "beautifulsoup" ]
Find all the div tags find class = "post-" followed by some numbers?
39,103,486
<p>I want to find all the div tags with class = "post-some number some text " There are multiple div tags e.g.</p> <pre><code>&lt;div class="post-3562 some text"&gt; &lt;div class="post-some text"&gt; &lt;div class="post-some text"&gt; &lt;div class="post-1324 some text"&gt; &lt;div class="post-4540 some text"&gt; &lt...
1
2016-08-23T14:06:19Z
39,104,963
<p>You can pass in a regular expression as the value of your <code>class_</code> parameter, like so:</p> <pre><code>soup.find_all(name='div', class_=re.compile(r'^post-\d+$')) </code></pre> <p>Full Program:</p> <pre><code>from bs4 import BeautifulSoup import re soup = BeautifulSoup(''' &lt;root&gt; &lt;div class="p...
3
2016-08-23T15:14:45Z
[ "python", "regex", "beautifulsoup" ]
Get the names and count of all buckets in AWS S3
39,103,561
<p>I'm new to Boto3 and AWS API, and I want to get the list of buckets' names and the count of the available buckets in S3. </p> <p>Any help is appreciated.</p>
0
2016-08-23T14:09:30Z
39,110,079
<p>This script will help you to list all the bucket names and also get the count.</p> <pre><code>import boto from boto.s3.connection import OrdinaryCallingFormat conn = boto.connect_s3(calling_format=OrdinaryCallingFormat()) count = 0 print ("Bucket names: ") for bucket in conn.get_all_buckets(): print (bucke...
2
2016-08-23T20:24:30Z
[ "python", "python-3.x", "amazon-web-services", "amazon-s3", "boto3" ]
Get the names and count of all buckets in AWS S3
39,103,561
<p>I'm new to Boto3 and AWS API, and I want to get the list of buckets' names and the count of the available buckets in S3. </p> <p>Any help is appreciated.</p>
0
2016-08-23T14:09:30Z
39,114,716
<p>To get all buckets in your account:</p> <pre><code>import boto3 s3 = boto3.resource('s3') bucket_list = [bucket.name for bucket in s3.buckets.all()] print len(bucket_list) print bucket_list </code></pre>
1
2016-08-24T04:57:30Z
[ "python", "python-3.x", "amazon-web-services", "amazon-s3", "boto3" ]
How to use BeautifulSoup to get only strings from tags that have specific start?
39,103,570
<p>I am scraping usernames and all of them are in the same a tag and their hrefs all start the same, like this:</p> <pre><code>&lt;a href="http://lolprofile.net/summoner/eune/Sadastyczny" class="link5"&gt;Sadastyczny&lt;/a&gt; </code></pre> <p>I tried finding only if they have the class link5 but there are other valu...
1
2016-08-23T14:09:51Z
39,103,743
<p>From the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments" rel="nofollow">BeautifulSoup documentation</a>. </p> <p>Using a regular expression you can match the sites. If you have never heard of regular expressions you can use this:</p> <p><code>soup.find_all(href=re.compile("ht...
1
2016-08-23T14:17:33Z
[ "python", "beautifulsoup" ]
Trying to adapt TensorFlow's MNIST example gives NAN predictions
39,103,614
<p>I'm playing with TensorFlow, using the 'MNIST for beginners' example (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_softmax.py" rel="nofollow">initial code here</a>). I've made some slight adaptions:</p> <pre><code>mnist = input_data.read_data_sets(FLAGS.dat...
1
2016-08-23T14:11:51Z
39,109,819
<p>The real MNIST data contains very sparse data. Most of the values are zero. Your synthetic data is uniformly distributed (see <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.random.rand.html" rel="nofollow">numpy</a>). The W and b trained assume a sparse input. It is possible the model you ...
0
2016-08-23T20:05:42Z
[ "python", "machine-learning", "tensorflow" ]
Trying to adapt TensorFlow's MNIST example gives NAN predictions
39,103,614
<p>I'm playing with TensorFlow, using the 'MNIST for beginners' example (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_softmax.py" rel="nofollow">initial code here</a>). I've made some slight adaptions:</p> <pre><code>mnist = input_data.read_data_sets(FLAGS.dat...
1
2016-08-23T14:11:51Z
39,112,876
<p>What is messing you up is that log(softmax) isn't numerically stable.</p> <p><a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#softmax_cross_entropy_with_logits" rel="nofollow">The softmax cross entropy with logits loss</a> is numerically stabilised. </p> <p>so, you can do</p> <pre><code>...
0
2016-08-24T01:01:46Z
[ "python", "machine-learning", "tensorflow" ]
Restore CDATA during lxml serialization
39,103,615
<p>I know that I can preserve CDATA sections during XML parsing, using the following:</p> <pre><code>from lxml import etree parser = etree.XMLParser(strip_cdata=False) root = etree.XML('&lt;root&gt;&lt;![CDATA[test]]&gt;&lt;/root&gt;', parser) </code></pre> <p>See <a href="http://lxml.de/api.html#cdata" rel="nofollo...
0
2016-08-23T14:11:58Z
39,104,395
<p>Something like this?</p> <pre><code>from lxml import etree parser = etree.XMLParser(strip_cdata=True) root = etree.XML('&lt;root&gt;&lt;x&gt;&lt;![CDATA[&lt;test&gt;]]&gt;&lt;/x&gt;&lt;/root&gt;', parser) print etree.tostring(root) for elem in root.findall('x'): elem.text = etree.CDATA(elem.text) print etree....
1
2016-08-23T14:49:06Z
[ "python", "lxml", "cdata" ]
Comparing two arrays which have very dispersed values
39,103,641
<p>I have a very sparse array that looks like:</p> <pre><code>Array A: min = -68093253945.0 max=8.54631971208e+13 Array B: min=-1e+15 max = 1.87343e+14 </code></pre> <p>And also each array will have concentration at certain levels e.g. near 2000, near 1m, near 0.05 and so on.</p> <p>I am trying to compare these two ...
1
2016-08-23T14:13:13Z
39,380,663
<p>@sascha's suggestion of using AstroML was a good one, but the <code>knuth</code> and <code>freedman</code> versions seem to take astronomically long (excuse the pun), and the <code>blocks</code> version simply thinned the blocks.</p> <p>I took the sigmoid of each value via <code>from scipy.special import expit</cod...
0
2016-09-07T23:59:34Z
[ "python", "scipy", "histogram", "normalization", "binning" ]
How can I recursively import every file in a directory and run a function in each one?
39,103,649
<p>In essence, I'm trying to make an extension system, where each plugin hooks into the important functions via the respective function in the file. I need a way to run this function and get the return value, by just looping through the "plugins" directory.</p> <p>Any way I could do this?</p>
-2
2016-08-23T14:13:37Z
39,103,784
<p>you can import files dinamicaly using <code>__import__</code></p> <p>so you just need to iterate the folder looking for py files (not pyc) and import them</p> <pre><code>for root, dirs, files in os.walk(src_path): for f in files: if f.endswith('.py'): m = __import__(f) </code></pre> <p><co...
0
2016-08-23T14:19:00Z
[ "python", "python-3.x" ]
Extract variable names and values using REGEX in Python from a text file
39,103,676
<p>I am trying to read a large text file, containing variable names and corresponding values (see below for small example). Names are all upper case and the value is usually separated by a periods and whitespaces, but if the variable name is too long it is separated by only whitespaces.</p> <pre><code>WATER DEPTH .......
1
2016-08-23T14:14:20Z
39,103,904
<p>Use <code>[A-Z]{2,}(?:\s+[A-Z]+)*</code></p> <p><code>[A-Z]{2,}</code> looks for uppercase words at least 2 in length</p> <p><code>(?:\s+[A-Z]+)*</code> is a capture group for if there are multiple words in the label</p> <p><strong>EDIT</strong></p> <p>To handle the case in your comment I'd recommend:</p> <pre>...
0
2016-08-23T14:24:43Z
[ "python", "regex" ]
Extract variable names and values using REGEX in Python from a text file
39,103,676
<p>I am trying to read a large text file, containing variable names and corresponding values (see below for small example). Names are all upper case and the value is usually separated by a periods and whitespaces, but if the variable name is too long it is separated by only whitespaces.</p> <pre><code>WATER DEPTH .......
1
2016-08-23T14:14:20Z
39,103,905
<p>If you ever want to take out leading/trailing white space, you can use the <code>.strip()</code> method.</p> <p><a href="http://www.tutorialspoint.com/python/string_strip.htm" rel="nofollow">Python String strip</a></p> <pre><code>stripped_values = [raw.strip() for raw in re.findall('(?&lt;=\s.)[A-Z\s]+', line)] </...
0
2016-08-23T14:24:44Z
[ "python", "regex" ]
Extract variable names and values using REGEX in Python from a text file
39,103,676
<p>I am trying to read a large text file, containing variable names and corresponding values (see below for small example). Names are all upper case and the value is usually separated by a periods and whitespaces, but if the variable name is too long it is separated by only whitespaces.</p> <pre><code>WATER DEPTH .......
1
2016-08-23T14:14:20Z
39,104,657
<p>You can use the following expression along with <code>re.finditer()</code>:</p> <pre><code>(?P&lt;category&gt;[A-Z][A-Z- ]+[A-Z]) [. ]+ (?P&lt;value&gt;-?\d[.\d]+)\ (?P&lt;unit&gt;M|DEG|KN) </code></pre> <p>See <a href="https://regex101.com/r/wW2tL0/3" rel="nofollow"><strong>a demo on regex101.com</strong></a>. <...
0
2016-08-23T15:01:37Z
[ "python", "regex" ]
how to communicate with a router
39,103,719
<p>I have written a script to perform telnet, which i wanted to use for sending commands to my Device Under Test (router).</p> <p>My Telnet Script:</p> <pre><code>import sys, time, telnetlib sys.path.insert(0, '/tmp') import options def telnet_connect(): HOST = "%s" %options.DUT_telnet_ip PORT = "%...
1
2016-08-23T14:16:38Z
39,104,175
<p>Try to make this more like a class:</p> <pre><code>import sys, time, telnetlib sys.path.insert(0, '/tmp') class TelnetConnection(): def init(self, HOST, PORT): self.tn = telnetlib.Telnet(HOST, PORT, 10) def connect(self, username, password): tn = self.tn tn.write("\n") ...
1
2016-08-23T14:38:00Z
[ "python", "telnet" ]
Dreamhost PyCharm Django Python 3 Launching a Site
39,103,775
<p>I'm new to python/django and created a simple django website using PyCharm. The site works fine running on my computer, but I'm really lost when it comes to taking the site onto my host (Dreamhost). I'm able to upload the files to the correct directories fine, and I believe I made the correct changes for the datab...
-4
2016-08-23T14:18:36Z
39,103,882
<p>You should not run your Django application using <code>python manage.py runserver</code> on production. How to run the application on Django depends on the server (apache, nginx) you want to use</p> <p>For apache - <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">https:...
0
2016-08-23T14:23:42Z
[ "python", "mysql", "django", "dreamhost" ]
boto3 and connecting to custom url
39,103,814
<p>I have a test environment that mimics the S3 envrionment, and I want to write some test scripts using boto3. How can I connect to that service? </p> <p>I tried:</p> <pre><code> client = boto3.client('s3', region_name="us-east-1", endpoint_url="http://mymachine") client = boto3.client('iam', region_name="us-east...
0
2016-08-23T14:20:12Z
39,105,304
<p>Please use as below :</p> <pre><code>import boto3 client = boto3.client( 's3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY,) </code></pre> <p>Please check this link for more ways to configure AWS credentials. <a href="http://boto3.readthedocs.io/en/latest/guide/configuration.html" rel="nofollo...
0
2016-08-23T15:32:30Z
[ "python", "python-2.7", "boto3" ]
boto3 and connecting to custom url
39,103,814
<p>I have a test environment that mimics the S3 envrionment, and I want to write some test scripts using boto3. How can I connect to that service? </p> <p>I tried:</p> <pre><code> client = boto3.client('s3', region_name="us-east-1", endpoint_url="http://mymachine") client = boto3.client('iam', region_name="us-east...
0
2016-08-23T14:20:12Z
39,117,142
<p>1. boto API always look for credential to pass on to connecting services, there is no way you can access AWS resources using bot without a access key and password. </p> <p>If you intended to use some other method, e.g. Temporary Security Credentials, your AWS admin must setup roles and etc , to allow the VM instanc...
-1
2016-08-24T07:36:51Z
[ "python", "python-2.7", "boto3" ]
No module named matplotlib with matplotlib installed Python 2.7
39,103,877
<p>I am fairly new to python as well as matplotlib and I can't get it to work. From the code :</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G.add_node("spam") G.add_edge(1,2) plt.show() </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File ...
0
2016-08-23T14:23:19Z
39,104,025
<p>You have 2 pythons installed on your machine, one is the standard python that comes with MacOSX and the second is the one you installed with ports (this is the one that has matplotlib installed in its library, the one that comes with macosx does not).</p> <pre><code>/usr/bin/python </code></pre> <p>Is the standard...
1
2016-08-23T14:30:40Z
[ "python", "python-2.7", "matplotlib" ]
No module named matplotlib with matplotlib installed Python 2.7
39,103,877
<p>I am fairly new to python as well as matplotlib and I can't get it to work. From the code :</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G.add_node("spam") G.add_edge(1,2) plt.show() </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File ...
0
2016-08-23T14:23:19Z
39,105,267
<p>You can check whether <code>usr/lib/python2.7/dist-packages</code> (if you are pretty sure matplotlib is installed here) is in your <code>sys.path</code>.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path </code></pre> <p>If you don't find the path in the list, you can add lines below before importing m...
0
2016-08-23T15:30:57Z
[ "python", "python-2.7", "matplotlib" ]
No module named matplotlib with matplotlib installed Python 2.7
39,103,877
<p>I am fairly new to python as well as matplotlib and I can't get it to work. From the code :</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G.add_node("spam") G.add_edge(1,2) plt.show() </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File ...
0
2016-08-23T14:23:19Z
39,105,360
<p>thanks for your help. It appeared the wrong Python Version was used. By using </p> <pre><code>alias python=/usr/lib/python </code></pre> <p>it was fixed, but only temporarly.</p> <p>To permanently set the alias correctly, I had to edit the ~/.bash_aliases and insert:</p> <pre><code>alias python=/usr/bin/python2....
0
2016-08-23T15:34:58Z
[ "python", "python-2.7", "matplotlib" ]
How to fire a query with a number of variables from local array
39,103,972
<p>Sorry if title is not properly set. The problem is I want to filter DataFrame by comparing df's column with a couple of values from an array:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) array = np.arange(10) #simple query df....
0
2016-08-23T14:28:10Z
39,104,091
<p>This returns an integer, accepted by the <code>%d</code> format</p> <pre><code>df.query('A == %d' %array[3]) </code></pre> <p>This returns an array, not the same object!, refused by the latter</p> <pre><code>df.query('A == [%s]' %array[3:5]) </code></pre> <p>I suggest:</p> <pre><code>df.query('A == [%s]' % ","....
1
2016-08-23T14:33:55Z
[ "python", "pandas" ]
How to fire a query with a number of variables from local array
39,103,972
<p>Sorry if title is not properly set. The problem is I want to filter DataFrame by comparing df's column with a couple of values from an array:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) array = np.arange(10) #simple query df....
0
2016-08-23T14:28:10Z
39,104,267
<p><code>numexpr</code> doesn't support slicing so the closest you can get is to create a variable with the required data, then reference it from the query (note that the slicing here creates a view of the original <code>array</code> and doesn't perform a copy):</p> <pre><code>sliced = array[3:6] df.query('A == @slice...
2
2016-08-23T14:43:01Z
[ "python", "pandas" ]
pandas read_csv on a *.dat file delimited with cedilla not splitting into columns in dataframe
39,104,079
<p>This is my first time working on pandas so pardon my ignorance. My requirement is to download a file from S3 onto Ec2 and put the dat file onto a dataframe. This is how my input file data looked </p> <pre><code>1Ç70Ç23929Ç4341Ç1111Ç0Ç0Ç1ÇAAÇ012ÇFillerÇ 1Ç75Ç45555Ç4324Ç2222Ç0Ç0Ç1ÇAAÇ011ÇFillerÇ...
1
2016-08-23T14:33:22Z
39,104,169
<p>Try passing <code>sep='\Ç'</code> as this works for me:</p> <pre><code>In [35]: import pandas as pd import io t="""1Ç70Ç23929Ç4341Ç1111Ç0Ç0Ç1ÇAAÇ012ÇFillerÇ 1Ç75Ç45555Ç4324Ç2222Ç0Ç0Ç1ÇAAÇ011ÇFillerÇ 1Ç76Ç23957Ç4334Ç3333Ç0Ç0Ç1ÇAAÇ011ÇFillerÇ 1Ç72Ç47776Ç4344Ç4444Ç0Ç0Ç1ÇABÇ01...
0
2016-08-23T14:37:48Z
[ "python", "pandas", "utf-8" ]
pandas read_csv on a *.dat file delimited with cedilla not splitting into columns in dataframe
39,104,079
<p>This is my first time working on pandas so pardon my ignorance. My requirement is to download a file from S3 onto Ec2 and put the dat file onto a dataframe. This is how my input file data looked </p> <pre><code>1Ç70Ç23929Ç4341Ç1111Ç0Ç0Ç1ÇAAÇ012ÇFillerÇ 1Ç75Ç45555Ç4324Ç2222Ç0Ç0Ç1ÇAAÇ011ÇFillerÇ...
1
2016-08-23T14:33:22Z
39,779,389
<p>As standard practice you may want to open your docs using the codecs package. This will allow you to specify the encoding (UTF-16 in most cases) and the codecs package seems to be very good at deciphering things like line terminators and encoding. </p> <p><a href="http://stackoverflow.com/questions/27896214/reading...
0
2016-09-29T20:26:35Z
[ "python", "pandas", "utf-8" ]
Python import module fails with __init__.py
39,104,139
<p>I have two folders each containing several python modules:</p> <pre> 1. pyA: /a /b /c 2. pyB: /d /e /f </pre> <p>I have added the <code>__init__.py</code> (empty) to both folders. However when I try to import pyB in pyA, I get the "ImportError: No module named pyB".</p> <p>I have looked through the alr...
-2
2016-08-23T14:36:25Z
39,104,664
<p>Until unless root folder of pyB is in PYTHONPATH, this is expected. Files inside pyA folder is not aware of where pyB is.</p> <p>(Or) please do below:</p> <pre><code>import sys sys.path.append(/path/to/parentfolderofPyB) import pyB </code></pre> <p>Alternatively if you are sure that you don't use pyA in pyB, you...
0
2016-08-23T15:01:46Z
[ "python", "import" ]
Post CSV file contents as data in Python
39,104,216
<p>Again, relatively new to python, so this may seem like a no-brainer to some people. My apologies in advance. </p> <p>I would like to know how to open a .csv file and send the contents as data in a post session. </p> <p>Something kind of like this: </p> <pre><code>userData = json.loads(loginResponse.text) sessionT...
0
2016-08-23T14:40:09Z
39,104,448
<p>If you want to pass the file contents as simply a big blob of text, don't use the csv module at all. Just use the normal file read() method:</p> <pre><code>uploadResponse = loginAS.post(..., data=csvFile.read()) </code></pre>
0
2016-08-23T14:51:16Z
[ "python", "python-3.x", "csv", "post" ]
No relationship of type when opening Word document with Python
39,104,325
<p>When trying to open a <code>.dot</code> file with <code>python-docx</code>, I am getting the error:</p> <pre><code>KeyError: "no relationship of type 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' in collection" </code></pre> <p>This is the code in question:</p> <pre><code>fr...
0
2016-08-23T14:46:03Z
39,104,723
<p>How did you generate the input file? <a href="https://github.com/python-openxml/python-docx/issues/204" rel="nofollow">Here</a> it is an issue about the type when you save the file as <em>Strict Open XML Document</em>. Try the standard <em>Word document</em>.</p> <p>You can get more informations about relations ins...
2
2016-08-23T15:04:40Z
[ "python", "ms-word", "python-docx" ]
How to differ formsets in django when using modelformset_factory?
39,104,332
<p>Let's say I have an Contact object and I want to have two groups of contact Formsets in django(1.8) divided by <strong>fieldset</strong> tag in html template. I use modelformset_factory. Regardless I use one or two different factory functions, fields in these two formsets have same id in html. Since http.Request.bod...
0
2016-08-23T14:46:20Z
39,104,492
<p>The <code>modelformset_factory</code> class returns a FormSet class. This FormSet class has a optional <code>prefix</code> argument, similar to Form classes. </p> <pre><code>contacts_escalation_formset_new = contacts_formset( prefix='escalation', queryset=models.Contact.objects.none(), ) contacts_other_for...
1
2016-08-23T14:53:25Z
[ "python", "django", "django-forms", "django-templates", "django-views" ]
Going through all arguments given and checking their values
39,104,401
<p>I am pretty new to Python and I tried to make a simple program.<br> I tried to define a function that takes any given number of arguments and prints all even numbers given.<br> However, I do not know how to know how many numbers were given, and mostly how to go through them, or more precisely, how to make a loop tha...
1
2016-08-23T14:49:23Z
39,104,497
<p>You can iterate over <code>arg</code> itself, it is simply a tuple of the arguments</p> <pre><code>def even_number_filter(*arg): for i in arg: if i % 2 == 0: print('{} is an even number'.format(i)) &gt;&gt;&gt; even_number_filter(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 2 is an even number 4 is an ev...
2
2016-08-23T14:53:41Z
[ "python", "loops", "for-loop", "arguments" ]
Going through all arguments given and checking their values
39,104,401
<p>I am pretty new to Python and I tried to make a simple program.<br> I tried to define a function that takes any given number of arguments and prints all even numbers given.<br> However, I do not know how to know how many numbers were given, and mostly how to go through them, or more precisely, how to make a loop tha...
1
2016-08-23T14:49:23Z
39,104,668
<p>To do this using set &amp; list comprehension:</p> <pre><code>print {x for x in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} if x % 2 == 0} print [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 == 0] </code></pre> <p>Produces:</p> <pre><code>set([8, 2, 4, 10, 6]) [2, 4, 6, 8, 10] </code></pre> <p>Where possible you shou...
1
2016-08-23T15:01:59Z
[ "python", "loops", "for-loop", "arguments" ]
Going through all arguments given and checking their values
39,104,401
<p>I am pretty new to Python and I tried to make a simple program.<br> I tried to define a function that takes any given number of arguments and prints all even numbers given.<br> However, I do not know how to know how many numbers were given, and mostly how to go through them, or more precisely, how to make a loop tha...
1
2016-08-23T14:49:23Z
39,104,828
<p>Ideally, take the arguments as an iterable (a list or a generator) rather than varargs. Then, this is the ideal time to use a list comprehension:</p> <pre class="lang-py prettyprint-override"><code>def even_numbers(numbers): return [ num for num in numbers if num % 2 == 0 ] def even_number...
0
2016-08-23T15:09:20Z
[ "python", "loops", "for-loop", "arguments" ]