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 |
|---|---|---|---|---|---|---|---|---|---|
finding a special path string in HTML text in python | 40,107,690 | <p>I'm trying to extract a path in an HTML file that I read.
In this case the path that I'm looking for is a logo from google's main site.</p>
<p>I'm pretty sure that the regular expression I defined is right, but I guess I'm missing something.</p>
<p>The code is:</p>
<pre><code>import re
import urllib
a=urllib.urlo... | 2 | 2016-10-18T11:59:35Z | 40,108,138 | <p>Here's my answer:</p>
<pre><code>import re
import urllib
a=urllib.urlopen ('https://www.google.co.il/')
text = a.read(250)
print text
print '\n\n'
b= re.search (r'\"(\/[a-z0-9_. ]+)+\"',text)
print format(b.group(0))
</code></pre>
<p>Run gives:</p>
<pre><code>>>> python stackoverflow.py
<!doctype h... | 0 | 2016-10-18T12:21:55Z | [
"python",
"regex",
"expression"
] |
list comprehension does not return empty list | 40,107,819 | <p>I tried to find the relevant question but couldn't find so creating a new one.
My program creates a new list using list comprehension in python as per a simple if condition. </p>
<pre><code> Newone = [ temp for temp in Oldone if temp % 2 != 0 ]
</code></pre>
<p>It works fine but when in some situation it doesn't... | -6 | 2016-10-18T12:06:01Z | 40,107,855 | <pre><code> 1%2 == 1
</code></pre>
<p>So your your condition: <code>temp % 2 != 0</code> is <code>True</code>, therefore it is included in the list. If you want an empty list, you should change it <code>temp % 2 == 0</code>.</p>
| 5 | 2016-10-18T12:07:59Z | [
"python",
"list",
"condition",
"list-comprehension"
] |
list comprehension does not return empty list | 40,107,819 | <p>I tried to find the relevant question but couldn't find so creating a new one.
My program creates a new list using list comprehension in python as per a simple if condition. </p>
<pre><code> Newone = [ temp for temp in Oldone if temp % 2 != 0 ]
</code></pre>
<p>It works fine but when in some situation it doesn't... | -6 | 2016-10-18T12:06:01Z | 40,108,021 | <p>If you are not sure what's happening. Your list comprehension:</p>
<pre><code> Newone = [ temp for temp in Oldone if temp % 2 != 0 ]
</code></pre>
<p>Means; put in my new list <code>Newone</code> all <code>temp</code> values from my existing list <code>Oldone</code>, which satisfy the condition <code>temp % 2 != 0... | 3 | 2016-10-18T12:16:13Z | [
"python",
"list",
"condition",
"list-comprehension"
] |
Incomplete list pop in list comprehention | 40,108,025 | <p>I have been trying to <code>pop</code> elements in list comprehention using <code>takewhile</code> function and I came into things that is for me hard to understand. My terminal session looks like this:</p>
<p><a href="https://i.stack.imgur.com/yMiBB.png" rel="nofollow"><img src="https://i.stack.imgur.com/yMiBB.png... | 0 | 2016-10-18T12:16:28Z | 40,108,881 | <p>I figured it out, because i've tried to use <code>deque</code> which raised <code>RuntimeError: deque mutated during iteration</code>.</p>
<p>Execution goes like this:</p>
<ol>
<li><code>g[0] = 1 < 4; g.pop(0) => 1</code></li>
<li><code>g[1] = 3 < 4; g.pop(0) => 2</code></li>
<li><code>g[2] = 5 > 4;... | 1 | 2016-10-18T12:54:55Z | [
"python",
"python-2.7",
"list-comprehension",
"pop"
] |
How to check if a server is up or not in Python? | 40,108,043 | <p>In PHP I just did: <code>$fp = @fsockopen(irc.myserver.net, 6667, $errno, $errstr, 2);</code></p>
<p>Does Python 2.X also have a function like PHP's <code>fsockopen()</code>? If not how else can I check if a server on port 6667 is up or not?</p>
| 1 | 2016-10-18T12:17:22Z | 40,108,187 | <p>The <a href="https://docs.python.org/2/library/socket.html" rel="nofollow">socket module</a> can be used to simply check if a port is open or not.</p>
<pre><code>import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('irc.myserver.net',6667))
if result == 0:
print "Port... | 4 | 2016-10-18T12:24:05Z | [
"python",
"python-2.7"
] |
How to remove a black background from an image and make that transparent using opencv? | 40,108,062 | <p>I am using "PerspectiveTransform" method to transform the image in a given rectangle. Method "warpPerspective" works fine, but the output contains the black background and I want to remove the black color and make that transparent.</p>
<pre><code>import cv2
import numpy as np
img2 = cv2.imread(r"C:\Users\test\Desk... | 1 | 2016-10-18T12:18:13Z | 40,108,728 | <p>As your input image is in <code>.jpg</code> format so you need to convert the input image from <code>BGR</code> domain to <code>BGRA</code> domain:</p>
<pre><code>img2 = cv2.imread(r"C:\Users\test\Desktop\map.jpg")
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2BGRA)
</code></pre>
<p>Also you don't need to define a new <... | 2 | 2016-10-18T12:48:00Z | [
"python",
"opencv"
] |
How to get read/write disk speed in Python? | 40,108,070 | <p>In a Pyhton program I need to get the accumulated read/write speeds of all disks on the host. I was doing it with <code>subprocess.check_output()</code> to call the following Linux shell command:</p>
<pre><code>$ sudo hdparm -t /dev/sda
</code></pre>
<p>This gives as a result:</p>
<pre><code>/dev/sda:
Timing buf... | 5 | 2016-10-18T12:18:41Z | 40,108,198 | <p>According to <a href="http://unix.stackexchange.com/questions/55212/how-can-i-monitor-disk-io">http://unix.stackexchange.com/questions/55212/how-can-i-monitor-disk-io</a> the most usable solution includes the tool sysstat or iostat (same package).</p>
<p>But seriously, since you have sudo permissions on the host, y... | 3 | 2016-10-18T12:24:27Z | [
"python",
"linux",
"bash",
"performance"
] |
Writing to a JSON file and updating said file | 40,108,274 | <p>I have the following code that will write to a JSON file:</p>
<pre><code>import json
def write_data_to_table(word, hash):
data = {word: hash}
with open("rainbow_table\\rainbow.json", "a+") as table:
table.write(json.dumps(data))
</code></pre>
<p>What I want to do is open the JSON file, add ano... | 1 | 2016-10-18T12:28:14Z | 40,108,416 | <p>You may read the JSON data with :</p>
<pre><code>parsed_json = json.loads(json_string)
</code></pre>
<p>You now manipulate a classic dictionary. You can add data with :</p>
<pre><code>parsed_json.update({'test4': 0000123456789})
</code></pre>
<p>Then you can write data to a file using :</p>
<pre><code>with open... | 4 | 2016-10-18T12:34:48Z | [
"python",
"json",
"python-2.7"
] |
Writing to a JSON file and updating said file | 40,108,274 | <p>I have the following code that will write to a JSON file:</p>
<pre><code>import json
def write_data_to_table(word, hash):
data = {word: hash}
with open("rainbow_table\\rainbow.json", "a+") as table:
table.write(json.dumps(data))
</code></pre>
<p>What I want to do is open the JSON file, add ano... | 1 | 2016-10-18T12:28:14Z | 40,108,707 | <p>If you are sure the closing "}" is the last byte in the file you can do this:</p>
<pre><code>>>> f = open('test.json', 'a+')
>>> json.dump({"foo": "bar"}, f) # create the file
>>> f.seek(0)
>>> f.read()
'{"foo": "bar"}'
>>> f.seek(-1, 2)
>>> f.write(',\n', f.wr... | 1 | 2016-10-18T12:47:01Z | [
"python",
"json",
"python-2.7"
] |
Connect GAE Remote API to dev_appserver.py | 40,108,508 | <p>I want to execute a Python script that connects to my local dev_appserver.py instance to run some DataStore queries.</p>
<p>The dev_appserver.py is running with:</p>
<pre><code>builtins:
- remote_api: on
</code></pre>
<p>As per <a href="https://cloud.google.com/appengine/docs/python/tools/remoteapi" rel="nofollow... | 0 | 2016-10-18T12:38:21Z | 40,109,546 | <p>The <code>dev_appserver.py</code> doesn't support SSL (I can't find the doc reference anymore), so it can't answer <code>https://</code> requests.</p>
<p>You could try using http-only URLs (not sure if possible with the remote API - I didn't use it yet, may need to disable handler <code>secure</code> option in <cod... | 1 | 2016-10-18T13:24:14Z | [
"python",
"google-app-engine"
] |
Difficulty with python while installing YouCompleteMe in vim | 40,108,521 | <p>I've followed <a href="https://github.com/Valloric/YouCompleteMe/tree/ddf18cc6ec3bb0108bb89ac366fd74394815f2c6#ubuntu-linux-x64" rel="nofollow">these instructions</a>, in order to install YouCompleteMe in Vim, but when I issue:</p>
<pre><code>./install.py --clang-completer
</code></pre>
<p>The following error mess... | 0 | 2016-10-18T12:39:00Z | 40,112,214 | <p>The plugin builds for me on the same operating system. The relevant line from the configuration looks like this:</p>
<pre><code>Found PythonLibs: /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so
</code></pre>
<p>The shared object can be identified as belonging to <code>libpython2.7</code> package:</p>
<... | 0 | 2016-10-18T15:26:30Z | [
"python",
"linux",
"python-2.7",
"ubuntu",
"vim"
] |
Difficulty with python while installing YouCompleteMe in vim | 40,108,521 | <p>I've followed <a href="https://github.com/Valloric/YouCompleteMe/tree/ddf18cc6ec3bb0108bb89ac366fd74394815f2c6#ubuntu-linux-x64" rel="nofollow">these instructions</a>, in order to install YouCompleteMe in Vim, but when I issue:</p>
<pre><code>./install.py --clang-completer
</code></pre>
<p>The following error mess... | 0 | 2016-10-18T12:39:00Z | 40,131,786 | <p>I checked YouCompleteMe's build system and it uses a custom build script that uses the Python module <code>distutils</code> to find the paths to Python's library and include directories. Your <code>/usr/local/</code> installation of Python is probably included in your <code>PATH</code> variable before the official <... | 0 | 2016-10-19T12:45:48Z | [
"python",
"linux",
"python-2.7",
"ubuntu",
"vim"
] |
How to resize an image while uploading and saving it automaticly django? | 40,108,544 | <p>I'm unable to save the image that is either being resized or uploading directly through my <code>admin</code> panel. I want to resize it through <code>PLP</code> or any other way!</p>
<pre><code>def get_product_image_folder(instance, filename):
return "static/images/product/%s/base/%s" %(instance.product_id, filen... | 0 | 2016-10-18T12:40:08Z | 40,115,339 | <p>This can be done either in the save method of the model, the save_model method of the admin, or the save method of the form.</p>
<p>I recommend the last one, since it lets you decouple form/validation logic from the model and admin interface. </p>
<p>This could look something like the following:</p>
<pre><code>cl... | 0 | 2016-10-18T18:20:05Z | [
"python",
"django"
] |
validate the size and format if uploaded image and resize it in django | 40,108,553 | <p>I am uploading an image in django, i want to validate it's format and size in forms.py</p>
<pre><code>class CreateEventStepFirstForm(forms.Form):
user_image = forms.ImageField(required = True, widget=forms.FileInput(attrs={
'class' : 'upload-img',
'data-empty-message':'Please upload artist image... | 2 | 2016-10-18T12:40:17Z | 40,108,698 | <p>You should look at writing your own custom validator. You can read about them here in the <a href="https://docs.djangoproject.com/en/1.10/ref/validators/" rel="nofollow">documentation</a> </p>
<p>Once you've created a validator that checks against those values then you can attach it to the form in a couple of diff... | 0 | 2016-10-18T12:46:48Z | [
"python",
"django"
] |
Python running as Windows Service: OSError: [WinError 6] The handle is invalid | 40,108,816 | <p>I have a Python script, which is running as a Windows Service. The script forks another process with:</p>
<pre><code>with subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
</code></pre>
<p>which causes the following error:</p>
<pre><code>OSError: [WinError 6] The ... | 0 | 2016-10-18T12:51:41Z | 40,108,817 | <p>Line 1117 in <code>subprocess.py</code> is:</p>
<pre><code>p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
</code></pre>
<p>which made me suspect that service processes do not have a STDIN associated with them (TBC)</p>
<p>This troublesome code can be avoided by supplying a file or null device as the std... | 2 | 2016-10-18T12:51:41Z | [
"python",
"windows",
"subprocess"
] |
explode array of array- (Dataframe) pySpark | 40,108,822 | <p>I have a dataframe like this:</p>
<pre><code> +-----+--------------------+
|index| merged|
+-----+--------------------+
| 0|[[2.5, 2.4], [3.5...|
| 1|[[-1.0, -1.0], [-...|
| 2|[[-1.0, -1.0], [-...|
| 3|[[0.0, 0.0], [0.5...|
| 4|[[0.5, 0.5], [1.0...|
| 5|[[0.5, 0.5], [1.0...|
| 6|[... | 1 | 2016-10-18T12:52:00Z | 40,109,388 | <p>You could try the following code:</p>
<pre><code>from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
from pyspark.sql.types import FloatType, StringType, IntegerType
from pyspark.sql.functions import udf, col ... | 0 | 2016-10-18T13:17:09Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Error 'cannot import name post_revision_commit' | 40,108,833 | <p>Hi everyone I move my project, to a server I now I try to load the database
<code>python manage.py loaddata resource/ddbb/20160817_db.json</code>
or even run the server but I obtain this error.</p>
<pre><code>File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/mxp12... | 0 | 2016-10-18T12:52:39Z | 40,109,026 | <p>It looks like the <code>django-cms</code> version you are using doesn't support <code>django-reversion</code> 2.0+. The comments in the <a href="https://github.com/divio/django-cms/blob/3.4.1/cms/utils/reversion_hacks.py#L3" rel="nofollow">django-cms source</a> seem to affirm this. I would try installing the lates... | 1 | 2016-10-18T13:01:28Z | [
"python",
"django"
] |
Error 'cannot import name post_revision_commit' | 40,108,833 | <p>Hi everyone I move my project, to a server I now I try to load the database
<code>python manage.py loaddata resource/ddbb/20160817_db.json</code>
or even run the server but I obtain this error.</p>
<pre><code>File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/mxp12... | 0 | 2016-10-18T12:52:39Z | 40,109,269 | <p>You should be on latest <code>djnago-reversion</code>. Because <code>post_revision_commit</code> signal has been removed since 2.0.0 and added back in the latest version. <a href="http://django-reversion.readthedocs.io/en/latest/changelog.html?highlight=post_revision_commit#signals" rel="nofollow">Reference</a></p>
| 1 | 2016-10-18T13:11:24Z | [
"python",
"django"
] |
java script html element scrape using a scrapy on phython 2.7.11 i get like these | 40,108,890 | <pre><code>[root@Imx8 craigslist_sample]# scrapy crawl spider
/root/Python-2.7.11/craigslist_sample/craigslist_sample/spiders/test.py:1: ScrapyDeprecationWarning: Module `scrapy.spider` is deprecated, use `scrapy.spiders` instead
from scrapy.spider import BaseSpider
/root/Python-2.7.11/craigslist_sample/craigslist_sa... | -1 | 2016-10-18T12:55:25Z | 40,109,116 | <p>your should set name='spider' in craigslist_sample/craigslist_sample/spiders/test.py </p>
<pre><code>class MySpider(Spider):
name = 'spider'
def parse(self,response):
#....
</code></pre>
| 0 | 2016-10-18T13:05:17Z | [
"python",
"scrapy",
"pycurl"
] |
Python function: variable and string | 40,108,906 | <p>I have following formula to check (Thanks for helping me on <a href="http://stackoverflow.com/questions/40102772/python-applying-function-to-list-of-tems/40102936?noredirect=1#comment67478880_40102936">this</a>!).</p>
<pre><code>queries = ['dog','cat','hamster']
def get_trends(queries):
return pd.conca... | 0 | 2016-10-18T12:55:44Z | 40,109,680 | <p>You can do it this way:</p>
<pre><code>In [54]: %paste
static = 'animals'
animals = ['dog','cat','hamster']
queries = ['{}, {}'.format(static, x) for x in animals]
## -- End pasted text --
In [55]: queries
Out[55]: ['animals, dog', 'animals, cat', 'animals, hamster']
</code></pre>
<p>now you can pass <code>querie... | 0 | 2016-10-18T13:29:38Z | [
"python",
"string",
"list",
"function"
] |
Display Sum of overdue payments in Customer Form view for each customer | 40,109,065 | <p>In accounting -> Customer Invoices, there is a filter called <code>Overdue</code>. Now I want to calculate the overdue payments per user and then display it onto the customer form view.
I just want to know how can we apply the condition of <strong>filter</strong> in python code. I have already defined a smart button... | 0 | 2016-10-18T13:02:57Z | 40,124,695 | <p>Your smart button on partners should use a new action, like the button for customer or vendor bills. This button definition should include <code>context="{'default_partner_id': active_id}</code> which will allow to change the partner filter later on, or the upcoming action definition should include the partner in it... | 1 | 2016-10-19T07:19:14Z | [
"python",
"openerp",
"odoo-9"
] |
I want to make a variable in my views.py which changes depending the name of the urlpattern used | 40,109,185 | <p>Here's my code. whatever urlpattern is chosen: I want the name of it to be stored as <code>url</code> in views.py. Which is then used in queryset filter().</p>
<p><strong>urls.py</strong></p>
<pre><code>url(r'^news/', BoxesView.as_view(), name='news'),
url(r'^sport/', BoxesView.as_view(), name='sport'),
url(r'^car... | 0 | 2016-10-18T13:07:41Z | 40,109,729 | <p>I would replace your url.py by something like this:</p>
<pre><code>url(r'(?P<keyword>\w+)/$', BoxesView.as_view())
</code></pre>
<p>This changes your address into an url parameter which you can then access the in your methods like this:</p>
<pre><code>def get_queryset(self):
url = self.kwargs['k... | 1 | 2016-10-18T13:31:56Z | [
"python",
"django",
"django-views"
] |
I want to make a variable in my views.py which changes depending the name of the urlpattern used | 40,109,185 | <p>Here's my code. whatever urlpattern is chosen: I want the name of it to be stored as <code>url</code> in views.py. Which is then used in queryset filter().</p>
<p><strong>urls.py</strong></p>
<pre><code>url(r'^news/', BoxesView.as_view(), name='news'),
url(r'^sport/', BoxesView.as_view(), name='sport'),
url(r'^car... | 0 | 2016-10-18T13:07:41Z | 40,110,563 | <p>You can use this to get the name of the view</p>
<pre><code> url = resolve(self.request.path_info).url_name
</code></pre>
<p>UPDATE: Added "self." which is needed when using generic views. And don't forget to import:</p>
<pre><code> from django.core.urlresolvers import resolve
</code></pre>
| 0 | 2016-10-18T14:11:28Z | [
"python",
"django",
"django-views"
] |
%s showing strange behavior in regex | 40,109,204 | <p>I have a string in which I want to find some words preceding a parenthesis. Lets say the string is - </p>
<blockquote>
<p>'there are many people in the world having colorectal cancer (crc) who also have the depression syndrome (ds)'</p>
</blockquote>
<p>I want to capture at most 5 words before a parenthesis. I h... | 1 | 2016-10-18T13:08:35Z | 40,109,914 | <p>You need to make sure the variables you pass are escaped correctly so as to be used as literal text inside a regex pattern. Use <code>re.escape(acro)</code>:</p>
<pre><code>import re
text = "there are many people in the world having colorectal cancer (crc) who also have the depression syndrome (ds)"
acrolen=5
rt=[]... | 1 | 2016-10-18T13:40:54Z | [
"python",
"regex"
] |
How to retry before an exception with Eclipse/PyDev | 40,109,228 | <p>I am using Eclipse + PyDev, although I can break on exception using PyDev->Manage Exception Breakpoints, I am unable to continue the execution after the exception.</p>
<p>What I would like to be able to do is to set the next statement before the exception so I can run a few commands in the console window and contin... | 1 | 2016-10-18T13:09:30Z | 40,130,262 | <p>Unfortunately no, this is a Python restriction on setting the next line to be executed: it can't set the next statement after an exception is thrown (it can't even go to a different block -- i.e.: if you're inside a try..except, you can't set the next statement to be out of that block).</p>
<p>You could in theory t... | 1 | 2016-10-19T11:32:25Z | [
"python",
"eclipse",
"pydev"
] |
Django creating wrong type for fields in intermediate table (manytomany) | 40,109,257 | <p>I have a model in Django which the <code>pk</code> is not an integer and it has a field which is a <code>manytomany</code>. This <code>manytomany</code> references the model itself.</p>
<p>When I ran <code>makemigration</code> I didn't realize, but it did not create the fields in the intermediate table as <code>cha... | 1 | 2016-10-18T13:10:55Z | 40,109,488 | <p>Try to re-create migrations (unapply migrations by using <code>./manage.py migrate YOURAPP PREVIOUS_MIGRATION_NUMBER</code> or <code>./manage.py migrate YOURAPP zero</code> if it's initial migration), remove migration file (don't forget about <code>.pyc</code> file) and generate it again.</p>
<p>If that doesn't hel... | 0 | 2016-10-18T13:21:14Z | [
"python",
"django",
"django-models",
"manytomanyfield"
] |
Spark Dataframe-Python | 40,109,274 | <p>In pandas, I can successfully run the following:</p>
<pre><code>def car(t)
if t in df_a:
return df_a[t]/df_b[t]
else:
return 0
</code></pre>
<p>But how can I do the exact same thing with spark dataframe?Many thanks!<br>
The data is like this</p>
<pre><code>df_a
a 20
b 40
c 60
df_b
a 80
b 50... | 0 | 2016-10-18T13:11:42Z | 40,113,481 | <p>First you have to <code>join</code> both dataframes, then you have to <code>filter</code> by the letter you want and <code>select</code> the operation you need.</p>
<pre class="lang-py prettyprint-override"><code>df_a = sc.parallelize([("a", 20), ("b", 40), ("c", 60)]).toDF(["key", "value"])
df_b = sc.parallelize([... | 3 | 2016-10-18T16:27:53Z | [
"python",
"apache-spark"
] |
How do I link python 3.4.3 to opencv? | 40,109,379 | <p>So I have OpenCV on my computer all sorted out, I can use it in C/C++ and the Python 2.7.* that came with my OS.</p>
<p>My computer runs on Linux Deepin and whilst I usually use OpenCV on C++, I need to use Python 3.4.3 for some OpenCV tasks.</p>
<p>Problem is, I've installed python 3.4.3 now but whenever I try to... | 1 | 2016-10-18T13:16:42Z | 40,109,662 | <p>You can try:</p>
<ol>
<li>Download the OpenCV module</li>
<li>Copy the ./opencv/build/python/3.4/x64/cv2.pyd file </li>
<li>To the python installation directory path: ./Python34/Lib/site-packages.</li>
</ol>
<p>I hope this helps</p>
| 0 | 2016-10-18T13:29:17Z | [
"python",
"python-2.7",
"python-3.x",
"opencv",
"numpy"
] |
Django AppsNotLoaded | 40,109,400 | <p>I'm trying to make a python script to put some things in my database;</p>
<pre><code>from django.conf import settings
settings.configure()
import django.db
from models import Hero #Does not work..?
heroes = [name for name in open('hero_names.txt').readlines()]
names_in_db = [hero.hero_name for hero in Hero.object... | 0 | 2016-10-18T13:17:49Z | 40,109,851 | <p>Django must configure all installed applications before you can use any models. To do this you must call <code>django.setup()</code></p>
<pre><code>import django
django.setup()
</code></pre>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/applications/#how-applications-are-loaded" rel="nofollow">From the do... | 1 | 2016-10-18T13:37:51Z | [
"python",
"django"
] |
VirtualBox command works correct in bash, but does not work in nginx | 40,109,509 | <p>We have a project on nginx/Django, using VirtualBox.
When we try to run command <code>VBoxManage list runningvms</code> in nginx, we have the next error:</p>
<pre class="lang-none prettyprint-override"><code>Failed to initialize COM because the global settings directory '/.config/VirtualBox' is not accessible!
</co... | 0 | 2016-10-18T13:22:03Z | 40,113,772 | <p>We have fixed the issue.</p>
<ol>
<li>There was wrong environment variable "Home" (os.environ['HOME']). We changed it, and so the problem was gone. </li>
<li>Using Python API for VB instead of ssh can really help you with that problem, as <strong>RegularlyScheduledProgramming</strong> suggested - we added Python A... | 0 | 2016-10-18T16:45:00Z | [
"python",
"django",
"bash",
"nginx",
"virtualbox"
] |
How to prevent shell script injection on my local webpage? | 40,109,555 | <p>I have an openwrt router that I use as a local webserver and I created a webpage to dial USSD on my 3G modem, the script looks like this:</p>
<pre><code><html>
<title>CHECK USSD</title>
<body>
<?php
if($_POST['send']){
$ussd=$_POST['ussd'];
exec('ussd.py '.$ussd,$out);
echo "R... | 1 | 2016-10-18T13:24:29Z | 40,109,724 | <p>The command you're looking for is <code>escapeshellarg()</code> so that your string is treated as a single argument.</p>
<pre><code>$pattern = '/Some regex that matches your potential inputs/';
if (preg_match($pattern, $ussd)) {
exec('ussd.py '.escapeshellarg($ussd),$out);
} else {
//throw error / response t... | 0 | 2016-10-18T13:31:43Z | [
"php",
"python",
"shell"
] |
Python GUI program in wxPython won't run | 40,109,565 | <p>I have the following code, and I am following a tutorial:</p>
<p>(<a href="http://zetcode.com/wxpython/layout/" rel="nofollow">http://zetcode.com/wxpython/layout/</a> - GoToClass part)</p>
<p>I can't figure out what is wrong with it ... :/</p>
<p>As you can see in the tutorial, it is supposed to produce this:</p>... | 0 | 2016-10-18T13:24:55Z | 40,109,753 | <p>It's just a typo. The correct way is <code>wx.SystemSettings.GetFont()</code>, also see this: <a href="https://wxpython.org/Phoenix/docs/html/wx.SystemSettings.html#wx.SystemSettings.GetFont" rel="nofollow">https://wxpython.org/Phoenix/docs/html/wx.SystemSettings.html#wx.SystemSettings.GetFont</a></p>
<p>Change you... | 3 | 2016-10-18T13:33:11Z | [
"python",
"wxpython"
] |
Fastest way to Factor (Prime-1)/2 for 64-bit Prime? | 40,109,623 | <p>I'm trying to gather some statistics on prime numbers, among which is the distribution of factors for the number (prime-1)/2. I know there are general formulas for the size of factors of uniformly selected numbers, but I haven't seen anything about the distribution of factors of one less than a prime.</p>
<p>I've w... | 1 | 2016-10-18T13:27:25Z | 40,110,783 | <p>This is how I store primes for later:
(I'm going to assume you want the factors of the number, and not just a primality test).</p>
<p>Copied from my website <a href="http://chemicaldevelopment.us/programming/2016/10/03/PGS.html" rel="nofollow">http://chemicaldevelopment.us/programming/2016/10/03/PGS.html</a></p>
<... | 0 | 2016-10-18T14:20:51Z | [
"python",
"c++",
"prime-factoring",
"factoring"
] |
Fastest way to Factor (Prime-1)/2 for 64-bit Prime? | 40,109,623 | <p>I'm trying to gather some statistics on prime numbers, among which is the distribution of factors for the number (prime-1)/2. I know there are general formulas for the size of factors of uniformly selected numbers, but I haven't seen anything about the distribution of factors of one less than a prime.</p>
<p>I've w... | 1 | 2016-10-18T13:27:25Z | 40,133,079 | <p>I don't have a definitive answer, but I do have some observations and some suggestions.</p>
<p>There are about 2*10^17 primes between 2^63 and 2^64, so any program you write is going to run for a while.</p>
<p>Let's talk about a primality test for numbers in the range 2^63 to 2^64. Any general-purpose test will do... | 1 | 2016-10-19T13:41:18Z | [
"python",
"c++",
"prime-factoring",
"factoring"
] |
Scrapy - How to load html string into open_in_browser function | 40,109,782 | <p>I am working on some code which returns an <code>HTML</code> string (<code>my_html</code>). I want to see how this looks in a browser using <a href="https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser" rel="nofollow">https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser</a>. To do this I'... | 0 | 2016-10-18T13:34:10Z | 40,110,049 | <p>Your error seems to be with the <code>TextResponse</code> initialization, <a href="https://doc.scrapy.org/en/latest/topics/request-response.html#textresponse-objects" rel="nofollow">according to the docs,</a> you need to initialize it with a URL, <code>TextResponse("http://www.expample.com")</code> should do it.</p>... | 1 | 2016-10-18T13:47:18Z | [
"python",
"scrapy"
] |
Scrapy - How to load html string into open_in_browser function | 40,109,782 | <p>I am working on some code which returns an <code>HTML</code> string (<code>my_html</code>). I want to see how this looks in a browser using <a href="https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser" rel="nofollow">https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser</a>. To do this I'... | 0 | 2016-10-18T13:34:10Z | 40,110,170 | <p><a href="https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.TextResponse" rel="nofollow"><code>TextResponse</code> expects a URL as first argument</a>:</p>
<pre><code>>>> scrapy.http.TextResponse('http://www.example.com')
<200 http://www.example.com>
>>>
</code></pre... | 1 | 2016-10-18T13:53:03Z | [
"python",
"scrapy"
] |
How to use Adobe afm fonts in matplotlib text? | 40,109,850 | <p>I want to add a text to a figure using an AFM font. I know that I can pass the <code>fontproperties</code> or the <code>fontname</code> keyword argument when creating a text. </p>
<p>Regarding the usage of AFM fonts in matplotlib, I found <a href="http://matplotlib.org/api/afm_api.html" rel="nofollow">this</a> and ... | 0 | 2016-10-18T13:37:48Z | 40,117,876 | <p>What is an "AFM font"? AFM files are <strong>A</strong>dobe <strong>F</strong>ont <strong>M</strong>etrics files, which only contain metadata around glyph bounds, kerning pairs, etc. as a convenient lookup mechanism when you don't want to mine the real font file for that information (handy for typesetting, where hav... | 0 | 2016-10-18T20:52:42Z | [
"python",
"matplotlib",
"fonts",
"adobe"
] |
Python numpy.fft changes strides | 40,109,915 | <p>Dear stackoverflow community!</p>
<p>Today I found that on a high-end cluster architecture, an elementwise multiplication of 2 cubes with dimensions 1921 x 512 x 512 takes ~ 27 s. This is much too long since I have to perform such computations at least 256 times for an azimuthal averaging of a power spectrum in the... | 1 | 2016-10-18T13:40:54Z | 40,116,293 | <p>You could use scipy.fftpack.fftn (as suggested by hpaulj too) rather than numpy.fft.fftn, looks like it's doing what you want. It is however slightly less performing:</p>
<pre><code>import numpy as np
import scipy.fftpack
ran = np.random.rand(192, 51, 51) # not much memory on my laptop
a = np.fft.fftn(ran)
b = sc... | 2 | 2016-10-18T19:16:52Z | [
"python",
"arrays",
"numpy",
"memory-management",
"fft"
] |
Python numpy.fft changes strides | 40,109,915 | <p>Dear stackoverflow community!</p>
<p>Today I found that on a high-end cluster architecture, an elementwise multiplication of 2 cubes with dimensions 1921 x 512 x 512 takes ~ 27 s. This is much too long since I have to perform such computations at least 256 times for an azimuthal averaging of a power spectrum in the... | 1 | 2016-10-18T13:40:54Z | 40,142,164 | <blockquote>
<p>Any reasons why numpy.fft.fftn() changes the strides and ideas on how to prevent that except for reversing the axes (which would be just a workaround)?</p>
</blockquote>
<p>Computing the multidimensionnal DFT of an array consists in successively computing 1D DTFs over each dimensions. There are two s... | 1 | 2016-10-19T21:56:14Z | [
"python",
"arrays",
"numpy",
"memory-management",
"fft"
] |
Anaconda OpenCV Arch Linux libselinux.so error | 40,110,207 | <p>I have installed Anaconda 64 bit on a relatively fresh install of Arch.</p>
<p>I followed the instructions <a href="https://rivercitylabs.org/up-and-running-with-opencv3-and-python-3-anaconda-edition/" rel="nofollow">here</a> to set up a virtual environment for opencv:</p>
<pre><code>conda create -n opencv numpy s... | 0 | 2016-10-18T13:54:19Z | 40,112,167 | <p>disabled the selinux, then do the command </p>
<pre><code>yum reinstall glibc*
</code></pre>
| 0 | 2016-10-18T15:23:45Z | [
"python",
"linux",
"opencv",
"anaconda"
] |
Anaconda OpenCV Arch Linux libselinux.so error | 40,110,207 | <p>I have installed Anaconda 64 bit on a relatively fresh install of Arch.</p>
<p>I followed the instructions <a href="https://rivercitylabs.org/up-and-running-with-opencv3-and-python-3-anaconda-edition/" rel="nofollow">here</a> to set up a virtual environment for opencv:</p>
<pre><code>conda create -n opencv numpy s... | 0 | 2016-10-18T13:54:19Z | 40,127,651 | <p>Fixed with installing the libselinux package in the AUR. I now have </p>
<pre><code>ImportError: /usr/lib/libpangoft2-1.0.so.0: undefined symbol: FcWeightToOpenType
</code></pre>
<p>will post if I solve</p>
<p>EDIT:
Solved as in issue <a href="https://github.com/ContinuumIO/anaconda-issues/issues/368" rel="nofoll... | 0 | 2016-10-19T09:39:56Z | [
"python",
"linux",
"opencv",
"anaconda"
] |
Numerical keyboard Python | 40,110,222 | <p>I am recording responses during a simple calculation task in Python, and I am storing these in a string. I would like to use the numerical part of the keyboard, but these give for instance 'num_1' instead of '1'. It probably has something to do that I store the input as a Text Stimulus in PsychoPy.. Any way to get a... | 0 | 2016-10-18T13:54:57Z | 40,111,374 | <p>If all your responses are preceded by "num_" you can just amputate them. For example <code>int(CapturedResponseString[4:])</code> will grab the numerical portion and turn it into an integer. </p>
<p>Python has lots of string processing tools that are much more sophisticated than this, and they are all available to ... | 2 | 2016-10-18T14:46:23Z | [
"python",
"psychopy"
] |
Python, scipy, curve_fit, bounds: How can I contstraint param by two intervals? | 40,110,260 | <p>I`m using scipy.optimize.curve_fit for fitting a sigmoidal curve to data. I need to bound one of parammeters from [-3, 0.5] and [0.5, 3.0]</p>
<p>I tried fit curve without bounds, and next if parameter is lower than zero, I fit once more with bounds [-3, 0.5] and in contrary with[0.5, 3.0]</p>
<p>Is it possible, ... | 0 | 2016-10-18T13:56:33Z | 40,116,907 | <p>No, least_squares (hence curve_fit) only supports box constraints.</p>
| 0 | 2016-10-18T19:52:47Z | [
"python",
"scipy",
"curve-fitting"
] |
Python, scipy, curve_fit, bounds: How can I contstraint param by two intervals? | 40,110,260 | <p>I`m using scipy.optimize.curve_fit for fitting a sigmoidal curve to data. I need to bound one of parammeters from [-3, 0.5] and [0.5, 3.0]</p>
<p>I tried fit curve without bounds, and next if parameter is lower than zero, I fit once more with bounds [-3, 0.5] and in contrary with[0.5, 3.0]</p>
<p>Is it possible, ... | 0 | 2016-10-18T13:56:33Z | 40,130,121 | <p>There is a crude way to do this, and that is to have your function return very large values if the parameter is outside the multiple bounds. For example:</p>
<pre><code>sigmoid_func(x, parameters):
if parameter outside multiple bounds:
return 1.0E10 * len(x) # very large number
else:
return... | 0 | 2016-10-19T11:26:30Z | [
"python",
"scipy",
"curve-fitting"
] |
Reading a binary file with memoryview | 40,110,306 | <p>I read a large file in the code below which has a special structure - among others two blocks that need be processed at the same time. Instead of seeking back and forth in the file I load these two blocks wrapped in <code>memoryview</code> calls</p>
<pre><code>with open(abs_path, 'rb') as bsa_file:
# ...
# ... | 0 | 2016-10-18T13:59:28Z | 40,113,126 | <p>A <code>memoryview</code> is not going to give you any advantages when it comes to null-terminated strings as they have no facilities for anything but fixed-width data. You may as well use <code>bytes.split()</code> here instead:</p>
<pre><code>file_names_block = bsa_file.read(total_file_name_length)
file_names = f... | 1 | 2016-10-18T16:08:41Z | [
"python",
"python-2.7",
"binaryfiles",
"memoryview"
] |
Django queryset with isnull=True in get_object_or_404 | 40,110,309 | <p>I have 2 records in the posts table, one of the row in table has <strong>rating as NULL</strong> and the other has <strong>rating as 2</strong>, both have same user_id say 5</p>
<p>I implement this first</p>
<p><strong>views.py</strong></p>
<pre><code>class Rating(TemplateView):
template_name = 'base/rating.h... | 0 | 2016-10-18T13:59:34Z | 40,110,557 | <p>You need read more carefully the django doc, the above code is incorrect.
To use get_object_or_404, you have to write something like(from django <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#get-object-or-404" rel="nofollow">doc</a>)</p>
<pre><code>from django.shortcuts import get_object_or... | -1 | 2016-10-18T14:11:04Z | [
"python",
"django"
] |
How this Python generators based inorder traversal method works | 40,110,401 | <p>I am quite new to python and still exploring. Came across generators and below code snippet implementing inorder binary tree traversal using generators:</p>
<pre><code>def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
... | -1 | 2016-10-18T14:03:50Z | 40,110,463 | <p><code>inorder</code> returns a generator. <em>That</em> object is what remembers its local state between calls to <code>next</code>. There is no overlap between generators created by separate calls to <code>inorder</code>, even when called recursively.</p>
| 2 | 2016-10-18T14:06:41Z | [
"python"
] |
How this Python generators based inorder traversal method works | 40,110,401 | <p>I am quite new to python and still exploring. Came across generators and below code snippet implementing inorder binary tree traversal using generators:</p>
<pre><code>def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
... | -1 | 2016-10-18T14:03:50Z | 40,110,886 | <p>I modified the code somewhat to get the idea of the flow of the execution sequence. Basically I added some <code>print()</code> statements.</p>
<pre><code>class BinaryTreeNode():
def __init__(self, pLeft, pRight, pValue):
self.left = pLeft
self.right = pRight
self.label = pValue
def ino... | 1 | 2016-10-18T14:25:20Z | [
"python"
] |
How to check if a string contains a dictionary | 40,110,468 | <p>I want to recursively parse all values in a dict that are strings with <code>ast.literal_eval(value)</code> but not do that eval if the string doesn't contain a dict. I want this, because I have a string in a dict that is a dict in itself and I would like the value to be a dict. Best to give an example</p>
<pre><co... | 4 | 2016-10-18T14:06:51Z | 40,110,943 | <p>If you need to handle nested <code>str</code> defining <code>dict</code>, <a href="https://docs.python.org/3/library/json.html#json.loads" rel="nofollow"><code>json.loads</code> with an <code>object_hook</code></a> might work for you:</p>
<pre><code>import json
def convert_subdicts(d):
for k, v in d.items():
... | 0 | 2016-10-18T14:27:44Z | [
"python",
"string",
"python-3.x",
"dictionary",
"recursion"
] |
How to check if a string contains a dictionary | 40,110,468 | <p>I want to recursively parse all values in a dict that are strings with <code>ast.literal_eval(value)</code> but not do that eval if the string doesn't contain a dict. I want this, because I have a string in a dict that is a dict in itself and I would like the value to be a dict. Best to give an example</p>
<pre><co... | 4 | 2016-10-18T14:06:51Z | 40,110,967 | <p>The general idea referenced in my above comment is to run thru the dictionary and try and evaluate. Store that in a local variable, and then check if that evaluated expression is a dictionary. If so, then reassign it to the passed input. If not, leave it alone. </p>
<pre><code>my_dict = {'a': 42, 'b': "my_string", ... | 1 | 2016-10-18T14:28:40Z | [
"python",
"string",
"python-3.x",
"dictionary",
"recursion"
] |
How to check if a string contains a dictionary | 40,110,468 | <p>I want to recursively parse all values in a dict that are strings with <code>ast.literal_eval(value)</code> but not do that eval if the string doesn't contain a dict. I want this, because I have a string in a dict that is a dict in itself and I would like the value to be a dict. Best to give an example</p>
<pre><co... | 4 | 2016-10-18T14:06:51Z | 40,111,122 | <p>You can check if you have a dict after using <em>literal_eval</em> and reassign:</p>
<pre><code>from ast import literal_eval
def reassign(d):
for k, v in d.items():
try:
evald = literal_eval(v)
if isinstance(evald, dict):
d[k] = evald
except ValueError:
... | 1 | 2016-10-18T14:35:06Z | [
"python",
"string",
"python-3.x",
"dictionary",
"recursion"
] |
How to check if a string contains a dictionary | 40,110,468 | <p>I want to recursively parse all values in a dict that are strings with <code>ast.literal_eval(value)</code> but not do that eval if the string doesn't contain a dict. I want this, because I have a string in a dict that is a dict in itself and I would like the value to be a dict. Best to give an example</p>
<pre><co... | 4 | 2016-10-18T14:06:51Z | 40,111,199 | <p>Here is a proposition that handles recursion. As it was suggested in the comments, it tries to eval everything then check if the result is a dict, if it is we recurse, else we skip the value . I sligthly altered the initial dict to show that it hanldes recusion fine :</p>
<pre><code>import ast
my_dict = {'a': 42, '... | 1 | 2016-10-18T14:38:44Z | [
"python",
"string",
"python-3.x",
"dictionary",
"recursion"
] |
Jupyter magic to handle notebook exceptions | 40,110,540 | <p>I have a few long-running experiments in my Jupyter Notebooks. Because I don't know when they will finish, I add an email function to the last cell of the notebook, so I automatically get an email, when the notebook is done.</p>
<p>But when there is a random exception in one of the cells, the whole notebook stops e... | 3 | 2016-10-18T14:10:22Z | 40,127,067 | <p>I don't think there is an out-of-the-box way to do that not using a <code>try..except</code> statement in your cells. AFAIK <a href="https://github.com/ipython/ipython/issues/1977" rel="nofollow">a 4 years old issue</a> mentions this, but is still in open status.</p>
<p>However, the <a href="https://github.com/ipyt... | 1 | 2016-10-19T09:15:22Z | [
"python",
"jupyter",
"jupyter-notebook"
] |
Jupyter magic to handle notebook exceptions | 40,110,540 | <p>I have a few long-running experiments in my Jupyter Notebooks. Because I don't know when they will finish, I add an email function to the last cell of the notebook, so I automatically get an email, when the notebook is done.</p>
<p>But when there is a random exception in one of the cells, the whole notebook stops e... | 3 | 2016-10-18T14:10:22Z | 40,128,704 | <p>A such magic command does not exist, but you can write it.</p>
<pre><code>from IPython.core.magic import register_cell_magic
@register_cell_magic
def handle(line, cell):
try:
exec(cell)
except Exception as e:
send_mail_to_myself(e)
</code></pre>
<p>It is not possible to load automatically ... | 2 | 2016-10-19T10:26:33Z | [
"python",
"jupyter",
"jupyter-notebook"
] |
Jupyter magic to handle notebook exceptions | 40,110,540 | <p>I have a few long-running experiments in my Jupyter Notebooks. Because I don't know when they will finish, I add an email function to the last cell of the notebook, so I automatically get an email, when the notebook is done.</p>
<p>But when there is a random exception in one of the cells, the whole notebook stops e... | 3 | 2016-10-18T14:10:22Z | 40,135,960 | <p>@show0k gave the correct answer to my question (in regards to magic methods). Thanks a lot! :)</p>
<p>That answer inspired me to dig a little deeper and I came across an IPython method that lets you define a <strong>custom exception handler for the whole notebook</strong>.</p>
<p>I got it to work like this:</p>
<... | 0 | 2016-10-19T15:38:44Z | [
"python",
"jupyter",
"jupyter-notebook"
] |
Scraping a webpage that is using a firebase database | 40,110,562 | <p><strong>DISCLAIMER: I'm just learning by doing, I have no bad intentions</strong></p>
<p>So, I would like to fetch the list of the applications listed on this website: <a href="http://roaringapps.com/apps" rel="nofollow">http://roaringapps.com/apps</a></p>
<p>I've done similar things in the past, but with simpler ... | 1 | 2016-10-18T14:11:27Z | 40,112,159 | <p>While the Firebase Database allows you to read/write JSON data. But its SDKs don't simply transfer the raw JSON data, they do many tricks on top of that to ensure an efficient and smooth experience. W</p>
<p>hat you're getting there is Firebase's wire protocol. The protocol is not publicly documented and (if you're... | 1 | 2016-10-18T15:23:32Z | [
"javascript",
"python",
"web",
"firebase",
"firebase-database"
] |
sqlalchemy.exc.AmbiguousForeignKeysError after Inheritance | 40,110,574 | <p>I'm using <code>sqlacodegen</code> for reflecting a bunch of tables from my database.
And i'm getting the following error:</p>
<blockquote>
<p>sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'Employee' and 'Sales'; tables have more than one foreign key constraint relationship between them. ... | 0 | 2016-10-18T14:12:00Z | 40,128,908 | <p>Just use backref and use Integer on both EmployeeID and OldemployeeID. Otherwise you will get an another error.</p>
<pre><code>class Sales(Employee):
__tablename__ = 'Sales'
EmployeeID = Column(Integer, ForeignKey('Employee.EmployeeId'), primary_key=True)
OldemployeeID = Column(Integer, ForeignKey('Emp... | 0 | 2016-10-19T10:34:36Z | [
"python",
"python-3.x",
"inheritance",
"sqlalchemy",
"sqlacodegen"
] |
Pre-Calculated Objects in Python | 40,110,694 | <p>Is there a way to pre-calculate an object in Python?</p>
<p>Like when you use a constructor just like:</p>
<pre><code>master = Tk()
</code></pre>
<p>Is there a way to pre-calculate and save the object and read it on startup instead of creating it?</p>
<p>My mind is all about saving work, or doing it in advance f... | 2 | 2016-10-18T14:17:17Z | 40,111,242 | <p>I think what you're looking for is the <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow"><code>pickle</code> module</a> to serialize an object. In Python 2 there is <code>pickle</code> and <code>cPickle</code>, which is the same but faster, but iirc Python 3 only has <code>pickle</code> (which, ... | 3 | 2016-10-18T14:40:58Z | [
"python",
"optimization"
] |
How can I tell if I have a file-like object? | 40,110,731 | <p>I want to have a function that writes data to a file:</p>
<pre><code>def data_writer(data, file_name):
spiffy_data = data # ...
with open(file_name, 'w') as out:
out.write(spiffy_data)
</code></pre>
<p>But sometimes, I have a file object instead of a file name. In this case, I sometimes have a <cod... | 0 | 2016-10-18T14:18:40Z | 40,110,875 | <p>While your approach is <a href="https://docs.python.org/3/glossary.html#term-lbyl" rel="nofollow"><code>LBYL</code></a>, it's pythonic to assume it's <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow"><code>EAFP</code></a>. So you could just <code>try</code> to </p>
<ul>
<li><code>write()</c... | 0 | 2016-10-18T14:24:45Z | [
"python",
"python-3.x"
] |
How can I tell if I have a file-like object? | 40,110,731 | <p>I want to have a function that writes data to a file:</p>
<pre><code>def data_writer(data, file_name):
spiffy_data = data # ...
with open(file_name, 'w') as out:
out.write(spiffy_data)
</code></pre>
<p>But sometimes, I have a file object instead of a file name. In this case, I sometimes have a <cod... | 0 | 2016-10-18T14:18:40Z | 40,111,061 | <p>A function should do one thing, and do that one thing well. In the case of <code>data_writer</code>, its one thing is to write data to a file-like object. Let the caller worry about providing such an object. That said, you can also provide that caller in the form of a wrapper that takes a file name and opens it for ... | 3 | 2016-10-18T14:32:28Z | [
"python",
"python-3.x"
] |
Foolproofing a Python calculator | 40,110,778 | <p>I'm writing a basic calculator which works with two different numbers.
So far, I managed to write a working prototype, but while dividing and foolproofing it I ran into a multitude of problems, so I'm posting them
separately. </p>
<hr>
<p>I want the program to repeat the question if the user doesn't provide an el... | 1 | 2016-10-18T14:20:35Z | 40,111,135 | <p>You need to actually call your function:</p>
<pre><code>def hulk_math():
optn = optn_query()
#The rest of your code
</code></pre>
<p>Also, unless <code>num1</code> and <code>num2</code> are defined elsewhere in your code such that they are in the scope of <code>hulk_math</code>, your program is going to fa... | 1 | 2016-10-18T14:35:42Z | [
"python",
"python-3.x",
"object",
"calculator"
] |
Foolproofing a Python calculator | 40,110,778 | <p>I'm writing a basic calculator which works with two different numbers.
So far, I managed to write a working prototype, but while dividing and foolproofing it I ran into a multitude of problems, so I'm posting them
separately. </p>
<hr>
<p>I want the program to repeat the question if the user doesn't provide an el... | 1 | 2016-10-18T14:20:35Z | 40,112,736 | <p>Ok, I fixed it by writing <code>global optn</code> instead of <code>return optn</code>. That way it makes the variable global, so other functions can use it.</p>
| 0 | 2016-10-18T15:49:35Z | [
"python",
"python-3.x",
"object",
"calculator"
] |
Foolproofing a Python calculator | 40,110,778 | <p>I'm writing a basic calculator which works with two different numbers.
So far, I managed to write a working prototype, but while dividing and foolproofing it I ran into a multitude of problems, so I'm posting them
separately. </p>
<hr>
<p>I want the program to repeat the question if the user doesn't provide an el... | 1 | 2016-10-18T14:20:35Z | 40,112,906 | <p>Using <code>global</code> isn't the right way to do this. Pass values from one function to another by saving their return values and passing them as arguments.</p>
<pre><code>def main():
intro()
num1 = num1_query()
optn = optn_query()
num2 = num2_query()
hulk_math(num1, optn, num2)
def hulk_ma... | 0 | 2016-10-18T15:57:39Z | [
"python",
"python-3.x",
"object",
"calculator"
] |
large data transformation in python | 40,110,780 | <p>I have a large data set (ten 12gb csv files) that have 25 columns and would want to transform it to a dataset with 6 columns. the first 3 columns remains the same whereas the 4th one would be the variable names and the rest contains data. Below is my input:</p>
<pre><code>#RIC Date[L] Time[L] Type L1-BidPric... | 0 | 2016-10-18T14:20:45Z | 40,112,986 | <p>You need to group the levels, i.e <code>L1-BidPrice L1-BidSize L1-AskPrice L1-AskSize</code> and write each to a new row :</p>
<pre><code>import csv
from itertools import zip_longest # izip_longest python2
with open("infile.csv") as f, open("out.csv", "w") as out:
next(f) # skip header
cols = ["#RIC", ... | 1 | 2016-10-18T16:02:24Z | [
"python",
"csv"
] |
Python reading in a file and parsing it to variables with whitespaces | 40,110,782 | <p>I have a text file (Students.txt) i need to read into python and parse them into variables first_name, middle_name, last_name, student_id. The first few lines of the text file is as shows: </p>
<pre><code>Last Name Midle Name First Name Student ID
----------------------------------------------
Howard Joe ... | 0 | 2016-10-18T14:20:47Z | 40,111,026 | <p>Probably you should use readlines(), and then loop over each line with skipping first 2 rows. Hence the code will look like</p>
<pre><code>f = open("Student.txt")
lines = f.readlines()
print lines
for line in lines[2:]:
fields = line.split()
last_name = fields[0]
middle_name = fields[1]
</code></pre>
| 1 | 2016-10-18T14:30:44Z | [
"python",
"parsing"
] |
Python backtest using percentage based commission | 40,110,800 | <p>I'm writing a script to backtest some strategies for a set of stocks using the bt framework for python. In the bt documentation (<a href="http://pmorissette.github.io/bt/bt.html#module-bt.backtest" rel="nofollow">backtest module</a>) it says: </p>
<blockquote>
<p>commission (fn(quantity)): The commission function... | 0 | 2016-10-18T14:21:30Z | 40,128,258 | <p>Solved it by creating a function with parameters for quantity and price. Thus it was easy returning a percentage based on the transaction cost as follows:</p>
<pre><code>def my_comm(q, p):
return abs(q)*p*0.0025
</code></pre>
| 0 | 2016-10-19T10:07:21Z | [
"python",
"pandas",
"stocks",
"back-testing"
] |
How can we simulate pass by reference in python? | 40,110,812 | <p>Let's say we have a function <code>foo()</code></p>
<pre><code>def foo():
foo.a = 2
foo.a = 1
foo()
>> foo.a
>> 2
</code></pre>
<p>Is this pythonic or should I wrap the variable in mutable objects such as a list?</p>
<p>Eg:</p>
<pre><code>a = [1]
def foo(a):
a[0] = 2
foo()
>> a
>>... | 0 | 2016-10-18T14:21:59Z | 40,111,008 | <p>Since you "want to mutate the variable so that the changes are effected in global scope as well" use the <code>global</code> keyword to tell your function that the name <code>a</code> is a global variable. This means that any assignment to <code>a</code> inside of your function affects the global scope. Without th... | 1 | 2016-10-18T14:29:52Z | [
"python",
"pass-by-reference"
] |
How can we simulate pass by reference in python? | 40,110,812 | <p>Let's say we have a function <code>foo()</code></p>
<pre><code>def foo():
foo.a = 2
foo.a = 1
foo()
>> foo.a
>> 2
</code></pre>
<p>Is this pythonic or should I wrap the variable in mutable objects such as a list?</p>
<p>Eg:</p>
<pre><code>a = [1]
def foo(a):
a[0] = 2
foo()
>> a
>>... | 0 | 2016-10-18T14:21:59Z | 40,111,328 | <p>Use a class (maybe a bit overkill):</p>
<pre><code>class Foo:
def __init__(self):
a = 0
def bar(f):
f.a = 2
foo = Foo()
foo.a = 1
bar(foo)
print(foo.a)
</code></pre>
| 0 | 2016-10-18T14:44:31Z | [
"python",
"pass-by-reference"
] |
AttributeError 'nonetype' object has no attribute 'recv' | 40,110,816 | <p>First of all I need to say I've never tried coding in python before... </p>
<p>I'm trying to make a Twitch IRC bot working but I keep failing... </p>
<p>My bot.py code looks like this: </p>
<pre><code>from src.lib import irc as irc_
from src.lib import functions_general
from src.lib import functions_commands as... | 0 | 2016-10-18T14:22:12Z | 40,111,748 | <p>Your <code>get_irc_socket_object(self)</code> might be the problem. You call it with the line <code>self.socket = self.irc.get_irc_socket_object()</code>. This means that python expects the function <code>get_irc_socket_object(self)</code> to return a socket object, but you don't return anything (you just write <cod... | 0 | 2016-10-18T15:01:52Z | [
"python",
"python-3.x"
] |
How to import a module from a different directory and have it look for files in that directory | 40,110,847 | <p>I'm trying to import a Python module in the directory <code>/home/kurt/dev/clones/ipercron-utils/tester</code>. This directory contains a <code>tester.py</code> and a <code>config.yml</code> file. The <code>tester.py</code> includes the (leading) line</p>
<pre><code>config = yaml.safe_load(open("config.yml"))
</cod... | 2 | 2016-10-18T14:23:35Z | 40,110,909 | <p><code>__file__</code> always contains the current module filepath (here <code>/home/kurt/dev/clones/ipercron-utils/tester/tester.py</code>).</p>
<p>Just perform a <code>dirname</code> on it => you have the path which contains your <code>yml</code> configuration file.</p>
<p>code it like this in your <code>tester.p... | 2 | 2016-10-18T14:26:04Z | [
"python"
] |
update threaded tkinter gui | 40,110,907 | <p>I have a small display connected to my pi.
Now I have a Python script that measures the time between two events of the gpio headers.
I want to display this time (the script to get this time is working perfectly). For that I created a <code>tkinter</code> window.
There, I have a label that should display this time.
I... | 0 | 2016-10-18T14:26:01Z | 40,111,304 | <p>Use <code>tkinter.StringVar</code></p>
<pre><code># omitting lines
global timevar
timevar = StringVar()
timevar.set("Test")
beattime = Label(app, textvariable=timevar)
# omitting lines
#changing the text:
while True:
time.sleep(.01)
if (GPIO.input(3)):
time = trigger() #trigger is the function t... | 0 | 2016-10-18T14:43:16Z | [
"python",
"multithreading",
"user-interface",
"tkinter",
"gpio"
] |
dictionary to pandas DataFrame | 40,111,091 | <p>I have this dictionary:</p>
<pre><code>diccionario = {'Monetarios':['B1','B2'],
'Monetario Dinamico':['B1','B2'],
'Renta fija corto plazo':['B1','B2'],
'Garantizados de RF':['B1','B2'],
'Renta Fija Largo Plazo':['B2','B3'],
'Garantizados de RV':['B2','B3']... | 2 | 2016-10-18T14:33:57Z | 40,111,152 | <p>I think you can use transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow"><code>T</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p>
<pre><cod... | 1 | 2016-10-18T14:36:24Z | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
dictionary convert to list and sort causing error [python2.7] | 40,111,271 | <p>I have a dictionary which is a histogram of different hours in a day:</p>
<blockquote>
<p>{'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18':
1, '09': 2, '17': 2, '06': 1, '07': 1}</p>
</blockquote>
<p>and I want to sort the dictionary based on the hours(first item) and produce something like... | 0 | 2016-10-18T14:42:24Z | 40,111,348 | <p>When you do <code>for ... in d</code>, the <code>dict</code> only iterates over the keys in the dictionary, not the values. Instead of getting a tuple of <code>hour, count</code>, you're getting a two-character string that's being split into <code>first_character, second_character</code> Not that each of the pairs ... | 0 | 2016-10-18T14:45:23Z | [
"python",
"list",
"python-2.7",
"dictionary"
] |
dictionary convert to list and sort causing error [python2.7] | 40,111,271 | <p>I have a dictionary which is a histogram of different hours in a day:</p>
<blockquote>
<p>{'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18':
1, '09': 2, '17': 2, '06': 1, '07': 1}</p>
</blockquote>
<p>and I want to sort the dictionary based on the hours(first item) and produce something like... | 0 | 2016-10-18T14:42:24Z | 40,111,412 | <p>You can try something like this:</p>
<pre><code>d = {'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18': 1, '09': 2, '17': 2, '06': 1, '07': 1}
l = list(d.iteritems())
l.sort()
print l
</code></pre>
<p>The output is:</p>
<pre><code>[('04', 3), ('06', 1), ('07', 1), ('09', 2), ('10', 3), ('11', 6)... | 1 | 2016-10-18T14:47:42Z | [
"python",
"list",
"python-2.7",
"dictionary"
] |
dictionary convert to list and sort causing error [python2.7] | 40,111,271 | <p>I have a dictionary which is a histogram of different hours in a day:</p>
<blockquote>
<p>{'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18':
1, '09': 2, '17': 2, '06': 1, '07': 1}</p>
</blockquote>
<p>and I want to sort the dictionary based on the hours(first item) and produce something like... | 0 | 2016-10-18T14:42:24Z | 40,111,429 | <p>You'll want to use <code>iteritems</code></p>
<pre><code>for hour, value in dict.iteritems():
etc.
</code></pre>
<p>Of course, you shouldn't use the name 'dict' -- rename it to something else since it's already the name of the <code>dict</code> class. You can also use <code>items()</code> if you want -- it tak... | 1 | 2016-10-18T14:48:27Z | [
"python",
"list",
"python-2.7",
"dictionary"
] |
dictionary convert to list and sort causing error [python2.7] | 40,111,271 | <p>I have a dictionary which is a histogram of different hours in a day:</p>
<blockquote>
<p>{'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18':
1, '09': 2, '17': 2, '06': 1, '07': 1}</p>
</blockquote>
<p>and I want to sort the dictionary based on the hours(first item) and produce something like... | 0 | 2016-10-18T14:42:24Z | 40,111,461 | <p>Go through both keys and values using <code>dict.items()</code>. Combine it with a list comprehension to get the list you want and finally sort it.</p>
<pre><code>a = {'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18': 1, '09': 2, '17': 2, '06': 1, '07': 1}
b = sorted([(x, y) for x, y in a.items(... | 0 | 2016-10-18T14:49:57Z | [
"python",
"list",
"python-2.7",
"dictionary"
] |
dictionary convert to list and sort causing error [python2.7] | 40,111,271 | <p>I have a dictionary which is a histogram of different hours in a day:</p>
<blockquote>
<p>{'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18':
1, '09': 2, '17': 2, '06': 1, '07': 1}</p>
</blockquote>
<p>and I want to sort the dictionary based on the hours(first item) and produce something like... | 0 | 2016-10-18T14:42:24Z | 40,111,489 | <p>I think you are simply iterating over dictionary keys instead of pairs of key and value.</p>
<p>Have a look at this post:
<a href="http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python">Iterating over dictionaries using for loops in Python</a></p>
<p>Your code should work... | 1 | 2016-10-18T14:50:53Z | [
"python",
"list",
"python-2.7",
"dictionary"
] |
How to Convert URLField in a Image on Django | 40,111,431 | <p>I have kept the url of an image on a URLField, such that as well as I can display the image on the model of my home page and not the string of the URL, I can not convert that direction, "www.google.es/images/car "in an image of a car?</p>
<p>models.py</p>
<pre><code>Photo class (models.Model):
    name = mode... | 0 | 2016-10-18T14:48:34Z | 40,111,458 | <p>You cannot convert the string into image however you can use the url in <code>src</code> attribute inside <code><img></code> tag</p>
<pre><code>for photo in photos:
html + = '<li><img src="' + photo.url + '"></ li>'
</code></pre>
<p>Remember that you are generating HTML for the website... | 1 | 2016-10-18T14:49:54Z | [
"python",
"django"
] |
How to Convert URLField in a Image on Django | 40,111,431 | <p>I have kept the url of an image on a URLField, such that as well as I can display the image on the model of my home page and not the string of the URL, I can not convert that direction, "www.google.es/images/car "in an image of a car?</p>
<p>models.py</p>
<pre><code>Photo class (models.Model):
    name = mode... | 0 | 2016-10-18T14:48:34Z | 40,111,507 | <p>Try:</p>
<pre><code>def home (request):
photos = Photo.objects.all ()
html = '<ul>'
for photo in photos:
html + = '<li><img src="{}"><li>'.format(photo.url)
html + = '</ ul>'
return HttpResponse (html)
</code></pre>
<p>Perhaps even better, again relyi... | 0 | 2016-10-18T14:51:40Z | [
"python",
"django"
] |
GeoTIFF issue with opening in PIL | 40,111,453 | <p>Everytime I open an GeoTIFF image of a orthophoto in python (tried PIL, matplotlib, scipy, openCV) the image screws up. Some corners are beeing cropped , however the image remains its original shape. If I manually convert the tif to for instance a png in Photoshop and load it, it does work correctly. So it seems lik... | 0 | 2016-10-18T14:49:31Z | 40,128,829 | <p>It would've been really nice if you put the link of the figure that you are using (if it's free). I downloaded a sample geotiff image from <a href="http://eoimages.gsfc.nasa.gov/images/imagerecords/57000/57752/land_shallow_topo_2048.tif" rel="nofollow">here</a>, and I used <a href="https://pypi.python.org/pypi/GDAL/... | 0 | 2016-10-19T10:31:26Z | [
"python",
"image",
"scipy",
"tiff",
"geotiff"
] |
pandas - agg() function | 40,111,546 | <p>The ordering of my age, height and weight columns is changing with each run of the code. I need to keep the order of my agg columns static because I ultimately refer to this output file according to the column locations. What can I do to make sure age, height and weight are output in the same order every time?</p>... | 1 | 2016-10-18T14:53:11Z | 40,111,581 | <p>I think you can use subset:</p>
<pre><code>df_out = df.groupby(df.index_col)
.agg({'age':np.mean, 'height':np.sum, 'weight':np.sum})[['age','height','weight']]
</code></pre>
<p>Also you can use <code>pandas</code> functions:</p>
<pre><code>df_out = df.groupby(df.index_col)
.agg({'age':'mean'... | 0 | 2016-10-18T14:54:33Z | [
"python",
"pandas",
"format"
] |
install quandl in pycharm | 40,111,605 | <p>I am trying to install quandl in PyCharm. I am trying to do this by going into project interpreter clicking the "+" button and then selecting Quandl. I am getting the following error.</p>
<p>OSError: [Errno 13] Permission denied: '/Users/raysabbineni/Library/Python/2.7'</p>
<p>I have installed pandas and sklearn i... | 0 | 2016-10-18T14:55:20Z | 40,111,939 | <p>try with sudo pip install (your package) on the terminal
sudo pip install quandl
Or
Sudo easy_install quandl</p>
| 1 | 2016-10-18T15:12:03Z | [
"python",
"pycharm",
"quandl"
] |
Yahoo finance API missing data for certain days | 40,111,621 | <p>I'm coding a script that fetches information from the Yahoo finance API and even though the API is pretty slow it works for what I'm going to use it for. During testing of the script I found out that I got an IndexOutOfBounds exception and up on investigation I see that Yahoo Finance is returning stock quote informa... | 1 | 2016-10-18T14:55:52Z | 40,122,701 | <p>This probably has nothing to do with the Python bindings, and it's entirely Yahoo data. If you read through the bindings, the command that runs is essentially</p>
<pre><code>curl -G 'https://query.yahooapis.com/v1/public/yql' \
--data-urlencode 'env=store://datatables.org/alltableswithkeys' \
--data-urlenco... | 0 | 2016-10-19T05:16:31Z | [
"python",
"api",
"yahoo-finance"
] |
Problems while transforming a python dict to a list of triples? | 40,111,624 | <p>I have the following python dict:</p>
<pre><code>{'token_list': [{'quote_level': '0', 'affected_by_negation': 'no', 'token_list': [{'quote_level': '0', 'affected_by_negation': 'no', 'token_list': [{'id': '21', 'analysis_list': [{'tag': 'GNUS3S--', 'lemma': 'Robert Downey Jr', 'original_form': 'Robert Downey Jr'}], ... | 0 | 2016-10-18T14:56:06Z | 40,114,072 | <p>You could use this code:</p>
<pre><code>def gettuples(data, level = 0):
if isinstance(data, dict):
if 'analysis_list' in data:
yield data['analysis_list'][0]
for val in data.values():
yield from gettuples(val)
elif isinstance(data, list):
for val in data:
... | 1 | 2016-10-18T17:01:08Z | [
"python",
"json",
"parsing",
"pandas",
"dictionary"
] |
Extract values from pandas stream | 40,111,647 | <p>I have very weird data coming via curl into my pandas dataframe. What I would like to do is extract values out of the column as described below. Can someone guide me how to extract the info?</p>
<pre><code>cc = pd.read_csv(cc_curl)
print(cc['srv_id'])
srv_id
------
TicketID 14593_ServiceID 104731
ServiceID
Ticket... | 1 | 2016-10-18T14:57:08Z | 40,112,793 | <p>If you want to extract this information into two new columns, you can do it this way:</p>
<pre><code>import numpy as np
import pandas as pd
In [22]: df[['TicketID','ServiceID']] = (
...: df.srv_id.str.extract(r'TicketID\s+(\d+).*?ServiceID\s+(\d+)', expand=True)
...: .replace(r'\b0\b', np.nan, regex=... | 2 | 2016-10-18T15:52:25Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
IndexError: list index out of range in Python 3 | 40,111,680 | <p>I am newbie to Python. I got the index error when I run the code. I have seen the relevant questions in Stackoverflow, but I still can't see what the bug is. I am very appreciated for any response. Thank you. Here is the code:</p>
<pre><code> class Card:
def __init__(self, suit = 0, rank = 2):
self.suit =... | 0 | 2016-10-18T14:58:59Z | 40,111,742 | <p>You have <code>13</code> items inside your <code>rank_names</code> list so the index of last element is of value <code>12</code> (lists are enumerated starting with <code>0</code>) - inside loop</p>
<pre><code>for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
</code></pre>
<... | 3 | 2016-10-18T15:01:45Z | [
"python"
] |
IndexError: list index out of range in Python 3 | 40,111,680 | <p>I am newbie to Python. I got the index error when I run the code. I have seen the relevant questions in Stackoverflow, but I still can't see what the bug is. I am very appreciated for any response. Thank you. Here is the code:</p>
<pre><code> class Card:
def __init__(self, suit = 0, rank = 2):
self.suit =... | 0 | 2016-10-18T14:58:59Z | 40,111,746 | <pre><code>class Card:
def __init__(self, suit = 0, rank = 2):
self.suit = suit
self.rank = rank
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names =[None,'Ace','2','3','4','5','6','7','9','10','Jack','Queen', 'King']
def __str__ (self):
return '%s of %s' % (Card.rank_n... | 2 | 2016-10-18T15:01:51Z | [
"python"
] |
IndexError: list index out of range in Python 3 | 40,111,680 | <p>I am newbie to Python. I got the index error when I run the code. I have seen the relevant questions in Stackoverflow, but I still can't see what the bug is. I am very appreciated for any response. Thank you. Here is the code:</p>
<pre><code> class Card:
def __init__(self, suit = 0, rank = 2):
self.suit =... | 0 | 2016-10-18T14:58:59Z | 40,111,886 | <p>use are missing '8' in rank_names</p>
<pre><code>class Card:
def __init__(self, suit = 0, rank = 2):
self.suit = suit
self.rank = rank
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names =[None,'Ace','2','3','4','5','6','7','8','9','10','Jack','Queen', 'King']
def __str__ (... | 0 | 2016-10-18T15:08:50Z | [
"python"
] |
How to use a dict to subset a DataFrame? | 40,111,730 | <p>Say, I have given a DataFrame with most of the columns being categorical data.</p>
<pre><code>> data.head()
age risk sex smoking
0 28 no male no
1 58 no female no
2 27 no male yes
3 26 no male no
4 29 yes female yes
</code></pre>
<p>And I would like to subse... | 7 | 2016-10-18T15:01:30Z | 40,112,030 | <p>You could build a boolean vector that checks those attributes. Probably a better way though: </p>
<pre><code>df[risk == 'no' and smoking == 'yes' and sex == 'female' for (age, risk, sex, smoking) in df.itertuples()]
</code></pre>
| 2 | 2016-10-18T15:17:10Z | [
"python",
"pandas",
"dataframe",
"categorical-data"
] |
How to use a dict to subset a DataFrame? | 40,111,730 | <p>Say, I have given a DataFrame with most of the columns being categorical data.</p>
<pre><code>> data.head()
age risk sex smoking
0 28 no male no
1 58 no female no
2 27 no male yes
3 26 no male no
4 29 yes female yes
</code></pre>
<p>And I would like to subse... | 7 | 2016-10-18T15:01:30Z | 40,112,316 | <p>You can create a look up data frame from the dictionary and then do an inner join with the <code>data</code> which will have the same effect as <code>query</code>:</p>
<pre><code>from pandas import merge, DataFrame
merge(DataFrame(tmp, index =[0]), data)
</code></pre>
<p><a href="https://i.stack.imgur.com/xW4kf.pn... | 3 | 2016-10-18T15:31:04Z | [
"python",
"pandas",
"dataframe",
"categorical-data"
] |
How to use a dict to subset a DataFrame? | 40,111,730 | <p>Say, I have given a DataFrame with most of the columns being categorical data.</p>
<pre><code>> data.head()
age risk sex smoking
0 28 no male no
1 58 no female no
2 27 no male yes
3 26 no male no
4 29 yes female yes
</code></pre>
<p>And I would like to subse... | 7 | 2016-10-18T15:01:30Z | 40,112,387 | <p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">.query()</a> method for this task:</p>
<pre><code>In [103]: qry = ' and '.join(["{} == '{}'".format(k,v) for k,v in tmp.items()])
In [104]: qry
Out[104]: "sex == 'female' and risk == 'no' an... | 3 | 2016-10-18T15:33:25Z | [
"python",
"pandas",
"dataframe",
"categorical-data"
] |
How to use a dict to subset a DataFrame? | 40,111,730 | <p>Say, I have given a DataFrame with most of the columns being categorical data.</p>
<pre><code>> data.head()
age risk sex smoking
0 28 no male no
1 58 no female no
2 27 no male yes
3 26 no male no
4 29 yes female yes
</code></pre>
<p>And I would like to subse... | 7 | 2016-10-18T15:01:30Z | 40,125,748 | <p>You can use list comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a>:</p>
<pre><code>import numpy... | 2 | 2016-10-19T08:15:30Z | [
"python",
"pandas",
"dataframe",
"categorical-data"
] |
How to use a dict to subset a DataFrame? | 40,111,730 | <p>Say, I have given a DataFrame with most of the columns being categorical data.</p>
<pre><code>> data.head()
age risk sex smoking
0 28 no male no
1 58 no female no
2 27 no male yes
3 26 no male no
4 29 yes female yes
</code></pre>
<p>And I would like to subse... | 7 | 2016-10-18T15:01:30Z | 40,126,366 | <p>I think you can could use the <code>to_dict</code> method on your dataframe, and then filter using a list comprehension:</p>
<pre class="lang-python prettyprint-override"><code>df = pd.DataFrame(data={'age':[28, 29], 'sex':["M", "F"], 'smoking':['y', 'n']})
print df
tmp = {'age': 28, 'smoking': 'y', 'sex': 'M'}
pr... | 0 | 2016-10-19T08:45:41Z | [
"python",
"pandas",
"dataframe",
"categorical-data"
] |
matplotlib image shows in black and white, but I wanted gray | 40,111,822 | <p>I have a small code sample to plot images in matplotlib, and the image is shown as this :</p>
<p><a href="https://i.stack.imgur.com/r4CPR.png" rel="nofollow"><img src="https://i.stack.imgur.com/r4CPR.png" alt="enter image description here"></a></p>
<p>Notice the image in the black box has black background, while m... | 1 | 2016-10-18T15:05:28Z | 40,125,210 | <p>The problem seems to be that you have three channels while there should be only one, and that the data should be normalized between <code>[0, 1]</code>. I get a proper looking gray scaled image using this:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpim... | 0 | 2016-10-19T07:47:43Z | [
"python",
"matplotlib"
] |
Construct pandas dataframe from a .fits file | 40,111,872 | <p>I have a .fits file that contains data. </p>
<p>I would like to construct a pandas dataframe from this particular file but I don't know how to do it. </p>
<pre><code>data = fits.open('datafile')
data.info
</code></pre>
<p>gives: </p>
<pre><code>No. Name Type Cards Dimensions Format
0 PRIMA... | 0 | 2016-10-18T15:07:48Z | 40,112,001 | <p>According to what you have in your question and the astropy docs (<a href="http://docs.astropy.org/en/stable/io/fits/" rel="nofollow">http://docs.astropy.org/en/stable/io/fits/</a>), it looks like you just need to do: </p>
<pre><code>from astropy.io import fits
import pandas
with fits.open('datafile') as data:
... | 4 | 2016-10-18T15:15:52Z | [
"python",
"pandas",
"dataframe",
"astropy"
] |
Why won't values between 100 and 1000 work when playing Four is Magic, excluding values by 100 | 40,112,003 | <p>Everything works besides values between 100 and 999, except values divisible by 100 work.</p>
<p>The game is as follows:</p>
<p>Four is magic. Write a Python program (called q3.py) that given an integer from 0 to 1000 does the â4 is magicâ transformation. The steps are as follows:</p>
<ol>
<li>Convert the int... | -3 | 2016-10-18T15:16:00Z | 40,112,409 | <p><code>convert</code> always returns <code>"four is magic"</code> It looks like you want it to return some value based on its input. </p>
| 0 | 2016-10-18T15:34:22Z | [
"python",
"python-3.x",
"simulation"
] |
Why won't values between 100 and 1000 work when playing Four is Magic, excluding values by 100 | 40,112,003 | <p>Everything works besides values between 100 and 999, except values divisible by 100 work.</p>
<p>The game is as follows:</p>
<p>Four is magic. Write a Python program (called q3.py) that given an integer from 0 to 1000 does the â4 is magicâ transformation. The steps are as follows:</p>
<ol>
<li>Convert the int... | -3 | 2016-10-18T15:16:00Z | 40,112,451 | <pre><code>def convert(number_str):
# Enter your code here.
count = 0
index = 0
x = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
y = ['zero','ten','twenty','thirty','forty'... | 0 | 2016-10-18T15:36:05Z | [
"python",
"python-3.x",
"simulation"
] |
calcuale ----OverflowError: long int too large to convert to float | 40,112,133 | <pre><code>en_1 = 1
n = 1
factorial = 1
invfactorial = 1
while en_1 > 1e-6 :
en = en_1 +invfactorial
n = n + 1
factorial = factorial * n
invfactorial = float(1.0/factorial)
en_1 = en
print "e = %.5f"%en
</code></pre>
<p>I want to calculate e via this code, but it cannot ... | 0 | 2016-10-18T15:22:23Z | 40,113,227 | <p><code>en_1 > 1e-6</code> will never evaluate to <code>True</code>. <code>en_1</code> just gets bigger and bigger. At some point you end up with numbers so large that Python can't handle the conversions. Instead compare to <code>invfactorial > 1e-6</code>:</p>
<pre><code>en_1 = 1
n = 1
factorial = 1
invfact... | 1 | 2016-10-18T16:13:56Z | [
"python",
"python-2.7"
] |
Efficiently handling duplicates in a Python list | 40,112,139 | <p>I'm looking to compactly represent duplicates in a Python list / 1D numpy array. For instance, say we have </p>
<pre><code> x = np.array([1, 0, 0, 3, 3, 0])
</code></pre>
<p>this array has several duplicate elements, that can be represented with a </p>
<pre><code> group_id = np.array([0, 1, 1, 2, 2, 1])
</code></... | 0 | 2016-10-18T15:22:35Z | 40,112,380 | <p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>numpy.unique</code></a>:</p>
<pre><code>In [13]: x = np.array([1, 0, 0, 3, 3, 0])
In [14]: values, cluster_id = np.unique(x, return_inverse=True)
In [15]: values
Out[15]: array([0, 1, 3])
In [16]: ... | 1 | 2016-10-18T15:33:12Z | [
"python",
"algorithm",
"numpy",
"grouping",
"graph-algorithm"
] |
Efficiently handling duplicates in a Python list | 40,112,139 | <p>I'm looking to compactly represent duplicates in a Python list / 1D numpy array. For instance, say we have </p>
<pre><code> x = np.array([1, 0, 0, 3, 3, 0])
</code></pre>
<p>this array has several duplicate elements, that can be represented with a </p>
<pre><code> group_id = np.array([0, 1, 1, 2, 2, 1])
</code></... | 0 | 2016-10-18T15:22:35Z | 40,113,174 | <p>Here's an approach using <a href="https://numeric.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a> to keep the order according to the first appearance of a number -</p>
<pre><code>unq, first_idx, ID = np.unique(x,return_index=1,return_inverse=1)
out = first_idx.ar... | 1 | 2016-10-18T16:10:59Z | [
"python",
"algorithm",
"numpy",
"grouping",
"graph-algorithm"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.