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 |
|---|---|---|---|---|---|---|---|---|---|
Pandas: Use apply to sum row and column on data frame | 39,859,374 | <pre><code>import datetime
import pandas as pd
import numpy as np
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ['A','B', 'C']
df = pd.DataFrame(index=index, columns=columns)
df = df.fillna(0) # with 0s rather than NaNs
data = np... | 1 | 2016-10-04T18:31:38Z | 39,859,822 | <p>I am unsure of your question so I'll guess it. First off I don't like to use integer value so let's transform your df to float</p>
<pre><code>df = df.astype(float)
</code></pre>
<p>if you want to divide each element of column A by the sum of column A and vice versa you could do this :</p>
<pre><code>df.div(df.sum... | 1 | 2016-10-04T18:59:18Z | [
"python",
"pandas",
"aggregation"
] |
Get grouped Dictionary list from a file that has a time and errors then plot the time differences in python | 39,859,392 | <p>I have this file as below:</p>
<pre><code>Date;Time;Task;Error_Line;Error_Message
03-13-15;08:2123:10;C:LOGINMAN;01073;Web Login Successful from IP Address xxx.xxx.x.xx
03-13-15;05:23:1235;B:VDOM;0906123;Port 123 Device 1012300 Remote 1 1012301 Link Up RP2009
03-13-15;05:23:123123;A:VCOM;0906123;Port 123 Device 101... | 0 | 2016-10-04T18:32:54Z | 39,859,985 | <p>As far as grouping by line number, this should do the trick:</p>
<pre><code>import csv
D = {}
with open('logfile') as f:
reader = csv.DictReader(f, delimiter=';')
for row in reader:
el = row['Error_Line']
if el not in D:
D[el] = [] # Initiate an empty list
D[el].append(r... | 1 | 2016-10-04T19:10:14Z | [
"python",
"numpy",
"matplotlib",
"plot"
] |
Get grouped Dictionary list from a file that has a time and errors then plot the time differences in python | 39,859,392 | <p>I have this file as below:</p>
<pre><code>Date;Time;Task;Error_Line;Error_Message
03-13-15;08:2123:10;C:LOGINMAN;01073;Web Login Successful from IP Address xxx.xxx.x.xx
03-13-15;05:23:1235;B:VDOM;0906123;Port 123 Device 1012300 Remote 1 1012301 Link Up RP2009
03-13-15;05:23:123123;A:VCOM;0906123;Port 123 Device 101... | 0 | 2016-10-04T18:32:54Z | 39,860,357 | <p>I won't touch the plotting because there are multiple ways of displaying the data and I don't know what style you're looking for. Do you want to have separate graphs for each Error_Line? Each Error_Line's datapoints represented on one graph? Some other way of comparing times and errors (e.g. mean of each Error_Line'... | 1 | 2016-10-04T19:32:46Z | [
"python",
"numpy",
"matplotlib",
"plot"
] |
moving the location of y labels with matplotlib | 39,859,446 | <p>How can I move the location of y labels?</p>
<p><a href="http://i.stack.imgur.com/bIhOP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/bIhOP.jpg" alt="enter image description here"></a></p>
<p>And this is the zoomed version:</p>
<p><a href="http://i.stack.imgur.com/jkHHw.png" rel="nofollow"><img src="htt... | 0 | 2016-10-04T18:36:13Z | 39,866,712 | <p>Normally, the data does not flush out of the axis frame. This might however differ for an axis with dates. Since your data goes up to 3rd of october while in the non-zoomed version your last point on the x axis ist the first of october, you should simply plot your data until the 3rd of october or beyond. </p>
<p>Th... | 0 | 2016-10-05T06:20:16Z | [
"python",
"matplotlib"
] |
moving the location of y labels with matplotlib | 39,859,446 | <p>How can I move the location of y labels?</p>
<p><a href="http://i.stack.imgur.com/bIhOP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/bIhOP.jpg" alt="enter image description here"></a></p>
<p>And this is the zoomed version:</p>
<p><a href="http://i.stack.imgur.com/jkHHw.png" rel="nofollow"><img src="htt... | 0 | 2016-10-04T18:36:13Z | 39,873,309 | <p>showing how I did it in the end after @ImportanceOfBeingErnest pointed the right direction:</p>
<p>1) created an extra date that is actually longer than the last day of my data</p>
<pre><code>extradate = pd.Timestamp(dt.datetime(df.index[-1].year,df.index[-1].month,df.index[-1].day + 5))
</code></pre>
<p>2) use... | 0 | 2016-10-05T11:57:03Z | [
"python",
"matplotlib"
] |
Extract specific information from XML (Google Distance Matrix API) | 39,859,482 | <p>Here is my XML output:</p>
<pre><code><DistanceMatrixResponse>
<status>OK</status>
<origin_address>
868-978 Middle Tennessee Blvd, Murfreesboro, TN 37130, USA
</origin_address>
<destination_address>
980-1060 Middle Tennessee Blvd, Murfreesboro, TN 37130, USA
</destination_addr... | 0 | 2016-10-04T18:39:21Z | 39,860,297 | <p>Just use <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#example" rel="nofollow">XPath queries</a>:</p>
<pre><code>duration = tree.find('.//duration/value').text
distance = tree.find('.//distance/value').text
</code></pre>
<p>Here's a nice XPath tutorial: <a href="http://zvon.org/comp/r/tut-X... | 0 | 2016-10-04T19:28:53Z | [
"python",
"xml",
"elementtree"
] |
How to update a subset of 2D tensor in Tensorflow? | 39,859,516 | <p>I want to update an index in a 2D tensor with value 0. So data is a 2D tensor whose 2nd row 2nd column index value is to be replaced by 0. However, I am getting a type error. Can anyone help me with it?</p>
<blockquote>
<p>TypeError: Input 'ref' of 'ScatterUpdate' Op requires l-value input</p>
</blockquote>
<pre... | 0 | 2016-10-04T18:41:12Z | 39,860,467 | <p>Scatter update only works on variables. Instead try this pattern
<code>a = tf.concat(0, [a[:i], [updated_value], a[i+1:]])</code></p>
| 0 | 2016-10-04T19:39:50Z | [
"python",
"neural-network",
"tensorflow",
"deep-learning"
] |
How to update a subset of 2D tensor in Tensorflow? | 39,859,516 | <p>I want to update an index in a 2D tensor with value 0. So data is a 2D tensor whose 2nd row 2nd column index value is to be replaced by 0. However, I am getting a type error. Can anyone help me with it?</p>
<blockquote>
<p>TypeError: Input 'ref' of 'ScatterUpdate' Op requires l-value input</p>
</blockquote>
<pre... | 0 | 2016-10-04T18:41:12Z | 39,959,911 | <p><code>tf.scatter_update</code> could only be applied to <code>Variable</code> type. <code>data</code> in your code IS a <code>Variable</code>, while <code>data2</code> IS NOT, because the return type of <code>tf.reshape</code> is <code>Tensor</code>.</p>
<p>Solution:</p>
<pre><code>data = tf.Variable([[1,2,3,4,5],... | 1 | 2016-10-10T13:51:47Z | [
"python",
"neural-network",
"tensorflow",
"deep-learning"
] |
List KeyError Python | 39,859,562 | <p>I'm trying to append a list with values from an API for the Glassdoor.</p>
<p>When I get a response back from this API, I get info such as the name of the company, ratings, CEO, a bunch more info, and lastly if the company is owned by a parent company, I get that too.</p>
<p>My problem is when I append my list wit... | 0 | 2016-10-04T18:43:52Z | 39,859,615 | <p>I am not sure if I fully understand your question, but Python has a concept of "Better to ask forgiveness than permission" that might be helpful here:</p>
<pre><code>try:
comp_info.append(data['response']['employers'][0]['name'])
except KeyError:
comp_info.append("N/A")
# or print ("N/A")
</code></pre>
... | 0 | 2016-10-04T18:47:26Z | [
"python",
"json",
"for-loop",
"keyerror"
] |
List KeyError Python | 39,859,562 | <p>I'm trying to append a list with values from an API for the Glassdoor.</p>
<p>When I get a response back from this API, I get info such as the name of the company, ratings, CEO, a bunch more info, and lastly if the company is owned by a parent company, I get that too.</p>
<p>My problem is when I append my list wit... | 0 | 2016-10-04T18:43:52Z | 39,859,871 | <p>If I understand you correctly:</p>
<pre><code>comp_info.append(data['response']['employers'][0].get('name', 'N/A'))
</code></pre>
| 0 | 2016-10-04T19:02:18Z | [
"python",
"json",
"for-loop",
"keyerror"
] |
List KeyError Python | 39,859,562 | <p>I'm trying to append a list with values from an API for the Glassdoor.</p>
<p>When I get a response back from this API, I get info such as the name of the company, ratings, CEO, a bunch more info, and lastly if the company is owned by a parent company, I get that too.</p>
<p>My problem is when I append my list wit... | 0 | 2016-10-04T18:43:52Z | 39,862,871 | <pre><code>comp_info.append(data['response']['employers'][0].get('parentEmployer', 'N/A'))
</code></pre>
| 0 | 2016-10-04T22:42:11Z | [
"python",
"json",
"for-loop",
"keyerror"
] |
How can I rewrite this list comprehension as a for loop? | 39,859,566 | <p>How can I rewrite this using nested for loops instead of a list comprehension? </p>
<pre><code>final= [[]]
for i in array_list:
final.extend([sublist + [i] for sublist in final])
return final
</code></pre>
| 0 | 2016-10-04T18:44:08Z | 39,859,780 | <p>Your solution looks to be a very good <code>for</code> loop one. A one-liner using <code>itertools</code> is possible, but ugly</p>
<pre><code>list(itertools.chain(list(itertools.combinations(arr, i)) for i in range(len(arr) + 1)))
</code></pre>
<p>EDIT:</p>
<p>Prettier:</p>
<pre><code>list(itertools.chain(*[it... | 0 | 2016-10-04T18:56:53Z | [
"python"
] |
How can I rewrite this list comprehension as a for loop? | 39,859,566 | <p>How can I rewrite this using nested for loops instead of a list comprehension? </p>
<pre><code>final= [[]]
for i in array_list:
final.extend([sublist + [i] for sublist in final])
return final
</code></pre>
| 0 | 2016-10-04T18:44:08Z | 39,859,786 | <p>If you try to iterate over final as you extend it, it creates an infinite loop. Because every time you go to the next element, you add another element, so you never reach the end of the list. </p>
<p>If you want to do the inner loop as a for loop instead of a list comprehension, you need to iterate over a copy of f... | 2 | 2016-10-04T18:57:03Z | [
"python"
] |
How can I rewrite this list comprehension as a for loop? | 39,859,566 | <p>How can I rewrite this using nested for loops instead of a list comprehension? </p>
<pre><code>final= [[]]
for i in array_list:
final.extend([sublist + [i] for sublist in final])
return final
</code></pre>
| 0 | 2016-10-04T18:44:08Z | 39,860,626 | <p>This code also seems to give the same results as your code. </p>
<pre><code>final = [[]]
for i in array_list:
for sublist in list(final):
final.extend([sublist + [i]])
return final
</code></pre>
<p>It seems like your code takes the elements of the last iteration and combines them with the element of th... | 0 | 2016-10-04T19:49:21Z | [
"python"
] |
Python Regex handling dot character | 39,859,662 | <p>While using regex in python I came across a scenario.
What I am trying to do is if a string has operators, I want to add space before and after the operator.</p>
<pre><code>s = 'H>=ll<=o=wo+rl-d.my name!'
op = 'H >= ll <= o = wo + rl - d.my name!'
</code></pre>
<p>seemed pretty straight forward, so I c... | 1 | 2016-10-04T18:50:10Z | 39,859,758 | <p>The reason for the spaces around the dot is <code>-</code>. Concrete it is <code>[+-=]</code>, which is a character class with characters from <code>+</code> until <code>=</code>, which includes <code>.</code>.</p>
<p>To avoid this, you must escape <code>-</code> with <code>\-</code>, e.g. </p>
<pre><code>re.sub(r... | 7 | 2016-10-04T18:55:42Z | [
"python",
"regex"
] |
Python Regex handling dot character | 39,859,662 | <p>While using regex in python I came across a scenario.
What I am trying to do is if a string has operators, I want to add space before and after the operator.</p>
<pre><code>s = 'H>=ll<=o=wo+rl-d.my name!'
op = 'H >= ll <= o = wo + rl - d.my name!'
</code></pre>
<p>seemed pretty straight forward, so I c... | 1 | 2016-10-04T18:50:10Z | 39,859,777 | <p>So when you do a character class like:</p>
<pre><code>[+-=]
</code></pre>
<p>The regex reads that as any character between <code>+</code> (ASCII 43) and <code>=</code> (ASCII 61). It's similar to:</p>
<pre><code>[A-Z]
</code></pre>
<p>So you have to escape the <code>-</code>:</p>
<pre><code>r'((<=)|(>=)|[... | 4 | 2016-10-04T18:56:44Z | [
"python",
"regex"
] |
Python Regex handling dot character | 39,859,662 | <p>While using regex in python I came across a scenario.
What I am trying to do is if a string has operators, I want to add space before and after the operator.</p>
<pre><code>s = 'H>=ll<=o=wo+rl-d.my name!'
op = 'H >= ll <= o = wo + rl - d.my name!'
</code></pre>
<p>seemed pretty straight forward, so I c... | 1 | 2016-10-04T18:50:10Z | 39,859,849 | <p>I was able to simplify this a little bit by using a negated set:</p>
<pre><code>import re
s = 'H>=ll<=o=wo+rl-d.my name!'
op = 'H >= ll <= o = wo + rl - d.my name!'
s = re.sub(r'([^a-zA-Z0-9.])+',' \\1 ',r'H>=ll<=o=wo+rl-d.myname!')
print (s)
</code></pre>
<p>Other commenters above mentioned the ... | 0 | 2016-10-04T19:00:54Z | [
"python",
"regex"
] |
Error in tf.contrib.learn Quickstart, no attribute named load_csv | 39,859,670 | <p>I am getting started in tensorflow on OSX and installed the lasted version following the guidelines for a pip installation using:</p>
<pre><code>echo $TF_BINARY_URL
https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py2-none-any.whl
</code></pre>
<p>Quick overview:</p>
<p>OS: OS X El Capitan v... | 1 | 2016-10-04T18:50:35Z | 39,861,351 | <p>This function has been deprecated: <a href="https://github.com/tensorflow/tensorflow/commit/2d4267507e312007a062a90df37997bca8019cfb" rel="nofollow">https://github.com/tensorflow/tensorflow/commit/2d4267507e312007a062a90df37997bca8019cfb</a></p>
<p>And the tutorial seems not up to date. I believe you can simply rep... | 1 | 2016-10-04T20:38:54Z | [
"python",
"osx",
"python-2.7",
"tensorflow",
"osx-elcapitan"
] |
creating teaming from user input | 39,859,761 | <p>I'm trying to create a centos 7 a networking teaming (bonding) using a user input in a python script. C</p>
<pre><code>import socket
# IP Address
IPADDR = socket.gethostbyname(socket.gethostname())
print IPADDR
# Netmask
NETMASK = raw_input("Enter Netmask address: ")
PREFIX = sum([bin(int(x)).count("1") for x in N... | 0 | 2016-10-04T18:55:47Z | 39,859,831 | <p>Sure -- you terminated the string, as shown by the colouring of the text. It starts at <strong>"nmcli</strong>. Use a pair of double quotation marks to have them as a literal within the outer string.</p>
<pre><code>os.system("nmcli con add type team con-name team0 ifname team0 config '{""runner"":
</code></pre>
... | 2 | 2016-10-04T18:59:54Z | [
"python"
] |
creating teaming from user input | 39,859,761 | <p>I'm trying to create a centos 7 a networking teaming (bonding) using a user input in a python script. C</p>
<pre><code>import socket
# IP Address
IPADDR = socket.gethostbyname(socket.gethostname())
print IPADDR
# Netmask
NETMASK = raw_input("Enter Netmask address: ")
PREFIX = sum([bin(int(x)).count("1") for x in N... | 0 | 2016-10-04T18:55:47Z | 39,859,853 | <p>The syntax error is occurring because you are not escaping the quote <code>"</code> characters. The interpreter thinks that the string has ended and then trips.</p>
<p>You can use a backslash <code>\</code> to escape the quote:</p>
<pre><code>os.system("nmcli con add type team con-name team0 ifname team0 config '{... | 2 | 2016-10-04T19:00:58Z | [
"python"
] |
Python regex to remove punctuation except from URLs and decimal numbers | 39,859,764 | <p>People,</p>
<p>I need a regex to remove punctuation from a string, but keep the accents and URLs. I also have to keep the mentions and hashtags from that string.</p>
<p>I tried with the code above but unfortunately, it replaces the characters with accents but I want to keep the accents.</p>
<pre><code>import unic... | 0 | 2016-10-04T18:56:03Z | 39,860,030 | <p>You can use Python's <a href="https://docs.python.org/3/library/re.html#module-contents" rel="nofollow">regex module</a> and <code>re.sub()</code> to replace any characters you want to get rid of. You can either use a blacklist and replace all the characters you don't want, or use a whitelist of all the characters y... | 0 | 2016-10-04T19:13:11Z | [
"python",
"regex",
"nltk"
] |
How can I install pythonds module? | 39,859,834 | <p>when I run a programme containing:-</p>
<p>from pythonds.basic.stack import Stack</p>
<p>it says:-
ImportError: No module named pythonds.basic.stack</p>
<p>Please help me out.</p>
| 1 | 2016-10-04T19:00:01Z | 39,859,868 | <p><code>pip install pythonds</code>. </p>
<p>And then <code>from pythonds.basic.stack import Stack</code>. Note that it's <code>Stack</code>, not <code>stack</code>.</p>
| 3 | 2016-10-04T19:02:10Z | [
"python",
"data-structures",
"stack",
"python-module"
] |
How can I install pythonds module? | 39,859,834 | <p>when I run a programme containing:-</p>
<p>from pythonds.basic.stack import Stack</p>
<p>it says:-
ImportError: No module named pythonds.basic.stack</p>
<p>Please help me out.</p>
| 1 | 2016-10-04T19:00:01Z | 39,860,364 | <p>if you do not have the python path variable set, then type this into your command prompt.</p>
<p>C:\Python34\Scripts\pip install LIBRARY NAME</p>
<p>I cant remember if it is a forward slash, or a backslash, but try either. Or wherever you have python saved.</p>
| 0 | 2016-10-04T19:33:28Z | [
"python",
"data-structures",
"stack",
"python-module"
] |
Python - Split pdf by pages | 39,859,835 | <p>I am using <code>PyPdf2</code> to split large <code>PDF</code> to pages. The problem is that this process is very slow.</p>
<p>This is the code i use:</p>
<pre><code>import os
from PyPDF2 import PdfFileWriter, PdfFileReader
with open(input_pdf_path, "rb") as input_file:
input_pdf = PdfFileReader(input_file)
... | 1 | 2016-10-04T19:00:03Z | 39,868,722 | <h3>Refactoring</h3>
<p>I have refactored the code like this:</p>
<pre><code>import os
import PyPDF2
def split_pdf_pages(input_pdf_path, target_dir, fname_fmt=u"{num_page:04d}.pdf"):
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with open(input_pdf_path, "rb") as input_stream:
... | 1 | 2016-10-05T08:15:30Z | [
"python",
"python-3.x",
"pdf",
"pypdf",
"pypdf2"
] |
Python - Split pdf by pages | 39,859,835 | <p>I am using <code>PyPdf2</code> to split large <code>PDF</code> to pages. The problem is that this process is very slow.</p>
<p>This is the code i use:</p>
<pre><code>import os
from PyPDF2 import PdfFileWriter, PdfFileReader
with open(input_pdf_path, "rb") as input_file:
input_pdf = PdfFileReader(input_file)
... | 1 | 2016-10-04T19:00:03Z | 39,872,566 | <p>Any optimization couldn't really make a real improvement. I ended up using <code>pdftk</code>. I came across with this <a href="http://linuxcommando.blogspot.co.il/2013/02/splitting-up-is-easy-for-pdf-file.html" rel="nofollow">page</a> which explains really nice how to split pages fast. </p>
<p><code>pdftk</code> i... | 0 | 2016-10-05T11:19:30Z | [
"python",
"python-3.x",
"pdf",
"pypdf",
"pypdf2"
] |
How to use a variable from main in another function? | 39,860,055 | <p>In the following code how to I make the variable 'guesses' available to me in the 'end' function. Whenever I try this I just receive a guesses is not defined. In the play function I am returning a number and if I understand correctly than that number should be equal to 'guesses', and for a reason I don't understand ... | -2 | 2016-10-04T19:15:12Z | 39,860,115 | <p>Pass it as a parameter</p>
<pre><code>def main():
guesses = play()
play_again = again()
while (play_again == True):
guesses = play()
play_again = again()
total_games = 1
total_games += 1
end(guesses)
def end(guesses):
print("Results: ")
print("Total: " + str(... | 5 | 2016-10-04T19:18:16Z | [
"python"
] |
How to use a variable from main in another function? | 39,860,055 | <p>In the following code how to I make the variable 'guesses' available to me in the 'end' function. Whenever I try this I just receive a guesses is not defined. In the play function I am returning a number and if I understand correctly than that number should be equal to 'guesses', and for a reason I don't understand ... | -2 | 2016-10-04T19:15:12Z | 39,860,144 | <p>Something like this: </p>
<pre><code>def main():
guesses = play()
play_again = again()
while (play_again == True):
guesses = play()
play_again = again()
total_games = 1
total_games += 1
end(guesses)
def end(guesses):
print("Results: ")
print("Total: {}".forma... | 2 | 2016-10-04T19:19:52Z | [
"python"
] |
How to use a variable from main in another function? | 39,860,055 | <p>In the following code how to I make the variable 'guesses' available to me in the 'end' function. Whenever I try this I just receive a guesses is not defined. In the play function I am returning a number and if I understand correctly than that number should be equal to 'guesses', and for a reason I don't understand ... | -2 | 2016-10-04T19:15:12Z | 39,860,164 | <p>Simply pass <code>guesses</code> as a parameter to <code>end()</code> </p>
<pre><code>def main():
guesses = play()
play_again = again()
while (play_again == True):
guesses = play()
play_again = again()
total_games = 1
total_games += 1
end(guesses)
def end(guesses):
... | 0 | 2016-10-04T19:20:56Z | [
"python"
] |
How to use a variable from main in another function? | 39,860,055 | <p>In the following code how to I make the variable 'guesses' available to me in the 'end' function. Whenever I try this I just receive a guesses is not defined. In the play function I am returning a number and if I understand correctly than that number should be equal to 'guesses', and for a reason I don't understand ... | -2 | 2016-10-04T19:15:12Z | 39,860,237 | <p><code>main()</code> and <code>end()</code> are two separate functions with separate scopes. You defined the variable <code>guesses</code> inside the function <code>main()</code>. It will not be available to <code>end()</code>, because the scope in which <code>end()</code> was defined did not have access to <code>gue... | 2 | 2016-10-04T19:25:37Z | [
"python"
] |
How to get these information in context of given below using beautiful soup python | 39,860,107 | <p>Going to <a href="https://www.couponraja.in" rel="nofollow">https://www.couponraja.in</a></p>
<p>I need to data scrape the whole website with the code:
As I wrote my code like this:</p>
<pre><code>wiki = 'https://www.couponraja.in'
page = urllib2.urlopen(wiki)
soup = BeautifulSoup(page, 'html.parser')
titles = s... | -3 | 2016-10-04T19:17:54Z | 39,860,725 | <p>I don't really see anything wrong with your code. Perhaps the approach can be modified. If your going to use a for loop for all the items you are parsing it going to take code. If things on that page are being generated with javascript, then you can't use the raw html you get from a get request, you'll probably hav... | 0 | 2016-10-04T19:55:54Z | [
"python",
"html",
"beautifulsoup"
] |
How to serialize a one to many relation in django-rest using Model serializer? | 39,860,114 | <p>These are my models and serializers. I want a representation of Question Model along with a list of people the question was asked to.</p>
<p>I am trying this:</p>
<pre><code>@api_view(['GET', 'PATCH'])
def questions_by_id(request,user,pk):
question = Question.objects.get(pk=pk)
if request.method == 'GET':
... | 0 | 2016-10-04T19:18:15Z | 39,860,737 | <p>I figured it out. There were two errors.</p>
<p>changed this to </p>
<pre><code>class AskedToSerializer(serializers.ModelSerializer):
class Meta:
model = AskedTo
fields = ('to_user', 'answered')
</code></pre>
<p>this (notice the change in fields, fields on model and serializer didn't match)</p>
<pre><co... | 0 | 2016-10-04T19:56:42Z | [
"python",
"serialization",
"django-rest-framework",
"one-to-many",
"django-serializer"
] |
Pandas Column differences, containing lists | 39,860,131 | <p>I have a data frame where the columns values are list and want to find the differences between two columns, or in other words I want to find all the elements in column A which is not there in column B.</p>
<pre><code>data={'NAME':['JOHN','MARY','CHARLIE'],
'A':[[1,2,3],[2,3,4],[3,4,5]],
'B':[[2,3,4],[3,4,5],[4,... | 0 | 2016-10-04T19:19:00Z | 39,860,356 | <p>For a set difference,</p>
<pre><code>df['A'].map(set) - df['B'].map(set)
</code></pre>
| 1 | 2016-10-04T19:32:27Z | [
"python",
"list",
"pandas",
"dataframe"
] |
How can I get subgroups of the match in Scala? | 39,860,158 | <p>I have the following in python:</p>
<pre><code> regex.sub(lambda t: t.group(1).replace(" ", " ") + t.group(2),string)
</code></pre>
<p>where <code>regex</code> is a Regular Expression and <code>string</code> is a filled String. </p>
<p>So I am trying to do the same in Scala, using <code>regex.replaceAllIn(.... | 4 | 2016-10-04T19:20:37Z | 39,860,234 | <p>You can use <code>replaceAll</code>, and use <code>$n</code>, where "n" is the group you want to match. For example:</p>
<pre><code>yourString.replaceAll(yourRegex, "$1")
</code></pre>
<p>Replaces the matched parts with the first group.</p>
| 2 | 2016-10-04T19:25:32Z | [
"python",
"scala",
"grouping"
] |
How can I get subgroups of the match in Scala? | 39,860,158 | <p>I have the following in python:</p>
<pre><code> regex.sub(lambda t: t.group(1).replace(" ", " ") + t.group(2),string)
</code></pre>
<p>where <code>regex</code> is a Regular Expression and <code>string</code> is a filled String. </p>
<p>So I am trying to do the same in Scala, using <code>regex.replaceAllIn(.... | 4 | 2016-10-04T19:20:37Z | 39,861,056 | <p>Maybe other way to do this is having a <code>regex</code>, for example:</p>
<pre><code>val regExtractor = """a(b+)(c+)(d*)""".r
</code></pre>
<p>And then match the <code>String:</code></p>
<pre><code>val string = "abbbbbbbbbccdd"
val newString = string match {
case regExtractor(g1, g2, g3) =>
s"""String... | 1 | 2016-10-04T20:18:52Z | [
"python",
"scala",
"grouping"
] |
How can I get subgroups of the match in Scala? | 39,860,158 | <p>I have the following in python:</p>
<pre><code> regex.sub(lambda t: t.group(1).replace(" ", " ") + t.group(2),string)
</code></pre>
<p>where <code>regex</code> is a Regular Expression and <code>string</code> is a filled String. </p>
<p>So I am trying to do the same in Scala, using <code>regex.replaceAllIn(.... | 4 | 2016-10-04T19:20:37Z | 39,862,503 | <p>The scaladoc has one example. Provide a function from <code>Match</code> instead of a string.</p>
<pre><code>scala> val r = "a(b)(c)+".r
r: scala.util.matching.Regex = a(b)(c)+
scala> val s = "123 abcccc and abcc"
s: String = 123 abcccc and abcc
scala> r.replaceAllIn(s, m => s"a${m.group(1).toUpperCas... | 3 | 2016-10-04T22:07:16Z | [
"python",
"scala",
"grouping"
] |
Nose generate dynamically test with decorator | 39,860,189 | <p>I have dynamic amount of test so i want use for loop
I'd try something like:</p>
<pre><code>from nose.tools import istest, nottest
from nose.tools import eq_
import nose
nose.run()
@istest
def test_1():
for i in range(100):
@istest
def test_1_1():
eq_(randint(1,1),1)
-------------... | 1 | 2016-10-04T19:22:56Z | 39,860,236 | <p>For data-driven tests in nose, check out <a href="https://pypi.python.org/pypi/nose-parameterized/" rel="nofollow"><code>nose_parameterized</code></a>.</p>
<p>Example usage:</p>
<pre><code>from nose_parameterized import parameterized
@parameterized.expand([(1, 1, 2), (2, 2, 4)])
def test_add(self, a, b, sum):
... | 2 | 2016-10-04T19:25:37Z | [
"python",
"python-2.7",
"nose"
] |
How can i create a dictionary from a dataframe without specifying column names in pandas? | 39,860,219 | <p>I am trying to convert the dataframe into dictionary in pandas and i got into a problem. When i specify the column names i was able to convert the dataframe into dictionary but when i tried to do without specifying column names but just by column numbers it throws an error. </p>
<p>Here is an example of my datafram... | 0 | 2016-10-04T19:24:29Z | 39,860,574 | <p>you cannot call a column like that if you don't know the name. If you only know the position you could</p>
<pre><code> dict(zip(df.id,df.iloc[:,1]))
</code></pre>
<p>would be the second column. if you want the first use 0</p>
| 1 | 2016-10-04T19:45:38Z | [
"python",
"pandas",
"dictionary"
] |
How to apply read/write permissions to user-uploaded files in Django | 39,860,225 | <p>I have a "document" model, an upload system using dropzone.js and the register/login. Im now lost on how to apply permissions to each individual uploaded <strong>File</strong> so only the specified users can access them.</p>
<p>Basically:
File1->accessible_by = user1,user2</p>
<p>File2->accesible_by=user3,user5...... | 1 | 2016-10-04T19:24:51Z | 39,861,922 | <p>You can add an <code>allowed_user</code> field into the document model, so that only those users specified can access the files. for example:</p>
<pre><code>class Document(models.Model):
file = FileField()
uploaded_by = models.ForeignKey(User, related_name='uploadedByAsUser')
allowed_users = models.Many... | 0 | 2016-10-04T21:18:28Z | [
"python",
"django",
"authentication",
"permissions"
] |
How to apply read/write permissions to user-uploaded files in Django | 39,860,225 | <p>I have a "document" model, an upload system using dropzone.js and the register/login. Im now lost on how to apply permissions to each individual uploaded <strong>File</strong> so only the specified users can access them.</p>
<p>Basically:
File1->accessible_by = user1,user2</p>
<p>File2->accesible_by=user3,user5...... | 1 | 2016-10-04T19:24:51Z | 39,862,182 | <p>You can set content_type on a HttpResponse. So you can do permission handling in your view and serve the file directly from Django:</p>
<pre><code>return HttpResponse("Text only, please.", content_type="text/plain")
</code></pre>
<p>Note: Django isn't a web server. It is recommended to use a web server for serving... | 0 | 2016-10-04T21:38:21Z | [
"python",
"django",
"authentication",
"permissions"
] |
Trying to take input from stdin and convert to integer for sum | 39,860,245 | <p>Very new to Python.
Trying to take inputs from stdin in the form of numbers ex. 416 2876 2864 8575 9784 and convert to int for sum of all using a loop.</p>
<p>Having a terrible time just converting to int for use in a loop. Would like to get a hint on the integer issue and then try to solve myself. Was trying to te... | -1 | 2016-10-04T19:25:55Z | 39,860,316 | <p>You probably don't want to use <code>sys.stdin</code> directly. Use <code>input()</code> instead.</p>
<pre><code>line = input("Enter some numbers: ")
total = 0
for n in line.split():
total = total + int(n)
print("The total is: %d" % total)
</code></pre>
| 1 | 2016-10-04T19:30:10Z | [
"python"
] |
Trying to take input from stdin and convert to integer for sum | 39,860,245 | <p>Very new to Python.
Trying to take inputs from stdin in the form of numbers ex. 416 2876 2864 8575 9784 and convert to int for sum of all using a loop.</p>
<p>Having a terrible time just converting to int for use in a loop. Would like to get a hint on the integer issue and then try to solve myself. Was trying to te... | -1 | 2016-10-04T19:25:55Z | 39,860,330 | <pre><code>user_input = input("Type some numbers: ")
numbers = user_input.split()
print(sum([int(x) for x in numbers]))
</code></pre>
| 0 | 2016-10-04T19:30:45Z | [
"python"
] |
Trying to take input from stdin and convert to integer for sum | 39,860,245 | <p>Very new to Python.
Trying to take inputs from stdin in the form of numbers ex. 416 2876 2864 8575 9784 and convert to int for sum of all using a loop.</p>
<p>Having a terrible time just converting to int for use in a loop. Would like to get a hint on the integer issue and then try to solve myself. Was trying to te... | -1 | 2016-10-04T19:25:55Z | 39,860,589 | <p>If you want to read from <em>stdin</em> and cast to int just iterate over stdin and split then cast each int and <em>sum</em> :</p>
<pre><code>~$ cat test.py
import sys
print(sum(int(i) for sub in sys.stdin for i in sub.split()))
padraic@dell:~$ printf "416 2876 2864 8575 9784\n123 456 789 120"|python test.py
2... | 0 | 2016-10-04T19:46:42Z | [
"python"
] |
Python Requests ignoring time outs | 39,860,257 | <p>I'm trying to make some kind of a scanner with python (just for fun)</p>
<p>it will send a get request to an random ip and see if there is any answer
the problem is that every time that the connection fails the program will stop running .
this is the code </p>
<pre><code>import time
import requests
ips = open(... | 0 | 2016-10-04T19:26:34Z | 39,860,302 | <p>This is throwing an error. To protect against this, use a <code>try</code>/<code>except</code> statement:</p>
<pre><code>for ip in ips:
try:
r = requests.get(url="http://"+ip+"/",verify=False)
print(r.status_code)
except requests.exceptions.RequestException as e:
print('Connecting to... | 2 | 2016-10-04T19:29:06Z | [
"python",
"python-requests"
] |
Modifying a pandas dataframe that may be a view | 39,860,269 | <p>I have a pandas <code>DataFrame</code> <code>df</code> that is returned from a function and I generally don't know whether it is an independent object or a view on another <code>DataFrame</code>. I want to add new columns to it but don't want to copy it unnecessarily.</p>
<pre><code>df['new_column'] = 0
</code></pr... | 0 | 2016-10-04T19:27:11Z | 39,860,742 | <p>you should use an indexer to create your s1 such has:</p>
<pre><code>import pandas as pd
s = pd.DataFrame({'a':[1,2], 'b':[2,3]})
indexer = s[s.a > 1].index
s1 = s.loc[indexer, :]
s1['c'] = 0
</code></pre>
<p>should remove the warning.</p>
| 0 | 2016-10-04T19:56:57Z | [
"python",
"pandas"
] |
is there a way I can store the factorization machine model? | 39,860,371 | <p>I am using <a href="https://github.com/coreylynch/pyFM" rel="nofollow">https://github.com/coreylynch/pyFM</a> module, to predict move ratings. However, is there a way I can store (I am using django) the factorization machine after it is trained? Because right now (following the example), I would have to retrain the ... | 0 | 2016-10-04T19:33:54Z | 39,860,426 | <p>Take a look at <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle</a>. After you train your model, you can save a representation of the python object to a file, and reopen it when you need it.</p>
| 0 | 2016-10-04T19:37:28Z | [
"python",
"django",
"machine-learning",
"artificial-intelligence",
"collaborative-filtering"
] |
is there a way I can store the factorization machine model? | 39,860,371 | <p>I am using <a href="https://github.com/coreylynch/pyFM" rel="nofollow">https://github.com/coreylynch/pyFM</a> module, to predict move ratings. However, is there a way I can store (I am using django) the factorization machine after it is trained? Because right now (following the example), I would have to retrain the ... | 0 | 2016-10-04T19:33:54Z | 39,860,444 | <p>You are using <code>sklearn</code>. If your model is not huge, the built-in persistence model of python - pickle should work. There is an example <a href="http://scikit-learn.org/stable/modules/model_persistence.html" rel="nofollow">here</a>.</p>
| 0 | 2016-10-04T19:38:36Z | [
"python",
"django",
"machine-learning",
"artificial-intelligence",
"collaborative-filtering"
] |
Python list of lists to divide an element position on all sublists by a number | 39,860,398 | <p>How can in python take a lists of lists and apply a division to the third element of each sublist.</p>
<p>The sublists looks like this </p>
<pre><code>[1.3735876284e-05, 0.9277849431216683, 34.02875434027778, 0.0]
[2.60440773e-06, 7.35174234e-01, 2.79259180e+02, 0.00000000e+00]
...
</code></pre>
<p>I need t... | -2 | 2016-10-04T19:35:53Z | 39,860,493 | <p>use a list comprehension to extract sub-lists, and use addition to concatenate list parts...</p>
<p><code>lambda L: [l[:2]+[l[2]/100]+l[3:] for l in L]</code></p>
| 1 | 2016-10-04T19:41:16Z | [
"python",
"list"
] |
Python list of lists to divide an element position on all sublists by a number | 39,860,398 | <p>How can in python take a lists of lists and apply a division to the third element of each sublist.</p>
<p>The sublists looks like this </p>
<pre><code>[1.3735876284e-05, 0.9277849431216683, 34.02875434027778, 0.0]
[2.60440773e-06, 7.35174234e-01, 2.79259180e+02, 0.00000000e+00]
...
</code></pre>
<p>I need t... | -2 | 2016-10-04T19:35:53Z | 39,860,526 | <p>You could try this:</p>
<pre><code>a = [
[1.3735876284e-05, 0.9277849431216683, 34.02875434027778, 0.0],
[2.60440773e-06, 7.35174234e-01, 2.79259180e+02, 0.00000000e+00],
]
b = [
[(x / 100.0 if i == 2 else x) for (i, x) in enumerate(lst)]
for lst in a
]
</code></pre>
<p>Or the lambda ver... | 1 | 2016-10-04T19:43:04Z | [
"python",
"list"
] |
Referencing a C++ allocated object in pybind11 | 39,860,405 | <p>I'm trying to create a python binding with pybind11 that references a C++ instance whose memory is handled on the C++ side. Here is some example code:</p>
<pre><code>import <pybind11/pybind11>
struct Dog {
void bark() { printf("Bark!\n"); }
};
int main()
{
auto dog = new Dog;
Py_Initialize();
init... | 0 | 2016-10-04T19:36:03Z | 39,916,514 | <p>I found an answer to my own question. The trick was a combination of the following two concepts:</p>
<ul>
<li>Create an independent function that returns the singleton.</li>
<li>Create binding to the singleton class <strong>without</strong> binding a constructor. </li>
</ul>
<p>The following example illustrates th... | 0 | 2016-10-07T11:48:34Z | [
"python",
"c++",
"pybind11"
] |
Fast Python/Numpy Frequency-Severity Distribution Simulation | 39,860,431 | <p>I'm looking for a away to simulate a classical frequency severity distribution, something like:
X = sum(i = 1..N, Y_i), where N is for example poisson distributed and Y lognormal.</p>
<p>Simple naive numpy script would be:</p>
<pre><code>import numpy as np
SIM_NUM = 3
X = []
for _i in range(SIM_NUM):
nr_claim... | 3 | 2016-10-04T19:38:00Z | 39,861,935 | <p>You're looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow"><code>numpy.add.reduceat</code></a>:</p>
<pre><code>N = np.random.poisson(1, SIM_NUM)
losses = np.random.lognormal(0,1, np.sum(N))
x = np.zeros(SIM_NUM)
offsets = np.r_[0, np.cumsum(N[N>0])]... | 1 | 2016-10-04T21:19:12Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
Fast Python/Numpy Frequency-Severity Distribution Simulation | 39,860,431 | <p>I'm looking for a away to simulate a classical frequency severity distribution, something like:
X = sum(i = 1..N, Y_i), where N is for example poisson distributed and Y lognormal.</p>
<p>Simple naive numpy script would be:</p>
<pre><code>import numpy as np
SIM_NUM = 3
X = []
for _i in range(SIM_NUM):
nr_claim... | 3 | 2016-10-04T19:38:00Z | 39,862,127 | <p>We can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> , which is quite efficient for such interval/ID based summing operations specially when working with <code>1D</code> arrays. The implementation would look something like this -</p... | 3 | 2016-10-04T21:33:37Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
Operations with multiple dicts | 39,860,466 | <p>The main questions is how do I have to iterate / indicate correctly to work with two dicts?
I have given two dicts <code>(d1, d2)</code> which I have to compare. If the key i is the same in both, an operation is followed due to a given function. The result goes into another dict (<code>dict1</code>). If either <code... | 0 | 2016-10-04T19:39:50Z | 39,860,599 | <p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> to get an iterable of all keys in your dicts.</p>
<pre><code>from itertools import chain
def h(a, b):
return a > b
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
d1 = {1:30, 2:20, 3:30, 5:80}... | 0 | 2016-10-04T19:47:31Z | [
"python",
"dictionary",
"iteration"
] |
Operations with multiple dicts | 39,860,466 | <p>The main questions is how do I have to iterate / indicate correctly to work with two dicts?
I have given two dicts <code>(d1, d2)</code> which I have to compare. If the key i is the same in both, an operation is followed due to a given function. The result goes into another dict (<code>dict1</code>). If either <code... | 0 | 2016-10-04T19:39:50Z | 39,860,728 | <pre><code>import itertools
def interdict(d1,d2):
dict1 = {}
dict2 = {}
for i in set(itertools.chain(d1, d2)):
if i in d1 and i in d2:
#whatever
elif i in d1:
#not in d2
else:
#not in d1
</code></pre>
<p><code>set</code> gets rid of duplicates. ... | 0 | 2016-10-04T19:56:15Z | [
"python",
"dictionary",
"iteration"
] |
Running super().__init__(value) where value is an @property | 39,860,556 | <p>I'm just trying to grok how exactly Python handles this behind the scenes. So take this code snippet (from Effective Python by Brett Slatkin):</p>
<pre><code>class Resistor(object):
def __init__(self, ohms):
self.ohms = ohms
self.voltage = 0
self.current = 0
class VoltageResistor(Resi... | 1 | 2016-10-04T19:44:50Z | 39,860,687 | <p>Scope doesn't come into play when working with object's attributes. Consider the following:</p>
<pre><code>class A(object):
def __init__(self):
self.a = 1
def foo():
a = A()
a.a = 2
return a
def bar(a):
print(a.a)
bar(foo())
</code></pre>
<p>This example code will print 2. Note tha... | 2 | 2016-10-04T19:53:08Z | [
"python"
] |
Running super().__init__(value) where value is an @property | 39,860,556 | <p>I'm just trying to grok how exactly Python handles this behind the scenes. So take this code snippet (from Effective Python by Brett Slatkin):</p>
<pre><code>class Resistor(object):
def __init__(self, ohms):
self.ohms = ohms
self.voltage = 0
self.current = 0
class VoltageResistor(Resi... | 1 | 2016-10-04T19:44:50Z | 39,860,780 | <p>To supplement the above excellent answer, just add the following line in the parent's constructor to get a better idea of what is going on:</p>
<pre><code>class Resistor(object):
def __init__(self, ohms):
print (type(self).__name__)
self.ohms = ohms
</code></pre>
<p>It will print <code>VoltageR... | 1 | 2016-10-04T19:59:11Z | [
"python"
] |
Inspectdb error django | 39,860,583 | <p>I have postgresql db. I want to make reverse engeneering from db by command </p>
<pre><code>python3 manage.py inspectdb > models/models.py
</code></pre>
<p>All was ok, but I needed to customize auth. I extends from AbstractBaseUser, and try to reispect, because I was alter fields.Then, I looked up in db, and I ... | -1 | 2016-10-04T19:46:32Z | 39,860,669 | <p>Ok, I found I a solution. Need to delete from manage.py</p>
<pre><code>AUTH_USER_MODEL = 'models.models.Account'
</code></pre>
| 0 | 2016-10-04T19:52:04Z | [
"python",
"django",
"postgresql"
] |
multiprocessing function call | 39,860,588 | <p>I am trying to do some multiprocessing in Python. I have a function doing some work and returning a list. I want to repeat that for several cases. Finally, I want to get the returned list of each parallel call and unify them (have only one list with all duplicates removed).</p>
<pre><code>def get_version_list(env):... | 0 | 2016-10-04T19:46:41Z | 39,860,952 | <p>You have to put the multiprocessing portion inside of your main function, like:</p>
<pre><code>def get_version_list(env):
list = []
print "ENV: " + env
return list
if __name__ == '__main__':
from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(get_version_list, ['pro... | 1 | 2016-10-04T20:11:19Z | [
"python",
"multiprocessing"
] |
ZeroMQ FiniteStateMachineException in REQ/REP pattern | 39,860,614 | <p>I have two simple components which are supposed to communicate with each other using the REQ/REP ZeroMQ pattern.
The Server (REP Socket) is implemented in Python using pyzmq:</p>
<pre><code>import zmq
def launch_server():
print "Launching server"
with zmq.Context.instance() as ctx:
socket = ctx.soc... | 0 | 2016-10-04T19:48:41Z | 39,868,689 | <p>Request and Response sockets are state machines, with Request you must first Send and then call Receive, you cannot call 5 consecutive Send.</p>
<p>With Response its the opposite, you must call Receive first.</p>
<p>If one side is only sending and the other only receiving you can use Push-Pull pattern instead of R... | 1 | 2016-10-05T08:13:44Z | [
"c#",
"python",
"zeromq",
"pyzmq",
"netmq"
] |
Wrapping namespaced custom types defined only in headers with SWIG | 39,860,675 | <p>How can i wrap this content using SWIG?</p>
<p>usecase5.h</p>
<pre><code>#ifndef __USECASE5_H__
#define __USECASE5_H__
#include <math.h>
namespace foo_namespace {
struct vec2
{
int x, y;
vec2() {}
explicit vec2( int a, int b )
{
x = a;
y = b... | 0 | 2016-10-04T19:52:27Z | 39,862,458 | <p>It seems this wasn't any issue related with swig but more on the c++ side, to fix it I just needed to fix the c++ issues:</p>
<p>usecase5.h</p>
<pre><code>#ifndef __USECASE5_H__
#define __USECASE5_H__
#include <math.h>
namespace foo_namespace {
struct vec2
{
int x, y;
vec2() {}
... | 0 | 2016-10-04T22:02:21Z | [
"python",
"c++",
"swig"
] |
if elif else blocks evaluate for every case | 39,860,692 | <p>I am trying to append an iterator to a list but my code below evaluates for every case.</p>
<pre><code>Less7=Head7=Over7=[]
i=0
for i in range(0,10):
if i<7:
Less7.append(i)
elif i==7:
Head7=i
else:
Over7.append(i)
</code></pre>
<p>The result I am getting are:
Head7 is an ... | 1 | 2016-10-04T19:53:21Z | 39,860,771 | <p>You need to create <em>three lists</em>, one for each possible outcome:</p>
<pre><code>less_than_7, is_7, greater_than_7 = [], [], []
for i in range(0, 10):
if i < 7:
less_than_7.append(i)
elif i > 7:
greater_than_7.append(i)
else:
is_7.append(i)
</code></pre>
<p><em><cod... | 0 | 2016-10-04T19:58:37Z | [
"python",
"python-3.5.2"
] |
Insert into table without all values | 39,860,694 | <p>Specifically, how would I insert into sqlite3 database and python without using all the values.</p>
<p>If my table is setup like this:</p>
<pre><code>People:
f_name | l_name | age | favorite_color
</code></pre>
<p>When I create a new row, how would I be able to only put in a few values like this:</p>
<pre><c... | -1 | 2016-10-04T19:53:36Z | 39,860,715 | <p>You'll have to list the columns explicitly:</p>
<p><code>c.execute("INSERT INTO People (f_name, l_name) VALUES (?, ?)", (f_name, l_name))</code></p>
| 1 | 2016-10-04T19:55:21Z | [
"python",
"sqlite3"
] |
Insert into table without all values | 39,860,694 | <p>Specifically, how would I insert into sqlite3 database and python without using all the values.</p>
<p>If my table is setup like this:</p>
<pre><code>People:
f_name | l_name | age | favorite_color
</code></pre>
<p>When I create a new row, how would I be able to only put in a few values like this:</p>
<pre><c... | -1 | 2016-10-04T19:53:36Z | 39,860,904 | <p>1) INSERT statement doesn't automatically know what value goes where if you omit some parameters. It is generally good practice to explicitly mentioning the names of the columns. e.g: INSERT INTO People (f_name, l_name)</p>
<p>2) If those columns aren't nullable then you can't omit them at all!</p>
| 0 | 2016-10-04T20:07:24Z | [
"python",
"sqlite3"
] |
Google API Client: Container Registry API Python | 39,860,726 | <p>I want to get a list of images in the Google Container Engine using Python, and eventually, start an instance of one of them. I know there's a <a href="https://cloud.google.com/sdk/gcloud/reference/beta/container/images/list" rel="nofollow">gcloud command to list images</a>, but is this possible to do using the goog... | 0 | 2016-10-04T19:56:09Z | 39,883,430 | <p>For image listing,</p>
<p>Google Container Registry is a Docker Registry API so you probably won't be able to list images through googleapiclient.</p>
<p>Something that uses the Docker Registry API like <a href="https://pypi.python.org/pypi/docker-registry-client/1.0" rel="nofollow">https://pypi.python.org/pypi/do... | 0 | 2016-10-05T20:51:38Z | [
"python",
"google-api-client",
"google-container-engine",
"google-container-registry"
] |
Pyspark, initializing spark programmetically : IllegalArgumentException: Missing application resource | 39,860,907 | <p>When creating a spark context in Python, I get the following error.</p>
<pre><code> app_name="my_app"
master="local[*]"
sc = SparkContext(appName=app_name, master=master)
Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
at org.apache.spark.launcher.CommandBuilderUtils.... | 0 | 2016-10-04T20:07:39Z | 40,050,942 | <p>This was happening due to preexisting env variables, that conflicted. I deleted them in the python program and it works smoothly now.</p>
<p>ex:</p>
<pre><code>import os
#check if pyspark env vars are set and then reset to required or delete.
del os.environ['PYSPARK_SUBMIT_ARGS']
</code></pre>
| 0 | 2016-10-14T19:47:47Z | [
"python",
"pyspark"
] |
Call state module from within state module | 39,860,976 | <p>I'm writing a <a href="https://docs.saltstack.com/en/latest/ref/states/writing.html" rel="nofollow">custom state module</a> with the purpose of creating a file in a given location with (partly) configurable content.</p>
<p>Basically I'm looking to shorten the following SLS (simplified for the purpose of this questi... | 0 | 2016-10-04T20:13:37Z | 39,866,831 | <p>I found a solution using the <a href="https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.state.html#salt.modules.state.single" rel="nofollow"><code>state.single</code></a> execution module:</p>
<pre><code>def foo(name, messsage):
result = __salt__['state.single'](fun='file.managed',
... | 0 | 2016-10-05T06:27:44Z | [
"python",
"salt-stack"
] |
Reformat a column to only first 5 characters | 39,860,985 | <p>I am new to Python and I'm struggling with this section. There are about 25 columns in a text file and 50,000+ Rows. For one of the columns, #11 (<strong>ZIP</strong>), this column contains all the zip code values of customers in this format "<strong>07598-XXXX</strong>", I would only like to get the first 5, so "<s... | 3 | 2016-10-04T20:14:20Z | 39,861,016 | <pre><code>'{:.5}'.format(zip_)
</code></pre>
<p>where <code>zip_</code> is the string containing the zip code. More on <code>format</code> here: <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">https://docs.python.org/2/library/string.html#format-string-syntax</a></p>
| 3 | 2016-10-04T20:16:22Z | [
"python",
"python-3.x"
] |
Reformat a column to only first 5 characters | 39,860,985 | <p>I am new to Python and I'm struggling with this section. There are about 25 columns in a text file and 50,000+ Rows. For one of the columns, #11 (<strong>ZIP</strong>), this column contains all the zip code values of customers in this format "<strong>07598-XXXX</strong>", I would only like to get the first 5, so "<s... | 3 | 2016-10-04T20:14:20Z | 39,861,071 | <p>Process title line separately, then read row by row like you do, just modify second <code>line</code> column by truncating to 5 characters.</p>
<pre><code>import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
remove_words = ['INAC-EIM','-INAC','TO-INAC','TO_INAC','SHIP_TO-inac','SHIP_TOINAC']
with op... | 2 | 2016-10-04T20:19:49Z | [
"python",
"python-3.x"
] |
Reformat a column to only first 5 characters | 39,860,985 | <p>I am new to Python and I'm struggling with this section. There are about 25 columns in a text file and 50,000+ Rows. For one of the columns, #11 (<strong>ZIP</strong>), this column contains all the zip code values of customers in this format "<strong>07598-XXXX</strong>", I would only like to get the first 5, so "<s... | 3 | 2016-10-04T20:14:20Z | 39,861,278 | <p>to get first 5 <em>characters</em> in a string use <code>str[:6]</code></p>
<p>in your case:</p>
<pre><code>with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile:
writer = csv.writer(outfile)
for line in csv.reader(infile, delimiter='|'):
if not any(remov... | 1 | 2016-10-04T20:34:17Z | [
"python",
"python-3.x"
] |
Nested structured array field access with numpy | 39,861,047 | <p>I am working on parsing Matlab structured arrays in Python. For simplicity, the data structure ultimately consists of 3 fields, say header, body, trailer. Creating some data in Matlab for example:</p>
<pre><code>header_data = {100, 100, 100};
body_data = {1234, 100, 4321};
trailer_data = {1001, 1001, 1001};
data = ... | 0 | 2016-10-04T20:18:26Z | 39,861,747 | <p>Trying to recreate your file with Octave (save with -v7), I get, in an Ipython session:</p>
<pre><code>In [190]: data = io.loadmat('test.mat')
In [191]: data
Out[191]:
{'__globals__': [],
'__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.0.0, 2016-10-04 20:54:53 UTC',
'__version__': '1.0',
'body_data': a... | 1 | 2016-10-04T21:06:20Z | [
"python",
"numpy",
"scipy"
] |
How to DISABLE Jupyter notebook matplotlib plot inline? | 39,861,106 | <p>Well, I know I can use <code>%matplotlib inline</code> to plot inline.</p>
<p>However, how to disable it? </p>
<p>Sometime I just want to zoom in the figure that I plotted. Which I can't do on a inline-figure.</p>
| 0 | 2016-10-04T20:22:27Z | 39,861,256 | <p>Use <code>%matplotlib notebook</code> to change to a zoom-able display.</p>
| 0 | 2016-10-04T20:32:32Z | [
"python",
"matplotlib",
"ipython",
"jupyter"
] |
Python string have not control characters | 39,861,200 | <p>i have proxy string:</p>
<pre><code>proxy = '127.0.0.1:8080'
</code></pre>
<p>i need check is it real string:</p>
<pre><code>def is_proxy(proxy):
return not any(c.isalpha() for c in proxy)
</code></pre>
<p>to skip string like:</p>
<pre><code>fail_proxy = 'This is proxy: 127.0.0.1:8080'
</code></pre>
<p>but... | -1 | 2016-10-04T20:28:34Z | 39,861,459 | <p>Try the following specific approach using <code>re</code> module(regexp):</p>
<pre><code>import re
def is_proxy(proxy):
return re.fullmatch('^\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}:\d{1,5}$', proxy) is not None
proxy1 = '127.0.0.1:8080'
proxy2 = '127.0.0.1:8080\r'
print(is_proxy(proxy1)) # True
print(is_proxy(p... | 0 | 2016-10-04T20:46:22Z | [
"python",
"string",
"control-characters"
] |
Best to use join or append? | 39,861,226 | <p>Currently I have this code:</p>
<pre><code>with open(w_file, 'r') as file_r:
for line in file_r:
if len(line) > 0:
spLine = line.split()
if(spLine[0] == operandID and spLine[1] == bitID
and spLine[3] == sInstID and spLine[4] == opcodeID):
spLine[-2]='1'
... | -2 | 2016-10-04T20:30:27Z | 39,861,308 | <p>Just add a <code>+ "\n"</code> to the end, like this.</p>
<pre><code>line = ' '.join(spLine) + "\n"
</code></pre>
<p>This will add a new line after the joining. </p>
| 1 | 2016-10-04T20:36:18Z | [
"python",
"join",
"append"
] |
Text compressor doesn't compress the intended way | 39,861,280 | <p>For a school assignment I have to write a python program to compress a text and write a new file with the compressed text, conserving the original. For example, the text "heeeeeeellllooo" to "he7l4o3". So each character that is iterated subsequently has to be replaced by the character and has to be directly followed... | 0 | 2016-10-04T20:34:19Z | 39,861,622 | <p>Here's a correct solution:</p>
<pre><code>inp = open("hello.txt", "r")
out = open("compr.txt", "w")
kar=inp.read(1)
prevkar=''
def iterations(a,b):
re = 1
while a==b:
re+=1
b = a
a = inp.read(1)
out.write(str(re))
return a
def no_iteration(a):
out.write(a)
return
... | 0 | 2016-10-04T20:58:09Z | [
"python",
"python-2.7",
"compression"
] |
How do I create multiple instances of python application server? | 39,861,345 | <p>How do I create multiple instances of python application server?</p>
<p>I created an application server in python using httpserver. I am not using any python frameworks. Now I want to create multiple instances of the server and use load balancer on top of it. How can I create multiple instances of this application ... | 0 | 2016-10-04T20:38:45Z | 39,863,659 | <p>You could bind different ports for each instance of your server. </p>
<p>Make your script initialize each instance binding a different port ( e.g port 3000, 3001, 3002 ...) and configure nginx to spread the load on those ports. </p>
<p>From <a href="https://docs.python.org/2/library/basehttpserver.html" rel="nof... | 0 | 2016-10-05T00:23:42Z | [
"python",
"python-2.7",
"nginx",
"application-server"
] |
How to decode binary file with " for index, line in enumerate(file)"? | 39,861,431 | <p>I am opening up an extremely large binary file I am opening in Python 3.5 in <code>file1.py</code>:</p>
<pre><code>with open(pathname, 'rb') as file:
for i, line in enumerate(file):
# parsing here
</code></pre>
<p>However, I naturally get an error because I am reading the file in binary mode and then c... | -2 | 2016-10-04T20:44:26Z | 39,861,533 | <p>You could feed a generator with the decoded lines to <code>enumerate</code>:</p>
<pre><code>for i, line in enumerate(l.decode(errors='ignore') for l in f):
</code></pre>
<p>Which does the trick of yielding every line in <code>f</code> after decoding it. I've added <code>errors='ignore'</code> due to the fact that ... | 2 | 2016-10-04T20:51:24Z | [
"python",
"python-3.x",
"binary",
"decode",
"enumerate"
] |
Recursively modify a dictionary | 39,861,433 | <p>I've created a class that should transform a nested list into a dictionary. The following is my input:</p>
<pre><code>['function:and',
['variable:X', 'function:>=', 'value:13'],
['variable:Y', 'function:==', 'variable:W']]
</code></pre>
<p>And the output should be a dictionary in the following form:</p>... | 0 | 2016-10-04T20:44:43Z | 39,862,952 | <p>For your particular test case you don't need to go into recursion at all. You can comment out your calls:</p>
<pre><code>def walk(self, args):
left = self.to_dict(args[0])
right = self.to_dict(args[1])
#if isinstance(left, dict):
# if 'args' in left.keys():
# left = self.walk(left['arg... | 1 | 2016-10-04T22:51:06Z | [
"python",
"algorithm",
"dictionary",
"recursion"
] |
How to access items from two lists in circular order? | 39,861,439 | <p>I have 2 lists,</p>
<pre><code>list_a = ['color-1', 'color-2', 'color-3', 'color-4']
list_b = ['car1', 'car2', 'car3', 'car4' ........... 'car1000']
</code></pre>
<p>I need to access the elements in a circular order of <code>list_a</code>:</p>
<pre><code>['color-1']['car1']
['color-2']['car2']
['color-3']['car3']... | 0 | 2016-10-04T20:45:21Z | 39,861,525 | <p>Use the modulo operator <code>%</code> to index into the proper range:</p>
<pre><code>len_a = len(list_a)
len_b = len(list_b)
end = max(len_a, len_b)
for i in range(end):
print(list_a[i % len_a], list_b[i % len_b])
# ... do something else
</code></pre>
| 2 | 2016-10-04T20:50:40Z | [
"python",
"list",
"circular"
] |
How to access items from two lists in circular order? | 39,861,439 | <p>I have 2 lists,</p>
<pre><code>list_a = ['color-1', 'color-2', 'color-3', 'color-4']
list_b = ['car1', 'car2', 'car3', 'car4' ........... 'car1000']
</code></pre>
<p>I need to access the elements in a circular order of <code>list_a</code>:</p>
<pre><code>['color-1']['car1']
['color-2']['car2']
['color-3']['car3']... | 0 | 2016-10-04T20:45:21Z | 39,861,532 | <p>Use <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle"><code>itertools.cycle</code></a> to make a cyclic iterable out of <code>list_a</code>.
Use <a href="https://docs.python.org/3/library/functions.html#zip"><code>zip</code></a> to pair items from the cyclic iterable with items from <code>li... | 6 | 2016-10-04T20:51:22Z | [
"python",
"list",
"circular"
] |
How do test in Django | 39,861,651 | <p>I'm trying to do my first tests on Django and I don't know do it or after reading the docs (where it explains a very easy test) I still don't know how do it.</p>
<p>I'm trying to do a test that goes to "login" url and makes the login, and after a succesfull login redirects to the authorized page.</p>
<pre><code>fr... | 0 | 2016-10-04T21:00:05Z | 39,862,325 | <p>Django have plenty of tools for testing. For this task, you should use test case class from Django, for example <code>django.test.TestCase</code>.
Then you can use method <code>assertRedirects()</code> and it will check where you've been redirected and with which code. You can find any info you need <a href="https:/... | 1 | 2016-10-04T21:49:16Z | [
"python",
"django",
"django-testing"
] |
How do test in Django | 39,861,651 | <p>I'm trying to do my first tests on Django and I don't know do it or after reading the docs (where it explains a very easy test) I still don't know how do it.</p>
<p>I'm trying to do a test that goes to "login" url and makes the login, and after a succesfull login redirects to the authorized page.</p>
<pre><code>fr... | 0 | 2016-10-04T21:00:05Z | 39,865,780 | <p>To properly test redirects, use the <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.Client.post" rel="nofollow">follow</a> parameter </p>
<blockquote>
<p>If you set follow to True the client will follow any redirects and a
redirect_chain attribute will be set in the response ob... | 1 | 2016-10-05T05:02:06Z | [
"python",
"django",
"django-testing"
] |
Testing pull-request on other person's package | 39,861,662 | <p>I opened an <a href="https://github.com/mvantellingen/python-zeep/issues/177" rel="nofollow">issue</a> in a package that I need for my job, and now the author is asking me to test a <a href="https://github.com/mvantellingen/python-zeep/pull/205" rel="nofollow">pull request</a>. The problem is... I don't really know ... | 2 | 2016-10-04T21:00:47Z | 39,861,748 | <p>The GitHub pull request names the source: </p>
<blockquote>
<p>mvantellingen wants to merge 12 commits into <code>master</code> from <code>multiple-msg-parts</code></p>
</blockquote>
<p><code>multiple-msg-parts</code> is just another branch in the same repository. Just clone that repository and check out <a href... | 1 | 2016-10-04T21:06:29Z | [
"python",
"github",
"fork",
"pull-request"
] |
Testing pull-request on other person's package | 39,861,662 | <p>I opened an <a href="https://github.com/mvantellingen/python-zeep/issues/177" rel="nofollow">issue</a> in a package that I need for my job, and now the author is asking me to test a <a href="https://github.com/mvantellingen/python-zeep/pull/205" rel="nofollow">pull request</a>. The problem is... I don't really know ... | 2 | 2016-10-04T21:00:47Z | 39,861,833 | <blockquote>
<p>The only way I see now is that I fork the repository, download and apply the pull request as a patch [...]</p>
</blockquote>
<p>As <a href="http://stackoverflow.com/questions/39861662/testing-pull-request-on-other-persons-package#comment67011346_39861662">Martijn Pieters commented</a>: clone the repo... | 1 | 2016-10-04T21:12:27Z | [
"python",
"github",
"fork",
"pull-request"
] |
Does dask distributed use Tornado coroutines for workers tasks? | 39,861,685 | <p>I've read at the dask <a href="http://distributed.readthedocs.io/en/latest/foundations.html#concurrency-with-tornado-coroutines" rel="nofollow"><code>distributed</code> documentation</a> that:</p>
<blockquote>
<p>Worker and Scheduler nodes operate concurrently. They serve several
overlapping requests and perfor... | 2 | 2016-10-04T21:02:28Z | 39,861,932 | <p>You are correct. </p>
<p>Each <a href="http://distributed.readthedocs.io/en/latest/worker.html" rel="nofollow">distributed.Worker</a> object contains a <a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor" rel="nofollow">concurrent.futures.ThreadPoolExecutor</a> with multiple threa... | 1 | 2016-10-04T21:19:04Z | [
"python",
"multithreading",
"tornado",
"coroutine",
"dask"
] |
pyqt: How to quit a thread properly | 39,861,700 | <p>I wrote an pyqt gui and used threading to run code which needs a long time to be executed, but I want to have the choice to stop the execution safely. I dont want to use the get_thread.terminate() method. I want to stop the code by a special function (maybe <strong>del</strong>()). My problem is that, I wrote the co... | 0 | 2016-10-04T21:03:14Z | 39,862,105 | <p>This is impossible to do unless <code>prog.run(self)</code> would periodically inspect a value of a flag to break out of its loop. Once you implement it, <code>__del__(self)</code> on the thread should set the flag and only then <code>wait</code>.</p>
| 0 | 2016-10-04T21:32:38Z | [
"python",
"qt",
"python-3.x",
"pyqt",
"pyqt4"
] |
String or object compairson in Python 3.52 | 39,861,740 | <p>I am working on the exorcism.io clock exercise and I can not figure out why this test is failing. The results look identical and even have the same type.</p>
<p>Here is my code:</p>
<pre><code>class Clock:
def __init__(self, h, m):
self.h = h
self.m = m
self.adl = 0
def make_time(s... | 3 | 2016-10-04T21:06:01Z | 39,861,907 | <p>A custom class without an <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__" rel="nofollow"><code>__eq__</code> method</a> defaults to testing for <em>identity</em>. That is to say, two references to an instance of such a class are only equal if the reference they exact same object.</p>
<p>Y... | 5 | 2016-10-04T21:17:33Z | [
"python",
"python-3.x",
"equality"
] |
Parsing JSON string from URL with Python 3.5.2 | 39,861,782 | <p>I am trying to print out the values <code>"lat"</code> and <code>"lon"</code> from the JSON (<a href="https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&list=&titles=venice" rel="nofollow">source</a>):</p>
<pre class="lang-js prettyprint-override"><code>{
"batchcomplete... | -1 | 2016-10-04T21:08:55Z | 39,861,890 | <pre><code>print(array['query']['pages']['32616']['coordinates'][0]['lat'])
print(array['query']['pages']['32616']['coordinates'][0]['lon'])
insert ^
</code></pre>
| 1 | 2016-10-04T21:16:07Z | [
"python"
] |
Parsing JSON string from URL with Python 3.5.2 | 39,861,782 | <p>I am trying to print out the values <code>"lat"</code> and <code>"lon"</code> from the JSON (<a href="https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&list=&titles=venice" rel="nofollow">source</a>):</p>
<pre class="lang-js prettyprint-override"><code>{
"batchcomplete... | -1 | 2016-10-04T21:08:55Z | 39,861,891 | <pre><code>import requests
import json
r = requests.get('you URL here')
rData = json.loads(r.text, encoding="utf-8")
print(rData['query']['pages']['32616']['coordinates'][0]['lat'])
print(rData['query']['pages']['32616']['coordinates'][0]['lon'])
</code></pre>
| 1 | 2016-10-04T21:16:07Z | [
"python"
] |
Error trying parsing xml using python : xml.etree.ElementTree.ParseError: syntax error: line 1, | 39,861,806 | <p>In python, simply trying to parse XML: </p>
<pre><code>import xml.etree.ElementTree as ET
data = 'info.xml'
tree = ET.fromstring(data)
</code></pre>
<p>but got error:</p>
<pre><code>Traceback (most recent call last):
File "C:\mesh\try1.py", line 3, in <module>
tree = ET.fromstring(data)
File "C:\Python27\li... | -2 | 2016-10-04T21:10:55Z | 39,861,886 | <p>You're trying to parse the string <code>'info.xml'</code> instead of the contents of the file.</p>
<p>You could call <code>tree = ET.parse('info.xml')</code> which will open the file.</p>
<p>Or you could read the file directly:</p>
<p><code>ET.fromstring(open('info.xml').read())</code></p>
| 1 | 2016-10-04T21:16:02Z | [
"python",
"xml",
"python-2.7"
] |
Regular Expression Dot not working | 39,861,911 | <p>So I'm trying to parse through a file and I have the following code:</p>
<pre><code>def learn_re(s):
pattern=re.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3} .")
if pattern.match(s):
return True
return False
</code></pre>
<p>This matches with "01:01:01.123 â"; however, when I add in one more character, it fai... | 3 | 2016-10-04T21:17:51Z | 39,861,970 | <p>Rhe em dash in your string is a unicode character, which will be interpreted as multiple characters <a href="http://www.fileformat.info/info/unicode/char/2014/index.htm" rel="nofollow">(3 in your case)</a>. Your version of python is not unicode-aware so you'll either need to match 3 characters to capture <code>.{3}<... | 1 | 2016-10-04T21:21:42Z | [
"python",
"regex",
"python-2.7"
] |
Regular Expression Dot not working | 39,861,911 | <p>So I'm trying to parse through a file and I have the following code:</p>
<pre><code>def learn_re(s):
pattern=re.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3} .")
if pattern.match(s):
return True
return False
</code></pre>
<p>This matches with "01:01:01.123 â"; however, when I add in one more character, it fai... | 3 | 2016-10-04T21:17:51Z | 39,862,274 | <p>The issue is that your â is a unicode character. When in a <code>str</code>, it actually behaves more like several characters:</p>
<pre><code>>>> print len('â')
3
</code></pre>
<p>But, if you use a <code>unicode</code> instead of a <code>str</code>:</p>
<pre><code>>>> print len(u'â')
1
</c... | 3 | 2016-10-04T21:45:30Z | [
"python",
"regex",
"python-2.7"
] |
Pandas: find substring in a column | 39,861,957 | <p>I need to find in dataframe some strings</p>
<pre><code>url
003.ru/*/mobilnyj_telefon_bq_phoenix*
003.ru/*/mobilnyj_telefon_fly_*
003.ru/*mobile*
003.ru/telefony_i_smartfony/mobilnye_telefony_smartfony
003.ru/telefony_i_smartfony/mobilnye_telefony_smartfony/%brands%5D%5Bbr_23%
1click.ru/*iphone*
1click.ru/catalogue... | 0 | 2016-10-04T21:20:45Z | 39,862,148 | <p>Try:</p>
<pre><code>df[df['url'].str.contains(substr.url, regex=False)]
</code></pre>
<p>You have to specify whether or not you want your pattern to be interpreted as a regular expression or a normal string. In this case, you want to set the <code>regex</code> argument to <code>False</code> because it is set to <c... | 1 | 2016-10-04T21:35:36Z | [
"python",
"regex",
"pandas"
] |
Do we need to specify python interpreter externally if python script contains #!/usr/bin/python3? | 39,861,960 | <p>I am trying to invoke python script from C application using <code>system()</code> call</p>
<p>The python script has <code>#!/usr/bin/python3</code> on the first line.</p>
<p>If I do <code>system(python_script)</code>, the script does not seem to run.</p>
<p>It seems I need to do <code>system(/usr/bin/python3 pyt... | 2 | 2016-10-04T21:20:58Z | 39,862,114 | <p>Make sure you have executable permission for <code>python_script</code>.
You can make <code>python_script</code> executable by </p>
<p><code>chmod +x python_script</code></p>
<p>Also check if you are giving correct path for <code>python_script</code></p>
| 1 | 2016-10-04T21:33:07Z | [
"python",
"c",
"system",
"interpreter"
] |
ZeroMQ: load balance many workers and one master | 39,862,022 | <p>Suppose I have one master process that divides up data to be processed in parallel. Lets say there are 1000 chunks of data and 100 nodes on which to run the computations. </p>
<p>Is there some way to do REQ/REP to keep all the workers busy? I've tried to use the load balancer pattern in the guide but with a single... | 3 | 2016-10-04T21:25:40Z | 39,863,502 | <p>I guess there is different ways to do this :</p>
<p>-you can, for example, use the <strong><code>threading</code></strong> module to launch all your requests from your single client, with something like:</p>
<pre><code>result_list = [] # Add the result to a list for the example
rlock = threading.RLock()
def cli... | 1 | 2016-10-05T00:01:45Z | [
"python",
"zeromq"
] |
Pandas: create dataframe without auto ordering column names alphabetically | 39,862,053 | <p>I am creating an initial pandas dataframe to store results generated from other codes: e.g.</p>
<pre><code>result = pd.DataFrame({'date': datelist, 'total': [0]*len(datelist),
'TT': [0]*len(datelist)})
</code></pre>
<p>with <code>datelist</code> a predefined list. Then other codes will outp... | 1 | 2016-10-04T21:28:21Z | 39,862,649 | <p>You can pass the (correctly ordered) list of column as parameter to the constructor or use an OrderedDict:</p>
<pre><code># option 1:
result = pd.DataFrame({'date': datelist, 'total': [0]*len(datelist),
'TT': [0]*len(datelist)}, columns=['date', 'total', 'TT'])
# option 2:
od = collections.Orde... | 3 | 2016-10-04T22:21:07Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: create dataframe without auto ordering column names alphabetically | 39,862,053 | <p>I am creating an initial pandas dataframe to store results generated from other codes: e.g.</p>
<pre><code>result = pd.DataFrame({'date': datelist, 'total': [0]*len(datelist),
'TT': [0]*len(datelist)})
</code></pre>
<p>with <code>datelist</code> a predefined list. Then other codes will outp... | 1 | 2016-10-04T21:28:21Z | 39,862,651 | <pre><code>result = pd.DataFrame({'date': [23,24], 'total': 0,
'TT': 0},columns=['date','total','TT'])
</code></pre>
| 0 | 2016-10-04T22:21:09Z | [
"python",
"pandas",
"dataframe"
] |
turn categorical data to numeric and save to libsvm format python | 39,862,058 | <p>I have a DataFrame that looks something like this:</p>
<pre><code> A B C D
1 String1 String2 String3 String4
2 String2 String3 String4 String5
3 String3 String4 String5 String6
.........................................
</code></pre>
<p>My goal is to turn this DataFrame to... | 0 | 2016-10-04T21:28:31Z | 39,863,202 | <p>After preprocessing your data, you can extract a matrix and use scikit-learns <a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.dump_svmlight_file.html#sklearn.datasets.dump_svmlight_file" rel="nofollow">dump_svmlight_file</a> to create this format.</p>
<h3>Example code:</h3>
<pre><code>im... | 1 | 2016-10-04T23:23:21Z | [
"python",
"csv",
"dataframe",
"libsvm"
] |
Python threads and strings | 39,862,062 | <p>I am new to threads and multiprocessing. I have some code in which I start a process and I wanted the output to show an active waiting state of something like this </p>
<pre><code>wating....
</code></pre>
<p>The code is similiar to this below:</p>
<p>import threading
import time</p>
<pre><code>class ThreadE... | 0 | 2016-10-04T21:29:14Z | 39,862,172 | <p>This is probably due to <code>print</code> buffering. It is flushed on <code>\n</code> and on some other occasions (like buffer overflow or program exit). Instead of <code>print</code> try this:</p>
<pre><code>import sys
def unbuffered_print(msg):
sys.stdout.write(msg)
sys.stdout.flush()
...
unbuffered_pr... | 1 | 2016-10-04T21:37:38Z | [
"python",
"multithreading",
"python-3.x",
"buffering"
] |
âIncorrect string valueâ when trying to insert String into MySQL via Python and Text file | 39,862,121 | <p>What is causing this incorrect string? I have read many questions and answers and here are my results. I still am getting same error after reading answers.</p>
<p>I am getting the following error:
<code>ERROR 1366 (HY000) at line 34373: Incorrect string value: '\xEF\xBB\xBF<?x...' for column 'change' at row 1</c... | 0 | 2016-10-04T21:33:24Z | 39,862,191 | <p>Text you're trying to insert contains <a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow">UTF-8 BOM</a> in the beginning (that's the <strong>\xEF\xBB\xBF</strong> in your error).</p>
<p>Please <a href="http://stackoverflow.com/questions/13590749/reading-unicode-file-data-with-bom-chars-in-python"... | 2 | 2016-10-04T21:38:58Z | [
"python",
"mysql",
"utf-8"
] |
âIncorrect string valueâ when trying to insert String into MySQL via Python and Text file | 39,862,121 | <p>What is causing this incorrect string? I have read many questions and answers and here are my results. I still am getting same error after reading answers.</p>
<p>I am getting the following error:
<code>ERROR 1366 (HY000) at line 34373: Incorrect string value: '\xEF\xBB\xBF<?x...' for column 'change' at row 1</c... | 0 | 2016-10-04T21:33:24Z | 39,862,241 | <p>The string you're trying to insert into db has an unusual character at its beginning. I just copied your string:</p>
<pre><code>In [1]: a = '<'
In [2]: a
Out[2]: '\xef\xbb\xbf<'
</code></pre>
<p>You need to get rid of those characters. <a href="http://stackoverflow.com/questions/11159118/incorrect-string-va... | 2 | 2016-10-04T21:42:22Z | [
"python",
"mysql",
"utf-8"
] |
How send Datetime as parameter in SQL command on Python? | 39,862,199 | <p>I have a sql command and just want to select some records with some conditions ( using python & db is Postres):
So, my query is:</p>
<pre><code> current_date= datetime.now()
tt = yield self.db.execute(self.db.execute('SELECT "Id", "RubricId", "IsRubric"
FROM whis2011."CoockieUserInterests"
'WHER... | 0 | 2016-10-04T21:39:33Z | 39,862,384 | <p>You don't state what module you are using to connect to postgresql. Let's assume for the interim that it is <code>psycopg2</code>. </p>
<p>In that case, you use the following to pass parameters to a query:</p>
<pre><code>current_date = datetime.now()
self.db.execute(
'SELECT Id, RubricId, IsRubric '
'FRO... | 1 | 2016-10-04T21:54:57Z | [
"python",
"postgresql",
"datetime"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.