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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Classifying two lists and arrange accordingly in python | 38,457,948 | <p>I'm working with 2 lists looks like this: </p>
<pre><code>list_a = [x,y,z,.....]
list_b = [xa,xb,xc,xd,xe,ya,yb,yc,yd,za,zb,zc,zd,ze,zf]
</code></pre>
<p>What I'm trying to achieve is, to make more lists while arranging the data like following: </p>
<pre><code>list_x = [x,xa,xb,xc,xd,xe]
list_y = [y,ya,yb... | -2 | 2016-07-19T11:59:41Z | 38,464,596 | <p>You could follow a functional approach by using <a href="https://docs.python.org/2.7/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> and <a href="https://docs.python.org/2/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter()</code></a>:</... | 0 | 2016-07-19T17:09:08Z | [
"python"
] |
AssertionError: View function mapping is overwriting an existing endpoint function: EMPTY? | 38,458,026 | <p>Any suggestion toward a clean solution will be appreciated.</p>
<p>I am trying to add some static files to an existing app, a static folder with other files is already set. I would like to define several routes based on a list, the goal is to be able to easily add files.</p>
<p>The problem is that I receive this i... | -1 | 2016-07-19T12:03:47Z | 38,458,529 | <p>"Because you passed an empty string to <code>add_url_rule</code> multiple times in a for loop. Pick a unique name each time." -- davidism</p>
<p>This works fine</p>
<pre><code>for d in deps:
app.add_url_rule(d, d, app.serv_deps[d])
</code></pre>
<p>Thanks</p>
| 0 | 2016-07-19T12:24:51Z | [
"python",
"flask"
] |
how to add or use tfx python module for catkin? | 38,458,101 | <p>i download a repository [ <a href="https://github.com/simon0793/pr2_simu" rel="nofollow">https://github.com/simon0793/pr2_simu</a>... ] i am using catkin_workplace when ever i run python code</p>
<pre><code>python simulation_one_motion_queue.py
</code></pre>
<p>every time error comes tfx not found as;</p>
<pre><c... | 0 | 2016-07-19T12:07:18Z | 38,480,956 | <p>That means that the package <code>tfx</code> was not found. Make sure that it is on your ROS_PACKAGE_PATH. You can try if it is already added in path by running </p>
<pre><code>$ roscd tfx
</code></pre>
<p>that should bring you to the package directory. Otherwise you have to search and include it yourself. (Worst ... | 0 | 2016-07-20T12:11:05Z | [
"python",
"ros",
"catkin"
] |
Use decorators to wrap all functions with "if func returned false, return false" | 38,458,105 | <p>I'm writing a very basic Python script based on a <code>main</code> function that sequentially calls other functions.</p>
<p>What I would like to do is to wrap all of the functions that are called from <code>main</code> with something like:</p>
<pre><code>result = func(*some_args):
if (result != True):
r... | -2 | 2016-07-19T12:07:31Z | 38,458,548 | <p>I guess, what you really want is a universal exception catcher, that would catch and return the exception of any wrapped function. You can easily do it this way. </p>
<pre><code>def return_exception(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Excepti... | 0 | 2016-07-19T12:25:28Z | [
"python",
"decorator",
"python-decorators"
] |
Use decorators to wrap all functions with "if func returned false, return false" | 38,458,105 | <p>I'm writing a very basic Python script based on a <code>main</code> function that sequentially calls other functions.</p>
<p>What I would like to do is to wrap all of the functions that are called from <code>main</code> with something like:</p>
<pre><code>result = func(*some_args):
if (result != True):
r... | -2 | 2016-07-19T12:07:31Z | 38,458,604 | <p>I maintain that the best solution would be the use of exceptions. If that's absolutely not what you want, you can do some short-circuiting:</p>
<pre><code>return func1() and func2()
</code></pre>
<p>To extend this to more functions without a ton of <code>and</code>s:</p>
<pre><code>from functools import partial
... | 2 | 2016-07-19T12:28:08Z | [
"python",
"decorator",
"python-decorators"
] |
Use decorators to wrap all functions with "if func returned false, return false" | 38,458,105 | <p>I'm writing a very basic Python script based on a <code>main</code> function that sequentially calls other functions.</p>
<p>What I would like to do is to wrap all of the functions that are called from <code>main</code> with something like:</p>
<pre><code>result = func(*some_args):
if (result != True):
r... | -2 | 2016-07-19T12:07:31Z | 38,458,832 | <p>This is precisely what exceptions are built for in Python.</p>
<pre><code># imports belong at the *top* of the file
import sys
class SomeDescriptiveError(Exception): pass
class SomeOtherSpecialError(Exception): pass
def func1(arg1 , arg2):
if (some_cond):
raise SomeDescriptiveError('Cannot frobnost... | 2 | 2016-07-19T12:37:47Z | [
"python",
"decorator",
"python-decorators"
] |
Use decorators to wrap all functions with "if func returned false, return false" | 38,458,105 | <p>I'm writing a very basic Python script based on a <code>main</code> function that sequentially calls other functions.</p>
<p>What I would like to do is to wrap all of the functions that are called from <code>main</code> with something like:</p>
<pre><code>result = func(*some_args):
if (result != True):
r... | -2 | 2016-07-19T12:07:31Z | 38,459,003 | <p>Since you <em>do</em> actually want the program to die when one of these errors occurs you might as well raise <code>SystemExit</code>. Here's a way to do it with a decorator.</p>
<pre><code>flag = 2
def die_on_not_True(func):
def wrapper(*args):
rc = func(*args)
if rc is not True:
... | 1 | 2016-07-19T12:44:41Z | [
"python",
"decorator",
"python-decorators"
] |
Pandas: How to delete string with some value | 38,458,115 | <p>I have df</p>
<pre><code> subdomain search_engine search_term
0 vk.com None None
1 vk.com None None
2 facebook.com None None
3 vk.com None None
4 ... | 0 | 2016-07-19T12:08:00Z | 38,458,848 | <p>I think this should do it:</p>
<pre><code>In[75]:df[df.search_term.str.strip()!='None']
Out[75]:
subdomain search_engine search_term
4 vk.com None vkontakte
</code></pre>
<p>or will this work:</p>
<pre><code>df[~df.search_term.str.match('None')]
</code></pre>
| 1 | 2016-07-19T12:38:21Z | [
"python",
"pandas"
] |
Pandas: How to delete string with some value | 38,458,115 | <p>I have df</p>
<pre><code> subdomain search_engine search_term
0 vk.com None None
1 vk.com None None
2 facebook.com None None
3 vk.com None None
4 ... | 0 | 2016-07-19T12:08:00Z | 38,459,196 | <p>What about this?</p>
<pre><code>df[~df['search_term'].str.contains("None")]
subdomain search_engine search_term
4 vk.com None vkontakte
</code></pre>
| 1 | 2016-07-19T12:53:38Z | [
"python",
"pandas"
] |
python error for large number mod operator | 38,458,132 | <p>I have some data which looks like this :</p>
<pre><code>353: 340122810048577428
354: 363117512048110005
355: 387632532919029223
356: 413766180933342362
357: 441622981929358437
358: 471314064268398780
359: 502957566506000020
360: 536679070310691121
361: 572612058898037559
362: 610898403751884101
363: 651688879997206... | 1 | 2016-07-19T12:08:28Z | 38,458,245 | <p>Don't use index variables like <code>i</code> in Python. We are in the 21st century.</p>
<pre><code>s = """353: 340122810048577428
354: 363117512048110005
355: 387632532919029223
356: 413766180933342362
357: 441622981929358437
358: 471314064268398780
359: 502957566506000020
360: 536679070310691121
361: 572612058898... | 2 | 2016-07-19T12:13:03Z | [
"python"
] |
python error for large number mod operator | 38,458,132 | <p>I have some data which looks like this :</p>
<pre><code>353: 340122810048577428
354: 363117512048110005
355: 387632532919029223
356: 413766180933342362
357: 441622981929358437
358: 471314064268398780
359: 502957566506000020
360: 536679070310691121
361: 572612058898037559
362: 610898403751884101
363: 651688879997206... | 1 | 2016-07-19T12:08:28Z | 38,458,261 | <p>This type of ambiguity is caused when you use floats. To make the calculation precise you should convert them to long or int and then go ahead. Assuming that you are reading this data from file.</p>
<pre><code>f = open('data.csv')
my_data = []
for line in f:
a = line.split(':')
my_data+=[[int(a[0]), int(a[1... | 1 | 2016-07-19T12:14:02Z | [
"python"
] |
python error for large number mod operator | 38,458,132 | <p>I have some data which looks like this :</p>
<pre><code>353: 340122810048577428
354: 363117512048110005
355: 387632532919029223
356: 413766180933342362
357: 441622981929358437
358: 471314064268398780
359: 502957566506000020
360: 536679070310691121
361: 572612058898037559
362: 610898403751884101
363: 651688879997206... | 1 | 2016-07-19T12:08:28Z | 38,458,367 | <p>You're using floating-point numbers with limited precision. Check this:</p>
<pre><code>>>> 502957566506000020 % 1000000
20
>>> float(502957566506000020)
5.02957566506e+17
>>> 502957566506000020.0
5.02957566506e+17
>>> float(502957566506000020) % 1000000
0.0
>>> 50295756... | 0 | 2016-07-19T12:18:34Z | [
"python"
] |
Passing an array from python to shared DLL, seeing access violation error | 38,458,185 | <p>The C function from DLL:</p>
<pre><code>Multi(double Freq, double Power, int ports[], int Size)
Need to pass the 3rd parameter as an array from python
</code></pre>
<p>Tried the following different codes:</p>
<p>A:</p>
<pre><code>import ctypes
pyarr = [2,3]
arr = (ctypes.c_int * len(pyarr))(*pyarr)
lp = CDLL(C... | 0 | 2016-07-19T12:10:44Z | 38,619,995 | <p>Specify your <code>argtypes</code>. Given this test.dll source:</p>
<pre><code>#include <stdio.h>
__declspec(dllexport) void Multi(double Freq, double Power, int ports[], int Size)
{
int i;
printf("%f %f\n",Freq,Power);
for(i = 0; i < Size; ++i)
printf("%d\n",ports[i]);
}
</code></pre... | 0 | 2016-07-27T17:52:26Z | [
"python",
"ctypes"
] |
Apply python logging format to each line of a message containing new lines | 38,458,288 | <p>I would like to include an id associated with the request for <strong>every</strong> log line in a log file. I have the mechanism for retrieving the request id via a logging filter working fine.</p>
<p>My problem is that when a log line contains a newline, the line of course get wrapped onto a "bare" line. Is there... | 1 | 2016-07-19T12:15:15Z | 38,458,626 | <p>Instead of:</p>
<pre><code>message = "blah\nblah"
logger.debug(message)
</code></pre>
<p>You could use</p>
<pre><code>message = "blah\nblah"
for line in message.split("\n"):
logger.debug(message)
</code></pre>
<p>The principle here is that each module should have its own responsibilities. If the logger has t... | 1 | 2016-07-19T12:28:57Z | [
"python",
"logging"
] |
Apply python logging format to each line of a message containing new lines | 38,458,288 | <p>I would like to include an id associated with the request for <strong>every</strong> log line in a log file. I have the mechanism for retrieving the request id via a logging filter working fine.</p>
<p>My problem is that when a log line contains a newline, the line of course get wrapped onto a "bare" line. Is there... | 1 | 2016-07-19T12:15:15Z | 38,458,877 | <p>Though this is not the best way to go about this, but this will help you without changing a lot of code.</p>
<pre><code>import logging
class CustomHandler(logging.StreamHandler):
def __init__(self):
super(CustomHandler, self).__init__()
def emit(self, record):
messages = record.msg.split(... | 4 | 2016-07-19T12:39:27Z | [
"python",
"logging"
] |
Control Firefox Download Prompt Using Selenium and Python | 38,458,811 | <p>Here is my code :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2);
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("b... | 0 | 2016-07-19T12:36:52Z | 38,459,166 | <p>I remember providing more mime-type variants usually helped to solve issues like this:</p>
<pre><code>mime_types = [
'text/plain',
'application/vnd.ms-excel',
'text/csv',
'application/csv',
'text/comma-separated-values',
'application/download',
'application/octet-stream',
'bin... | 1 | 2016-07-19T12:52:25Z | [
"python"
] |
Pandas DataFrame - Adding rows to df based on data in df | 38,458,822 | <p>Apologies for the not so specified title. I've been, unsuccesfully so far, trying to come up with a way to add new 'rows' to a pandas dataframe based on the contents of some of the columns. I hope to make it clear with an example. The data is mock-up data which hopefully suffices in painting the bigger picture.</p>
... | 0 | 2016-07-19T12:37:23Z | 38,459,239 | <p>The way I would approach this is the following:</p>
<ol>
<li><p>Iterate over every <code>car</code> column and keep only the records that have non-null values</p>
<pre><code>df_dict = {}
for car in ['Audi', 'Ferrari', 'Porsche' ,'Jaguar']:
non_nulls = df[ df.apply(lambda x: not pd.isnull(x[car] ), axis=1)]... | 1 | 2016-07-19T12:55:22Z | [
"python",
"pandas",
"dataframe"
] |
Pandas DataFrame - Adding rows to df based on data in df | 38,458,822 | <p>Apologies for the not so specified title. I've been, unsuccesfully so far, trying to come up with a way to add new 'rows' to a pandas dataframe based on the contents of some of the columns. I hope to make it clear with an example. The data is mock-up data which hopefully suffices in painting the bigger picture.</p>
... | 0 | 2016-07-19T12:37:23Z | 38,460,540 | <pre><code>import pandas as pd
df = pd.DataFrame({'Audi': ['R8', 'NA', 'RS7', 'NA', 'NA', 'S6', 'A8'],
'Country': ['FR', 'US', 'UK', 'RU', 'US', 'US', 'UK'],
'Cust-id': ['Cu1', 'Cu2', 'Cu3', 'Cu4', 'Cu5', 'Cu6', 'Cu7'],
'Ferrari': ['FF', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA'],
'Jaguar': ['NA', 'XF', 'NA', 'NA', 'Ford... | 0 | 2016-07-19T13:50:40Z | [
"python",
"pandas",
"dataframe"
] |
Flask Google Maps Infobox with multiple marker images leads to wrong information | 38,458,874 | <p>I have a Flask application where user can search for a room in a city by typing in the cityname.</p>
<p>When a cityname is typed in the user is redirected to a result page, where I use flask google maps to show available rooms on the map with markers.</p>
<p>I have two different marker images (for free users and f... | 0 | 2016-07-19T12:39:25Z | 38,459,125 | <p>This is just a guessâ but from looking at the source code of your search page showing the markers I can see duplicates of <code>var marker_0</code> and others. I presume you're iterating through the <code>markerlist</code> from a zero index, then the <code>markerlist_bezahlt</code> basing their <code>marker_x</co... | 0 | 2016-07-19T12:50:36Z | [
"python",
"google-maps",
"flask"
] |
MySQL #1054 error code for UPDATE query | 38,459,126 | <p>I currently have a MySQL table that looks like:</p>
<pre><code>mysql> SELECT * FROM settings;
+--------------+-------+
| name | value |
+--------------+-------+
| connected | 0 |
+--------------+-------+
</code></pre>
<p>and I'm trying to update the value with a timestamp for connected through Py... | 0 | 2016-07-19T12:50:37Z | 38,459,185 | <blockquote>
<p>1054, "Unknown column 'connected' in 'where clause'</p>
</blockquote>
<p>This error clearly states that <code>connected</code> is consider as a column name. </p>
<p>But here <code>connected</code> is string value that want to match with the columnname <code>name</code>.</p>
<p>So you need to place ... | 1 | 2016-07-19T12:53:13Z | [
"python",
"mysql"
] |
Conda uninstall one package and one package only | 38,459,186 | <p>When I try to uninstall <code>pandas</code> from my <code>conda</code> virtual env, I see that it tries to uninstall more packages as well:</p>
<pre><code>$ conda uninstall pandas
Using Anaconda Cloud api site https://api.anaconda.org
Fetching package metadata: ....
Solving package specifications: .........
Packag... | 0 | 2016-07-19T12:53:15Z | 38,463,294 | <p>You can use <code>conda remove --force</code>.</p>
<p>The documentation says:</p>
<pre><code>--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
... | 3 | 2016-07-19T15:54:21Z | [
"python",
"pip",
"anaconda",
"conda"
] |
Python HTTPServer - get HTTP body | 38,459,216 | <p>I wrote a HTTP server using python, but I do not know how to get the HTTP body. what should I do to get the HTTP body?</p>
<p>here is my code:</p>
<pre><code>from http.server import HTTPServer,BaseHTTPRequestHandler
class MyHTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
print("connect from ",... | 0 | 2016-07-19T12:54:29Z | 38,459,402 | <p>Having a request body in a GET request is not a good practice, as its discussed here: <a href="https://stackoverflow.com/questions/978061/http-get-with-request-body">HTTP GET with request body</a></p>
<p>Instead, you can <strong>change your method to POST</strong> and check there the <code>BaseHTTPRequestHandler</c... | 0 | 2016-07-19T13:01:48Z | [
"python",
"httpserver"
] |
Python Glueviz - is there a way to replace ie update the imported data | 38,459,234 | <p>I am using Glueviz 0.7.2 as part of the Anaconda package, on OSX. Glueviz is a data visualization and exploration tool. </p>
<p>I am regularly regenerating an updated version of the same data set from an external model, then importing that data set into Glueviz. </p>
<p>Currently I can not find a way to have Gluev... | 0 | 2016-07-19T12:55:10Z | 38,460,641 | <p>As it turns out, the data is not stored in the Glueviz session file, but rather loaded fresh each time the saved session is opened from the original data source file. </p>
<p>Hence the solution is simple: Replace the data source file with a new file (of the same type) in with the updated data. </p>
<p>The update... | 0 | 2016-07-19T13:56:15Z | [
"python"
] |
python for x in y loop does not complete | 38,459,241 | <p>trying to make a script that extracts song information from a playlist.</p>
<p>This is the beginning of my playlist:</p>
<pre><code>#EXTM3U
#EXTINF:402,Junior's Eyes - Black Sabbath
/Users/omitted/Black Sabbath/[1978] Never Say Die!/03. Junior's Eyes.mp3
#EXTINF:327,After Forever - Black Sabbath
/Users/omitted/Bla... | 0 | 2016-07-19T12:55:34Z | 38,459,565 | <p>There are some lines in your file where the regex fails to match. In that case, the Match object is <code>None</code>, and <code>None</code> doesn't have a <code>.group()</code> property, causing a <code>AttributeError</code> to be raised. You should be seeing that error in your console.</p>
<p>You could do somethi... | 2 | 2016-07-19T13:08:13Z | [
"python",
"for-loop"
] |
ImportError: libboost_python.so.1.41.0: cannot open shared object file: No such file or directory | 38,459,254 | <p>I am trying to install PyV8 to debian (I tried to ubuntu too)according the steps here <a href="http://www.wikisecure.net/importing-pyv8-engine-into-python-v2-7-the-easy-way/" rel="nofollow">http://www.wikisecure.net/importing-pyv8-engine-into-python-v2-7-the-easy-way/</a></p>
<p>However I always get <em>ImportError... | 0 | 2016-07-19T12:55:54Z | 38,459,517 | <p>Try installing libboost-all-dev, the file you're missing should be in there.</p>
<p>For clarity: What actually worked was copying and renaming a later version of libboost to 1.41. I would not recommend this as a fist solution, if getting the correct version is an option.</p>
| 0 | 2016-07-19T13:06:07Z | [
"python",
"debian",
"boost-python",
"pyv8"
] |
decorators execution of python | 38,459,350 | <pre><code>registry = []
def register(func):
print('running register(%s)' % func)
registry.append(func)
return func
@register
def f1():
print('running f1()')
@register
def f2():
print('running f2()')
def f3():
print('running f3()')
def main():
print('running main()')
print('registry ->', registry)
f1()
... | 0 | 2016-07-19T12:59:39Z | 38,479,086 | <p>A decorator is a higher-order function which takes a function as input and returns a function as output. Decorator syntax is a way of calling this higher order function. </p>
<p>The lines</p>
<pre><code>@register
def f1():
print('running f1()')
</code></pre>
<p>are <em>equivalent</em> to the lines</p>
<pre><cod... | 1 | 2016-07-20T10:44:29Z | [
"python",
"python-decorators"
] |
Application slows down over time - Java + Python | 38,459,380 | <p>This is a difficult one to explain, and not hopeful for a single, simple answer, but thought it's worth a shot. Interested in what might slow down a long Python job that interacts with a Java application.</p>
<p>We have an instance of Tomcat running a fairly complex and robust webapp called <a href="http://fedorar... | 0 | 2016-07-19T13:00:53Z | 38,459,680 | <p>Well, instead of looking into obscure GC settings, you might want to start managing memory explicitly, so the GC doesn't affect your execution that much.</p>
| -1 | 2016-07-19T13:12:50Z | [
"java",
"python",
"tomcat",
"garbage-collection",
"fedora-commons"
] |
Application slows down over time - Java + Python | 38,459,380 | <p>This is a difficult one to explain, and not hopeful for a single, simple answer, but thought it's worth a shot. Interested in what might slow down a long Python job that interacts with a Java application.</p>
<p>We have an instance of Tomcat running a fairly complex and robust webapp called <a href="http://fedorar... | 0 | 2016-07-19T13:00:53Z | 38,459,800 | <p>You say you suspect GC as the problem, but you show no GC metrics. Put your program through a profiler and see why the GC is overloaded. It is hard to solve a problem without identifying the cause.</p>
<p>Once you have the found where the problem lies, likely you will need to change the code instead of just tweak... | 0 | 2016-07-19T13:18:36Z | [
"java",
"python",
"tomcat",
"garbage-collection",
"fedora-commons"
] |
Application slows down over time - Java + Python | 38,459,380 | <p>This is a difficult one to explain, and not hopeful for a single, simple answer, but thought it's worth a shot. Interested in what might slow down a long Python job that interacts with a Java application.</p>
<p>We have an instance of Tomcat running a fairly complex and robust webapp called <a href="http://fedorar... | 0 | 2016-07-19T13:00:53Z | 38,526,310 | <p>Thanks to all for the suggestions around GC and Tomcat analysis. Turns out, the slowdown was entirely due to ways that Fedora Commons builds digital objects. I was able to isolate this by creating an extremely simple digital object, iteratively adding near zero-size datastreams and watching the progress. You can ... | 0 | 2016-07-22T12:21:42Z | [
"java",
"python",
"tomcat",
"garbage-collection",
"fedora-commons"
] |
Descartes product with repetition | 38,459,401 | <p>So i wanted to make a function that takes positive integer <strong><code>n</code></strong> and returns bunch of <strong><code>n-tuples</code></strong>, filled with all possible combinations of <code>True/False (1/0)</code>, for example:</p>
<pre><code>f(1) = (0,),(1,)
f(2) = (0, 0), (0, 1), (1, 0), (1, 1)
</code>... | 0 | 2016-07-19T13:01:47Z | 38,459,546 | <p>What you describe is not a powerset but a Descartes product with repetition. Use <a href="https://docs.python.org/2.7/library/itertools.html#itertools.product"><code>itertools.product</code></a>:</p>
<pre><code>import itertools
def fill(n):
return itertools.product((0,1), repeat=n)
print(list(fill(3)))
# [(0,... | 8 | 2016-07-19T13:07:24Z | [
"python",
"python-3.x",
"combinatorics"
] |
Flask App outputting Excel file | 38,459,445 | <p>Here's what I currently have... My application is outputting an excel file, I just don't know how to output an excel file that has MY DATA in it. Right now it's just outputting an excel file that just contains "test" in Cell A1, and I know that's because of my line that says <code>strIO.write('test')</code>. How can... | -1 | 2016-07-19T13:03:20Z | 38,459,977 | <p>The <code>send_file</code> function in flask sends the file you are specifying in the first argument (compare to the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.send_file" rel="nofollow">documentation</a>). You put there <code>strIO</code> which means that the string you saved there will get send. If you wa... | 1 | 2016-07-19T13:26:34Z | [
"python",
"flask",
"openpyxl"
] |
converting a string to a list from a text file | 38,459,467 | <pre><code>with open('task3randomtext.txt', 'r') as f:
text = f.readlines()
</code></pre>
<p>this is the code I use to take text from a text file and read it into my program but it reads it in as a list an will not let me split it to convert it to a array. Is there any other way or splitting it or reading it in.</... | -6 | 2016-07-19T13:04:19Z | 38,619,021 | <p>If you look at the Python documentation (<a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">which you should</a>!) you can see that readlines() returns a list containing every line in the file. To then split each line, you could do something along the lines of:</p>
<pre><code>with open('ti... | 0 | 2016-07-27T16:53:51Z | [
"python"
] |
A function with itself as a default argument | 38,459,668 | <p>Defaults are parsed at definition. So this will not work</p>
<pre><code>def f(x, func = f):
if x<1:
return x
else:
return x + func(x-1)
</code></pre>
<p>I did find a way, though. I start with some dummy function</p>
<pre><code>def a(x):
return x
def f(x, func=a):
if x < 1:
... | 1 | 2016-07-19T13:12:19Z | 38,463,058 | <p>To elaborate on Andrea Corbellini's suggestion, you can do something like this:</p>
<pre><code>def f(x, func=None):
if func is None:
func = f
if x < 1:
return x
else:
return x + func(x-1)
</code></pre>
<p>It is a pretty standard idiom in Python to implement the actual defaul... | 3 | 2016-07-19T15:42:32Z | [
"python"
] |
Specific Sort of elements to add in new list Python/Django | 38,459,780 | <p>I have this : </p>
<pre><code>[
[{ 'position': 1, 'user_id': 2, 'value': 4, 'points': 100}],
[{ 'position': 2, 'user_id': 6, 'value': 3, 'points': 88}],
[{ 'position': 3, 'user_id': 5, 'value': 2, 'points': 77}],
[{ 'position': 4, 'user_id': 7, 'value': 1, 'points': 66}],
[{ 'position': 5, 'user_id': 3, '... | 1 | 2016-07-19T13:17:50Z | 38,461,599 | <p>This is basically only an update of <a href="http://stackoverflow.com/questions/38441568/populating-a-list-in-a-specific-way/38443636#38443636">my answer</a> to <a href="http://stackoverflow.com/questions/38441568/populating-a-list-in-a-specific-way">your original question</a>.</p>
<pre><code>a = [
[{ 'position... | 1 | 2016-07-19T14:38:21Z | [
"python",
"django",
"sorting",
"populate"
] |
substract values from column in dataframe if another column in datafram matches some value using pandas | 38,459,794 | <p>say I have two matrix original and reference </p>
<pre><code>import pandas as pa
print "Original Data Frame"
# Create a dataframe
oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]}
a = pa.DataFrame(oldcols)
print "Original Table:"
print a
print "Reference Table:"
b = pa.DataFrame({'co... | 1 | 2016-07-19T13:18:28Z | 38,459,939 | <p>This should work:</p>
<pre><code>a['col3'] + a['col2'].map(b.set_index('col2')['col3'])
Out[94]:
0 11
1 22
2 13
3 24
dtype: int64
</code></pre>
<p>Or this:</p>
<pre><code>a.merge(b, on='col2', how='left')[['col3_x', 'col3_y']].sum(axis=1)
Out[110]:
0 11
1 22
2 13
3 24
dtype: int64
</code... | 3 | 2016-07-19T13:24:56Z | [
"python",
"pandas",
"data-science"
] |
opening google searches with python | 38,459,894 | <p>I want to make my program open first 5 searches of google. Currently I have only simple google search generator which opens a search. Is there a way to open 5 searches into new tabs then close them ?</p>
<pre><code>dict = readdict()
lenght = len(dict)
search_term=""
for _ in range(self.variable2.get()):
skc=ra... | 2 | 2016-07-19T13:22:55Z | 38,462,948 | <p>Use the <a href="https://docs.python.org/3/library/webbrowser.html#webbrowser.open_new_tab" rel="nofollow"><code>open_new_tab</code></a> function:</p>
<pre><code>import webbrowser
search_terms = []
# ... construct your list of search terms ...
for term in search_terms:
url = "https://www.google.com.tr/search?... | 1 | 2016-07-19T15:37:20Z | [
"python",
"google-chrome"
] |
How to output a long dictionary in a pandas dataframe column in its entirety? | 38,459,901 | <p>I have a pandas dataframe with rather long dictionaries in one column.</p>
<p>Example:</p>
<pre><code>import pandas as pd
D = [[{'a':'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','b':'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'}]]
df = pd.DataFrame.from_dict(D)
print df[0]
</code></pre>
<p>Which leads to this output:</p>
<pre><code... | 0 | 2016-07-19T13:23:13Z | 38,459,943 | <p>this should work:</p>
<pre><code>In[6]:df[0].values
Out[6]: array([ {'a': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'b': 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'}], dtype=object)
</code></pre>
| 1 | 2016-07-19T13:25:08Z | [
"python",
"pandas",
"dictionary"
] |
How to output a long dictionary in a pandas dataframe column in its entirety? | 38,459,901 | <p>I have a pandas dataframe with rather long dictionaries in one column.</p>
<p>Example:</p>
<pre><code>import pandas as pd
D = [[{'a':'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','b':'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'}]]
df = pd.DataFrame.from_dict(D)
print df[0]
</code></pre>
<p>Which leads to this output:</p>
<pre><code... | 0 | 2016-07-19T13:23:13Z | 38,460,207 | <pre><code>D = [[{'a':'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','b':'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'}]]
print D[0][0]
</code></pre>
| 0 | 2016-07-19T13:36:18Z | [
"python",
"pandas",
"dictionary"
] |
Rename downloaded files selenium | 38,459,972 | <p>I'm using selenium to automatically download files in csv format from this page:</p>
<p><a href="https://catalog.data.gov/dataset?tags=crime" rel="nofollow">https://catalog.data.gov/dataset?tags=crime</a></p>
<p>This is the code I'm using:</p>
<pre><code>profile = webdriver.FirefoxProfile()
profile.set_preference... | 1 | 2016-07-19T13:26:17Z | 38,460,110 | <p><em>You don't have control over the download file naming through selenium</em>.</p>
<p>What you can do is to use a directory watcher/observer to detect when the file is downloaded and then rename it accordingly. Please see <a href="http://stackoverflow.com/a/34338926/771848">this answer</a> containing more follow-u... | 1 | 2016-07-19T13:32:16Z | [
"python",
"selenium",
"web-scraping"
] |
How to get the tokens from an NLTK Tree? | 38,460,049 | <p>So I have this tree returned to me</p>
<pre><code>Tree('S', [('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN'), (',', ','), Tree('PERSON', [('Stackoverflow', 'NNP'), ('Users', 'NNP')]), ('.', '.')])
</code></pre>
<p>I can turn this into a nice python list like so</p>
<pre><code>sentence = "This is a test... | 1 | 2016-07-19T13:29:44Z | 38,462,574 | <pre><code>>>> from nltk import Tree
>>> yourtree = Tree('S', [('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN'), (',', ','), Tree('PERSON', [('Stackoverflow', 'NNP'), ('Users', 'NNP')]), ('.', '.')])
>>> yourtree.leaves()
[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN'), ... | 6 | 2016-07-19T15:20:47Z | [
"python",
"list",
"python-2.7",
"nlp",
"nltk"
] |
How to replace only a certain part of a list? | 38,460,154 | <p>How do I replace apple in the beginning of each string in the list to orange?</p>
<p>Here is what I have tried:</p>
<pre><code>appleList = ['apple_00', 'apple_01', 'apple_02', 'apple_03']
appleList = ['orange' if 'apple' in appleList]
print appleList
</code></pre>
<p><strong>Output:</strong> <code>['apple_00', ... | -1 | 2016-07-19T13:34:24Z | 38,460,224 | <p>Use <code>replace</code> when an item contains <code>Apple</code>. </p>
<p>This does it:</p>
<pre><code>r = [x.replace('Apple', 'Orange') for x in Register]
print(r)
# ['Orange_00', 'Orange_01', 'Orange_02', 'Orange_03']
</code></pre>
| 0 | 2016-07-19T13:36:57Z | [
"python",
"list"
] |
How to replace only a certain part of a list? | 38,460,154 | <p>How do I replace apple in the beginning of each string in the list to orange?</p>
<p>Here is what I have tried:</p>
<pre><code>appleList = ['apple_00', 'apple_01', 'apple_02', 'apple_03']
appleList = ['orange' if 'apple' in appleList]
print appleList
</code></pre>
<p><strong>Output:</strong> <code>['apple_00', ... | -1 | 2016-07-19T13:34:24Z | 38,460,231 | <p>You should use the <code>replace</code> method to modify the strings inside the list:</p>
<pre><code>>>> my_list = ['Apple_00', 'Apple_01', 'Apple_02', 'Apple_03']
>>> print([s.replace('Apple', 'Orange') for s in my_list])
</code></pre>
<p>this will print</p>
<pre><code>['Orange_00', 'Orange_01'... | 3 | 2016-07-19T13:37:14Z | [
"python",
"list"
] |
How to replace only a certain part of a list? | 38,460,154 | <p>How do I replace apple in the beginning of each string in the list to orange?</p>
<p>Here is what I have tried:</p>
<pre><code>appleList = ['apple_00', 'apple_01', 'apple_02', 'apple_03']
appleList = ['orange' if 'apple' in appleList]
print appleList
</code></pre>
<p><strong>Output:</strong> <code>['apple_00', ... | -1 | 2016-07-19T13:34:24Z | 38,460,336 | <p>You're checking if certain elements in the list are the string <code>'Apple'</code>, which is obviously never <code>True</code>. you can do it like this:</p>
<pre><code>Register = ['Apple_00', 'Apple_01', 'Apple_02', 'Apple_03']
New_Register = []
for entry in Register:
New_Register.append(entry.replace('Apple'... | 0 | 2016-07-19T13:41:44Z | [
"python",
"list"
] |
Pythonic way to create dictionary from bottom level of nested dictionary | 38,460,244 | <p>I have a dictionary which contains nested dictionaries, like this:</p>
<pre><code>example_dict = {
"test1": "string here",
"test2": "another string",
"test3": {
"test4": 25,
"test5": {
"... | 0 | 2016-07-19T13:37:50Z | 38,460,334 | <p>With a bit of recursion it's fairly simple to do:</p>
<pre><code>example_dict = {
"test1": "string here",
"test2": "another string",
"test3": {
"test4": 25,
"test5": {
"test7": "very nested."
},
"test6": "yep, another string"
},
}
def flatten(dictionary)... | 5 | 2016-07-19T13:41:44Z | [
"python",
"dictionary"
] |
Raster values extraction from Shapefile | 38,460,314 | <p>I have a raster file which contains polygons or lines I draw for mapping features. What I want to do now is extract along these polygons/lines the values from raster data and plot a graph of the elevations along the pixels. As in <a href="http://stackoverflow.com/questions/7878398/how-to-extract-an-arbitrary-line-of... | -1 | 2016-07-19T13:40:51Z | 38,749,651 | <p>You will have to decide on a sampling interval. You can add points along the line/polygon edges at the desired interval, and then extract the raster value at those points (using gdal/numpy). </p>
<p>You need to be mindful of the relation between your raster resolution and sampling interval to avoid artifacts from "... | 0 | 2016-08-03T17:00:08Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"gdal"
] |
python xsd within soap response | 38,460,347 | <p>I'm using spyne for generating web services in the server side with python to communicate with an excel client (xmla plugin), and I have some difficulties to generate a soap response that match with the client request,
what I want is a soap response like this ( under <strong>root</strong> tag a <strong>schema</stron... | 0 | 2016-07-19T13:42:19Z | 38,481,321 | <p>You need to switch to bare mode and return <code>AnyXml</code> like this:</p>
<pre><code>class DiscoverRequest(ComplexModel):
RequestType = Unicode
Restrictions = Restrictionlist
Properties = Propertielist
class HelloWorldService(ServiceBase):
@rpc(DiscoverRequest, _returns=AnyXml, _body_style="ba... | 0 | 2016-07-20T12:28:01Z | [
"python",
"soap",
"spyne",
"xmla"
] |
Issue with Updating Global/Local Variables | 38,460,445 | <p>Take a look at the example code below. There is a main window, which calls the function <code>fun2</code> to display the value of variable <code>a</code> (as a label w/ text). At the same time, a menu item on the main window launches a secondary window (function <code>fun1</code>) with two buttons. I am trying to fi... | 0 | 2016-07-19T13:46:20Z | 38,460,716 | <p>The <code>global</code> statement must be used <em>in the function that assigns to the variable</em>. It does not carry over into sub-functions, which is why it didn't have an effect in <code>fun1</code>. You have to add it to both <code>var_yes</code> and <code>var_no</code>.</p>
| 2 | 2016-07-19T13:59:11Z | [
"python",
"global-variables"
] |
Issue with Updating Global/Local Variables | 38,460,445 | <p>Take a look at the example code below. There is a main window, which calls the function <code>fun2</code> to display the value of variable <code>a</code> (as a label w/ text). At the same time, a menu item on the main window launches a secondary window (function <code>fun1</code>) with two buttons. I am trying to fi... | 0 | 2016-07-19T13:46:20Z | 38,460,773 | <p>What you are doing wrong is thinking that global variables are a good idea. Then not understanding how to use them. In python you create a global by assignment in the module level scope. You have done that by creating a value and calling it <code>a</code></p>
<p>In each function which needs to write `a' you need... | 0 | 2016-07-19T14:02:20Z | [
"python",
"global-variables"
] |
'Operation Denied' Error when deploying an Elastic Beanstalk app using awsebcli | 38,460,457 | <p>I'm trying to deploy a Django application onto Elastic Beanstalk for the first time. I've been following two tutorials <a href="https://realpython.com/blog/python/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/" rel="nofollow">here</a> and <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/d... | 1 | 2016-07-19T13:46:48Z | 38,461,850 | <p>So it turns out the issue was that my security keys were "out of date". This is due to my IAM permissions being changed between the generation of the first set of keys and the attempt to deploy my application.</p>
<p>Generating a new set of keys solved the problem.</p>
| 0 | 2016-07-19T14:48:24Z | [
"python",
"django",
"amazon-web-services",
"amazon-ec2",
"elastic-beanstalk"
] |
Scipy installation failed with error code 1 | 38,460,477 | <p>I'm trying to install Scipy through pip.
when doing</p>
<pre><code>pip install scipy
</code></pre>
<p>I get the error </p>
<pre><code> failed with error code 1 in C:\Users\MYNAME\AppData\Local\Temp\pip-build-c3n82mii\Scipy\
</code></pre>
<p>I got pip updated to newest version (8.1.2) and python 3.5.2. any help?<... | 0 | 2016-07-19T13:47:48Z | 38,473,318 | <p>The most likely problem is the lack of the appropriate compiler(s) on your machine and its paths - scipy uses a lot of C code for speed and pip will by default, if there isn't a wheel available for SciPy that matches your combination of python and OS, download the source and try to build it. </p>
<p>I have had a lo... | 1 | 2016-07-20T05:56:40Z | [
"python",
"scipy",
"pip"
] |
Python, Tk and OptionMenu: how to sort a drop down list? | 38,460,590 | <p>I want to make a drop down list with tk and OptionMenu. I want to show a string to the user ("10 us", "40 us"...) and return a number (0, 1,...) which is a parameter that I send to a variable. It works well, but it's not sorted. I want to sort the list like the variable "lst1".</p>
<p><a href="http://i.stack.imgur.... | -1 | 2016-07-19T13:53:36Z | 38,460,771 | <p>The issue is that you're using a dictionary as a list, and dictionaries don't have any notion of order. Two ways you could do it; both are pretty straightforward.</p>
<h1>Way 1: Just use sorted keys</h1>
<p>You don't have to change much, just when you pass in <code>lst1.keys()</code>, you instead pass in <code>sor... | 2 | 2016-07-19T14:02:19Z | [
"python",
"list",
"tkinter"
] |
Change superclass without modifying original code | 38,460,591 | <p>I'm writing an application in GTK. We have the need to support both VTE terminal API 2.90 and 2.91. So I created a silly compatibility layer between the two in a module called 'compatibility'. It looks like this. </p>
<pre><code>import gi
try:
gi.require_version('Vte', '2.91')
vte_version = '2.91'
except Va... | 0 | 2016-07-19T13:53:39Z | 38,461,237 | <p>I really think there is a better way, which was why I originally posted as a comment rather than an answer, but to illustrate how you might create a dynamic module and add a class to it, consider the following:</p>
<pre><code>class AlternativeCounter:
def __init__(self, *args):
pass
def __repr__(se... | 1 | 2016-07-19T14:22:39Z | [
"python",
"oop"
] |
Xpath on request response returns empty list | 38,460,682 | <p>I'm trying to learn web scraping.
I need fetch all URLs from this page- <a href="http://www.99acres.com/rent-property-in-chennai-ffid" rel="nofollow">http://www.99acres.com/rent-property-in-chennai-ffid</a>?</p>
<p>First I need to sort the entries by newest first for which I replicate the getresults_ajax POST requ... | 2 | 2016-07-19T13:58:01Z | 38,469,089 | <p>If you print the text you can see it is a json response:</p>
<pre><code>{"html_ysf":" <div class=\"srp-ysfWrap boxSize\">\n\n\n\n <diV. etc.............
</code></pre>
<p>So to get what you want just extract the interesting html using the <em>html2 key</em>:</p>
<pre><code>req = requests.post(ur... | 1 | 2016-07-19T21:48:48Z | [
"python",
"xpath",
"web-scraping"
] |
How do I link accounts in the Google Adwords API using just a customer ID? | 38,460,718 | <p>I'm having a very hard time understanding Google's API documentation and was hoping for some help here.</p>
<p>To me, as an extremely new developer, the Google API documentation makes no sense whatsoever.</p>
<p>I am using the google adwords Python library, and this code may be useful: <a href="https://github.com/... | 0 | 2016-07-19T13:59:21Z | 38,511,109 | <p>To link an existing account into your MCC account, you also need to use the <code>ManagedCustomerService</code>, specifically the <code>mutateLink</code> method.
In Python, it would look something like this:</p>
<pre><code># Create the service object
managed_customer_service = client.GetService('ManagedCustomerServ... | 0 | 2016-07-21T17:51:20Z | [
"python",
"google-adwords"
] |
How does one store a Pandas DataFrame as an HDFS PyTables table (or CArray, EArray, etc.)? | 38,460,744 | <p>I have the following pandas dataframe:</p>
<pre><code>import pandas as pd
df = pd.read_csv(filename.csv)
</code></pre>
<p>Now, I can use <code>HDFStore</code> to write the <code>df</code> object to file (like adding key-value pairs to a Python dictionary):</p>
<pre><code>store = HDFStore('store.h5')
store['df'] =... | 1 | 2016-07-19T14:00:49Z | 38,460,810 | <p>common part - create or open existing HDFStore file:</p>
<pre><code>store = pd.HDFStore('store.h5')
</code></pre>
<p>Try this if you want to have indexed <strong>all</strong> columns:</p>
<pre><code>store.append('key_name', df, data_columns=True)
</code></pre>
<p>or this if you want to have indexed just a subset... | 1 | 2016-07-19T14:04:03Z | [
"python",
"pandas",
"hdf5",
"pytables",
"hdf5storage"
] |
django filter queryset based on __str__ of model | 38,460,768 | <p>I have the following model:</p>
<pre><code>class Subspecies(models.Model):
species = models.ForeignKey(Species)
subspecies = models.CharField(max_length=100)
def __str__(self):
return self.species.species_english+" "+self.species.species+" "+self.subspecies
def __unicode__(self):
r... | 0 | 2016-07-19T14:02:13Z | 38,460,910 | <p>Filter generates a query to be executed in DB.</p>
<p><code>__str__</code> is run in Python interpreter. You can't call it from DB.
SO the short answer is "no, you can't". You have to filter it manually, using <code>filter</code> built-in function, for example.</p>
| 1 | 2016-07-19T14:08:19Z | [
"python",
"django",
"filter",
"django-queryset"
] |
Retrieving the value of specific attribute using E Tree | 38,460,824 | <p>I have an XML document through which I want ti retrieve the value of specific attribute using e tree.
Below is the document-snippet I have:</p>
<pre><code>-<orcid-message>
<message-version>1.2</message-version>
-<orcid-profile type="user">
-<orcid-identifier>
<uri&... | 0 | 2016-07-19T14:04:35Z | 38,462,944 | <p>You can use the Element class' <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.find" rel="nofollow">find</a> method with the path to the element you wish to pick out, for example:</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse("filename")
root ... | 0 | 2016-07-19T15:37:06Z | [
"python",
"xml",
"python-2.7"
] |
Sorting the xml file based on xml text attribute | 38,460,831 | <p>I have a xml file in which elements are present in some random order. I have to compare these files but due to the change in order of elements, it requires manual effort. </p>
<p>I am looking for some way to sort these files. Can someone please give me some pointers/approach to this problem. I tried reading the doc... | 1 | 2016-07-19T14:04:46Z | 38,467,785 | <p>If you want to sort the children by the text, just find the legal nodes and sort the children using <em>child.text</em> as the key:</p>
<pre><code>x = """<root>
<attribute Name="attr2">
<v>
<cstat>
<s>nObjDef2</s>
<... | 0 | 2016-07-19T20:20:27Z | [
"python",
"xml",
"lxml"
] |
Sorting the xml file based on xml text attribute | 38,460,831 | <p>I have a xml file in which elements are present in some random order. I have to compare these files but due to the change in order of elements, it requires manual effort. </p>
<p>I am looking for some way to sort these files. Can someone please give me some pointers/approach to this problem. I tried reading the doc... | 1 | 2016-07-19T14:04:46Z | 38,468,091 | <p>Consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the special purpose language designed specifically to manipulate and transform XML files. Python's lxml can run XSLT 1.0 scripts. Specifically, XSLT maintains the <a href="http://www.w3schools.com/xsl/el_sort.asp" rel="nofollow"><code><xsl:... | 0 | 2016-07-19T20:39:21Z | [
"python",
"xml",
"lxml"
] |
Intercept the request send from an ios app to a service, from Pyhon and Appium | 38,460,857 | <p>I am working on a mac and I am trying to automate a certain app on an iPhone and at some point I am required to verify the request that the app sends to a service (more exactly a json request). I am using Appium to connect to the phone and Python to write the scripts.</p>
<p>I am aware that instruments has a networ... | 0 | 2016-07-19T14:05:39Z | 38,462,895 | <p>I had the similar question few months back and some dumbs who are not even remotely concerned with Automation gave down votes to me as well. But anyways you have two solutions for this problem. I am not sure about instruments functionality so will not comment on it.</p>
<p>1) Use idevicesyslog to basically look at ... | 1 | 2016-07-19T15:34:28Z | [
"python",
"ios",
"json",
"networking",
"appium"
] |
Python file search program not fast enough | 38,460,908 | <p>I wrote the following code for searching a file on your computer:</p>
<pre><code>import os, sys
import win32api
x=raw_input("Enter file name: ")
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
for drive in drives:
for folderName, subfolders, filenames in os.walk(drive):
f... | 0 | 2016-07-19T14:08:15Z | 38,461,331 | <p>You can't enhance this program much - any static file search will have to do that sort of thing. By adding a lot of complexity and making it parallel, you could get it to work faster by walking different portions of the file system at a time, and possibly enabling a "lucky hit" earlier. </p>
<p>Applications and uti... | 1 | 2016-07-19T14:26:27Z | [
"python",
"file-search"
] |
Python file search program not fast enough | 38,460,908 | <p>I wrote the following code for searching a file on your computer:</p>
<pre><code>import os, sys
import win32api
x=raw_input("Enter file name: ")
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
for drive in drives:
for folderName, subfolders, filenames in os.walk(drive):
f... | 0 | 2016-07-19T14:08:15Z | 38,505,686 | <p>Reducing the number of print statements should increase speed significantly. If you need to trace the files, you could write your results to a log file instead.</p>
| 1 | 2016-07-21T13:31:46Z | [
"python",
"file-search"
] |
remove symbols from string | 38,460,917 | <p>I have a file like:</p>
<pre><code>@HWI
ABCDE
+
@HWI7
EFSA
+
???=AF
GTEY@JF
GVTAWM
</code></pre>
<p>I want to keep only the strings ( so remove everything that contains a symbol ) </p>
<p>I tried :</p>
<pre><code>import numpy as np
arr = np.genfromtxt(f, dtype=str)
for line in np.nditer(arr):
if np.core.def... | 1 | 2016-07-19T14:08:42Z | 38,461,017 | <p>W/ numpy:</p>
<p>There is an isalpha() and isnumeric() function to numpy as well. They can be read about <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow">here</a>.</p>
<p>Without numpy, you could try this regex:</p>
<p><code>re.sub(r'[^\w]', ' ', s)</code></p>
<p>where <code>... | 0 | 2016-07-19T14:13:06Z | [
"python",
"numpy"
] |
remove symbols from string | 38,460,917 | <p>I have a file like:</p>
<pre><code>@HWI
ABCDE
+
@HWI7
EFSA
+
???=AF
GTEY@JF
GVTAWM
</code></pre>
<p>I want to keep only the strings ( so remove everything that contains a symbol ) </p>
<p>I tried :</p>
<pre><code>import numpy as np
arr = np.genfromtxt(f, dtype=str)
for line in np.nditer(arr):
if np.core.def... | 1 | 2016-07-19T14:08:42Z | 38,461,481 | <p>This is my solution :</p>
<pre><code>import numpy as np
arr = np.genfromtxt('text.txt', dtype=str)
test = np.core.defchararray.isalpha(arr) #Create a mask : True = only str and False = not only str
print arr[test] #Use the mask on arr and it will print only good values
</code></pre>
<p>Don't use <code>if</code>... | 1 | 2016-07-19T14:33:25Z | [
"python",
"numpy"
] |
Regex-matching a dictionary efficiently in Python | 38,460,918 | <p>I have a dictionary of word:count pairs in my Python script. From this dictionary, I would like to extract the entries matching any item in a list of strings. </p>
<p>I have found a working solution using regular expressions (see below), but it takes <strong>forever</strong> (~ 10 hours for a run). I feel there mus... | 0 | 2016-07-19T14:08:43Z | 38,461,483 | <p>Compiling the regular expressions once rather than each time you use them would probably gain you a fair bit of performance improvement. So you'd have something like:</p>
<pre><code>import re
dicti={'the':20, 'a':10, 'over':2}
patterns=['the', 'an?']
regex_matches = [re.compile("^"+pattern+"$").match for pattern ... | 1 | 2016-07-19T14:33:28Z | [
"python",
"regex",
"list",
"dictionary",
"list-comprehension"
] |
Regex-matching a dictionary efficiently in Python | 38,460,918 | <p>I have a dictionary of word:count pairs in my Python script. From this dictionary, I would like to extract the entries matching any item in a list of strings. </p>
<p>I have found a working solution using regular expressions (see below), but it takes <strong>forever</strong> (~ 10 hours for a run). I feel there mus... | 0 | 2016-07-19T14:08:43Z | 38,462,941 | <p>What about joining the dict.keys in a single string to reduce number of loops? It seems faster here:</p>
<pre><code>import re, random, string
#Generate random dictionary
dicti={''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5)):i for i in xrange(1000000)}
#Using ; as separator, you c... | 1 | 2016-07-19T15:37:01Z | [
"python",
"regex",
"list",
"dictionary",
"list-comprehension"
] |
Regex-matching a dictionary efficiently in Python | 38,460,918 | <p>I have a dictionary of word:count pairs in my Python script. From this dictionary, I would like to extract the entries matching any item in a list of strings. </p>
<p>I have found a working solution using regular expressions (see below), but it takes <strong>forever</strong> (~ 10 hours for a run). I feel there mus... | 0 | 2016-07-19T14:08:43Z | 38,465,673 | <p>Your problem looks very much like the ad blocking problem. The <a href="https://adblockplus.org/filter-cheatsheet" rel="nofollow">Easylist</a> is similar to your regex list but includes urls and url patterns.</p>
<p>In general regular expression matching is relatively fast. Yet, as you have already seen, it is not ... | 1 | 2016-07-19T18:11:44Z | [
"python",
"regex",
"list",
"dictionary",
"list-comprehension"
] |
How do I parse request data in Python-Django? | 38,460,927 | <p>I am getting the django request.POST in the format :
{
'a': 1,
'b[c]': 2,
'b[d]': 3,
'b[e]': 4,
'f[g]': 5,
'f[h]': 6
}</p>
<p>How do i parse it so that I get a dict in the format:
{
'a': 1,
'b': {
'c': 2,
'd': 3,
'e': 4
},
'f': {
'g': 5,
... | 1 | 2016-07-19T14:09:05Z | 38,461,687 | <p>You could use something similar to this:</p>
<pre><code>d = { 'a': 1, 'b[c]': 2, 'b[d]': 3, 'b[e]': 4, 'f[g]': 5, 'f[h]': 6 }
def parse_post_dict(d):
new_d = {}
for key in d.iterkeys():
if "[" in key and "]" in key:
key_split = key.split("[")
outer_key = key_split[0]
... | 0 | 2016-07-19T14:42:20Z | [
"python",
"django"
] |
Replace values in one column for specific instances of another column | 38,460,944 | <p>I am new to Pandas and not sure how to do the following:</p>
<p>I have a dataframe (df) with several columns. One column is called </p>
<pre><code>OldCat = ['a-nn', 'bb-nm', 'ab-pp', 'ba-nn', 'cc-nm', 'ca-mn']
</code></pre>
<p>Now I want to create a new column that organizes/categories OldCat in a new way (NewCat... | 1 | 2016-07-19T14:09:39Z | 38,461,137 | <p>You can use the vectorised <code>str.extract</code> to return matches with <code>fillna</code> to replace <code>NaN</code> with the string <code>'nan'</code>:</p>
<pre><code>In [119]:
df['NewCat'] = df['OldCat'].str.extract('(^a|ba|ca)', expand=False).fillna('nan')
df
Out[119]:
OldCat NewCat
0 a a
1 ... | 2 | 2016-07-19T14:19:23Z | [
"python",
"string",
"pandas",
"str-replace"
] |
Saving the content of a <textarea> to file with Bottle | 38,461,095 | <p>I'm writing a small web portal which will enable users to annotate some text, for a computational linguistics project, and save their annotations to file.</p>
<p>I'm having trouble getting the modified text to be saved.</p>
<p>My page is:</p>
<pre><code>from bottle import template
from project import app
from b... | 0 | 2016-07-19T14:17:25Z | 38,484,173 | <p>Your textarea and your submit form items are both named "package".</p>
<p>Change your button to this and see if that helps:</p>
<pre><code><INPUT TYPE=SUBMIT name="submit" VALUE="Submit">
</code></pre>
<hr>
<p><strong>EDIT</strong>: Explanation</p>
<p>The problem with having two form items that have the s... | 1 | 2016-07-20T14:32:40Z | [
"python",
"html",
"bottle"
] |
Splitting a string in pandas and join it to the old data | 38,461,103 | <p>What I am doing seems simple, but I can not figure it out. </p>
<p>I have dataframe with data such as </p>
<pre><code>City State ZIP
Ames IA 50011-3617
Ankeny IA 50021
</code></pre>
<p>I want to split the zipcodes by <code>-</code> and save only the first ones in a new dataframe which has the old dat... | 3 | 2016-07-19T14:17:54Z | 38,461,197 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> to split on your delimeter and then <code>str[0]</code> on the result to return the first split:</p>
<pre><code>In [122]:
df['ZIP'] = df['ZIP'].str.split('-').str[0]
df
... | 2 | 2016-07-19T14:21:08Z | [
"python",
"pandas"
] |
Splitting a string in pandas and join it to the old data | 38,461,103 | <p>What I am doing seems simple, but I can not figure it out. </p>
<p>I have dataframe with data such as </p>
<pre><code>City State ZIP
Ames IA 50011-3617
Ankeny IA 50021
</code></pre>
<p>I want to split the zipcodes by <code>-</code> and save only the first ones in a new dataframe which has the old dat... | 3 | 2016-07-19T14:17:54Z | 38,461,784 | <p>Ultimately, you want to scrape those first 5 characters and reassign to <code>data.ZIP</code>. Here are some alternatives to scrape the first 5, all of which return the same thing.</p>
<pre><code>0 50011
1 50021
Name: ZIP, dtype: object
data.ZIP.str.extract(r'^(\d{5})', expand=False)
data.ZIP.str[:5]
data.Z... | 2 | 2016-07-19T14:46:09Z | [
"python",
"pandas"
] |
update figure inside loop | 38,461,113 | <p>I'm new to Python <code>matplotlib</code> and want to make a figure updated in a loop.
This is some simple test code. I want to draw 3 graphs, each for 2 seconds, with different slopes each time. Of course, I know I should read some more about <code>matplotlib</code> but I need to do something quick. What is wrong b... | 0 | 2016-07-19T14:18:13Z | 38,461,324 | <p>It seems that you're trying to understand <a href="http://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib">how to update a plot in matplotlib</a>.</p>
<p>You should use this code to understand how to use <code>fig1.canvas.draw()</code> to update your charts data:</p>
<pre><code>fig1 = figure... | 0 | 2016-07-19T14:26:06Z | [
"python",
"python-2.7",
"matplotlib"
] |
update figure inside loop | 38,461,113 | <p>I'm new to Python <code>matplotlib</code> and want to make a figure updated in a loop.
This is some simple test code. I want to draw 3 graphs, each for 2 seconds, with different slopes each time. Of course, I know I should read some more about <code>matplotlib</code> but I need to do something quick. What is wrong b... | 0 | 2016-07-19T14:18:13Z | 38,461,682 | <p>Here is a code which works. The key lines are:</p>
<ul>
<li><code>plt.cla()</code>: to clear the axis between each draw. Remove this line if you want to keep all graphs.</li>
<li><code>fig.canvas.draw()</code>: to actually draw the plot into the canvas of the figure</li>
</ul>
<hr>
<pre><code>#!/usr/bin/env pytho... | 0 | 2016-07-19T14:42:13Z | [
"python",
"python-2.7",
"matplotlib"
] |
update figure inside loop | 38,461,113 | <p>I'm new to Python <code>matplotlib</code> and want to make a figure updated in a loop.
This is some simple test code. I want to draw 3 graphs, each for 2 seconds, with different slopes each time. Of course, I know I should read some more about <code>matplotlib</code> but I need to do something quick. What is wrong b... | 0 | 2016-07-19T14:18:13Z | 38,469,136 | <p>So plt.ion() needs to be paused for a short period of time for it to be interactive. Otherwise, you'll just run into a frozen white screen. Secondly you want to use draw() to update the figure. Therefore, your code would look something like this:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
... | 1 | 2016-07-19T21:52:25Z | [
"python",
"python-2.7",
"matplotlib"
] |
how to increment matrix element in tensorflow using tf.scatter_add? | 38,461,214 | <p>tf.scatter_add works nicely for 1d (shape <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/state_ops.html#scatter_add" rel="nofollow">1</a>) tensors:</p>
<pre><code>> S = tf.Variable(tf.constant([1,2,3,4]))
> sess.run(tf.initialize_all_variables())
> sess.run(tf.scatter_add(S, [0], [10]))
... | 1 | 2016-07-19T14:21:37Z | 38,462,627 | <p><code>tf.scatter_add</code> updates slices of a tensor and not capable of updating individual coefficients. For instance, it can update entire rows of a matrix at once.</p>
<p>Also, the shape of the <code>updates</code> argument to <code>tf.scatter_add</code> depends on the shape of its <code>indices</code> argumen... | 2 | 2016-07-19T15:23:09Z | [
"python",
"tensorflow"
] |
Graph Making from Pandas dataframe | 38,461,334 | <p>i have a data frame called abc, that has rows of times (y direction) and columns of dates (x direction), the frame is made up of values.</p>
<p>what i need to do is create a graph by selecting a certain time, this graph needs to be dates vs the values in that row in the the dataframe. attached is a photo of the dat... | 1 | 2016-07-19T14:26:39Z | 38,462,184 | <p>This is very basic pandas functionality:
You can access the dataframe along the respective axis with the .ix operator</p>
<pre><code>df=pd.DataFrame(np.random.randint(0,10,(5, 4)),index=['9am','10am','11am','12pm','1pm'],columns=['jun','jul','aug','sept'])
# select '9am' and all [:] of the months
df.ix['9am',:].plo... | 3 | 2016-07-19T15:02:06Z | [
"python",
"pandas",
"graph",
"dataframe",
"time-series"
] |
Python 2.x - QueryPerformanceCounter() on Windows | 38,461,335 | <p>I would like to program my own clock object using Python. I'd like it to be very, very accurate. I read that on Windows, I could use QueryPerformanceCounter(). But how? I don't know any C; only Python 2.x. </p>
<p>Can someone give me a hint on how to make use of this in Python to make an accurate clock on Win?</p>
| 1 | 2016-07-19T14:26:46Z | 38,463,185 | <p>I've ported the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx#examples_for_acquiring_time_stamps" rel="nofollow">C++ example</a> you've given to Python using the <code>ctypes</code> module:</p>
<p><strong>C++</strong></p>
<pre><code>LARGE_INTEGER StartingTime, EndingTime,... | 2 | 2016-07-19T15:48:37Z | [
"python",
"windows",
"time",
"clock",
"performancecounter"
] |
Multiple lookup_fields for django rest framework | 38,461,366 | <p>I have multiple API which historically work using <code>id</code> as the lookup field:</p>
<pre><code>/api/organization/10
</code></pre>
<p>I have a frontend consuming those api.</p>
<p>I'm building a new interface and for some reasons, I would like to use a slug instead an id:</p>
<pre><code>/api/organization/m... | 1 | 2016-07-19T14:28:24Z | 38,462,137 | <p>Try this</p>
<pre><code>from django.db.models import Q
import operator
class MultipleFieldLookupMixin(object):
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
... | 2 | 2016-07-19T15:00:19Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
How to get the value selected on a Spinbox with Tkinter? | 38,461,423 | <p>I have a Spinbox with the values (480, 1024, 2048, 5000, 10000) and a Button. Is there a way so I can get the value of selected in the Spinbox?</p>
| 1 | 2016-07-19T14:30:56Z | 38,461,507 | <p><a href="http://effbot.org/tkinterbook/spinbox.htm#Tkinter.Spinbox.get-method" rel="nofollow">get()</a></p>
<p>Remember to refer to the documentation for questions like these.</p>
| 2 | 2016-07-19T14:34:42Z | [
"python",
"tkinter"
] |
django - how to return the same page with all data when form.is_valid() is false | 38,461,434 | <p>I am newbie to django and I am struggling for a longer time with form which doesn't display all data after submitting with error.
On my application to book fitness classes there is sth like header which display data of chosen training,there are also fields to input data of training participant and there is a submit ... | 2 | 2016-07-19T14:31:19Z | 38,461,528 | <p>You should be using the correct classes for the functionality you are implementing. You are creating an entity in the database, so you should subclass CreateView. Once you've done that, you can remove most of your logic, and just define <code>get_context_data</code> to return the relevant Training object.</p>
| 0 | 2016-07-19T14:35:26Z | [
"python",
"django",
"forms",
"django-forms"
] |
django - how to return the same page with all data when form.is_valid() is false | 38,461,434 | <p>I am newbie to django and I am struggling for a longer time with form which doesn't display all data after submitting with error.
On my application to book fitness classes there is sth like header which display data of chosen training,there are also fields to input data of training participant and there is a submit ... | 2 | 2016-07-19T14:31:19Z | 38,468,347 | <p>In your <code>get</code> you're rendering with <code>context = { 'training': training, 'form': form }</code> while in your <code>post</code>, you return only <code>{ 'form' : form }</code> in case of an error (when form is invalid). </p>
<p>You should return <code>training</code> object either way, as it's always d... | 0 | 2016-07-19T20:54:20Z | [
"python",
"django",
"forms",
"django-forms"
] |
Vectorizing three nested loops - NumPy | 38,461,464 | <p>I have two arrays <code>x.dim = (N,4)</code> and <code>y.dim = (M, M, 2)</code> and a function <code>f(a, b)</code>, which takes <code>K</code> and <code>L</code>dimensional vectors respectively as arguments. I want to obtain an array <code>res.dim = (N, M, M)</code> such that</p>
<pre><code>for n in range(N):
fo... | 1 | 2016-07-19T14:32:48Z | 38,462,713 | <p>Here's a vectorized approach to work with the listed function using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> and slicing -</p>
<pre><code># Slice out relevant cols from x
x_slice1 = x[:,None,None,:2]
x_slice2 = x[:,None,None,2:4]
# P... | 1 | 2016-07-19T15:26:34Z | [
"python",
"numpy",
"vectorization"
] |
Theano cannot find lstdc++ | 38,461,469 | <p>I used anaconda2 to install mingw and libpython, afterwards I test run the Theano by doing import theano on the IDLE, unfortunately I am experiencing an error telling me several files are not found.</p>
<p>I went to the file path C:\Anaconda2\MinGW\x86_64-w64-mingw32\lib and I found that there are indeed no such fi... | 0 | 2016-07-19T14:32:59Z | 38,463,390 | <p>The exact message given is:</p>
<pre><code>skipping incompatible .../libstdc++.dll.a when searching for -lstdc++
etc..
</code></pre>
<p>I also see it looking for <code>user32</code> and <code>kernel32</code>, yet the toolchain is apparently configured for <code>x86_64-w64-mingw32</code>.</p>
<p>Are you trying to ... | 0 | 2016-07-19T15:58:20Z | [
"python",
"c++",
"g++",
"anaconda",
"theano"
] |
Theano cannot find lstdc++ | 38,461,469 | <p>I used anaconda2 to install mingw and libpython, afterwards I test run the Theano by doing import theano on the IDLE, unfortunately I am experiencing an error telling me several files are not found.</p>
<p>I went to the file path C:\Anaconda2\MinGW\x86_64-w64-mingw32\lib and I found that there are indeed no such fi... | 0 | 2016-07-19T14:32:59Z | 38,475,952 | <p>Finally, after reinstalling mingw and libpython in Anaconda on 32bit windows, everything is solved by upgrading to the latest version. I updated mine from 2.7.10 to 2.7.12.</p>
<p>Note: Do not forget to place the Anaconda2 folder on your PATH in the variable environment.</p>
| 0 | 2016-07-20T08:18:31Z | [
"python",
"c++",
"g++",
"anaconda",
"theano"
] |
why can't return assignment statement | 38,461,509 | <p>In IDLE,
I write a function and intend to return a value. but it can't return</p>
<pre><code>>>> def grade(value):
if value > 100:
return (value=100)
if value <0:
return (value=0)
SyntaxError: invalid syntax
</code></pre>
<p>why can't return? but when I change to</p>
<pre><... | -3 | 2016-07-19T14:34:44Z | 38,461,614 | <p>In a <a href="https://docs.python.org/2/reference/simple_stmts.html#the-return-statement" rel="nofollow">return statement</a>, only an expression can come after the "return".</p>
<blockquote>
<p><code>return_stmt ::= "return" [expression_list]</code></p>
</blockquote>
<p>An assignment is a <a href="https://docs... | 1 | 2016-07-19T14:39:15Z | [
"python"
] |
RunTimeError in merge sort function using python | 38,461,550 | <p>I am trying to write a merge sort function using python 2 but i get a RunTimeError </p>
<blockquote>
<p>Input: unsorted list (ex:[10,9,8,7,6,5,4,3,2,1])</p>
<p>Output: [1,2,3,4,5,6,7,8,9,10]</p>
</blockquote>
<p>My code is shown below:</p>
<pre><code>lst = [10,9,8,7,6,5,4,3,2,1]
def mergesort(array):
if le... | 0 | 2016-07-19T14:36:02Z | 38,461,786 | <p>You're comparing list values to list indices:</p>
<pre><code>for i in array: # i is a list value
if i <= len(array)/2: # len(array)/2 is a list index
</code></pre>
<p>Change this to <code>if i <= array[len(array)/2]:</code> and it should work.</p>
| 0 | 2016-07-19T14:46:12Z | [
"python",
"sorting",
"mergesort"
] |
RunTimeError in merge sort function using python | 38,461,550 | <p>I am trying to write a merge sort function using python 2 but i get a RunTimeError </p>
<blockquote>
<p>Input: unsorted list (ex:[10,9,8,7,6,5,4,3,2,1])</p>
<p>Output: [1,2,3,4,5,6,7,8,9,10]</p>
</blockquote>
<p>My code is shown below:</p>
<pre><code>lst = [10,9,8,7,6,5,4,3,2,1]
def mergesort(array):
if le... | 0 | 2016-07-19T14:36:02Z | 38,461,948 | <p>This code works:</p>
<pre><code>lst = [10,9,8,7,6,5,4,3,2,1]
def mergesort(array):
if len(array) == 1:
return array
left = []
right = []
for i in range(len(array)):
if i < len(array)/2:
left.append(array[i])
else:
right.append(array[i])
left... | 0 | 2016-07-19T14:52:40Z | [
"python",
"sorting",
"mergesort"
] |
How to break time.sleep() in a python concurrent.futures | 38,461,603 | <p>I am playing around with <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent.futures</a>.</p>
<p>Currently my future calls <code>time.sleep(secs)</code>.</p>
<p>It seems that <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel">Future.cance... | 7 | 2016-07-19T14:38:39Z | 38,562,474 | <p>If you submit a function to a <code>ThreadPoolExecutor</code>, the executor will run the function in a thread and store its return value in the <code>Future</code> object. Since the number of concurrent threads is limited, you have the option to <em>cancel</em> the <em>pending</em> execution of a future, but once co... | 3 | 2016-07-25T07:59:52Z | [
"python",
"concurrency",
"concurrent.futures"
] |
How to break time.sleep() in a python concurrent.futures | 38,461,603 | <p>I am playing around with <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent.futures</a>.</p>
<p>Currently my future calls <code>time.sleep(secs)</code>.</p>
<p>It seems that <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel">Future.cance... | 7 | 2016-07-19T14:38:39Z | 38,628,723 | <p>I do not know much about concurrent.futures, but you can use this logic to break the time. Use a loop instead of sleep.time() or wait() </p>
<pre><code>for i in range(sec):
sleep(1)
</code></pre>
<p>interrupt or break can be used to come out of loop. </p>
| 1 | 2016-07-28T06:34:56Z | [
"python",
"concurrency",
"concurrent.futures"
] |
Can I use a key from a dict I'm still defining? | 38,461,604 | <p>For instance, is there a way to call <code>a</code> while defining <code>b</code> as outlined below?</p>
<pre><code>c = dict(
a = "foo",
b = a + "bar"
)
</code></pre>
<p>Or can I only use:</p>
<pre><code>c = dict()
c['a'] = "foo"
c['b'] = c['a'] + "bar"
</code></pre>
| -1 | 2016-07-19T14:38:39Z | 38,461,959 | <p>This should be refactored:</p>
<pre><code>a = "foo"
c = dict(a=a, b=a+"bar")
</code></pre>
<p>You <em>could</em> do it in one line, without the temporary variable <code>a</code>, but it's not pretty:</p>
<pre><code>c = (lambda x: dict(a=x, b=x+"bar"))("foo")
</code></pre>
| 2 | 2016-07-19T14:53:17Z | [
"python",
"python-2.7"
] |
Can I use a key from a dict I'm still defining? | 38,461,604 | <p>For instance, is there a way to call <code>a</code> while defining <code>b</code> as outlined below?</p>
<pre><code>c = dict(
a = "foo",
b = a + "bar"
)
</code></pre>
<p>Or can I only use:</p>
<pre><code>c = dict()
c['a'] = "foo"
c['b'] = c['a'] + "bar"
</code></pre>
| -1 | 2016-07-19T14:38:39Z | 38,461,964 | <p>No. With the first example you provided it's not possible. The seconds example is more Pythonic.</p>
<p>If you really want it to be in one call you will probably not have hard coded values so you could use:</p>
<pre><code>text = "foo"
c = dict(
a = text,
b = text + "bar"
)
</code></pre>
| 0 | 2016-07-19T14:53:23Z | [
"python",
"python-2.7"
] |
How to concurrently append and remove elements from a deque, every x seconds in Python? | 38,461,612 | <p>I have a Python deque.</p>
<p>I would like to append() a new element at the end of the deque, for example, every 1 second.</p>
<p>At the same time, I would like to popleft() the first element of the deque, for example, every 3 seconds.</p>
<p>This is the first time I'm doing time-based programming, so I'm not sur... | 0 | 2016-07-19T14:38:55Z | 38,462,376 | <p>There are much more sophisticated (and proper) methods to obtain concurrency in Python than what I'm about to show, but the following approach is pretty straightforward and might be more friendly.</p>
<p>n.b. This is not "true" concurrency in the sense that it's ever possible for more than one operation to happen a... | 0 | 2016-07-19T15:11:33Z | [
"python",
"time",
"concurrency"
] |
How to rotate a cylinder without causing a 'sheared' appearance | 38,461,638 | <p>I have plotted a 'tear drop' shaped cylinder in matplotlib. To obtain the tear drop shape I plotted a normal cylinder from <code>theta = 0</code> to <code>theta = pi</code> and an ellipse from <code>theta = pi</code> to <code>theta = 2pi</code>. However I am now trying to 'spin' the cylinder around it's axis which h... | 0 | 2016-07-19T14:40:20Z | 38,462,771 | <p>Your rotating is flawed: To calculate <code>Y1[i]</code> you need the old value of <code>X1[i]</code>, but you already updated it. You can try something like </p>
<pre><code>X1[i], Y1[i] = cos(a)*X1[i]-sin(a)*Y1[i], sin(a)*X1[i]+cos(a)*Y1[i]
</code></pre>
<p>if you want to make the matrix multiplication a bit more... | 2 | 2016-07-19T15:28:27Z | [
"python",
"matplotlib"
] |
Basic Python Class Yields TypeError | 38,461,663 | <p>I'm fairly new to Python. Here, I'm creating a class to represent a blob-like structure. However, my code yields the following error:</p>
<blockquote>
<p>TypeError: add() takes 3 positional arguments but 4 were given</p>
</blockquote>
<pre><code>class Blob:
mass = 0
xvals = []
yvals = []
correlat... | -1 | 2016-07-19T14:41:18Z | 38,461,708 | <p>Your instance methods are missing the <code>self</code> reference:</p>
<pre><code>def computeCorrelation(self, newCorrel)
# ^
def add(self, x, y, newCorrel)
# ^
</code></pre>
<p>The first parameter passed by an instance method is a reference to that instance of the class. So your <cod... | 4 | 2016-07-19T14:43:20Z | [
"python",
"class"
] |
Basic Python Class Yields TypeError | 38,461,663 | <p>I'm fairly new to Python. Here, I'm creating a class to represent a blob-like structure. However, my code yields the following error:</p>
<blockquote>
<p>TypeError: add() takes 3 positional arguments but 4 were given</p>
</blockquote>
<pre><code>class Blob:
mass = 0
xvals = []
yvals = []
correlat... | -1 | 2016-07-19T14:41:18Z | 38,461,775 | <p>in a class, the first argument of a function is <code>self</code>. When in your main, you call <code>test1.add(0, 0, 12)</code>, python call <code>test1.add(test1,0, 0, 12)</code>, so now he has 4 argument.</p>
<pre><code>class Blob:
mass = 0
xvals = []
yvals = []
correlationVal = 0
def __init__(se... | 1 | 2016-07-19T14:45:55Z | [
"python",
"class"
] |
Basic Python Class Yields TypeError | 38,461,663 | <p>I'm fairly new to Python. Here, I'm creating a class to represent a blob-like structure. However, my code yields the following error:</p>
<blockquote>
<p>TypeError: add() takes 3 positional arguments but 4 were given</p>
</blockquote>
<pre><code>class Blob:
mass = 0
xvals = []
yvals = []
correlat... | -1 | 2016-07-19T14:41:18Z | 38,461,797 | <p>The first argument to a Python class method needs to be <code>self</code> i.e. <code>def add(self, x, y, newCorrel):</code> instead of <code>def add(x, y, newCorrel):</code>.</p>
<p>Self is implicitly passed to class instance methods when they are called, hence why 4 arguments are being passed instead of just the 3... | 0 | 2016-07-19T14:46:21Z | [
"python",
"class"
] |
Extract fields and values from string in Python | 38,461,751 | <p>I'm trying to extract the field name and the value.From a string containing fields and values like the following one:</p>
<pre><code>/location=(7966, 8580, 1) /station=NY /comment=Protein RadB n=1 Tax=M (SB / ATCC) RepID=A6USB2_METV
</code></pre>
<ul>
<li><p>Each string can contain a different number of fields</p>... | 2 | 2016-07-19T14:44:59Z | 38,462,011 | <p>You can use <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a> to first split the "key=value" pairs, then regular <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> splitting by the first occurrence of <... | 3 | 2016-07-19T14:55:28Z | [
"python",
"regex"
] |
Extract fields and values from string in Python | 38,461,751 | <p>I'm trying to extract the field name and the value.From a string containing fields and values like the following one:</p>
<pre><code>/location=(7966, 8580, 1) /station=NY /comment=Protein RadB n=1 Tax=M (SB / ATCC) RepID=A6USB2_METV
</code></pre>
<ul>
<li><p>Each string can contain a different number of fields</p>... | 2 | 2016-07-19T14:44:59Z | 38,462,593 | <p>Just use the re.split()</p>
<pre><code>>>> string
'/location=(7966, 8580, 1) /station=NY /comment=Protein RadB n=1 Tax=M (SB / ATCC) RepID=A6USB2_METV'
>>> import re
>>> pattern = re.compile(r'\s*/([a-z]+)=')
>>> pattern.split(string)[1:]
['location', '(7966, 8580, 1)', 'station'... | 1 | 2016-07-19T15:21:25Z | [
"python",
"regex"
] |
Multiple conditional average python | 38,461,863 | <p>What I'm trying to do is a multiple conditional average. It means that I have a list of x variables (of the same length) and I'd like to compute the average of one variable conditioned to the value/range of the others.</p>
<p>The file is:
<a href="http://i.stack.imgur.com/juLJs.png" rel="nofollow"><img src="http://... | 3 | 2016-07-19T14:48:48Z | 38,462,109 | <p>What you have written seems all sorts of wrong. I believe what you want is:</p>
<pre><code>(Var1 == 0).all() and (Var2 == 0) and (Var3 >= 0).all() and (Var3 < 1).all() and (Var6 == 0).all()
</code></pre>
| 4 | 2016-07-19T14:59:04Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.