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 |
|---|---|---|---|---|---|---|---|---|---|
Understanding the runtime of numpy.where and equivalent alternatives | 38,313,400 | <p>According to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html</a>, if x and y are given and input arrays are 1-D, where is equivalent to <code>[xv if c else yv for (c,xv, yv) in zip(x!=0, 1/x, x)]</code>... | 2 | 2016-07-11T18:04:40Z | 38,313,837 | <p>You just asked about 'delaying' the 'where':</p>
<p><a href="http://stackoverflow.com/questions/38276813/numpy-where-how-to-delay-evaluating-parameters">numpy.where : how to delay evaluating parameters?</a></p>
<p>and someone else just asked about divide by zero:</p>
<p><a href="http://stackoverflow.com/questions... | 3 | 2016-07-11T18:33:59Z | [
"python",
"arrays",
"numpy"
] |
Understanding the runtime of numpy.where and equivalent alternatives | 38,313,400 | <p>According to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html</a>, if x and y are given and input arrays are 1-D, where is equivalent to <code>[xv if c else yv for (c,xv, yv) in zip(x!=0, 1/x, x)]</code>... | 2 | 2016-07-11T18:04:40Z | 38,313,839 | <p>Consider changing the array <strong>in place</strong> by using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.put.html" rel="nofollow"><code>np.put()</code></a>:</p>
<pre><code>In [56]: x = np.linspace(-1, 1, 5)
In [57]: x
Out[57]: array([-1. , -0.5, 0. , 0.5, 1. ])
In [58]: indices = np.ar... | 0 | 2016-07-11T18:34:05Z | [
"python",
"arrays",
"numpy"
] |
Why does a Python script to read files cause my computer to emit beeping sounds? | 38,313,445 | <p>I wrote a little module that will search files in a directory and all of its sub-directories for the occurrence of some input string. It's been handy a few times, mostly to find old scripts if I remember some function/variable name that I used.</p>
<p>So, I was completely baffled the other day when I used the funct... | 10 | 2016-07-11T18:07:40Z | 38,313,491 | <p>This line:</p>
<pre><code>print count,line,dir_element
</code></pre>
<p>is probably printing the <a href="https://en.wikipedia.org/wiki/Bell_character">BEL character</a> if you feed your program binary files.</p>
<p>To test, here's a little code I wrote. Python will try and play it note-for-note. Don't worry. Be ... | 18 | 2016-07-11T18:10:57Z | [
"python"
] |
Python: Printing data only when number enters or leaves interval | 38,313,450 | <p>Currently I'm making a script that, given a set of celestial coordinates, will tell you on the next days when that point will be visible for a specific telescope. The criteria is simple, in the Horizontal Coordinate system, altitude of the object must be between 30 and 65 degrees(Variable "crit" here represents that... | 1 | 2016-07-11T18:07:54Z | 38,313,514 | <p>You need to keep track of whether it is already in range. So, for instance, at the beginning you'd initialize it:</p>
<pre><code>is_visible = False
</code></pre>
<p>and your if statement might look like:</p>
<pre><code>if crit>=0.523599 and crit <=1.13446:
if not is_visible:
print "Visible at %s... | 2 | 2016-07-11T18:12:29Z | [
"python",
"astronomy",
"pyephem"
] |
python pip cryptography build wheel fail | 38,313,548 | <p>I am trying to install python packages like quandl. Since I am using pip3 I am installing the package using the following command in ubuntu 16.</p>
<pre><code>sudo pip3 install quandl
</code></pre>
<p>This gives me the following error. </p>
<pre><code>Running setup.py clean for cryptography
Failed to build crypto... | 0 | 2016-07-11T18:14:33Z | 38,313,779 | <p>Cleared the error. I installed the openssl. I upgraded cryptography.</p>
<p>Install open-ssl using the following command for ubuntu.</p>
<pre><code>sudo apt-get install libssl-dev.
</code></pre>
| 0 | 2016-07-11T18:29:45Z | [
"python",
"ubuntu",
"cryptography",
"pip",
"quandl"
] |
Freeswitch detect Fax programmatically | 38,313,649 | <p>I'm currently generating dial outs using "ESL with Python library" and the <strong>originate</strong> command.
Since some dial out calls are <strong>Fax</strong> I need to classify which of these calls are fax, otherwise I record the ones which are normally answered by humans, voice mail or auto-attendants.</p>
<p>... | 0 | 2016-07-11T18:20:42Z | 38,642,238 | <p><code>execute_on_fax_detect</code> is only for incoming calls to detect fax.
<code>originate loopback/9178 &txfax(/tmp/surface3d.tiff)</code> this you making call to loopback and on answer it starts transmitting tiff file. so you're seeing fax modules invoked.
try <code>tone_detect</code> to see if you can achi... | 1 | 2016-07-28T16:43:07Z | [
"python",
"freeswitch",
"fax"
] |
ImportError: No module named spiders on mac OS using Homebrew installation package | 38,313,660 | <p>All, </p>
<p>I followed the following steps from scrapy.org to updated default system packages and install scrapy, the open source framework for building spiders found here: <a href="http://doc.scrapy.org/en/1.1/intro/install.html" rel="nofollow">http://doc.scrapy.org/en/1.1/intro/install.html</a></p>
<ol>
<li>I r... | 0 | 2016-07-11T18:21:21Z | 38,314,419 | <p>Check in <code>scrapy/tutorial/tutorial/spiders/[your_spider].py</code> the name of your spider, that should be run with <code>scrapy crawl</code> command. In the example below, the name is <code>dmozdirectory</code> and the run command is <code>scrapy crawl dmozdirectory</code></p>
<p>Example:</p>
<pre><code>clas... | 0 | 2016-07-11T19:10:04Z | [
"python",
"scrapy",
"homebrew"
] |
PL/Python & postgreSQL: What is the best way to return a table of many columns? | 38,313,718 | <p>In Pl/Python "RETURNS setof" or "RETURNS table" clause are used to return a table like structured data. It seems to me that one has to provide the name of each column to get a table returned. If you have a table with a few columns it is an easy thing. However, if you have a table of 200 columns, what's the best way... | 0 | 2016-07-11T18:25:48Z | 38,315,231 | <p>Try this:</p>
<pre><code>CREATE OR REPLACE FUNCTION myFunc02()
RETURNS TABLE (like mysales) AS
$$
rv = plpy.execute('SELECT * FROM mysales ORDER BY id;', 5)
d = rv.nrows()
return rv[0:d]
$$ LANGUAGE 'plpythonu';
</code></pre>
<p>which returns:</p>
<pre><code>gpadmin=# SELECT * FROM myFunc02(); ... | 0 | 2016-07-11T20:01:03Z | [
"python",
"postgresql",
"greenplum"
] |
Python regex curly brackets multiline | 38,313,784 | <p>I'm writing in python and let's say I have a file looking like this:</p>
<pre><code>aaa
aaa "word" --sdsdrrr2 --sds {
test test
}
aaa "word2" --sdsdd sdsd {
fffsd
ssss
}
aaa "word3" -sdksdld sdsd
{
sdsdd
sdsddd
sdsdddd }
</code></pre>
<p>now I want to parse output for "word2" including... | 1 | 2016-07-11T18:29:54Z | 38,313,838 | <p>You could do it like:</p>
<pre><code>^(?=.*"word2") # ^ - start of the line with pos. lookahead
[^{]+ # anything not a {
{[^}]+} # followed by {, anything in between and a closing }
</code></pre>
<p>See <a href="https://regex101.com/r/gE7uF3/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>... | 0 | 2016-07-11T18:34:00Z | [
"python",
"regex",
"multiline",
"brackets"
] |
Plotting Time Values in Matplotlib | 38,313,798 | <p>I am trying to plot time values vs. column readings by uploading a text file with data that looks like:</p>
<pre><code>16:07:24,9.13084E+15
16:07:24,8.46849E+18
16:07:24,5.94966E+22
16:07:24,7.15403E+21
16:07:24,3.72465E+14
16:07:24,8.13681E+15
</code></pre>
<p>My code looks like:</p>
<pre><code>import numpy as n... | 0 | 2016-07-11T18:30:36Z | 38,313,995 | <p>The <code>datetime</code> module contains a class named <code>datetime</code>. <code>strptime</code> is a class method of the latter, so you should call <code>datetime.datetime.strptime</code>.</p>
| 0 | 2016-07-11T18:43:09Z | [
"python",
"matplotlib"
] |
How to plot the horizontal bar graph in the given sequence of a dictionary? | 38,313,816 | <p>I have the following dict in <strong>Python 2.7</strong>:</p>
<pre><code>packetsNeeded = {
'Hydrogen': 142,
'Helium': 122,
'Lithium': 135,
'Boron': 145,
'Beryllium': 135,
'Nitrogen': 171,
'Neon': 141,
'Oxygen': 134,
'Carbon': 239,
'Florine': 134
}
</code></pre>
<p>I have written a script where I draw a horizontal ... | 0 | 2016-07-11T18:32:18Z | 38,327,029 | <p>Thanks to @Tim for suggestion of collecting data as a <em>List of Tuples</em> since</p>
<blockquote>
<p>that the answer may be that dictionaries are not ordered in memory</p>
</blockquote>
<p>The collected data was now represented as a <strong>List of Tuples</strong>:</p>
<pre><code>from pylab import *
## List... | 0 | 2016-07-12T11:02:55Z | [
"python",
"dictionary",
"matplotlib",
"bar-chart"
] |
How to know if a service is installed | 38,313,859 | <p>I'm looking for a way to check with a Python script if a service is installed. For example, if I want to check than a SSH server in installed/running/down in command line, I used : </p>
<pre><code>service sshd status
</code></pre>
<p>If the service is not installed, I have a message like this:</p>
<pre><code>ss... | 0 | 2016-07-11T18:35:00Z | 38,314,935 | <p>Choose some different <code>systemctl</code> call, which differs for existing and non-existing services. For example</p>
<pre><code>systemctl cat sshd
</code></pre>
<p>will return exit code <code>0</code> if the service exists and <code>1</code> if not. And it should be quite easy to check, isn't it?</p>
| 0 | 2016-07-11T19:42:00Z | [
"python",
"service",
"subprocess",
"sshd"
] |
How to know if a service is installed | 38,313,859 | <p>I'm looking for a way to check with a Python script if a service is installed. For example, if I want to check than a SSH server in installed/running/down in command line, I used : </p>
<pre><code>service sshd status
</code></pre>
<p>If the service is not installed, I have a message like this:</p>
<pre><code>ss... | 0 | 2016-07-11T18:35:00Z | 38,315,035 | <p>Just catch the error and avoid <code>shell=True</code>:</p>
<pre><code>import subprocess
try:
output = subprocess.check_output(["service", "sshd", "status"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print(e.output)
print(e.returncode)
</code></pre>
| 0 | 2016-07-11T19:48:11Z | [
"python",
"service",
"subprocess",
"sshd"
] |
Python requests module, how to issue multiple requests in the for loop? | 38,313,875 | <p>I wonder why when I call requests.get() method consequentially, like this:</p>
<pre><code>response = requests.get(url.format("set"))
print(response.status_code)
response = requests.get(url.format("map"))
print(response.status_code)
response = requests.get(url.format("list"))
print(response.status_code)
response = r... | 1 | 2016-07-11T18:36:02Z | 38,314,314 | <p>You have trailing newlines that you need to <em>strip</em> off:</p>
<pre><code>with open('dummyWords.txt') as fIn:
for word in map(str.strip, fIn) :
</code></pre>
<p>It works for the last as you obviously have no newline at the end of the last word in the file. <code>"www.foo.com\n"</code> is not the same as <... | 2 | 2016-07-11T19:03:37Z | [
"python",
"python-requests"
] |
Why does python 2.4 keep ignoring my exit function? | 38,313,911 | <p>I've written a script that only runs on version 2.6 or 2.7. I've placed in a safety check to see if another version is installed and to also check if there are any compatible versions available. Here is my code snippet;</p>
<pre><code># !/usr/bin/python
import sys, os, re
from sys import exit
if sys.version[0:3] ... | 0 | 2016-07-11T18:38:32Z | 38,313,986 | <p>Python 2.4 doesn't have the <code>with</code> syntax support yet, so the script fails at the parsing stage, rather than at runtime. You can work around that by having some wrapper like:</p>
<pre><code>if version_check_ok():
import actual_app
actual_app.run()
else:
...
</code></pre>
<p>This way the new ... | 4 | 2016-07-11T18:42:35Z | [
"python",
"exit",
"python-2.4"
] |
Requiring only one of two dependencies in a requirements file | 38,313,917 | <p>Some Python packages require one of two packages as a dependency. For example, <code>Ghost.py</code> requires either <code>PySide</code> or <code>PyQt4</code>.</p>
<p>Is it possible to include such a dependency in a <code>requirements.txt</code> file? Is there any 'or' operator that works with these files?</p>
<p>... | 2 | 2016-07-11T18:38:40Z | 38,321,172 | <p>Currently neither pip's <code>requirement.txt</code> nor setuptools directly allow such a construction. Both require you to specify a list of requirements. You can restrict the version of a requirement, but that's all.</p>
<p>Inside Python, you can handle this situation as follows:</p>
<pre><code>try:
import d... | 2 | 2016-07-12T06:09:40Z | [
"python",
"python-2.7",
"pip",
"requirements.txt"
] |
Requiring only one of two dependencies in a requirements file | 38,313,917 | <p>Some Python packages require one of two packages as a dependency. For example, <code>Ghost.py</code> requires either <code>PySide</code> or <code>PyQt4</code>.</p>
<p>Is it possible to include such a dependency in a <code>requirements.txt</code> file? Is there any 'or' operator that works with these files?</p>
<p>... | 2 | 2016-07-11T18:38:40Z | 38,322,886 | <p>I would use a small Python script to accomplish this</p>
<pre><code>#!/usr/bin/env python
packages = 'p1 p2 p3'.split()
try:
import optional1
except ImportError: # opt1 not installed
try:
import optional2
except ImportError: # opt2 not installed
packages.append('optional2')
print(' '.... | 1 | 2016-07-12T07:47:45Z | [
"python",
"python-2.7",
"pip",
"requirements.txt"
] |
What is this as a for loop not list comprehension? | 38,313,922 | <p>I came across a program and want to know what the program would be without the list comprehensions. Shown below is the code Thank You:</p>
<pre><code>sentence = input("Enter a sentence: ")
sentence = sentence.lower().split()
uniquewords = []
for word in sentence:
if word not in uniquewords:
uniquewords.... | -3 | 2016-07-11T18:38:52Z | 38,316,021 | <p>A list comprehension can be replaced by a more-or-less equivalent <code>for</code> loop. Consider these two snippets:</p>
<pre><code># 1
a = [f(b) for b in expression]
# 2
a = []
for b in expression:
a.append(f(b))
</code></pre>
<p>You can see how the elements of the list comprehension appear in the expanded ... | 0 | 2016-07-11T20:52:08Z | [
"python"
] |
ImportError: No module named numpy :different | 38,313,924 | <p>I know this question has been asked few times, however, none of those solutions worked for me, so I thought of reposting the question in my context.</p>
<p>I have downloaded IDLE and Python2.7, and trying to run a python script. The above error is shown. I have verified that numpy is present somewhere in my comp., ... | -1 | 2016-07-11T18:39:04Z | 38,314,757 | <p>As some of your comments above stated, you have not actually installed NumPy, as NumPy does not come with the base package of Python. My suggestion is to look into python package such as <a href="https://www.continuum.io/downloads" rel="nofollow">Anaconda</a> or <a href="https://winpython.github.io/" rel="nofollow">... | 0 | 2016-07-11T19:31:24Z | [
"python",
"numpy"
] |
Advice on database access approach in a custom environment using Python Pyramid | 38,313,969 | <p>Iâm new to Pyramid. Iâve used Python for a few months. I've created a Python application on Linux to maintain an Oracle database using weekly data feeds from a vendor. To get that done, one of the things I did was to create a customized database wrapper class using the cx_Oracle package. I had specific requireme... | 0 | 2016-07-11T18:41:12Z | 38,324,294 | <p>You should definitely use SQLAlchemy as it makes use of connection pooling and such. In your case SQLAlchemy would use cx_Oracle underneath but make you be able to concentrate writing actual code instead of maintaining connections/pooling them/and such.</p>
<p>You should follow the patterns in <a href="http://docs.... | 0 | 2016-07-12T09:00:38Z | [
"python",
"database",
"oracle",
"sqlalchemy",
"pyramid"
] |
Advice on database access approach in a custom environment using Python Pyramid | 38,313,969 | <p>Iâm new to Pyramid. Iâve used Python for a few months. I've created a Python application on Linux to maintain an Oracle database using weekly data feeds from a vendor. To get that done, one of the things I did was to create a customized database wrapper class using the cx_Oracle package. I had specific requireme... | 0 | 2016-07-11T18:41:12Z | 38,360,705 | <p>So, basically, the question boils down to "how do I use my existing API with Pyramid", right? This is quite easy as Pyramid is database-agnostic and very transparent in this area despite what you say :) Basically, you import it, call its methods, retrieve data and send it to the template:</p>
<pre><code>import poke... | 0 | 2016-07-13T20:01:43Z | [
"python",
"database",
"oracle",
"sqlalchemy",
"pyramid"
] |
Watson Retrieve and Rank: Python Bluemix runtime | 38,314,004 | <p>I am trying to run through the following tutorial on Bluemix:
<a href="https://www.ibm.com/watson/developercloud/doc/retrieve-rank/get_start.shtml" rel="nofollow">https://www.ibm.com/watson/developercloud/doc/retrieve-rank/get_start.shtml</a></p>
<p>However, I am not able to install Python locally onto my system du... | 0 | 2016-07-11T18:43:34Z | 38,322,406 | <p>An alternative to the manual Python and curl commands in that tutorial is to use the web interface. </p>
<p>I've written about it in some detail <a href="http://dalelane.co.uk/blog/?p=3381" rel="nofollow">on my blog</a> which also includes a <a href="https://youtu.be/SveIksv7V9E" rel="nofollow">video walkthrough</a... | 1 | 2016-07-12T07:22:12Z | [
"python",
"ibm-bluemix",
"ibm-watson-cognitive",
"retrieve-and-rank"
] |
Django: Filter, list, session | 38,314,005 | <p>I have some question on Django and how to use it to solve the problem below.
Suppose you have this two table
Products table</p>
<pre><code> ---------------------------------------------------------------
| id | productName | description | id_country |
-------------------------------------------------... | 0 | 2016-07-11T18:43:37Z | 38,314,059 | <p>You've said it yourself in the question tags: use the session.</p>
<p>When the user chooses a country, set that value in the <code>request.session</code> dict; then, in each of your views, filter the products by that value.</p>
| 0 | 2016-07-11T18:47:51Z | [
"python",
"django",
"session",
"implementation"
] |
Problems with django cookies | 38,314,115 | <p>How do you properly set cookies in Django?</p>
<p>I have tried this:</p>
<pre><code> re=HttpResponse('Hello world')
re.set_cookie('key','value')
</code></pre>
<p>and also this:</p>
<pre><code> request.COOKIES['key']='value'
</code></pre>
<p>None of these are working and I have yet to figure out why.</p>
<p><s... | 0 | 2016-07-11T18:51:07Z | 38,321,876 | <p>Finally I figured out that the reason why cookies are not set is that I am nor returning my response object . Here is final version</p>
<pre><code>re=HttpResponse('/')
re.set_cookie('language',request.POST.get('lang','') )
return re
</code></pre>
| 0 | 2016-07-12T06:52:29Z | [
"python",
"django",
"cookies",
"browser"
] |
"OverflowError: Python int too large to convert to C long" on windows but not mac | 38,314,118 | <p>I am running the exact same code on both windows and mac, with python 3.5 64 bit. </p>
<p>On windows, it looks like this:</p>
<pre><code>>>> import numpy as np
>>> preds = np.zeros((1, 3), dtype=int)
>>> p = [6802256107, 5017549029, 3745804973]
>>> preds[0] = p
Traceback (most r... | 1 | 2016-07-11T18:51:15Z | 38,314,163 | <p>You'll get that error once your numbers are greater than <code>sys.maxsize</code>:</p>
<pre><code>>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Py... | 0 | 2016-07-11T18:54:00Z | [
"python",
"windows",
"int",
"long-integer"
] |
Using boolean operators in an if statement | 38,314,251 | <p>I'm a beginner in coding, and I'm trying to create a quadratic equation calculator using python.</p>
<pre><code>while True:
print("""
Welcome to DJIGURDA Supreme Quadratic Calculator
Please enter three values in the form of /'ax^2 + bx +c/'. """)
a = input("a (first constant)")
b = input... | 0 | 2016-07-11T18:59:05Z | 38,314,284 | <p>You're not calling those methods:</p>
<pre><code>c.isalpha()
# ^^
</code></pre>
<p>Note that a method or function in Python has a truthy value:</p>
<pre><code>>>> bool(''.isalpha)
True
</code></pre>
<p>So <code>not a.isalpha</code> (and others) will always evaluate to <code>False</code> and the c... | 8 | 2016-07-11T19:01:23Z | [
"python",
"if-statement",
"calculator"
] |
Using boolean operators in an if statement | 38,314,251 | <p>I'm a beginner in coding, and I'm trying to create a quadratic equation calculator using python.</p>
<pre><code>while True:
print("""
Welcome to DJIGURDA Supreme Quadratic Calculator
Please enter three values in the form of /'ax^2 + bx +c/'. """)
a = input("a (first constant)")
b = input... | 0 | 2016-07-11T18:59:05Z | 38,330,683 | <p>You must put brackets around the a.isalpha - like this a.isalpha () this calls the method whereas before it didn't. You must do it for b and c as well </p>
<p>UPDATE </p>
<p>Sorry I just realised someone has answered this like I have way before me, please don't accept my answer and accept theirs!</p>
| 0 | 2016-07-12T13:44:17Z | [
"python",
"if-statement",
"calculator"
] |
Comparing time in Python | 38,314,322 | <p>My current project is scraping weather data from websites for calculation. Part of this calculation involves different logic depending on if the current time is before or after noon.</p>
<pre><code>import pandas as pd
from bs4 import BeautifulSoup
import requests
import numpy as np
# Arkansas State Plant Board W... | 1 | 2016-07-11T19:03:49Z | 38,314,650 | <p>You can do it like this:</p>
<pre><code>t = pd.to_datetime(data1['Current Time'][0:1][0])
noon = pd.to_datetime("12:00 PM")
if t < noon:
print("yes")
else:
print("no")
>>> no
t
>>> Timestamp('2016-07-11 14:04:00')
noon
>>> Timestamp('2016-07-11 12:00:00')
</code></pre>
| 0 | 2016-07-11T19:24:38Z | [
"python",
"python-2.7"
] |
Comparing time in Python | 38,314,322 | <p>My current project is scraping weather data from websites for calculation. Part of this calculation involves different logic depending on if the current time is before or after noon.</p>
<pre><code>import pandas as pd
from bs4 import BeautifulSoup
import requests
import numpy as np
# Arkansas State Plant Board W... | 1 | 2016-07-11T19:03:49Z | 38,314,668 | <p>Just check if the meridian is PM or AM.</p>
<pre><code> time = "2:09 PM"
meridian = time.split(' ')[-1] # get just the meridian
before_noon = meridian == 'AM'
after_noon = meridian == 'PM'
</code></pre>
| 3 | 2016-07-11T19:25:49Z | [
"python",
"python-2.7"
] |
How to create and keep a set of variables in python? | 38,314,358 | <p>I'm developing an application that reads a message input from telegram with a set of variables, and then starts a game with the user. So I created a class that represents an instance of the game, making one game per chat possible: </p>
<pre><code>class Battle:
def __init__(self, mainchat):
self.mainchat... | 2 | 2016-07-11T19:06:12Z | 38,314,424 | <p>You're on the right track with <code>def reset(self)</code>. You just need to change the instances of <code>battle</code> to <code>self</code> in the method itself. <strong>NOTE:</strong> This needs to be a method of the <code>Battle</code> class.</p>
<pre><code>def reset(self):
self.pcount = 0
... # etc
... | 5 | 2016-07-11T19:10:26Z | [
"python"
] |
How to create and keep a set of variables in python? | 38,314,358 | <p>I'm developing an application that reads a message input from telegram with a set of variables, and then starts a game with the user. So I created a class that represents an instance of the game, making one game per chat possible: </p>
<pre><code>class Battle:
def __init__(self, mainchat):
self.mainchat... | 2 | 2016-07-11T19:06:12Z | 38,314,462 | <p>You're almost there!</p>
<pre><code>class Battle:
def __init__(self, mainchat):
self.mainchat = mainchat
print('Instance of battle started on chat %s' % self.mainchat)
self.reset()
def reset(self):
self.team1, self.team2 = [], []
self.p1 = self.p2 = () #New tuples w... | 0 | 2016-07-11T19:13:26Z | [
"python"
] |
mail_admins causing connection refused for Django/Apache2? | 38,314,365 | <p>I'm running Django with an Apache2 server on an Ubuntu backend. On load of my site, I get a 500 internal server error. The Apache log looks like: </p>
<pre><code>AH00094: Command line: '/usr/sbin/apache2'
mod_wsgi (pid=9568): Exception occurred processing WSGI script '/home/ubuntu/project/project/wsgi.py'.
Trac... | 0 | 2016-07-11T19:07:02Z | 38,314,732 | <p>Django has a special logger for sending an email to admins when a 500-error occurs. Check out <a href="https://docs.djangoproject.com/en/1.9/topics/logging/#django.utils.log.AdminEmailHandler" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/logging/#django.utils.log.AdminEmailHandler</a> for more info.</... | 1 | 2016-07-11T19:29:46Z | [
"python",
"django",
"apache",
"apache2"
] |
How to rank a 2-d tensor along an axis in tensorflow? | 38,314,560 | <p>I am trying to get the ranks of a 2-d tensor in Tensorflow. I can do that in numpy using something like:</p>
<pre><code>import numpy as np
from scipy.stats import rankdata
a = np.array([[0,3,2], [6,5,4]])
ranks = np.np.apply_along_axis(rankdata, 1, a)
</code></pre>
<p>And <code>ranks</code> is:</p>
<pre><code>ar... | 0 | 2016-07-11T19:19:40Z | 38,317,640 | <p><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#top_k" rel="nofollow"><code>tf.nn.top_k</code></a> would work for you, although it has slightly different semantics. Please read the documentation to know how to use it for your case. But here is the snippet to solve your example :</p>
<pre><... | 1 | 2016-07-11T23:14:35Z | [
"python",
"numpy",
"tensorflow",
"ranking"
] |
Writing contents of list to single csv column | 38,314,633 | <p>I am trying to write the contents of a list to a single column in a csv file. While I have done this in the past, I am not able to get this script to work. Instead I all of the columns filled instead of the rows</p>
<pre><code>#getting values for p vlue of 1%-100%
a = [numpy.arange(.01,1.01,.01)]
for i in a... | 1 | 2016-07-11T19:23:48Z | 38,314,953 | <p>Ignoring the questions of what <code>list1</code> and <code>list2</code> are (they are irrelevant if <code>score()</code> returns a single integer), I think the problem lies in your loop structure.</p>
<p>Instead of </p>
<pre><code>for i in a:
with open("GFOLD_Hisat2.csv", 'wb') as file3:
filewriter = ... | 2 | 2016-07-11T19:43:11Z | [
"python",
"list",
"csv"
] |
Writing contents of list to single csv column | 38,314,633 | <p>I am trying to write the contents of a list to a single column in a csv file. While I have done this in the past, I am not able to get this script to work. Instead I all of the columns filled instead of the rows</p>
<pre><code>#getting values for p vlue of 1%-100%
a = [numpy.arange(.01,1.01,.01)]
for i in a... | 1 | 2016-07-11T19:23:48Z | 38,316,545 | <p>You have to change the order of the file opening and the loop:</p>
<pre><code>a = [numpy.arange(.01,1.01,.01)]
with open("GFOLD_Hisat2.csv", 'wb') as file3:
filewriter = csv.writer(file3)
for i in a:
filewriter.writerow(score(list1, list2, i))
</code></pre>
| 0 | 2016-07-11T21:30:57Z | [
"python",
"list",
"csv"
] |
stack all levels of a MultiIndex | 38,314,674 | <p>I have a dataframe:</p>
<pre><code>index = pd.MultiIndex.from_product([['a', 'b'], ['A', 'B'], ['One', 'Two']])
df = pd.DataFrame(np.arange(16).reshape(2, 8), columns=index)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/MHPpX.png"><img src="http://i.stack.imgur.com/MHPpX.png" alt="enter image description h... | 5 | 2016-07-11T19:26:02Z | 38,314,750 | <p>You can first find <code>len</code> of levels, get <code>range</code> and pass it to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p>
<pre><code>print (df.columns.nlevels)
3
print (list(range(df.columns.nlevels)))
[0, 1, 2]
prin... | 4 | 2016-07-11T19:31:04Z | [
"python",
"pandas",
"multi-index"
] |
python mktime(.timetuple()) returns different results in mac and linux | 38,314,734 | <p>I noticed <code>time.mktime(.timetuple())</code> returned different time on mac and linux(ubuntu). Why this?</p>
<pre><code>date = ['2016-07-01', '2016-07-05']
xdata = [datetime.datetime.strptime(str(s), "%Y-%m-%d") for s in date]
xdata = [time.mktime(s.timetuple()) * 1000 for s in xdata]
print xdata
# ----mac--
... | 2 | 2016-07-11T19:29:54Z | 38,315,810 | <p>I marked to close this as a duplicate, but it's really not if you're viewing your original inputs as being in UTC to begin with. <em>If</em> you are (it's not wholly clear), then just replace your <code>time.mktime</code> with <code>calendar.timegm</code>.</p>
<pre><code>>>> d = datetime.datetime(2016, 9,... | 0 | 2016-07-11T20:38:09Z | [
"python"
] |
how to convert items of array into array themselves Python | 38,314,820 | <p>My problem is that I've got this array:</p>
<pre><code>np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
</code></pre>
<p>and I want to convert the elements to array like this:</p>
<pre><code>np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
</code></pre>
<p>So is there a loop or a ... | 3 | 2016-07-11T19:35:42Z | 38,314,856 | <p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions">list comprehension</a>:</p>
<pre><code>>>> a1 = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
>>> np.array([[x] for x in a1])
array([[ 0. ],
[ 0. ],
[-1.2],
[-1.2],
... | 7 | 2016-07-11T19:37:27Z | [
"python",
"python-3.x",
"numpy"
] |
how to convert items of array into array themselves Python | 38,314,820 | <p>My problem is that I've got this array:</p>
<pre><code>np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
</code></pre>
<p>and I want to convert the elements to array like this:</p>
<pre><code>np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
</code></pre>
<p>So is there a loop or a ... | 3 | 2016-07-11T19:35:42Z | 38,314,864 | <p>Or simply:</p>
<pre><code>arr[:,None]
# array([[ 0. ],
# [ 0. ],
# [-1.2],
# [-1.2],
# [-3.4],
# [-3.4],
# [-4.5],
# [-4.5]])
</code></pre>
| 13 | 2016-07-11T19:38:13Z | [
"python",
"python-3.x",
"numpy"
] |
how to convert items of array into array themselves Python | 38,314,820 | <p>My problem is that I've got this array:</p>
<pre><code>np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
</code></pre>
<p>and I want to convert the elements to array like this:</p>
<pre><code>np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
</code></pre>
<p>So is there a loop or a ... | 3 | 2016-07-11T19:35:42Z | 38,314,883 | <p>Isn't this just a <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape"><code>reshape</code></a> operation from row to column vector?</p>
<pre><code>In [1]: import numpy as np
In [2]: x = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
In [3]: np.reshape(x, (-1,1))... | 6 | 2016-07-11T19:39:24Z | [
"python",
"python-3.x",
"numpy"
] |
Running an exe file on the azure | 38,314,909 | <p>I am working on an azure web app and inside the web app, I use python code to run an exe file. The webapp recieves certain inputs (numbers) from the user and stores those inputs in in a text file. Afterwards, an exe file would run and read the inputs and generate another text file, called "results". The problem is t... | 0 | 2016-07-11T19:40:29Z | 38,332,951 | <p>Have you looked at using a <a href="https://azure.microsoft.com/en-us/documentation/articles/websites-webjobs-resources/" rel="nofollow">WebJob</a> to host\run your executable from? A WebJob can be virtually any kind of script or win executable. There are a number of ways to trigger your WebJob. You also get a lot o... | 0 | 2016-07-12T15:19:24Z | [
"python",
"django",
"azure",
"vs-team-services"
] |
Running an exe file on the azure | 38,314,909 | <p>I am working on an azure web app and inside the web app, I use python code to run an exe file. The webapp recieves certain inputs (numbers) from the user and stores those inputs in in a text file. Afterwards, an exe file would run and read the inputs and generate another text file, called "results". The problem is t... | 0 | 2016-07-11T19:40:29Z | 38,352,553 | <p>@F.K I searched some information which may be helpful for you, please see below.</p>
<ol>
<li>Accroding to the python document for <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> module, <code>Using shell=True can be a security hazard.</code> Please see the war... | 0 | 2016-07-13T13:02:36Z | [
"python",
"django",
"azure",
"vs-team-services"
] |
How to save a dictionary of objects in Python? | 38,314,960 | <p>I have a Python 3.5 program that creates an inventory of objects. I created a class of Trampolines (color, size, spring, etc.). I constantly will create new instances of the class and I then save a dictionary of them. The dictionary looks like this:</p>
<pre><code>my_dict = {name: instance} and the types are lik... | 0 | 2016-07-11T19:43:35Z | 38,315,274 | <p>For a simple class, you can make an easy serializer as below. This will take all of the properties of your <code>Trampoline</code> object and put them into a dictionary and then into JSON. </p>
<pre><code>class Trampoline(object):
...
def serialize(self):
return json.dumps(vars(self))
</code></pre>
... | 0 | 2016-07-11T20:04:26Z | [
"python",
"json",
"dictionary",
"save",
"object-oriented-database"
] |
How to save a dictionary of objects in Python? | 38,314,960 | <p>I have a Python 3.5 program that creates an inventory of objects. I created a class of Trampolines (color, size, spring, etc.). I constantly will create new instances of the class and I then save a dictionary of them. The dictionary looks like this:</p>
<pre><code>my_dict = {name: instance} and the types are lik... | 0 | 2016-07-11T19:43:35Z | 38,316,239 | <p>What you might be able to do is saving the instance's attributes to a CSV-file and then just create it when starting up. This might be a bit too much code and is possible not the best way. One obvious problem is that it doesn't work if you don't have the same amount of attributes as parameters, which should be poss... | 1 | 2016-07-11T21:07:00Z | [
"python",
"json",
"dictionary",
"save",
"object-oriented-database"
] |
How to save a dictionary of objects in Python? | 38,314,960 | <p>I have a Python 3.5 program that creates an inventory of objects. I created a class of Trampolines (color, size, spring, etc.). I constantly will create new instances of the class and I then save a dictionary of them. The dictionary looks like this:</p>
<pre><code>my_dict = {name: instance} and the types are lik... | 0 | 2016-07-11T19:43:35Z | 38,316,383 | <p>Here is an example of a class that handles datetime objects. </p>
<pre><code>class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
if obj.tzinfo:
obj = obj.astimezone(isodate.tzinfo.UTC).replace(tzinfo=None)
return o... | 1 | 2016-07-11T21:18:13Z | [
"python",
"json",
"dictionary",
"save",
"object-oriented-database"
] |
Speeding up TensorFlow Cifar10 Example for Experimentation | 38,314,964 | <p>The TensorFlow tutorial for using CNN for the cifar10 data set has the following advice:</p>
<p>EXERCISE: When experimenting, it is sometimes annoying that the first training step can take so long. Try decreasing the number of images that initially fill up the queue. Search for NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN in c... | 0 | 2016-07-11T19:43:54Z | 38,317,151 | <p>Note that this exercise only speeds up the <strong>first step time</strong> by skipping the prefetching of a larger from of the data. This exercise does <strong>not</strong> speed up the overall training</p>
<p>That said, the tutorial text needs to be updated. It should read </p>
<blockquote>
<p>Search for <code... | 0 | 2016-07-11T22:24:17Z | [
"python",
"tensorflow"
] |
Filter Pandas DataFrame by GroupBy Contents | 38,314,981 | <p>Consider the following DataFrame:</p>
<pre><code> records = [{'item': 'Widget A', 'quantity': 50, 'revenue': 25.0, 'trandate': '2016-3-24'},
{'item': 'Widget B', 'quantity': 6, 'revenue': 72.0, 'trandate': '2016-3-28'},
{'item': 'Widget C', 'quantity': 5, 'revenue': 75.0, 'trandate': '2016-3-28'}... | 2 | 2016-07-11T19:45:15Z | 38,315,040 | <p>I think you need filter by <code>mask</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a>:</p>
<pre><code>print (df.groupby('item').cumcount())
487 0
488 0
493 0
495 1
497 1
dtype: int64
... | 3 | 2016-07-11T19:48:50Z | [
"python",
"pandas",
"dataframe",
"scipy"
] |
Standard logging for every method in a Class | 38,314,993 | <p>I would like every class method that is called in my script to log the time it took to complete the method. What is the best/cleanest way to do this without adding logging to every method?</p>
<p>I can do this by brute-forcing it, but adding the same boilerplate to every method I write doesn't seem right:</p>
<pre... | 2 | 2016-07-11T19:46:07Z | 38,316,203 | <p>Use a timing function and a decorator:</p>
<pre><code>def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
delta = te - ts
hours, remainder = divmod(delta, 3600)
minutes, seconds = divmod(remainder, 60)
... | 1 | 2016-07-11T21:04:39Z | [
"python",
"inheritance",
"logging",
"decorator"
] |
How to add widgets to a QScrollView with Python | 38,315,012 | <p>I am writing an app that dynamically adds and removes widgets to a <a href="https://doc.qt.io/archives/3.3/qscrollview.html#QScrollView" rel="nofollow"><code>QScrollView</code></a>. The code below, using Qt3 and python, will give me dynamic widgets, but when I add too many to be seen, no scroll bar appears. It is no... | 1 | 2016-07-11T19:47:05Z | 38,315,888 | <p>The only way to use a layout with a <code>QScrollView</code> is to set the layout on its <code>viewport()</code>, not the view itself. This is <a href="https://doc.qt.io/archives/3.3/qscrollview.html#details" rel="nofollow">documented</a>.</p>
<p>Replace <code>self.Form1Layout = QGridLayout(self.scrollArea)</code> ... | 0 | 2016-07-11T20:43:25Z | [
"python",
"qt",
"pyqt",
"qt-designer",
"qt3"
] |
HTML parsing with python regular expression | 38,315,034 | <p>I am using python regular expression to parse html file, now I need to extract a number from a html tag, the number can be either integer or floating point value. Following are two examples:</p>
<p>integer case:</p>
<pre><code><span class='addr-bbs'>2 baths</span>
</code></pre>
<p>floating point case:... | 0 | 2016-07-11T19:48:03Z | 38,315,148 | <p>As commented, use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">html parser</a> to find the tags by <em>class name</em>. If the number is always the first in the text you can just split to extract it once you have the tag:</p>
<pre><code>from bs4 import BeautifulSoup
h = """<s... | 1 | 2016-07-11T19:55:31Z | [
"python",
"html",
"regex"
] |
HTML parsing with python regular expression | 38,315,034 | <p>I am using python regular expression to parse html file, now I need to extract a number from a html tag, the number can be either integer or floating point value. Following are two examples:</p>
<p>integer case:</p>
<pre><code><span class='addr-bbs'>2 baths</span>
</code></pre>
<p>floating point case:... | 0 | 2016-07-11T19:48:03Z | 38,315,203 | <p>Three typos:</p>
<ul>
<li>the inverted commas;</li>
<li>the dash;</li>
<li>the space.</li>
</ul>
<p>Try with <code>bath = re.findall('''<span class=["']addr-bbs["']>''' + '(.{1,3})' + ' baths{0,1}<', str(homedata))</code></p>
| 0 | 2016-07-11T19:59:21Z | [
"python",
"html",
"regex"
] |
HTML parsing with python regular expression | 38,315,034 | <p>I am using python regular expression to parse html file, now I need to extract a number from a html tag, the number can be either integer or floating point value. Following are two examples:</p>
<p>integer case:</p>
<pre><code><span class='addr-bbs'>2 baths</span>
</code></pre>
<p>floating point case:... | 0 | 2016-07-11T19:48:03Z | 38,315,233 | <p>First, realize you are somewhat doomed without more processing. Some realtors will write "2.5", others "2 1/2", others "2+1/2", and so on. MLS
data has never normalized, in part to make it difficult to parse. Just when you think you have it solved, you get "2+sink". It's usually permissible to guess the numeric... | 0 | 2016-07-11T20:01:14Z | [
"python",
"html",
"regex"
] |
Editing Large Matrix Python | 38,315,039 | <p>I want to make a 34x34 Matrix consisting of entirely zeroes and ones. I have an array that lists the coordinates where all of the ones should go but don't know how to use it. The array looks like this: </p>
<p>0 1 1</p>
<p>0 2 1</p>
<p>0 3 1</p>
<p>1 1 1</p>
<p>where the first number in each row is the x coordi... | -3 | 2016-07-11T19:48:36Z | 38,315,661 | <p>That's work:</p>
<pre><code>a = np.array([[0,1,1],[0,2,1],[0,3,1],[1,1,1]])
m = np.zeros([5,5])
for i in range(len(a)):
m[a[i][0],a[i][1]] = a[i][2] # Or = 1 if that's always the case
</code></pre>
<p>And the m matrix is:</p>
<pre><code>array([[ 0., 1., 1., 1., 0.],
[ 0., 1., 0., 0., 0.],
... | 0 | 2016-07-11T20:27:48Z | [
"python",
"matrix"
] |
How do I use Pandas to read in multiple datasets from one file? | 38,315,085 | <p>I have a file that has multiple sets of data separated by rows. It looks something like:</p>
<pre><code>country1
0.9
1.3
2.9
1.1
...
country2
4.1
3.1
0.2
...
</code></pre>
<p>I would like to use Pandas to read the whole file into multiple dataframes, where each dataframe corresponds to a country.... | 2 | 2016-07-11T19:51:26Z | 38,315,308 | <p>You can create <code>mask</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html"><code>to_numeric</code></a> with <code>errors='coerce'</code>, so get <code>NaN</code> where are column names. Then find them by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pa... | 5 | 2016-07-11T20:05:46Z | [
"python",
"pandas"
] |
How do I use Pandas to read in multiple datasets from one file? | 38,315,085 | <p>I have a file that has multiple sets of data separated by rows. It looks something like:</p>
<pre><code>country1
0.9
1.3
2.9
1.1
...
country2
4.1
3.1
0.2
...
</code></pre>
<p>I would like to use Pandas to read the whole file into multiple dataframes, where each dataframe corresponds to a country.... | 2 | 2016-07-11T19:51:26Z | 38,315,466 | <p>Pandas supports standard file formats like csv and json, and this is not one of those. I'm going to assume reformatting the file by hand is a waste of time and suggest you parse the file yourself using <code>with open(...) as f:</code> and <code>f.readlines()</code> into python objects. </p>
<p>Say you've done tha... | 1 | 2016-07-11T20:15:17Z | [
"python",
"pandas"
] |
Scrapy returns more results than expected | 38,315,087 | <p><em>This is a continuation of the question: <a href="http://stackoverflow.com/questions/38310986/extract-from-dynamic-json-response-with-scrapy">Extract from dynamic JSON response with Scrapy</a></em></p>
<p>I have a Scrapy spider that extract values from a JSON response. It works well, extract the right values, bu... | 1 | 2016-07-11T19:51:32Z | 38,315,478 | <p>The <code>parse</code> function should be like this:</p>
<pre><code>def parse(self, response):
jsonresponse = json.loads(response.body_as_unicode())
item = WhoisItem()
domain_name = list(jsonresponse['domains'].keys())[0]
item["avail"] = jsonresponse["domains"][domain_name]["avail"]
item["domain... | 1 | 2016-07-11T20:15:57Z | [
"python",
"json",
"web-scraping",
"scrapy",
"web-crawler"
] |
Python 2.7 - Trying to work convert UTC string to local time taking into account DST | 38,315,110 | <p>I have a UTC time string like so</p>
<pre><code>supplied_datetime = 20160711230000 -0500
</code></pre>
<p>This is the format</p>
<pre><code>yyyyMMddhhmmss +/-hhmm
</code></pre>
<p>Now if I take that offset (-5hrs) from the original time it should read</p>
<pre><code>supplied_datetime = 20160711180000
</code></p... | 1 | 2016-07-11T19:52:56Z | 38,316,072 | <p>If the format of your date time strings are always consistent, you can manually obtain the local datetime given the utc datetime. </p>
<p><code>time.timezone</code> gives local offset in seconds.</p>
<p>Then you just need to parse the datetime string and add it with local offset in hours as well as the offset in t... | 0 | 2016-07-11T20:55:21Z | [
"python"
] |
Python 2.7 - Trying to work convert UTC string to local time taking into account DST | 38,315,110 | <p>I have a UTC time string like so</p>
<pre><code>supplied_datetime = 20160711230000 -0500
</code></pre>
<p>This is the format</p>
<pre><code>yyyyMMddhhmmss +/-hhmm
</code></pre>
<p>Now if I take that offset (-5hrs) from the original time it should read</p>
<pre><code>supplied_datetime = 20160711180000
</code></p... | 1 | 2016-07-11T19:52:56Z | 38,323,674 | <p>Ok with the help of @CentAu I managed to answer this as below</p>
<pre><code>import time
import calendar
from datetime import datetime, timedelta
def datetime_from_utc_to_local(input_datetime):
#Get local offset from UTC in seconds
local_offset_in_seconds = calendar.timegm(time.localtime()) - calendar.time... | 0 | 2016-07-12T08:30:53Z | [
"python"
] |
Django model query tune up | 38,315,188 | <p>I want to reduce the number of template filter calls in my_filter_function(). Because It's used inside two for-loops inside a template. Please see below for my code setup. </p>
<pre><code>class ModelA(models.model):
models.ForeignKey(OtherModel1)
class ModelB(models.model):
models.ForeignKey(OtherModel2)
... | 1 | 2016-07-11T19:58:20Z | 38,315,449 | <p>Here's a faster alternative.</p>
<p>Fetch all the ids of <code>A</code> and <code>B</code> in <code>C</code> at once:</p>
<pre><code>z = ModelC.objects.values_list('a_id', 'b_id')
a_related, b_related = zip(*z) # split into a and b ids
</code></pre>
<p>Pass these to your context:</p>
<pre><code>def my_views(req... | 2 | 2016-07-11T20:14:02Z | [
"python",
"django"
] |
Whats going on with this code that finds roots? | 38,315,224 | <p>Lines Im having trouble with are: </p>
<ol>
<li><p><code>while not withinEpsilon(ans**pwr, val, epsilon)</code>: is it, while withinEpsilon is false, continue executing?</p></li>
<li><p>Why do I need a negative absolute value and why is it between max val and 1?</p>
<pre><code>low = -abs(val)
high = max(abs(va... | -1 | 2016-07-11T20:00:44Z | 38,315,667 | <ol>
<li>Yes, the code specifies to continue looping while withinEpsilon is False.</li>
<li><p>The code is using <a href="https://en.wikipedia.org/wiki/Dichotomy" rel="nofollow" title="Dichotomy">dichotomy</a> to find "ans" such that "0 < |val - ans**n| < epsilon".</p>
<p>"low" must be smaller than the root, and... | 1 | 2016-07-11T20:28:19Z | [
"python"
] |
Regular expression to search for plural or singular of specific python | 38,315,284 | <p>I want to use a regular expression to search for dog or dogs in a certain sentence. Here is what I have but its not working. I need it to search for the specific word, not just a plural or singular of all words. </p>
<pre><code>x = re.findall('(?<=\|)dog[s]?(?=\|)', txt)
</code></pre>
| 2 | 2016-07-11T20:04:54Z | 38,315,456 | <p>A quantifier is applied to the atom on the left. If it is a group, it will be applied to a group. If it is a literal symbol, it will be applied to this symbol.</p>
<p>So, <code>s?</code> matches 1 or 0 <code>s</code>. </p>
<p>Use</p>
<pre><code>x = re.findall(r'\bdogs?\b', txt)
</code></pre>
<p>where <code>\b</c... | 1 | 2016-07-11T20:14:34Z | [
"python",
"regex"
] |
Sensu: client socket input (how-to print an event) | 38,315,287 | <p>I am trying to create an event using the "Client socket input" described here: <a href="https://sensuapp.org/docs/latest/reference/clients.html#client-socket-input" rel="nofollow">https://sensuapp.org/docs/latest/reference/clients.html#client-socket-input</a></p>
<p>when i do, from bash:</p>
<pre><code>echo '{"sta... | 0 | 2016-07-11T20:04:59Z | 38,316,170 | <pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect( ("localhost",3030) )
sock.sendall(json.dumps(msg))
sock.close()
</code></pre>
<p>does the trick :)</p>
| 1 | 2016-07-11T21:02:36Z | [
"python",
"sensu"
] |
django DRF: how to Get related model field in serializer | 38,315,332 | <p>I'm trying to return a HttpResponse from Django Rest Framework including data from 3 linked models. The models are</p>
<pre><code>class ErrorDb(models.Model):
error_id = models.AutoField(primary_key=True)
error_msg = models.CharField(max_length=500)
user_name = models.CharField(max_length=45)
class ... | 0 | 2016-07-11T20:07:20Z | 38,315,440 | <p>you can use <code>source</code> of <code>serializer.CharField</code> and access to field throw fk as usual: </p>
<pre><code>class TaskSerializer(serializers.HyperlinkedModelSerializer):
error_field = serializers.CharField(read_only=True, source='error.error_msg')
key_field = serializers.CharField(read_only=... | 0 | 2016-07-11T20:13:39Z | [
"python",
"django",
"serialization",
"drf-nested-routers"
] |
How can I render a JS template from a rendered HTML template? | 38,315,368 | <p>If I'd like to generate JavaScript code, and not just HTML, through Jinja2, am I stuck with keeping the JS code inline, or is there a way for me to reference the script?</p>
<p>Concretely:</p>
<p><strong>app.py</strong></p>
<pre><code>from flask import Flask, render_template
app = Flask(__name__)
app.config['DEBU... | 2 | 2016-07-11T20:09:21Z | 38,315,457 | <p>You can add a route that generates the JS.</p>
<pre><code>@app.route('/script.js')
def script():
return render_template('script.js', color='pink')
</code></pre>
<p>And in script.js, this should be in the same folder as your other templates:</p>
<pre><code> function myEnterFunction() {
element ... | 2 | 2016-07-11T20:14:38Z | [
"javascript",
"python",
"flask",
"jinja2"
] |
How to output features in a Convolutional RBM? | 38,315,475 | <p>Having read <a href="http://blog.echen.me/2011/07/18/introduction-to-restricted-boltzmann-machines/]" rel="nofollow">this text</a> I learnt that I can create what people call "reconstructions" by turning only one hidden unit active and Gibbs sampling the visible from the hidden units.</p>
<p>But now I am trying to ... | 0 | 2016-07-11T20:15:46Z | 39,024,270 | <p>Well yes, I was already wondering why they didn't provide details on plotting their bases for higher layers in this paper.</p>
<p>For visualizing the features of the first layer (Figure 3, upper image) it is definitely sufficient to plot just the weights (i.e. filters) of the individual hidden units. If your result... | 0 | 2016-08-18T17:33:04Z | [
"python",
"feature-extraction",
"rbm"
] |
saving dask dataframe in bcolz format | 38,315,532 | <p>The dask documentation states: "BColz is an on-disk, chunked, compressed, column-store. These attributes make it very attractive for dask.dataframe which can operate particularly well on it. There is a special from_bcolz function."</p>
<p>However, I could not find an example how to <strong>save</strong> a dask data... | 0 | 2016-07-11T20:19:23Z | 38,437,262 | <p>I created a pull request to implement this. Until it is merged into the master branch you can find it here: </p>
<p><a href="https://github.com/dask/dask/pull/1386" rel="nofollow">https://github.com/dask/dask/pull/1386</a></p>
<p>If you don't want to edit your own Dask implementation you can just copy the <code>to... | 1 | 2016-07-18T12:54:36Z | [
"python",
"dask",
"bcolz"
] |
PySide import error Mac OS X El Capitan, Library not loaded: @rpath/libpyside.cpython-34m.1.2.dylib | 38,315,537 | <p>ive been trying to run an application that was written on a Linux machine (and works without any issues), on my Mac running OS X El Capitan. the program utilizes PyQt4(4.11.4) and PySide (1.2.4), using Python 3.4.2. I created a virtualenv to guarantee that everything runs on the correct version of python. i have sip... | 1 | 2016-07-11T20:19:42Z | 38,581,865 | <p>I got it to work.
First, following this thread <a href="https://github.com/PySide/PySide/issues/138" rel="nofollow">here</a></p>
<p>This gave the option of using PySide 1.2.2 or building 1.2.4 from scratch.
I settled for 1.2.2:</p>
<pre><code>pip install -U PySide==1.2.2
</code></pre>
<p>After that, when trying t... | 0 | 2016-07-26T05:46:12Z | [
"python",
"osx",
"pyside"
] |
Can multiple CPU cores be used in Google Datalab? | 38,315,571 | <p>If the answer is yes, what will be a simple example to test this capability?</p>
<p>I have tried to use the multiprocessing capabilities of SFrame and implicit. But the CPU utilization is always below 10% of a n1-highmem-32 (32 vCPUs, 208 GB memory) instance.</p>
<pre><code>import os
os.environ['OMP_NUM_THREADS'] ... | 2 | 2016-07-11T20:21:26Z | 38,902,408 | <p>Sorry about the delay in answering. Jupyter Python kernel itself is single threaded. I am not certain about the specific sframe library but this is not something where Datalab does anything special either way. We use the standard Python kernel in Jupyter. Perhaps you could tag your question as an sframe one?</p>
<p... | 1 | 2016-08-11T17:12:56Z | [
"python",
"google-cloud-datalab"
] |
Not getting Namespace returned from subparser in parse_args() | 38,315,599 | <p>I can't seem to figure out how to call the <code>add_user()</code> function in the script and pass it all the arguments needed. If I do this</p>
<pre><code>if args.adduser:
add_user(username, account, groups)
</code></pre>
<p>it doesn't find the <code>adduser</code> <code>Namespace</code>.</p>
<pre><code>Attr... | 0 | 2016-07-11T20:23:41Z | 38,315,802 | <p>I think you're misunderstanding what it means to add a subparser. When you add a subparser, if the subparser is selected on the commandline, that subparser's arguments will be added to the namespace. Then the standard way of interacting with the commandline is to create an entry point for each subparser that accep... | 0 | 2016-07-11T20:37:37Z | [
"python",
"argparse"
] |
How do I use output from python script in my Powershell application? | 38,315,735 | <p>I have a power-shell GUI Application. Inside my application I call a python script. I want to display the output of the python script.</p>
<blockquote>
<p>test.py prints "hello world"</p>
</blockquote>
<pre><code>$dog.Add_Click({FixIndefinite})
$Form.Controls.Add($dog)
function FixIndefinite {
try { $outputBo... | 1 | 2016-07-11T20:33:05Z | 38,315,981 | <pre><code>$outputBox.text = python .\test.py
</code></pre>
| 0 | 2016-07-11T20:49:18Z | [
"python",
"powershell"
] |
Error in loading JSON from itsdangerous file TimedJSONSerializer Token | 38,315,742 | <p>I am currently working on authenticating my users. I checked out this blog - <a href="http://blog.miguelgrinberg.com/post/restful-authentication-with-flask" rel="nofollow">RESTful Authentication with Flask</a> - and followed its steps to produce a piece of code I believed would serve my purpose. I wanted to use the ... | 0 | 2016-07-11T20:33:36Z | 38,316,739 | <p>I ended up having to uninstall and reinstall the package <code>itsdangerous</code> with <code>pip</code>. The statements used were:</p>
<pre><code>pip uninstall itsdangerous
</code></pre>
<p>followed by:</p>
<pre><code>pip install itsdangerous
</code></pre>
<p>Apparently, the file had been corrupted somehow caus... | 0 | 2016-07-11T21:47:47Z | [
"python",
"authentication",
"token",
"serializer"
] |
Change the python executable that Django 1.7 loads | 38,315,752 | <p>I am building an app on Google Compute Engine using Django 1.7 and Python 2.7 within a Debian environment. </p>
<p>To get the mpl_toolkit library to work I have had to install Anaconda and its various modules within that environment, thereby over-riding the default "out-the-box" Bitnami setup. </p>
<p>I am current... | 1 | 2016-07-11T20:34:36Z | 38,425,327 | <p>Ok I found an answer (which avoids having to rebuild mod_wsgi). If you're using Bitnami, you can get python to load from a different path by changing /opt/bitnami/apache2/bin/envvars by adding a PATH line as follows (for example):</p>
<pre><code>PATH=/home/beastflow/anaconda2/envs/django17/bin/:$PATH
export PATH
<... | 0 | 2016-07-17T19:50:12Z | [
"python",
"django",
"anaconda"
] |
Python and JSON Conditional Optimization | 38,315,796 | <p>I'm trying to use Python to classify businesses based on a number of attributes. The data pointing to what attributes each business category has is stored in a json file, such as:</p>
<pre><code>{
"type1": {
"business_code": [
1,
3,
5
],
"business_code2": [
2,
7,
1... | 0 | 2016-07-11T20:37:12Z | 38,315,939 | <p><code>classify_business</code> should take a function that tests whether a business matches the criteria.</p>
<pre><code>def classify_business(j_test, tester):
for key, business in j_test:
if tester(business):
return key
return None
</code></pre>
<p>Then you can call it with a <code>lam... | 0 | 2016-07-11T20:46:55Z | [
"python",
"json",
"python-2.7",
"conditional"
] |
How to execute a JavaScript function defined in the website script with Selenium? | 38,315,819 | <p>I am working with a website and I need to run a couple js code with Selenium. To make things easier, I need to run functions declared in the website scripts.<br>
For example, the website use a script file called <code>document_handler.js</code> with the following code:</p>
<pre><code> (function ($) {
var getCo... | 0 | 2016-07-11T20:38:48Z | 38,315,969 | <p>If this is a script you have access to, you have to make the function available to the outer/global scope.. The simplest would be to assign it to the window object, and it should work.</p>
<pre><code>(function ($) {
window.getConversationId = function(){
return $('input[name="conversationId"]').val()
... | 1 | 2016-07-11T20:48:40Z | [
"javascript",
"python",
"selenium",
"selenium-webdriver"
] |
Simplifying categorical variables with python/pandas | 38,315,846 | <p>I'm working with an airbnb dataset on Kaggle:</p>
<pre><code>https://www.kaggle.com/c/airbnb-recruiting-new-user-bookings
</code></pre>
<p>and want to simplify the values for the language column into 2 groupings - english and non-english. </p>
<p>For instance:</p>
<pre><code>users.language.value_counts()
en 1... | 3 | 2016-07-11T20:40:51Z | 38,315,931 | <p>is that what you want?</p>
<pre><code>In [181]: x
Out[181]:
val
en 15011
zh 101
fr 99
de 53
es 53
ko 43
ru 21
it 20
ja 19
pt 14
sv 11
no 6
da 5
nl 4
el 2
pl 2
tr 2
cs 1
fi 1
is 1
hu 1
In [182]: x.groupby(x.index == 'en'... | 2 | 2016-07-11T20:46:37Z | [
"python",
"pandas",
"data-science"
] |
Simplifying categorical variables with python/pandas | 38,315,846 | <p>I'm working with an airbnb dataset on Kaggle:</p>
<pre><code>https://www.kaggle.com/c/airbnb-recruiting-new-user-bookings
</code></pre>
<p>and want to simplify the values for the language column into 2 groupings - english and non-english. </p>
<p>For instance:</p>
<pre><code>users.language.value_counts()
en 1... | 3 | 2016-07-11T20:40:51Z | 38,316,200 | <p>Try this: </p>
<pre><code> users.language = np.where( users.language !='en', 'non-english', 'english' )
</code></pre>
| 2 | 2016-07-11T21:04:28Z | [
"python",
"pandas",
"data-science"
] |
Eval function with parameters | 38,315,946 | <p>I have three functions:</p>
<pre><code>def function_1(arg_1, arg_1, arg_1, arg_1):
return sol_1
def function_2(arg_1, arg_2, arg_3, arg_4):
return sol_2
def function_3(arg_1, arg_2, arg_3, arg_4):
return sol_3
</code></pre>
<p>And I would like to call them with a string:</p>
<pre><code>myString = 'fun... | -3 | 2016-07-11T20:47:26Z | 38,316,119 | <p>Thak you Tim,</p>
<p>Everything had to be in string format, that worked.</p>
<pre><code>eval(myString + '(arg_1, arg_2, arg_3, arg_4)')
</code></pre>
| 0 | 2016-07-11T20:58:54Z | [
"python",
"eval"
] |
Eval function with parameters | 38,315,946 | <p>I have three functions:</p>
<pre><code>def function_1(arg_1, arg_1, arg_1, arg_1):
return sol_1
def function_2(arg_1, arg_2, arg_3, arg_4):
return sol_2
def function_3(arg_1, arg_2, arg_3, arg_4):
return sol_3
</code></pre>
<p>And I would like to call them with a string:</p>
<pre><code>myString = 'fun... | -3 | 2016-07-11T20:47:26Z | 38,316,128 | <p>To call a function from a variable containing the name of the function, you can make use of the <code>locals</code> and <code>globals</code> function. Basically, you treat the output of <code>locals()</code> as a dictionary of your locally declared functions and then call the return value as normal using parentheses... | 1 | 2016-07-11T20:59:42Z | [
"python",
"eval"
] |
Yahtzee game, __str__ not working | 38,315,960 | <p>I realize I've been pretty much spamming this forum lately, I'm just trying to break my problems down since I'm supposed to create a yahtzee game for assignment. My code is currently looking like this:</p>
<pre><code>class Player:
def __init__(self,name):
self.name=name
self.lista={"ones":0,"two... | 0 | 2016-07-11T20:48:07Z | 38,316,034 | <p>When you print a list of objects python doesn't call the objects <code>__str__</code> method but the container list. If you want to print them all you can call the <code>__str__</code> method by applying the built-in function <code>str()</code> on them using <code>map()</code> or a list comprehension and join them w... | 1 | 2016-07-11T20:52:47Z | [
"python"
] |
Yahtzee game, __str__ not working | 38,315,960 | <p>I realize I've been pretty much spamming this forum lately, I'm just trying to break my problems down since I'm supposed to create a yahtzee game for assignment. My code is currently looking like this:</p>
<pre><code>class Player:
def __init__(self,name):
self.name=name
self.lista={"ones":0,"two... | 0 | 2016-07-11T20:48:07Z | 38,316,044 | <p>If you are getting <code>Player object at 0x7fac824</code> or anything similar, it seems that you are calling the <code>repr</code> on the object (indirectly), which in turn calls the object's <code>__repr__</code> method.</p>
<pre><code>class Player:
# ...
def __repr__(self):
return self.name
... | 1 | 2016-07-11T20:53:27Z | [
"python"
] |
GAE: Read static file | 38,315,975 | <p>I'm using app engine and I don't know how to read a static file from my project. I have a file structure that globally looks like this:</p>
<pre><code>- html (static folder)
- staticfile1.html
- staticfile2.html
- script
- main.py
app.yaml
</code></pre>
<p>In my app.yaml I already set the application_read... | 0 | 2016-07-11T20:49:00Z | 38,316,085 | <p>You'll probably need to use relative paths based on the current module's <code>__file__</code> attribute. e.g. from <code>main.py</code>, you'd do something like:</p>
<pre><code>import os
_HERE = os.path.basename(__file__)
_HTML_DIR = os.path.join(_HERE, os.pardir, 'html')
</code></pre>
| 1 | 2016-07-11T20:55:53Z | [
"python",
"file",
"google-app-engine",
"static",
"accessibility"
] |
Django Model Relationship with Multiple Classes | 38,316,005 | <p>Sure the answer's out there but I've struggled to find the search terms! This is my first Django project and I can't seem to come up with a logical model structure... </p>
<pre><code>Domain-->* Region-->* [Domain]Network
</code></pre>
<p>Within a <strong>Domain</strong> there are various <strong>Regions</st... | 2 | 2016-07-11T20:51:05Z | 38,318,920 | <p>If I understand your question, I'd just add some validation to your <code>Domain</code>s.
See: <a href="https://docs.djangoproject.com/en/dev/ref/forms/validation/" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/forms/validation/</a></p>
| 0 | 2016-07-12T02:07:58Z | [
"python",
"django",
"models"
] |
Django Model Relationship with Multiple Classes | 38,316,005 | <p>Sure the answer's out there but I've struggled to find the search terms! This is my first Django project and I can't seem to come up with a logical model structure... </p>
<pre><code>Domain-->* Region-->* [Domain]Network
</code></pre>
<p>Within a <strong>Domain</strong> there are various <strong>Regions</st... | 2 | 2016-07-11T20:51:05Z | 38,319,099 | <p>To answer your question "how to inherit common fields" use 'abstract=True' see this example <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes</a></p>
| 0 | 2016-07-12T02:31:05Z | [
"python",
"django",
"models"
] |
Decrementing Python | 38,316,020 | <p>I've got a package that depends on an earlier version of Python -- I'm running 3.5.1, but the package only supports up through Python 3.4. I'd like to clone my current environment, decrement my Python version to 3.4, and then update all other packages to the latest version compatible with Python 3.4. How do I do t... | 1 | 2016-07-11T20:52:05Z | 38,316,112 | <p>Create a new environment:</p>
<pre><code>conda create -n py34 python=3.4
</code></pre>
<p>activate it:</p>
<pre><code>source activate py34
</code></pre>
<p>(no <code>source</code> on Windows)</p>
<p>Install all your packages:</p>
<pre><code>(py34) conda install package1 package2
</code></pre>
<p>This keeps y... | 4 | 2016-07-11T20:58:14Z | [
"python",
"python-3.4",
"python-3.5",
"conda"
] |
What is the name for "for $x in ... return ..." syntax in XPath? | 38,316,062 | <p>I have this xpath:</p>
<pre><code>/document/offers/offer/concat(price/text(), for $r in . return 'default-value'[not($r/price/text())])
</code></pre>
<p>which solves my problem (default value for missing tags) for this document:</p>
<pre><code><document>
<company>
<ceo>Elon Musk</ceo>... | 0 | 2016-07-11T20:54:44Z | 38,316,624 | <p>That is an <a href="https://www.w3.org/TR/xpath20/#id-for-expressions" rel="nofollow">xpath2 for-expressions</a> which is not supported by lxml or xml.etree in python. You could replicate it using a for loop </p>
<pre><code>from lxml import etree
xml = etree.parse("the_file")
for node in xml.xpath("//document/off... | 3 | 2016-07-11T21:37:52Z | [
"python",
"xml",
"xpath",
"lxml"
] |
Django unable to load JS and CSS files as static resources | 38,316,129 | <p>I have a <code>html</code> file called <code>base.html</code> inside a folder called <strong><code>html</code></strong>. There are two directories at the same level as <strong><code>html</code></strong> - <strong><code>js</code></strong> and <strong><code>css</code></strong> which contain static resources. The <code... | 0 | 2016-07-11T20:59:41Z | 38,316,307 | <p>You don't need to be including the static resource folders in your template dirs. What you do need to do is set your <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-STATICFILES_DIRS" rel="nofollow"><code>STATICFILES_DIRS</code></a> under settings and include a <a href="https://docs.djangopro... | 3 | 2016-07-11T21:12:11Z | [
"python",
"django"
] |
error importing numpy in python 3.5 | 38,316,134 | <p>I tried installing numpy with homebrew, but instead it installed in the Python 2.7 version. I found this out by following the answer on this post: <a href="http://stackoverflow.com/questions/22543745/cant-import-numpy">Can't import numpy</a></p>
<p>Which is very strange especially since I specifically asked for... | 0 | 2016-07-11T20:59:55Z | 38,316,254 | <p>Check that you have Python 3.5 installed by running <code>which python3</code> and <code>which python</code> (to make sure your versions aren't mixed up). </p>
<p>Then, to install for Python 3, you should run <code>pip3 install numpy</code>. It's a good idea to use the given Python tools to install Python-related p... | 1 | 2016-07-11T21:08:08Z | [
"python",
"numpy",
"import",
"homebrew"
] |
How to switch the colors of two categories in seaborn? | 38,316,199 | <p>Let's say I use the following 'iris' example with scatterplots</p>
<pre><code>import pandas as pd
import seaborn as sns
sns.set(style="whitegrid", palette="muted")
# Load the example iris dataset
iris = sns.load_dataset("iris")
# "Melt" the dataset to "long-form" or "tidy" representation
iris = pd.melt(iris, "spe... | 0 | 2016-07-11T21:04:23Z | 38,334,415 | <p>Seaborn is opensource:
The hexcodes are listed here:
<a href="https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py" rel="nofollow">https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py</a></p>
<pre><code>SEABORN_PALETTES = dict(
deep=["#4C72B0", "#55A868", "#C44E52",
"#8172... | 0 | 2016-07-12T16:28:17Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Numerical Laplace transform python | 38,316,225 | <p>I have a time series of experimental data x = x(t) in two numpy arrays, x for the observable and t for the time values of the observations. Is there a numpy function or a way that can evaluate the laplace transform of the timeseries? Thank you in advance.</p>
| 0 | 2016-07-11T21:05:46Z | 38,339,527 | <p>I think you should have to consider the Laplace Transform of f(x) as the Fourier Transform of Gamma(x)f(x)e^(bx), in which Gamma is a step function that delete the negative part of the integral and e^(bx) constitute the real part of the complex exponential.
There is a well known algorithm for Fourier Transform known... | 0 | 2016-07-12T21:59:10Z | [
"python",
"numpy",
"transform"
] |
Numerical Laplace transform python | 38,316,225 | <p>I have a time series of experimental data x = x(t) in two numpy arrays, x for the observable and t for the time values of the observations. Is there a numpy function or a way that can evaluate the laplace transform of the timeseries? Thank you in advance.</p>
| 0 | 2016-07-11T21:05:46Z | 38,599,137 | <p>You may use the <strong>Trapezoidal rule</strong> to calculate numerically the integral for the Laplace transform. One paper which describes this method is <a href="https://www.researchgate.net/publication/233658371_Pade_-Laplace_analysis_of_signal_averaged_voltage_decays_obtained_from_a_simple_circuit" rel="nofollo... | 0 | 2016-07-26T20:17:22Z | [
"python",
"numpy",
"transform"
] |
How do I execute a command after pushing a button while also closing the window with the button in python (with tkinter)? | 38,316,281 | <p>Basically I want to execute the command as seen below and also close the window with the 2 buttons (in either case). The command just sets the variable self.switch to True or False, so if there is a neater way of doing this rather than writing a new method for each of those, that would also be nice.</p>
<pre><code>... | 0 | 2016-07-11T21:10:07Z | 38,316,576 | <p>Doing it in a new method <em>is</em> the neat way of doing things- you'd probably make the <code>command=lambda:self.switchTo([value])</code>, with [value] being True or False that you would like to swap to. You would have to pass <code>top</code> into the function as well, so you can <code>destroy</code> it.</p>
<... | 0 | 2016-07-11T21:33:31Z | [
"python",
"python-3.x",
"tkinter"
] |
Trouble using numpy.load | 38,316,283 | <p>I have the following data, written in python 2, that I'd like to load to a python 3 file.</p>
<pre><code>import numpy as np
x = np.array([{'a': np.array([1., 2., 3])}])
np.save('data.npy', x)
</code></pre>
<p>My first attempt was this:</p>
<pre><code>import numpy as np
x = np.load('data.npy')
UnicodeError: Unpic... | 1 | 2016-07-11T21:10:09Z | 38,316,603 | <p>The default encoding in Python 2 is <code>ascii</code>; in Python 3 it is <code>utf-8</code>. <code>latin1</code> (a.k.a., ISO-8859-1) is a superset of <code>ascii</code>. That's why loading <code>ascii</code>-encoded strings with <code>latin1</code> works and gives the same result as loading it with <code>ascii</co... | 3 | 2016-07-11T21:35:56Z | [
"python",
"arrays",
"numpy",
"dictionary"
] |
Pandas Create Column that Copies Another Cell Value | 38,316,290 | <p>I have a Receipt Journal DataFrame that contains about 400,000 rows of the following:
<a href="http://i.stack.imgur.com/N7oq9.png" rel="nofollow">Snippet1</a></p>
<p>The row which contains a value for the "Tender" column (e.g., Cash, CrCd) is the receipt total. The rows that follow are the items in that transaction... | 4 | 2016-07-11T21:10:20Z | 38,316,407 | <p><strong>UPDATE:</strong></p>
<pre><code>In [11]: df['ReceiptNumber'] = (df.assign(ReceiptNumber=np.where(pd.notnull(df.Tender),
....: df['Rcpt#'],
....: np.nan))['ReceiptNumber']
....: ... | 3 | 2016-07-11T21:19:52Z | [
"python",
"pandas",
"dataframe"
] |
cannot locate haarcascade default frontal face XML file on windows | 38,316,294 | <p>I am new to image processing and i've been getting my hands dirty with opencv for python for past few weeks. Today I tried to use the default haarcascade XML file for the face detection. Here is my code:</p>
<pre><code>import cv2
import numpy as np
front_cascade = cv2.CascadeClassifier('haarcascade_frontalface_def... | 0 | 2016-07-11T21:11:01Z | 38,320,944 | <p>When you say <code>front_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')</code>, the cascade file must be present in the same folder in which the program is being executed, Best practice is to pass the full qualified path of the cascade file, If you are not able to locate the cascade files bun... | 1 | 2016-07-12T05:52:19Z | [
"python",
"windows",
"opencv"
] |
How to save a canvas as PNG in Selenium? | 38,316,402 | <p>I am trying to save a canvas element as a png image. This is my code right now but, unfortunately, it does not work.</p>
<pre><code>import time
from selenium import webdriver
#from PIL import Image
driver = webdriver.Firefox()
driver.get('http://www.agar.io')
driver.maximize_window()
driver.find_element_by_id('fre... | 3 | 2016-07-11T21:19:30Z | 38,318,578 | <p>You could call <code>HTMLCanvasElement.toDataURL()</code> to get the canvas as PNG base64 string. Here is a working example:</p>
<pre><code>import base64
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://curran.github.io/HTML5Examples/canvas/smileyFace.html")
canvas = driver.find_eleme... | 1 | 2016-07-12T01:20:53Z | [
"javascript",
"python",
"selenium",
"canvas",
"png"
] |
Pandas multi-indexing succeeds when given a tuple, fails with a list | 38,316,475 | <p>I have data in the form of an array of lists, of the form <code>[['Manhattan', 142, 42], [...]]</code>. I have a <code>pd.DataFrame</code> with a multi-index, one containing, among other things, a column called <code>VAC</code>.</p>
<p>The following raises a <code>ValueError</code>:</p>
<pre><code>for vac_bbl in v... | 1 | 2016-07-11T21:24:37Z | 38,317,304 | <p>pandas uses a list in this context to return a dataframe of columns in which each column is indexed with each specific item in the list. A tuple is used to represent the multiple layers for that particular column in the multiindex. This makes perfect sense and is as expected.</p>
<p>You can also pass a list of tu... | 3 | 2016-07-11T22:38:47Z | [
"python",
"numpy",
"pandas"
] |
Python extract substring from string | 38,316,477 | <p>so i'm trying to convert a bash script, that i wrote, into python, that i'm learning, and the python equivalent of the bash whois just can't give me the answer that i need.</p>
<p>this is what i have in bash-</p>
<pre><code>whois 'ip address' | grep -i abuse | \
grep -o [[:alnum:]]*\@[[:alnum:]]*\.[[:alpha:]]... | 0 | 2016-07-11T21:24:52Z | 38,316,618 | <p>You were on the right track with using the regex module. Your <a href="https://docs.python.org/3.5/library/re.html#re.search" rel="nofollow">search</a> could be</p>
<pre><code>re.search(r'(\w*@\w*\.\w*)', IPWhois(ip).lookup_whois()['nets'][0]['emails']).group(1)
</code></pre>
| 0 | 2016-07-11T21:36:56Z | [
"python"
] |
Python extract substring from string | 38,316,477 | <p>so i'm trying to convert a bash script, that i wrote, into python, that i'm learning, and the python equivalent of the bash whois just can't give me the answer that i need.</p>
<p>this is what i have in bash-</p>
<pre><code>whois 'ip address' | grep -i abuse | \
grep -o [[:alnum:]]*\@[[:alnum:]]*\.[[:alpha:]]... | 0 | 2016-07-11T21:24:52Z | 38,340,557 | <p>What I ended up doing was</p>
<pre><code>domain = socket.gethostbyname(hostname/ipaddr) #if ipaddr it stays the same
email_addr = re.search(r'(\w*\D\w*@\w*\.\w*)', IPWhois(domain).lookup_whois()['nets'][0]['emails']).group(1)
</code></pre>
<p>I had to put the extra <code>\w*\D</code> in there because some of the e... | 0 | 2016-07-12T23:50:43Z | [
"python"
] |
Dynamically plot, show, and close changing data sizes in python | 38,316,528 | <p>I need to plot, and show a matplotlib graph that updates dynamically. Problem is, my data size is always growing by one. I'm ok replotting the whole thing, but I need the plot to be visible until the next one is available. As far as I can tell, because my data shape is changing, I can't use plt.ion()</p>
<p>Here's ... | 0 | 2016-07-11T21:29:26Z | 38,317,361 | <p>I was able to figure this out, due to help from <a href="http://stackoverflow.com/questions/28269157/plotting-in-a-non-blocking-way-with-matplotlib" title="this">this</a> answer, though I am still getting a deprecated matplotlib answer. </p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
plt.io... | 0 | 2016-07-11T22:45:44Z | [
"python",
"matplotlib",
"plot"
] |
Fast Fourier Transform Javascript | 38,316,538 | <p>I need a FFT function like the FFT in <code>numpy</code> (python) that takes only ONE list( length doesnt necessarily need to be power of 2).</p>
<p>I used <code>dsp.js</code> but it needs the Buffer size and buffer size <strong>must</strong> be power of 2 but my data length is 500.</p>
<p>is there any library tha... | 1 | 2016-07-11T21:30:25Z | 38,318,618 | <p>You absolutely can pad with zeros to reach the desired size. See this reference: <a href="http://www.bitweenie.com/listings/fft-zero-padding/" rel="nofollow">http://www.bitweenie.com/listings/fft-zero-padding/</a></p>
<p>A quote straight from the article:</p>
<blockquote>
<p>There are a few reasons why you migh... | 1 | 2016-07-12T01:24:07Z | [
"javascript",
"python",
"fft"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.