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
A python regex that matches the regional indicator character class
39,108,298
<p>Flags in emoji are indicated by a pair of <a href="https://en.wikipedia.org/wiki/Regional_Indicator_Symbol" rel="nofollow">Regional Indicator Symbols</a>. I would like to write a python regex to insert spaces between a string of emoji flags. </p> <p>For example, this string is two Brazilian flags:</p> <pre><...
4
2016-08-23T18:26:36Z
39,108,371
<p>I believe you're using Python 2.7 in Windows or Mac, which has the narrow 16-bit Unicode build - Linux/Glibc usually have 32-bit full unicode, also Python 3.5 has wide Unicode on all platforms. </p> <p>What you see is the one code being split into a surrogate pair. Unfortunately it also means that you cannot use a ...
7
2016-08-23T18:32:00Z
[ "python", "regex", "unicode" ]
Numpy unicode to int
39,108,376
<p>Using python 2.7 through Pycharm</p> <p>I have a python code - which is very simple. </p> <pre><code>a = [2, 3, 4, 5] b = [30,32,33,34] c = ['test1', 'test2', 'test3', 'test4'] a = np.asarray(a) # -- Similarly for b and c </code></pre> <p>I converted these lists to numpy array.</p> <p>Then I did the following</...
0
2016-08-23T18:32:12Z
39,108,513
<pre><code>a = np.array(a) b = np.array(b) </code></pre> <blockquote> <p>Now how can I access the columns of a,b and do some arithmetic operations on those values.</p> </blockquote> <pre><code>a + b </code></pre>
0
2016-08-23T18:40:36Z
[ "python", "python-2.7", "numpy", "unicode" ]
Numpy unicode to int
39,108,376
<p>Using python 2.7 through Pycharm</p> <p>I have a python code - which is very simple. </p> <pre><code>a = [2, 3, 4, 5] b = [30,32,33,34] c = ['test1', 'test2', 'test3', 'test4'] a = np.asarray(a) # -- Similarly for b and c </code></pre> <p>I converted these lists to numpy array.</p> <p>Then I did the following</...
0
2016-08-23T18:32:12Z
39,108,526
<p>Because the last column is text, the other two columns are converted to text also. You can have only one type for one matrix. The solution would be a structured array:</p> <pre><code>a = [2, 3, 4, 5] b = [30,32,33,34] c = ['test1', 'test2', 'test3', 'test4'] matrix = np.array(zip(a,b,c), dtype=[('a',int),('b',int),...
1
2016-08-23T18:41:17Z
[ "python", "python-2.7", "numpy", "unicode" ]
Surviving icinga2 restart in a python requests stream
39,108,449
<p>I have been working on a chatbot interface to icinga2, and have not found a persistent way to survive the restart/reload of the icinga2 server. After a week of moving try/except blocks, using requests sessions, et al, it's time to reach out to the community.</p> <p>Here is the current iteration of the request funct...
1
2016-08-23T18:36:33Z
39,171,305
<p>I wound up getting advice on IRC to reorder the try/except blocks and make sure they were in the right places. Here's the working result.</p> <pre><code>def i2api_request(url, headers={}, data={}, stream=False, *, auth=api_auth, ca=api_ca): ''' Do not call this function directly; it's a helper for the i2* comma...
0
2016-08-26T16:59:26Z
[ "python", "python-requests", "icinga" ]
Find and select a required word from a sentence?
39,108,452
<p>I am trying to get <code>raw_input</code> from user and then find a required word from that input. If the required word is there, then a function runs. So I tried <code>.split</code> to split the input but how do I find if the required word is in the list.</p>
2
2016-08-23T18:36:36Z
39,108,469
<p>It's really simple to get this done. Python has an <code>in</code> operator that does exactly what you need. You can see if a word is present in a string and then do whatever else you'd like to do.</p> <pre><code>sentence = 'hello world' required_word = 'hello' if required_word in sentence: # do whatever you'd...
6
2016-08-23T18:37:56Z
[ "python", "python-2.7" ]
Find and select a required word from a sentence?
39,108,452
<p>I am trying to get <code>raw_input</code> from user and then find a required word from that input. If the required word is there, then a function runs. So I tried <code>.split</code> to split the input but how do I find if the required word is in the list.</p>
2
2016-08-23T18:36:36Z
39,109,444
<p>Harrison's way is one way. Here are other ways:</p> <p>Way 1:</p> <pre><code>sentence = raw_input("enter input:") words = sentence.split(' ') desired_word = 'test' if desired_word in words: # do required operations </code></pre> <p>Way 2:</p> <pre><code>import re sentence = raw_input("enter input:") desire...
1
2016-08-23T19:41:38Z
[ "python", "python-2.7" ]
Running two separate (non-nested) for loops within one CSV file
39,108,464
<p>I am currently trying to create a config template using CSV rows and columns as variable output into a text file for one of my network configurations. Here is the code:</p> <pre><code>import sys import os import csv with open('VRRP Mapping.csv', 'rb') as f: reader = csv.reader(f) myfile = open('VRRP fix.tx...
0
2016-08-23T18:37:32Z
39,108,579
<p>You have consumed all lines in your reader object and need to start from the beginning again. Before the second for loop add:</p> <pre><code>f.seek(0) </code></pre> <p>This will bring the pointer back to the beginning of the file so you can loop over it again. <a href="http://www.tutorialspoint.com/python/file_see...
2
2016-08-23T18:45:28Z
[ "python", "networking", "network-programming" ]
Running two separate (non-nested) for loops within one CSV file
39,108,464
<p>I am currently trying to create a config template using CSV rows and columns as variable output into a text file for one of my network configurations. Here is the code:</p> <pre><code>import sys import os import csv with open('VRRP Mapping.csv', 'rb') as f: reader = csv.reader(f) myfile = open('VRRP fix.tx...
0
2016-08-23T18:37:32Z
39,108,587
<p>If you need to read the reader twice, you need to read the file twice. Once you finish a book, you don't just keep reading and expect to find anything else. You need to go back to the beginning. To do that, use</p> <pre><code>f.seek(0) next(reader, None) </code></pre> <p>between the <code>for</code> loops. Not...
2
2016-08-23T18:45:57Z
[ "python", "networking", "network-programming" ]
How to pass commands to gcc through cx_Freeze
39,108,524
<p>How to pass commands to gcc through cx_Freeze 'disutils.core.setup()' arguments?</p> <p>Specifically, i want my <code>.exe</code> file to use relative paths in traceback messages, rather than the path where i build <code>.exe</code> file</p> <p>Here is my setup.py file:</p> <pre><code>setup( name="test", packages...
0
2016-08-23T18:41:10Z
39,148,794
<p>You need to add one additional option to the ones you already have:</p> <pre><code>replace_paths = [("*", "")] </code></pre> <p>That will replace all paths with relative paths. You can also do more interesting things like:</p> <pre><code>replace_paths = [ ("/path/to/python/lib", "&lt;Python&gt;"), ("/path...
1
2016-08-25T15:06:49Z
[ "python", "gcc", "freeze", "cx-freeze" ]
How can I enable the users delete and edit post they create in Django?
39,108,550
<p>I am trying to have users delete and edit post they create. I was told "Post.user needs to be an object instance what you wrote is incorrect." but I am still newer to django and would like to know the steps to do this as I created this project with some help. </p> <p>here is my models </p> <pre><code> from ...
1
2016-08-23T18:42:38Z
39,108,644
<p>You are almost there.</p> <p>in <code>delete</code>, your check should be:</p> <pre><code>request.user == instance.user </code></pre> <p>instead of </p> <pre><code>request.user == Post.user </code></pre> <p>Similarly in <code>post_update</code>, you could do:</p> <pre><code>if instance.user == request.user: ...
2
2016-08-23T18:48:55Z
[ "python", "django", "python-3.x", "edit", "delete-file" ]
updating existing custom field in JIRA with python
39,108,621
<p>Im trying to update an existing custom field within python so that I can automatically add several "values" that can be used in a dropdown box. The below line targets the custom field I want </p> <pre><code>for a in jira.fields(): if a['name'] == "block": #print a.update(fields={'customfield_12100': {'...
0
2016-08-23T18:47:35Z
39,154,220
<p>It can not be done with the OOB Jira install. A third party plugin must be installed <a href="https://marketplace.atlassian.com/plugins/jiracustomfieldeditorplugin/server/overview" rel="nofollow">https://marketplace.atlassian.com/plugins/jiracustomfieldeditorplugin/server/overview</a>. </p>
0
2016-08-25T20:27:46Z
[ "python", "jira" ]
Form Data not refreshing with newest entries
39,108,641
<p>When I add a new customer in customer table and access AddOrderForm form, I don't get the new customer in the choices.But on server restart I am able to get the new customer in the choices list.Any reason ?</p> <p>Customer Table </p> <pre><code>class Customer(db.Model): id = db.Column(db.Integer, primary_key=...
-1
2016-08-23T18:48:52Z
39,108,873
<p>You're only setting the choices once, when you define the form. Instead, re-select them every time you instantiate the form.</p> <p>class AddOrderForm(Form): customer_id = SelectField('Customer', coerce=int)</p> <pre><code>def __init__(self, *args, **kwargs): super(AddOrderForm, self).__init__(*args, **kw...
1
2016-08-23T19:04:36Z
[ "python", "flask", "flask-sqlalchemy", "flask-wtforms" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00...
0
2016-08-23T18:53:30Z
39,108,779
<p>What you can do is</p> <pre><code>if (x // 10**n % 10) == y: ... </code></pre> <p>to check if the <code>n</code>-th digit of <code>x</code> (counting from <strong>right</strong>) is equal to <code>y</code></p>
4
2016-08-23T18:58:00Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00...
0
2016-08-23T18:53:30Z
39,108,800
<p>You have to use divide and modulo for a decimal mask:</p> <pre><code>flags = 18573628 mask = 10000 if (flags / mask) % 10 == 7: do_something </code></pre>
1
2016-08-23T18:58:45Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00...
0
2016-08-23T18:53:30Z
39,108,848
<p>if <code>flags</code> and <code>mask</code> are hexadecimal values, you can do:</p> <pre><code>flags = int("18573628", 16) mask = int("00070000", 16) result = flags &amp; mask print(hex(result)) =&gt; '0x70000' </code></pre>
0
2016-08-23T19:02:29Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00...
0
2016-08-23T18:53:30Z
39,108,851
<p>You can convert the input number into an array of digit numbers and then simply indexing into that array with that specific index or indices would give us those digit(s). For doing that conversion, we can use <code>np.fromstring</code>, like so -</p> <pre><code>In [87]: nums = np.fromstring(str(18573628),dtype=np.u...
1
2016-08-23T19:02:37Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00...
0
2016-08-23T18:53:30Z
39,108,960
<blockquote> <p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code></p> </blockquote> <p>Firstly, bitwise operations like <code>&amp;</code> are <em>bit</em>-wise, which is to say they operate on base-...
1
2016-08-23T19:09:55Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00...
0
2016-08-23T18:53:30Z
39,112,336
<p>Without dealing with the particulars of your case (the SDSS data, which should be documented in the product specification), let's look at some options.</p> <p>First, you need to to know if it is to be read in big-endian or little-endian order (is the first bit to the right or to the left). Then you need to know the...
0
2016-08-23T23:45:32Z
[ "python", "numpy" ]
appending values to Python dictionary
39,108,729
<p>I have a script that reads a CSV file <a href="http://i.stack.imgur.com/CrflA.png" rel="nofollow">csv file</a></p> <pre><code>Asset IP Address,Vulnerability Title 50.103.128.11,Partition Mounting Weakness 10.103.128.11,UDP IP ID Zero 10.103.128.11,Root's umask value is unsafe 0.103.128.11,Root's umask value is unsa...
1
2016-08-23T18:54:38Z
39,108,763
<p>You are trying to reinvent the <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>:</p> <pre><code>from collections import defaultdict d = defaultdict(list) with open('test.csv', 'rb') as f: reader = csv.DictReader(f, delimiter=',') ...
2
2016-08-23T18:57:11Z
[ "python", "list", "csv", "dictionary", "append" ]
appending values to Python dictionary
39,108,729
<p>I have a script that reads a CSV file <a href="http://i.stack.imgur.com/CrflA.png" rel="nofollow">csv file</a></p> <pre><code>Asset IP Address,Vulnerability Title 50.103.128.11,Partition Mounting Weakness 10.103.128.11,UDP IP ID Zero 10.103.128.11,Root's umask value is unsafe 0.103.128.11,Root's umask value is unsa...
1
2016-08-23T18:54:38Z
39,108,788
<p>Use <code>setdefault()</code>, don't make <code>b</code> a list, and don't use builtins as variable names:</p> <pre><code>d = {} with open('test.csv', 'rb') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: a = row["Vulnerability Title"] b = row["Asset IP Address"] d.setdefa...
2
2016-08-23T18:58:28Z
[ "python", "list", "csv", "dictionary", "append" ]
dataframe merge with missing data
39,108,845
<p>I have 2 dataframes:</p> <pre><code>df.head() Out[2]: Unnamed: 0 Symbol Date Close 0 4061 A 2016-01-13 36.515889 1 4062 A 2016-01-14 36.351784 2 4063 A 2016-01-15 36.351784 3 4064 A 2016-01-19 36.590483 4 4065 A 2016-01-20 35.9340...
1
2016-08-23T19:02:14Z
39,108,951
<pre><code>df_all = df[df.Symbol.isin(dfw.Symbol.unique())].merge(dfw, how='left', on='Symbol') </code></pre> <p>I am not sure why you are getting NaN values. Perhaps you have spaces in you your symbols? You can clean them via: <code>dfw['Symbol'] = dfw.Symbol.str.strip()</code> You would need to do the same for <c...
3
2016-08-23T19:09:24Z
[ "python", "pandas", "dataframe", "merge" ]
OSError: The CUDA lib64 path could not be located in /usr/lib64
39,108,859
<p>How can I fix this? </p> <pre><code>(cv) jalal@klein:~/computer_vision/py-faster-rcnn/lib$ make python setup.py build_ext --inplace Traceback (most recent call last): File "setup.py", line 58, in &lt;module&gt; CUDA = locate_cuda() File "setup.py", line 55, in locate_cuda raise EnvironmentError('The CUD...
1
2016-08-23T19:03:33Z
39,109,011
<p>Solved this problem using the following change for those who might end of using this popular software (for Cuda ~5):</p> <pre><code>jalal@klein:~/computer_vision/py-faster-rcnn/lib$ vi setup.py change: cudaconfig = {'home':home, 'nvcc':nvcc, 'include': pjoin(home, 'include'), ...
1
2016-08-23T19:12:18Z
[ "python", "ubuntu", "path", "gpu" ]
Join two columns in a Dataframe that has been pivoted
39,108,935
<p>I have two columns I am trying to join (Year and Quarter). I have pulled the data from sql and pivoted it as seen below:</p> <pre><code>df3 = pd.pivot_table(df, index=["Year", "Q"], columns='Area', values="Lows", aggfunc=np.sum, fill_value=0) </code></pre> <p>I would now like to join the columns <code>Year</code> ...
3
2016-08-23T19:08:43Z
39,109,134
<p>This should work:</p> <pre><code>df3.index = df3.index.to_series().apply(lambda x: ' '.join([str(y) for y in x])) </code></pre> <p><strong><em>more generalized</em></strong></p> <pre><code>join = lambda x, delim=' ': delim.join([str(y) for y in x]) df3.index = df3.index.to_series().apply(join, delim=' ') </code>...
2
2016-08-23T19:19:35Z
[ "python", "pandas", "join", "dataframe", "pivot" ]
Join two columns in a Dataframe that has been pivoted
39,108,935
<p>I have two columns I am trying to join (Year and Quarter). I have pulled the data from sql and pivoted it as seen below:</p> <pre><code>df3 = pd.pivot_table(df, index=["Year", "Q"], columns='Area', values="Lows", aggfunc=np.sum, fill_value=0) </code></pre> <p>I would now like to join the columns <code>Year</code> ...
3
2016-08-23T19:08:43Z
39,120,371
<p>Another faster solutions:</p> <pre><code>df.index = ['{} {}'.format(idx[1], idx[0]) for idx in df.index] </code></pre> <p>and</p> <pre><code>df.index = [' '.join((str(idx[0]), str(idx[1]))) for idx in df.index] </code></pre> <p><strong>Timings</strong>:</p> <pre><code>In [190]: %timeit df.index.to_series().appl...
0
2016-08-24T10:10:11Z
[ "python", "pandas", "join", "dataframe", "pivot" ]
How to extract the first numbers in a string - Python
39,108,980
<p>How do I remove all the numbers before the first letter in a string? For example,</p> <pre><code>myString = "32cl2" </code></pre> <p>I want it to become:</p> <pre><code>"cl2" </code></pre> <p>I need it to work for any length of number, so 2h2 should become h2, 4563nh3 becomes nh3 etc. <strong>EDIT:</strong> Thi...
1
2016-08-23T19:10:50Z
39,109,017
<p>If you were to solve it without regular expressions, you could have used <a href="https://docs.python.org/2/library/itertools.html#itertools.dropwhile"><code>itertools.dropwhile()</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import dropwhile &gt;&gt;&gt; &gt;&gt;&gt; ''.join(dropwhile(str.isdigit, "32cl2"...
5
2016-08-23T19:12:47Z
[ "python", "string", "numbers", "truncate" ]
How to extract the first numbers in a string - Python
39,108,980
<p>How do I remove all the numbers before the first letter in a string? For example,</p> <pre><code>myString = "32cl2" </code></pre> <p>I want it to become:</p> <pre><code>"cl2" </code></pre> <p>I need it to work for any length of number, so 2h2 should become h2, 4563nh3 becomes nh3 etc. <strong>EDIT:</strong> Thi...
1
2016-08-23T19:10:50Z
39,109,021
<p>Use <code>lstrip</code>:</p> <pre><code>myString.lstrip('0123456789') </code></pre> <p>or</p> <pre><code>import string myString.lstrip(string.digits) </code></pre>
2
2016-08-23T19:13:00Z
[ "python", "string", "numbers", "truncate" ]
How to specify a variable as a member variables of a class or of an instance of the class?
39,108,996
<p>in latest Python 2.7.x:</p> <ol> <li><p>Given any member variable inside the definition of a class, is the member variable always at the class level in the sense that it is a single variable shared by all the instances of the class?</p></li> <li><p>In the definition of a class, how can I specify </p> <ul> <li>whic...
1
2016-08-23T19:11:33Z
39,109,336
<p>You might want to use the <a href="https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables" rel="nofollow">terminology</a> "class variable" and "instance variable" here, as that's the usual language in python. </p> <pre><code>class Foo(object): var1 = "I'm a class variable" def __ini...
1
2016-08-23T19:33:50Z
[ "python", "python-2.7" ]
django: RecursionError when initialize a object
39,109,000
<p>SO I am trying to build a simple shopping cart feature for my app, that simply add, remove a piece of equipment, and display a list of current cart. Here are my codes for this cart: (codes largely adopted from <a href="https://github.com/bmentges/django-cart" rel="nofollow">https://github.com/bmentges/django-cart</a...
1
2016-08-23T19:11:41Z
39,109,394
<p>You have two separate classes called Cart. Rename one of ,them.</p>
2
2016-08-23T19:37:45Z
[ "python", "django", "oop" ]
Numpy "where" with multiple conditions
39,109,045
<p>I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see th...
4
2016-08-23T19:14:07Z
39,109,099
<p>You can use a <a href="http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator">ternary</a>:</p> <pre><code>np.where(consumption_energy &gt; 400, 'high', (np.where(consumption_energy &lt; 200, 'low', 'medium))) </code></pre>
4
2016-08-23T19:17:48Z
[ "python", "pandas", "numpy", "dataframe" ]
Numpy "where" with multiple conditions
39,109,045
<p>I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see th...
4
2016-08-23T19:14:07Z
39,109,969
<p>I would use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">cut()</a> method here, which will generate very efficient and memory-saving <code>category</code> dtype:</p> <pre><code>In [124]: df Out[124]: consumption_energy 0 459 1 ...
4
2016-08-23T20:16:18Z
[ "python", "pandas", "numpy", "dataframe" ]
Numpy "where" with multiple conditions
39,109,045
<p>I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see th...
4
2016-08-23T19:14:07Z
39,111,919
<p>Try this: Using the setup from @Maxu</p> <pre><code>conditions = [ df2['consumption_energy'] &gt;= 400, (df2['consumption_energy'] &lt; 400) &amp; (df2['consumption_energy']&gt; 200), df2['consumption_energy'] &lt;= 200 ] choices = [ "high", 'medium', 'low' ] df2["energy_class"] = np.select(conditions, choic...
1
2016-08-23T22:53:29Z
[ "python", "pandas", "numpy", "dataframe" ]
Why does truncating a BytesIO mess it up?
39,109,068
<p>Running this on Python 3.5.1 on OSX:</p> <pre><code>import io b = io.BytesIO() b.write(b'222') print(b.getvalue()) b.truncate(0) b.write(b'222') print(b.getvalue()) </code></pre> <p>Produces:</p> <pre><code>b'222' b'\x00\x00\x00222' </code></pre> <p>So truncating the <code>BytesIO</code> somehow causes it to ...
0
2016-08-23T19:15:21Z
39,109,137
<p><code>truncate</code> does not move the file pointer. So the next byte is written to the next position. You have also to seek to the beginning:</p> <pre><code>b.seek(0) b.truncate() </code></pre>
3
2016-08-23T19:19:47Z
[ "python", "python-3.x", "bytesio" ]
Checking if epic issue exists and if not, make a new epic issue
39,109,140
<p>So the problem is an IndexError, which makes sense considering there isn't supposed to be any results for that jql query.</p> <pre><code>epic_search = 'project = "EXM" and type = Epic and summary ~ "summaryx" ' esearch = jira.search_issues(epic_search) if esearch[0].key == None: epic_dict = { 'pro...
1
2016-08-23T19:19:58Z
39,111,416
<p>Probably something like </p> <p>if (count(esearch) > 0):</p> <p>I assume this is python. I don't do python but there must be something like a count() or maybe esearch.length to tell you how many items are in there.</p>
2
2016-08-23T22:06:22Z
[ "python", "python-3.x", "jira", "jql", "python-jira" ]
Dumping JSON directly into a tarfile
39,109,180
<p>I have a large list of dict objects. I would like to store this list in a tar file to exchange remotely. I have done that successfully by writing a json.dumps() string to a tarfile object opened in 'w:gz' mode. </p> <p>I am trying for a piped implementation, opening the tarfile object in 'w|gz' mode. Here is my cod...
0
2016-08-23T19:22:37Z
39,110,105
<p>Why do you think you can write a tarfile to a StringIO? That doesn't work like you think it does.</p> <p>This approach doesn't error, but it's not actually how you create a tarfile in memory from in-memory objects.</p> <pre><code>from json import dumps ...
0
2016-08-23T20:26:33Z
[ "python", "json", "python-3.x", "tarfile" ]
Python LDAP: LDAPObject.search_s() works, but LDAPObject.search() doesn't
39,109,248
<p>I am trying to implement a basic LDAP authentication script in Python, and I am trying to just perform a simple LDAP search and see if it works. I believe I have correctly created and set up my LDAP object and connection.</p> <p>After binding, I try to perform a search. Using the LDAPObject.search_s() method succes...
0
2016-08-23T19:27:43Z
39,309,051
<p>The following command is using an async search which does not block to wait for a return value. The int it returns is actually the MSGID of the LDAPObject which you need to get the return value when it is returned. </p> <pre><code>msgid = ld.search(base_dn, ldap.SCOPE_SUBTREE, search_filter) # Returns int of m...
0
2016-09-03T16:30:02Z
[ "python", "active-directory", "ldap", "ldap-query" ]
C++11 equivalent to Python's all() function
39,109,324
<p>Is there an equivalent function to Python's <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a> built-in function?</p> <p>In other words: Does a C++11 function exist that returns <code>true</code> when all of the elements of an iterable meet a certain condition and <...
-2
2016-08-23T19:33:07Z
39,109,362
<p>Check out <code>std::all_of</code> in the <code>&lt;algorithm&gt;</code> header. You can pass a custom predicate that evaluates to true or false on each element.</p>
2
2016-08-23T19:35:16Z
[ "python", "c++11", "iterable", "built-in" ]
C++11 equivalent to Python's all() function
39,109,324
<p>Is there an equivalent function to Python's <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a> built-in function?</p> <p>In other words: Does a C++11 function exist that returns <code>true</code> when all of the elements of an iterable meet a certain condition and <...
-2
2016-08-23T19:33:07Z
39,109,741
<p>Also, for doing the same thing with template parameter pack (like <code>template &lt;bool... values&gt;</code>) you can use fold expression: <code>(values &amp;&amp; ...)</code>, but only since C++17. Documentation of this feature is here:</p> <p><a href="http://en.cppreference.com/w/cpp/language/fold" rel="nofollo...
0
2016-08-23T20:00:34Z
[ "python", "c++11", "iterable", "built-in" ]
"list indices must be integers, not list" with enumerate
39,109,342
<p>I have this code</p> <pre><code>cNames = data["channelnames"] goodChannels = [i for i,x in enumerate(cNames) if x!='Skipped'] data["channelnames"]=cNames[goodChannels] </code></pre> <p>I need the channel numbers later, but the cNames[goodChannels] throws the error "list indices must be integers, not list"</p> <p>...
-2
2016-08-23T19:34:07Z
39,109,409
<p>You need another list comprehension:</p> <pre><code>data["channelnames"] = [cNames[i] for i in goodChannels] </code></pre>
1
2016-08-23T19:38:47Z
[ "python" ]
Making the name of shape node to be the same as the parent
39,109,369
<p>How can I make the name of the shape node to have similar name as its parent node? (Assuming there is only 1 shape node per geometry/object)</p> <p>For eg. parent_geo is called <code>test_geo1</code>, however its shape node is <code>testing_geo2Shape</code> instead of <code>test_geo1Shape</code></p> <p>I tried doi...
0
2016-08-23T19:35:44Z
39,118,600
<pre><code>all = cmds.ls(sl=True, dag=True, shapes=True) for shape in all: ''' shape contain the dag path exm.: grp_a grp_aShape grp_b grp_bShape print cmds.ls('grp_a', dag=1, shapes=1) &gt;&gt;('grp_a|grp_aShape', 'grp_b|grp_bShape') n...
1
2016-08-24T08:49:34Z
[ "python", "maya" ]
NotImplementedError: 'pop' not supported on frozendict
39,109,393
<p>I'm adapting a module for Odoo v9 community</p> <p>It uses frozendict, but everytime I try to use a feature, it throws:</p> <pre><code>NotImplementedError: 'pop' not supported on frozendict </code></pre> <p>The code is as follows:</p> <pre><code>def fields_view_get(self, cr, uid, view_id=None, view_type=False, ...
0
2016-08-23T19:37:42Z
39,109,844
<p>Contexts are <a href="https://pypi.python.org/pypi/frozendict" rel="nofollow">frozendict</a> objects that you cannot directly modify. This has been implemented on version 9 from what I am aware, </p> <p>If you want to modify the context in your code you have to use methods provided by Odoo's API, take a look at the...
2
2016-08-23T20:07:31Z
[ "python", "openerp", "odoo-9" ]
NotImplementedError: 'pop' not supported on frozendict
39,109,393
<p>I'm adapting a module for Odoo v9 community</p> <p>It uses frozendict, but everytime I try to use a feature, it throws:</p> <pre><code>NotImplementedError: 'pop' not supported on frozendict </code></pre> <p>The code is as follows:</p> <pre><code>def fields_view_get(self, cr, uid, view_id=None, view_type=False, ...
0
2016-08-23T19:37:42Z
39,113,481
<p>A quick way to get over this would be to copy the frozen dictionary to another dictionary and then pass that dictionary to the method either as an argument or if you are using the new api, use the 'with_context' method.</p> <p>Here is an example:</p> <pre><code>ctx = dict(self._context) self.with_context(ctx).writ...
1
2016-08-24T02:27:44Z
[ "python", "openerp", "odoo-9" ]
Underscore after a variable name in python
39,109,398
<p>I am deciphering someone else's code and I see the following:</p> <pre><code>def get_set_string(set_): if PY3: return str(set_) else: return str(set_) </code></pre> <p>Does the underscore AFTER the variable mean anything or is this just a part of the variable's name and mean...
0
2016-08-23T19:37:53Z
39,109,438
<p>It means nothing. I believe the one who wrote this wanted a variable name designating a set, but <code>set</code> is a type in Python (which creates a set), so he added the underscore.</p>
1
2016-08-23T19:41:03Z
[ "python", "python-3.x" ]
Underscore after a variable name in python
39,109,398
<p>I am deciphering someone else's code and I see the following:</p> <pre><code>def get_set_string(set_): if PY3: return str(set_) else: return str(set_) </code></pre> <p>Does the underscore AFTER the variable mean anything or is this just a part of the variable's name and mean...
0
2016-08-23T19:37:53Z
39,109,501
<p>No semantics are associated with a trailing underscore. According to <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow"><code>PEP 8</code></a>, the style guide for Python, users are urged to use trailing underscores in order to not conflict with Python keywords and/or Python...
2
2016-08-23T19:45:18Z
[ "python", "python-3.x" ]
Using itertools for arbitrary number of nested loops of different ranges with dependencies?
39,109,537
<p>Given a list of upperbounds: B1, B2, .. BN;<br> Dependency Functions: f1, ..., fN-1, </p> <p>I'm wondering if there's a recipe using itertools or other classes in python for:</p> <pre><code>for i1 in range(0, B1): for i2 in range(f1(i1), B2): ... for iN in range(fN-1(iN-1), BN) dostuff(...
4
2016-08-23T19:48:17Z
39,110,133
<p>Here is an example of what you want:</p> <pre><code>B = [10, 15, 20, 5] F = [lambda x: x, lambda x: x * x, lambda x: x * 2 - 5] def dostuff(i0, i1, i2, i3): print((i0, i1, i2, i3)) expected = [] for i0 in range(0, B[0]): for i1 in range(F[0](i0), B[1]): for i2 in range(F[1](i1), B[2]): ...
2
2016-08-23T20:28:39Z
[ "python", "python-3.x", "itertools", "functools" ]
Using itertools for arbitrary number of nested loops of different ranges with dependencies?
39,109,537
<p>Given a list of upperbounds: B1, B2, .. BN;<br> Dependency Functions: f1, ..., fN-1, </p> <p>I'm wondering if there's a recipe using itertools or other classes in python for:</p> <pre><code>for i1 in range(0, B1): for i2 in range(f1(i1), B2): ... for iN in range(fN-1(iN-1), BN) dostuff(...
4
2016-08-23T19:48:17Z
39,111,298
<p>An iterative solution using @LaurentLAPORTE's setup. Put this code right under his and it should work. My <code>args</code> is a stack of the arguments fed into <code>dostuff</code> whenever it's full. The actual solution is the middle part, top and bottom parts are just testing.</p> <pre><code>stefan = [] def dost...
3
2016-08-23T21:56:34Z
[ "python", "python-3.x", "itertools", "functools" ]
__str__() doesn't work after importing class
39,109,677
<p>I encountered a problem while importing a class: the <strong>str</strong>() doesn't work after importing the class </p> <pre><code>class unit: value = None node = None def __init__(self,value,node): self.value = value self.node = node def __str__(self): if self.node == Non...
0
2016-08-23T19:56:44Z
39,115,939
<p>Assuming you put both <code>.py</code> files in the same directory, your <code>Python 2.7</code> code runs fine with a standard <code>CPython</code> interpreter such as <code>Canopy</code>. <code>Python 3.5</code> interpreters such as Anaconda will complain about the <code>print</code> not being used as a function a...
0
2016-08-24T06:30:17Z
[ "python", "string", "oop", "import" ]
check if pair of values is in pair of columns in pandas
39,109,688
<p>Basically, I have latitude and longitude (on a grid) in two different columns. I am getting fed two-element lists (could be numpy arrays) of a new coordinate set and I want to check if it is a duplicate before I add it.</p> <p>For example, my data:</p> <pre><code>df = pd.DataFrame([[4,8, 'wolf', 'Predator', 10], ...
3
2016-08-23T19:57:19Z
39,109,736
<p>you can do it this way:</p> <pre><code>In [140]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long') Out[140]: lat long name kingdom energy 5 7 5 rabbit Prey 10 In [146]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long').empty Out[146]: False </code></pre> <p>the follow...
2
2016-08-23T20:00:26Z
[ "python", "pandas", "dataframe" ]
check if pair of values is in pair of columns in pandas
39,109,688
<p>Basically, I have latitude and longitude (on a grid) in two different columns. I am getting fed two-element lists (could be numpy arrays) of a new coordinate set and I want to check if it is a duplicate before I add it.</p> <p>For example, my data:</p> <pre><code>df = pd.DataFrame([[4,8, 'wolf', 'Predator', 10], ...
3
2016-08-23T19:57:19Z
39,109,824
<pre><code>x, y = newcoords1 &gt;&gt;&gt; df[(df.lat == x) &amp; (df.long == y)].empty True # Coordinates are not in the dataframe, so you can add it. x, y = newcoords2 &gt;&gt;&gt; df[(df.lat == x) &amp; (df.long == y)].empty False # Coordinates already exist. </code></pre>
2
2016-08-23T20:06:01Z
[ "python", "pandas", "dataframe" ]
Form input-box not displaying
39,109,694
<p>I'm trying to display a simple form input-text box with Django. I'm am deploying on Amazon AWS. The site works fine on a different server (pythonanywhere) but there is a major problem on AWS. Specifically, the input box is not being displayed. I'm using templates as follows:</p> <p><strong>home.html</strong></p> <...
3
2016-08-23T19:57:41Z
39,126,082
<p>In my experience with Django, there are 2 things you often (always?) need to do to get static files to "refresh" after pushing them to a remote server:</p> <ol> <li>Run <code>./manage.py collectstatic</code> to make sure all your static files are in the right place.</li> <li>While <code>ssh</code>ed into your serve...
3
2016-08-24T14:27:42Z
[ "python", "django", "forms", "amazon-web-services", "input" ]
python POST with file - convert from RAW data
39,109,698
<p>I have been trying to get this thing to work for days, with no luck. I have worked through the majority of my issues, but I am now at a new error and I don't know why. </p> <p>I have read multiple posts, and even asked a few questions along the way, but now I am completely stumped and it seems that nothing that I s...
0
2016-08-23T19:57:54Z
39,126,162
<p>I am not sure if it's the API, or if I was messing something up, but in this case I had to create a body that looked similar to the RAW data. I was under the impression that "files=" would do this for me, but apparently it did not. </p> <p>I defined a boundary in the multipart/form and then used that to add my sect...
0
2016-08-24T14:31:00Z
[ "python", "python-3.x", "csv", "post", "python-requests" ]
Adding New Text to Sklearn TFIDIF Vectorizer (Python)
39,109,743
<p>Is there a function to add to the existing corpus? I've already generated my matrix, I'm looking to periodically add to the table without re-crunching the whole sha-bang</p> <p>e.g;</p> <pre><code>articleList = ['here is some text blah blah','another text object', 'more foo for your bar right now'] tfidf_vectorize...
4
2016-08-23T20:00:40Z
39,114,555
<p>You can access the <code>vocabulary_</code> attribute of your vectoriser directly, and you can access the <code>idf_</code> vector via <code>_tfidf._idf_diag</code>, so it would be possible to monkey-patch something like this:</p> <pre><code>import re from scipy.sparse.dia import dia_matrix def partial_fit(self, ...
3
2016-08-24T04:41:50Z
[ "python", "scikit-learn", "tf-idf" ]
Which recursive approach is a better design?
39,109,765
<p>Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.</p> <p>My in...
0
2016-08-23T20:01:55Z
39,109,840
<p>To avoid passing the <code>line_sep</code> parameter, you can define the helper function inside the recursive function:</p> <pre><code>def deep_print(s, line_sep): def deep_print_helper(file_path): with open(file_path) as f: text = f.read() return deep_print(text, line_sep) ...
0
2016-08-23T20:07:14Z
[ "python", "recursion", "design", "arguments", "parameter-passing" ]
Which recursive approach is a better design?
39,109,765
<p>Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.</p> <p>My in...
0
2016-08-23T20:01:55Z
39,110,361
<p>Your question should not be related to Pythonic way to achieve this. It is related to the design, independent of language. If you ask me among the two approaches, I'll go with <code>1</code>. But the better way to achieve is via class having your functions within it. In Python you may do it like:</p> <pre><code>cla...
2
2016-08-23T20:45:53Z
[ "python", "recursion", "design", "arguments", "parameter-passing" ]
Which recursive approach is a better design?
39,109,765
<p>Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.</p> <p>My in...
0
2016-08-23T20:01:55Z
39,110,873
<p>Your requirements may not allow for this, but using <a href="https://docs.python.org/3/library/stdtypes.html#str.splitlines" rel="nofollow">str.splitlines</a> would make things a little less complicated. In the same vain, is there a reason why the original file is not opened as part of the recursion (i.e., rather t...
0
2016-08-23T21:20:53Z
[ "python", "recursion", "design", "arguments", "parameter-passing" ]
Count how often a specific string occurs in a list
39,109,780
<p>I want to pairwise compare several lists in a kind of "bag of words" approach. I have only strings in my lists.<br> Unfortunatelly, I have a bug in my script that I cannot fix.<br> The code works if there are numbers in the lists but as soon as I have strings in the lists it doesn't run anymore. I appreciate your he...
1
2016-08-23T20:03:17Z
39,109,907
<p>By default <code>numpy.zeros</code> makes an empty array of floats, to use strings you need to specify <code>dtype=str</code>:</p> <pre><code>bow_matrix = numpy.zeros(shape = (3, len_bow_matrix),dtype=str) </code></pre>
3
2016-08-23T20:12:01Z
[ "python", "string", "list", "numpy" ]
attribute call speed VS method call Python
39,109,799
<p>Hi I have a simple question but I wasn't able to find the direct comparison I was looking for.</p> <p>My question is:</p> <p>Does calling attribute tend to be faster than calling a method in Python.</p> <p>I have a game and I want to check whether or not a player has discovered a planet. I can either do a call to...
0
2016-08-23T20:04:45Z
39,110,377
<p>I've maked some script that generate 'planetsCount' of planets in galaxy, and checks 'testsCount' times. (code at end of message) Some results:</p> <pre><code>Preparing was done in 0.0 seconds, planetsCount is 10, testsCount is 1000000 First test time is 2.50099992752 sec Second test time is 2.5 sec Preparing was ...
1
2016-08-23T20:46:48Z
[ "python", "class", "optimization", "methods", "attributes" ]
Resolving 2 Python version in Mac OSX
39,109,843
<p>I am running <strong>Mac OS X 10.11.5</strong>. I have two Python versions on my machine:</p> <ol> <li><p><strong>Python 2.7</strong> (Inbuilt python in OSX) and </p></li> <li><p><strong>Python 3.5</strong> (Anaconda version- 4.1.1)</p></li> </ol> <p>The path is set up as shown:</p> <blockquote> <p>$PATH</p> ...
-1
2016-08-23T20:07:25Z
39,110,921
<p>My approach would be to create a new conda enviornment and install your packages there. This will help you avoid any issues if you still want to use 2.7. Example would be: </p> <p><code>conda create --name foo python=3 pandas Theano</code></p>
0
2016-08-23T21:24:21Z
[ "python", "osx", "python-3.x", "path", "anaconda" ]
Ply example calculator multiple expressions
39,109,851
<p>I've been trying out the Ply <a href="https://github.com/dabeaz/ply/blob/master/example/calc/calc.py" rel="nofollow">example calculator from Github</a>.</p> <p>When I run the calculator, it runs inside of a REPL. How would I use Ply to enable multiple expressions to be evaluated, one after the other.</p> <p>For ex...
-1
2016-08-23T20:08:14Z
39,110,837
<p>The sample calculator's grammar allows expressions like <code>- 42</code> (or <code>-(4*8)+7</code>). If such an expression were the second expression on a line, it would create an ambiguity. Is:</p> <pre><code>calc &gt; 4 * 3 -(4*8)+7 </code></pre> <p>one expression or two?</p> <p>One way to make the grammar una...
1
2016-08-23T21:18:18Z
[ "python", "parsing", "lexer", "ply" ]
How do I assign series or sequences to dask dataframe column?
39,109,855
<p>My <strong>dask dataframe</strong> is the follwing:</p> <pre><code>In [65]: df.head() Out[65]: id_orig id_cliente id_cartao inicio_processo fim_processo score \ 0 1.0 1.0 1.0 1.0 1.0 1.0 1 1.0 1.0 1.0 1.0 1.0 1.0 2 ...
1
2016-08-23T20:08:32Z
39,109,961
<p>DataFrame.assign accepts any scalar or any <code>dd.Series</code></p> <pre><code>df = df.assign(a=1) # accepts scalars df = df.assign(z=df.x + df.y) # accepts dd.Series objects </code></pre> <p>If you are trying to assign a NumPy array or Python list then it might be your data is small enough to fit in RAM, and ...
1
2016-08-23T20:15:34Z
[ "python", "dataframe", "dask" ]
How can I make this code quicker?
39,109,877
<p>I have a lot of 750x750 images. I want to take the geometric mean of non-overlapping 5x5 patches from each image, and then for each image, average those geometric means to create one feature per image. I wrote the code below, and it seems to work just fine. But, I know it's not very efficient. Running it on 300 or s...
-1
2016-08-23T20:09:54Z
39,111,456
<p>I can understand the suggestion to move this to the code review site, but this problem provides a nice example of the power of using vectorized numpy and scipy functions, so I'll give an answer.</p> <p>The function below, cleverly called <code>func</code>, computes the desired value. The key is to reshape the image...
2
2016-08-23T22:09:38Z
[ "python", "scipy" ]
Run scripts in php
39,109,891
<p>I am running a python script through my php. It works fine on console but returns null when I run it on browser.I even tried writing output to a file, but it doesn't return anything. The php code is:</p> <pre><code>&lt;?php $y = "python Code.py"; $output = shell_exec($y); if($output!=null){ echo $output; } else...
-2
2016-08-23T20:10:48Z
39,109,946
<pre><code>$command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; #!/usr/bin/env python **is this in the first line of you python script?** chmod +x /usr/custom/test.py </code></pre>
0
2016-08-23T20:14:31Z
[ "php", "python", "web" ]
global variable not working python
39,109,901
<p>Hello there developers,</p> <p>i am writing code that takes the user input and initializes a class depending on the input like in the example code below:</p> <pre><code>class X: def __init__(self): return def run(self): print("i am X") def func1(cls): exec("global " + cls.lower()) e...
-5
2016-08-23T20:11:29Z
39,109,940
<p>It seems like you'd be better off having <code>func2</code> instantiate <em>and</em> run the method:</p> <pre><code>def func2(mode_to_set): globals()[mode_to_set]().run() </code></pre> <p>In this way, you don't have a whole bunch of undesireable cruft floating about in your global namespace and you don't end u...
0
2016-08-23T20:13:47Z
[ "python", "class", "python-3.x", "input", "global-variables" ]
global variable not working python
39,109,901
<p>Hello there developers,</p> <p>i am writing code that takes the user input and initializes a class depending on the input like in the example code below:</p> <pre><code>class X: def __init__(self): return def run(self): print("i am X") def func1(cls): exec("global " + cls.lower()) e...
-5
2016-08-23T20:11:29Z
39,110,057
<p>A much better way to instantiate a class based on user input would be to use a "factory pattern":</p> <p><a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html" rel="nofollow">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html</a></p> <p>Basically you create a c...
1
2016-08-23T20:22:19Z
[ "python", "class", "python-3.x", "input", "global-variables" ]
global variable not working python
39,109,901
<p>Hello there developers,</p> <p>i am writing code that takes the user input and initializes a class depending on the input like in the example code below:</p> <pre><code>class X: def __init__(self): return def run(self): print("i am X") def func1(cls): exec("global " + cls.lower()) e...
-5
2016-08-23T20:11:29Z
39,110,126
<p>Dictionaries, dictionaries, dictionaries. Your program should maintain control over what code gets executed, rather than letting the user construct new code dynamically.</p> <pre><code>classes = {'X': X} instances = {} def func1(cls): var = cls.lower() instances[var] = classes[cls]() def func2(mode_to_set...
0
2016-08-23T20:28:06Z
[ "python", "class", "python-3.x", "input", "global-variables" ]
Validate WTForm before submitting
39,109,933
<p>Is it possible to validate a WTForm field after leaving the field but before submit? For example, after entering a username, that field is validated to see if its available and shows a checkmark, before the user clicks submit.</p>
0
2016-08-23T20:13:28Z
39,110,440
<p>When the field is changed, perform a check and change the text in an adjacent node. Some things can be validated directly in the browser. To validate against data on the server, send a request with JavaScript to a view that checks the data and returns a JSON response.</p> <pre><code>@app.route('/username-exists',...
0
2016-08-23T20:50:15Z
[ "python", "flask", "jinja2", "flask-wtforms" ]
Convert '%m/%d/%Y' string index into pandas datetime index
39,109,971
<p>MY index is datetime string with format <code>'%m/%d/%Y' ('09/26/2007')</code> </p> <p>When I try to convert the index into datetime index using <code>pd.to_datetime</code> function <code>pd.to_datetime(df.index)</code>, I got error message <code>OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:0...
3
2016-08-23T20:16:23Z
39,110,086
<p>The the look of the error message, it appears you may have the string <code>'1/1/0001'</code> in your index. For example,</p> <pre><code>df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001']) pd.to_datetime(df.index) </code></pre> <p>raises </p> <pre><code>OutOfBoundsDatetime: Out of bounds nanosecond timesta...
3
2016-08-23T20:25:18Z
[ "python", "pandas" ]
Finding random pairs in a large directory
39,110,012
<p>I have ~5M csv files stored in ~100.000 folders. Each folder contains roughly the same number of files and there's always an even number of files in a folder. I need to find the paths to all these files and load them into a list in a somewhat strange order for a statistical modeling project.</p> <p>In particular, I...
3
2016-08-23T20:19:08Z
39,110,408
<p>One way to ensure that everything's random is to use <code>random.shuffle</code>, which shuffles a list inplace. That way you can simply pair each item with its neighbor, safe in the knowledge that the pairing is random. To achieve a result like your example you can then shuffle and flatten the resulting list of pai...
1
2016-08-23T20:48:10Z
[ "python", "performance", "design", "io" ]
Finding random pairs in a large directory
39,110,012
<p>I have ~5M csv files stored in ~100.000 folders. Each folder contains roughly the same number of files and there's always an even number of files in a folder. I need to find the paths to all these files and load them into a list in a somewhat strange order for a statistical modeling project.</p> <p>In particular, I...
3
2016-08-23T20:19:08Z
39,111,100
<p>The best strategy would be to divide and conquer with some help from threading. You want to get the file names loaded into memory as quick as possible for fastest completion.</p> <p>First step would be to create a queue for the folder names and another for the list of the files in each folder. Something like:</p> ...
1
2016-08-23T21:39:30Z
[ "python", "performance", "design", "io" ]
ImportError: No module named tflearn
39,110,075
<p>Above Error comes only when i am trying to run the script : <code>"rgarg:pytutorial raghav$ python tflearn11.py"</code></p> <p>It working fine in Rodeo IDE, also if I put <code>"import tflearn "</code> in command line python interpreter it works fine (even I typed full script in command line , it worked fine w/o i...
0
2016-08-23T20:23:48Z
39,129,241
<p>As @Two-Bit mentioned i used virtualenvs <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">Link</a>.</p> <p>But please make sure use below for installation of virtualenvs</p> <p><em>$ sudo easy_install virtualenvs</em></p> <p>instead of pip install virtualenvs.</p>
1
2016-08-24T17:06:59Z
[ "python", "bash", "python-import" ]
CSS Selector not parsing anything in Python Webscrape
39,110,188
<p>I am trying to webscrape this website: <a href="http://canoeracing.org.uk/marathon/results/burton2016.htm" rel="nofollow">http://canoeracing.org.uk/marathon/results/burton2016.htm</a> using Python and CSS selectors, but my CSS selectors which I'm using aren't finding anything to parse in the DOM tree. I've managed t...
3
2016-08-23T20:33:00Z
39,110,390
<p>There is no tbody, that is added by the browser, you want <em><code>body &gt; table &gt; tr &gt; td:nth-child(2)</code></em>:</p> <p>With that change:</p> <pre><code>In [1]: import lxml.html In [2]: import requests In [3]: r = requests.get('http://canoeracing.org.uk/marathon/results/burton2016.htm') In [4]: t...
1
2016-08-23T20:47:26Z
[ "python", "css", "web-scraping" ]
What Happens when a Generator Runs out of Values to Yield?
39,110,210
<p>To illustrate the question, suppose we have this simple generator:</p> <pre><code>def firstn(n): num = 0 while num &lt; n: yield num num += 1 for i in firstn(10): print i </code></pre> <p>This will print the digits 0 through 9. But what if we have:</p> <pre><code>def firstn(n): nu...
0
2016-08-23T20:34:35Z
39,110,344
<p>This isn't very mysterious. When a generator runs out of values to yield, it raises a <code>StopIteration</code> exception. You just need to understand how a for-loop works in Python. Essentially, it is equivalent to the following code:</p> <pre><code>iterator = iter(collection) while True: try: x = nex...
1
2016-08-23T20:44:36Z
[ "python", "generator", "yield-keyword" ]
Storing a score in Python
39,110,212
<p>So far I have made a short game in which you have to guess the area of the shape in question. Only the triangle works so far and the correct answer is B for testing.</p> <p>I am trying to store the user's progress by putting it into a text file, but when I call a function to update the score, it overwrites the file...
-1
2016-08-23T20:34:38Z
39,110,738
<p>It's not saving because you never close the file. This is why most people agree <code>with open(filename, 'w+')</code> is best practice.</p> <p>Try using the below format for <code>LoginScreen()</code></p> <pre><code>def LoginScreen(): print("Welcome to Area Trainer") print("Please enter the username for y...
1
2016-08-23T21:12:14Z
[ "python", "python-3.x" ]
Storing a score in Python
39,110,212
<p>So far I have made a short game in which you have to guess the area of the shape in question. Only the triangle works so far and the correct answer is B for testing.</p> <p>I am trying to store the user's progress by putting it into a text file, but when I call a function to update the score, it overwrites the file...
-1
2016-08-23T20:34:38Z
39,110,758
<p>The addition that you are doing here</p> <pre><code>score = reading.read() score = score + '2' </code></pre> <p>is of <code>type str</code> so you keep getting values like <code>024</code>, change the value in the file to <code>int</code> first.</p> <pre><code> score = int(score) + '2' </code></pre> <p>Also o...
2
2016-08-23T21:13:40Z
[ "python", "python-3.x" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4...
0
2016-08-23T20:36:42Z
39,110,354
<p>You may try the <code>groupby</code> from itertools with the original list sorted by the last three elements of the sublist:</p> <pre><code>lst=[[4,"blue","round","none"], [6,"blue","round","none"], [8,"red","round","none"], [10,"red","round","none"], [8,"red","square","none"]] from itertools import groupby [[sum(...
2
2016-08-23T20:45:17Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4...
0
2016-08-23T20:36:42Z
39,110,435
<p>You can use a counter to accumulate the results:</p> <pre><code>&gt;&gt;&gt; in_data = [[4,'blue','round',None], [6,'blue','round',None], [8,'red','round',None], [10,'red','round',None], [8,'red','square',None]] &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counter = Counter() &gt;&gt;&gt; for count, *k...
2
2016-08-23T20:49:53Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4...
0
2016-08-23T20:36:42Z
39,110,438
<p>Roughly speaking, all you are doing is associating element 0 with a tuple defined as the last three elements of any given list. Luckily, it's perfectly okay for a tuple to be a key of a dictionary!</p> <pre><code>from collections import OrderedDict color_data = [[4,'blue','round','none'], [6,'blue','round','none']...
1
2016-08-23T20:50:06Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4...
0
2016-08-23T20:36:42Z
39,110,457
<p>if you feel like use pandas, you could do:</p> <pre><code>import pandas data = [ [4,"blue","round","none"], [6,"blue","round","none"], [8,"red","round","none"], [10,"red","round","none"], [8,"red","square","none"] ] summary = ( pandas.DataFrame(data, columns=['q', 'color', 'shape', 'other'...
0
2016-08-23T20:51:28Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4...
0
2016-08-23T20:36:42Z
39,110,580
<p>So there's a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> class that makes incrementing over a list of keys very convenient.</p> <pre><code>import collections list_ = [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8,...
0
2016-08-23T20:59:14Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4...
0
2016-08-23T20:36:42Z
39,110,602
<p>If <code>a</code> is your list of lists, then:</p> <pre><code>import collections d = collections.defaultdict(int) for row in a: key = tuple(row[1:]) d[key] += row[0] e = [list((val,) + key) for key, val in d.items()] </code></pre> <p>Output:</p> <pre><code>In [14]: e Out[14]: [[18, 'red', 'round', None...
0
2016-08-23T21:00:56Z
[ "python", "list" ]
3d scatter plot with color in matplotlib
39,110,336
<p>I am using scatter 3d plot in matplotlib in python for plotting following data,</p> <pre><code> x y z b2 3.28912855713 4.64604863545 3.95526335139 1.0 3.31252670518 4.65385917898 3.96834118896 1.0 </code></pre> <p>When the plot is 2d,</p> <pre><code>fig = plt.figure() ax = fig....
0
2016-08-23T20:43:58Z
39,122,150
<p>Probably not. I don't know what version of Matplotlib you are using but at some point a bug existed with this issue that apparently still has repercussions for the version I'm using today, i.e. 1.5.1 (check <a href="http://stackoverflow.com/questions/8971309/matplotlib-3d-scatter-color-lost-after-redraw">this questi...
1
2016-08-24T11:30:55Z
[ "python", "matplotlib", "plot", "colors", "3d" ]
Object permissions with read only access for anonymous users in Django Rest Framework
39,110,380
<p><strong>The problem</strong></p> <p>I am using Django REST Framework - and so far I have been using the <code>DjangoObjectPermissions</code> permissions class. I use <code>django-rules</code> to determine which users have permissions for objects.</p> <p>However, this permissions class seems to deny read access to ...
0
2016-08-23T20:46:58Z
39,113,738
<pre><code>from rest_framework import permissions </code></pre> <p>and Just give </p> <pre><code> permission_classes = [permissions.IsAuthenticatedOrReadOnly, YourPermissionshere, ] </code></pre> <p>in your viewset. That will do the job. if not authenticated, Anonymous users will be getting a read-only permission ...
0
2016-08-24T03:02:35Z
[ "python", "django", "permissions", "django-rest-framework", "anonymous-users" ]
Object permissions with read only access for anonymous users in Django Rest Framework
39,110,380
<p><strong>The problem</strong></p> <p>I am using Django REST Framework - and so far I have been using the <code>DjangoObjectPermissions</code> permissions class. I use <code>django-rules</code> to determine which users have permissions for objects.</p> <p>However, this permissions class seems to deny read access to ...
0
2016-08-23T20:46:58Z
39,319,138
<p>The fix was actually really simple. It's possible to create a custom permissions class extending <code>DjangoObjectPermissions</code>, and to override the <code>authenticated_users_only</code> variable.</p> <pre><code>class DjangoObjectPermissionsOrAnonReadOnly(DjangoObjectPermissions): authenticated_users_only...
0
2016-09-04T16:34:29Z
[ "python", "django", "permissions", "django-rest-framework", "anonymous-users" ]
NameError: global name 'workflow' is not defined - Odoo v9
39,110,424
<p>I have this code:</p> <pre><code>def compute_refund(self, cr, uid, ids, mode='refund', context=None): """@param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: the account invoice refund’s ID or list of IDs """ inv_obj = self...
1
2016-08-23T20:49:22Z
39,115,050
<p>You can try with following code.</p> <p>Replace code </p> <pre><code>wf_service.trg_validate(uid, 'account.invoice',refund.id, 'invoice_open', cr) </code></pre> <p>with </p> <pre><code>refund.signal_workflow('invoice_open') </code></pre> <p><strong>EDIT</strong></p> <p>Remove following line</p> <pre><code>wf...
1
2016-08-24T05:25:37Z
[ "python", "openerp", "odoo-9" ]
Sphinx: list local sections first, linked pages last in TOC
39,110,429
<p>Let's say I have the following <code>index.rst</code>:</p> <pre><code>Some global topic ===================== .. toctree:: :glob: nested/index Global topic introduction ------------------------ </code></pre> <p>And <code>nested/index.rst</code>:</p> <pre><code>Some sub-topic ============== </code></pre> <...
1
2016-08-23T20:49:28Z
39,118,622
<p>It's not a perfect solution, but how about</p> <pre><code>.. contents:: :local: .. toctree:: :glob: nested/index </code></pre> <p>That will give you: </p> <ul> <li>Some global topic <ul> <li>Global topic introduction</li> </ul></li> <li>Some sub-topic</li> </ul>
0
2016-08-24T08:50:26Z
[ "python", "python-sphinx", "restructuredtext" ]
Pad dates within groups with pandas
39,110,470
<p>I'm trying to pad dates within a group ('type') and backfill the new rows. I've seen examples using reindex, but I'm not sure how to pad these dates while maintaining the groups.</p> <p>in:</p> <pre><code>type date value a 2016-01-01 1 a 2016-01-04 3 b 2016-01-10 4 b 2016-01-13...
3
2016-08-23T20:52:08Z
39,110,574
<pre><code>df.set_index('date').groupby('type', as_index=False).resample('d').bfill().reset_index().drop('level_0', axis=1) Out: date type value 0 2016-01-01 a 1 1 2016-01-02 a 3 2 2016-01-03 a 3 3 2016-01-04 a 3 4 2016-01-10 b 4 5 2016-01-11 b 7 6 2016-01-12 ...
5
2016-08-23T20:58:50Z
[ "python", "pandas" ]
Python Pandas Groupby Resetting Values Based on Index
39,110,476
<p>So I have a dataframe that contains some wrong information that I want to fix:</p> <pre><code>import pandas as pd tuples_index = [(1,1990), (2,1999), (2,2002), (3,1992), (3,1994), (3,1996)] index = pd.MultiIndex.from_tuples(tuples_index, names=['id', 'FirstYear']) df = pd.DataFrame([2007, 2006, 2006, 2000, 2000, 20...
5
2016-08-23T20:52:31Z
39,112,266
<pre><code>shift_year = lambda df: df.index.get_level_values('FirstYear').to_series().shift(-1) df.groupby(level=0).apply(shift_year) \ .combine_first(df.LastYear).astype(int) \ .rename('LastYear').to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/Lph1W.png"><img src="http://i.stack.imgur.com/Lph1W...
6
2016-08-23T23:34:27Z
[ "python", "pandas" ]
Python program terminating unexpectedly
39,110,504
<p>I have a program that scrapes a website and downloads files when it finds it. Often it runs just fine but at other times it flat out terminates the operation of the program before it is finishing searching the sequence. I'm stumped. It never quits while downloading only while searching. I'm currently guessing a ...
1
2016-08-23T20:54:39Z
39,111,138
<p>I think the problem is caused by tkinter not given the chance to start it's main event loop which is done when you call <code>root.mainloop()</code>, I'd recommend making the code you currently have in a <code>while</code> loop instead to be a function that is periodically called with the <code>root.after()</code> m...
1
2016-08-23T21:42:14Z
[ "python", "sockets", "python-3.x", "tkinter" ]
Call a C++ function from Python and convert a OpenCV Mat to a Numpy array
39,110,507
<p><strong>Background situation</strong></p> <p>I'm trying to use the OpenCV Stitching module via the Python bindings, but I'm getting an error:</p> <pre><code>import cv2 stitcher = cv2.createStitcher(False) imageL = cv2.imread("imageL.jpg") imageC = cv2.imread("imageC.jpg") imageR = cv2.imread("imageR.jpg") stitch...
2
2016-08-23T20:55:04Z
39,130,543
<p>You need to convert the Python NDArray &lt;=> C++ cv::Mat. I can recommend this <a href="https://github.com/Algomorph/pyboostcvconverter" rel="nofollow">GitHub Repo</a>. It contains an example that should fit to your needs. I am using the converter on Ubuntu 15.10 with Python 2.7/3.4 and OpenCV 3.1.</p>
1
2016-08-24T18:25:46Z
[ "python", "c++", "opencv", "numpy", "boost" ]
Getting an argument name as a string - Python
39,110,640
<p>I have a function that takes in a variable as an argument. That variable happens to contain a directory, also holding a bunch of txt files.</p> <p>I was wondering if there is a way for that variable to be taken as a string? Not what's inside the variable, just the name of that variable. Thanks a bunch!</p> <pre><c...
1
2016-08-23T21:04:14Z
39,110,763
<p>Although that is very weird request, here is how you get the name of argument from inside the function</p> <pre><code>import inspect def f(value): frame = inspect.currentframe() print(inspect.getargvalues(frame)[0][0]) f(10) f("Hello world") f([1, 2, 3]) </code></pre> <p>Prints</p> <pre><code>value valu...
2
2016-08-23T21:13:55Z
[ "python", "glob" ]
Python - If WGET access denied then
39,110,724
<p>I am writing a python script that performs an os.system call to wget and attempts to download a file from a set location. At the point of execution it does not know if the server has HTTP-AUTH or not but will attempt a wget of the default page. If not successful it needs to then run some alternative code. I have see...
0
2016-08-23T21:10:47Z
39,111,746
<p>You can use <code>subprocess.run</code> to execute <code>wget</code> then use the <code>returncode</code> to determine if it was successful. So it might look like this:</p> <pre><code>output = subprocess.run(["wget", "http://..."]) if output.returncode == 0: &lt; wget worked&gt; else: &lt; wget did not wo...
0
2016-08-23T22:37:15Z
[ "python", "wget" ]
POST XML information using Python
39,110,765
<p>I am creating a program in python that posts an XML file to a website's rest API to create a VCS root (this is what the website API documentation suggests). My program creates an XML file, based on user input, posts it (using the requests library), then deletes the file. Is there a way I can post the information c...
0
2016-08-23T21:13:58Z
39,132,533
<p>Use the data-Attribute of <code>requests</code>:</p> <pre><code>from io import BytesIO import xml.etree.ElementTree as et data = et.Element('some-xml') tree = et.ElementTree(data) payload = BytesIO() tree.write(payload) r = requests.post(url, data=payload.getvalue()) </code></pre>
0
2016-08-24T20:30:12Z
[ "python", "xml", "post", "curl" ]
Disable Alt+Tab Combination on Tkinter App
39,110,800
<p>How can i disable Alt+Tab combination, especially tab on my Tkinter App. I disabled Alt and F4 with <em>-</em> return "break" <em>-</em> but i can't disable Tab key with it.</p>
0
2016-08-23T21:16:08Z
39,112,160
<p>Tkinter provides no option for this. Alt-tab is intercepted before tkinter ever sees it. If you want to do this, you'll have to find some platform-specific hooks.</p>
0
2016-08-23T23:21:53Z
[ "python", "python-3.x", "tkinter" ]
Can SQLAlchemy Use MySQL's SSCursor For Only Some Queries?
39,110,864
<p>I have a query that fetches a lot of data from my MySQL db, where loading all of the data into memory isn't an option. Luckily, SQLAlchemy lets me create an engine using MySQL's SSCursor, so the data is streamed and not fully loaded into memory. I can do this like so:</p> <pre><code>create_engine(connect_str, conne...
1
2016-08-23T21:20:31Z
39,112,538
<p>From the <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html" rel="nofollow">docs</a>:</p> <blockquote> <p>stream_results – Available on: Connection, statement. Indicate to the dialect that results should be “streamed” and not pre-buffered, if possible. This is a limitation of many DBAPI...
0
2016-08-24T00:12:16Z
[ "python", "mysql", "sqlalchemy" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a>...
-1
2016-08-23T21:23:23Z
39,111,008
<p>You have to assign the return value of <code>attack1</code> to <code>playerhp</code>:</p> <pre><code>def attack1(x): x = (x - 17) return x playerhp = 100 while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": playerhp = attack1(play...
2
2016-08-23T21:32:08Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a>...
-1
2016-08-23T21:23:23Z
39,111,058
<p>Here's a working example of your code:</p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": playerhp = attack1(playerhp) print(playerhp) else: ...
0
2016-08-23T21:35:14Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a>...
-1
2016-08-23T21:23:23Z
39,111,086
<p>As mentioned in a comment above, this issue comes down to scoping. Try googling that for more info, but I'll try to give a beginner level explanation here.</p> <p>When you declare a variable, it exists in a specific scope, and can only be accessed by variables in the same or a lower scope. For example,</p> <pre>...
0
2016-08-23T21:38:04Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a>...
-1
2016-08-23T21:23:23Z
39,111,090
<p>There are two approaches to achieve it.</p> <p><em>Approach 1</em>: Update <code>playerhp</code>'s value based on value return by <code>attack1()</code>. For example:</p> <pre><code>&gt;&gt;&gt; playerhp = 100 &gt;&gt;&gt; def attack1(x): ... return x -= 17 ... &gt;&gt;&gt; playerhp = attack1(playerhp) &gt;&...
0
2016-08-23T21:38:46Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a>...
-1
2016-08-23T21:23:23Z
39,112,231
<pre><code>#this works for me. You were not printing the result of the function. def attack1(x): return(x-17) playerhp=100 while playerhp&gt;0: enemyattack= input("Please type the word 'attack':") if enemyattack.upper()=="ATTACK": x=attack1(playerhp) print (x) else: break </co...
0
2016-08-23T23:30:59Z
[ "python", "function" ]
Run pip through jenkins-plugin?
39,110,980
<p>If pip is not installed on the jenkins linux-box, is there any jenkins-plugin that lets me run pip, without installing it at the os-level?</p>
0
2016-08-23T21:29:59Z
39,111,137
<p>Create a <a href="https://docs.python.org/3/library/venv.html" rel="nofollow">virtual environment</a>. It should come with pip, but otherwise install it in the virtualenv.</p>
0
2016-08-23T21:42:06Z
[ "python", "linux", "jenkins", "pip" ]
Run pip through jenkins-plugin?
39,110,980
<p>If pip is not installed on the jenkins linux-box, is there any jenkins-plugin that lets me run pip, without installing it at the os-level?</p>
0
2016-08-23T21:29:59Z
39,174,711
<p>Not a specific plug-in like you might want, but as was said, you can create a virtual environment in one of a few ways to get the functionality you're after.</p> <p>Docker can handle this, you can create a small script to build a docker image that will have access to pip and there are Jenkins plug-ins for docker.</...
0
2016-08-26T21:14:37Z
[ "python", "linux", "jenkins", "pip" ]