title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to efficiently insert bulk data into Cassandra using Python? | 38,852,492 | <p>I have a Python application, built with Flask, that allows importing of many data records (anywhere from 10k-250k+ records at one time). Right now it inserts into a Cassandra database, by inserting one record at a time like this:</p>
<pre><code>for transaction in transactions:
self.transaction_table.insert_reco... | 0 | 2016-08-09T13:43:13Z | 38,855,747 | <p>The easiest solution is to generate csv files from your data, and import it with the <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_reference/copy_r.html" rel="nofollow">COPY</a> command. That should work well for up to a few million rows. For more complicated scenarios you could use the <a href="http://www.d... | 1 | 2016-08-09T16:12:27Z | [
"python",
"cassandra"
] |
Stipulation of "Good"/"Bad"-Cases in an LDA Model (Using gensim in Python) | 38,852,506 | <p>I am trying to analyze news snippets in order to identify crisis periods.
To do so, I have already downloaded news articles over the past 7 years and have those available.
Now, I am applying a LDA (Latent Dirichlet Allocation) model on this dataset in order to identify those countries show signs of an economic cri... | 0 | 2016-08-09T13:43:38Z | 38,870,432 | <p><strong>First some suggestions on your specific questions:</strong></p>
<blockquote>
<p>a) incorporate the information of âcrisisâ vs ânon-crisisâ </p>
</blockquote>
<p>To do this with a standard LDA model, I'd probably go for mutual information between doc topic proportions and whether docs are in a cri... | 0 | 2016-08-10T10:13:05Z | [
"python",
"python-2.7",
"lda",
"gensim"
] |
Look for existing entry in database before trying to insert | 38,852,561 | <p>I am currently working with Access 2013. I have built a database that revolves around applicants submitting for a Job. The database is set up so that a person can apply for many different jobs, when the same person applies for a job through our website (uses JotForms) it automatically updates the database. </p>
<p>... | 1 | 2016-08-09T13:45:58Z | 38,853,815 | <p>Simply look up the email address in the [tblPerson_Information] table:</p>
<pre class="lang-python prettyprint-override"><code>primary_email = 'gord@example.com' # test data
crsr = conn.cursor()
sql = """\
SELECT Personal_ID FROM tblPerson_Information WHERE Primary_email=?
"""
crsr.execute(sql, (primary_email... | 1 | 2016-08-09T14:38:58Z | [
"python",
"database",
"ms-access",
"access-vba",
"ms-access-2013"
] |
How to remove substrings marked with special characters from a string? | 38,852,589 | <p>I have a string in Python:</p>
<pre><code>Tt = "This is a <\"string\">string, It should be <\"changed\">changed to <\"a\">a nummber."
print Tt
'This is a <"string">string, It should be <"changed">changed to <"a">a nummber.'
</code></pre>
<p>You see the some words repeat in thi... | -2 | 2016-08-09T13:46:56Z | 38,852,628 | <p>Use regular expressions:</p>
<pre><code>import re
Tt = re.sub('<\".*?\">', '', Tt)
</code></pre>
<p>Note the <code>?</code> after <code>*</code>. It makes the expression non-greedy,
so it tries to match so few symbols between <code><\"</code> and <code>\"></code> as possible.</p>
<p>The Solution of <e... | 5 | 2016-08-09T13:48:41Z | [
"python",
"regex"
] |
How to remove substrings marked with special characters from a string? | 38,852,589 | <p>I have a string in Python:</p>
<pre><code>Tt = "This is a <\"string\">string, It should be <\"changed\">changed to <\"a\">a nummber."
print Tt
'This is a <"string">string, It should be <"changed">changed to <"a">a nummber.'
</code></pre>
<p>You see the some words repeat in thi... | -2 | 2016-08-09T13:46:56Z | 38,852,687 | <p>I'd use a quick regular expression:</p>
<pre><code>import re
Tt = "This is a <\"string\">string, It should be <\"changed\">changed to <\"a\">a number."
print re.sub("<[^<]+>","",Tt)
#Out: This is a string, It should be changed to a nummber.
</code></pre>
<p>Ah - similar to Igor's post, h... | 1 | 2016-08-09T13:50:58Z | [
"python",
"regex"
] |
python tool to generate txt file by coping only directory/folder names but not the other file names | 38,852,599 | <p>This is my </p>
<pre><code> import os
filenames= os.listdir (".")
file = open("XML.txt", "w")
result = []
for filename in filenames:
result = "<capltestcase name =\""+filename+"\"\n"
file.write(result)
result = "title = \""+filename+"\"\n"
file.write(result)
result = "/>\n"
fil... | -2 | 2016-08-09T13:47:13Z | 38,852,815 | <p>use the escape () to write special characters</p>
<pre><code>print("\\<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\\")
</code></pre>
| 0 | 2016-08-09T13:56:39Z | [
"python"
] |
python tool to generate txt file by coping only directory/folder names but not the other file names | 38,852,599 | <p>This is my </p>
<pre><code> import os
filenames= os.listdir (".")
file = open("XML.txt", "w")
result = []
for filename in filenames:
result = "<capltestcase name =\""+filename+"\"\n"
file.write(result)
result = "title = \""+filename+"\"\n"
file.write(result)
result = "/>\n"
fil... | -2 | 2016-08-09T13:47:13Z | 38,853,121 | <p>Rather than escaping all those double-quotes, why not embed your string inside single quotes instead? In Python (unlike many other languages) there is no difference between using single or double quotes, provided they are balanced (the same at each end).</p>
<p>If you need the backslashes in the text then use a <a... | 0 | 2016-08-09T14:09:18Z | [
"python"
] |
Python "split" on empty new line | 38,852,712 | <p>Trying to use a python split on a "empty" newline but not any other new lines. I tried a few other example I found but none of them seem to work. </p>
<p>Data example:</p>
<pre>
(*,224.0.0.0/4) RPF nbr: 96.34.35.36 Flags: C RPF P
Up: 1w6d
(*,224.0.0.0/24) Flags: D P
Up: 1w6d
(*,224.0.1.39) Flags: S P
Up: 1... | 0 | 2016-08-09T13:52:10Z | 38,852,821 | <p>It's quite easy when you consider what is on empty line. It's just the the newline character, so splitting on empty line would be splitting on two newline characters in sequence (one from the previou non-empty line, one is the 'whole' empty line.</p>
<pre><code>myarray = output.split("\n\n")
for line in myarray:
... | 1 | 2016-08-09T13:56:55Z | [
"python"
] |
Python "split" on empty new line | 38,852,712 | <p>Trying to use a python split on a "empty" newline but not any other new lines. I tried a few other example I found but none of them seem to work. </p>
<p>Data example:</p>
<pre>
(*,224.0.0.0/4) RPF nbr: 96.34.35.36 Flags: C RPF P
Up: 1w6d
(*,224.0.0.0/24) Flags: D P
Up: 1w6d
(*,224.0.1.39) Flags: S P
Up: 1... | 0 | 2016-08-09T13:52:10Z | 38,852,929 | <p>A blank line is just two new lines. So your easiest solution is probably to check for two new lines (UNLESS you expect to have a situation where you'll have more than two blank lines in a row).</p>
<pre><code>import os
myarray = [] #As DeepSpace notes, this is not necessary as split will return a list. No impact to... | 1 | 2016-08-09T14:00:59Z | [
"python"
] |
Python: trying to get three elements of a list with slice over a iterator | 38,852,779 | <p>I'm new to python.</p>
<p>I'm trying to create another list from a big one just with 3 elements of that list at a time.</p>
<p>I'm trying this:</p>
<pre><code>my_list = ['test1,test2,test3','test4,test5,test6','test7,test8,test9','test10,test11,test12']
new_three = []
for i in my_list:
item = my_list[int(... | -2 | 2016-08-09T13:55:07Z | 38,875,607 | <p>Is this what you meant?</p>
<pre><code>my_list = ['test1,test2,test3','test4,test5,test6','test7,test8,test9','test10,test11,test12']
for item in my_list:
print "this is one item from the list :", item
list_of_things = item.split(',')
print "make a list with split on comma:", list_of_things
# yo... | 0 | 2016-08-10T14:00:29Z | [
"python",
"list"
] |
How to flatten XML file in Python | 38,852,822 | <p>Is there a library or mechanism I can use to flatten the XML file?</p>
<p>Existing:</p>
<pre><code><A>
<B>
<ConnectionType>a</ConnectionType>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:00</EndTime>
<UseDataDictionary>N<... | 3 | 2016-08-09T13:56:57Z | 38,853,421 | <p>By using <a href="https://github.com/martinblech/xmltodict" rel="nofollow"><code>xmltodict</code></a> to transform your XML file to a dictionary, in combination with <a href="http://codereview.stackexchange.com/a/21035">this answer</a> to flatten a <code>dict</code>, this should be possible.</p>
<p>Example:</p>
<p... | 1 | 2016-08-09T14:22:44Z | [
"python",
"xml"
] |
How to flatten XML file in Python | 38,852,822 | <p>Is there a library or mechanism I can use to flatten the XML file?</p>
<p>Existing:</p>
<pre><code><A>
<B>
<ConnectionType>a</ConnectionType>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:00</EndTime>
<UseDataDictionary>N<... | 3 | 2016-08-09T13:56:57Z | 38,937,986 | <p>This is not a complete implementation but you could take advantage of <a href="http://lxml.de/api/lxml.etree._ElementTree-class.html#getpath" rel="nofollow">lxmls's getpath</a>:</p>
<pre><code>xml = """<A>
<B>
<ConnectionType>a</ConnectionType>
<... | 0 | 2016-08-13T23:55:16Z | [
"python",
"xml"
] |
Can I iterate over a cursor in pymssql more than once? | 38,852,826 | <p>For example, if I run a sql query in python (using pymssql):</p>
<pre><code>cursor.execute("""SELECT * FROM TABLE""")
</code></pre>
<p>Then I do:</p>
<pre><code>for row in cursor:
print row[0]
</code></pre>
<p>but then I want to loop through the table a second time for a different operation, like this:</p>
<... | 2 | 2016-08-09T13:57:10Z | 38,852,924 | <p>No, cursors in pymssql function like a generator. Once you get the results from them, they no longer contain the result set.</p>
<p>The only way to do this is to save the query results to an intermediary list.</p>
<p>For example:</p>
<pre><code>import pymssql
database = pymssql.connect()
db_cursor = database.curs... | 0 | 2016-08-09T14:00:51Z | [
"python",
"sql",
"database"
] |
Can I iterate over a cursor in pymssql more than once? | 38,852,826 | <p>For example, if I run a sql query in python (using pymssql):</p>
<pre><code>cursor.execute("""SELECT * FROM TABLE""")
</code></pre>
<p>Then I do:</p>
<pre><code>for row in cursor:
print row[0]
</code></pre>
<p>but then I want to loop through the table a second time for a different operation, like this:</p>
<... | 2 | 2016-08-09T13:57:10Z | 38,853,081 | <p>No, you can't do that as pymssql cursor (python generator) is almost same as file pointer and each row in cursor is same as each line in file and once you pass over an line you have to seek to start and start again, same case for cursor, you have to run the query again to get data.</p>
| 0 | 2016-08-09T14:07:05Z | [
"python",
"sql",
"database"
] |
REST API POST - Check if each nested object exists. If no, create new. If yes, return existing object | 38,852,863 | <p>I'm somewhat new to <code> RESTful API</code> design practice and looking for help. The data model I'm working with details a top-level object (e.g. Book) containing a list of a nested objects (e.g. Chapters).<br>
Each Chapter is persisted in its own right and has a <code><em>simple_name</em></code> field that is se... | 0 | 2016-08-09T13:58:37Z | 38,854,018 | <p>The idea here is to remove the uniqueness constraint by dropping the associated validator and deal with adding / updating / removing by yourself after (see <a href="https://stackoverflow.com/questions/38438167/unique-validation-on-nested-serializer-on-django-rest-framework">Unique validation on nested serializer on ... | 0 | 2016-08-09T14:48:57Z | [
"python",
"django",
"rest",
"django-rest-framework",
"api-design"
] |
Adding new columns to data frame based on the values of multiple columns | 38,852,904 | <p>I have a data frame whose header looks like following,
</p>
<pre><code>df.head()
Out[660]:
Samples variable value Type
0 PE01I 267N12.3_Beta 0.066517 Beta
1 PE01R R267N12.3_Beta 0.061617 Beta
2 PE02I 267N12.3_Beta 0.071013 Beta
3 PE02R 267N12.3_Beta 0.056623 Beta
4 PE03... | 1 | 2016-08-09T14:00:01Z | 38,853,142 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a>:</p>
<pre><code>df1 = df.set_index(['Samples','Type']).unstack()
print (df1)
variable value
Type Beta ... | 1 | 2016-08-09T14:10:03Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Adding new columns to data frame based on the values of multiple columns | 38,852,904 | <p>I have a data frame whose header looks like following,
</p>
<pre><code>df.head()
Out[660]:
Samples variable value Type
0 PE01I 267N12.3_Beta 0.066517 Beta
1 PE01R R267N12.3_Beta 0.061617 Beta
2 PE02I 267N12.3_Beta 0.071013 Beta
3 PE02R 267N12.3_Beta 0.056623 Beta
4 PE03... | 1 | 2016-08-09T14:00:01Z | 38,854,278 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow"><code>merge</code></a> after separating them into 2 dataframes based on their <code>Type</code> column.</p>
<pre><code>In [14]: df_1 = df.loc[(df['Type'] == "Beta"), ['Samples', 'variable', 'valu... | 1 | 2016-08-09T15:01:00Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
How to get screen name instead of user ID with tweepy | 38,853,003 | <p>I'm printing out the tweets from my twitter feed to a CSV and want to get the CSV to show the username instead of the user ID.</p>
<p>My code uses tweepy.</p>
<pre><code>outtweets.append([tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")])
</code></pre>
<p>This is what I use in my loop to get the user ID... | 0 | 2016-08-09T14:03:55Z | 38,853,350 | <p>See <a href="https://dev.twitter.com/overview/api/tweets" rel="nofollow">https://dev.twitter.com/overview/api/tweets</a> Tweet object and <a href="https://dev.twitter.com/overview/api/users" rel="nofollow">https://dev.twitter.com/overview/api/users</a> User object.</p>
<p>This will reveal that you need to use:</p>
... | 2 | 2016-08-09T14:19:47Z | [
"python",
"csv",
"twitter",
"tweepy"
] |
Paramiko & rsync - Get Progress asynchronously while command runs | 38,853,031 | <p>I am using paramiko to run rsync on a remote machine. When i use stdout.readlines() it blocks my program and outputs a ton of lines after the command ends. I know rsync progress always updates its output. How do i read the output every interval without waiting for the command to finish (i am transferring a very larg... | 2 | 2016-08-09T14:05:07Z | 38,853,426 | <p>Instead of using <code>readlines()</code> you should use <code>read([bytes])</code> to progressively read output. <code>readlines()</code> reads all lines until EOF (that's why you see the blocking) and then splits into lines on the <code>\n</code> character.</p>
<p>Instead, do something like this:</p>
<pre><code>... | 0 | 2016-08-09T14:22:55Z | [
"python",
"rsync",
"paramiko"
] |
Append an existing DataFrame with output from def as DataFrame | 38,853,054 | <p>I want to append an existing <code>DataFrame</code> with the output from a defined routine which returns itself a <code>DataFrame</code>. I want to take six of the thirteen columns and append the existing dataframe. Here is my code to create the output from the defined routine:</p>
<pre><code>import matplotlib.pypl... | 0 | 2016-08-09T14:06:06Z | 38,875,817 | <p>I was able to get the solution the following way:</p>
<pre><code>data_store = pandas.DataFrame(columns=('TICKER', 'DATE', 'rolling_vola_40', 'rolling_vola_80', 'f_rolling_vola_40', 'f_rolling_vola_80', 'rolling_vola_prev_annum', 'rolling_vola_post_annum'))
for index, row in data_static.iterrows():
data_output ... | 0 | 2016-08-10T14:09:56Z | [
"python",
"pandas",
"dataframe",
"return"
] |
Reading data from a VSD (Windows Visio Binary) File in Python (Linux) with OLE Tools is very unclear, is there any other way to extract the data? | 38,853,094 | <p>I am trying to read the contents of a Visio Binary .VSD file which contains information from a graph I have made. </p>
<p>I have tried using the OLE Tools and OLEFile but cannot correctly read the contents. I can view the file with the OLETools. When I dump the contents and view it with the 'xxd' command (in termin... | 0 | 2016-08-09T14:07:46Z | 38,855,285 | <p>You have really picked a strong enemy :)</p>
<p>Unlike other office apps Visio .vsd binary file format is not exactly Microsoft's "compound document", that's basically just a wrapper. The format was created by Visio Corp back in 199x, and AFAIK was never actually publicly documented.</p>
<p>I would really recomme... | 0 | 2016-08-09T15:49:54Z | [
"python",
"linux",
"ole",
"visio"
] |
Reading data from a VSD (Windows Visio Binary) File in Python (Linux) with OLE Tools is very unclear, is there any other way to extract the data? | 38,853,094 | <p>I am trying to read the contents of a Visio Binary .VSD file which contains information from a graph I have made. </p>
<p>I have tried using the OLE Tools and OLEFile but cannot correctly read the contents. I can view the file with the OLETools. When I dump the contents and view it with the 'xxd' command (in termin... | 0 | 2016-08-09T14:07:46Z | 38,856,029 | <p>Thanks for all the help. </p>
<p>I have found a way to extract plain text from the file and convert it to XHTML and parse that. The main problem is that now I loose any structure the original document may have had. </p>
<p>The tools are libvisio-tools
<a href="https://launchpad.net/ubuntu/trusty/+package/libvisio... | 0 | 2016-08-09T16:27:39Z | [
"python",
"linux",
"ole",
"visio"
] |
Using greater than expression to filter text file lines? | 38,853,162 | <p>I have a text file with multiple lines and want to find which lines have values greater than 85%.</p>
<pre class="lang-none prettyprint-override"><code>'workdata worka worka1 size 84% total'
'workdata workb workb1 size 89% total'
'workdata workc workc1 size 63% total'
'workdata workd workd1 size 94% total'
</code><... | -4 | 2016-08-09T14:10:53Z | 38,853,212 | <p>You need to extract percent first, and then filter the lines basing on that.</p>
<pre><code>import re
def extract_percent(line):
# doing extraction
try:
return int(re.findall('[0-9]+%', line)[0][:-1])
except:
return 0
print [line for line in lines if extract_percent(line) > 85]
</co... | 1 | 2016-08-09T14:13:29Z | [
"python"
] |
Using greater than expression to filter text file lines? | 38,853,162 | <p>I have a text file with multiple lines and want to find which lines have values greater than 85%.</p>
<pre class="lang-none prettyprint-override"><code>'workdata worka worka1 size 84% total'
'workdata workb workb1 size 89% total'
'workdata workc workc1 size 63% total'
'workdata workd workd1 size 94% total'
</code><... | -4 | 2016-08-09T14:10:53Z | 38,853,349 | <p>If you know the percentage will always be in the 5th column, then just split each row on space, remove the percentage sign, and turn it into a float. Something like this:</p>
<pre><code>lines = open("fileName", "r").read().splitlines()
for row in lines:
if float(row.split()[4].replace("%",""))>85:
pr... | 0 | 2016-08-09T14:19:42Z | [
"python"
] |
Write a CSV in Multiple rows - Python 2.7 | 38,853,343 | <p>Iâm working on a csv file containing data recorders of game players. sample of csv shows 4 players (10 rows) and 13 columns:</p>
<pre><code>Player_ID,Name,Age,DOB,Gender,Game1_result,Date_first_game,Game2_result,`Game3_result,Final_result,Team,Date_last_game,Finals_dates`
101,Ethan,16,1/15/2000,Male,won,3/20/201... | 0 | 2016-08-09T14:19:26Z | 38,853,655 | <p>You are appending all the data to <code>final_output</code>. Instead, make it list of lists as so:</p>
<pre><code>for row in reader:
new_row = []
new_row.append(row[0])
...
final_output.append(new_row)
</code></pre>
<p>And then when writing to file:</p>
<pre><code>csv_writer.writerow(headers)
for ... | 0 | 2016-08-09T14:32:42Z | [
"python",
"list",
"python-2.7",
"csv"
] |
perspective transformation in Python: from rectangular to trapezoid | 38,853,428 | <p>I am looking for a python function or library that can convert coordinates of rectangle to trapezoid coordinates. So far I found the relevant problem here: <a href="http://math.stackexchange.com/questions/13404/mapping-irregular-quadrilateral-to-a-rectangle">http://math.stackexchange.com/questions/13404/mapping-irre... | -1 | 2016-08-09T14:23:01Z | 38,853,928 | <p>I wanted to do the same but from trapezoid to rectangular coordinated. The package that do the trick is:</p>
<pre><code>from skimage.transform import ProjectiveTransform
</code></pre>
<p>You can read the complete answer in:</p>
<p><a href="http://stackoverflow.com/questions/33283088/transform-irregular-quadrilate... | 1 | 2016-08-09T14:44:17Z | [
"python",
"geometry",
"computational-geometry",
"projection",
"geometry-surface"
] |
Common rows of two .txt files in python | 38,853,517 | <p>I have 2 big .txt files and each file has 10 columns and 21008 rows. I need to get the common rows of two files and create a new file. The first column of two files include the IDs. Some of the IDs in 2 files are similar but not all of them. The new files would contain the common IDs and of course the complete row. ... | 1 | 2016-08-09T14:27:02Z | 38,854,023 | <p>Read the first file and iterate line by line, for each line keep the id and line. Do it for the next one only this time find the common lines by id and append then to a list in the output format:</p>
<pre><code>ids = {}
found = []
with open(filepath1) as file1:
for line in file1.lines():
id_ = line.spli... | 0 | 2016-08-09T14:49:18Z | [
"python",
"text"
] |
Common rows of two .txt files in python | 38,853,517 | <p>I have 2 big .txt files and each file has 10 columns and 21008 rows. I need to get the common rows of two files and create a new file. The first column of two files include the IDs. Some of the IDs in 2 files are similar but not all of them. The new files would contain the common IDs and of course the complete row. ... | 1 | 2016-08-09T14:27:02Z | 38,854,439 | <p>You can use a <code>dict</code> to keep track of seen lines from the second file to allow the first to set the order:</p>
<pre><code>d2={}
with open("f2.txt") as f2:
for line in f2:
k,_,v=line.partition(' ')
d2[k]=line.strip()
with open("f1.txt") as f1:
for line in f1:
k,_,v=line.pa... | 0 | 2016-08-09T15:09:19Z | [
"python",
"text"
] |
Common rows of two .txt files in python | 38,853,517 | <p>I have 2 big .txt files and each file has 10 columns and 21008 rows. I need to get the common rows of two files and create a new file. The first column of two files include the IDs. Some of the IDs in 2 files are similar but not all of them. The new files would contain the common IDs and of course the complete row. ... | 1 | 2016-08-09T14:27:02Z | 38,855,494 | <p>Here is a working solution (using lists) for your problem. At the end, you're going to get a list with all the rows with the same ID in a file named "res" </p>
<pre><code>l1 = []
l2 = []
with open('file1', 'r') as f1:
for line in f1:
line = line.split()
l1.append(line)
with open('file2', 'r') ... | 0 | 2016-08-09T15:59:26Z | [
"python",
"text"
] |
python, stub randomness twice in the same function | 38,853,524 | <p>How would I stub the output of <code>pickCard()</code> function which is being called twice in <code>deal()</code> function? I want to test both losing and winning cases.<br>
For example, I would like to have for the winning case, the first time <code>pickCard()</code> is called is given value <code>8</code> to <cod... | 2 | 2016-08-09T14:27:22Z | 38,853,823 | <p><code>mock.patch</code> is the way to go, but instead of <code>return_value</code> you should specify <code>side_effect=(8, 10)</code></p>
<pre><code>with mock.patch('lib.game.Game.pickCard') as mock_pick:
mock_pick.side_effect = (8, 10)
g = Game()
print(g.pickCard())
print(g.pickCard())
# 8
# 10
<... | 1 | 2016-08-09T14:39:37Z | [
"python",
"unit-testing"
] |
What is the best way to filter the dictionaries value in the list and remove that dictionary from list | 38,853,553 | <p>For example I have dictionaries inside list,</p>
<pre><code>student_list = [{'name':'ABC', 'marks': 8}, {'name':'DEF', 'marks': 0}, {'name': 'GHI', 'marks': 0}, {'name': 'JKL', 'marks': 0}, {'name': 'JKL', 'marks': 9}]
</code></pre>
<p>Output should be like,</p>
<pre><code>[{'name':'ABC', 'marks': 8}, {'name': 'J... | -2 | 2016-08-09T14:28:40Z | 38,853,612 | <p>You can use list comprehension.</p>
<pre><code>print [i for i in student_list if i['marks'] > 0]
</code></pre>
<p>As suggested in the comments, you can also use </p>
<pre><code>print [i for i in student_list if i.get('marks', 0)]
</code></pre>
| 2 | 2016-08-09T14:31:03Z | [
"python",
"python-2.7",
"dictionary"
] |
What is the best way to filter the dictionaries value in the list and remove that dictionary from list | 38,853,553 | <p>For example I have dictionaries inside list,</p>
<pre><code>student_list = [{'name':'ABC', 'marks': 8}, {'name':'DEF', 'marks': 0}, {'name': 'GHI', 'marks': 0}, {'name': 'JKL', 'marks': 0}, {'name': 'JKL', 'marks': 9}]
</code></pre>
<p>Output should be like,</p>
<pre><code>[{'name':'ABC', 'marks': 8}, {'name': 'J... | -2 | 2016-08-09T14:28:40Z | 38,853,790 | <p>You're looking for something a bit advanced like:</p>
<pre><code>print filter(lambda x: True if x['marks'] > 0 else False, student_list)
</code></pre>
<p>But this is really just an equivalent of the list comprehensions that were already suggested. See <a href="https://docs.python.org/2/library/functions.html#fi... | 1 | 2016-08-09T14:37:47Z | [
"python",
"python-2.7",
"dictionary"
] |
How to compile a Python module to dll and call it in VBA | 38,853,633 | <p>I want to create a user defined function written in Python. Then I want to compile it to a dll, and distribute it and call in EXCEL vba on another computer which doesn't have python installed.</p>
<p>For example, I want to create a function in Python:</p>
<p>def add(a,b):
return a+b</p>
<p>Then, compile it and... | -1 | 2016-08-09T14:31:43Z | 38,853,731 | <p>in excel go to the vbe editor Tools>References browse your dll and add a reference, this will make available your dll functions in vba.</p>
<p>as per making it a dll, look what jb suggest here <a href="http://stackoverflow.com/questions/10859369/how-to-compile-a-python-package-to-a-dll">How to compile a Python pack... | 0 | 2016-08-09T14:35:27Z | [
"python",
"vba",
"dll"
] |
Python XML: ParseError: junk after document element | 38,853,644 | <p>Trying to parse XML file into ElementTree:</p>
<pre><code>>>> import xml.etree.cElementTree as ET
>>> tree = ET.ElementTree(file='D:\Temp\Slikvideo\JPEG\SV_4_1_mask\index.xml')
</code></pre>
<p>I get following error:</p>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in
... | 3 | 2016-08-09T14:32:15Z | 38,853,752 | <p>The root node of your document (<code>Version</code>) is opened <strong>and</strong> closed on line 2. The parser does not expect any nodes after the root node. Solution is to remove the closing forward slash.</p>
| 2 | 2016-08-09T14:36:21Z | [
"python",
"xml"
] |
Python XML: ParseError: junk after document element | 38,853,644 | <p>Trying to parse XML file into ElementTree:</p>
<pre><code>>>> import xml.etree.cElementTree as ET
>>> tree = ET.ElementTree(file='D:\Temp\Slikvideo\JPEG\SV_4_1_mask\index.xml')
</code></pre>
<p>I get following error:</p>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in
... | 3 | 2016-08-09T14:32:15Z | 38,854,127 | <p>As @Matthias Wiehl said, ElementTree expects only a single root node and is not well-formed XML and should be fixed at its origin.
As a workaround you can simply add a fake root node to the document.</p>
<pre><code>import xml.etree.cElementTree as ET
import re
with open("index.xml") as f:
xml = f.read()
tree =... | 1 | 2016-08-09T14:54:11Z | [
"python",
"xml"
] |
Python XML: ParseError: junk after document element | 38,853,644 | <p>Trying to parse XML file into ElementTree:</p>
<pre><code>>>> import xml.etree.cElementTree as ET
>>> tree = ET.ElementTree(file='D:\Temp\Slikvideo\JPEG\SV_4_1_mask\index.xml')
</code></pre>
<p>I get following error:</p>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in
... | 3 | 2016-08-09T14:32:15Z | 38,854,205 | <p>Try repairing the document like this. Close the <code>version</code> element at the end</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<Version Writer="E:\d\src\Modules\SceneSerialization\src\mitkSceneIO.cpp" Revision="$Revision: 17055 $" FileVersion="1">
<node UID="OBJECT_201608081904158... | 0 | 2016-08-09T14:57:55Z | [
"python",
"xml"
] |
SpaCy urllib.error.URLError during Installation | 38,853,776 | <p>i'm just getting started with spaCy under python. Sadly I'm already stuck at installation process (<a href="https://spacy.io/docs/#getting-started" rel="nofollow">https://spacy.io/docs/#getting-started</a>).<br>
After <code>pip install spacy</code> i want to download the model with <code>python -m spacy.en.download... | 1 | 2016-08-09T14:37:26Z | 39,330,872 | <p>The problem was caused by a serverproblem of spacy itself and is fixed now.
(spacy.io/blog/announcement)</p>
| 0 | 2016-09-05T12:41:56Z | [
"python",
"python-3.x",
"pip",
"nltk",
"spacy"
] |
Determines the first integer that is evenly divisible by all other integers in a list of integers | 38,853,789 | <pre><code>def divisible(a):
d = 0
n = len(a)
i = 0
p = 0
while d == 0 and p < n and i < n:
if a[i] % a[p] != 0:
i = i + 1
p = 0
else:
p = p + 1
return d
a = [12, 4, 6]
r = divisible(a)
print(r)
</code></pre>
<p>Can anyone help me pls... | 0 | 2016-08-09T14:37:46Z | 38,853,951 | <p>A short solution would be</p>
<pre><code>def divisible(a):
for i in a:
if all(i%j==0 for j in a):
return i
return None
</code></pre>
<p>or a bit longer</p>
<pre><code>def divisible(a):
for i in a:
found=True
for j in a:
if i%j: # everything that is not 0... | 2 | 2016-08-09T14:45:14Z | [
"python"
] |
Determines the first integer that is evenly divisible by all other integers in a list of integers | 38,853,789 | <pre><code>def divisible(a):
d = 0
n = len(a)
i = 0
p = 0
while d == 0 and p < n and i < n:
if a[i] % a[p] != 0:
i = i + 1
p = 0
else:
p = p + 1
return d
a = [12, 4, 6]
r = divisible(a)
print(r)
</code></pre>
<p>Can anyone help me pls... | 0 | 2016-08-09T14:37:46Z | 38,853,961 | <p>I think you're looking for the least common multiple algorithm, in python3 you could code it like this:</p>
<pre><code>from fractions import gcd
from functools import reduce
def lcm(*args):
return reduce(lambda a, b: a * b // gcd(a, b), args)
print lcm(4, 6, 12)
</code></pre>
<p>But it seems you can't use a... | 0 | 2016-08-09T14:45:45Z | [
"python"
] |
Determines the first integer that is evenly divisible by all other integers in a list of integers | 38,853,789 | <pre><code>def divisible(a):
d = 0
n = len(a)
i = 0
p = 0
while d == 0 and p < n and i < n:
if a[i] % a[p] != 0:
i = i + 1
p = 0
else:
p = p + 1
return d
a = [12, 4, 6]
r = divisible(a)
print(r)
</code></pre>
<p>Can anyone help me pls... | 0 | 2016-08-09T14:37:46Z | 38,854,557 | <p>I have expended on my previous comment. We don't need to actually compute any multiples, since we expect it to already be in the list. The trick is just to take the max (or min, if negative numbers are allowed), and then validate. </p>
<p>But first, figure out how you are going to handle 0. It is divisible by all o... | 0 | 2016-08-09T15:14:30Z | [
"python"
] |
How to use python argparse with args other than sys.argv? | 38,853,812 | <p>I've been all over the documentation and it seems like there's no way to do it, but:</p>
<p>Is there a way to use argparse with any list of strings, instead of only with sys.argv?</p>
<p>Here's my problem: I have a program which looks something like this:</p>
<pre><code># This file is program1.py
import argparse
... | 0 | 2016-08-09T14:38:54Z | 38,853,865 | <p>Just change the script to default to <code>sys.argv[1:]</code> and parse arguments omitting the first one (which is the name of the invoked command)</p>
<pre><code>import argparse,sys
def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser()
# Do some argument parsing
args = parser.parse_args(arg... | 1 | 2016-08-09T14:41:22Z | [
"python",
"argparse",
"argv"
] |
How to use python argparse with args other than sys.argv? | 38,853,812 | <p>I've been all over the documentation and it seems like there's no way to do it, but:</p>
<p>Is there a way to use argparse with any list of strings, instead of only with sys.argv?</p>
<p>Here's my problem: I have a program which looks something like this:</p>
<pre><code># This file is program1.py
import argparse
... | 0 | 2016-08-09T14:38:54Z | 38,853,883 | <p>You can pass a list of strings to <code>parse_args</code>:</p>
<pre><code>parser.parse_args(['--foo', 'FOO'])
</code></pre>
| 4 | 2016-08-09T14:42:14Z | [
"python",
"argparse",
"argv"
] |
import json to csv in python | 38,853,819 | <p>When I use the following code, I keep getting an error even though it creates the csv file. I need help and am fairly new to python. </p>
<p>The error i receive is "Traceback (most recent call last):
File "/home/ubuntu/workspace/parse-json.py", line 34, in
values = [ x.encode('utf8') for x in item['fields'].... | -1 | 2016-08-09T14:39:25Z | 38,854,041 | <p>You need to check your data structures.
Basically what the error is saying is that <code>item</code> is not a dictionary.</p>
<p>From what I see in your code, you are iterating over <code>data</code>, but data is not a list of dictionaries but a dictionary itself.</p>
<p>If you want to iterate through the elements... | 0 | 2016-08-09T14:50:08Z | [
"python",
"json",
"csv"
] |
Matching elements between lists in Python - keeping location | 38,853,828 | <p>I have two lists, both fairly long. List A contains a list of integers, some of which are repeated in list B. I can find which elements appear in both by using:</p>
<pre><code>idx = set(list_A).intersection(list_B)
</code></pre>
<p>This returns a set of all the elements appearing in both list A and list B.</p>
<p... | 0 | 2016-08-09T14:39:46Z | 38,854,019 | <p>Try this:</p>
<pre><code>def match_lists(list_A, list_B):
match_A = {}
match_B = {}
for elem in list_A:
if elem in list_B:
match_A[elem] = list_A.index(elem)
match_B[elem] = list_B.index(elem)
return match_A, match_B
</code></pre>
| -1 | 2016-08-09T14:49:03Z | [
"python",
"list",
"iterator",
"match"
] |
Matching elements between lists in Python - keeping location | 38,853,828 | <p>I have two lists, both fairly long. List A contains a list of integers, some of which are repeated in list B. I can find which elements appear in both by using:</p>
<pre><code>idx = set(list_A).intersection(list_B)
</code></pre>
<p>This returns a set of all the elements appearing in both list A and list B.</p>
<p... | 0 | 2016-08-09T14:39:46Z | 38,854,036 | <p>How about this:</p>
<pre><code>def match_lists(list_A, list_B):
idx = set(list_A).intersection(list_B)
A_indexes = []
for i, element in enumerate(list_A):
if element in idx:
A_indexes.append(i)
B_indexes = []
for i, element in enumerate(list_B):
if element in idx:
... | 1 | 2016-08-09T14:50:01Z | [
"python",
"list",
"iterator",
"match"
] |
Matching elements between lists in Python - keeping location | 38,853,828 | <p>I have two lists, both fairly long. List A contains a list of integers, some of which are repeated in list B. I can find which elements appear in both by using:</p>
<pre><code>idx = set(list_A).intersection(list_B)
</code></pre>
<p>This returns a set of all the elements appearing in both list A and list B.</p>
<p... | 0 | 2016-08-09T14:39:46Z | 38,854,050 | <p>That should do the job :)</p>
<pre><code>def match_list(list_A, list_B):
intersect = set(list_A).intersection(list_B)
interPosA = [[i for i, x in enumerate(list_A) if x == dup] for dup in intersect]
interPosB = [i for i, x in enumerate(list_B) if x in intersect]
return interPosA, interPosB
</code></... | 3 | 2016-08-09T14:50:26Z | [
"python",
"list",
"iterator",
"match"
] |
Matching elements between lists in Python - keeping location | 38,853,828 | <p>I have two lists, both fairly long. List A contains a list of integers, some of which are repeated in list B. I can find which elements appear in both by using:</p>
<pre><code>idx = set(list_A).intersection(list_B)
</code></pre>
<p>This returns a set of all the elements appearing in both list A and list B.</p>
<p... | 0 | 2016-08-09T14:39:46Z | 38,854,144 | <p>Use <code>dict</code>s or <code>defaultdict</code>s to store the unique values as keys that map to the indices they appear at, then combine the <code>dicts</code>:</p>
<pre><code>from collections import defaultdict
def make_offset_dict(it):
ret = defaultdict(list) # Or set, the values are unique indices eithe... | 2 | 2016-08-09T14:54:44Z | [
"python",
"list",
"iterator",
"match"
] |
Matching elements between lists in Python - keeping location | 38,853,828 | <p>I have two lists, both fairly long. List A contains a list of integers, some of which are repeated in list B. I can find which elements appear in both by using:</p>
<pre><code>idx = set(list_A).intersection(list_B)
</code></pre>
<p>This returns a set of all the elements appearing in both list A and list B.</p>
<p... | 0 | 2016-08-09T14:39:46Z | 38,854,415 | <p>This only runs through each list once (requiring only one dict) and also works with duplicates in list_B</p>
<pre><code>def match_lists(list_A,list_B):
da=dict((e,i) for i,e in enumerate(list_A))
for bi,e in enumerate(list_B):
try:
ai=da[e]
yield (e,ai,bi) # element e... | 0 | 2016-08-09T15:08:09Z | [
"python",
"list",
"iterator",
"match"
] |
Trying to get formset to work with two models in django | 38,853,841 | <p>I can't seem to figure out why this isn't working. What I want to do is have my inspection_vals formset show inspeciton_val reading and dimension description for each for some reason django keeps yelling at me that description isn't specified for inspeciton_vals and help would be greatly appreciated. Below I gave m... | 0 | 2016-08-09T14:40:12Z | 38,856,744 | <p>You are missing the management form in template</p>
<pre><code><form method="post">
{% csrf_token %}
{{ formset.management_form }} # important
{% for x in formset %}
{{ x.as_p }}
{% endfor %}
</form>
</code></pre>
| 0 | 2016-08-09T17:10:17Z | [
"python",
"django",
"python-2.7"
] |
groupby/unstack on columns name | 38,853,916 | <p>I have a dataframe with the following structure</p>
<pre><code> idx value Formula_name
0 123456789 100 Frequency No4
1 123456789 150 Frequency No25
2 123456789 125 Frequency No27
3 123456789 0.2 Power Level No4
4 123456789 0.5 Power Level No25
5 123456789 ... | 1 | 2016-08-09T14:43:47Z | 38,854,188 | <p>You can use:</p>
<pre><code>print (df)
idx value Formula_name
0 123456789 100.0 Frequency No4
1 123456789 150.0 Frequency No25
2 123456789 125.0 Frequency No27
3 123456789 0.2 Power Level No4
4 123456789 0.5 Power Level No25
5 123456789 -1.0 Power Level No27
6 12345678... | 2 | 2016-08-09T14:57:11Z | [
"python",
"pandas"
] |
Python 3.5 | Split List and convert to csv | 38,853,966 | <p>I have two lists saved in two values. Those look like:</p>
<pre><code>project_titles = ['T1', 'T2', 'T3']
project_loc = ['L1', 'L2', 'L3']
</code></pre>
<p>Actual I write the values with this Code into a csv:</p>
<pre><code>with open('data.csv', 'w') as f:
csv.writer(f).writerow(project_titles)
</code></pre>
... | 0 | 2016-08-09T14:46:15Z | 38,854,046 | <p>You could use <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> to aggregate elements from two or more lists, then write the resulting rows to the file with <a href="https://docs.python.org/3.5/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>csvwrit... | 3 | 2016-08-09T14:50:22Z | [
"python",
"excel",
"python-3.x",
"csv"
] |
Python client error 'Connection reset by peer' | 38,853,972 | <p>I have written a very small python client to access confluence restful api. I am using https protocol to connect with the confluence. I am running into <code>Connection reset by peer</code> error.
Here is the full stack trace.</p>
<pre><code>/Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-pack... | 1 | 2016-08-09T14:46:33Z | 38,854,398 | <p>While installing <code>requests</code> library it skips few of <a href="https://github.com/kennethreitz/requests/blob/5a799dd0f505e6c6c2ff67e227f6a3d25c086342/setup.py#L71" rel="nofollow">optional security packages</a> ('pyOpenSSL', 'ndg-httpsclient', and 'pyasn1') which are required for the SSL/Https connection.
Y... | 0 | 2016-08-09T15:07:23Z | [
"python",
"python-requests",
"confluence-rest-api"
] |
python csv reader not reading all rows | 38,854,118 | <p>So I've got about 5008 rows in a CSV file, a total of 5009 with the headers. I'm creating and writing this file all within the same script. But when i read it at the end, with either pandas pd.read_csv, or python3's csv module, and print the len, it outputs 4967. I checked the file for any weird characters that may ... | 2 | 2016-08-09T14:53:50Z | 38,854,533 | <p>My best guess without seeing the file is that you have some lines with too many or not enough commas, maybe due to values like <code>foo,bar</code>. </p>
<p>Please try setting <code>error_bad_lines=True</code>. From Pandas documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv... | 0 | 2016-08-09T15:13:25Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
Processing form data with a Python CGI Script | 38,854,189 | <p>Can anyone point out where I am going wrong here. I have two scripts, one for the form and the other for the processing. It looks correct but after two hours of staring at it I cannot see where I am going wrong.
Here are the two scripts, they are very short so please take a look at it.</p>
<p>The Form:</p>
<pre><c... | 0 | 2016-08-09T14:57:14Z | 38,976,264 | <p>Well thats simple in your form replace the <code>action=process_data.py</code>to
<code>action=http://localhost/cgi-bin/practice/process_practice.py</code> or may be <code>action=http://localhost/cgi-bin/practice/process_data.py</code> whatever the name of that script is.</p>
| 0 | 2016-08-16T13:28:15Z | [
"python",
"html",
"forms",
"cgi"
] |
Processing form data with a Python CGI Script | 38,854,189 | <p>Can anyone point out where I am going wrong here. I have two scripts, one for the form and the other for the processing. It looks correct but after two hours of staring at it I cannot see where I am going wrong.
Here are the two scripts, they are very short so please take a look at it.</p>
<p>The Form:</p>
<pre><c... | 0 | 2016-08-09T14:57:14Z | 38,978,566 | <p>Changing it from:</p>
<pre><code>action=process_data.py
</code></pre>
<p>to:</p>
<pre><code>action=http://localhost/cgi-bin/practice/process_data.py
</code></pre>
<p>Worked.</p>
| 0 | 2016-08-16T15:14:28Z | [
"python",
"html",
"forms",
"cgi"
] |
How do I assign a group # to a set of rows in a pandas data frame? | 38,854,207 | <p>A dataframe has a time column with int values that start at zero. I want to group my data frame into 100 groups (for example) where the step is <code>ts = df['time'].max()/100</code>. One naive way to do it, is to test each value of the 'time' column if is greater than <code>t</code> <code>and</code> less than <code... | 0 | 2016-08-09T14:57:58Z | 38,854,369 | <p>You can use <code>pd.cut</code> to generate the groups:</p>
<pre><code>df.groupby(pd.cut(df['time'], 2)).mean()
Out:
0 1 2 3 time
time
(59530697.759, 73895991.5] 1 1 1 1130165891 59559371
(73895991.5, 88232612] ... | 2 | 2016-08-09T15:06:07Z | [
"python",
"pandas",
"dataframe"
] |
Create multiplication table? | 38,854,223 | <p>Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code</p>
<pre><code>x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
</code></pre>
<p>well,the result is correct but it does not appear in a squar... | 1 | 2016-08-09T14:58:34Z | 38,854,295 | <p>You should print without a line break. </p>
<pre><code>x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
print i*j, # will not break the line
print # will break the line
</code></pre>
| 8 | 2016-08-09T15:02:04Z | [
"python",
"python-2.7"
] |
Create multiplication table? | 38,854,223 | <p>Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code</p>
<pre><code>x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
</code></pre>
<p>well,the result is correct but it does not appear in a squar... | 1 | 2016-08-09T14:58:34Z | 38,854,317 | <p>you may add formatting to keep constant cell width</p>
<pre><code>x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
# substitute value for brackets
# force 4 characters, n stands for number
print '{:4n}'.format(i*j), # comma prevents line break
print # print empty line
</code... | 2 | 2016-08-09T15:03:16Z | [
"python",
"python-2.7"
] |
Create multiplication table? | 38,854,223 | <p>Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code</p>
<pre><code>x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
</code></pre>
<p>well,the result is correct but it does not appear in a squar... | 1 | 2016-08-09T14:58:34Z | 38,854,521 | <p>Python's print statement adds new line character by default to the numbers you wish to have in your output. I guess you would like to have just a trailing spaces for inner loop and a new line character at the end of the outer loop.</p>
<p>You can achieve this by using</p>
<pre><code>print i * j, # note the comma... | 1 | 2016-08-09T15:12:55Z | [
"python",
"python-2.7"
] |
Do union types actually exist in python? | 38,854,282 | <p>Since python is dynamically typed, of course we can do something like this:</p>
<pre><code>def f(x):
return 2 if x else "s"
</code></pre>
<p>But is the way python was actually intended to be used? or in other words, do union types exist in the sense they do in racket for example? Or do we only use them like th... | 2 | 2016-08-09T15:01:15Z | 38,854,368 | <p>Union typing is only needed when you have a statically typed language, as you need to declare that an object can return one of multiple types (in your case an <code>int</code> or <code>str</code>, or in the other example <code>str</code> or <code>NoneType</code>).</p>
<p>Python deals in <em>objects</em> only, so th... | 6 | 2016-08-09T15:06:03Z | [
"python",
"types",
"unions",
"dynamic-typing"
] |
Do union types actually exist in python? | 38,854,282 | <p>Since python is dynamically typed, of course we can do something like this:</p>
<pre><code>def f(x):
return 2 if x else "s"
</code></pre>
<p>But is the way python was actually intended to be used? or in other words, do union types exist in the sense they do in racket for example? Or do we only use them like th... | 2 | 2016-08-09T15:01:15Z | 38,854,474 | <p>Adding to @MartijnPieters answer:</p>
<blockquote>
<p>But is the way python was actually intended to be used?</p>
</blockquote>
<p>Returning different type depending on the param is never a good practice in any language. This makes testing, maintaining and extending the code really difficult and IMHO is an anti-... | 1 | 2016-08-09T15:10:59Z | [
"python",
"types",
"unions",
"dynamic-typing"
] |
Returning dict Value with a variable Key | 38,854,337 | <p>I am using the characters in a word to search the keys of a dictionary. The dictionary is SCRABBLE_LETTER_VALUES: { 'a' : 1, 'b' : 3, ...} and so on.</p>
<p>Here is my incomplete code:</p>
<pre><code>"""
Just a test example
word = 'pie'
n = 3
"""
def get_word_score(word, n):
"""
Returns the score for a word. A... | 1 | 2016-08-09T15:04:13Z | 38,854,481 | <p>You put zero in <code>score</code> in every iteration. You should initialize it before the <code>for</code> loop.</p>
<pre><code>score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score
</code></pre>
| -1 | 2016-08-09T15:11:19Z | [
"python",
"dictionary",
"key",
"value"
] |
Returning dict Value with a variable Key | 38,854,337 | <p>I am using the characters in a word to search the keys of a dictionary. The dictionary is SCRABBLE_LETTER_VALUES: { 'a' : 1, 'b' : 3, ...} and so on.</p>
<p>Here is my incomplete code:</p>
<pre><code>"""
Just a test example
word = 'pie'
n = 3
"""
def get_word_score(word, n):
"""
Returns the score for a word. A... | 1 | 2016-08-09T15:04:13Z | 38,854,483 | <p>You can do the following:</p>
<pre><code>score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score
</code></pre>
<p><code>get()</code> will return the value of the key if the dictionary contains it, otherwise it will return the default value passed as second argument (0 in the snippet).</... | 2 | 2016-08-09T15:11:24Z | [
"python",
"dictionary",
"key",
"value"
] |
How to draw a tiled triangle with python turtle | 38,854,370 | <p>I am trying to draw a tiled equilateral triangle that looks like this</p>
<p><a href="http://i.stack.imgur.com/X7ybH.png" rel="nofollow"><img src="http://i.stack.imgur.com/X7ybH.png" alt="enter image description here"></a></p>
<p>using python's turtle. I would like to be able to have either 16,25,36,49 or 64 trian... | 2 | 2016-08-09T15:06:09Z | 38,856,185 | <p>I found this an interesting problem, if modified so that the turtle must draw the figure just by moving and without jumps.</p>
<p>The solution I found is ugly, but it can be a starting point...</p>
<pre><code>def n_tri(t, size, n):
for k in range(n):
for i in range(k-1):
t.left(60)
... | 1 | 2016-08-09T16:36:45Z | [
"python",
"turtle-graphics",
"tiling"
] |
using Python list to set conditional pandas statement | 38,854,437 | <p>I have a calculation that I need to aggregate, but it will not work with GROUPBY in PANDAs. So, I'm stuck with iterating over the groups manually. The groups are defined by 2 fields of 'object' type values, which are essentially the categories.</p>
<p>I think an elegant solution may be to create 2 lists from the un... | -1 | 2016-08-09T15:09:18Z | 38,858,417 | <p>The simple answer to your edit is to just use <code>enumerate</code>:</p>
<pre><code>for z, (x, y) in enumerate(itertools.product(cats1, cats2)):
print x, y, z
blue dog 0
blue horse 1
blue cow 2
blue sheep 3
yellow dog 4
yellow horse 5
yellow cow 6
yellow sheep 7
pink dog 8
pink horse 9
pink cow 10
pink sheep ... | 0 | 2016-08-09T18:56:09Z | [
"python",
"python-2.7",
"pandas"
] |
BitVector operations impossible | 38,854,440 | <p>I want to perform an xor operation on two BitVectors. While trying to turn one of the strings into a bitVector to then proceed into the xor operation, I get the following error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: '\x91'
</code></pre>
<p>How can I bypass this problem? I just want to ... | 0 | 2016-08-09T15:09:24Z | 38,854,661 | <p><code>bitstring</code> is for sequences of <code>'0'</code>s and <code>'1'</code>s. To use text use <code>textstring</code> instead.</p>
| 2 | 2016-08-09T15:20:30Z | [
"python",
"python-3.x",
"bitvector"
] |
Conda/Python: Import Error - image not found in jupyter notebook only | 38,854,513 | <p>I'm getting an import failure of <code>scipy.io</code> in a <code>jupyter</code> notebook. The confusing part is that I'm not getting the same, or any, error in an iPython terminal but I am in a standard Python terminal. This leads me to think that somehow, my <code>jupyter</code> session is using a different linkin... | 1 | 2016-08-09T15:12:41Z | 38,861,038 | <p>This appears to be a bug with the conda build:</p>
<p><a href="https://github.com/ContinuumIO/anaconda-issues/issues/899" rel="nofollow">https://github.com/ContinuumIO/anaconda-issues/issues/899</a></p>
<p>One commentor (@stuarteberg) on the issue stated:</p>
<blockquote>
<p>The new latest scipy version (0.18.0... | 1 | 2016-08-09T21:53:55Z | [
"python",
"scipy",
"anaconda",
"jupyter-notebook",
"conda"
] |
how to convert a (possibly negative) Pandas TimeDelta in minutes (float)? | 38,854,582 | <p>I have a dataframe like this</p>
<pre><code>df[['timestamp_utc','minute_ts','delta']].head()
Out[47]:
timestamp_utc minute_ts delta
0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000
1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000
... | 2 | 2016-08-09T15:16:06Z | 38,854,647 | <p>You can use:</p>
<pre><code>df['a'] = df['delta'] / np.timedelta64(1, 'm')
print (df)
timestamp_utc minute_ts delta \
0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000
1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000
2 2015-0... | 1 | 2016-08-09T15:19:53Z | [
"python",
"datetime",
"pandas"
] |
how to convert a (possibly negative) Pandas TimeDelta in minutes (float)? | 38,854,582 | <p>I have a dataframe like this</p>
<pre><code>df[['timestamp_utc','minute_ts','delta']].head()
Out[47]:
timestamp_utc minute_ts delta
0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000
1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000
... | 2 | 2016-08-09T15:16:06Z | 38,855,580 | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow">Timedelta object</a> in Pandas, and then use floor division in a list comprehension to calculate the minutes. Note that the seconds property of <code>Timedelta</code> returns the number of seconds (>= 0 and less tha... | 1 | 2016-08-09T16:03:19Z | [
"python",
"datetime",
"pandas"
] |
How to select a drop down option based on text of a variable in python and selenium | 38,854,606 | <p>All, I'm just learning python as well as selenium. and i'm stuck on how to select from a dropdown menu based on a variable. </p>
<p>I am able to select it based on the Text within the dropdown menu. like below ... </p>
<pre><code>CreateJob = driver.find_element_by_partial_link_text('Create Activity')
time.sleep(5... | 0 | 2016-08-09T15:17:29Z | 38,854,781 | <p>Directly pass variable <code>createjob1</code> into <code>select_by_visible_text()</code> as below :</p>
<pre><code>createjob1 = "THE ITEM I WANT"
select.select_by_visible_text(createjob1)
</code></pre>
| 0 | 2016-08-09T15:26:18Z | [
"python",
"selenium"
] |
'try' for 'duration' in python 3 | 38,854,726 | <p>I am figuring out how to have my python try to complete an action ( that may never be able to happen ) until what is the equivalent of a timer runs out in which case it runs a separate function. </p>
<p>The exact scenario is bypassing the "Warning" screen that outlook provides when something of an automation system... | 3 | 2016-08-09T15:23:27Z | 38,854,986 | <p>One of the solutions is this:</p>
<pre><code>import threading
mail = None
def func():
global mail
mail = inbox.Items[0].Sender
thread = threading.Thread(target=func)
thread.start()
thread.join(timeout=10)
if thread.is_alive():
# operation not completed
outlookWarningFunc()
# you must do clea... | 4 | 2016-08-09T15:35:56Z | [
"python",
"time",
"outlook"
] |
Zip File with Python Shutil like File Explorer | 38,854,745 | <h2>Background</h2>
<p>I am trying to zip a directory with python shutil like this:</p>
<pre><code>shutil.make_archive("~/Desktop/zipfile", 'zip', "~/Documents/foldertozip")
</code></pre>
<p>but the result only zips the files <em>inside</em> "foldertozip". So for instance,</p>
<pre><code>foldertozip
-- file1
... | 1 | 2016-08-09T15:24:21Z | 38,854,947 | <p><code>make_archive</code> will do what you want if you pass both <code>root_dir</code> and <code>base_dir</code>. See <a href="https://docs.python.org/2/library/shutil.html#shutil.make_archive" rel="nofollow">the docs</a>.</p>
<pre><code>import shutil
shutil.make_archive('~/Desktop/zipfile', 'zip', '~/Documents/',... | 2 | 2016-08-09T15:33:55Z | [
"python",
"directory",
"zip",
"folder",
"shutil"
] |
Zip File with Python Shutil like File Explorer | 38,854,745 | <h2>Background</h2>
<p>I am trying to zip a directory with python shutil like this:</p>
<pre><code>shutil.make_archive("~/Desktop/zipfile", 'zip', "~/Documents/foldertozip")
</code></pre>
<p>but the result only zips the files <em>inside</em> "foldertozip". So for instance,</p>
<pre><code>foldertozip
-- file1
... | 1 | 2016-08-09T15:24:21Z | 38,855,180 | <p>From the documentation of make_archive: </p>
<pre><code>shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
</code></pre>
<p>Create an archive file (eg. zip or tar) and returns its name.</p>
<p><strong>base_name</strong> is the name of the file to creat... | 1 | 2016-08-09T15:44:56Z | [
"python",
"directory",
"zip",
"folder",
"shutil"
] |
Python 3: how to tests exceptions within with? | 38,854,796 | <p>I have problems to test exceptions which would be raised within a with in python 3.4. I just can't get the tests run for this peace of code:</p>
<pre><code>import logging
...
class Foo(object):
...
def foo(self, src, dst):
try:
with pysftp.Connection(self._host, username=self._username, ... | 1 | 2016-08-09T15:27:00Z | 38,856,121 | <p>Your <code>sftp_mock.return_value</code> object is never called, so the <code>side_effect</code> is never triggered and no exception is raised. It would only be called if the <em>return value</em> of <code>pysftp.Connection(...)</code> was itself called again.</p>
<p>Set the side effect <em>directly on the mock</em... | 1 | 2016-08-09T16:32:45Z | [
"python",
"unit-testing",
"mocking",
"nose",
"python-mock"
] |
how can I make my django app automatically scrape in the background on heroku | 38,854,897 | <p>I am trying to figure out how to have my app use a function that scrapes sites in the backround, becuase it takes a long time and causes an error if ran in the foreground. So I followed the tutorial on Heroku's site that has a function that counts words and is ran in the background. It works. So I was ready to put m... | 0 | 2016-08-09T15:31:46Z | 38,858,992 | <p>Im not sure about Heroku. But normally you can achieve such automated tasks in django through Celery. </p>
<p>You have awesome documentation here. <a href="http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html" rel="nofollow">http://docs.celeryproject.org/en/latest/django/first-steps-with-djan... | 1 | 2016-08-09T19:31:58Z | [
"python",
"django",
"heroku",
"redis"
] |
Pig//Spark jobs not seeing Python modules | 38,854,914 | <p>I have a <strong>recurring problem</strong> with my hadoop cluster in that occasionally a <strong>functioning code stops seeing python modules</strong> that are in the proper location. I'm looking for tips from someone who might have faced the same problem.</p>
<p>When I first started programming and a code stopped... | 2 | 2016-08-09T15:32:31Z | 39,107,892 | <p>So we solved the problem. The issue is particular to our set up. We have all of our datanodes nfs mounted. Occasionally a node fails, and someone has to bring it back up and remount it. </p>
<p>Our script specifies the path to libraries like:'</p>
<pre><code> pig -Dmapred.child.env="PYTHONPATH=$path_to_mnt$hdfs... | 0 | 2016-08-23T18:00:23Z | [
"python",
"hadoop",
"apache-pig",
"pyspark"
] |
matplotlib - autosize of text according to shape size | 38,854,940 | <p>I'm adding a text inside a shape by:
<code>ax.text(x,y,'text', ha='center', va='center',bbox=dict(boxstyle='circle', fc="w", ec="k"),fontsize=10)</code> (ax is AxesSubplot)</p>
<p>The problem is that I couldn't make the circle size constant while changing the string length. I want the text size adjust to the circle... | 0 | 2016-08-09T15:33:34Z | 38,860,355 | <p>I have a very dirty and hard-core solution which requires quite deep knowledge of matplotlib. It is not perfect but might give you some ideas how to start.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import numpy as np
plt.close('all')
fig, ax = plt.subplots(1, 1, figsize=... | 0 | 2016-08-09T21:01:31Z | [
"python",
"matplotlib"
] |
NoBrokersAvailable: NoBrokersAvailable-Kafka Error | 38,854,957 | <p>i have already started to learn Kafka. Trying basic operations on it. I have stucked on a point which about the 'Brokers'. </p>
<p>My kafka is running but when i want to create a partition.</p>
<pre><code> from kafka import TopicPartition
(ERROR THERE) consumer = KafkaConsumer(bootstrap_servers='localhost:1234')
... | 1 | 2016-08-09T15:34:26Z | 38,859,436 | <p>It looks like you want to start consuming messages instead of creating partions. Nevertheless - can you reach kafka at port 1234? 9092 is kafkas default port maybe you can try this one. If you found the right port but your application still produces errors you can try to use a console consumer to test your setup:</p... | 1 | 2016-08-09T20:01:04Z | [
"python",
"apache-kafka",
"kafka-consumer-api",
"kafka-producer-api",
"python-kafka"
] |
NoBrokersAvailable: NoBrokersAvailable-Kafka Error | 38,854,957 | <p>i have already started to learn Kafka. Trying basic operations on it. I have stucked on a point which about the 'Brokers'. </p>
<p>My kafka is running but when i want to create a partition.</p>
<pre><code> from kafka import TopicPartition
(ERROR THERE) consumer = KafkaConsumer(bootstrap_servers='localhost:1234')
... | 1 | 2016-08-09T15:34:26Z | 38,867,470 | <p>You cannot create partitions within a consumer. Partitions are created when you create a topic. For example, using command line tool:</p>
<pre class="lang-sh prettyprint-override"><code>bin/kafka-topics.sh \
--zookeeper localhost:2181 \
--create --topic myNewTopic \
--partitions 10 \
--replication-factor 3
... | 1 | 2016-08-10T08:01:03Z | [
"python",
"apache-kafka",
"kafka-consumer-api",
"kafka-producer-api",
"python-kafka"
] |
Python Console GUI Updating whilst getting keyboard input | 38,855,001 | <p>I was wondering if it is possible to have a command-line interface that in essence blinks the current system time every second but allows the user to keep entering data via raw_input or something?</p>
<p>Thanks,</p>
<p>Ryan</p>
| 0 | 2016-08-09T15:36:34Z | 38,855,087 | <p>No it's not at the same time anyway. Here's an example for showing the time in terminal.</p>
<pre><code>import time
while True:
#time.sleep(1) #Uncommet to have it only print the time every second
x = time.strftime("%H:%M:%S")
print x
</code></pre>
| 2 | 2016-08-09T15:41:45Z | [
"python",
"python-2.7",
"date",
"input"
] |
Conversion from CMYK to RGB with Pillow is different from that of Photoshop | 38,855,022 | <p>I need to convert an image from CMYK to RGB in python. I used Pillow in this way:</p>
<pre><code>img = Image.open('in.jpg')
img = img.convert('RGB')
img.save('out.jpg')
</code></pre>
<p>The code works, but if I convert the same image with Photoshop I have a different result as shown below:-</p>
<p><a href="http:/... | 2 | 2016-08-09T15:38:06Z | 38,855,893 | <p><strong>SOLVED</strong></p>
<p>The problem is that Pillow does not know the input ICC profile, while photoshop had one set as default.</p>
<p>Photoshop use for</p>
<p><strong>CMYK</strong>: U.S. Web Coated (SWOP) v2</p>
<p><strong>RGB</strong>: sRGB IEC61966-2.1</p>
<p>So I've solved in this way:</p>
<pre><cod... | 2 | 2016-08-09T16:20:15Z | [
"python",
"rgb",
"photoshop",
"pillow",
"image-conversion"
] |
Inverting the "numpy.ma.compressed" operation | 38,855,058 | <p>I want to create an array from a compressed masked array and a corresponding mask. Its easier to explain this with an example:</p>
<pre><code>>>> x=np.ma.array(np.arange(4).reshape((2,2)), mask = [[True,True],[False,False]])
>>> y=x.compressed()
>>> y
array([ 2, 3])
</code></pre>
<p>Now... | 0 | 2016-08-09T15:39:58Z | 38,856,546 | <p>While I've answered a number of <code>ma</code> questions I'm by no means an expert with it. But I'll explore the issue</p>
<p>Let's generalize your a array a bit:</p>
<pre><code>In [934]: x=np.ma.array(np.arange(6).reshape((2,3)), mask = [[True,True,False],[False,False,True]])
In [935]: x
Out[935]:
masked_array... | 1 | 2016-08-09T16:57:39Z | [
"python",
"numpy",
"masked-array"
] |
TypeError: Can't convert 'NoneType' object to str implicitly Error while running python script | 38,855,106 | <p>When trying to run a python script for website scanning the error TypeError: Can't convert 'NoneType' object to str implicitly keeps occuring the python code is </p>
<p>main.py</p>
<pre><code>from general import *
from domain_name import *
from ip_address import *
from robots_txt import *
from whois import *
from ... | -2 | 2016-08-09T15:42:22Z | 38,856,755 | <p>Python is telling you that it can't take an object of type <code>NoneType</code> and make it into a string for concatenation. Some where in your code your assigning either the <code>options</code> variable or the <code>ip</code> variable to None. Like Lost said above, print out <code>ip</code> and <code>options</cod... | 0 | 2016-08-09T17:10:47Z | [
"python"
] |
How to cleanly ask user for input and allow several types? | 38,855,160 | <p>So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the num... | 1 | 2016-08-09T15:44:13Z | 38,855,298 | <p>Just downcase it.</p>
<pre><code>number = str(input("Enter number, or q to quit. \n"))
number = number.lower()
</code></pre>
<p>That will make the q lower case so it doesn't matter if they press it with shift if they press something else just make a if statement that sets a while loop true.</p>
| 1 | 2016-08-09T15:50:08Z | [
"python",
"python-3.x",
"coding-style",
"code-cleanup"
] |
How to cleanly ask user for input and allow several types? | 38,855,160 | <p>So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the num... | 1 | 2016-08-09T15:44:13Z | 38,855,416 | <p>A bit simpler:</p>
<pre><code>while True:
choice = str(input("Enter number, or q to quit. \n"))
if choice.lower() == "q":
sys.exit()
elif choice.isdigit() and (0 < int(choice) <= len(list_of_names)):
name = list_of_names[int(choice)-1]
break
</code></pre>
| 1 | 2016-08-09T15:55:29Z | [
"python",
"python-3.x",
"coding-style",
"code-cleanup"
] |
Check if a row in one data frame exist in another data frame | 38,855,204 | <p>I have a data frame A like this:</p>
<p><a href="http://i.stack.imgur.com/uu12A.png" rel="nofollow"><img src="http://i.stack.imgur.com/uu12A.png" alt="enter image description here"></a></p>
<p>And another data frame B which looks like this:</p>
<p><a href="http://i.stack.imgur.com/DI78z.png" rel="nofollow"><img s... | 0 | 2016-08-09T15:46:06Z | 38,855,394 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with parameter <code>indicator</code>, then remove column <code>Rating</code> and use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow... | 1 | 2016-08-09T15:54:13Z | [
"python",
"pandas",
"dataframe"
] |
Pandas - Parse time data with and without miliseconds | 38,855,222 | <p>How do you parse time data if the time is in the format <code>2007-08-06T18:11:44.688Z</code>, but treats no milliseconds as <code>2007-08-06T18:11:44Z</code>? </p>
<p><code>pd.to_datetime(x.split('Z')[0], errors='coerce', format='%Y-%m-%dT%H:%M:%S.%f')</code> to remove remove the Zulu marker fails due to the <code... | 1 | 2016-08-09T15:46:59Z | 38,855,954 | <p>IIUC you can simply use <code>pd.to_datetime(df_column_or_series)</code> without specifying the <code>format</code> parameter should properly parse both your datetime formats</p>
<p>having or not having <code>Zulu</code> marker, doesn't change anything - you will have the same dtype after your string is converted t... | 1 | 2016-08-09T16:23:29Z | [
"python",
"pandas"
] |
Read .txt file and export selective data to .csv | 38,855,260 | <p>I'm looking for help, I have multipath output from centos server in a .txt file, which looks like this.</p>
<pre class="lang-none prettyprint-override"><code>asm (393040300403de) dm-12 HITACHI
size=35G queue_if_no_path
|- 1:0:0:18 sda 65:48 active ready running
`- 3:0:0:18 sdbc 70:368 active ready running... | 0 | 2016-08-09T15:48:32Z | 38,855,832 | <p>Assuming that you only have the two types of entry as described in your above sample, you can define each line as a factor of the number of elements within it that will be seperated by <code>line.split()</code>. For example:</p>
<pre><code>disk_name = ""
... # other parameters you need to keep track of across lines... | 0 | 2016-08-09T16:17:18Z | [
"python"
] |
Django urls and file structure for templates | 38,855,496 | <p>I'm using Django 1.9.8 and started learning by following <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/" rel="nofollow">the official tutorial</a>. The official tutorial emphasised reusabilitiy and "plugability". From there I followed <a href="http://blog.narenarya.in/right-way-django-authenticatio... | 0 | 2016-08-09T15:59:26Z | 38,859,073 | <p>In your <code>settings.py</code> you need to add the <code>loaders</code> key in <code>OPTIONS</code> section. This specifies how django finds your <code>template files</code>. If you weren't specifying the <code>OPTIONS</code> key, the <code>APP_DIRS</code> settings should have been enough.</p>
<pre><code>TEMPLATE... | 1 | 2016-08-09T19:36:18Z | [
"python",
"django",
"templates",
"django-urls"
] |
Update Database Using AJAX in Django | 38,855,543 | <p>So I have an AJAX command, which passes information to a views.py method (I have verified that the passing works from the HTML->urls.py->views.py, so that's all good), but once I have it in "views.py", I have no idea how to get it to update in the database itself.</p>
<p>I have tried to avoid using a forms.py file ... | 0 | 2016-08-09T16:01:46Z | 38,856,036 | <pre><code>def update_act(request,furtherData_id):
from django.http import JsonResponse
if request.method == 'POST':
obj=MyObj.objects.get(pk=furtherData_id)
obj.data=request.POST['furtherData']
obj.save()
return JsonResponse({'result':'ok'})
else:
return JsonRespons... | 4 | 2016-08-09T16:27:55Z | [
"python",
"ajax",
"django",
"django-models",
"django-views"
] |
Update Database Using AJAX in Django | 38,855,543 | <p>So I have an AJAX command, which passes information to a views.py method (I have verified that the passing works from the HTML->urls.py->views.py, so that's all good), but once I have it in "views.py", I have no idea how to get it to update in the database itself.</p>
<p>I have tried to avoid using a forms.py file ... | 0 | 2016-08-09T16:01:46Z | 38,856,658 | <p>Your view function:<br></p>
<pre><code>def my_view_action(request, any_pk_id):
from django.http import JsonResponse
if request.method=='POST' and request.is_ajax():
try:
obj = MyModel.objects.get(pk=any_pk_id)
obj.data_attr = request.POST['attr_name']
obj.save()
... | 1 | 2016-08-09T17:05:18Z | [
"python",
"ajax",
"django",
"django-models",
"django-views"
] |
python csv module issues with embedded JSON strings (Python + Oracle + CSV + JSON) | 38,855,599 | <p>I am importing a small amount of baseline data into tables immediately after creating them. Only one table is giving me trouble, and this is because one of the fields is JSON.</p>
<p>I have not found a syntax engine capable of properly interpreting escapped quotes and commas within the JSON. I have not tried them... | 0 | 2016-08-09T16:04:27Z | 38,856,485 | <p>Line 69-70 (from <a href="https://docs.python.org/3.5/library/csv.html#dialects-and-formatting-parameters" rel="nofollow">https://docs.python.org/3.5/library/csv.html#dialects-and-formatting-parameters</a> ) Dialects. Escapechar is set to None by default.</p>
<p>Modified to backslash</p>
<pre><code>csvreader = cs... | 0 | 2016-08-09T16:53:47Z | [
"python",
"json",
"python-3.x",
"csv",
"parsing"
] |
Unable to convert strptime properly | 38,855,625 | <p>I was trying to take a string such as '2016-07-30T20:00:00' and convert it via </p>
<pre><code>(string, '%Y-%d-%mT%H:%M:%S')
</code></pre>
<p>but I keep getting the error...</p>
<pre><code>time data '2016-07-30T20:00:00' does not match format '%Y-%d-%mT%H:%M:%S'
</code></pre>
<p>when I had a string such as '2016... | 0 | 2016-08-09T16:05:43Z | 38,855,683 | <p>Clearly, you swapped between the month and the days, use:</p>
<pre><code>(string, '%Y-%m-%dT%H:%M:%S')
# --^--^--
</code></pre>
| 2 | 2016-08-09T16:09:20Z | [
"python",
"django"
] |
UnicodeDecodeError Loading with sqlalchemy | 38,855,631 | <p>I am querying a MySQL database with sqlalchemy and getting the following error:</p>
<pre><code>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 498-499: unexpected end of data
</code></pre>
<p>A column in the table was defined as <code>Unicode(500)</code> so this error suggests to me that there is a... | 7 | 2016-08-09T16:06:11Z | 38,910,412 | <p>Make the column you are storing into a <code>BLOB</code>. After loading the data, do various things such as </p>
<pre><code> SELECT MAX(LENGTH(col)) FROM ... -- to see what the longest is in _bytes_.
</code></pre>
<p>Copy the data into another <code>BLOB</code> column and do</p>
<pre><code> ALTER TABLE t MODIFY ... | 0 | 2016-08-12T05:17:05Z | [
"python",
"mysql",
"unicode",
"utf-8",
"sqlalchemy"
] |
UnicodeDecodeError Loading with sqlalchemy | 38,855,631 | <p>I am querying a MySQL database with sqlalchemy and getting the following error:</p>
<pre><code>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 498-499: unexpected end of data
</code></pre>
<p>A column in the table was defined as <code>Unicode(500)</code> so this error suggests to me that there is a... | 7 | 2016-08-09T16:06:11Z | 38,979,387 | <p>In short, you should change:</p>
<pre><code>Unicode(500)
</code></pre>
<p>to:</p>
<pre><code>Unicode(500, unicode_errors='ignore', convert_unicode='force')
</code></pre>
<p>(Python 2 code follows, but the principles hold in python 3; only some of the output will differ.)</p>
<p>What's going on is that when you ... | 2 | 2016-08-16T15:54:07Z | [
"python",
"mysql",
"unicode",
"utf-8",
"sqlalchemy"
] |
UnicodeDecodeError Loading with sqlalchemy | 38,855,631 | <p>I am querying a MySQL database with sqlalchemy and getting the following error:</p>
<pre><code>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 498-499: unexpected end of data
</code></pre>
<p>A column in the table was defined as <code>Unicode(500)</code> so this error suggests to me that there is a... | 7 | 2016-08-09T16:06:11Z | 39,161,038 | <p>In short, your MySQL setup is incorrect in that it truncates UTF-8 characters in mid-sequence. I would check twice that MySQL actually expects the character encoding of UTF-8 within the sessions and in the tables themselves.</p>
<hr>
<p>I would suggest switching to PostgreSQL (seriously) to avoid this kind of prob... | 0 | 2016-08-26T07:46:55Z | [
"python",
"mysql",
"unicode",
"utf-8",
"sqlalchemy"
] |
Writing API Results to CSV in Python | 38,855,641 | <p>I am looking for some assistance with writing API results to a .CSV file using Python. At this point, I'm successfully writing to .CSV, but I cannot seem to nail down the code behind the .CSV format I'm looking for, which is the standard one field = one column format.</p>
<p>Any help is appreciated! Details are bel... | 1 | 2016-08-09T16:06:36Z | 38,856,010 | <pre><code>csvFile = open('C:\_Python\\CompletionReportOutput.csv', 'w')
writer = csv.writer(csvFile, delimiter = ' ')
for row in data.split('\n'):
writer.writerow(row)
</code></pre>
| 1 | 2016-08-09T16:26:04Z | [
"python",
"python-2.7",
"python-3.x",
"csv",
"export-to-csv"
] |
Writing API Results to CSV in Python | 38,855,641 | <p>I am looking for some assistance with writing API results to a .CSV file using Python. At this point, I'm successfully writing to .CSV, but I cannot seem to nail down the code behind the .CSV format I'm looking for, which is the standard one field = one column format.</p>
<p>Any help is appreciated! Details are bel... | 1 | 2016-08-09T16:06:36Z | 38,861,353 | <p>So, I eventually stumbled onto a solution. Not sure if this is the "correct" way of handling this, but the code below wrote the API results directly into a .CSV with the correct column formatting.</p>
<pre><code># Get JSON Data
rcomp = requests.get(urlcomp, headers=headers)
# Write to .CSV
f = open('C:\_Python\Two... | 0 | 2016-08-09T22:20:58Z | [
"python",
"python-2.7",
"python-3.x",
"csv",
"export-to-csv"
] |
Python - Split a row into columns - csv data | 38,855,648 | <p>Am trying to read data from csv file, split each row into respective columns. </p>
<p>But my regex is failing when a particular column has <strong>commas with in itself</strong>. </p>
<p>eg: a,b,c,"d,e, g,",f </p>
<p>I want result like: </p>
<pre><code>a b c "d,e, g," f
</code></pre>
<p>which... | 2 | 2016-08-09T16:06:55Z | 38,855,714 | <p>Much easier with the help of the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong><code>regex</code></strong></a> module:</p>
<pre><code>import regex as re
string = 'a,b,c,"d,e, g,",f'
rx = re.compile(r'"[^"]*"(*SKIP)(*FAIL)|,')
parts = rx.split(string)
print(parts)
# ['a', 'b', 'c', '"d,... | 3 | 2016-08-09T16:10:38Z | [
"python",
"regex",
"csv",
"pyspark",
"rdd"
] |
Python - Split a row into columns - csv data | 38,855,648 | <p>Am trying to read data from csv file, split each row into respective columns. </p>
<p>But my regex is failing when a particular column has <strong>commas with in itself</strong>. </p>
<p>eg: a,b,c,"d,e, g,",f </p>
<p>I want result like: </p>
<pre><code>a b c "d,e, g," f
</code></pre>
<p>which... | 2 | 2016-08-09T16:06:55Z | 38,855,739 | <p>Try <code>\,(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)</code>.</p>
<p>Used <a href="https://www.stackoverflow.com/questions/6462578/alternative-to-regex-match-all-instances-not-inside-quotes#6464500">this answer which explains how to match everything that is not in quotes ignoring escaped quotes</a> and <a hr... | 2 | 2016-08-09T16:11:44Z | [
"python",
"regex",
"csv",
"pyspark",
"rdd"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.