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
Learning Python; don't know why my function works improperly
37,848,445
<p>I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to fi...
0
2016-06-16T01:29:13Z
37,848,596
<p>If you try it with a string containing consecutive <code>a</code> characters (or any vowel), you'll see why.</p> <p>The actual <code>remove</code> call modifies the list so the iterator over that list will no longer be correct.</p> <p>There are many ways you can fix that but perhaps the best is to not use that met...
0
2016-06-16T01:48:42Z
[ "python" ]
Learning Python; don't know why my function works improperly
37,848,445
<p>I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to fi...
0
2016-06-16T01:29:13Z
37,848,630
<p>not sure how exactly your function is supposed to work as there are quite a few errors with it. I will walk you through a solution I would come up with.</p> <pre><code>def anti_vowel(text): final = '' for letter in text: for vowel in 'aeiouAEIOU': if (letter == vowel): ...
0
2016-06-16T01:53:47Z
[ "python" ]
Learning Python; don't know why my function works improperly
37,848,445
<p>I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to fi...
0
2016-06-16T01:29:13Z
37,848,664
<p>Adding on to what the rest has already said, that you should not modify the iterable when looping through it, here is my shorter version of the whole code:</p> <pre><code>def anti_vowel(text): return text.translate(None, "aeiouAEIOU") </code></pre> <p>Python already has a "built-in text remover", you can read ...
0
2016-06-16T01:57:17Z
[ "python" ]
get unique count ~and~ unique values on per row basis using numpy
37,848,468
<p>I'm trying to get the equivalent of np.unique, but with an 'axis=1' option.</p> <pre><code>a = np.array([[8, 8, 8, 5, 8], [8, 2, 0, 8, 8], [4, 5, 4, 2, 4], [4, 6, 5, 2, 6]]) </code></pre> <p>I'm looking to get the value with the highest count in each row and save it to a 1D vector. Basically "...
1
2016-06-16T01:32:27Z
37,848,640
<p>One option is to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html" rel="nofollow"><code>scipy.stats.mode</code></a>:</p> <pre><code>In [36]: from scipy.stats import mode In [37]: a Out[37]: array([[8, 8, 8, 5, 8], [8, 2, 0, 8, 8], [4, 5, 4, 2, 4], [4, 6, ...
1
2016-06-16T01:54:52Z
[ "python", "numpy" ]
get unique count ~and~ unique values on per row basis using numpy
37,848,468
<p>I'm trying to get the equivalent of np.unique, but with an 'axis=1' option.</p> <pre><code>a = np.array([[8, 8, 8, 5, 8], [8, 2, 0, 8, 8], [4, 5, 4, 2, 4], [4, 6, 5, 2, 6]]) </code></pre> <p>I'm looking to get the value with the highest count in each row and save it to a 1D vector. Basically "...
1
2016-06-16T01:32:27Z
37,850,555
<p>A fully vectorized solution can be implemented using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author):</p> <pre><code>import numpy_indexed as npi r = np.indices(a.shape)[0] (ua, ur), c = npi.unique((a.flatten(), r.flatten()...
1
2016-06-16T05:30:38Z
[ "python", "numpy" ]
How to configure CELERYBEAT_SCHEDULE in Django settings?
37,848,481
<p>I can get this to run as a standalone application, but I am having trouble getting it to work in Django.</p> <h2>Here is the stand alone code:</h2> <pre><code> `from celery import Celery from celery.schedules import crontab app = Celery('tasks') app.conf.update( CELERY_TASK_SERIALIZER='json...
1
2016-06-16T01:34:07Z
37,851,090
<p>Why don't you try like the following and let me know if it worked out for you or not. It does work for me.</p> <p>In settings.py</p> <pre><code>CELERYBEAT_SCHEDULE = { 'my_scheduled_job': { 'task': 'run_scheduled_jobs', # the same goes in the task name 'schedule': crontab(), }, } </code></p...
2
2016-06-16T06:04:33Z
[ "python", "django", "celery", "periodic-task" ]
performance of get the length of a string in Python 2.7
37,848,483
<p>When calling <code>len("1234567890")</code>, the performance is constant i.e. O(1), or linear to the length of the string, i.e. O(n) according to the length of the string (in this example, the length of the string is n=10)? If constant performance, why? And if linear performance, any ideas how to improve performance...
0
2016-06-16T01:34:30Z
37,848,517
<p>Check it:</p> <pre><code>C:\&gt;py -m timeit -s "x='a'*1000" "len(x)" 10000000 loops, best of 3: 0.0959 usec per loop C:\&gt;py -m timeit -s "x='a'*10000" "len(x)" 10000000 loops, best of 3: 0.0902 usec per loop C:\&gt;py -m timeit -s "x='a'*100000" "len(x)" 10000000 loops, best of 3: 0.0927 usec per loop </code>...
1
2016-06-16T01:38:47Z
[ "python", "python-2.7" ]
Run TCL code alongside Python script
37,848,527
<p>In <a href="https://stackoverflow.com/questions/37799692/python-pause-while-true-loop-until-condition-fulfilled">this</a> question, I asked about a game I was making with Python. I have finished the code, without any graphics, but now I want to add those graphics.</p> <p>I am planning to do it with a determinate pr...
-1
2016-06-16T01:40:03Z
37,980,958
<p>A reference can be found here <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Progressbar.html" rel="nofollow">http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Progressbar.html</a></p> <p>You probably want .start and .step</p>
-1
2016-06-23T01:43:39Z
[ "python", "python-3.x", "tkinter", "tcl", "tk" ]
How to change axis range displayed in a histogram
37,848,627
<p>I want to plot a histogram of my df with about 60 thousand of values. After I used <code>plt.hist(x, bins = 30)</code> it gave me something like <a href="http://i.stack.imgur.com/GjSXp.png" rel="nofollow"><img src="http://i.stack.imgur.com/GjSXp.png" alt="enter image description here"></a></p> <p>The problem...
0
2016-06-16T01:53:22Z
37,848,707
<p>You could use <code>plt.xscale('log')</code></p> <p><a href="http://matplotlib.org/1.5.0/users/pyplot_tutorial.html#logarithmic-and-other-nonlinear-axis" rel="nofollow">PyPlot Logarithmic and other nonlinear axis</a></p>
0
2016-06-16T02:02:26Z
[ "python", "matplotlib" ]
How to change axis range displayed in a histogram
37,848,627
<p>I want to plot a histogram of my df with about 60 thousand of values. After I used <code>plt.hist(x, bins = 30)</code> it gave me something like <a href="http://i.stack.imgur.com/GjSXp.png" rel="nofollow"><img src="http://i.stack.imgur.com/GjSXp.png" alt="enter image description here"></a></p> <p>The problem...
0
2016-06-16T01:53:22Z
37,848,718
<p>The problem with histograms that skew so much towards one value is you're going to essentially flatten out any outlying values. A solution might be just to present the data with two charts.</p> <p>Can you create another histogram containing only the values greater than 20?</p> <p>(psuedo-code, since I don't know y...
0
2016-06-16T02:04:24Z
[ "python", "matplotlib" ]
How to change axis range displayed in a histogram
37,848,627
<p>I want to plot a histogram of my df with about 60 thousand of values. After I used <code>plt.hist(x, bins = 30)</code> it gave me something like <a href="http://i.stack.imgur.com/GjSXp.png" rel="nofollow"><img src="http://i.stack.imgur.com/GjSXp.png" alt="enter image description here"></a></p> <p>The problem...
0
2016-06-16T01:53:22Z
37,852,475
<p>Finally, it could look like this example:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np values1 = np.random.rand(1000,1)*100 values2 = np.random.rand(100000,1)*5 values3 = np.random.rand(10000,1)*20 values = np.vstack((values1,values2,values3)) fig = plt.figure(figsize=(12,5)) ax1 = fig.add_s...
0
2016-06-16T07:23:28Z
[ "python", "matplotlib" ]
using python datetime type in BOLT neo4j-driver throws an error. workaround available?
37,848,646
<p>Here is a simplified example of code that I want to run under BOLT and that I was able to execute uner py2neo</p> <pre><code>timeCreated = datetime.datetime(year=2016, month=6, day=15, hour=23) driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "password")) session = driver.session() stmt = ...
0
2016-06-16T01:55:11Z
37,848,739
<p>Node4j has no concept of dates or times as properties of objects; so I doubt there will be support for <code>datetime</code> type. You should store the epoch value instead:</p> <pre><code>import calendar import time epoch = calendar.timegm(time.gmtime()) </code></pre>
0
2016-06-16T02:06:05Z
[ "python", "neo4j", "py2neo" ]
using python datetime type in BOLT neo4j-driver throws an error. workaround available?
37,848,646
<p>Here is a simplified example of code that I want to run under BOLT and that I was able to execute uner py2neo</p> <pre><code>timeCreated = datetime.datetime(year=2016, month=6, day=15, hour=23) driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "password")) session = driver.session() stmt = ...
0
2016-06-16T01:55:11Z
37,848,764
<p>Neo4j doesn't natively support datetimes, and I believe py2neo silently converted datetimes into strings in previous versions. </p> <p>My workaround has been to call the <code>.isoformat()</code> method on <code>datetime</code> objects to insert them into databases as strings. </p>
2
2016-06-16T02:09:23Z
[ "python", "neo4j", "py2neo" ]
Writing a list into a text file
37,848,713
<p>Using windows 10</p> <p>Here's a sample of my code, where the problem is:</p> <pre><code>if choice2 == "d": amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " % intBalance)) newBalance = intBalance + amount print "Current balance: %i" %newBalance f.close() ...
0
2016-06-16T02:03:50Z
37,849,602
<p>Not a direct answer to your question, but some pointers which may end up making it much easier for both yourself and others to debug your code.</p> <p>1) Functions are your friend. See if you can take small tasks and break them up into functions. For example, writing out someone's balance to a file could be a small...
0
2016-06-16T03:51:32Z
[ "python", "list", "file" ]
Writing a list into a text file
37,848,713
<p>Using windows 10</p> <p>Here's a sample of my code, where the problem is:</p> <pre><code>if choice2 == "d": amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " % intBalance)) newBalance = intBalance + amount print "Current balance: %i" %newBalance f.close() ...
0
2016-06-16T02:03:50Z
37,883,557
<p>For a minimal change that will solve the issue, this is the code that needs to change:</p> <pre><code>for i, line in enumerate(fileVar): if account in line: for j in fileVar[i:i+3]: print j accessedAccount.append(j) </code></pre> <p>This records which entries are part of the <co...
0
2016-06-17T13:59:39Z
[ "python", "list", "file" ]
Zipping a folder with os.walk
37,848,788
<p>I'm trying to zip a folder and every contained subfolder and file using <code>os.walk()</code>, but I am having trouble removing the folder path to the root folder - meaning I would like to remove <code>D:\\Users\\Username\\Desktop</code> when opening up the zipfile, but instead open straight to the root folder. </p...
2
2016-06-16T02:13:12Z
37,849,661
<ol> <li>Use <code>os.chdir</code> to change your current path</li> <li>Make sure that the parameter of <code>os.walk</code> is relative path</li> </ol> <p>*Should be careful when using <code>os.chdir</code></p> <hr> <pre><code>import zipfile, os def backupToZip(folder): cwdpath = os.getcwd() # save original p...
1
2016-06-16T03:58:22Z
[ "python", "zipfile" ]
Zipping a folder with os.walk
37,848,788
<p>I'm trying to zip a folder and every contained subfolder and file using <code>os.walk()</code>, but I am having trouble removing the folder path to the root folder - meaning I would like to remove <code>D:\\Users\\Username\\Desktop</code> when opening up the zipfile, but instead open straight to the root folder. </p...
2
2016-06-16T02:13:12Z
37,850,348
<p>If you want to avoid chdir, which impacts the whole process, you can use <a href="https://docs.python.org/3/library/os.path.html#os.path.relpath" rel="nofollow">relpath</a> to get the relative path starting from your top folder.</p> <p>You could use something like</p> <pre><code>def backupToZip(folder): impor...
1
2016-06-16T05:13:14Z
[ "python", "zipfile" ]
Zipping a folder with os.walk
37,848,788
<p>I'm trying to zip a folder and every contained subfolder and file using <code>os.walk()</code>, but I am having trouble removing the folder path to the root folder - meaning I would like to remove <code>D:\\Users\\Username\\Desktop</code> when opening up the zipfile, but instead open straight to the root folder. </p...
2
2016-06-16T02:13:12Z
37,875,496
<p>Made some revisions based on user2313067's answer above and finally got what I wanted in case anyone was curious:</p> <pre><code>import zipfile, os def backupToZip(folder): # Make sure folder is absolute. folder = os.path.abspath(folder) backupZip = zipfile.ZipFile('backup.zip', 'w') backupZip....
1
2016-06-17T07:22:57Z
[ "python", "zipfile" ]
Export all the tables in the database into a single csv file in python
37,848,808
<p>I'm been trying to export <strong>all</strong> the tables in my database into a single csv file. </p> <h1>I've tried</h1> <pre><code>import MySQLdb as dbapi import sys import csv import time dbname = 'benu-local' user = 'root' host = '127.0.0.1' password = '' date = time.strftime("%d...
0
2016-06-16T02:16:15Z
37,865,317
<p>Using python isn't the way to go about this. The simplest solution is to use <a href="http://dev.mysql.com/doc/refman/5.7/en/select-into.html" rel="nofollow">SELECT INTO OUTFILE</a>. That can dump even very large tables into CSV format speedily and without the need to bother with CSV writers in your python code.</p>...
1
2016-06-16T17:03:05Z
[ "python", "mysql", "csv" ]
Export all the tables in the database into a single csv file in python
37,848,808
<p>I'm been trying to export <strong>all</strong> the tables in my database into a single csv file. </p> <h1>I've tried</h1> <pre><code>import MySQLdb as dbapi import sys import csv import time dbname = 'benu-local' user = 'root' host = '127.0.0.1' password = '' date = time.strftime("%d...
0
2016-06-16T02:16:15Z
37,868,150
<p>Consider iteratively exporting the <code>SHOW CREATE TABLE</code> (txt files) and <code>SELECT * FROM</code> (csv files) output from all database tables. From your related earlier questions, since you need to migrate databases, you can then run the create table statements (adjusting the MySQL for Postgre syntax such...
1
2016-06-16T19:45:46Z
[ "python", "mysql", "csv" ]
Django FormView - Input Field not saving into DB
37,848,846
<p>So, I am trying to use the input fields to add info into them and then save it. As of right now, I am not receiving any errors when I try and submit the form, but its also not creating objects either. Can anyone see the error? Would appreciate some help.</p> <p>Here is my <code>client_setup.py</code> form:</p> <pr...
0
2016-06-16T02:21:10Z
37,849,247
<p>There are several problems with your code: </p> <ul> <li><p>The <code>clean_&lt;fieldname&gt;</code> methods must return a value - yours just <code>pass</code>.</p></li> <li><p>You should not be calling those methods manually in your view anyway. These are called <a href="https://docs.djangoproject.com/en/1.9/ref/f...
3
2016-06-16T03:10:16Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
Dictionary generated from 2 lists not doing what I want
37,848,859
<p>My problem is this, when given any input (correctly formatted) the dictionary <code>dancer_placings</code> is not correctly generated based on my code. An input of 1 dancer, with number 1, 2 dances, named foo and bar, the dictionary <code>dancer_placings</code> is <code>{'1': {'bar': 0}}</code>, when I want it to be...
0
2016-06-16T02:22:54Z
37,848,989
<p>I think the issue is that you are overwriting the values for dancer_placings for each dance. A minor adjustment should return the results that you are seeking:</p> <pre><code>for dancer in dancers: dancer_placings.update({dancer: {}}) for dance in dances: dancer_placings[dancer].update({dance: 0}) </code><...
0
2016-06-16T02:39:05Z
[ "python", "dictionary", "user-input" ]
Dictionary generated from 2 lists not doing what I want
37,848,859
<p>My problem is this, when given any input (correctly formatted) the dictionary <code>dancer_placings</code> is not correctly generated based on my code. An input of 1 dancer, with number 1, 2 dances, named foo and bar, the dictionary <code>dancer_placings</code> is <code>{'1': {'bar': 0}}</code>, when I want it to be...
0
2016-06-16T02:22:54Z
37,848,991
<p>Your code has a few problems, but I'll just address the ones to make your use case work: </p> <ol> <li>You're overwriting the dancerplacings every time:<br> dancer_placings.update({dancer:{}})</li> </ol> <p>That's not necessary. That should be up an indentation level.</p> <ol start="2"> <li>You are currently crea...
0
2016-06-16T02:39:19Z
[ "python", "dictionary", "user-input" ]
Dictionary generated from 2 lists not doing what I want
37,848,859
<p>My problem is this, when given any input (correctly formatted) the dictionary <code>dancer_placings</code> is not correctly generated based on my code. An input of 1 dancer, with number 1, 2 dances, named foo and bar, the dictionary <code>dancer_placings</code> is <code>{'1': {'bar': 0}}</code>, when I want it to be...
0
2016-06-16T02:22:54Z
37,849,057
<p>The bit of code in question here is this:</p> <pre><code>for dancer in dancers: for dance in dances: dancer_placings.update({dancer:{}}) dancer_placings[dancer].update({dance:0}) </code></pre> <p>As it is written now, each iteration through dancers will have a loop through each dance. However, ...
0
2016-06-16T02:45:33Z
[ "python", "dictionary", "user-input" ]
Python's os.system command and redirection
37,848,864
<p>I am trying to experiment with redirection in a BASH shell, though this make work in a Windows Command Prompt shell too, with Python's <code>os.system</code> function. My problem is I was trying to redirect output from a Python script to a text file and the Python script would not do that for whatever strange syntac...
0
2016-06-16T02:23:43Z
37,849,304
<p>The output from your Python print statement is getting buffered, and written to the file when the script is finished (or when the buffer is full, in the case of a larger amount of printed text), whereas the output from the external call is getting written immediately. This occurs when the output is getting piped to ...
1
2016-06-16T03:16:53Z
[ "python", "bash", "shell", "redirect" ]
from list of tuples to array with the 2nd row become the header
37,848,882
<p>from list of tuples to array with the 2nd row become the header to print it to a csv file.</p> <p>This is my data set for buss trips between cities original list</p> <pre><code>L= [ ("Seattle WA US","Seattle WA US","56"), ("Seattle WA US","North Bend WA US","1"), ("Seattle WA US","Candelaria 137 PR","2"), ("Seatt...
1
2016-06-16T02:25:13Z
37,848,960
<pre><code>import pandas as pd L= [ ("Seattle WA US","Seattle WA US","56"), ("Seattle WA US","North Bend WA US","1"), ("Seattle WA US","Candelaria 137 PR","2"), ("Seattle WA US","La Cienega NM US","2"), ("Seattle WA US","Thousand Palms CA US","1"), ("Oakhurst CA US","Thousand Palms CA US","2") ] df = pd.DataFrame(L,...
5
2016-06-16T02:34:52Z
[ "python", "arrays", "list", "csv", "matrix" ]
How to treat str variable as Unicode after initialization for the OS module in Python 2?
37,848,944
<p>For example you can specify a Unicode string explicitly during initialization by adding an <code>u</code> in front of the string as shown below:</p> <pre><code>path1 = u'./테스트' # printing type of path1 returns &lt;type 'unicode'&gt; </code></pre> <p>On the other hand, if you were to initialize it as a normal...
0
2016-06-16T02:33:27Z
37,848,988
<p><code>'unicode-escape'</code> doesn't do anything useful unless your string contains Unicode escapes. For normal text encoded with a charset decode with that charset instead.</p> <pre><code>&gt;&gt;&gt; './테스트'.decode('utf8') u'./\ud14c\uc2a4\ud2b8' &gt;&gt;&gt; print './테스트'.decode('utf8') ./테스트 ...
1
2016-06-16T02:38:51Z
[ "python", "unicode" ]
Optimize nested loop over a fixed object with itertools.product
37,849,058
<p>I have a fixed object, like so:</p> <pre><code>TAG_SET = [...] </code></pre> <p>I iterate over it twice in a loop</p> <pre><code>for x in very_outer_object: # ... for t1, t2 in itertools.product(TAG_SET, repeat=2) </code></pre> <p>Is it possible to create one product that is reused? The result of <code>i...
0
2016-06-16T02:45:34Z
37,849,110
<p>Calling <code>list</code> on the generator object forces it to evaluate all its items:</p> <pre><code>products = list(itertools.product(TAG_SET, repeat=2)) for x in very_outer_object: # ... for t1, t2 in products: # ... </code></pre> <p><code>products</code> can now be reused in your inner loop.</p> ...
0
2016-06-16T02:51:19Z
[ "python", "nested-loops", "itertools" ]
Why is Python's json.dumps refusing to serialise strings from my objects?
37,849,071
<p>My objects are not being serialised correctly from my Django site when using Python's <code>json.dumps()</code>. I've got a class which is designed to make the injection of data into <a href="http://www.chartjs.org/" rel="nofollow">Chart.js</a> components:</p> <pre><code>class ChartData: def __init__(self): ...
1
2016-06-16T02:47:10Z
37,849,166
<p>The second version of get converted data works because it is a dict and your template wants chartdata dot data and chart data dot background colours. The template is accessing the dict to get those values, which is why when you use a dict with json encoded values it works. The first version json encodes the whole di...
0
2016-06-16T02:59:21Z
[ "python", "json", "django", "string", "serialization" ]
Transform sequences of values in a column to rows for a timeseries of events in Pandas
37,849,073
<p>I am working with a timeseries with certain events that occur with a given order: <code>A-&gt;B-&gt;C-&gt;D</code> and I want to create a new <code>DataFrame</code> having as columns the time of these events, namely from the <code>DataFrame</code> <code>old_df</code>:</p> <pre><code> ev_type ev_time 1 ...
1
2016-06-16T02:47:24Z
37,849,346
<p>After clarifying the question, you could:</p> <p>Sample data:</p> <pre><code>size = 10000 df = pd.DataFrame(data={'ev_type': np.random.choice(list("ABCDWK"), size=size, replace=True), 'ev_time': pd.date_range(start=pd.datetime(2016, 1, 1), freq='Min', periods=size)}) seq = 'ABCD' df['sequ...
1
2016-06-16T03:20:24Z
[ "python", "pandas", "time-series" ]
Transform sequences of values in a column to rows for a timeseries of events in Pandas
37,849,073
<p>I am working with a timeseries with certain events that occur with a given order: <code>A-&gt;B-&gt;C-&gt;D</code> and I want to create a new <code>DataFrame</code> having as columns the time of these events, namely from the <code>DataFrame</code> <code>old_df</code>:</p> <pre><code> ev_type ev_time 1 ...
1
2016-06-16T02:47:24Z
37,879,877
<p>For whoever visits this question looking for a similar issue, here I report how I did solve it. I am not sure it is the most pythonic/memory efficient way to look for event sequences...</p> <p>To generate the data I used the code suggested by Stefan</p> <pre><code>size_of_df = 10000 df_old = pd.DataFrame(data={'ev...
0
2016-06-17T10:58:39Z
[ "python", "pandas", "time-series" ]
tornado one handler blocks for another
37,849,128
<p>Using python/tornado I wanted to set up a little "trampoline" server that allows two devices to communicate with each other in a RESTish manner. There's probably vastly superior/simpler "off the shelf" ways to do this. I'd welcome those suggestions, but I still feel it would be educational to figure out how to do my...
0
2016-06-16T02:53:28Z
37,851,730
<blockquote> <p>1) How can one HTTP verb invocation (e.g. get, put, post,u ne etc) block and then be signaled by another HTTP verb invocation.</p> <p>2) How can I share data from one invocation to another?</p> </blockquote> <p>The new <code>RequestHandler</code> object is created for every request. So you need ...
2
2016-06-16T06:46:07Z
[ "python", "tornado" ]
Compute Pairwise Cosine Similarity using scikit-learn
37,849,151
<p>I am new to this, so it would be helpful if someone could point me in right direction/help me with some tutorial. Given a sentence and a list of other sentences (English):</p> <pre><code>s = "This concept of distance is not restricted to two dimensions." list_s = ["It is not difficult to imagine the figure above tr...
-2
2016-06-16T02:56:28Z
37,850,182
<p>First, you might want to transform your documents as follows </p> <pre><code>X = tfidf.fit_transform([s] + list_s) # now X will have 3 rows </code></pre> <ol> <li><p>What's next?: you have to find cosine similarity between each row of tf-idf matrix. See this <a href="http://stackoverflow.com/questions/17627219/wha...
1
2016-06-16T04:58:06Z
[ "python", "machine-learning", "nlp", "scikit-learn" ]
Why is Django returning stale cache data?
37,849,236
<p>I have two Django models as shown below, <code>MyModel1</code> &amp; <code>MyModel2</code>:</p> <pre><code>class MyModel1(CachingMixin, MPTTModel): name = models.CharField(null=False, blank=False, max_length=255) objects = CachingManager() def __str__(self): return "; ".join(["ID: %s" % self.pk...
9
2016-06-16T03:08:58Z
37,851,540
<p>This was my workaround solution:</p> <pre><code> &gt;&gt;&gt; m1 = MyModel1.objects.all()[0] &gt;&gt;&gt; m1 &lt;MyModel1: ID: 8887972990743179; name: my-name-blahblah&gt; &gt;&gt;&gt; m2 = MyModel2.objects.all()[0] &gt;&gt;&gt; m2.model1.all() [] &gt;&gt;&gt; m2.model1.add(m1) &gt;&...
1
2016-06-16T06:35:02Z
[ "python", "django", "django-cache", "django-cache-machine" ]
Why is Django returning stale cache data?
37,849,236
<p>I have two Django models as shown below, <code>MyModel1</code> &amp; <code>MyModel2</code>:</p> <pre><code>class MyModel1(CachingMixin, MPTTModel): name = models.CharField(null=False, blank=False, max_length=255) objects = CachingManager() def __str__(self): return "; ".join(["ID: %s" % self.pk...
9
2016-06-16T03:08:58Z
37,904,144
<h2>Is django-cache-machine really needed?</h2> <pre><code>MyModel1.objects.all()[0] </code></pre> <p>Roughly translates to</p> <pre><code>SELECT * FROM app_mymodel LIMIT 1 </code></pre> <p>Queries like this are always fast. There would not be a significant difference in speeds whether you fetch it from the cache o...
9
2016-06-19T05:11:48Z
[ "python", "django", "django-cache", "django-cache-machine" ]
Why is Django returning stale cache data?
37,849,236
<p>I have two Django models as shown below, <code>MyModel1</code> &amp; <code>MyModel2</code>:</p> <pre><code>class MyModel1(CachingMixin, MPTTModel): name = models.CharField(null=False, blank=False, max_length=255) objects = CachingManager() def __str__(self): return "; ".join(["ID: %s" % self.pk...
9
2016-06-16T03:08:58Z
37,933,665
<p>Have you considered hooking into the model signals to invalidate the cache when an object is added? For your case you should look at <a href="https://docs.djangoproject.com/en/1.8/ref/signals/#django.db.models.signals.m2m_changed" rel="nofollow">M2M Changed Signal</a> </p> <p>Small example that doesn't solve your ...
1
2016-06-21T00:05:49Z
[ "python", "django", "django-cache", "django-cache-machine" ]
Looking up values of one csv file in another csv file and print the row
37,849,267
<p>I have two csv files, one is a single column with a header and the other is multiple columns with headers. I want to lookup the values in the one column file and search the column with the same header in the other file. Once a match is found, I want that whole row to be printed. I know this is a vlookup function, bu...
1
2016-06-16T03:12:30Z
37,850,152
<p>There are a lot of problems with your code which shows that you are very confused.</p> <pre><code>with open('/home/s/Untitled 1.csv') as f: r = pandas.read_csv(f) with open('/home/s/Test1.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['age'] for line in w: # w is not...
1
2016-06-16T04:54:50Z
[ "python", "csv", "pandas" ]
Integer data in -> averaged -> float data out in python for large files
37,849,341
<p>I have a large amount of data from a sensor represented as integers from 0-255 in a column of length 2048, and there are at least 10000 rows in the same 2D numpy array. I wish to average all of the rows together to obtain a column of floats and plot them. Simple, right?</p> <p>When there was less than 1000 rows, my...
1
2016-06-16T03:20:00Z
37,934,524
<p>The problem was that the data that I was averaging had an error (caused by data acquisition program). Basically, more than half of the frames of data collected from the sensor were identical and repeated. This caused the output to approximate a single frame of data, rather than smooth out the large set of data that ...
1
2016-06-21T02:14:06Z
[ "python", "arrays", "numpy", "matplotlib" ]
Iterating through DataFrame using pandas for stocks
37,849,343
<p>I am relatively new to python and <code>pandas</code>. I have a <code>DataFrame</code> with a few stocks and their associated 'low' prices for the past few days. I am trying to iterate through each stock (right now I only have 3 but will eventually have thousands) and then for each stock, I want to see if the curre...
1
2016-06-16T03:20:15Z
37,849,480
<p>To identify whether the <code>Low</code> has been increasing for the last three days, you can use the following:</p> <pre><code>stockData = stockData.sort_index(ascending=False).iloc[:3] # reverse order, use last three days </code></pre> <p>either a condition that compares <code>Low</code> between adjacent days, a...
0
2016-06-16T03:37:39Z
[ "python", "pandas", "datareader" ]
Iterating through DataFrame using pandas for stocks
37,849,343
<p>I am relatively new to python and <code>pandas</code>. I have a <code>DataFrame</code> with a few stocks and their associated 'low' prices for the past few days. I am trying to iterate through each stock (right now I only have 3 but will eventually have thousands) and then for each stock, I want to see if the curre...
1
2016-06-16T03:20:15Z
37,850,020
<p>This is an example of a similar, but slightly different approach to this problem. I am using dummy values to demonstrate.</p> <p>First, I create a dataframe.</p> <pre><code>dates = pd.date_range('20130101', periods=3) IBM = [5,3,2] AMZN = [1,7,6] FB = [4,7,9] df = pd.DataFrame({'IBM': IBM,'AMZN': AMZN,'FB':FB}, in...
0
2016-06-16T04:42:10Z
[ "python", "pandas", "datareader" ]
BeautifulSoup text outside of tags
37,849,347
<p>I'm trying to grab all of Kramer's lines from every episode of Seinfled on this site:</p> <p><a href="http://www.imsdb.com/TV/Seinfeld.html" rel="nofollow">http://www.imsdb.com/TV/Seinfeld.html</a></p> <p>I've already pulled the list of episode names into a file I labeled episode-list.txt</p> <p>I'm trying now to...
0
2016-06-16T03:20:26Z
37,849,682
<p>Here's a code snippet to serve as a reference to get you started...</p> <pre><code>import re from bs4 import BeautifulSoup html = """ &lt;b&gt; KRAMER &lt;/b&gt; (enters) Are you up? &lt;b&gt; &lt;/b&gt;&lt;b&gt; JERRY &lt;/b&gt;...
1
2016-06-16T04:00:54Z
[ "python", "parsing", "beautifulsoup", "screen-scraping" ]
performance of get a specific character of a string in Python 2.7
37,849,352
<p>Suppose I want to get a specific character of a string in Python 2.7, suppose</p> <pre><code>a = 'abcdefg...' # a long string print a[5] </code></pre> <p>Wondering when access any specific character of a string, for example, access the 5th element, wondering what is the performance, is it constant time O(1), or li...
2
2016-06-16T03:21:07Z
37,849,423
<pre><code>&gt;&gt;&gt; long_string_1M ="".join(random.choice(string.printable) for _ in xrange(1000000)) &gt;&gt;&gt; short_string = "hello" &gt;&gt;&gt; timeit.timeit(lambda:long_string_1M[50000]) 0.1487280547441503 &gt;&gt;&gt; timeit.timeit(lambda:short_string[4]) 0.1368805315209798 &gt;&gt;&gt; timeit.timeit(lambd...
4
2016-06-16T03:29:32Z
[ "python", "performance", "python-2.7" ]
performance of get a specific character of a string in Python 2.7
37,849,352
<p>Suppose I want to get a specific character of a string in Python 2.7, suppose</p> <pre><code>a = 'abcdefg...' # a long string print a[5] </code></pre> <p>Wondering when access any specific character of a string, for example, access the 5th element, wondering what is the performance, is it constant time O(1), or li...
2
2016-06-16T03:21:07Z
37,849,455
<p>In addition to Joran's answer, I'd point you to <a href="https://hg.python.org/cpython/file/c6880edaf6f3/Objects/stringobject.c" rel="nofollow">this reference implementation</a>, confirming his answer that it is O(1) lookup</p> <pre class="lang-c prettyprint-override"><code>/* String slice a[i:j] consists of charac...
4
2016-06-16T03:34:18Z
[ "python", "performance", "python-2.7" ]
Django GET request params from POST request
37,849,400
<p>I have a form that you need to fill out using a POST request, but I want to the result to be a redirection to various pages on my site. Sometimes I want the user to be redirected to a profile page, sometimes to a purchase page. </p> <p>So I put the redirect URI in the GET params of the URL of the form page that POS...
1
2016-06-16T03:27:14Z
37,849,773
<p>In the POST request - i.e. when you submit the form - the url will be what you specified in the <code>'action'</code> attribute in the form. If the parameters you require are not there, your view will not get them.</p> <p>So either update your forms's <code>action</code> attribute to have these parameters or altern...
1
2016-06-16T04:12:44Z
[ "python", "django", "url", "request" ]
Django GET request params from POST request
37,849,400
<p>I have a form that you need to fill out using a POST request, but I want to the result to be a redirection to various pages on my site. Sometimes I want the user to be redirected to a profile page, sometimes to a purchase page. </p> <p>So I put the redirect URI in the GET params of the URL of the form page that POS...
1
2016-06-16T03:27:14Z
37,849,878
<p>Your form has to be modified as follows:</p> <pre><code>&lt;form action="/form/?redirect_uri={{ request.GET.redirect_url}}" method="POST" class="wizard-form" enctype="application/x-www-form-urlencoded" autocomplete="off"&gt; </code></pre> <p>Permit me to also suggest a slight optimization to your view</p> ...
1
2016-06-16T04:23:49Z
[ "python", "django", "url", "request" ]
why does getsizeof a float num return 16 in python
37,849,402
<pre><code>&gt;&gt;&gt; x=float(12.345) &gt;&gt;&gt; x 12.345 &gt;&gt;&gt; sys.getsizeof(x) 16 &gt;&gt;&gt; sys.getsizeof(12.345) 16 </code></pre> <p>Here 16 is of the unit of byte? But in the document it's of 64 bits the float</p> <p>python 3.5.1 32bits Windows 7 64 </p>
0
2016-06-16T03:27:29Z
37,849,504
<p>The memory space consumed by a python variable depends on the what version of python you have ie. 32 bit or 64 bit platform.</p> <p>Coming to float representation. A float in 32 bit python consumes 16 bytes of memory while for 64 bit it consumes 24 byte of memory. </p>
0
2016-06-16T03:39:54Z
[ "python", "python-3.x", "floating-point" ]
why does getsizeof a float num return 16 in python
37,849,402
<pre><code>&gt;&gt;&gt; x=float(12.345) &gt;&gt;&gt; x 12.345 &gt;&gt;&gt; sys.getsizeof(x) 16 &gt;&gt;&gt; sys.getsizeof(12.345) 16 </code></pre> <p>Here 16 is of the unit of byte? But in the document it's of 64 bits the float</p> <p>python 3.5.1 32bits Windows 7 64 </p>
0
2016-06-16T03:27:29Z
37,849,694
<p><code>sys.getsizeof()</code> returns the memory size of an instance of the <code>float</code> type. In addition to the 8 bytes used by the 64-bit IEEE representation of a float, additional memory is used for reference count, a pointer to type information, etc.</p>
3
2016-06-16T04:02:09Z
[ "python", "python-3.x", "floating-point" ]
How to Override .signup() on Django-Allauth Form
37,849,501
<p>I am trying to override <code>.signup()</code> on a form that inherits from <code>django-allauth</code>'s <code>SignupForm</code>, but it does not seem to be working. My main goal is to save an instance of the <code>UserProfile</code> model at the same time as saving the <code>User</code> model.</p> <p>Here is the ...
0
2016-06-16T03:39:32Z
37,849,677
<p>you need this in your settings.py</p> <pre><code>ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm' </code></pre> <p><strong>EDIT</strong>:</p> <p>you can just use the post_save signal to create userprofile instance</p> <pre><code>from django.db.models.signals import post_save @receiver(post_sav...
1
2016-06-16T04:00:04Z
[ "python", "django", "forms", "registration", "django-allauth" ]
appending numpy array with booleans
37,849,523
<p>Can someone explain what this code is doing?</p> <pre><code> a = np.array([[1, 2], [3, 4]]) a[..., [True, False]] </code></pre> <p>What is the <code>[True, False]</code> doing there?</p>
5
2016-06-16T03:41:19Z
37,849,603
<p><strong>Ellipsis Notation and Booleans as Integers</strong></p> <p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">From the numpy docs</a>:</p> <blockquote> <p>Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim. There m...
1
2016-06-16T03:51:36Z
[ "python", "numpy" ]
Animation timing problems
37,849,577
<h1>The problem</h1> <p>I have two images and I wish to display them both every half second. I do this with timer, yet whenever the image pops in it looks really weird because it seems like the first image is shown then disappears so you see the background, then the other image is shown quickly and disappears and show...
0
2016-06-16T03:48:30Z
37,849,672
<p>You need to add your screen.fill before each animation update and not fill the screen every time the loop runs. If you do that, you will cover your loaded images right after they appear.</p>
2
2016-06-16T03:59:24Z
[ "python", "pygame" ]
Combining multiple pandas rows into a single record of different headings
37,849,642
<p>I have a table of users with how much they spend each day. I want to rearrange them into just one row per users with the columns indicating how much they spend each day.</p> <pre><code>user_id day spending 111 mon 15 111 tues 20 111 weds 25 .... 122 mon 44 122 t...
1
2016-06-16T03:56:22Z
37,849,780
<p>You could use DataFrame.pivot to achieve this. If you store the table in a dataframe named df then the code would be</p> <pre><code>Table = df.pivot(index='userid',columns='day',values='spending') </code></pre>
1
2016-06-16T04:12:56Z
[ "python", "pandas" ]
Combining multiple pandas rows into a single record of different headings
37,849,642
<p>I have a table of users with how much they spend each day. I want to rearrange them into just one row per users with the columns indicating how much they spend each day.</p> <pre><code>user_id day spending 111 mon 15 111 tues 20 111 weds 25 .... 122 mon 44 122 t...
1
2016-06-16T03:56:22Z
37,849,782
<pre><code>df.pivot(index='user_id', columns='day').fillna(0) Out[50]: spending day mon thurs tues weds user_id 111 15 0 20 25 122 44 26 34 90 </code></pre> <p>Or if you want customized aggregation functions, use <code>pivot_...
2
2016-06-16T04:13:23Z
[ "python", "pandas" ]
How do I set the values of tkinter combobox from dictionary keys
37,849,715
<pre><code>root = Tk() my_dict = {'Drosophila melanogaster':1 'Danio rerio': 2, 'Caenorhabditis elegans':3, 'Rattus norvegicus': 4, 'Mus musculus': 5, 'Homo sapiens': 6, } combobox_values = "\n".join(my_dict.keys()) organism = ttk.Combobox(root, values=c...
2
2016-06-16T04:05:44Z
37,849,888
<p>You were very close!</p> <pre><code>combobox_values = "\n".join(my_dict.keys()) </code></pre> <p>should be</p> <pre><code>combobox_values = my_dict.keys() </code></pre> <p>By using <a href="http://www.tutorialspoint.com/python/string_join.htm" rel="nofollow">join</a>, you take all of the keys from the dictionary...
4
2016-06-16T04:24:59Z
[ "python", "user-interface", "combobox", "tkinter", "tk" ]
parse a string till an empty space to form a list in python
37,849,849
<p>I have a <code>string</code> in <code>python</code> in this format:</p> <p>The <code>""</code> above is to show that it is a string. Now I want to parse this <code>string</code> until I hit the first <code>''</code> (an empty element after col3 in above example) and <strong>form a list with elements before this</st...
1
2016-06-16T04:20:50Z
37,849,957
<pre><code>import re import numpy as np l ="['col1', 'col2', 'col3','', 'row1', 'row2']" pattern = r"'([A-Za-z0-9_\./\\-]*)'" m = re.findall(pattern, l) mn = np.array(m) rslt = list(np.split(mn, np.where(mn==''))[0]) </code></pre> <p><strong>Output:</strong></p> <pre><code>rslt Out[75]: ['col1', 'col2', 'col3'] </co...
0
2016-06-16T04:32:52Z
[ "python", "string", "parsing" ]
parse a string till an empty space to form a list in python
37,849,849
<p>I have a <code>string</code> in <code>python</code> in this format:</p> <p>The <code>""</code> above is to show that it is a string. Now I want to parse this <code>string</code> until I hit the first <code>''</code> (an empty element after col3 in above example) and <strong>form a list with elements before this</st...
1
2016-06-16T04:20:50Z
37,849,979
<p>Convert the string to a list and use list operations to slice the string at the empty string:</p> <pre><code>&gt;&gt;&gt; s = "['col1', 'col2', 'col3','', 'row1', 'row2']" &gt;&gt;&gt; import ast &gt;&gt;&gt; L = ast.literal_eval(s) &gt;&gt;&gt; L ['col1', 'col2', 'col3', '', 'row1', 'row2'] &gt;&gt;&gt; L.index(''...
3
2016-06-16T04:35:33Z
[ "python", "string", "parsing" ]
parse a string till an empty space to form a list in python
37,849,849
<p>I have a <code>string</code> in <code>python</code> in this format:</p> <p>The <code>""</code> above is to show that it is a string. Now I want to parse this <code>string</code> until I hit the first <code>''</code> (an empty element after col3 in above example) and <strong>form a list with elements before this</st...
1
2016-06-16T04:20:50Z
37,849,985
<p>I wish I could parse your string directly using <code>json</code> but when I do, I get this error:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.loads("['col1', 'col2', 'col3','', 'row1', 'row2']") ... ValueError: No JSON object could be decoded </code></pre> <p>So, I first replaced the single quotes ...
0
2016-06-16T04:36:05Z
[ "python", "string", "parsing" ]
search efficiently in a dictionary
37,849,863
<p>I have a long dictionary of form string to string like </p> <pre><code>{'a':'b' , 'c':'d'} </code></pre> <p>I want to efficiently search for a key so that I can get the corresponding answer from the dictionary, but I would like a better search than just iterating over the entire dictionary. Is there a better way l...
-2
2016-06-16T04:22:00Z
37,849,894
<p>If you have a dictionary <code>d</code> and want to test for membership of a key <code>k</code>, you can just use <code>k in d</code> or <code>k not in d</code>. For example:</p> <pre><code>&gt;&gt;&gt; d = {'a':'b' , 'c':'d'} &gt;&gt;&gt; 'a' in d True &gt;&gt;&gt; 'x' in d False &gt;&gt;&gt; 'a' not in d False &...
1
2016-06-16T04:25:36Z
[ "python", "list", "set" ]
search efficiently in a dictionary
37,849,863
<p>I have a long dictionary of form string to string like </p> <pre><code>{'a':'b' , 'c':'d'} </code></pre> <p>I want to efficiently search for a key so that I can get the corresponding answer from the dictionary, but I would like a better search than just iterating over the entire dictionary. Is there a better way l...
-2
2016-06-16T04:22:00Z
37,850,658
<p>There is already an interesting quest on <a href="http://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented">How are Python's Built In Dictionaries Implemented</a> ...</p> <p>but why not try and measure here (after having read about time coplexity in python implementation):</p> <p...
0
2016-06-16T05:37:27Z
[ "python", "list", "set" ]
search efficiently in a dictionary
37,849,863
<p>I have a long dictionary of form string to string like </p> <pre><code>{'a':'b' , 'c':'d'} </code></pre> <p>I want to efficiently search for a key so that I can get the corresponding answer from the dictionary, but I would like a better search than just iterating over the entire dictionary. Is there a better way l...
-2
2016-06-16T04:22:00Z
37,855,257
<p>You could use the <a href="https://docs.python.org/3.4/library/stdtypes.html?highlight=translate#str.translate" rel="nofollow"><code>str.translate</code></a> function to replace a string's characters using a table (in this case the <code>dict</code>) from key to value.</p>
0
2016-06-16T09:33:27Z
[ "python", "list", "set" ]
Pass command line arguments for fabric execute task
37,849,865
<p>I'm new to the <code>fabric</code> API and I'm trying to figure out to pass command line arguments, which are different for each host. So, here's where I'm at right now. Currently, the bit below runs the script <code>get_num_reviews_aws.py</code> correctly, in parallel, on each of the three hosts. </p> <pre><code>h...
0
2016-06-16T04:22:03Z
37,858,081
<p>I think you could use roles defined <a href="http://docs.fabfile.org/en/1.11/api/core/decorators.html#fabric.decorators.roles" rel="nofollow">here</a>.</p>
0
2016-06-16T11:38:25Z
[ "python", "amazon-ec2", "fabric" ]
Pass command line arguments for fabric execute task
37,849,865
<p>I'm new to the <code>fabric</code> API and I'm trying to figure out to pass command line arguments, which are different for each host. So, here's where I'm at right now. Currently, the bit below runs the script <code>get_num_reviews_aws.py</code> correctly, in parallel, on each of the three hosts. </p> <pre><code>h...
0
2016-06-16T04:22:03Z
37,868,850
<p>This worked for me, after looking at a few other <a href="http://stackoverflow.com/questions/11602084/passing-different-arguments-to-different-hosts-in-fabric?answertab=votes#tab-top">similar questions on SO</a>.</p> <pre><code>hosts = [ubuntu@54.xxx.xx.xx, ubuntu@52.xx.xxx.xx, ubuntu@54.xx.xxx.xx...
0
2016-06-16T20:32:55Z
[ "python", "amazon-ec2", "fabric" ]
Why can't python-colormath convert sRGB to Adobe RGB?
37,849,901
<p>This seems like such a simple problem, exactly what <code>colormath</code> was designed for. But calling <code>convert_color</code> appears to return the same object that was passed in. According to <a href="http://python-colormath.readthedocs.io/en/latest/conversions.html" rel="nofollow">the documentation</a> a fai...
1
2016-06-16T04:26:34Z
37,873,991
<p>The content of the <code>conversion</code> variable in the <a href="https://github.com/gtaylor/python-colormath/blob/fa1aa638c421e6a8ca23fb3bcc48d43da523fff8/colormath/color_conversions.py#L939" rel="nofollow">convert_color</a> definition using your example is an empty list, meaning that there is no conversion to pe...
0
2016-06-17T05:46:28Z
[ "python", "color-space" ]
Handling masked numpy array
37,849,921
<p>I have masked numpy array. While doing processing for each of the element, I need to first check whether the particular element is masked or not, if masked then I need to skip those element. </p> <p>I have tried like this : </p> <pre><code>from netCDF4 import Dataset data=Dataset('test.nc') dim_size=len(data.dime...
0
2016-06-16T04:28:45Z
37,850,290
<p>Instead of a loop you could use</p> <pre><code>correction = model_dry_tropo_corr/2 + solid_earth_tide </code></pre> <p>This will create a new masked array that will have your answers and masks. You could then access unmasked values from new array.</p>
1
2016-06-16T05:07:00Z
[ "python", "numpy" ]
Handling masked numpy array
37,849,921
<p>I have masked numpy array. While doing processing for each of the element, I need to first check whether the particular element is masked or not, if masked then I need to skip those element. </p> <p>I have tried like this : </p> <pre><code>from netCDF4 import Dataset data=Dataset('test.nc') dim_size=len(data.dime...
0
2016-06-16T04:28:45Z
37,868,561
<p>I'm puzzled about this code</p> <pre><code>try : model_dry_tropo_corr[i].mask=True continue except : Pass </code></pre> <p>I don't have <code>netCDF4</code> installed, but it appears from the documentation that your variable will look like, maybe even be a <code>numpy.ma</code> masked array.</p> <p>It...
0
2016-06-16T20:11:18Z
[ "python", "numpy" ]
Printing console command exactly how I entered it
37,849,964
<p>I'm having issues with console commands.</p> <pre><code>import re import string import sys import subprocess productname= "".join(sys.argv[1:]) def check(): global productname productname= productname.replace(' ','') productname= productname.replace('\n','') if len(productname) &gt;= 3: ...
1
2016-06-16T04:33:29Z
37,849,991
<p>That's because by default, the array is coerced to string in that format. (Because of the <code>%s</code> formatter you're using.)</p> <p>If you want something else, convert the array to the string you want first. A simple solution for you would be <code>' '.join(sys.argv[1:None])</code>.</p>
-1
2016-06-16T04:36:56Z
[ "python", "printing", "console", "command" ]
Printing console command exactly how I entered it
37,849,964
<p>I'm having issues with console commands.</p> <pre><code>import re import string import sys import subprocess productname= "".join(sys.argv[1:]) def check(): global productname productname= productname.replace(' ','') productname= productname.replace('\n','') if len(productname) &gt;= 3: ...
1
2016-06-16T04:33:29Z
37,850,115
<p>If you want your exact input, you could enter it on the command line as:</p> <pre><code>python test.py "a a a s" </code></pre> <p>This means that <code>argv[1]</code> will be the entire string <code>"a a a s"</code>, so code like this would work:</p> <pre><code>productname = sys.argv[1] # Other stuff # Use ...
1
2016-06-16T04:51:13Z
[ "python", "printing", "console", "command" ]
openpyxl no attribution error
37,849,980
<h2>Python 3.5 openpyxl 2.4</h2> <p>Hi everyone, I got a simple but confusing problem here. FYI the API doc relating to worksheet is </p> <p><a href="http://openpyxl.readthedocs.io/en/default/api/openpyxl.worksheet.worksheet.html" rel="nofollow">http://openpyxl.readthedocs.io/en/default/api/openpyxl.worksheet.works...
0
2016-06-16T04:35:37Z
37,850,074
<p>I tried it with openpyxl 2.3.5 and got the following</p> <blockquote> <p> /usr/local/lib/python3.5/site-packages/openpyxl/worksheet/worksheet.py:350: <strong>UserWarning: Call to deprecated function or class get_highest_row (Use the max_row property).</strong> def get_highest_row(self):</p> </blockquote> ...
1
2016-06-16T04:47:45Z
[ "python", "excel", "python-3.x", "openpyxl" ]
GSpread ImportError: No module named oauth2client.service_account
37,850,004
<p>Ok I'm following along with the Become A Technical Marketer course and I'm trying to learn how to manage Google Spreadsheets with GSpread. I've followed along with the documentation at <a href="http://gspread.readthedocs.io/en/latest/oauth2.html" rel="nofollow">http://gspread.readthedocs.io/en/latest/oauth2.html</a>...
3
2016-06-16T04:39:24Z
37,921,518
<p>According to <a href="https://github.com/pypa/pip/issues/3165" rel="nofollow">this discussion</a>,</p> <blockquote> <p>This is because OS X El Capitan ships with six 1.4.1 installed already and when it attempts to uninstall it, it doesn't have permission to do so because System Integrity Protection doesn't allow ...
2
2016-06-20T11:34:51Z
[ "python", "google-api-python-client", "google-app-engine-python", "gspread" ]
Using python to read an array from a JSON file
37,850,048
<p>I have this JSON file:</p> <pre><code>[ { id: "29", name: "abc", email: "def@school.edu", data: "2016-05-03" }, { id: "17", name: "ghi", email: "jkl@school.edu", data: "2016-05-12" }, { id: "12", name: "qwe", email: "cde@school.edu", data: "2016-04-11" } ] </code></pre> <p>I wrote this script:</p> <pre><code>with...
0
2016-06-16T04:44:32Z
37,850,249
<p>Your JSON is not formatted properly. I put validated it in <a href="https://jsonformatter.curiousconcept.com/" rel="nofollow">https://jsonformatter.curiousconcept.com/</a> and it shows that your keys are not wrapped in quotes. This is what it should be:</p> <pre><code>[ { "id":"29", "name":"abc",...
2
2016-06-16T05:03:53Z
[ "python", "json" ]
Using python to read an array from a JSON file
37,850,048
<p>I have this JSON file:</p> <pre><code>[ { id: "29", name: "abc", email: "def@school.edu", data: "2016-05-03" }, { id: "17", name: "ghi", email: "jkl@school.edu", data: "2016-05-12" }, { id: "12", name: "qwe", email: "cde@school.edu", data: "2016-04-11" } ] </code></pre> <p>I wrote this script:</p> <pre><code>with...
0
2016-06-16T04:44:32Z
37,850,261
<p>This is the error:</p> <blockquote> <p>Traceback (most recent call last): File "C:/Users/L30607/PycharmProjects/untitled1/333.py", line 36, in d = json.load(json_data) File "C:\Python27\lib\json__init__.py", line 291, in load **kw) File "C:\Python27\lib\json__init__.py", line 339, in loads ...
0
2016-06-16T05:04:52Z
[ "python", "json" ]
Using python to read an array from a JSON file
37,850,048
<p>I have this JSON file:</p> <pre><code>[ { id: "29", name: "abc", email: "def@school.edu", data: "2016-05-03" }, { id: "17", name: "ghi", email: "jkl@school.edu", data: "2016-05-12" }, { id: "12", name: "qwe", email: "cde@school.edu", data: "2016-04-11" } ] </code></pre> <p>I wrote this script:</p> <pre><code>with...
0
2016-06-16T04:44:32Z
37,850,275
<p>Always validate your json from <a href="http://jsonlint.com/" rel="nofollow">http://jsonlint.com/</a> if you get any errors. In your case you are not giving <em>Keys</em> as string.</p>
0
2016-06-16T05:06:03Z
[ "python", "json" ]
Using python to read an array from a JSON file
37,850,048
<p>I have this JSON file:</p> <pre><code>[ { id: "29", name: "abc", email: "def@school.edu", data: "2016-05-03" }, { id: "17", name: "ghi", email: "jkl@school.edu", data: "2016-05-12" }, { id: "12", name: "qwe", email: "cde@school.edu", data: "2016-04-11" } ] </code></pre> <p>I wrote this script:</p> <pre><code>with...
0
2016-06-16T04:44:32Z
37,850,362
<p>Your json should be like :</p> <pre><code>[{ "id": "29", "name": "abc", "email": "def@school.edu", "data": "2016-05-03" }, { "id": "17", "name": "ghi", "email": "jkl@school.edu", "data": "2016-05-12" }, { "id": "12", "name": "qwe", "email": "cde@school.edu", "data": "...
0
2016-06-16T05:14:34Z
[ "python", "json" ]
Trust On First Use in BOLT Neo4j driver for python - how to make the code run
37,850,112
<p>I'm using PyCharm 2016.1.4 and an example from the neo4j manual. I'm wondering how to use the TRUST_ON_FIRST_USE in the expression. It's not recognized by pycharm as a valid entry. Placing it between " " or ' ' also did not resolve the issue. What do I miss here?</p> <pre><code>driver = GraphDatabase.driver("bolt:/...
0
2016-06-16T04:51:04Z
37,852,896
<p>You presumably need to include:</p> <pre><code>from neo4j.v1 import TRUST_ON_FIRST_USE </code></pre>
1
2016-06-16T07:45:45Z
[ "python", "neo4j", "pycharm" ]
Debugging IBM Watson APIs on Bluemix
37,850,126
<p>I am trying to use IBM Watson's conversation API on Bluemix and am getting the following exception. I am not able to find any documentation as to how to debug it. </p> <pre><code>Error: "conversation.py", line 14, in &lt;module&gt; response = conversation.message(workspace_id=workspace_id, message_input={'text...
1
2016-06-16T04:52:16Z
38,727,546
<p>I know this is an old question but I don't want to leave it unanswered.</p> <p>As @jonrsharpe said, <code>Error: NLU service error: Processing error, Code: 500</code> means that there was a server side error.</p> <p>When you hit a 5XX error there is nothing you can't do more than trying the request again.</p>
0
2016-08-02T18:03:02Z
[ "python", "ibm-bluemix", "ibm-watson-cognitive", "watson-conversation" ]
Calculate day time differences in a pandas Dataframe
37,850,330
<p>I have the following dataframe:</p> <pre><code> data = [ ("10/10/2016","A"), ("10/10/2016","B"), ("09/12/2016","B"), ("09/12/2016","A"), ("08/11/2016","A"), ("08/11/2016","C")] #Create DataFrame base df = pd.DataFrame(data, columns=("Time","User")) # Convert time column to correct format for time calculations df...
2
2016-06-16T05:10:24Z
37,850,356
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a>, convert to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html#frequency-conversion" rel="nofollow"><code>np.timedelta64(1,'D')</code></a> a...
1
2016-06-16T05:13:50Z
[ "python", "datetime", "pandas", "group-by" ]
Calculate day time differences in a pandas Dataframe
37,850,330
<p>I have the following dataframe:</p> <pre><code> data = [ ("10/10/2016","A"), ("10/10/2016","B"), ("09/12/2016","B"), ("09/12/2016","A"), ("08/11/2016","A"), ("08/11/2016","C")] #Create DataFrame base df = pd.DataFrame(data, columns=("Time","User")) # Convert time column to correct format for time calculations df...
2
2016-06-16T05:10:24Z
37,850,653
<p>Building on from @Jezrael's answer:</p> <p>If by "how frequently" you mean - how much time passes between each user performing the action then here's an approach:</p> <pre><code>import pandas as pd import numpy as np data = [ ("10/10/2016","A"), ("10/10/2016","B"), ("09/12/2016","B"), ("09/12/2016...
0
2016-06-16T05:37:11Z
[ "python", "datetime", "pandas", "group-by" ]
Tensorflow: ImportError cannot import name graph_util in retrain.py
37,850,347
<p>I compiled Tensorflow from source to work with GPU. I was able to successfully install it. It's able to successfully run the sample mnist <code>convolutional.py</code> script.</p> <p>However, when I do the <code>retrain.py</code> script in <code>tensorflow/examples/image_retraining</code>, it spits out the followin...
1
2016-06-16T05:12:58Z
37,853,249
<p>There was a <a href="https://github.com/tensorflow/tensorflow/commit/a558c6e3b38846727873b5afbbc3ba309ae5dff5" rel="nofollow">commit</a> yesterday which moved the file <code>graph_util.py</code> from <code>tensorflow.python.client</code> to <code>tensorflow.python.framework</code>.</p> <p>It is weird that you have ...
3
2016-06-16T08:00:57Z
[ "python", "tensorflow" ]
Why does this valid shell command throw an error in python via subprocess?
37,850,357
<p>The line <code>awk -F'[][]' '/dB/ { print $2 }' &lt;(amixer sget Master)</code> in bash returns my system's current volume (e.g. "97%"). </p> <p>I tried to incorporate this in Python 3 </p> <pre><code>#!/usr/bin/env python3 import subprocess command = "awk -F'[][]' '/dB/ { print $2 }' &lt;(amixer sget Master)" ou...
0
2016-06-16T05:14:01Z
37,850,395
<p>Because you are using bashism in form of a <a href="http://wiki.bash-hackers.org/syntax/expansion/proc_subst" rel="nofollow">process substitution</a>, and your <code>/bin/sh</code> doesn't support that:</p> <pre><code>&lt;(...) </code></pre> <p>Changing this to a pipe should solve your problem:</p> <pre><code>com...
3
2016-06-16T05:17:06Z
[ "python", "bash", "shell" ]
Why does this valid shell command throw an error in python via subprocess?
37,850,357
<p>The line <code>awk -F'[][]' '/dB/ { print $2 }' &lt;(amixer sget Master)</code> in bash returns my system's current volume (e.g. "97%"). </p> <p>I tried to incorporate this in Python 3 </p> <pre><code>#!/usr/bin/env python3 import subprocess command = "awk -F'[][]' '/dB/ { print $2 }' &lt;(amixer sget Master)" ou...
0
2016-06-16T05:14:01Z
37,850,823
<p>As already pointed out, the syntax you are using is a <code>bash</code> syntax (a.k.a. bashism). The <strong>default</strong> shell used in <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>subprocess.Popen</code></a> is <code>/bin/sh</code> &amp; it does not support <...
1
2016-06-16T05:47:43Z
[ "python", "bash", "shell" ]
Adding a new column in data frame after calculation on time
37,850,374
<p>I have a <code>DataFrame</code> like this:</p> <pre><code> Name first_seen last_seen 0 Random guy 1 5/22/2016 18:12 5/22/2016 18:15 1 Random guy 2 5/22/2016 12:03 5/22/2016 12:03 2 Random guy 3 5/22/2016 21:06 5/22/2016 21:06 3 Random guy 4 5/22/...
7
2016-06-16T05:15:11Z
37,850,728
<p>You could use <code>apply</code> with the below <code>main_visit_period</code> function that attempts to assign a visit period according to the conditions you outlined:</p> <pre><code>times = list(range(8, 21, 4)) labels = ['morning', 'afternoon', 'evening', 'night'] periods = dict(zip(times, labels)) </code></pre>...
2
2016-06-16T05:41:46Z
[ "python", "python-2.7", "pandas" ]
Adding a new column in data frame after calculation on time
37,850,374
<p>I have a <code>DataFrame</code> like this:</p> <pre><code> Name first_seen last_seen 0 Random guy 1 5/22/2016 18:12 5/22/2016 18:15 1 Random guy 2 5/22/2016 12:03 5/22/2016 12:03 2 Random guy 3 5/22/2016 21:06 5/22/2016 21:06 3 Random guy 4 5/22/...
7
2016-06-16T05:15:11Z
37,853,948
<p>You can do this:</p> <pre><code>start = pd.datetime(2016, 05, 22, 8, 00, 00) d = ["Morning", "Afternoon", "Evening", "Night"] def max_spent(fs, ls): # Transform your date into timedelta in seconds: sr = np.arange(8,25,4)*3600 fss = (fs-start).seconds lss = (ls-start).seconds # In which slot ...
0
2016-06-16T08:34:17Z
[ "python", "python-2.7", "pandas" ]
How to draw a diagonal line in subplot?
37,850,444
<p>I try to draw a diagonal line but it doesn't work.</p> <p>I can draw a horizontal and vertical line by use axhline and axvline</p> <p>but I dont know about diagonal I have use plot but it doesn't work</p> <p>Here is some of my code and result : </p> <pre><code>while (loop &lt; candleLength) : date = stoc...
0
2016-06-16T05:21:21Z
37,850,733
<p>well, use a conventional line:</p> <pre><code>ax.plot((xStart, xEnd), (yStart, yEnd), ...) </code></pre>
0
2016-06-16T05:42:12Z
[ "python", "matplotlib", "candlestick-chart" ]
How to draw a diagonal line in subplot?
37,850,444
<p>I try to draw a diagonal line but it doesn't work.</p> <p>I can draw a horizontal and vertical line by use axhline and axvline</p> <p>but I dont know about diagonal I have use plot but it doesn't work</p> <p>Here is some of my code and result : </p> <pre><code>while (loop &lt; candleLength) : date = stoc...
0
2016-06-16T05:21:21Z
37,850,746
<p>Try adding</p> <pre><code>plt.plot([0, 90], [0, 90], '-') </code></pre> <p>or appropriate values to your plot.</p>
0
2016-06-16T05:43:16Z
[ "python", "matplotlib", "candlestick-chart" ]
spliting sigle row of string in form of tuple in list to multiple rows (equal to number of tuple)
37,850,711
<p>I have a <code>DataFrame</code> which has tuples of strings in one row and its id.</p> <p>like:</p> <pre><code>id words 223 [('flying bird','round place'),('blue sky','red rose')] 368 [('fairy tales','great day'),('show time','break free'),('noise free')] </code></pre> <p>I want:</p> <pre><...
2
2016-06-16T05:40:51Z
37,851,121
<pre><code>d = {'id': [233, 368], 'words': [[('flying bird','round place'),('blue sky','red rose')], [('fairy tales','great day'),('show time','break free'),('noise free')]]} df = pd.DataFrame(d) dfidtemp = df['id'] df = df['words'].apply(pd.Series, 1) df.index = dfidtemp rslt = df.stack() </code>...
0
2016-06-16T06:06:26Z
[ "python", "list", "pandas", "dataframe", "tuples" ]
spliting sigle row of string in form of tuple in list to multiple rows (equal to number of tuple)
37,850,711
<p>I have a <code>DataFrame</code> which has tuples of strings in one row and its id.</p> <p>like:</p> <pre><code>id words 223 [('flying bird','round place'),('blue sky','red rose')] 368 [('fairy tales','great day'),('show time','break free'),('noise free')] </code></pre> <p>I want:</p> <pre><...
2
2016-06-16T05:40:51Z
37,851,195
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>. Last column <code>word...
1
2016-06-16T06:12:30Z
[ "python", "list", "pandas", "dataframe", "tuples" ]
spliting sigle row of string in form of tuple in list to multiple rows (equal to number of tuple)
37,850,711
<p>I have a <code>DataFrame</code> which has tuples of strings in one row and its id.</p> <p>like:</p> <pre><code>id words 223 [('flying bird','round place'),('blue sky','red rose')] 368 [('fairy tales','great day'),('show time','break free'),('noise free')] </code></pre> <p>I want:</p> <pre><...
2
2016-06-16T05:40:51Z
37,851,661
<pre><code>words=[] ids = [] for i in df.index: words = words + df.words[i] ids = ids + [df.id[i]]*len(df.words[i]) df = pd.DataFrame({'words':words,'ids':ids}) </code></pre>
0
2016-06-16T06:42:30Z
[ "python", "list", "pandas", "dataframe", "tuples" ]
spliting sigle row of string in form of tuple in list to multiple rows (equal to number of tuple)
37,850,711
<p>I have a <code>DataFrame</code> which has tuples of strings in one row and its id.</p> <p>like:</p> <pre><code>id words 223 [('flying bird','round place'),('blue sky','red rose')] 368 [('fairy tales','great day'),('show time','break free'),('noise free')] </code></pre> <p>I want:</p> <pre><...
2
2016-06-16T05:40:51Z
37,852,376
<p>You could also use <a href="https://docs.python.org/3.5/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast</code></a> <code>literal_evaluation</code> to parse <code>tuples</code> out of <code>strings</code>:</p> <pre><code>from ast import literal_eval as make_tuple df = df.groupby('id')['words'].apply(lamb...
0
2016-06-16T07:18:16Z
[ "python", "list", "pandas", "dataframe", "tuples" ]
Storing objects in file instead of in memory
37,850,869
<p>I've created a genetic programming system in Python, but am having troubles related to memory limits. The problem is with storing all of the individuals in my population in memory. Currently, I store all individuals in memory, then reproduce the next generation's population, which then gets stored in to memory. This...
3
2016-06-16T05:50:37Z
37,853,966
<p>Given the RAM constraint, I'd change the population model from generational to <strong><em>steady state</em></strong>.</p> <p>The idea is to iteratively breed a new child or two, assess their fitness and then reintroduce them directly into the population itself, killing off some preexisting individuals to make room...
2
2016-06-16T08:35:17Z
[ "python", "memory", "memory-management", "genetic-programming" ]
Storing objects in file instead of in memory
37,850,869
<p>I've created a genetic programming system in Python, but am having troubles related to memory limits. The problem is with storing all of the individuals in my population in memory. Currently, I store all individuals in memory, then reproduce the next generation's population, which then gets stored in to memory. This...
3
2016-06-16T05:50:37Z
38,424,384
<p>Bear in mind that if you use Steady State, you would need to have some method to have the probability of the Fittest individuals to cross breed to be higher than the less fit individuals.</p> <p>A couple of additional options you could think about are:</p> <p>a) Use SQLLite. (<a href="https://docs.python.org/2/li...
0
2016-07-17T18:10:52Z
[ "python", "memory", "memory-management", "genetic-programming" ]
how to call old api function in new api function(unlink)?
37,850,917
<p>I want to call the old api function of hr_attendance in new api of unlink() function.</p> <p>My old api code is:</p> <pre><code>def _altern_si_so(self, cr, uid, ids, context=None): for att in self.browse(cr, uid, ids, context=context): prev_att_ids = self.search(cr, uid, [('employee_id', '=',att.employee_id.id),...
0
2016-06-16T05:54:00Z
37,851,623
<p>try this way:</p> <pre><code>class product_attribute(models.Model): _inherit = "product.attribute" @api.multi def unlink(self): res= super(product_attribute,self).unlink() #do your code return res </code></pre> <p><strong>Regarding</strong> Calling old api method (those...
0
2016-06-16T06:40:07Z
[ "python", "api", "odoo-8" ]
FormView - How to use self.request outside the methods
37,850,927
<p>It is possible to do this some how:</p> <pre><code>class Login_vw(FormView): form_class = Login_fr success_url = '/success/' template_name = 'login.html' someVar_ses = self.request.session['someVar'] record_qr = MyModel.objects.filter(id=someVar_ses) </code></pre> <p>When I do that I get this:...
0
2016-06-16T05:54:22Z
37,851,084
<p>you're defining class object variables (static), in contrast to instance object variables. <a href="http://stackoverflow.com/questions/68645/static-class-variables-in-python">See this question and answers</a>. See also the <a href="https://docs.python.org/2/tutorial/classes.html#class-objects" rel="nofollow">python ...
-1
2016-06-16T06:04:16Z
[ "python", "django" ]
FormView - How to use self.request outside the methods
37,850,927
<p>It is possible to do this some how:</p> <pre><code>class Login_vw(FormView): form_class = Login_fr success_url = '/success/' template_name = 'login.html' someVar_ses = self.request.session['someVar'] record_qr = MyModel.objects.filter(id=someVar_ses) </code></pre> <p>When I do that I get this:...
0
2016-06-16T05:54:22Z
37,851,727
<p>Actually you can not do that. Why would you want to populate <code>record_qr</code> on view initialization and not where you'd want to use it ? For example if I want to use <code>record_qr</code> once the form has been submitted, I would do it in the <code>form_valid</code> method. If you would want to use it in mul...
0
2016-06-16T06:45:56Z
[ "python", "django" ]
For loop in the csv module
37,850,946
<p>I was using the csv module to do some parsing, but I have been confounded by a problem that I couldn't really put my hands on. I think the <code>for</code>-loop for the <code>csv.reader()</code> eliminates the row that has been looped through. For example:</p> <pre><code>import csv f = open('example.csv', 'rb') r ...
0
2016-06-16T05:55:25Z
37,851,758
<p>It's late so sorry about any mistake, I need to do some brush up on my python skills, but I will try to solve your problem.</p> <p>From the documentation:</p> <blockquote> <p>csv.reader(csvfile, dialect='excel', **fmtparams) Return a reader object which will iterate over lines in the given csvfile. csvfile can...
1
2016-06-16T06:47:52Z
[ "python", "csv" ]
How to create a list with multiple datatypes (characters as well as integers) using loop (both for and while loop) in python .
37,850,966
<p>I am trying to create a list with multiple datatypes (characters as well as integers) using loop (both for and while loop). </p> <p>The code snippet using while loop is as follows:-</p> <pre><code>my_list=[] item=0 while item!=5: item=int(input("""Enter the number to create the list(To discontinue enter 5): ""...
0
2016-06-16T05:56:41Z
37,851,440
<pre><code>my_list=[] item=0 while item!="5": item=raw_input("""Enter the number to create the list(To discontinue enter 5): """) if item.isdigit(): my_list.append(int(item)) else: my_list.append(item) print("The list created is: ",my_list) </code></pre>
2
2016-06-16T06:28:40Z
[ "python", "list", "types" ]
Getting cookies from a form submit and using them with a webtest
37,851,014
<p>So I'm trying to do some test cases with webtest library, the problem is that my site has access control which requires a user to login. It seems that the form post is successful, but the result do not have any cookies (that I could find at least), and the cookiejar is empty after the login. </p> <p>Test setup:</p>...
0
2016-06-16T06:00:19Z
37,882,874
<p>Problem was that the <code>form.submit()</code> didn't actually mimic the basic use-case of mine, where the user clicks the submit button. In normal case the browser adds the username, password and the <code>('form.submitted', '')</code> in side of the <code>request.POST</code>. But the <code>form.submit()</code> on...
0
2016-06-17T13:29:14Z
[ "python", "python-3.x", "pyramid", "webtest", "cookiejar" ]
Django: Query Group By Month
37,851,053
<p>How to calculate total by month without using extra?</p> <p>I'm currently using:</p> <ul> <li>django 1.8</li> <li>postgre 9.3.13</li> <li>Python 2.7</li> </ul> <p>Example.</p> <p><a href="http://i.stack.imgur.com/aZ1Fm.png" rel="nofollow"><img src="http://i.stack.imgur.com/aZ1Fm.png" alt="enter image description...
4
2016-06-16T06:02:32Z
37,852,938
<p>I don't know if my solution is faster than your. You should profile it. Nonetheless I only query the db once instead of 12 times.</p> <pre><code>#utils.py from django.db.models import Count, Sum def get_total_per_month_value(): """ Return the total of sales per month ReturnType: [Dict] {'December...
0
2016-06-16T07:47:47Z
[ "python", "django", "postgresql" ]
Django: Query Group By Month
37,851,053
<p>How to calculate total by month without using extra?</p> <p>I'm currently using:</p> <ul> <li>django 1.8</li> <li>postgre 9.3.13</li> <li>Python 2.7</li> </ul> <p>Example.</p> <p><a href="http://i.stack.imgur.com/aZ1Fm.png" rel="nofollow"><img src="http://i.stack.imgur.com/aZ1Fm.png" alt="enter image description...
4
2016-06-16T06:02:32Z
37,854,337
<p><a href="https://docs.python.org/2.7/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> is the performant option in Python and can be utilized with a single db query:</p> <pre><code>from itertools import groupby invoices = Invoice.objects.only('date', 'total').order_by('dat...
1
2016-06-16T08:53:24Z
[ "python", "django", "postgresql" ]
Django: Query Group By Month
37,851,053
<p>How to calculate total by month without using extra?</p> <p>I'm currently using:</p> <ul> <li>django 1.8</li> <li>postgre 9.3.13</li> <li>Python 2.7</li> </ul> <p>Example.</p> <p><a href="http://i.stack.imgur.com/aZ1Fm.png" rel="nofollow"><img src="http://i.stack.imgur.com/aZ1Fm.png" alt="enter image description...
4
2016-06-16T06:02:32Z
37,858,126
<p>First, you have to make a Function that can extract the month for you:</p> <pre><code>from django.db import models from django.db.models import Func class Month(Func): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() </code></pre> <p>After...
3
2016-06-16T11:40:04Z
[ "python", "django", "postgresql" ]
Python and MySQL UPDATE
37,851,115
<p>Everything is working as it should for the ping tool but MySQL updates are failing. </p> <p>It should pull the ip address it is currently doing and update it in the MYSQL.</p> <pre><code>import MySQLdb db = MySQLdb.connect(host="10.1.1.151", # your host, usually localhost user="root", ...
1
2016-06-16T06:06:09Z
37,851,202
<p>The problem may be that you need to <a href="https://dev.mysql.com/doc/refman/5.6/en/glossary.html#glos_commit" rel="nofollow">commit</a> the transactions, after calling <code>cur.execute()</code>.</p> <p>Hence you'll need to call <code>db.commit()</code> after all your transactions are executed.</p> <p>Hope it'll...
0
2016-06-16T06:12:46Z
[ "python", "mysql", "mysql-python" ]
Python and MySQL UPDATE
37,851,115
<p>Everything is working as it should for the ping tool but MySQL updates are failing. </p> <p>It should pull the ip address it is currently doing and update it in the MYSQL.</p> <pre><code>import MySQLdb db = MySQLdb.connect(host="10.1.1.151", # your host, usually localhost user="root", ...
1
2016-06-16T06:06:09Z
37,851,213
<p>You're missing the binding of the data (ip) to the cursor:</p> <pre><code>if ret == 0: cur.execute("UPDATE application_status SET status = 1 WHERE ip_address = %s", (ip,)) print "%s: is alive" % ip else: cur.execute("UPDATE application_status SET status = 0 WHERE ip_address = %s", (ip,))...
1
2016-06-16T06:13:27Z
[ "python", "mysql", "mysql-python" ]