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 |
|---|---|---|---|---|---|---|---|---|---|
How would I make a simple recursive function outputting the number of divisors a number has? | 38,493,387 | <p>In an online class, I received this problem.</p>
<p>Write a function numDivisors( N ) that returns the number of integers from 1 to N (inclusive) that divide N evenly. For example, numDivisors(42) would return 8, since 1, 2, 3, 6, 7, 14, 21, and 42 are divisors of 42. (Python 2.7)</p>
<p>Although I have solved it with a loop, I'm wondering how I would go about this with recursion.</p>
<p>The basic functionality of this function with a loop would be:</p>
<pre><code>def numDivisors( N ):
""" returns # of integers that divide evenly into N """
divisors = 1 # the factor 1
if N != 1:
divisors += 1 # the factor N
for i in range(2,int(N)): # loops through possible divisors
if N % i == 0: # factor found
divisors += 1
return divisors
</code></pre>
<p>How could I implement it recursively using the bare basics (declaration, conditionals, looping, etc. up to list comprehensions)?</p>
<p>Thanks!</p>
| 0 | 2016-07-21T01:26:12Z | 38,493,455 | <p>how about</p>
<pre><code>def find_divisors(N,i=1):
if i >= N**0.5+1: return set([])
if N%i == 0: return set([i,N//i]).union(find_divisors(N,i+1))
return find_divisors(N,i+1)
</code></pre>
<p>recursion is a pretty lousy solution to this problem ... do you really need to find all the divisors? or are you looking for a special one? </p>
| 1 | 2016-07-21T01:33:04Z | [
"python",
"recursion"
] |
How would I make a simple recursive function outputting the number of divisors a number has? | 38,493,387 | <p>In an online class, I received this problem.</p>
<p>Write a function numDivisors( N ) that returns the number of integers from 1 to N (inclusive) that divide N evenly. For example, numDivisors(42) would return 8, since 1, 2, 3, 6, 7, 14, 21, and 42 are divisors of 42. (Python 2.7)</p>
<p>Although I have solved it with a loop, I'm wondering how I would go about this with recursion.</p>
<p>The basic functionality of this function with a loop would be:</p>
<pre><code>def numDivisors( N ):
""" returns # of integers that divide evenly into N """
divisors = 1 # the factor 1
if N != 1:
divisors += 1 # the factor N
for i in range(2,int(N)): # loops through possible divisors
if N % i == 0: # factor found
divisors += 1
return divisors
</code></pre>
<p>How could I implement it recursively using the bare basics (declaration, conditionals, looping, etc. up to list comprehensions)?</p>
<p>Thanks!</p>
| 0 | 2016-07-21T01:26:12Z | 38,493,635 | <p>If we have to be recursive:</p>
<pre><code>>>> def ndiv(N, i=1):
... return 1 if N==i else ((N % i == 0) + ndiv(N, i+1))
...
</code></pre>
<p>Let's test it. As per the question:</p>
<blockquote>
<p>For example, numDivisors(42) would return 8</p>
</blockquote>
<pre><code>>>> ndiv(42)
8
</code></pre>
<p>Thus, this produces the desired output.</p>
<p>If we can do away with recursion, here is how to do it just using list comprehension:</p>
<pre><code>>>> def div(N):
... return sum(1 for i in range(1, N+1) if N % i == 0)
...
>>> div(42)
8
</code></pre>
| 1 | 2016-07-21T01:57:43Z | [
"python",
"recursion"
] |
Append keys and values to one JSON object from multiple JSON files | 38,493,405 | <p>I'm currently working with three json files. </p>
<p>master.json</p>
<pre><code> {
"master":[
{
"sport": "soccer",
"id": 1
},
{
"sport": "football",
"id": 2
}
]
}
</code></pre>
<p>data1.json</p>
<pre><code>{
"soccer": {
"players": 11
},
"football": {
"players": 12
}
}
</code></pre>
<p>data2.json</p>
<pre><code>{
"soccer": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
"football": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
}
</code></pre>
<p>What I'd like to do is combine attributes from each sport in each json file into the <code>master.json</code>. </p>
<p>This is what I'm looking for: </p>
<pre><code>{
"master":[
{
"sport": "soccer",
"id": 1,
"players": 11,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
{
"sport": "football",
"id": 2,
"players": 12,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
]
}
</code></pre>
<p>Ideally, I'd like to be able to include a conditional where the sport value in <code>data1</code> and <code>data2</code> must match what is in <code>master.json</code> to do the appending. So, if "baseball" is in <code>data1</code> and <code>data2</code> but not <code>master</code>, then it is not included. </p>
<p>I've tried using <code>underscore</code> in JavaScript and <code>json</code> in Python but to no luck. I can't seem to find a way to loop through all three json files to have them talking to each other, especially to see if the sport matches.</p>
<p>Any help would be appreciate. I'll also do my best to clarify and confusion. </p>
| 0 | 2016-07-21T01:28:15Z | 38,493,667 | <p>This will do it. Bare in mind, this is for your case.</p>
<pre><code>var master = {
"master":[
{
"sport": "soccer",
"id": 1
},
{
"sport": "football",
"id": 2
}
]
}
var data1 = {
"soccer": {
"players": 11
},
"football": {
"players": 12
}
}
var data2 = {
"soccer": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
"football": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
}
var masterSports = master.master.map(function(object){
return object.sport;
});
var data1Keep = {};
var data2Keep = {};
Object.keys(data1).map(function(key){
if(masterSports.indexOf(key) > -1 && !data1Keep.hasOwnProperty(key)){
data1Keep[key] = data1[key];
}
});
Object.keys(data2).map(function(key){
if(masterSports.indexOf(key) > -1 && !data2Keep.hasOwnProperty(key)){
data2Keep[key] = data2[key];
}
});
master.master.map(function(object){
for(key in data1Keep){
if(key == object.sport){
for(i in data1Keep[key]){
object[i] = data1Keep[key][i];
}
}
}
for(key2 in data2Keep){
if(key2 == object.sport){
for(j in data2Keep[key2]){
object[j] = data2Keep[key2][j];
}
}
}
return object;
});
</code></pre>
| 1 | 2016-07-21T02:01:19Z | [
"javascript",
"python",
"json"
] |
Append keys and values to one JSON object from multiple JSON files | 38,493,405 | <p>I'm currently working with three json files. </p>
<p>master.json</p>
<pre><code> {
"master":[
{
"sport": "soccer",
"id": 1
},
{
"sport": "football",
"id": 2
}
]
}
</code></pre>
<p>data1.json</p>
<pre><code>{
"soccer": {
"players": 11
},
"football": {
"players": 12
}
}
</code></pre>
<p>data2.json</p>
<pre><code>{
"soccer": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
"football": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
}
</code></pre>
<p>What I'd like to do is combine attributes from each sport in each json file into the <code>master.json</code>. </p>
<p>This is what I'm looking for: </p>
<pre><code>{
"master":[
{
"sport": "soccer",
"id": 1,
"players": 11,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
{
"sport": "football",
"id": 2,
"players": 12,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
]
}
</code></pre>
<p>Ideally, I'd like to be able to include a conditional where the sport value in <code>data1</code> and <code>data2</code> must match what is in <code>master.json</code> to do the appending. So, if "baseball" is in <code>data1</code> and <code>data2</code> but not <code>master</code>, then it is not included. </p>
<p>I've tried using <code>underscore</code> in JavaScript and <code>json</code> in Python but to no luck. I can't seem to find a way to loop through all three json files to have them talking to each other, especially to see if the sport matches.</p>
<p>Any help would be appreciate. I'll also do my best to clarify and confusion. </p>
| 0 | 2016-07-21T01:28:15Z | 38,493,755 | <p>Just to demonstrate the relative finesse of Python, I'll throw in a solution:</p>
<pre><code>import json
from collections import OrderedDict
with open('master.json') as m, open('data1.json') as d1, open('data2.json') as d2:
master = json.load(m, object_pairs_hook=OrderedDict)
data1 = json.load(d1, object_pairs_hook=OrderedDict)
data2 = json.load(d2, object_pairs_hook=OrderedDict)
for i, obj in enumerate(master['master']):
d1, d2 = data1.get(obj['sport']), data2.get(obj['sport'])
if d1:
master['master'][i].update(d1)
if d2:
master['master'][i].update(d2)
print(json.dumps(master,indent=2))
</code></pre>
<p>Output:</p>
<pre><code>{
"master": [
{
"sport": "soccer",
"id": 1,
"players": 11,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
{
"sport": "football",
"id": 2,
"players": 12,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
]
}
</code></pre>
| 1 | 2016-07-21T02:12:49Z | [
"javascript",
"python",
"json"
] |
python one-liner to do arithmetic operation on one element with same index for all sublists | 38,493,469 | <p>For example: I need to create a <code>list2</code> as <code>[[2, 0], [3, 0], [4, 0]]</code> from existing list <code>[[1, 0], [2, 0], [3, 0]]</code>. The index of the element is the same among all the sublist (0). How to achieve using one-liner?</p>
<p>I have tried:</p>
<pre><code>list=[[1,0],[2,0],[3,0]]
list2=[i[0]+1 for i in list] # only ends up with [2,3,4]
[i[0]=i[0]+1 for i in list] # invalid syntax
</code></pre>
| 2 | 2016-07-21T01:35:39Z | 38,493,493 | <p><code>list2 = [[i+1,j], for [i,j] in list]</code></p>
<p>if your sublists have different lengths:</p>
<p><code>list2 = [[x[0]+1]+x[1:] for x in list]</code></p>
| 4 | 2016-07-21T01:38:09Z | [
"python",
"list"
] |
python one-liner to do arithmetic operation on one element with same index for all sublists | 38,493,469 | <p>For example: I need to create a <code>list2</code> as <code>[[2, 0], [3, 0], [4, 0]]</code> from existing list <code>[[1, 0], [2, 0], [3, 0]]</code>. The index of the element is the same among all the sublist (0). How to achieve using one-liner?</p>
<p>I have tried:</p>
<pre><code>list=[[1,0],[2,0],[3,0]]
list2=[i[0]+1 for i in list] # only ends up with [2,3,4]
[i[0]=i[0]+1 for i in list] # invalid syntax
</code></pre>
| 2 | 2016-07-21T01:35:39Z | 38,493,503 | <p><code>[[x[0]+1,x[1]] for x in list]</code>
although you really should not name things list because of name conflicts</p>
| 2 | 2016-07-21T01:39:27Z | [
"python",
"list"
] |
Python script running twice | 38,493,508 | <p>Can somebody help me understand why is my code executed twice?</p>
<pre><code>import multiprocessing
from time import sleep
import os, signal
def neverEnding():
while True:
print ' Looping ... '
sleep(3)
p = multiprocessing.Process(target=neverEnding)
p.start()
sleep(10)
print p.is_alive()
print p.pid
p.terminate()
print p.is_alive()
print 'terminated?'
os.kill(int(p.pid), signal.SIGTERM)
print 'Now?'
sleep(3)
print p.is_alive()
</code></pre>
<p>This is the output I'm getting.</p>
<pre><code> Looping ...
Looping ...
Looping ...
Looping ...
True
8999
True
terminated?
Now?
False
Looping ...
Looping ...
Looping ...
Looping ...
True
9000
True
terminated?
Now?
False
</code></pre>
<p>I'm getting 'terminated?', 'Now?' etc... printed twice.<br>
Can somebody explain why does this happen?</p>
<p>Will the other processes running in the background cause this? (I had run the same script using subprocess before)</p>
<p>I'm using Ubuntu.</p>
| 2 | 2016-07-21T01:40:13Z | 38,493,911 | <p>Which python version do you use? I am using 2.6.9 on linux, the same code as yours but get the different result:</p>
<pre><code> *Looping ...
Looping ...
Looping ...
Looping ...
True
6634
True
terminated?
Now?
False*
</code></pre>
<p>The problem of why after "p.terminate()" the process is still alive is due to
the parent process can not get the sub-process state that fast.
If I add a sleep(0.1) in between:</p>
<pre><code>p.terminate()
sleep(0.1)
print p.is_alive()
</code></pre>
<p>I get the following result:</p>
<pre><code> Looping ...
Looping ...
Looping ...
Looping ...
True
7046
False
terminated?
Traceback (most recent call last):
File "./test_m.py", line 24, in <module>
os.kill(int(p.pid), signal.SIGTERM)
OSError: [Errno 3] No such process
</code></pre>
<p>The subprocess is terminated, so os.kill(int(p.pid), signal.SIGTERM) get an error!</p>
| 0 | 2016-07-21T02:30:38Z | [
"python",
"multiprocessing"
] |
Accessing MATLAB data in Python with a concatenated filename | 38,493,542 | <p>I'm translating some MATLAB code into Python and I need to access data structures. Using scipy, I need to concatenate a user input string into a filename:</p>
<p><code>cb_data = scipy.io.loadmat('./cb_data/' + subj_id + '_cb_AAAD_V2.mat' , 'rb')</code></p>
<p>where subj_id is a variable coming from user input. I have also tried inputting the user input directly but it returned the same error</p>
<pre><code>File "/Users/pproctor/anaconda/PythonScripts_conda/get_num_trials.py",line 36, in
get_num_trials cb_data = scipy.io.loadmat('./cb_data/' + subj_id + '_cb_AAAD_V2.mat' , 'rb')
File "/Users/pproctor/anaconda/lib/python2.7/site-packages/scipy
/io/matlab/mio.py", line 137, in loadmat mdict.update(matfile_dict)
AttributeError: 'str' object has no attribute 'update'
</code></pre>
| 0 | 2016-07-21T01:45:36Z | 38,493,569 | <p>The second argument, <code>mdict</code>, of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html" rel="nofollow"><code>loadmat</code></a> is not the file access mode. It is optional, but if it is given, it must be a dictionary. The loaded arrays are added to this dictionay, with the variable names as keys and the actual arrays as values.</p>
| 0 | 2016-07-21T01:49:27Z | [
"python",
"matlab",
"scipy"
] |
Using a variable in a regex in Python | 38,493,544 | <p>I am trying to capture the last name, first name and number from a string that has the following pattern:</p>
<pre><code>str = "Doe, John; 620 Eisenberg, Andrew; 253"
</code></pre>
<p>The following line of code seems to capture the last name and first name but returns None when I include the part for the number:</p>
<pre><code>strfind = re.findall(r'(?P<last>[A-Z][A-Za-z]+), (?P<first>[A-Z][A-Za-z]+): (?P<num>\d+)', str, re.M|re.I)
print(strfind)
</code></pre>
<p>Sorry, could not get the Verbose version to cooperate.<br>
I tried putting a comma and a colon outside the parentheses for <strong>last</strong> and <strong>first</strong> to include it in the search to capture the string that comes before it, but that didn't seem to work. Along the same lines, I tried using a space at the end of the <strong>num</strong> group as well. </p>
<p>Excluding the <strong>num</strong> group I get the following output:</p>
<p>[('Doe', 'John'), ('Eisenberg', 'Andrew')]</p>
| 0 | 2016-07-21T01:45:48Z | 38,493,665 | <p>Replacing <code>:</code> with <code>;</code>, as @Kasramvd suggested, works perfectly:</p>
<pre><code>>>> import re
>>> s = "Doe, John; 620 Eisenberg, Andrew; 253"
>>> re.findall(r'(?P<last>[A-Z][A-Za-z]+), (?P<first>[A-Z][A-Za-z]+); (?P<num>\d+)', s, re.M|re.I)
[('Doe', 'John', '620'), ('Eisenberg', 'Andrew', '253')]
</code></pre>
<p>If you want results in a list of dictionaries format, use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>finditer()</code></a> and <a href="https://docs.python.org/2/library/re.html#re.MatchObject.groupdict" rel="nofollow"><code>groupdict()</code></a>:</p>
<pre><code>>>> results = re.finditer(r'(?P<last>[A-Z][A-Za-z]+), (?P<first>[A-Z][A-Za-z]+); (?P<num>\d+)', s, re.M|re.I)
>>> [m.groupdict() for m in results]
[
{'num': '620', 'last': 'Doe', 'first': 'John'},
{'num': '253', 'last': 'Eisenberg', 'first': 'Andrew'}
]
</code></pre>
| 2 | 2016-07-21T02:01:08Z | [
"python",
"regex"
] |
Using a variable in a regex in Python | 38,493,544 | <p>I am trying to capture the last name, first name and number from a string that has the following pattern:</p>
<pre><code>str = "Doe, John; 620 Eisenberg, Andrew; 253"
</code></pre>
<p>The following line of code seems to capture the last name and first name but returns None when I include the part for the number:</p>
<pre><code>strfind = re.findall(r'(?P<last>[A-Z][A-Za-z]+), (?P<first>[A-Z][A-Za-z]+): (?P<num>\d+)', str, re.M|re.I)
print(strfind)
</code></pre>
<p>Sorry, could not get the Verbose version to cooperate.<br>
I tried putting a comma and a colon outside the parentheses for <strong>last</strong> and <strong>first</strong> to include it in the search to capture the string that comes before it, but that didn't seem to work. Along the same lines, I tried using a space at the end of the <strong>num</strong> group as well. </p>
<p>Excluding the <strong>num</strong> group I get the following output:</p>
<p>[('Doe', 'John'), ('Eisenberg', 'Andrew')]</p>
| 0 | 2016-07-21T01:45:48Z | 38,493,690 | <p>Try this below:</p>
<pre><code>>>> input = "Doe, John; 620 Eisenberg, Andrew; 253"
>>> import re
>>> tmpLst = re.split(r'[;,\s]\s*', input)
>>> print tmpLst
['Doe', 'John', '620', 'Eisenberg', 'Andrew', '253']
>>> output = []
>>> for i in range(0, len(tmpLst), 3):
... output.append(tuple(tmpLst[i:i+3]))
...
>>> print output
[('Doe', 'John', '620'), ('Eisenberg', 'Andrew', '253')]
</code></pre>
| 0 | 2016-07-21T02:04:45Z | [
"python",
"regex"
] |
'SparkSession' object has no attribute 'sparkContext' | 38,493,570 | <p>I have Spark 2.0.0 and I am trying to run some Python examples from Spark source code.</p>
<p>This is the <a href="https://github.com/apache/spark/blob/master/examples/src/main/python/pi.py" rel="nofollow">example</a>. And I was running like:</p>
<pre><code>spark-submit pi.py 2
</code></pre>
<p>But I kept getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "/home/docker-user/src/hellospark/src/main/python/pi.py", line 21, in <module>
count = ss.sparkContext.parallelize(range(1, n + 1), partitions).map(f).reduce(add)
AttributeError: 'SparkSession' object has no attribute 'sparkContext'
</code></pre>
<p>I've also tested with other examples like wordcount.py, sort.py and sql.py, all of them works as expected. Anybody has met this issue before? Any comment would be super helpful.</p>
<p>Thanks in advance!! </p>
| 0 | 2016-07-21T01:49:29Z | 39,668,926 | <p>As @stpk mentioned, you are probably running an older spark version. For example, Spark 1.5.1 doesn't have <code>pyspark.sql.SparkSession</code> (check out the <a href="https://spark.apache.org/docs/1.5.1/api/python/pyspark.sql.html" rel="nofollow">api document</a>, but later versions have <a href="https://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html" rel="nofollow">doc</a>. Or use older test files.</p>
| 0 | 2016-09-23T20:20:23Z | [
"python",
"apache-spark",
"pyspark"
] |
Python: WindowsError when creating folder with os.mkdir and using square brackets | 38,493,598 | <p>On Windows, when I tried to create the following folder:</p>
<pre><code> os.mkdir('H:\\__ Photos\\____Photos to be sorted\\[ Photo sorting process ]\\_NEW\\__PROC_PHOTOS\\1. Original CRW')
</code></pre>
<p>I got the error:</p>
<blockquote>
<p>WindowsError: [Error 3] <strong>The system cannot find the path specified</strong>: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW'</p>
</blockquote>
<p>"_NEW" folder already existed, it was the current working directory. Then I tried to use single backslashes:</p>
<pre><code>os.mkdir('H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW')
</code></pre>
<blockquote>
<p>WindowsError: [Error 123] <strong>The filename, directory name, or volume label syntax is incorrect</strong>: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\x01. Original CRW'</p>
</blockquote>
<p>So the "\1" got converted into "\x01". Escaping this particular backslash resulted in the [Error 3] error, as before.</p>
<p>Making the string a string literal:</p>
<pre><code>os.mkdir(r'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW')
</code></pre>
<p>produced the same error:</p>
<blockquote>
<p>WindowsError: [Error 3] <strong>The system cannot find the path specified</strong>: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW'</p>
</blockquote>
<p>Then:</p>
<pre><code>os.mkdir("H:\[ Photo sorting process ]\\NEW")
</code></pre>
<p>was bad ("[ Photo sorting process ]" didn't exist), but:</p>
<pre><code>os.mkdir("H:\[ Photo sorting process ]")
os.mkdir("H:\[ Photo sorting process ]\\NEW")
</code></pre>
<p>was good. Does it mean that I can only create 1 level of subdirectories? Is there any other way? I want to pass the path as a variable.</p>
| 0 | 2016-07-21T01:53:07Z | 38,493,622 | <p>You can use <code>os.makedirs</code> instead of <code>os.mkdir</code>. From the documentation:</p>
<blockquote>
<p>Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.</p>
</blockquote>
| 3 | 2016-07-21T01:56:19Z | [
"python",
"windows",
"folder",
"mkdir"
] |
Python Anaconda - no module named numpy | 38,493,608 | <p>I recently installed Anaconda on Arch Linux from the Arch repositories. By default, it was set to Python3, whereas I would like to use Python2.7. I followed the Anaconda documentation to create a new Python2 environment. Upon running my Python script which uses Numpy, I got the error <code>No module named NumPy</code>. I found this rather strange, as one of the major points of using Anaconda is easy installation of the NumPy/SciPy stack...</p>
<p>Nevertheless, I ran <code>conda install numpy</code> and it installed. Now, I still cannot import numpy, but when I run <code>conda install numpy</code> it says it is already installed. What gives?</p>
<p>Output of <code>which conda</code>: <code>/opt/anaconda/envs/python2/bin/conda</code></p>
<p>Output of <code>which python</code>: <code>/opt/anaconda/envs/python2/bin/python</code></p>
| 0 | 2016-07-21T01:54:08Z | 38,503,517 | <p>The <code>anaconda</code> package in the AUR is broken. If anyone encounters this, simply install <code>anaconda</code> from their website. The AUR attempts to do a system-wide install, which gets rather screwy with the path.</p>
| 0 | 2016-07-21T11:50:51Z | [
"python",
"python-2.7",
"numpy",
"anaconda"
] |
How to append stdout to file for pyinotify daemonize? | 38,493,659 | <p>I am trying to add watches using python pyinotify and daemonize the notifier.</p>
<pre><code>notifier = pyinotify.Notifier(wm, handler)
notifier.loop(daemonize=True, pid_file='/tmp/pyinotifier.pid',
stdout='/tmp/out.log', stderr='/tmp/error.log')
</code></pre>
<p>However I could find, the log files are overwritten not getting appended.
Is there a way to append <code>stdout</code> and <code>stderr</code>?
I am on Linux OS.</p>
<p>thanks</p>
| 0 | 2016-07-21T02:00:28Z | 38,494,257 | <p>Looking at <a href="https://github.com/seb-m/pyinotify/blob/master/python2/pyinotify.py#L1295" rel="nofollow">the source</a>, it appears as though the logs are opened in <code>O_WRONLY</code> mode, which is why you see them being overwritten each time you invoke the loop:</p>
<pre><code>def __daemonize(self, pid_file=None, stdin=os.devnull, stdout=os.devnull,
stderr=os.devnull):
"""
@param pid_file: file where the pid will be written. If pid_file=None
the pid is written to
/var/run/<sys.argv[0]|pyinotify>.pid, if pid_file=False
no pid_file is written.
@param stdin:
@param stdout:
@param stderr: files associated to common streams.
"""
if pid_file is None:
dirname = '/var/run/'
basename = os.path.basename(sys.argv[0]) or 'pyinotify'
pid_file = os.path.join(dirname, basename + '.pid')
if pid_file != False and os.path.lexists(pid_file):
err = 'Cannot daemonize: pid file %s already exists.' % pid_file
raise NotifierError(err)
def fork_daemon():
# Adapted from Chad J. Schroeder's recipe
# @see http://code.activestate.com/recipes/278731/
pid = os.fork()
if (pid == 0):
# parent 2
os.setsid()
pid = os.fork()
if (pid == 0):
# child
os.chdir('/')
os.umask(022)
else:
# parent 2
os._exit(0)
else:
# parent 1
os._exit(0)
fd_inp = os.open(stdin, os.O_RDONLY)
os.dup2(fd_inp, 0)
fd_out = os.open(stdout, os.O_WRONLY|os.O_CREAT, 0600)
os.dup2(fd_out, 1)
fd_err = os.open(stderr, os.O_WRONLY|os.O_CREAT, 0600)
os.dup2(fd_err, 2)
# Detach task
fork_daemon()
# Write pid
if pid_file != False:
flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
fd_pid = os.open(pid_file, flags, 0600)
os.write(fd_pid, str(os.getpid()) + '\n')
os.close(fd_pid)
# Register unlink function
atexit.register(lambda : os.unlink(pid_file))
</code></pre>
<p>There is a <a href="https://github.com/seb-m/pyinotify/pull/114/commits/8b6ec45e75f969ae2885e57b6d779d8a48c3df34" rel="nofollow">pull request</a> open to open the logs in <code>O_APPEND</code> mode, but it's nearly 8 months old and the author has not responded.</p>
<p>It doesn't look like there's a reasonable way to append the logs at this time.</p>
| 0 | 2016-07-21T03:10:38Z | [
"python",
"pyinotify"
] |
ZeroMQ ROUTER-DEALER redirect to another ROUTER-DEALER issue | 38,493,675 | <p>I have a static DNS named <code>vops-server.com</code> that points to my Dell PowerEdge 2950. On this 2950 I run the <code>server.py</code> which initially binds to <code>tcp://0.0.0.0:7777</code>, and subsequently redirects any incoming clients to a socket bound to a port greater than <code>7777</code>, the first of which being <code>7778</code>. This newly-spawned <code>ROUTER-DEALER</code> pair simply echo <code>"Hello, world!"</code>.</p>
<p>The Dell PowerEdge 2950 operates <code>Ubuntu 16.04.1 LTS</code> and fails to run the code properly, outputting the following upon a KeyboardInterrupt:</p>
<pre><code>kâEg
Listening on port 7778
Recv
Resource temporarily unavailable
Client on port 7778 disconnected
^CProcess Process-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "test_server.py", line 76, in worker_task
data = worker_socket.recv_multipart()
File "/usr/local/lib/python2.7/dist-packages/zmq/sugar/socket.py", line 395, in recv_multipart
parts = [self.recv(flags, copy=copy, track=track)]
File "zmq/backend/cython/socket.pyx", line 693, in zmq.backend.cython.socket.Socket.recv (zmq/backend/cython/socket.c:7283)
File "zmq/backend/cython/socket.pyx", line 727, in zmq.backend.cython.socket.Socket.recv (zmq/backend/cython/socket.c:7081)
File "zmq/backend/cython/socket.pyx", line 145, in zmq.backend.cython.socket._recv_copy (zmq/backend/cython/socket.c:2033)
File "zmq/backend/cython/checkrc.pxd", line 12, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:7522)
PyErr_CheckSignals()
KeyboardInterrupt
</code></pre>
<p>While the client outputs the following:</p>
<pre><code>Connecting to distribution server tcp://vops-server.com:7777
[Dist] Send
[Dist] Recv
[Dist] 7778
Connecting to host tcp://vops-server.com:7778
[Host] Send
[Host] Recv
</code></pre>
<p>At this point the client is supposed to output a final line of <code>[Host] Hello, world!</code>, yet it hangs waiting to receive a message.</p>
<p>Now, on my laptop which operates <code>Windows 10 Home 1511</code>, the output is as expected:</p>
<pre><code> Ã )
Listening on port 7778
Recv
['\x00\x80\x00\x00)', 'Hello, world!']
Sent
</code></pre>
<p>With the client now properly outputting:</p>
<pre><code>Connecting to distribution server tcp://vops-server.com:7777
[Dist] Send
[Dist] Recv
[Dist] 7778
Connecting to host tcp://vops-server.com:7778
[Host] Send
[Host] Recv
[Host] Hello, world!
</code></pre>
<p>Please review the code below.</p>
<p>server.py:</p>
<pre><code>import sys
import zmq
from multiprocessing import Process, Queue, Array, Value
import time
def server_task():
port_base = 7777
server_context = zmq.Context.instance()
server_socket = server_context.socket(zmq.ROUTER)
server_socket.bind("tcp://0.0.0.0:%d" % (port_base, ))
timeout_queue = Queue()
port_list = [ 1 ]
proc_list = [ ]
while True:
try:
client_id = server_socket.recv_multipart()[0]
print(client_id)
# Get an unused port from the list
# Ports from clients that have timed out are recycled here
while not timeout_queue.empty():
port_list.append(timeout_queue.get())
port_offset = port_list.pop()
if len(port_list) == 0:
port_list.append(port_offset + 1)
# Spawn a new worker task, binding the port to a socket
proc_running = Value("b", True)
proc_list.append(proc_running)
Process(target=worker_task, args=(proc_running, port_base, port_offset, timeout_queue)).start()
# Send the new port to the client
server_socket.send_multipart([client_id, str(port_base + port_offset)])
except KeyboardInterrupt:
break
for proc_running in proc_list:
proc_running.value = False
server_socket.close()
server_context.term()
def worker_task(proc_running, port_base, port_offset, timeout_queue):
port = port_base + port_offset
print("Listening on port %d" % (port, ))
worker_context = zmq.Context.instance()
worker_socket = worker_context.socket(zmq.ROUTER)
worker_socket.setsockopt(zmq.RCVTIMEO, 5000)
worker_socket.bind("tcp://0.0.0.0:%d" % (port, ))
while proc_running.value:
try:
print("Recv")
data = worker_socket.recv_multipart()
print(data)
worker_socket.send_multipart(data)
print("Sent")
except zmq.ZMQError as e:
print(e)
break
print("Client on port %d disconnected" % (port, ))
timeout_queue.put(port_offset)
worker_socket.close()
worker_context.term()
if __name__ == "__main__":
server_task()
</code></pre>
<p>client.py:</p>
<pre><code>import os
import io
import time
import zmq
from multiprocessing import Process
def connect_to_host(context, host, port, timeout):
address = ("tcp://%s:%s" % (host, port))
socket = context.socket(zmq.DEALER)
socket.setsockopt(zmq.RCVTIMEO, timeout)
socket.connect(address)
print("Connecting to distribution server %s" % (address, ))
while True:
try:
print("[Dist] Send")
socket.send_multipart([str(0)])
print("[Dist] Recv")
port = socket.recv_multipart()[0]
print("[Dist] %s" % (port, ))
break
except zmq.Again:
socket.close()
socket = context.socket(zmq.DEALER)
socket.setsockopt(zmq.RCVTIMEO, timeout)
socket.connect(address)
print("Connecting to distribution server %s" % (address, ))
socket.close()
address = ("tcp://%s:%s" % (host, port))
socket = context.socket(zmq.DEALER)
socket.setsockopt(zmq.RCVTIMEO, timeout)
socket.connect(address)
print("Connecting to host %s" % (address, ))
return socket
def client_task(client_type):
timeout = 5000
host = "vops-server.com"
port = "7777"
context = zmq.Context().instance()
socket = connect_to_host(context, host, port, timeout)
while True:
try:
try:
print("[Host] Send")
socket.send_multipart(["Hello, world!"])
print("[Host] Recv")
data = socket.recv_multipart()[0]
print("[Host] %s" % (data, ))
except zmq.Again:
socket.close()
socket = connect_to_host(context, host, port, timeout)
except KeyboardInterrupt:
break
print("Connection terminated")
socket.close()
context.term()
if __name__ == "__main__":
client_task(0)
</code></pre>
<p>I can't possibly fathom why the same code works on the one machine and not the other; I've considered installing Windows Server 2012 on the Dell PowerEdge 2950 with my hopes being that the error lay in the OS and not the hardware itself. For now I wait and hope that an expert somewhere has the solution to my problem.</p>
| 0 | 2016-07-21T02:02:27Z | 38,548,405 | <p>Same code works fine on the Dell PowerEdge 2950 running Windows Server 2012 R2. ZMQ appears to have issues with Ubuntu. </p>
| 0 | 2016-07-24T03:17:05Z | [
"python",
"sockets",
"zeromq"
] |
Comparing rows of two pandas dataframes? | 38,493,795 | <p>This is a continuation of my question. <a href="http://stackoverflow.com/questions/38267763/fastest-way-to-compare-rows-of-two-pandas-dataframes/38270174#38270174">Fastest way to compare rows of two pandas dataframes?</a></p>
<p>I have two dataframes <code>A</code> and <code>B</code>: </p>
<p><code>A</code> is 1000 rows x 500 columns, filled with binary values indicating either presence or absence. </p>
<p>For a condensed example:</p>
<pre><code> A B C D E
0 0 0 0 1 0
1 1 1 1 1 0
2 1 0 0 1 1
3 0 1 1 1 0
</code></pre>
<p><code>B</code> is 1024 rows x 10 columns, and is a full iteration from 0 to 1023 in binary form.</p>
<p>Example: </p>
<pre><code> 0 1 2
0 0 0 0
1 0 0 1
2 0 1 0
3 0 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
</code></pre>
<p>I am trying to find which rows in <code>A</code>, at a particular 10 columns of <code>A</code>, correspond with each row of <code>B</code>.</p>
<p>Each row of <code>A[My_Columns_List]</code> is guaranteed to be somewhere in <code>B</code>, but not every row of <code>B</code> will match up with a row in <code>A[My_Columns_List]</code></p>
<p>For example, I want to show that for columns <code>[B,D,E]</code> of <code>A</code>, </p>
<p>rows <code>[1,3]</code> of A match up with row <code>[6]</code> of <code>B</code>,</p>
<p>row <code>[0]</code> of A matches up with row <code>[2]</code> of <code>B</code>, </p>
<p>row <code>[2]</code> of A matches up with row <code>[3]</code> of <code>B</code>.</p>
<p>I have tried using:</p>
<pre><code>pd.merge(B.reset_index(), A.reset_index(),
left_on = B.columns.tolist(),
right_on =A.columns[My_Columns_List].tolist(),
suffixes = ('_B','_A')))
</code></pre>
<p>This works, but I was hoping that this method would be faster:</p>
<pre><code>S = 2**np.arange(10)
A_ID = np.dot(A[My_Columns_List],S)
B_ID = np.dot(B,S)
out_row_idx = np.where(np.in1d(A_ID,B_ID))[0]
</code></pre>
<p>But when I do this, <code>out_row_idx</code> returns an array containing all the indices of <code>A</code>, which doesn't tell me anything.
I think this method will be faster, but I don't know why it returns an array from 0 to 999.
Any input would be appreciated!</p>
<p>Also, credit goes to @jezrael and @Divakar for these methods. </p>
| 4 | 2016-07-21T02:17:44Z | 38,494,149 | <p>I'll stick by my initial answer but maybe explain better.</p>
<p>You are asking to compare 2 pandas dataframes. Because of that, I'm going to build dataframes. I may use numpy, but my inputs and outputs will be dataframes.</p>
<h3>Setup</h3>
<p>You said we have a a 1000 x 500 array of ones and zeros. Let's build that.</p>
<pre><code>A_init = pd.DataFrame(np.random.binomial(1, .5, (1000, 500)))
A_init.columns = pd.MultiIndex.from_product([range(A_init.shape[1]/10), range(10)])
A = A_init
</code></pre>
<p>In addition, I gave <code>A</code> a <code>MultiIndex</code> to easily group by columns of 10.</p>
<h3>Solution</h3>
<p>This is very similar to @Divakar's answer with one minor difference that I'll point out.</p>
<p>For one group of 10 ones and zeros, we can treat it as a bit array of length 8. We can then calculate what it's integer value is by taking the dot product with an array of powers of 2.</p>
<pre><code>twos = 2 ** np.arange(10)
</code></pre>
<p>I can execute this for every group of 10 ones and zeros in one go like this</p>
<pre><code>AtB = A.stack(0).dot(twos).unstack()
</code></pre>
<p>I <code>stack</code> to get a row of 50 groups of 10 into columns in order to do the dot product more elegantly. I then brought it back with the <code>unstack</code>.</p>
<p>I now have a 1000 x 50 dataframe of numbers that range from 0-1023.</p>
<p>Assume <code>B</code> is a dataframe with each row one of 1024 unique combinations of ones and zeros. <code>B</code> should be sorted like <code>B = B.sort_values().reset_index(drop=True)</code>.</p>
<p>This is the part I think I failed at explaining last time. Look at </p>
<pre><code>AtB.loc[:2, :2]
</code></pre>
<p><a href="http://i.stack.imgur.com/tbnj8.png" rel="nofollow"><img src="http://i.stack.imgur.com/tbnj8.png" alt="enter image description here"></a></p>
<p>That value in the <code>(0, 0)</code> position, <code>951</code> means that the first group of 10 ones and zeros in the first row of <code>A</code> matches the row in <code>B</code> with the index <code>951</code>. That's what you want!!! Funny thing is, I never looked at B. You know why, B is irrelevant!!! It's just a goofy way of representing the numbers from 0 to 1023. This is the difference with my answer, I'm ignoring <code>B</code>. Ignoring this useless step should save time.</p>
<p>These are all functions that take two dataframes <code>A</code> and <code>B</code> and returns a dataframe of indices where <code>A</code> matches <code>B</code>. Spoiler alert, I'll ignore <code>B</code> completely.</p>
<pre><code>def FindAinB(A, B):
assert A.shape[1] % 10 == 0, 'Number of columns in A is not a multiple of 10'
rng = np.arange(A.shape[1])
A.columns = pd.MultiIndex.from_product([range(A.shape[1]/10), range(10)])
twos = 2 ** np.arange(10)
return A.stack(0).dot(twos).unstack()
</code></pre>
<hr>
<pre><code>def FindAinB2(A, B):
assert A.shape[1] % 10 == 0, 'Number of columns in A is not a multiple of 10'
rng = np.arange(A.shape[1])
A.columns = pd.MultiIndex.from_product([range(A.shape[1]/10), range(10)])
# use clever bit shifting instead of dot product with powers
# questionable improvement
return (A.stack(0) << np.arange(10)).sum(1).unstack()
</code></pre>
<hr>
<p>I'm channelling my inner @Divakar (read, this is stuff I've learned from Divakar)</p>
<pre><code>def FindAinB3(A, B):
assert A.shape[1] % 10 == 0, 'Number of columns in A is not a multiple of 10'
a = A.values.reshape(-1, 10)
a = np.einsum('ij->i', a << np.arange(10))
return pd.DataFrame(a.reshape(A.shape[0], -1), A.index)
</code></pre>
<hr>
<h3>Minimalist One Liner</h3>
<pre><code>f = lambda A: pd.DataFrame(np.einsum('ij->i', A.values.reshape(-1, 10) << np.arange(10)).reshape(A.shape[0], -1), A.index)
</code></pre>
<p>Use it like </p>
<pre><code>f(A)
</code></pre>
<hr>
<h3>Timing</h3>
<p>FindAinB3 is an order of magnitude faster</p>
<p><a href="http://i.stack.imgur.com/eh0uF.png" rel="nofollow"><img src="http://i.stack.imgur.com/eh0uF.png" alt="enter image description here"></a></p>
| 7 | 2016-07-21T02:59:47Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Where is the value of objects like lists,ints, and strings stored? | 38,493,846 | <p>Alright so all lists have <code>__setitem__</code> and <code>__getitem__</code> and ints have <code>__add__</code> <code>__sub__</code> and such to operate on their value. But where is that value actually stored / how can I reference it? Say I want to make a class imitating an list. It might look something like this</p>
<pre><code>class Memory(object):
def __init__(self):
self.data = []
def __getitem__(self, i):
return self.data[i]
def __setitem__(self, key, item):
self.data[key] = item
</code></pre>
<p>This isn't very efficient, and I'd have to most likely write every single method of the class individually, which can span hundreds of lines with multiple classes.</p>
<p>The next best solution to create the class being a child of a list like:</p>
<pre><code>class Memory(list):
...
</code></pre>
<p>But you can't edit any of its methods because you can't reference its value. If you changes its <code>__setitem__()</code>
What I was wanting to do with this is to create a list class so I can set the list's and do other operations values all on one lambda. I can't just simply directly call <code>__setitem__(key,item)</code> because you can't input a key outside of the range of the items already present in the list. How would I be able to edit the list's value without calling its <code>__setitem__()</code> method.</p>
| 2 | 2016-07-21T02:22:16Z | 38,493,939 | <p>I realize this doesn't directly answer your question about "where is the value ... stored", and I'm not sure what you mean by "I can't just simply directly call <code>__setitem__(key,item)</code> because you can't input a key outside of the range of the items already present in the list," but if I understand you correctly, you just have to "fill in" values in between the value you want to set and the current length. </p>
<p>For example, I have a utility class that I sometimes use to do this. (See the test cases at the bottom for an idea of how I use it.)</p>
<pre><code>class DynamicArray(list):
''' Just like a normal list except you can skip indices when you fill it. '''
def __init__(self, defaultVal = None, startingCapacity = 0):
super(DynamicArray, self).__init__()
self.defaultVal = defaultVal
if (startingCapacity > 0):
self += [ defaultVal ] * startingCapacity
def insert(self, ind, val):
if (ind > len(self)):
for i in xrange(len(self), ind):
self.append(self.defaultVal)
super(DynamicArray, self).insert(ind, val)
def set(self, ind, val):
self[ind] = val
def __setitem__(self, ind, val):
if (ind >= len(self)):
for i in xrange(len(self), ind + 1):
self.append(self.defaultVal)
super(DynamicArray, self).__setitem__(ind, val)
if __name__ == "__main__":
a = DynamicArray()
assert(len(a) == 0)
a[3] = 2
assert(a[3] == 2)
assert(a[0] is None and a[1] is None and a[2] is None)
assert(len(a) == 4)
a[1] = 1
assert(a[1] == 1)
assert(a[3] == 2)
assert(a[0] is None and a[2] is None)
assert(len(a) == 4)
a[5] = 7
assert(a[5] == 7)
assert(a[3] == 2)
assert(a[1] == 1)
assert(a[0] is None and a[2] is None)
assert(len(a) == 6)
</code></pre>
| 1 | 2016-07-21T02:34:24Z | [
"python"
] |
How to visualize the cluster result as a graph with different node color based on its cluster? | 38,493,875 | <p>i have a geodesic distance of graph data in .csv format</p>
<p><img src="http://i.stack.imgur.com/CVu4B.png" alt="data.csv"></p>
<p>i want to reduce it into 2D using Multidimensional Scaling (MDS) and cluster it using Kmedoids</p>
<p>This is my code:</p>
<pre><code># coding: utf-8
import numpy as np
import csv
from sklearn import manifold
from sklearn.metrics.pairwise import pairwise_distances
import kmedoidss
rawdata = csv.reader(open('data.csv', 'r').readlines()[1:])
# Process the data into a 2D array, omitting the header row
data, labels = [], []
for row in rawdata:
labels.append(row[1])
data.append([int(i) for i in row[1:]])
#print data
# Now run very basic MDS
# Documentation here: http://scikit-learn.org/dev/modules/generated/sklearn.manifold.MDS.html#sklearn.manifold.MDS
mds = manifold.MDS(n_components=2, dissimilarity="precomputed")
pos = mds.fit_transform(data)
# distance matrix
D = pairwise_distances(pos, metric='euclidean')
# split into c clusters
M, C = kmedoidss.kMedoids(D, 3)
print ('Data awal : ')
for index, point_idx in enumerate(pos, 1):
print(index, point_idx)
print ('\n medoids:' )
for point_idx in M:
print('{} index ke - {} '.format (pos[point_idx], point_idx+1))
print('')
print('clustering result:')
for label in C:
for point_idx in C[label]:
print('cluster- {}:{} index- {}'.format(label, pos[point_idx], point_idx+1))
</code></pre>
<p>kmedoidss.py</p>
<pre><code>import numpy as np
import random
def kMedoids(D, k, tmax=100):
# determine dimensions of distance matrix D
m, n = D.shape
# randomly initialize an array of k medoid indices
M = np.sort(np.random.choice(n, k))
# create a copy of the array of medoid indices
Mnew = np.copy(M)
# initialize a dictionary to represent clusters
C = {}
for t in xrange(tmax):
# determine clusters, i. e. arrays of data indices
J = np.argmin(D[:,M], axis=1)
for kappa in range(k):
C[kappa] = np.where(J==kappa)[0]
# update cluster medoids
for kappa in range(k):
J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
j = np.argmin(J)
Mnew[kappa] = C[kappa][j]
np.sort(Mnew)
# check for convergence
if np.array_equal(M, Mnew):
break
M = np.copy(Mnew)
else:
# final update of cluster memberships
J = np.argmin(D[:,M], axis=1)
for kappa in range(k):
C[kappa] = np.where(J==kappa)[0]
# return results
return M, C
</code></pre>
<p>how to visualize the cluster result as a graph with different node color based on its cluster? </p>
| -1 | 2016-07-21T02:25:16Z | 38,498,902 | <p>You don't need MDS to run kMedoids - just run it on the original distance matrix (kMedoids can also be made to work on a similarity matrix by switching min for max).</p>
<p>Use MDS only for plotting.</p>
<p>The usual approach for visualization is to use a loop over clusters, and plot each cluster in a different color; or to use a color predicate. There are many examples in the scipy documentation.</p>
<p><a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html</a></p>
<blockquote>
<pre><code>colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk'])
colors = np.hstack([colors] * 20)
y_pred = labels.astype(np.int)
plt.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), s=10)
</code></pre>
</blockquote>
<p>where <code>X</code> is your <code>pos</code> variable (2d mds result) and <code>labels</code> are an integer cluster number for every point. Since you don't have your data in thid "labels" layout, consider using a loop instead:</p>
<pre><code>for label, pts in C.items():
plt.scatter(pos[pts, 0], pos[pts, 1], color=colors[label])
plt.show()
</code></pre>
| 0 | 2016-07-21T08:26:46Z | [
"python",
"csv",
"graph",
"cluster-analysis",
"networkx"
] |
Python combine 2 lists of strings for CSV | 38,493,886 | <p>I have two lists that I want to combine for csv output:</p>
<pre><code>alist = ['a', 'b', 'c']
blist = ['d', 'e', 'f']
</code></pre>
<p>However, I want the output for the csv to format like this:</p>
<pre><code>clist = ['a', 'b', 'c', 'd e f']
</code></pre>
<p>such that the last entry extended of the list contains the list of "blist", but will not be comma separated. Unfortunately, what I have been trying instead gives me:</p>
<pre><code>clist = ['a', 'b', 'c', 'def']
</code></pre>
| 0 | 2016-07-21T02:26:37Z | 38,493,926 | <p>Is this what you are after?</p>
<pre><code> clist = alist + [" ".join(blist)]
</code></pre>
<p>otherwise I think what you are after doesn't make sense, or you need to explain better what you want... Given python syntax, <code>'x' 'y' 'z'</code> <strong>is</strong> <code>'xyz'</code>.</p>
| 0 | 2016-07-21T02:32:37Z | [
"python",
"csv"
] |
How to remove the quote and bracket from list value | 38,493,899 | <p>I have a function to return a list of values, referenced by result:</p>
<pre><code>def populate(*args):
i=1
result = []
for arg in args:
arg = str(cols[i].get_text())
i+=1
result.append(arg)
return result
</code></pre>
<p>And I want to assign the values from result to different variables:</p>
<pre><code>a, b, c = populate(result)
</code></pre>
<p>Supposing <code>result = ['LINZ','WLG Cisco BYOL 2','32']</code></p>
<p>However I got the following output for a,b,c:</p>
<pre><code>**LINZ**
**['WLG Cisco BYOL 2']**
**32**
</code></pre>
<p>How to remove <code>[' ']</code> and assign it as a string?</p>
<p>Many thanks for your help!</p>
| 1 | 2016-07-21T02:28:20Z | 38,494,061 | <p>If you just want to convert each item in the list to string, then you could make it more simpler:</p>
<pre><code>In [12]: a, b, c= [str(item) for item in result]
In [13]: a, b, c
Out[13]: ('LINZ', 'WLG Cisco BYOL 2', '32')
In [14]: a
Out[14]: 'LINZ'
In [15]: b
Out[15]: 'WLG Cisco BYOL 2'
In [16]: c
Out[16]: '32'
</code></pre>
<p>The function might look like this (minimally modifying your code:</p>
<pre><code>def populate(*args):
result = []
for arg in args:
arg = str(arg)
result.append(arg)
return result
</code></pre>
<p>which is just equivalent to:</p>
<pre><code>[str(item) for item in result]
</code></pre>
| 1 | 2016-07-21T02:49:09Z | [
"python",
"string",
"list"
] |
Pygame keeps crashing when I open it | 38,493,997 | <p>I've have this dodging aliens game and it's not working. I can get the front begin screen to open but then when I hit enter to start it crashes and freezes. I've tried running it from python.exe instead of just IDLE but in that case it just pops up then closes right down. A few errors popped up the first few times I tried to run it but now there are no errors indicating what might be wrong. It just stops responding. What am I doing wrong here?</p>
<pre><code>import pygame, random, sys
from pygame.locals import *
def startGame():
if event.type == K_ENTER:
if event.key == K_ESCAPE:
sys.exit()
return
def playerCollision():
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont(None, 55)
playerImage = pygame.image.load('')
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('')
drawText('Dodge the Aliens!', font, screen, (750 / 3), (750 / 3))
drawText('Press ENTER to start.', font, screen, (750 / 3) - 45, (750 / 3) + 65)
pygame.display.update()
topScore = 0
while True:
aliens = []
score = 0
playerRect.topleft = (750 /2, 750 - 50)
alienAdd = 0
while True:
score += 1
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: x -=3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_ESCAPE]: sys.exit()
alienAdd += 1
if alienAdd == addedaliens:
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a)
screen.fill(0,0,0)
drawText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.update()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
drawText('Game Over!', font, screen, (750 / 3), ( 750 / 3))
drawText('Press ENTER To Play Again.', font, screen, ( 750 / 3) - 80, (750 / 3) + 50)
pygame.display.update()
startGame()
</code></pre>
<p>Here's my new code after modifying it some
import pygame, random, sys
from pygame.locals import*
alienimg = pygame.image.load('C:\Python27\alien.png')
playerimg = pygame.image.load('C:\Python27\spaceship.png')</p>
<pre><code>def playerCollision(): # a function for when the player hits an alien
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
def screenText(text, font, screen, x, y): #text display function
textobj = font.render(text, 1, (255, 255, 255))
textrect = textobj.get_rect()
textrect.topleft = (x,y)
screen.blit(textobj, textrect)
def main(): #this is the main function that starts the game
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont("monospace", 55)
pressed = pygame.key.get_pressed()
aliens = []
score = 0
alienAdd = 0
addedaliens = 0
while True: #our while loop that actually runs the game
for event in pygame.event.get(): #key controls
if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit()
elif event.type == KEYDOWN and event.key == pygame.K_LEFT:
playerRect.x -= 3
elif event.type == KEYDOWN and event.key == pygame.K_RIGHT:
playerRect.x += 3
playerImage = pygame.image.load('C:\\Python27\\spaceship.png').convert() # the player images
playerRect = playerImage.get_rect()
playerRect.topleft = (750 /2, 750 - 50)
alienImage = pygame.image.load('C:\\Python27\\alien.png').convert() #alien images
alienAdd += 1
pygame.display.update()
if alienAdd == addedaliens: # randomly adding aliens of different sizes and speeds
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a) #removes the aliens when they get to the bottom of the screen
screen.blit(screen, (0,0))
screenText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.flip()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
screenText('Game Over!', font, screen, (750 / 6), ( 750 / 6))
screenText('Press ENTER To Play Again.', font, screen, ( 750 / 6) - 80, (750 / 6) + 50)
pygame.display.update()
main()
</code></pre>
| -3 | 2016-07-21T02:42:18Z | 38,499,725 | <p>I still see several issues with your code and I think you're trying to do too much at once for the very beginning. Try to keep it as simple as possible. Try creating a display and draw some image:</p>
<pre><code>import pygame
pygame.init()
display = pygame.display.set_mode((750, 750))
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
display.blit(img, (0, 0))
pygame.display.flip()
</code></pre>
<p>You'll have to adjust the img path of course. Running this you should either get an explicit Error (which you should then post in another thread) or see your img on the screen. BUT the program will not respond as there's no event handling and no main loop at all.</p>
<p>To avoid this, you could introduce a main loop like:</p>
<pre><code>import sys
import pygame
pygame.init()
RESOLUTION = (750, 750)
FPS = 60
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
</code></pre>
<p>This should result in a program that displays the same img over and over, and it can be quit properly using the mouse. But still it's like a script, and if someone imported this, it would execute immediately, which is not what we want. So let's fix that as well and wrap it all up in a main function like this:</p>
<pre><code>import sys
import pygame
#defining some constants
RESOLUTION = (750, 750)
FPS = 60
def main(): # <--- program starts here
# setting things up
pygame.init()
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
if __name__ == "__main__":
main()
</code></pre>
<p>The 'if <strong>name</strong> == "<strong>main</strong>":' ensures that the program does not execute when it's imported.</p>
<p>I hope this helps. And remember: Don't try too much all at once. Take small steps, one after another, and try to keep the control over your program. If needed, you can even put a print statement after every single line of code to exactly let you know what your program does and in what order.</p>
| 0 | 2016-07-21T09:06:05Z | [
"python",
"crash",
"pygame"
] |
Python - safely close socket connection on terminal from keyboard input besides cntrl-c? | 38,494,003 | <p>The server I'm communicating to has stream session slots and sometimes the stream session couldnât opened because all stream session slots are used. I suspect its because I'm building a program that talks to the server and feel when I cntrl-c to force stop the stream it doesn't close safely keeping the stream session slot open for that instance connection on the server. So when I terminate the program dozens of times this error builds up</p>
<p>I don't have much knowledge on Python Networking to know if cntrl-c is as clean as hitting a key and calling the method close_conn(sock) but I want to try.</p>
<p>Suppose I'm running this on my terminal"</p>
<pre><code> ...
print("Now listening from server for data...\n")
while True:
received = sock.recv(1024)
#pseudo_code
if (user_input == "e") close_conn(sock)
</code></pre>
<p>How can for debugging purposes close the connection safely? </p>
| 0 | 2016-07-21T02:42:58Z | 38,494,150 | <p>After re-reading your question I think I answered some other question. Sorry.</p>
<p>I don't know whether you identified root of problem correctly, but you can put your code in <code>try...except...finally...</code> structure. You can omit <code>except</code> or <code>finally</code>, if you don't need one of them.</p>
<p>for example:</p>
<pre><code>from time import sleep
try:
sleep(10)
except KeyboardInterrupt:
print "This line is printed only if Ctrl+C was pressed"
finally:
print "This line is printed even if Ctrl+C was pressed"
</code></pre>
| 0 | 2016-07-21T02:59:47Z | [
"python",
"sockets",
"python-sockets"
] |
Python - safely close socket connection on terminal from keyboard input besides cntrl-c? | 38,494,003 | <p>The server I'm communicating to has stream session slots and sometimes the stream session couldnât opened because all stream session slots are used. I suspect its because I'm building a program that talks to the server and feel when I cntrl-c to force stop the stream it doesn't close safely keeping the stream session slot open for that instance connection on the server. So when I terminate the program dozens of times this error builds up</p>
<p>I don't have much knowledge on Python Networking to know if cntrl-c is as clean as hitting a key and calling the method close_conn(sock) but I want to try.</p>
<p>Suppose I'm running this on my terminal"</p>
<pre><code> ...
print("Now listening from server for data...\n")
while True:
received = sock.recv(1024)
#pseudo_code
if (user_input == "e") close_conn(sock)
</code></pre>
<p>How can for debugging purposes close the connection safely? </p>
| 0 | 2016-07-21T02:42:58Z | 38,494,447 | <p>If you want to close your socket when you press "Ctrl + C" and then wait for another connection, you can try the code below.</p>
<pre><code>while True:
try:
received = sock.recv(1024)
except KeyboardInterrupt:
print "i want to close client socket"
sock.close()
break
except socket.error, e:
print "a socket erro has occured, e = ", e
break
</code></pre>
| 0 | 2016-07-21T03:34:24Z | [
"python",
"sockets",
"python-sockets"
] |
ImportError : cannot import name unwrap | 38,494,014 | <p>I have been trying to run my codes :
(neaweather.py)</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib3
r = requests.get('http://www.nea.gov.sg/api/WebAPI/?
dataset=2hr_nowcast&keyref=<keyrefno>')
soup = BeautifulSoup(r.content, "xml")
soup.find('validTime').string
</code></pre>
<p>However, when I run the codes, this is the error I got :</p>
<p><a href="http://i.stack.imgur.com/P7usq.png" rel="nofollow">Error on CMD</a></p>
<p>I used to have a file called "urllib.py" (located on <strong>C:\scripts</strong> along with the file which im running neaweather.py) which clashes with the python modules however I have deleted the file. I have also deleted the file "urllib.pyc" from C:\scripts as well.</p>
<p>I have also deleted files for python3 which I have installed previously as im using python 2.7.12</p>
<p>I tried googling about this error and I saw a comment saying that .pyc files has something to do with this error. Is this true as I have already deleted the file "urllib.pyc" on C:\scripts</p>
<p>I'm not sure on how to solve this error, anyone?</p>
<p>This is not a duplicate of another similar error as I donot have a file name that clashes with python built in modules anymore as I have deleted it. </p>
<p>Thanks</p>
| 0 | 2016-07-21T02:44:03Z | 38,494,296 | <p>From a Python prompt:</p>
<pre><code>>>> import urllib
>>> print urllib.__file__
</code></pre>
<p>Make sure the file is part of the Python distribution and not your own script.</p>
| 0 | 2016-07-21T03:15:53Z | [
"python",
"python-import",
"importerror"
] |
sqlalchemy building 'sqlalchemy.cprocessors' extension error: [Error 2] | 38,494,235 | <p>I need install Python sqlalchemy for windows. But the system can not find the file sqlalchemy.cprocessors' extension</p>
<p>Thanks!</p>
| -1 | 2016-07-21T03:08:06Z | 38,566,254 | <p>Installing <a href="https://www.microsoft.com/en-us/download/details.aspx?id=44266" rel="nofollow">Microsoft Visual C++ Compiler for Python</a> helped me.</p>
| -2 | 2016-07-25T11:13:24Z | [
"python",
"sqlalchemy"
] |
Converting Dataframe Object into Date Python | 38,494,246 | <p>A python dataframe 'dff' containing data imported from SAS is having a date field whose type is showing as below by python:</p>
<pre><code>dff.effvdate.head()
Out[47]:
0 b'09JUL2013'
1 b'17OCT2013'
2 b'03MAR2014'
3 b'08MAY2014'
4 b'10MAR2015'
Name: effvdate, dtype: object
</code></pre>
<p>I am trying to convert this date to datetype as below:</p>
<pre><code>dff['REPORT_MONTH'] =[dt.datetime.strptime(d,"%d%b%Y").date() for d in dff['effvdate']]
</code></pre>
<p>showing this error</p>
<pre><code>TypeError: strptime() argument 1 must be str, not bytes
</code></pre>
<p>As i am new to python, need help on this.</p>
| 0 | 2016-07-21T03:09:05Z | 38,494,297 | <p>The error <code>TypeError: strptime() argument 1 must be str, not bytes</code> gives you the information you need to know! <code>d</code> is in bytes, not a string. you should cast d to string. </p>
<pre><code>dff['REPORT_MONTH'] =[dt.datetime.strptime(d.decode('UTF-8'),"%d%b%Y").date() for d in dff['effvdate']]
</code></pre>
<p>should work.</p>
<p>see <a href="http://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal">What does the 'b' character do in front of a string literal?</a></p>
| 0 | 2016-07-21T03:15:54Z | [
"python",
"date",
"object",
"dataframe",
"casting"
] |
How to find all the messages in a python protobuff | 38,494,286 | <p>I have a python google-protobuff, now I wanna find all the messages in this protobuff file.</p>
| -1 | 2016-07-21T03:14:50Z | 38,494,355 | <p>This is a bit crude, but:</p>
<pre><code>>>> import protobufmodule
>>> from google.protobuf.message import Message
>>> messageClasses = [v for v in vars(protobufmodule).values() if isinstance(v, type) and issubclass(v, Message)]
</code></pre>
| 1 | 2016-07-21T03:23:26Z | [
"python",
"google-protobuf"
] |
Flatten/ravel/collapse 3-dimensional xr.DataArray (Xarray) into 2 dimensions along an axis? | 38,494,300 | <p>I have a dataset where I'm storing replicates for different classes/subtypes (not sure what to call it) and then attributes for each one. Essentially, there are 5 subtype/classes, 4 replicates for each subtype/class, and 100 attributes that are measured. </p>
<p><strong>Is there a method like <code>np.ravel</code> or <code>np.flatten</code> that can merge 2 dimensions using <code>Xarray</code>?</strong> </p>
<p>In this, I want to merge dims <code>subtype</code> and <code>replicates</code> so I have a 2D array (or <code>pd.DataFrame</code> with <code>attributes vs. subtype/replicates</code>. </p>
<p>It wouldn't need to have the format "coord_1 | coord_2" or anything. It would be useful if it kept the original coord names. Maybe there's something like <code>groupby</code> that could do this? <code>Groupby</code> always confuses me so if it's something native to <code>xarray</code> that would be awesome. </p>
<pre><code>import xarray as xr
import numpy as np
# Set up xr.DataArray
dims = (5,4,100)
DA_data = xr.DataArray(np.random.random(dims), dims=["subtype","replicates","attributes"])
DA_data.coords["subtype"] = ["subtype_%d"%_ for _ in range(dims[0])]
DA_data.coords["replicates"] = ["rep_%d"%_ for _ in range(dims[1])]
DA_data.coords["attributes"] = ["attr_%d"%_ for _ in range(dims[2])]
# DA_data.coords
# Coordinates:
# * subtype (subtype) <U9 'subtype_0' 'subtype_1' 'subtype_2' ...
# * replicates (replicates) <U5 'rep_0' 'rep_1' 'rep_2' 'rep_3'
# * attributes (attributes) <U7 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
# DA_data.dims
# ('subtype', 'replicates', 'attributes')
# Naive way to collapse the replicate dimension into the subtype dimension
desired_columns = list()
for subtype in DA_data.coords["subtype"]:
for replicate in DA_data.coords["replicates"]:
desired_columns.append(str(subtype.values) + "|" + str(replicate.values))
desired_columns
# ['subtype_0|rep_0',
# 'subtype_0|rep_1',
# 'subtype_0|rep_2',
# 'subtype_0|rep_3',
# 'subtype_1|rep_0',
# 'subtype_1|rep_1',
# 'subtype_1|rep_2',
# 'subtype_1|rep_3',
# 'subtype_2|rep_0',
# 'subtype_2|rep_1',
# 'subtype_2|rep_2',
# 'subtype_2|rep_3',
# 'subtype_3|rep_0',
# 'subtype_3|rep_1',
# 'subtype_3|rep_2',
# 'subtype_3|rep_3',
# 'subtype_4|rep_0',
# 'subtype_4|rep_1',
# 'subtype_4|rep_2',
# 'subtype_4|rep_3']
</code></pre>
| 3 | 2016-07-21T03:15:57Z | 38,495,149 | <p>Yes, this is exactly what the <code>.stack</code> is for:</p>
<pre><code>In [33]: stacked = DA_data.stack(desired=['subtype', 'replicates'])
In [34]: stacked
Out[34]:
<xarray.DataArray (attributes: 100, desired: 20)>
array([[ 0.54020268, 0.14914837, 0.83398895, ..., 0.25986503,
0.62520466, 0.08617668],
[ 0.47021735, 0.10627027, 0.66666478, ..., 0.84392176,
0.64461418, 0.4444864 ],
[ 0.4065543 , 0.59817851, 0.65033094, ..., 0.01747058,
0.94414244, 0.31467342],
...,
[ 0.23724934, 0.61742922, 0.97563316, ..., 0.62966631,
0.89513904, 0.20139552],
[ 0.21157447, 0.43868899, 0.77488211, ..., 0.98285015,
0.24367352, 0.8061804 ],
[ 0.21518079, 0.234854 , 0.18294781, ..., 0.64679141,
0.49678393, 0.32215219]])
Coordinates:
* attributes (attributes) |S7 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
* desired (desired) object ('subtype_0', 'rep_0') ...
</code></pre>
<p>The resulting stacked coordinate is a <code>pandas.MultiIndex</code>, whose values are given by tuples:</p>
<pre><code>In [35]: stacked['desired'].values
Out[35]:
array([('subtype_0', 'rep_0'), ('subtype_0', 'rep_1'),
('subtype_0', 'rep_2'), ('subtype_0', 'rep_3'),
('subtype_1', 'rep_0'), ('subtype_1', 'rep_1'),
('subtype_1', 'rep_2'), ('subtype_1', 'rep_3'),
('subtype_2', 'rep_0'), ('subtype_2', 'rep_1'),
('subtype_2', 'rep_2'), ('subtype_2', 'rep_3'),
('subtype_3', 'rep_0'), ('subtype_3', 'rep_1'),
('subtype_3', 'rep_2'), ('subtype_3', 'rep_3'),
('subtype_4', 'rep_0'), ('subtype_4', 'rep_1'),
('subtype_4', 'rep_2'), ('subtype_4', 'rep_3')], dtype=object)
</code></pre>
| 2 | 2016-07-21T04:54:09Z | [
"python",
"arrays",
"pandas",
"multidimensional-array",
"python-xarray"
] |
import from parent directory in script which lies in sub directory | 38,494,342 | <p>Here's my directory structure:</p>
<pre><code>my_package
|
+--__init__.py
|
+--setup.py
|
+--module.py
|
+--sub_package
|
+--__init__.py
|
+--script.py
</code></pre>
<p>The script <code>script.py</code> needs to import a function from <code>module.py</code>, and I need to be able to run <code>script.py</code> using the Python interpreter.</p>
<p>I know that Guido calls this an "anti-pattern". And I know you have 10 reasons why I shouldn't do this. I probably agree with most of them - really, I do. I wouldn't be asking this question if I could avoid this. So can we just skip the part where we go over why this is bad and move on to the solution? Thanks!</p>
<p>I also know that there are about a 1000 other SO questions about this. I've probably read them all by now. Most of them were made obsolete by changes to Python's import system, and the rest just aren't right.</p>
<p>What I have tried:</p>
<ul>
<li>Using <code>from .module import my_function</code> in <code>script.py</code> and then either running <code>python script.py</code> inside the directory <code>sub_package</code> or <code>python sub_package/script.py</code> inside the directory <code>my_package</code>. Either way, I get the error:</li>
</ul>
<p><code>SystemError: Parent module '' not loaded, cannot perform relative import</code></p>
<ul>
<li>Using <code>from module import my_function</code> or <code>from my_package.module import my_function</code> and running <code>script.py</code> as above (either from <code>sub_package</code> or <code>my_package</code>). I get:</li>
</ul>
<p><code>ImportError: No module named 'module'</code></p>
<p>(or similarly with <code>my_package</code> instead of <code>module</code>)</p>
<ul>
<li>Running <code>python -m sub_package/script</code> from the directory <code>my_package</code> or <code>python -m my_package/sub_package/script</code> from the parent directory of <code>my_package</code>. I get:</li>
</ul>
<p><code>No module named sub_package/script</code></p>
<p>(or similarly with <code>my_package/sub_package/script</code>)</p>
<p>Is there anything else I should be trying? I would <em>really</em> rather avoid messing with <code>sys.path</code> or <code>PYTHONPATH</code> for a whole host of reasons. </p>
| 0 | 2016-07-21T03:21:44Z | 38,494,433 | <p>I believe you can just say</p>
<pre><code>import module
</code></pre>
<p>from within <code>script.py</code> if you do the following:</p>
<p>from your terminal in the mypackage directory run:</p>
<pre><code>$ python setup.py install
</code></pre>
<p>This will allow you to make the import statement that you want. The one issue that I have found with this method is that you will have to call</p>
<pre><code>$ python setup.py install
</code></pre>
<p>every time you make a change to <code>module.py</code> but if you are ok with that this method should work</p>
| 0 | 2016-07-21T03:32:08Z | [
"python",
"python-3.x",
"python-import"
] |
import from parent directory in script which lies in sub directory | 38,494,342 | <p>Here's my directory structure:</p>
<pre><code>my_package
|
+--__init__.py
|
+--setup.py
|
+--module.py
|
+--sub_package
|
+--__init__.py
|
+--script.py
</code></pre>
<p>The script <code>script.py</code> needs to import a function from <code>module.py</code>, and I need to be able to run <code>script.py</code> using the Python interpreter.</p>
<p>I know that Guido calls this an "anti-pattern". And I know you have 10 reasons why I shouldn't do this. I probably agree with most of them - really, I do. I wouldn't be asking this question if I could avoid this. So can we just skip the part where we go over why this is bad and move on to the solution? Thanks!</p>
<p>I also know that there are about a 1000 other SO questions about this. I've probably read them all by now. Most of them were made obsolete by changes to Python's import system, and the rest just aren't right.</p>
<p>What I have tried:</p>
<ul>
<li>Using <code>from .module import my_function</code> in <code>script.py</code> and then either running <code>python script.py</code> inside the directory <code>sub_package</code> or <code>python sub_package/script.py</code> inside the directory <code>my_package</code>. Either way, I get the error:</li>
</ul>
<p><code>SystemError: Parent module '' not loaded, cannot perform relative import</code></p>
<ul>
<li>Using <code>from module import my_function</code> or <code>from my_package.module import my_function</code> and running <code>script.py</code> as above (either from <code>sub_package</code> or <code>my_package</code>). I get:</li>
</ul>
<p><code>ImportError: No module named 'module'</code></p>
<p>(or similarly with <code>my_package</code> instead of <code>module</code>)</p>
<ul>
<li>Running <code>python -m sub_package/script</code> from the directory <code>my_package</code> or <code>python -m my_package/sub_package/script</code> from the parent directory of <code>my_package</code>. I get:</li>
</ul>
<p><code>No module named sub_package/script</code></p>
<p>(or similarly with <code>my_package/sub_package/script</code>)</p>
<p>Is there anything else I should be trying? I would <em>really</em> rather avoid messing with <code>sys.path</code> or <code>PYTHONPATH</code> for a whole host of reasons. </p>
| 0 | 2016-07-21T03:21:44Z | 38,494,985 | <p>In fact, python interpreter will find module in sys.path.It means if you add your module's directory in this example "somepath/my_package" to sys.path, python will find it by "import module".</p>
<p>So how to achieve this goal?</p>
<p>If your directory absolute path never change, you can do this below:</p>
<pre><code>sys.path.append(yourAbsPath)
</code></pre>
<p>But sometimes the path of directory might change, but the relative path will not change.So i recommend to follow this, try to add it to the beginning of your script.py:</p>
<pre><code>import sys
import os
my_packagePath = os.path.dirname(os.path.dirname(__file__))
sys.path.append(my_packagePath)
import module
#from module import yourFunction #replace yourFunction with your real function
</code></pre>
<p>In the cmd tool, just type "python yourScript.py's abspath".</p>
| 0 | 2016-07-21T04:38:51Z | [
"python",
"python-3.x",
"python-import"
] |
How to use the while loop to get the factorial of an integer without getting endless factorials back? | 38,494,434 | <p>I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!</p>
<p>Update: I realized that I should use "while" for what num isn't, so I now have this code below, but it still says invalid syntax for the second "while".</p>
<pre><code># take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
</code></pre>
| 0 | 2016-07-21T03:32:20Z | 38,494,498 | <p>you have missed the braces at the end of <code>int()</code> funtion</p>
<pre><code># take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")) # brace was missing
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")) # brace was missing
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
</code></pre>
<p>You might have meant like the below in order to loop until you get correct input:</p>
<pre><code># take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
while(True):
if num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")) # brace was missing
continue
if num > 15:
num = int(input("Please enter a number between 1 and 15! ")) # brace was missing
continue
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
break
</code></pre>
| 0 | 2016-07-21T03:42:32Z | [
"python",
"while-loop"
] |
How to use the while loop to get the factorial of an integer without getting endless factorials back? | 38,494,434 | <p>I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!</p>
<p>Update: I realized that I should use "while" for what num isn't, so I now have this code below, but it still says invalid syntax for the second "while".</p>
<pre><code># take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
</code></pre>
| 0 | 2016-07-21T03:32:20Z | 38,494,502 | <p>You missed a closing parenthesis:</p>
<pre><code>while num > 15:
num = int(input("Please enter a number between 1 and 15! "))
^ here
</code></pre>
| 0 | 2016-07-21T03:42:50Z | [
"python",
"while-loop"
] |
How to use the while loop to get the factorial of an integer without getting endless factorials back? | 38,494,434 | <p>I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!</p>
<p>Update: I realized that I should use "while" for what num isn't, so I now have this code below, but it still says invalid syntax for the second "while".</p>
<pre><code># take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
</code></pre>
| 0 | 2016-07-21T03:32:20Z | 38,495,390 | <p>I would do this:</p>
<pre><code>from math import factorial as factorial
while True:
num = int(input("Please enter a number from 1 to 15: "))
if 1 <= num <= 15:
fact = factorial(num)
print 'the factorial of {n} is {f}'.format(n=num, f=fact)
else:
num = int(input("Please enter a number from 1 to 15: "))
</code></pre>
| 2 | 2016-07-21T05:17:04Z | [
"python",
"while-loop"
] |
How to scrape data generated with infinite scroll? | 38,494,563 | <p>How to scrape the list of product from <a href="https://www.amazon.cn/gp/pdp/profile/A34PAP6LGJIN6N/ref=cm_cr_arp_d_pdp?ie=UTF8" rel="nofollow">this page</a> with scrapy?</p>
<p>I have tried the ajax request url the browser sends:</p>
<pre><code>https://www.amazon.cn/gp/profile/A34PAP6LGJIN6N/more?next_batch_params%5Breview_offset%5D=10&_=1469081762384
</code></pre>
<p>but it returns <code>404</code>.</p>
| 0 | 2016-07-21T03:50:10Z | 38,495,644 | <p>You need to replicate the headers you see in the request.</p>
<p>If you inspect the response headers you can see:
<a href="http://i.stack.imgur.com/upI1P.png" rel="nofollow"><img src="http://i.stack.imgur.com/upI1P.png" alt="amazon.ca next page headers"></a></p>
<p>from this you need to update your <code>scrapy.Request.headers</code> attribute. With few of these values. For the most part you can skip the Cookie since scrapy manages this one by itself and usually for ajax requests like this it's meaningless.</p>
<p>For this case I've manage to get a successful response by replicating only <code>X-Requested-With</code> header. This header is used to indicate that ajax request is happening. </p>
<p>You can actually test out and engineer this real time:</p>
<pre><code>scrapy shell <url>
# gives you 403
request.headers.update({'X-Requested-With': 'XMLHttpRequest'})
request.headers.update({'User-Agent': <some user agent>})
fetch(request)
# now the request is redownloaded and it's 200!
</code></pre>
| 1 | 2016-07-21T05:36:21Z | [
"python",
"scrapy"
] |
CSS style my django table | 38,494,603 | <p><a href="http://i.stack.imgur.com/fDCxv.png" rel="nofollow">picture of my table</a></p>
<p>i rendered my table with django table2 and above link how it looks like</p>
<p>i style it with css like this</p>
<pre><code>thead {
background-color: #4CAF50;
font-color: white;
}
</code></pre>
<p>It looks like the background-color works and it shows green
However the font-color did not turn white. Strangely it is purple/blue. any idea why?</p>
<p>thanks in advance!</p>
| 0 | 2016-07-21T03:54:01Z | 38,495,400 | <p>They are hyperlinks (<code>a</code> tag) for which the browser has <strong>default</strong> colors.
You can set the color of hyperlinks like that:</p>
<p><strong>For unvisited links</strong></p>
<pre><code>a:link {
color: red;
}
</code></pre>
<p><strong>Visited links</strong></p>
<pre><code>a:visited {
color: green;
}
</code></pre>
<p><strong>Hover over links</strong></p>
<pre><code>a:hover {
color: hotpink;
}
</code></pre>
<p><strong>Selected links</strong></p>
<pre><code>a:active {
color: blue;
}
</code></pre>
<p>Or if you want for all the same color:</p>
<pre><code>a {
color:white;
}
</code></pre>
<p>If you also want to get rid of the underlines you can set the <code>text-decoration</code> property to <code>none</code>:</p>
<pre><code>text-decoration:none;
</code></pre>
| 0 | 2016-07-21T05:17:52Z | [
"python",
"css",
"django",
"table"
] |
Why is pip still not recognized even though it is on my path? | 38,494,617 | <p>I ran the <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">get-pip</a> python file, and it told me that </p>
<blockquote>
<p>Requirement already up-to-date: pip in c:\python27\lib\site-packages</p>
</blockquote>
<p>So, I added that to my path. However, whenever I try to run a <code>pip</code> command, I get the error:</p>
<blockquote>
<p>'pip' is not recognized as an internal or external command, operable program or batch file.</p>
</blockquote>
<p>Here is what happens when I <code>echo</code> my path:</p>
<pre><code>echo %Path%
C:\Program Files\Docker\Docker\Resources\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Windows\CCM;C:\Program Files\OpenVPN\bin;C:\Program Files\Git\cmd;C:\Program Files\Git\mingw64\bin;C:\Program Files\Java\jdk1.8.0_74\bin;C:\Program Files (x86)\Skype\Phone\;C:\Program Files (x86)\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Windows Live\Shared;C:\Python27;C:\Users\cstaheli\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Python27\Lib\site-packages;C:\Users\cstaheli\AppData\Roaming\npm;C:\Program Files\Docker Toolbox;C:\Python27\Lib\site-packages
</code></pre>
<p>As you can see, the last one is <code>C:\Python27\Lib\site-packages</code>. So, I can't figure out why it is still not recognized by Windows.</p>
<p>Let me know if you need more information to solve this issue.</p>
| 1 | 2016-07-21T03:56:18Z | 38,494,663 | <p>This says that module <code>pip</code> installed:</p>
<blockquote>
<p>Requirement already up-to-date: pip in c:\python27\lib\site-packages</p>
</blockquote>
<p>This says that there is no command <code>pip</code> in <code>path</code> (<code>pip.exe</code> is in <code>C:\Python27\Scripts</code>):</p>
<blockquote>
<p>'pip' is not recognized as an internal or external command, operable program or batch file.</p>
</blockquote>
<p>You can run <code>python -m pip</code> or add <code>C:\Python27\Scripts</code> to <code>path</code>.</p>
| 2 | 2016-07-21T04:02:13Z | [
"python",
"pip"
] |
How to generate all possible combinations of two coins with three possibilities (up, down and In between) | 38,494,634 | <p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p>
<pre><code> 00
01
10
11
</code></pre>
<p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p>
<p>Here is the code to print the previous combinations:</p>
<pre><code> for n=1:2^2
r(n) = dec2bin(n);
end
</code></pre>
<p>What I want to do is to print all the possible combinations for the same two coins but with three different possibilities (head(up), tail(down) and in between (not up or down))
To give something like:</p>
<pre><code>00
01
10
11
0B
B0
B1
1B
BB
</code></pre>
<p>Where, <code>B</code> means one of the two coins is In between (not up or down)</p>
<p>Any Ideas?</p>
| 3 | 2016-07-21T03:58:39Z | 38,494,673 | <p>Python solution:</p>
<pre><code>from itertools import product
possible_values = '01B'
number_of_coins = 2
for result in product(possible_values, repeat=number_of_coins):
print(''.join(result))
# Output:
# 00
# 01
# 0B
# 10
# 11
# 1B
# B0
# B1
# BB
</code></pre>
| 2 | 2016-07-21T04:03:04Z | [
"c#",
"python",
"c++",
"matlab",
"cartesian-product"
] |
How to generate all possible combinations of two coins with three possibilities (up, down and In between) | 38,494,634 | <p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p>
<pre><code> 00
01
10
11
</code></pre>
<p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p>
<p>Here is the code to print the previous combinations:</p>
<pre><code> for n=1:2^2
r(n) = dec2bin(n);
end
</code></pre>
<p>What I want to do is to print all the possible combinations for the same two coins but with three different possibilities (head(up), tail(down) and in between (not up or down))
To give something like:</p>
<pre><code>00
01
10
11
0B
B0
B1
1B
BB
</code></pre>
<p>Where, <code>B</code> means one of the two coins is In between (not up or down)</p>
<p>Any Ideas?</p>
| 3 | 2016-07-21T03:58:39Z | 38,494,800 | <pre><code>from itertools import product
outcomes = ["".join(item) for item in list(product('01B', repeat=2))]
for outcome in outcomes:
print(outcome)
#reusults:
00
01
0B
10
11
1B
B0
B1
BB
</code></pre>
| 1 | 2016-07-21T04:18:27Z | [
"c#",
"python",
"c++",
"matlab",
"cartesian-product"
] |
How to generate all possible combinations of two coins with three possibilities (up, down and In between) | 38,494,634 | <p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p>
<pre><code> 00
01
10
11
</code></pre>
<p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p>
<p>Here is the code to print the previous combinations:</p>
<pre><code> for n=1:2^2
r(n) = dec2bin(n);
end
</code></pre>
<p>What I want to do is to print all the possible combinations for the same two coins but with three different possibilities (head(up), tail(down) and in between (not up or down))
To give something like:</p>
<pre><code>00
01
10
11
0B
B0
B1
1B
BB
</code></pre>
<p>Where, <code>B</code> means one of the two coins is In between (not up or down)</p>
<p>Any Ideas?</p>
| 3 | 2016-07-21T03:58:39Z | 38,495,490 | <p>Matlab Solution:
<code>n</code> is the amount of possible solutions. In your case 3 different once. <code>k</code> is the amount of sets. In your case 2 coins. <code>p</code>should contain a matrix with the results.</p>
<pre><code>n = 3; k = 2;
nk = nchoosek(1:n,k);
p=zeros(0,k);
for i=1:size(nk,1),
pi = perms(nk(i,:));
p = unique([p; pi],'rows');
end
</code></pre>
<p>For more solutions check: <a href="http://stackoverflow.com/questions/19440595/possible-combinations-order-is-important">Possible combinations - order is important</a></p>
| 1 | 2016-07-21T05:25:03Z | [
"c#",
"python",
"c++",
"matlab",
"cartesian-product"
] |
How to generate all possible combinations of two coins with three possibilities (up, down and In between) | 38,494,634 | <p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p>
<pre><code> 00
01
10
11
</code></pre>
<p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p>
<p>Here is the code to print the previous combinations:</p>
<pre><code> for n=1:2^2
r(n) = dec2bin(n);
end
</code></pre>
<p>What I want to do is to print all the possible combinations for the same two coins but with three different possibilities (head(up), tail(down) and in between (not up or down))
To give something like:</p>
<pre><code>00
01
10
11
0B
B0
B1
1B
BB
</code></pre>
<p>Where, <code>B</code> means one of the two coins is In between (not up or down)</p>
<p>Any Ideas?</p>
| 3 | 2016-07-21T03:58:39Z | 38,497,701 | <p>I found several solutions for MATLAB. (That's not completely mine code, I found some parts and adapt it). Post it because <a href="http://stackoverflow.com/questions/38494634/how-to-generate-all-possible-combinations-of-two-coins-with-three-possibilities/38495490#38495490">@C.Colden' answer</a> is not full.
What you want to achieve is a <a href="https://en.wikipedia.org/wiki/Permutation#Permutations_with_repetition" rel="nofollow">permutations with repetitions</a>. C.Colden shows it without repetitions. So you can go this way:</p>
<p><strong>Solution 1:</strong></p>
<pre><code>a = [1 2 3]
n = length(a)
k = 2
for ii = k:-1:1
temp = repmat(a,n^(k-ii),n^(ii-1));
res(:,ii) = temp(:);
end
</code></pre>
<p>Result:</p>
<pre><code>res =
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
</code></pre>
<p>And interesting <strong>Solution 2</strong> if you need it in string form:</p>
<pre><code>dset={'12b','12b'};
n=numel(dset);
pt=[3:n,1,2];
r=cell(n,1);
[r{1:n}]=ndgrid(dset{:});
r=permute([r{:}],pt);
r=sortrows(reshape(r,[],n));
</code></pre>
<p>Result:</p>
<pre><code>r =
11
12
1b
21
22
2b
b1
b2
bb
</code></pre>
| 1 | 2016-07-21T07:27:32Z | [
"c#",
"python",
"c++",
"matlab",
"cartesian-product"
] |
How to generate all possible combinations of two coins with three possibilities (up, down and In between) | 38,494,634 | <p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p>
<pre><code> 00
01
10
11
</code></pre>
<p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p>
<p>Here is the code to print the previous combinations:</p>
<pre><code> for n=1:2^2
r(n) = dec2bin(n);
end
</code></pre>
<p>What I want to do is to print all the possible combinations for the same two coins but with three different possibilities (head(up), tail(down) and in between (not up or down))
To give something like:</p>
<pre><code>00
01
10
11
0B
B0
B1
1B
BB
</code></pre>
<p>Where, <code>B</code> means one of the two coins is In between (not up or down)</p>
<p>Any Ideas?</p>
| 3 | 2016-07-21T03:58:39Z | 38,508,963 | <p>Granted I am not familiar with the syntax of these other languages, the solutions to them look overly complicated.</p>
<p>It's just a simple doubly-nested <code>for</code> loop:</p>
<p><strong>C++</strong></p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
const char* ch = "01B";
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
cout << ch[i] << ch[j] << '\n';
}
}
</code></pre>
<p>Output:</p>
<pre><code>00
01
0B
10
11
1B
B0
B1
BB
</code></pre>
| 0 | 2016-07-21T15:58:21Z | [
"c#",
"python",
"c++",
"matlab",
"cartesian-product"
] |
pyexcel - get column names and add entire rows together | 38,494,652 | <p>I have a couple of speadsheets:</p>
<pre><code>Sheet 1 sheet2 sheet3
A B C D E F D F G
1 2 3 4 5 6 7 9 8
</code></pre>
<p>I'm using pyexcel to join rows together from spreadsheets 1 and 2, and 1 and 3, so the combined row for 1 and 2 would be:</p>
<pre><code>A B C D E F D F G,
1 2 3 4 5 6
</code></pre>
<p>and 1 and 3:</p>
<pre><code>A B C D E F D F G
1 2 3 7 9 8
</code></pre>
<p>How can this be done in pyexcel?</p>
<p>Right now I have two for loops and this:</p>
<pre><code> if t_row['name'] is not "":
update_sheet[count, 'name'] = t_row['name']
</code></pre>
<p>But sheet 2 does not have F and G columns and sheet 3 does not have E and F. How do I list what columns a sheet has OR just take the whole row and join it with row and store that?</p>
| 0 | 2016-07-21T04:00:35Z | 38,495,764 | <p>It is not clear:</p>
<ol>
<li>How you are reading the worksheet</li>
<li><p>how you want to handle the join when both sheets has values. I assume you want to sum up.</p>
<pre><code>import numpy as np
import pyexcel as pe
a = np.array(pe.get_array(file_name='Sheet1.xlsx'))
b = np.array(pe.get_array(file_name='Sheet2.xlsx'))
c = np.array(pe.get_array(file_name='Sheet3.xlsx'))
all=[a,b,c]
max_cols = max([i.shape[1] for i in all])
for i in range(3):
if all[i].dtype!=np.dtype('int'):
all[i][all[i]=='']=0
all[i]=all[i].astype('int')
if (all[i].shape[1] != max_cols):
all[i]=np.hstack([all[i], [[0]*(max_cols-all[i].shape[1])]*(all[i].shape[0])])
np.sum(np.vstack(all), 0)
</code></pre></li>
</ol>
<h1>EDIT</h1>
<p>Using you will need no for loops (just for looping through different sheets). This will use numpy in a pythonic fashion!</p>
<pre><code>def join_sheets(a, b):
both = [a,b]
max_cols = max([i.number_of_columns() for i in both])
min_rows = min([i.number_of_rows() for i in both])
both_arr = [np.array(i.array) for i in both]
for i in range(2):
both_arr[i] = np.hstack([both_arr[i], [['']*(max_cols - both_arr[i].shape[1])]*(both_arr[i].shape[0])])
both_arr[0][0:min_rows,][both_arr[1][0:min_rows,]!=''] = both_arr[1][0:min_rows,][both_arr[1][0:min_rows,]!='']
if (b.number_of_rows() > min_rows):
both_arr[0] = np.vstack([both_arr[0], both_arr[1][min_rows:,]])
a.array = both_arr[0].tolist()
sheets = pe.get_book(file_name='Sheet1.xlsx')
for i in range(1, sheets.number_of_sheets()): join_sheets(sheets[0], sheets[i])
sheets.save_as(sheets.path + '/' + sheets.filename)
</code></pre>
| 1 | 2016-07-21T05:44:34Z | [
"python",
"python-3.x",
"pyexcel"
] |
Loop through a page of voice samples, downloading each sample and putting the lines into a text file | 38,494,704 | <p><a href="http://theportalwiki.com/wiki/GLaDOS_voice_lines" rel="nofollow">Here</a> is the page I am trying to do this on. It is the voice lines of GLaDOS from Portal. Each line is inner "i" HTML text as well as between quotes as displayed on the page. They each have a direct download link beside them labeled "download". I'm trying to put the voice lines into the MARY TTS voice synthesizer <a href="https://github.com/marytts/marytts/wiki/VoiceImportToolsTutorial" rel="nofollow">here</a> in one of two formats. Either every line in its own text file with the file name matching the name of the wav files, or all in one text file formatted as ( <em>filename</em> "<em>insert line here</em>" ).</p>
<p>I was trying to do this myself but I've already spent 4 hours on it and have gotten only a small piece of Python code that doesn't work.</p>
<pre><code>from bs4 import BeautifulSoup
import re
import urllib.request
soup = BeautifulSoup(urllib.request.urlopen("http://theportalwiki.com/wiki/GLaDOS_voice_lines"), "html.parser")
tags = soup.find_all('i')
f = open('Lines.txt', 'w')
for t in range(len(tags)):
f.write(tags[t] + '\n')
f.close()
</code></pre>
<p>It returns "TypeError: unsupported operand type(s) for +: 'Tag' and 'str'." </p>
<p>I also tried AutoHotKey.</p>
<pre><code>^g::
IEGet(Name="") ;Retrieve pointer to existing IE window/tab
{
IfEqual, Name,, WinGetTitle, Name, ahk_class IEFrame
Name := ( Name="New Tab - Windows Internet Explorer" ) ? "about:Tabs"
: RegExReplace( Name, " - (Windows|Microsoft) Internet Explorer" )
For wb in ComObjCreate( "Shell.Application" ).Windows
If ( wb.LocationName = Name ) && InStr( wb.FullName, "iexplore.exe" )
Return wb
} ;written by Jethrow
wb := IEGet()
IELoad(wb) ;You need to send the IE handle to the function unless you define it as global.
{
If !wb ;If wb is not a valid pointer then quit
Return False
Loop ;Otherwise sleep for .1 seconds untill the page starts loading
Sleep,100
Until (wb.busy)
Loop ;Once it starts loading wait until completes
Sleep,100
Until (!wb.busy)
Loop ;optional check to wait for the page to completely load
Sleep,100
Until (wb.Document.Readystate = "Complete")
Return True
}
For IE in ComObjCreate("Shell.Application").Windows ; for each open window
If InStr(IE.FullName, "iexplore.exe") ; check if it's an ie window
break ; keep that window's handle
; this assumes an ie window is available. it won't work if not
IE.Navigate("http://theportalwiki.com/wiki/GLaDOS_voice_lines")
While IE.Busy
Sleep, 100
Links := IE.Document.Links
Inner := FileOpen("C:\Users\Johnson\Desktop\GLaDOS Voice", "w")
Rows := IE.Document.All.Tags("table")[4].Rows
Loop % Rows.Length
Inner.Write(Row[A_Index].InnerText . "`r`n")
Inner.Close()
Return
</code></pre>
<p>As far as I can tell, the AutoHotKey script does absolutely nothing. I use the hotkey and nothing happens. </p>
<p>I'd prefer Lua because it's consistent and I understand it. </p>
| 0 | 2016-07-21T04:06:52Z | 38,494,759 | <p>Your Python code is very close to working. Minor fix (plus using a context manager for the file) below:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib.request
soup = BeautifulSoup(urllib.request.urlopen("http://theportalwiki.com/wiki/GLaDOS_voice_lines"), "html.parser")
tags = soup.find_all('i')
with open('Lines.txt', 'w') as f:
for t in range(len(tags)):
f.write(tags[t].text.strip('ââ') + '\n')
</code></pre>
<p>Lines.txt:</p>
<pre><code>You just have to look at things objectively, see what you don't need anymore, and trim out the fat.
Portal
Portal 2
Hello and, again, welcome to the Aperture Science computer-aided enrichment center.
...
</code></pre>
<p><strong>EDIT</strong></p>
<p>To answer the question in the comment below, this should get the download links:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib.request
soup = BeautifulSoup(urllib.request.urlopen("http://theportalwiki.com/wiki/GLaDOS_voice_lines"), "html.parser")
tags = soup.find_all('a')
with open('Downloads.txt', 'w') as f:
for tag in tags:
if tag.text == 'Download':
f.write(tag['href'] + '\n')
</code></pre>
<p>Downloads.txt:</p>
<pre><code>http://i1.theportalwiki.net/img/e/e5/GLaDOS_00_part1_entry-1.wav
http://i1.theportalwiki.net/img/d/d7/GLaDOS_00_part1_entry-2.wav
http://i1.theportalwiki.net/img/5/50/GLaDOS_00_part1_entry-3.wav
...
</code></pre>
| 1 | 2016-07-21T04:12:48Z | [
"python",
"html",
"file",
"lua",
"speech-synthesis"
] |
AWS Elastic Beanstalk mod_wsgi "compiled for" version different than "runtime" version | 38,494,722 | <p>I'm seeing the following error when I run my Pyramid application on AWS Elastic Beanstalk.</p>
<pre><code>[Thu Jul 21 03:45:20.629134 2016] [:warn] [pid 5232] mod_wsgi: Compiled for Python/2.7.9.
[Thu Jul 21 03:45:20.629139 2016] [:warn] [pid 5232] mod_wsgi: Runtime using Python/2.7.10.
</code></pre>
<p>Anyone know of a fix?</p>
| 1 | 2016-07-21T04:08:58Z | 38,512,539 | <p>If you compile <em>mod_wsgi</em>, you need to point the configure script to the appropriate Python binary. For example:</p>
<pre><code>wget -q "https://github.com/GrahamDumpleton/mod_wsgi/archive/4.4.21.tar.gz"
tar -xzf '4.4.21.tar.gz'
cd ./mod_wsgi-4.4.21
./configure --with-python=/usr/local/bin/python3.5
make
make install
</code></pre>
<p>Good luck!</p>
| 0 | 2016-07-21T19:10:22Z | [
"python",
"amazon-web-services",
"elastic-beanstalk",
"mod-wsgi"
] |
Listing locations in Azure using Python Azure SDK error | 38,494,727 | <p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine
Below is the error :</p>
<p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p>
<p>Please see my code :</p>
<pre><code>import os
import sys
import logging
from azure import *
from azure.servicemanagement import *
subscription_id = 'XXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXXXX'
certificate_path = '\.pem'
sms = ServiceManagementService(subscription_id, certificate_path)
result = sms.list_subscriptions()
for location in result:
print(location.name)
</code></pre>
<p><img src="http://i.stack.imgur.com/pBoOD.png" alt="enter image description here"></p>
| 0 | 2016-07-21T04:09:12Z | 38,535,024 | <p>Your code is correct. Based on the stacktrace, it's seems your certificate is not valid. This might help you:
<a href="http://azure-sdk-for-python.readthedocs.io/en/latest/servicemanagement.html#creating-and-uploading-new-certificate-with-openssl" rel="nofollow">http://azure-sdk-for-python.readthedocs.io/en/latest/servicemanagement.html#creating-and-uploading-new-certificate-with-openssl</a></p>
<p>It's not directly related to your question, but this method is part of the Service Management library of Azure. Current recommendation is to use the Azure Resource Management library (a.k.a. ARM):</p>
<ul>
<li><p>Install the ARM client for Python:
<a href="http://azure-sdk-for-python.readthedocs.io/en/latest/index.html#installation" rel="nofollow">http://azure-sdk-for-python.readthedocs.io/en/latest/index.html#installation</a></p></li>
<li><p>Create a resource client:
<a href="http://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html" rel="nofollow">http://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html</a></p></li>
<li><p>The list_location method:
<a href="http://azure-sdk-for-python.readthedocs.io/en/latest/ref/azure.mgmt.resource.subscriptions.operations.html#azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations.list_locations" rel="nofollow">http://azure-sdk-for-python.readthedocs.io/en/latest/ref/azure.mgmt.resource.subscriptions.operations.html#azure.mgmt.resource.subscriptions.operations.SubscriptionsOperations.list_locations</a></p></li>
</ul>
| 0 | 2016-07-22T20:49:51Z | [
"python",
"python-2.7",
"azure"
] |
Listing locations in Azure using Python Azure SDK error | 38,494,727 | <p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine
Below is the error :</p>
<p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p>
<p>Please see my code :</p>
<pre><code>import os
import sys
import logging
from azure import *
from azure.servicemanagement import *
subscription_id = 'XXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXXXX'
certificate_path = '\.pem'
sms = ServiceManagementService(subscription_id, certificate_path)
result = sms.list_subscriptions()
for location in result:
print(location.name)
</code></pre>
<p><img src="http://i.stack.imgur.com/pBoOD.png" alt="enter image description here"></p>
| 0 | 2016-07-21T04:09:12Z | 38,553,275 | <p>According to your code & the error information, I think the issue was caused by the value of the <code>certificate_path</code> variable which is not a valid file path. On Windows, the path <code>\</code> means the root path of disk driver like <code>C:\</code> or <code>D:\</code>, and the file name <code>.pem</code> just is a file suffix name, not a valid file name, and the symbol <code>\</code> is not a valid character for naming file. So please use a valid file path of a existing valid certificate file in your code.</p>
<p>Meanwhile, the list locations functions in ASM mode are different from its in ARM mode. The ASM one lists all of the data center locations that are valid for the specified subscription, but the ARM one list all of the available geo-locations. Please see the related REST API references below to know them because of Azure SDK for Python only wrapped the REST APIs.</p>
<ol>
<li>List locations in ASM mode, please see <a href="https://msdn.microsoft.com/en-us/library/azure/gg441293.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/azure/gg441293.aspx</a>.</li>
<li>List locations in ARM mode, please see <a href="https://msdn.microsoft.com/en-us/library/azure/dn790540.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/azure/dn790540.aspx</a>.</li>
</ol>
| 0 | 2016-07-24T14:43:59Z | [
"python",
"python-2.7",
"azure"
] |
Listing locations in Azure using Python Azure SDK error | 38,494,727 | <p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine
Below is the error :</p>
<p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p>
<p>Please see my code :</p>
<pre><code>import os
import sys
import logging
from azure import *
from azure.servicemanagement import *
subscription_id = 'XXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXXXX'
certificate_path = '\.pem'
sms = ServiceManagementService(subscription_id, certificate_path)
result = sms.list_subscriptions()
for location in result:
print(location.name)
</code></pre>
<p><img src="http://i.stack.imgur.com/pBoOD.png" alt="enter image description here"></p>
| 0 | 2016-07-21T04:09:12Z | 39,504,122 | <ol>
<li><p>Identify the relevant python SDK API for the following: </p>
<ul>
<li>Spin-off an instance using a designated image from the storage account</li>
</ul></li>
<li>Why are anticipated platform issues.</li>
<li>Identify the API to detach the data disk from the failed instance
and attach it to the newly created instance.</li>
</ol>
| -1 | 2016-09-15T06:09:16Z | [
"python",
"python-2.7",
"azure"
] |
Listing locations in Azure using Python Azure SDK error | 38,494,727 | <p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine
Below is the error :</p>
<p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p>
<p>Please see my code :</p>
<pre><code>import os
import sys
import logging
from azure import *
from azure.servicemanagement import *
subscription_id = 'XXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXXXX'
certificate_path = '\.pem'
sms = ServiceManagementService(subscription_id, certificate_path)
result = sms.list_subscriptions()
for location in result:
print(location.name)
</code></pre>
<p><img src="http://i.stack.imgur.com/pBoOD.png" alt="enter image description here"></p>
| 0 | 2016-07-21T04:09:12Z | 40,135,396 | <p>Use <code>sms.list_locations()</code> to list out the regions.</p>
<p>Thanks,
Gopal.</p>
| 0 | 2016-10-19T15:12:38Z | [
"python",
"python-2.7",
"azure"
] |
Get sound input & Find similar sound with Python | 38,494,736 | <p>What I wanna do is just like 'Shazam' or 'SoundHound' with Python, only sound version, not music.</p>
<p>For example, when I make sound(e.g door slam), find the most similar sound data in the sound list.</p>
<p>I don't know you can understand that because my English is bad, but just imagine the sound version of 'Shazam'.</p>
<p>I know that 'Shazam' doesn't have open API.
Is there any api like 'Shazam'?
Or,
How can I implement it?</p>
| 0 | 2016-07-21T04:10:17Z | 38,497,404 | <p>There are several libraries you can use, but none of them will classify a sample as a 'door shut' for example. BUT you can use those libraries for feature extraction and build/get a data set of sound, build a classifier, train it and use it for sound classification.</p>
<p>The libraries:</p>
<ol>
<li><p><strong>Friture</strong> - Friture is a graphical program designed to do time-frequency analysis on audio input in real-time. It provides a set of visualization widgets to display audio data, such as a scope, a spectrum analyser, a rolling 2D spectrogram.</p></li>
<li><p><strong>LibXtract</strong> - LibXtract is a simple, portable, lightweight library of audio feature extraction functions. The purpose of the library is to provide a relatively exhaustive set of feature extraction primatives that are designed to be 'cascaded' to create a extraction hierarchies.</p></li>
<li><p><strong>Yaafe</strong> - Yet Another Audio Feature Extractor is a toolbox for audio analysis. Easy to use and efficient at extracting a large number of audio features simultaneously. WAV and MP3 files supported, or embedding in C++, Python or Matlab applications.</p></li>
<li><p><strong>Aubio</strong> - Aubio is a tool designed for the extraction of annotations from audio signals. Its features include segmenting a sound file before each of its attacks, performing pitch detection, tapping the beat and producing midi streams from live audio.</p></li>
<li><p><strong>LibROSA</strong> - A python module for audio and music analysis. It is easy to use, and implements many commonly used features for music analysis.</p></li>
</ol>
<p>If you do choose to use my advise as I mention above, I recommend on
<a href="http://scikit-learn.org/stable/" rel="nofollow">scikit-learn</a> as Machine Learning libraries. It contains a lot of classifiers you may want to use.</p>
| 2 | 2016-07-21T07:13:52Z | [
"python",
"audio"
] |
Alternative to Goto, Label in python? | 38,494,761 | <p>I know I can't use Goto and I know Goto is not the answer. I've readed similar questions, but I just can't figure out a way to solve my problem (I'm a noob, btw). </p>
<p>So, I'm writting a program, in which you have to guess a number. This is an extract of the part I have problems:</p>
<pre><code>` x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
</code></pre>
<p>What would you do? :s </p>
<p>PS: Sorry for my bad English.</p>
| 0 | 2016-07-21T04:12:59Z | 38,494,859 | <p>You can use infinite loop, and also explicit break if necessary.</p>
<pre><code>x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break
</code></pre>
| 0 | 2016-07-21T04:24:35Z | [
"python"
] |
Alternative to Goto, Label in python? | 38,494,761 | <p>I know I can't use Goto and I know Goto is not the answer. I've readed similar questions, but I just can't figure out a way to solve my problem (I'm a noob, btw). </p>
<p>So, I'm writting a program, in which you have to guess a number. This is an extract of the part I have problems:</p>
<pre><code>` x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
</code></pre>
<p>What would you do? :s </p>
<p>PS: Sorry for my bad English.</p>
| 0 | 2016-07-21T04:12:59Z | 38,494,862 | <p>There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore <code>break</code> and <code>continue</code>. Here's one possible solution:</p>
<pre><code>import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
</code></pre>
<p><code>continue</code> jumps to the next iteration of the loop, and <code>break</code> terminates the loop altogether.</p>
<p>(Also note that I wrapped <code>int(raw_input(...))</code> in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the <code>randint</code> call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)</p>
| 6 | 2016-07-21T04:24:46Z | [
"python"
] |
Alternative to Goto, Label in python? | 38,494,761 | <p>I know I can't use Goto and I know Goto is not the answer. I've readed similar questions, but I just can't figure out a way to solve my problem (I'm a noob, btw). </p>
<p>So, I'm writting a program, in which you have to guess a number. This is an extract of the part I have problems:</p>
<pre><code>` x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
</code></pre>
<p>What would you do? :s </p>
<p>PS: Sorry for my bad English.</p>
| 0 | 2016-07-21T04:12:59Z | 38,494,958 | <h2>Python does not support <code>goto</code> or anything equivalent.</h2>
<p>You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the <a href="https://docs.python.org/3/tutorial/controlflow.html" rel="nofollow">control flow page</a> for more information. </p>
<pre><code>x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
</code></pre>
<p>In many other cases, you'll want to use a <a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="nofollow">function</a> to handle the logic you want to use a goto statement for.</p>
| 1 | 2016-07-21T04:36:33Z | [
"python"
] |
Flask UnicodeDecodeError | 38,494,772 | <p>Error:</p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 24: ordinal not in range(128)</p>
</blockquote>
<p>So basically I have a Flask app where users fill a sign up form and it renders a new page.</p>
<p>Here's the code:</p>
<pre><code>render_template('signUpSuccess.html', password="You should know, right? í ½í¸")
</code></pre>
<p>It's not a serious project just a practice app I'm creating since I'm learning Python. I'm positive it's because of the emoji. I've tried other SO questions but just can't figure it out. I know the emoji is not necessary but It'd be nice to know how I can fix this in the future.</p>
| -1 | 2016-07-21T04:14:22Z | 38,494,864 | <p>Try passing a <code>unicode</code> object, not a <code>str</code> into <code>render_template()</code>, like so:</p>
<pre><code>render_template('signUpSuccess.html', password=u"You should know, right? í ½í¸")
</code></pre>
<p>Sample program:</p>
<pre><code># coding: utf-8
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def root():
return render_template('signUpSuccess.html', password=u"You should know, right? í ½í¸")
if __name__=="__main__":
app.run(debug=True)
</code></pre>
<p>template:</p>
<pre><code><html>password: {{ password }}</html>
</code></pre>
| 1 | 2016-07-21T04:25:17Z | [
"python",
"encoding",
"utf-8",
"flask"
] |
Flask UnicodeDecodeError | 38,494,772 | <p>Error:</p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 24: ordinal not in range(128)</p>
</blockquote>
<p>So basically I have a Flask app where users fill a sign up form and it renders a new page.</p>
<p>Here's the code:</p>
<pre><code>render_template('signUpSuccess.html', password="You should know, right? í ½í¸")
</code></pre>
<p>It's not a serious project just a practice app I'm creating since I'm learning Python. I'm positive it's because of the emoji. I've tried other SO questions but just can't figure it out. I know the emoji is not necessary but It'd be nice to know how I can fix this in the future.</p>
| -1 | 2016-07-21T04:14:22Z | 38,494,876 | <p>You should decode that string. Try this:</p>
<pre><code>the_password = "You should know, right? í ½í¸"
the_password = the_password.decode('utf-8')
render_template('signUpSuccess.html', password=the_password)
</code></pre>
| 0 | 2016-07-21T04:26:52Z | [
"python",
"encoding",
"utf-8",
"flask"
] |
How do I work with different graph databases using the Bolt neo4j python? | 38,494,879 | <p>My test using Python Neo4j Bolt was successful. During the test I had opened a graph database (lets call it "First.graphdb"). Then I opened another python file and wanted to call neo4j. This time I had another graph database opened (lets call it "Second.graphdb) and I couldnt get through. How do I know which graphdatabase I am using/updating?</p>
| 0 | 2016-07-21T04:27:42Z | 38,501,634 | <p>If you use two encrypted connections to the same host, you will get into trouble with the SSL certificate.</p>
<p>If you do the following, you will get a <code>ProtocolError</code> stating that the server certificate for the second connection does not match the known certificate for the first:</p>
<pre><code>from neo4j.v1 import GraphDatabase, basic_auth
g1 = GraphDatabase.driver('bolt://localhost:7687')
with g1.session() as s:
s.run('MATCH (a) RETURN a')
g2 = GraphDatabase.driver('bolt://localhost:7787')
with g2.session() as s:
s.run('MATCH (a) RETURN a')
</code></pre>
<p>The error message is:</p>
<pre><code>ProtocolError: Server certificate does not match known certificate for 'localhost';
check details in file '/Users/someuser/.neo4j/known_hosts'
</code></pre>
<p>If you use unencrypted connections (by adding <code>encrypted=False</code> to the <code>driver()</code>) it works.</p>
<p>The simple solution is to delete the <code>known_hosts</code> file after using the first database. However, if you use both in parallel this will cause a lot of overhead. If both databases run on different hosts you should also be fine. Apart from that I don't really know much about dealing with certificates etc. Maybe there is a way to tell the driver which database on which port belongs to which certificate.</p>
| 0 | 2016-07-21T10:23:56Z | [
"python",
"neo4j"
] |
Counting the grouped elements of a Dataframe in Python | 38,494,908 | <p>I have a dataframe that I am trying to group by and sum. I was able to achieve this, but I'd also like to count the grouped by elements. </p>
<pre><code>sessions_summed = df.groupby("screens_completed").sum()
print sessions_summed
</code></pre>
<p>using this, I get this output:</p>
<pre><code>screens_completed sessions
0 6
1 1
2 3
3 1
4 1
5 1
9 33
12 8
13 872
14 103292
</code></pre>
<p>What I would like is to see the count of how many times each entity in screens completed (i.e. how many times did 14 appear) appeared alongside this new summed sessions column. And then I would like divide the summed column by the count column.</p>
<p>How would I do this?</p>
| 1 | 2016-07-21T04:31:47Z | 38,495,716 | <h2>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>DataFrame.pivot_table</code></a> to count the number of times a certain value appears in a column.</h2>
<p>You can take advantage of the <code>aggfunc</code> argument in the <code>pivot_table</code> function.</p>
<pre><code>sessions_summed = df.groupby("screens_completed").sum()
#the below line will count the number of times each value occurs in screens_completed.
sessions_summed["count"] = df.pivot_table(index="screens_completed", values="sessions", aggfunc=len)
sessions_summed["mean"] = sessions_summed["sessions"] / sessions_summed["count"]
</code></pre>
<h3>So what's going on here?</h3>
<p><code>pivot_table</code> will group your rows based on the column you specify with the <code>index</code> parameter. For each of the columns you pass the 'values' parameter, <code>pivot_table</code> will try to compute some summarizing information to put in that column using all of the values in rows corresponding to rows with a matching index value. The <code>aggfunc</code> parameter allows you to tell <code>.pivot_table</code> how you want that column summarized. </p>
<p>For example, let's say you have the following table:</p>
<pre><code>index screens_completed sessions
0 0 2
1 1 4
2 1 1
3 1 3
3 0 3
</code></pre>
<p><code>pivot_table</code> will create two groups for you:</p>
<p><code>screens_completed</code> == 0, which will pass <code>[2, 3]</code> into your aggfunc for column <code>sessions</code>.
<code>screens_completed</code> == 1, which will pass <code>[4, 1, 3]</code> into your <code>aggfunc</code> for column <code>sessions</code></p>
<p>If you pass <code>len</code> to the <code>aggfunc</code> parameter, you're just asking for the length of the list passed into your <code>aggfunc</code>, which is another way of asking for how many times each <code>screens_completed</code> value occurs in your original DataFrame. </p>
<h3>You can also calculate the mean by passing a mean calculating function into the <code>aggfunc</code> parameter</h3>
<p>for example:</p>
<pre><code>from numpy import mean
sessions_summed["mean"] = df.pivot_table(index="screens_completed", values="sessions", aggfunc=mean)
</code></pre>
| 0 | 2016-07-21T05:41:27Z | [
"python"
] |
How does one use numpy's Meshgrid function with a random interval rather than a equally spaced one? | 38,494,934 | <p>Conceptually this is sort of what I wanted to do. I wanted to select random points in a 2D plane and then plot a surface plot of how that would look like. Similarly, an alternative (sub-optimal idea) could be to grade a Meshgrid and select N random points and their corresponding heights and then plot them in a surface plot.</p>
<p>Currently the only successful way that I've been able to make surface plots is with equally intervaled points using the following:</p>
<pre><code>start_val, end_val = -1,1
N = 100
x_range = np.linspace(start_val, end_val, N)
y_range = np.linspace(start_val, end_val, N)
(X,Y) = np.meshgrid(x_range, y_range)
Z = np.sin(2*np.pi*X) + 4*np.power(Y - 0.5, 2) #function height for the sake of an example
</code></pre>
<p>and then plot the thing with the standard:</p>
<pre><code>fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
plt.title('Original function')
plt.show()
</code></pre>
<p>this results in a pretty plot of the function just as I expected.</p>
<p>However, I'd like to select random points in a known interval. For that I tried the alternative:</p>
<pre><code>start_val, end_val = -1,1
N = 100
x_range = np.random.uniform(low=start_val, high=end_val, size=N)
y_range = np.random.uniform(low=start_val, high=end_val, size=N)
(X,Y) = np.meshgrid(x_range, y_range)
Z = np.sin(2*np.pi*X) + 4*np.power(Y - 0.5, 2) #function height for the sake of an example
</code></pre>
<p>Unfortunately, that results in non-sense:</p>
<p><a href="http://i.stack.imgur.com/gBwk7.png" rel="nofollow"><img src="http://i.stack.imgur.com/gBwk7.png" alt="enter image description here"></a></p>
<p>instead of something nicer as the original with the evenly spaced points:</p>
<p><a href="http://i.stack.imgur.com/h8tDT.png" rel="nofollow"><img src="http://i.stack.imgur.com/h8tDT.png" alt="enter image description here"></a></p>
<p>does someone know how to do the task (or a similar task) I am trying to do but being able to plot random points or include some randomness in a sensible way?</p>
| 0 | 2016-07-21T04:33:43Z | 38,508,403 | <p>The x and y ranges used for meshgrid should not be in random order. This is because to draw a surface, it's not enough just to have a bunch of points in XYZ space: we also need to know which are to be connected with which. This is determined from the adjacency of values in the arrays.</p>
<p>Example: if x_range is [1, 2, 3] and y_range is [5, 9], then we know that the points (1,5), (2,5), (1,9), and (2,9) form the vertices of a rectangle to be included in the surface (with the corresponding Z-values, of course). If the x_range was instead [1, 3, 2], we would instead have a rectangle based on (1,5), (3,5), (1,9), and (3,9). </p>
<p>To have a graph of z=f(x,y), we need sorted x and y arrays, so that rectangles we get look like this: </p>
<p><a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface-plots" rel="nofollow"><img src="http://i.stack.imgur.com/P6lzq.png" alt="plot"></a></p>
<p>(For parametric graphs, with x,y,z being functions of parameters u,v, we won't necessarily have sorted x and y values; but u and v probably will be, and their order will determine the order of x,y.)</p>
| 2 | 2016-07-21T15:31:33Z | [
"python",
"numpy",
"random",
"plot"
] |
Installing Tensorflow on Mac for PyPy | 38,494,982 | <p>I am able to install tensorflow for python using pip just fine but when I try and install tensorflow for pypy using:</p>
<pre><code>pypy -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl
</code></pre>
<p>I get error messages about how pypy doesn't play well with numpy. I already have numpy installed for pypy and it workes fine. I can do </p>
<pre><code>pypy
>>>>import numpy
</code></pre>
<p>without any errors.</p>
<p>What am I doing wrong here? Is there a way to try and install tensorflow without it trying to install numpy? Has anyone done this before?</p>
| 0 | 2016-07-21T04:38:40Z | 38,663,650 | <p>youcan use directly pip</p>
<p>example: Mac OS X, CPU only - py2</p>
<pre><code>export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl
sudo pip install --upgrade $TF_BINARY_URL
</code></pre>
<p>If you need validate pip installation:</p>
<pre><code>sudo easy_install pip
sudo easy_install --upgrade six
</code></pre>
<p>If you need info for other SO or more details you can see <a href="http://export%20TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl" rel="nofollow">here</a></p>
| 0 | 2016-07-29T16:37:41Z | [
"python",
"osx",
"numpy",
"tensorflow",
"pypy"
] |
Store tuple as field in model | 38,495,141 | <p>I have the following models:-</p>
<pre><code>class A(...):
id=...
name=...
class B(...):
setOfA=models.ManyToManyField(A)
</code></pre>
<p>What I want is that the setOfA be a 2-d array of A and date.
That is:-</p>
<p>setOfA = [[A1,date1],[A2,date2]]</p>
<p>How can I implement this?</p>
| 1 | 2016-07-21T04:52:43Z | 38,496,327 | <p>You want custom relation model.</p>
<pre><code>class A(...):
id=...
name=...
class B(...):
setOfA=models.ManyToManyField(A, through='Relation')
class Relation(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
important_date = models.DateField()
</code></pre>
<p>Then to get result in format you mentioned:</p>
<pre><code>foo = Relation.objects.filter(b=my_b).select_related('a')
result = [[x.a, x.important_date] for x in foo]
</code></pre>
| 1 | 2016-07-21T06:18:57Z | [
"python",
"django",
"postgresql",
"django-models",
"django-queryset"
] |
pyqtgraph : I want to execute pyqtgraph in new process | 38,495,166 | <p>Dear pyqtgraph masters, </p>
<p>I want to execute pyqtgraph in a newly created process.</p>
<p>In my project there is a python module : trading.py. This module makes a new process using this code</p>
<pre><code>p = Process(target = realDataProcess.realDataProcessStart, args=(self.TopStockList, self.requestCodeList, self.account))
</code></pre>
<p>And you know, To maintain pyqtgraph displaying the computer moniter, we have to use pyqt loop like below.</p>
<pre><code>QApplication.instance().exec_()
</code></pre>
<p>But in new process, It seems that Above code doesn't work. My graph pops up and suddenly disappear.....</p>
<p>Is there any solution about this? please help me out.</p>
| 0 | 2016-07-21T04:55:30Z | 38,980,727 | <p>My experience with multiprocess and pyqtgraph is, that you can't create a new pyqtgraph window on new processes.
Therefore, you can only use pyqtgrahp on your <strong>main process</strong>.
I think there was the explanation somewhere on the net.</p>
<p>If you want to create additional processes to do something, besides pyqtgraph, put your pyqtgraph code below if <strong>name</strong> == '<strong>main</strong>':
Otherwise, you will have as many windows as you have processes.</p>
| 0 | 2016-08-16T17:08:52Z | [
"python",
"pyqt",
"pyqtgraph",
"multiprocess"
] |
Column name and corresponding data are not matching in python | 38,495,355 | <p>I have a CSV file n while working on it in python I am facing following problem:</p>
<p>CSV file:</p>
<pre><code> cand_id cand_name cand_age cand_sex
A1 Adam 35 M
A2 Max 31 M
A3 Uma 32 F
B1 Jack 29 M
B2 Maya 30 F
</code></pre>
<p>Now after loading it in python, the out file has become something like this:</p>
<pre><code> cand_id cand_name cand_age cand_sex
Adam 35 M NaN
Max 31 M NaN
Uma 32 F NaN
Jack 29 M NaN
Maya 30 F Nan
</code></pre>
<p>please tell me how can I align the correct column name with the corresponding data.</p>
<p>Thanks</p>
| 2 | 2016-07-21T05:13:35Z | 38,496,338 | <p>You need add parameter <code>index_col=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p>
<pre><code>import pandas as pd
df = pd.read_csv('P00000001-AL.csv', index_col=False)
</code></pre>
<pre><code>print (df.head())
cmte_id cand_id cand_nm contbr_nm \
0 C00574624 P60006111 Cruz, Rafael Edward 'Ted' LUCAS, FRAN
1 C00574624 P60006111 Cruz, Rafael Edward 'Ted' KERR, JOHN MCCLURE II
2 C00574624 P60006111 Cruz, Rafael Edward 'Ted' LADD, TEENA E. MRS.
3 C00574624 P60006111 Cruz, Rafael Edward 'Ted' KERR, JOHN MCCLURE II
4 C00574624 P60006111 Cruz, Rafael Edward 'Ted' KERR, JOHN MCCLURE II
contbr_city contbr_st contbr_zip contbr_employer \
0 FAIRHOPE AL 365322922.0 SELF EMPLOYED
1 HAMILTON AL 355706637.0 NORTH MISSISSIPPI MEDICAL CENTER
2 MADISON AL 357586884.0 RETIRED
3 HAMILTON AL 355706637.0 NORTH MISSISSIPPI MEDICAL CENTER
4 HAMILTON AL 355706637.0 NORTH MISSISSIPPI MEDICAL CENTER
contbr_occupation contb_receipt_amt contb_receipt_dt \
0 COSMETOLOGIST 25.0 27-APR-16
1 PHYSICIAN 1000.0 28-MAR-16
2 RETIRED 25.0 20-APR-16
3 PHYSICIAN -100.0 30-APR-16
4 PHYSICIAN 100.0 30-APR-16
receipt_desc memo_cd memo_text form_tp \
0 NaN NaN NaN SA17A
1 SEE REDESIGNATION X SEE REDESIGNATION SA17A
2 NaN NaN NaN SA17A
3 REDESIGNATION TO GENERAL X REDESIGNATION TO GENERAL SA17A
4 REDESIGNATION FROM PRIMARY X REDESIGNATION FROM PRIMARY SA17A
file_num tran_id election_tp
0 1077664 SA17A.1722559 P2016
1 1077664 SA17A.1675656 P2016
2 1077664 SA17A.1693960 P2016
3 1077664 SA17A.1827542 P2016
4 1077664 SA17A.1827677 G2016
</code></pre>
<p>EDIT by comment:</p>
<pre><code>print (df)
cand_id cand_name cand_age cand_sex
0 A1 Adam 35 M
1 A2 Max 31 M
2 A3 Uma 32 F
3 B1 Jack 29 M
4 B2 Maya 30 F
print (df.ix[2])
cand_id A3
cand_name Uma
cand_age 32
cand_sex F
Name: 2, dtype: object
df.set_index('cand_id', inplace=True)
print (df.ix['A3'])
cand_name Uma
cand_age 32
cand_sex F
Name: A3, dtype: object
</code></pre>
| 1 | 2016-07-21T06:19:32Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
How to create parallel tasks in Python | 38,495,357 | <p>I am creating a battle game for telegram groups as my beginner's project, one player challenges the other, and then a battle happens in the chat. Now I want to implement a "timeout" function for it.
I've managed to make it work using _thread:</p>
<pre><code>import _thread
class Battle:
def __init__(self, chat_id):
self.chat = chat
print('Instance of battle started on chat %s' % self.chat)
self.pcount = 0
self.p1score = 0
self.p2score = 0
def reset(self):
self.pcount = 0
self.p1score = 0
self.p2score = 0
def timeout(chat_id):
time.sleep(90)
battle = battledic[chat_id]
if battledic[chat_id].timer == 1:
sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
battle.reset()
else:
return
battle = Battle(chat_id)
if message == "challenge":
if battle.pcount == 0:
_thread.start_new_thread(timeout, (chat_id,))
...
</code></pre>
<p>So basically what I'm doing is calling the timeout function, that is going to sleep in a different thread for 90 seconds, and then it checks if the battle still with only one player (pcount == 1), if it is the case, it sends the chat a message telling them the fight did not start, and then resets the battle instance.</p>
<p>The problem here is that I'm raising exceptions very often, even though it works fine most of the time, also sometimes it doesn't have the desired effect, closing ongoing battles. Researching I've found out that this is not the desired way of doing this butI could not find better solution, and maybe I want to run other battles from other chats in parallel too. What should be used in this case? cooperative multitasking? multiprocessing? the trheading module? thanks for any tips on this task!</p>
| 0 | 2016-07-21T05:13:45Z | 38,495,692 | <p>I've got you started. I'm not sure how you are going to chat or keep record of who's playing.</p>
<p>My first thoughts were to run threads but the while loop is easier and waits, too. I assumed Py 3 because of the print function. Let me know if this is what you had in mind.</p>
<pre><code># from threading import Thread
from time import sleep
no_one = True
battledic = {} # I guess you have some?
class Battle(object):
def __init__(self, chat_id):
self.chat_id = chat_id
self.pcount = 0
self.p1score = 0
self.p2score = 0
print('Instance of battle started on chat %s' % self.chat_id)
def reset(self):
self.pcount = 0
self.p1score = 0
self.p2score = 0
def wheres_waldo():
x = 0;no_one = True
while x < 90: # waits 90 seconds unless found
for player in battledic.keys():
if player.is_requesting: # found someone
no_one = False
break # quit looking
else:
print('No one yet')
sleep(1); x+= 1
if no_one:
sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
battle.reset()
else:
sendmessage(chat_id,'Found someone')
def sendmessage(chat_id,message):
print('%s on chat %s' % (message,chat_id))
battle = Battle(chat_id)
while True:
message = raw_input('Command? ')
if message == "challenge":
if battle.pcount == 0:
wheres_waldo()
# first thoughts were to run threads but the while loop is easier and waits, too
# wait = Thread(target=timeout, args=(chat_id))
# where = Thread(target=wheres_waldo)
# wait.start();where.start()
# wait.join();where.join()
</code></pre>
| 0 | 2016-07-21T05:39:29Z | [
"python",
"multithreading"
] |
How to open adb shell and execute commands inside shell using python | 38,495,426 | <p>I am trying to execute adb shell commands in python using subprocess.Popen</p>
<p>Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.</p>
<pre><code>>adb shell
#<command>
</code></pre>
<p>In Python I am using as below but the process is stuck and doesn't give output</p>
<pre><code>subprocess.Popen('adb shell <command>)
</code></pre>
<p>Tried executing manually in command window, same result as python code,stuck and doesn't give output</p>
<pre><code>>adb shell <command>
</code></pre>
<p>I am trying to execute a binary file in background(using binary file name followed by &) in the command. </p>
| 0 | 2016-07-21T05:20:29Z | 38,501,052 | <p>Ankur Kabra, try the code below:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
command = 'adb devices'
p = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print 'standard output: %s \n error output: %s \n',(stdout,stderr)
</code></pre>
<p>and you will see the error output.</p>
<p>Usually it will tell you:</p>
<pre><code> /bin/sh: adb: command not found
</code></pre>
<p>which means, shell can not excute <code>adb</code> command.
so, adding <code>adb</code> to your <code>PATH</code> or writing the full path of <code>adb</code> will solve the problem.</p>
<p>May help.</p>
| -1 | 2016-07-21T10:00:41Z | [
"android",
"python",
"shell",
"adb"
] |
How to open adb shell and execute commands inside shell using python | 38,495,426 | <p>I am trying to execute adb shell commands in python using subprocess.Popen</p>
<p>Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.</p>
<pre><code>>adb shell
#<command>
</code></pre>
<p>In Python I am using as below but the process is stuck and doesn't give output</p>
<pre><code>subprocess.Popen('adb shell <command>)
</code></pre>
<p>Tried executing manually in command window, same result as python code,stuck and doesn't give output</p>
<pre><code>>adb shell <command>
</code></pre>
<p>I am trying to execute a binary file in background(using binary file name followed by &) in the command. </p>
| 0 | 2016-07-21T05:20:29Z | 38,523,219 | <p>use pexpect (<a href="https://pexpect.readthedocs.io/en/stable/" rel="nofollow">https://pexpect.readthedocs.io/en/stable/</a>)</p>
<pre><code>adb="/Users/lishaokai/Library/Android/sdk/platform-tools/adb"
import pexpect
import sys, os
child = pexpect.spawn(adb + " shell")
child.logfile_send = sys.stdout
while True:
index = child.expect(["$","@",pexpect.TIMEOUT])
print index
child.sendline("ls /storage/emulated/0/")
index = child.expect(["huoshan","google",pexpect.TIMEOUT])
print index, child.before, child.after
break
</code></pre>
| 0 | 2016-07-22T09:43:27Z | [
"android",
"python",
"shell",
"adb"
] |
How to open adb shell and execute commands inside shell using python | 38,495,426 | <p>I am trying to execute adb shell commands in python using subprocess.Popen</p>
<p>Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.</p>
<pre><code>>adb shell
#<command>
</code></pre>
<p>In Python I am using as below but the process is stuck and doesn't give output</p>
<pre><code>subprocess.Popen('adb shell <command>)
</code></pre>
<p>Tried executing manually in command window, same result as python code,stuck and doesn't give output</p>
<pre><code>>adb shell <command>
</code></pre>
<p>I am trying to execute a binary file in background(using binary file name followed by &) in the command. </p>
| 0 | 2016-07-21T05:20:29Z | 38,525,350 | <p>Found a way to do it using communicate() method in subprocess module</p>
<pre><code>procId = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
procId.communicate('command1\ncommand2\nexit\n')
</code></pre>
| 0 | 2016-07-22T11:29:53Z | [
"android",
"python",
"shell",
"adb"
] |
's' prefix for list in Python 3 | 38,495,500 | <p><strong>Already did some searches on SO and looked on the python 3 documentation for str.split() and list()</strong></p>
<p>Why does python prefix a list object with <code>s</code> when it prints to my terminal from a <code>.py</code> script, but not when I'm in the python shell?</p>
<p>For example, if I make a short python program and execute it from the command line,</p>
<pre><code>#!/usr/bin/env python
my_path="/data/user"
print(my_path.strip().split("/"))
</code></pre>
<p>it outputs this: <code>s['', 'data', 'user']</code></p>
<p>However, if I open the python shell and execute the same code, the <code>s</code> prefix disappears. Why is this, and can anyone link a resource to explain what is going on?</p>
<pre><code>Python 3.5.1 |Anaconda 4.1.0 (64-bit)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
>>> my_path = "/data/user"
>>> print(my_path.strip().split("/"))
['', 'data', 'user']
</code></pre>
| 0 | 2016-07-21T05:25:39Z | 38,495,930 | <p><strong>Sorry to waste your time, everyone!</strong></p>
<p>I realized that I was executing this script from a <code>unittest</code> class and that the <code>s</code> character is printed upon execution of the <code>setup()</code> method. No problems now, thank you.</p>
| 0 | 2016-07-21T05:55:58Z | [
"python",
"python-3.x"
] |
Unix timestamp is different in two computers | 38,495,603 | <p>I just tried to run the same python code on two computers. The code says:</p>
<pre><code>import time
print time.time()
</code></pre>
<p>I started the execution in both computers with a click with both of my fingers (I accept a difference of up to 80ms), and both codes executed immediately (I saw no delay in execution)</p>
<p>One of the consoles says time X, and the other says X-3. (seconds! 3 seconds difference)</p>
<p>How is such thing possible? I believed that UNIX timestamp is accurate in all computers to the Millisecond...</p>
| 0 | 2016-07-21T05:33:55Z | 38,495,642 | <p>Intern clocks of your computers are probably simply set at different times.</p>
| 0 | 2016-07-21T05:36:08Z | [
"python",
"unix"
] |
Unix timestamp is different in two computers | 38,495,603 | <p>I just tried to run the same python code on two computers. The code says:</p>
<pre><code>import time
print time.time()
</code></pre>
<p>I started the execution in both computers with a click with both of my fingers (I accept a difference of up to 80ms), and both codes executed immediately (I saw no delay in execution)</p>
<p>One of the consoles says time X, and the other says X-3. (seconds! 3 seconds difference)</p>
<p>How is such thing possible? I believed that UNIX timestamp is accurate in all computers to the Millisecond...</p>
| 0 | 2016-07-21T05:33:55Z | 38,498,162 | <p>You need to synchronize your clocks, if not there is no possible such accuracy. Clocks naturally drift for many reasons. You can simply synchronize the clocks if your computers are on the internet by using <code>ntp</code>. There is a lot of <code>ntp</code> servers around the world. This usually synchronizes your clocks tightly.</p>
| 0 | 2016-07-21T07:50:30Z | [
"python",
"unix"
] |
Django self-referential class for most similar car | 38,495,633 | <p>Let's say I have a class <code>Car</code> with a number of fields describing its features. I call and display these features in my html using <code>{{ object.price }}</code> etc.</p>
<p>With a nearest neighbor algorithm I have calculated a list of most similar cars for each car and would like to be able to display features of for example the five most similar cars.
Want kind of field should I use for <code>most_similar_cars</code> in my class? Please note that the relationship is not symmetric. I.e. while car B might be the nearest neighbor of car A, car A is not necessarily the nearest neighbor of car B. I also need to be able to differentiate between the most similar, second most similar, third most etc.</p>
<p><code>models.py</code></p>
<pre><code>from django.db import models
# Create your models here.
class Car(models.Model):
"""A model of a bureau."""
car_model = models.CharField(max_length = 50)
price = models.IntegerField(default=1)
most_similar = ?
def __str__(self):
return self.car_model
</code></pre>
<p>I really hope someone can help. Thank you co much.</p>
| 0 | 2016-07-21T05:35:42Z | 38,496,040 | <p>You probably want asymmetrycal M2M with custom relation model for ordering nearest cars.
In your case:</p>
<pre><code>class Car(models.Model):
"""A model of a bureau."""
car_model = models.CharField(max_length = 50)
price = models.IntegerField(default=1)
most_similar = models.ManyToManyField('self', symmetrical=False, through='CarRelation')
def __str__(self):
return self.car_model
class CarRelation(models.Model):
car = models.ForeignKey(Car)
close_car = models.ForeignKey(Car, related_name='nearest_cars')
order = models.PositiveIntegerField()
class Meta:
ordering = ('order',)
</code></pre>
<p>Then you can add relations like this:</p>
<pre><code>a = Car.objects.create(car_model='A')
b = Car.objects.create(car_model='B')
relation = CarRelation.objects.create(car=a, close_car=b, order=1)
</code></pre>
<p>More info in Django docs: <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.symmetrical" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.symmetrical</a></p>
| 2 | 2016-07-21T06:02:15Z | [
"python",
"django",
"python-3.x",
"django-models",
"django-templates"
] |
Find strings from a list starting with strings in another list | 38,495,868 | <p>I have two list <code>listOne</code> & <code>listTwo</code></p>
<p><strong>e.g.</strong></p>
<p><code>listOne</code> could contain 'about', 'day', 'school'</p>
<p><code>listTwo</code> could contain 'a','c','da','z'</p>
<p>I want to find out all the elements in <code>listOne</code> which start with characters from elements in <code>listTwo</code>. The output with above example is 'about' and 'day'</p>
<p>I try to implement it with following code:</p>
<pre><code>for elem1 in listTwo:
for elem2 in listOne:
if elem2.startswith(elem1):
result.append(elem2)
</code></pre>
<p>but I feel it nested too much. Is there a more elegant way to achieve it in Python?</p>
| 1 | 2016-07-21T05:50:42Z | 38,495,918 | <p>The way that you're doing it is fine. It's easy to read/understand, etc.</p>
<p>However, if you really want, you can probably condense it down using <code>itertools.product</code>:</p>
<pre><code>from itertools import product
result = [elem2 for elem1, elem2 in product(listTwo, listOne) if elem2.startswith(elem1)]
</code></pre>
| 1 | 2016-07-21T05:54:56Z | [
"python",
"string",
"list"
] |
Find strings from a list starting with strings in another list | 38,495,868 | <p>I have two list <code>listOne</code> & <code>listTwo</code></p>
<p><strong>e.g.</strong></p>
<p><code>listOne</code> could contain 'about', 'day', 'school'</p>
<p><code>listTwo</code> could contain 'a','c','da','z'</p>
<p>I want to find out all the elements in <code>listOne</code> which start with characters from elements in <code>listTwo</code>. The output with above example is 'about' and 'day'</p>
<p>I try to implement it with following code:</p>
<pre><code>for elem1 in listTwo:
for elem2 in listOne:
if elem2.startswith(elem1):
result.append(elem2)
</code></pre>
<p>but I feel it nested too much. Is there a more elegant way to achieve it in Python?</p>
| 1 | 2016-07-21T05:50:42Z | 38,495,985 | <p>You can pass a tuple to <code>str.startswith</code> method. </p>
<p>From the <a href="https://docs.python.org/2/library/stdtypes.html#str.startswit" rel="nofollow">doc</a>:</p>
<blockquote>
<p><strong>str.startswith(prefix[, start[, end]]):</strong> Return True if string starts
with the prefix, otherwise return False. prefix can also be a tuple of
prefixes to look for. With optional start, test string beginning at
that position. With optional end, stop comparing string at that
position.</p>
</blockquote>
<p><strong>But this is supported in Python 2.5+</strong></p>
<pre><code>tuple_listTwo = tuple(listTwo)
[ele for ele in listOne if ele.startswith(tuple_listTwo)]
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p>['day', 'about']</p>
</blockquote>
| 1 | 2016-07-21T05:59:08Z | [
"python",
"string",
"list"
] |
Converting a PDF file to a Text file in Python | 38,496,026 | <p>I've been on it for several days + researching the internet on how to get specific information from a pdf file.</p>
<p>Eventually I was able to fetch all information using Python from a text file(which I created by going to the <em>PDF file -----> File ------> Save as Text</em>).</p>
<p>The question is how do I get Python to accomplish those tasks(Going to the PDF file(opening it - is quite easy open("file path"), clicking on File in the menu, and then saving the file as a text file in the same directory).</p>
<p>Just to be clear, I do not require the pdfminer or pypdf libraries as I have already extracted the information with the same file(after converting it manually to txt)</p>
| 2 | 2016-07-21T06:01:42Z | 38,498,670 | <p>You could use pdftotext.exe that you can download from <a href="http://www.foolabs.com/xpdf/download.html" rel="nofollow">http://www.foolabs.com/xpdf/download.html</a> and then execute it on your pdf files via Python:</p>
<pre><code>import os
import glob
import subprocess
#remember to put your pdftotxt.exe to the folder with your pdf files
for filename in glob.glob(os.getcwd() + '\\*.pdf'):
subprocess.call([os.getcwd() + '\\pdftotext', filename, filename[0:-4]+".txt"])
</code></pre>
<p>At least it worked for one of my projects.</p>
| 0 | 2016-07-21T08:15:52Z | [
"python",
"python-2.7",
"pdf",
"text",
"converter"
] |
Subscribe to Carriots Stream | 38,496,055 | <p>I am trying to subscribe to carriots data stream using paho mqtt client. But i am not able to read any data from carriots.
Here's the source code i am using to subscribe to carriots.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Client paho-mqtt CarriotsMqttServer
# sub_carriot.py
import paho.mqtt.subscribe as mqtt
class CarriotsMqttClient():
host = 'mqtt.carriots.com'
port = '1883'
auth = {}
topic = '%s/streams'
tls = None
def __init__(self, auth, tls=None):
self.auth = auth
self.topic = '%s/streams' % auth['username']
if tls:
self.tls = tls
self.port = '8883'
#Subscribe
def subscribe(self):
try:
mqtt.simple(topics=self.topic, msg_count=10, hostname=self.host, port=self.port, auth=self.auth, tls=self.tls)
except Exception, ex:
print ex
if __name__ == '__main__':
auth = {'username': '72cdf4ec......bbeec9d9fb4483e', 'password': ''}
client_mqtt = CarriotsMqttClient(auth=auth)
client_mqtt.subscribe()
</code></pre>
<p>Can anybody tell me if there is something wrong with the code or i am missing some step which is required to subscribe to cariots stream.</p>
<p>I was able to successfully publish on carriots using paho mqtt, with help of reference code given on carriots website.</p>
| 0 | 2016-07-21T06:02:56Z | 38,499,715 | <p>The <code>mqtt.simple</code> function blocks until <code>msg_count</code> messages have been received and then it returns those messages.</p>
<p>So the code as you have it will just sit until it has received 10 messages then it is probably going to exit without any output as there is nothing to collect the messages returned by the function.</p>
<p>I would suggest you look at using the normal subscription method using a callback and the network loop. Something like this:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Client paho-mqtt CarriotsMqttServer
# sub_carriot.py
import paho.mqtt.client as mqtt
class CarriotsMqttClient():
host = 'mqtt.carriots.com'
port = '1883'
auth = {}
topic = '%s/streams'
tls = None
client = None
def __init__(self, auth, tls=None):
self.auth = auth
self.topic = '%s/streams' % auth['username']
if tls:
self.tls = tls
self.port = '8883'
self.client = mqtt.Client()
self.client.on_message = self.onMessage
self.client.connect(self.host, self.port)
self.client.loop_start()
def onMessage(self, client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
#Subscribe
def subscribe(self):
try:
self.client.subscribe(self.topic)
except Exception, ex:
print ex
if __name__ == '__main__':
auth = {'username': '72cdf4ec......bbeec9d9fb4483e', 'password': ''}
client_mqtt = CarriotsMqttClient(auth=auth)
client_mqtt.subscribe()
</code></pre>
| 0 | 2016-07-21T09:05:32Z | [
"python",
"mqtt",
"iot",
"paho"
] |
Nested for-loop error python | 38,496,105 | <p>I am completely new to programing. I am trying to nest what i think is a "for-loop" inside of what i think is a "for-loop". Every time i run the program i get an error: "There's an error in your program:
unexpected unindent". I honestly have no clue how to fix it. Any help would be greatly appreciated.
Here is the Code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import urllib2
import time
stocksToPull = 'AAPL'
def pullData(stock):
try:
pricedata = urllib2.urlopen("http://www.google.com/finance/getprices?i=60&p=1d&f=d,o,h,l,c,v&df=cpct&q="+stock+"").read()
pricevalues = pricedata.split()
current_price = float(pricevalues[len(pricevalues)-1].split(",")[4]) #High
pricevalues = pricedata.split()
Pcurrent_price = float(pricevalues[len(pricevalues)-1].split(",")[2]) #Open
DPCge= (current_price/Pcurrent_price)/Pcurrent_price #Daily Precent Change
number = 0.010000000000
# This is the begging of the nested for-loop
if stock == 'AAPL' and DPCge> number:
for eachStock in stocksToPull:
stocksToPull = 'AAPL'
pullData(eachStock)
def pullData(stock):
try:
pricedata = urllib2.urlopen("http://www.google.com/finance/getprices?i=60&p=1d&f=d,o,h,l,c,v&df=cpct&q="+stock+"").read()
pricevalues = pricedata.split()
current_price = float(pricevalues[len(pricevalues)-1].split(",")[4]) #High
pricevalues = pricedata.split()
Pcurrent_price = float(pricevalues[len(pricevalues)-1].split(",")[2]) #Open
DPCge= (current_price/Pcurrent_price)/Pcurrent_price #Daily Precent Change
number = 0.010000000000
except Exception,e:
print'main loop',str(e)
for eachStock in stocksToPull:
pullData(eachStock)</code></pre>
</div>
</div>
</p>
| -3 | 2016-07-21T06:06:16Z | 38,496,310 | <p>In your code, you have two try blocks and one except. The indentation of the except block does not align with either of the try blocks. Moreover, you have defined the same function within the given function! Your code is all over the place. Remove the inner function block and replace it with a call to the function if that is what you need and fix your try and except blocks.</p>
| 0 | 2016-07-21T06:17:49Z | [
"python",
"for-loop"
] |
character buffer object error in translate python | 38,496,199 | <pre><code> 1 import sys
2 import string
3 from collections import Counter
4
5 def count_words(input_file_path, *w_f):
6 tab = dict.fromkeys([ord(i) for i in string.punctuation], u' ')
7 words = []
8 count = 0
9 frequency = Counter()
10 with open(input_file_path, "r") as fp:
11 for line in fp.readlines():
12 linei = line.translate(tab)
13 words = linei.split()
14 count += len(words)
15 for item in words:
16 frequency[item] += 1
17 if w_f:
18 with open(w_f, "w") as wfp:
19 to_write = fp.read()
20 wfp.write(to_write)
21
22 sorted(frequency.items())
23 print "total word count %d" % count
24 print "Frequency "
25 print frequency
26
27 if __name__ == '__main__':
28 if len(sys.argv) == 2:
29 count_words(sys.argv[1])
30 elif len(sys.argv) == 3:
31 count_words(sys.argv[1], sys.argv[2])
32 else: raise Exception("Insufficient Arguments")
</code></pre>
<p>I've written a program to count words.
The error is a typeerror.
It says translate expects a buffer object .Its got to do with the unicode i guess.</p>
<p>What is the exact problem?</p>
| 0 | 2016-07-21T06:11:59Z | 38,497,578 | <p>From the <a href="https://docs.python.org/2/library/string.html#string.translate" rel="nofollow">documentation on <code>str.translate</code></a>:</p>
<blockquote>
<p>translate the characters using table, which <strong>must be a 256-character string</strong></p>
</blockquote>
<p>You're however trying to use a dict. To create a valid translation table, take a look at <a href="https://docs.python.org/2/library/string.html#string.maketrans" rel="nofollow"><code>str.maketrans</code></a>.</p>
| 0 | 2016-07-21T07:21:59Z | [
"python",
"translate"
] |
Can I dynamically change an individual handler's log level in Python? | 38,496,263 | <p>I have a logger set up with two handlers - one to console and one a rotated file. I set each individual handlers with their own log level. The idea is that important messages are available on the console, while the lower level stuff goes to the file in case I need to do further troubleshooting.</p>
<p>My config file looks like this:</p>
<pre><code>[loggers]
keys=root
[handlers]
keys=consoleHandler,rotateFileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,rotateFileHandler
qualname=MyApplication
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=ERROR
formatter=simpleFormatter
args=(sys.stdout,)
[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=INFO
formatter=simpleFormatter
args=('TESTLOG.log', 'a', 100000, 5, 'utf8')
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
</code></pre>
<p>Is there a way to dynamically change (and then reset) the log level for an individual handler? I have attempted to do this, but it fails because <code>logger</code> is, well, the logger and not the handler. It is also already set to <code>DEBUG</code>, it's the handlers that are set at higher levels.</p>
<pre><code>import logging
import logging.config
logging.config.fileConfig('logging.config', disable_existing_loggers=False)
logger = logging.getLogger('TestLog')
def main():
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
# Reset log level to debug temporarily
logger.setLevel(logging.DEBUG)
logger.debug('This message appears if level was reset to DEBUG')
if __name__ == '__main__':
main()
</code></pre>
<p>My goal is to be able to set the console to a lower level (ie. <code>logging.DEBUG</code> for a period of time and then change it back, either by saving the previous level before the change is executed or explicitly resetting it). I don't want to touch the other handlers when I do this though.</p>
<p>How do I change the <em>handler</em> log level dynamically?</p>
| 0 | 2016-07-21T06:15:08Z | 38,496,484 | <p>You'd have to traverse to the specific handler:</p>
<pre><code>console_handler = logging.getLogger().handlers[0]
old_level = console_handler.level
console_handler.setLevel(logging.DEBUG)
</code></pre>
<p>The index matches the order from the <code>handlers</code> in your logging configuration (any previous handlers on a given logger are cleared whet the config is loaded).</p>
| 1 | 2016-07-21T06:26:27Z | [
"python",
"logging"
] |
Fastest way to extract dictionary of sums in numpy in 1 I/O pass | 38,496,418 | <p>Let's say I have an array like:</p>
<pre><code>arr = np.array([[1,20,5],
[1,20,8],
[3,10,4],
[2,30,6],
[3,10,5]])
</code></pre>
<p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first column, i.e. return <code>{1: 13, 2: 6, 3: 9}</code>. To make matters more challenging, there's 1 billion rows in my array and 100k unique elements in the first column.</p>
<p>Approach 1: Naively, I can invoke <code>np.unique()</code> then iterate through each item in the unique array with a combination of <code>np.where()</code> and <code>np.sum()</code> in a one-liner dictionary enclosing a list comprehension. This would be reasonably fast if I have a small number of unique elements, but at 100k unique elements, I will incur a lot of wasted page fetches making 100k I/O passes of the entire array.</p>
<p>Approach 2: I could make a single I/O pass of the last column (because having to hash column 1 at each row will probably be cheaper than the excessive page fetches) too, but I lose the advantage of numpy's C inner loop vectorization here.</p>
<p>Is there a fast way to implement Approach 2 without resorting to a pure Python loop?</p>
| 7 | 2016-07-21T06:23:23Z | 38,497,749 | <p>numpy approach:</p>
<pre><code>u = np.unique(arr[:, 0])
s = ((arr[:, [0]] == u) * arr[:, [2]]).sum(0)
dict(np.stack([u, s]).T)
{1: 13, 2: 6, 3: 9}
</code></pre>
<p>pandas approach:</p>
<pre><code>import pandas as pd
import numpy as np
pd.DataFrame(arr, columns=list('ABC')).groupby('A').C.sum().to_dict()
{1: 13, 2: 6, 3: 9}
</code></pre>
<p><a href="http://i.stack.imgur.com/RXLMz.png" rel="nofollow"><img src="http://i.stack.imgur.com/RXLMz.png" alt="enter image description here"></a></p>
| 4 | 2016-07-21T07:30:20Z | [
"python",
"numpy",
"pandas",
"dictionary",
"vectorization"
] |
Fastest way to extract dictionary of sums in numpy in 1 I/O pass | 38,496,418 | <p>Let's say I have an array like:</p>
<pre><code>arr = np.array([[1,20,5],
[1,20,8],
[3,10,4],
[2,30,6],
[3,10,5]])
</code></pre>
<p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first column, i.e. return <code>{1: 13, 2: 6, 3: 9}</code>. To make matters more challenging, there's 1 billion rows in my array and 100k unique elements in the first column.</p>
<p>Approach 1: Naively, I can invoke <code>np.unique()</code> then iterate through each item in the unique array with a combination of <code>np.where()</code> and <code>np.sum()</code> in a one-liner dictionary enclosing a list comprehension. This would be reasonably fast if I have a small number of unique elements, but at 100k unique elements, I will incur a lot of wasted page fetches making 100k I/O passes of the entire array.</p>
<p>Approach 2: I could make a single I/O pass of the last column (because having to hash column 1 at each row will probably be cheaper than the excessive page fetches) too, but I lose the advantage of numpy's C inner loop vectorization here.</p>
<p>Is there a fast way to implement Approach 2 without resorting to a pure Python loop?</p>
| 7 | 2016-07-21T06:23:23Z | 38,501,309 | <p>Here's a NumPy based approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow"><code>np.add.reduceat</code></a> -</p>
<pre><code>sidx = arr[:,0].argsort()
idx = np.append(0,np.where(np.diff(arr[sidx,0])!=0)[0]+1)
keys = arr[sidx[idx],0]
vals = np.add.reduceat(arr[sidx,2],idx,axis=0)
</code></pre>
<p>If you would like to get the keys and values in a 2-column array -</p>
<pre><code>out = np.column_stack((keys,vals)) # If you
</code></pre>
<p>Sample run -</p>
<pre><code>In [351]: arr
Out[351]:
array([[ 1, 20, 5],
[ 1, 20, 8],
[ 3, 10, 4],
[ 2, 30, 6],
[ 3, 10, 5]])
In [352]: out
Out[352]:
array([[ 1, 13],
[ 2, 6],
[ 3, 9]])
</code></pre>
| 3 | 2016-07-21T10:10:16Z | [
"python",
"numpy",
"pandas",
"dictionary",
"vectorization"
] |
Fastest way to extract dictionary of sums in numpy in 1 I/O pass | 38,496,418 | <p>Let's say I have an array like:</p>
<pre><code>arr = np.array([[1,20,5],
[1,20,8],
[3,10,4],
[2,30,6],
[3,10,5]])
</code></pre>
<p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first column, i.e. return <code>{1: 13, 2: 6, 3: 9}</code>. To make matters more challenging, there's 1 billion rows in my array and 100k unique elements in the first column.</p>
<p>Approach 1: Naively, I can invoke <code>np.unique()</code> then iterate through each item in the unique array with a combination of <code>np.where()</code> and <code>np.sum()</code> in a one-liner dictionary enclosing a list comprehension. This would be reasonably fast if I have a small number of unique elements, but at 100k unique elements, I will incur a lot of wasted page fetches making 100k I/O passes of the entire array.</p>
<p>Approach 2: I could make a single I/O pass of the last column (because having to hash column 1 at each row will probably be cheaper than the excessive page fetches) too, but I lose the advantage of numpy's C inner loop vectorization here.</p>
<p>Is there a fast way to implement Approach 2 without resorting to a pure Python loop?</p>
| 7 | 2016-07-21T06:23:23Z | 38,501,662 | <p>This is a typical grouping problem, which the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package solves efficiently and elegantly (if I may say so myself; I am its author)</p>
<pre><code>import numpy_indexed as npi
npi.group_by(arr[:, 0]).sum(arr[:, 2])
</code></pre>
<p>Its a much more lightweight solution than the pandas package, and I think the syntax is cleaner, as there is no need to create a special datastructure just to perform this type of elementary operation. Performance should be identical to the solution posed by Divakar, since it follows the same steps; just with a nice and tested interface on top.</p>
| 3 | 2016-07-21T10:24:51Z | [
"python",
"numpy",
"pandas",
"dictionary",
"vectorization"
] |
Fastest way to extract dictionary of sums in numpy in 1 I/O pass | 38,496,418 | <p>Let's say I have an array like:</p>
<pre><code>arr = np.array([[1,20,5],
[1,20,8],
[3,10,4],
[2,30,6],
[3,10,5]])
</code></pre>
<p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first column, i.e. return <code>{1: 13, 2: 6, 3: 9}</code>. To make matters more challenging, there's 1 billion rows in my array and 100k unique elements in the first column.</p>
<p>Approach 1: Naively, I can invoke <code>np.unique()</code> then iterate through each item in the unique array with a combination of <code>np.where()</code> and <code>np.sum()</code> in a one-liner dictionary enclosing a list comprehension. This would be reasonably fast if I have a small number of unique elements, but at 100k unique elements, I will incur a lot of wasted page fetches making 100k I/O passes of the entire array.</p>
<p>Approach 2: I could make a single I/O pass of the last column (because having to hash column 1 at each row will probably be cheaper than the excessive page fetches) too, but I lose the advantage of numpy's C inner loop vectorization here.</p>
<p>Is there a fast way to implement Approach 2 without resorting to a pure Python loop?</p>
| 7 | 2016-07-21T06:23:23Z | 38,501,913 | <p>The proper way of doing this is with NumPy is using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a>. If your unique first column labels are already small contiguous integers you could simply do:</p>
<pre><code>cum_sums = np.bincount(arr[:, 0], weights=arr[:, 2])
cum_dict = {index: cum_sum for index, cum_sum in enumerate(cum_sums)
if cum_sum != 0}
</code></pre>
<p>where the <code>cum_sum != 0</code> is an attempt to skip missing first column labels, which may be grossly wrong if your third column includes negative numbers.</p>
<p>Alternatively you can do things properly and call <code>np.unique</code> first and do:</p>
<pre><code>uniques, indices = np.unique(arr[:, 0], return_inverse=True)
cum_sums = np.bincount(indices, weights=arr[:, 2])
cum_dict = {index: cum_sum for index, cum_sum in zip(uniques, cum_sums)}
</code></pre>
| 3 | 2016-07-21T10:35:18Z | [
"python",
"numpy",
"pandas",
"dictionary",
"vectorization"
] |
Writing less elif statement | 38,496,466 | <p>I need help with this.</p>
<pre><code>a = ["cat","dog","fish","hamster"]
user = raw_input("choose your fav pet ")
if user == a[0]:
print a[0]
elif user == a[1]:
print a[1]
elif user == a[2]:
print a[2]
elif user == a[3]:
print a[3]
else:
print "sorry, the aninimal you type does not exist"
</code></pre>
<p>What I want to do is a testing mobile app so I use animal as testing. The program did work but the problem is that there are over 100's of animals in the world and I put them in a list, I don't want to create many <code>elif</code> statements. </p>
<p>Is there a way to make it shorter and faster?</p>
| 0 | 2016-07-21T06:25:35Z | 38,496,554 | <p>I'd go with:</p>
<pre><code>if user in a:
print user
</code></pre>
<p>That will check if <code>user</code> input is in the list of pets and if it is, it will print it.</p>
| 4 | 2016-07-21T06:30:37Z | [
"python",
"python-2.7",
"if-statement"
] |
Writing less elif statement | 38,496,466 | <p>I need help with this.</p>
<pre><code>a = ["cat","dog","fish","hamster"]
user = raw_input("choose your fav pet ")
if user == a[0]:
print a[0]
elif user == a[1]:
print a[1]
elif user == a[2]:
print a[2]
elif user == a[3]:
print a[3]
else:
print "sorry, the aninimal you type does not exist"
</code></pre>
<p>What I want to do is a testing mobile app so I use animal as testing. The program did work but the problem is that there are over 100's of animals in the world and I put them in a list, I don't want to create many <code>elif</code> statements. </p>
<p>Is there a way to make it shorter and faster?</p>
| 0 | 2016-07-21T06:25:35Z | 38,496,561 | <p>Use a <code>for</code> loop:</p>
<pre><code>for animal in a:
if user == animal:
print animal
break
else:
print "Sorry, the animal you typed does not exist"
</code></pre>
<p>I'd note however that this code is a bit silly. If all you're going to do when you find the animal matching the user's entry is print it, you could instead just check if the entry is in the <code>a</code> list and <code>print user</code> if it is:</p>
<pre><code>if user in a:
print user
else:
print "Sorry, the animal you typed does not exist"
</code></pre>
| 5 | 2016-07-21T06:31:05Z | [
"python",
"python-2.7",
"if-statement"
] |
Writing less elif statement | 38,496,466 | <p>I need help with this.</p>
<pre><code>a = ["cat","dog","fish","hamster"]
user = raw_input("choose your fav pet ")
if user == a[0]:
print a[0]
elif user == a[1]:
print a[1]
elif user == a[2]:
print a[2]
elif user == a[3]:
print a[3]
else:
print "sorry, the aninimal you type does not exist"
</code></pre>
<p>What I want to do is a testing mobile app so I use animal as testing. The program did work but the problem is that there are over 100's of animals in the world and I put them in a list, I don't want to create many <code>elif</code> statements. </p>
<p>Is there a way to make it shorter and faster?</p>
| 0 | 2016-07-21T06:25:35Z | 38,496,587 | <p>Use in operator: </p>
<pre><code>if user in a:
print user
else :
print "sorry, the aninimal you type does not exist"
</code></pre>
| 0 | 2016-07-21T06:32:47Z | [
"python",
"python-2.7",
"if-statement"
] |
Writing less elif statement | 38,496,466 | <p>I need help with this.</p>
<pre><code>a = ["cat","dog","fish","hamster"]
user = raw_input("choose your fav pet ")
if user == a[0]:
print a[0]
elif user == a[1]:
print a[1]
elif user == a[2]:
print a[2]
elif user == a[3]:
print a[3]
else:
print "sorry, the aninimal you type does not exist"
</code></pre>
<p>What I want to do is a testing mobile app so I use animal as testing. The program did work but the problem is that there are over 100's of animals in the world and I put them in a list, I don't want to create many <code>elif</code> statements. </p>
<p>Is there a way to make it shorter and faster?</p>
| 0 | 2016-07-21T06:25:35Z | 38,496,976 | <pre><code> a = ["cat","dog","pig","cat"]
animal = input("enter animal:")
if animal in a:
print (animal , "found")
else:
print ("animal you entered not found in the list")
</code></pre>
<p>The above code is apt for your requirement.</p>
| 0 | 2016-07-21T06:51:52Z | [
"python",
"python-2.7",
"if-statement"
] |
Writing less elif statement | 38,496,466 | <p>I need help with this.</p>
<pre><code>a = ["cat","dog","fish","hamster"]
user = raw_input("choose your fav pet ")
if user == a[0]:
print a[0]
elif user == a[1]:
print a[1]
elif user == a[2]:
print a[2]
elif user == a[3]:
print a[3]
else:
print "sorry, the aninimal you type does not exist"
</code></pre>
<p>What I want to do is a testing mobile app so I use animal as testing. The program did work but the problem is that there are over 100's of animals in the world and I put them in a list, I don't want to create many <code>elif</code> statements. </p>
<p>Is there a way to make it shorter and faster?</p>
| 0 | 2016-07-21T06:25:35Z | 38,499,352 | <p>I would like to add a new way which i am unable to guess how every body missed. We must check string with case insensitive criteria.</p>
<pre><code>a = ["cat","dog","fish","hamster"]
user = raw_input("choose your fav pet ")
// adding for user case where user might have entered DOG, but that is valid match
matching_obj = [data for data in a if data.lower() == user.lower()]
if matching_obj:
print("Data found ",matching_obj)
else:
print("Data not found")
</code></pre>
| 0 | 2016-07-21T08:47:31Z | [
"python",
"python-2.7",
"if-statement"
] |
Python Timedelta Arithmetic With noleap Calendars | 38,496,831 | <p>I'm working with CMIP5 data that has time units of "days since 1-1-1850". To find the current day I'm working with in the file, I would normally just do a timedelta addition from 1-1-1850 and the time value (in days) for the datapoint that I'm working with. However, CMIP5 (or at least the file I'm using) uses a 'noleap' calendar, meaning that all years are only 365 days. </p>
<p>In my current case, when dealing with the datapoint that corresponds to January 1, 1980, I add its time argument of 47450 days to the original date of January 1, 1850. However, I get back an answer of December 1, 1979 because all the Feb. 29ths between 1850 and 1980 are excluded. Is there an additional argument in timedelta or datetime in general that deals with calendars that exclude leap days?</p>
| 1 | 2016-07-21T06:45:21Z | 38,503,519 | <p><a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF num2date</a> is the function you are looking for:</p>
<pre><code>import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # note that we do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
</code></pre>
<p>Note that the CMIP5 models do not have a standard calendar, so the <code>time.calendar</code> argument is important to include when doing this conversion. </p>
| 2 | 2016-07-21T11:51:02Z | [
"python",
"datetime",
"time-series",
"netcdf",
"timedelta"
] |
Performance of groupby when dealing with `category` type in pandas | 38,496,930 | <p>I would like to understand the subtlety behind the usage of <code>category</code> in pandas.</p>
<p>I created a random three columns DataFrame through</p>
<pre><code>import pandas as pd
import numpy as np
a = np.random.choice(['a', 'A'], size=100000)
b = np.random.choice(range(10000), size=100000)
df = pd.DataFrame(data=dict(A1=a, A2=a, B=b))
df['A2'] = df.A2.astype('category')
</code></pre>
<p>treating <code>A2</code> has a <code>category</code> type column.</p>
<pre><code>df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100000 entries, 0 to 99999
Data columns (total 3 columns):
A1 100000 non-null object
A2 100000 non-null category
B 100000 non-null int64
dtypes: category(1), int64(1), object(1)
memory usage: 1.6+ MB
</code></pre>
<p>Running a <code>groupby</code> operator on <code>B</code> and applying a simple function on both <code>A1</code> and <code>A2</code> leads to a dramatic difference in terms of performance,</p>
<pre><code>%%timeit
df_ = df.groupby(by='B').agg(
dict(
A1=lambda s: len(s.unique())
)
)
1 loop, best of 3: 666 ms per loop
</code></pre>
<p>and</p>
<pre><code>%%timeit
df_ = df.groupby(by='B').agg(
dict(
A2=lambda s: len(s.unique())
)
)
1 loop, best of 3: 2.73 s per loop
</code></pre>
<p>Could you please enlighten me on the reason behind this?</p>
| 1 | 2016-07-21T06:50:07Z | 38,497,089 | <p>I think you can use rather <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>SeriesGroupBy.nunique</code></a>, it works with <code>category</code> only a little bit slowier:</p>
<pre><code>print (df.groupby(by='B')['A1'].nunique())
print (df.groupby(by='B')['A2'].nunique())
In [71]: %timeit (df.groupby(by='B')['A1'].nunique())
10 loops, best of 3: 19.8 ms per loop
In [72]: %timeit (df.groupby(by='B')['A2'].nunique())
10 loops, best of 3: 20.2 ms per loop
</code></pre>
<p>Interesting, if use <code>agg</code> with <code>dict</code>, performance is same:</p>
<pre><code>In [77]: %timeit df.groupby(by='B').agg({'A1':'nunique'})
100 loops, best of 3: 20.1 ms per loop
In [78]: %timeit df.groupby(by='B').agg({'A2':'nunique'})
10 loops, best of 3: 20.1 ms per loop
</code></pre>
<p>but if use <code>lambda</code> function, <code>dtype</code> <code>category</code> is more slowier (same problem as you):</p>
<pre><code>In [73]: %timeit df.groupby(by='B').agg(dict(A1=lambda s: s.nunique()))
1 loop, best of 3: 824 ms per loop
In [74]: %timeit df.groupby(by='B').agg(dict(A2=lambda s: s.nunique()))
1 loop, best of 3: 3.07 s per loop
</code></pre>
| 2 | 2016-07-21T06:58:00Z | [
"python",
"performance",
"pandas",
"category"
] |
Check if item in a Python list is an int/number | 38,496,967 | <p>I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this. </p>
<pre><code>list = []
i = 0
for row in reader:
list.append([])
list[i].append(row[0])
...
i += 1
</code></pre>
<p>I want to check one of these fields to see if it's an number (integer).</p>
<p>When I perform a <code>print type(list[i][0])</code> it returns a <code><type 'str'></code> even though the value is say 100.</p>
<p>The if statements below are in a <code>for</code> loop iterating through the lists so what I was thinking of doing is doing a check:</p>
<pre><code>if type(list[i][0] == types.IntType):
True
else:
False
</code></pre>
<p>This works, however that's frowned upon in PEP8 and so I should be using <code>isinstance()</code>, therefore I have modified it to</p>
<pre><code># check if a value is entered
if list[i][0] != '':
if isinstance(int(list[i][0]), int):
True
else:
False
else
False
</code></pre>
<p>But I run into the problem of trying to convert a string to an int (if the user enters a string).</p>
<p>How do I overcome this? It seems like a simple issue however I am new to Python so I was wondering of a neat and efficient way of dealing with this. Should I be checking if the value is an int before storing it into the list?</p>
<p>I am using Python2. </p>
<p>Thanks</p>
<p>edit: I have wrapped the <code>isinstance()</code> check around a try exception catch however I feel like I shouldn't have to resort to this just to check if something is an int or not? Just curious if there was a neater way to do this. </p>
<p>edit: I have used <code>isdigit</code> as mentioned previously however I was getting negative results. </p>
<p>i.e. given this data set. list[0][0] = 123, list[1][0] = asdasd</p>
<pre><code>for i in range(0, 1):
if (list[i][0]).isdigit:
tempInt = list[i][0]
print type(tempInt)
print 'True: ' + tempInt
else:
tempInt = 1
print 'False: ' + tempInt
</code></pre>
<p>Results:</p>
<pre><code><type 'str'>
True: 123
<type 'str'>
True: asdasd
</code></pre>
| 0 | 2016-07-21T06:51:26Z | 38,497,044 | <p>You can check it with this - this is for all numbers (positive and negative integer, floats, Nan), for only <code>int</code> or certain subclass, better approaches might exist.</p>
<pre><code>def is_number(a):
# will be True also for 'NaN'
try:
number = float(a)
return True
except ValueError:
return False
</code></pre>
<p>At face-value, it does not look good. But I think this is probably the best way if you want to consider all number (negative, float, integer, infinity etc), you can see a highly view/voted question/answer <a href="http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python">here</a>. Also note that <code>isdigit</code> does not work in all cases.</p>
| 1 | 2016-07-21T06:55:31Z | [
"python",
"int",
"isinstance"
] |
Check if item in a Python list is an int/number | 38,496,967 | <p>I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this. </p>
<pre><code>list = []
i = 0
for row in reader:
list.append([])
list[i].append(row[0])
...
i += 1
</code></pre>
<p>I want to check one of these fields to see if it's an number (integer).</p>
<p>When I perform a <code>print type(list[i][0])</code> it returns a <code><type 'str'></code> even though the value is say 100.</p>
<p>The if statements below are in a <code>for</code> loop iterating through the lists so what I was thinking of doing is doing a check:</p>
<pre><code>if type(list[i][0] == types.IntType):
True
else:
False
</code></pre>
<p>This works, however that's frowned upon in PEP8 and so I should be using <code>isinstance()</code>, therefore I have modified it to</p>
<pre><code># check if a value is entered
if list[i][0] != '':
if isinstance(int(list[i][0]), int):
True
else:
False
else
False
</code></pre>
<p>But I run into the problem of trying to convert a string to an int (if the user enters a string).</p>
<p>How do I overcome this? It seems like a simple issue however I am new to Python so I was wondering of a neat and efficient way of dealing with this. Should I be checking if the value is an int before storing it into the list?</p>
<p>I am using Python2. </p>
<p>Thanks</p>
<p>edit: I have wrapped the <code>isinstance()</code> check around a try exception catch however I feel like I shouldn't have to resort to this just to check if something is an int or not? Just curious if there was a neater way to do this. </p>
<p>edit: I have used <code>isdigit</code> as mentioned previously however I was getting negative results. </p>
<p>i.e. given this data set. list[0][0] = 123, list[1][0] = asdasd</p>
<pre><code>for i in range(0, 1):
if (list[i][0]).isdigit:
tempInt = list[i][0]
print type(tempInt)
print 'True: ' + tempInt
else:
tempInt = 1
print 'False: ' + tempInt
</code></pre>
<p>Results:</p>
<pre><code><type 'str'>
True: 123
<type 'str'>
True: asdasd
</code></pre>
| 0 | 2016-07-21T06:51:26Z | 38,502,956 | <p>The following approach will return for integers only:</p>
<pre><code>string_list = ['20.0', '100', 'abc', '10.3445', 'adsfasdf.adsfasdf', '10,3445', '34,0']
def check(inp):
try:
inp = inp.replace(',', '.')
num_float = float(inp)
num_int = int(num_float)
return num_int == num_float
except ValueError:
return False
print([check(s) for s in string_list])
</code></pre>
<p>Giving:</p>
<pre><code>[True, True, False, False, False, False, True]
</code></pre>
<p>The trick is to cast the string to a float first and convert that into an integer (which will round the float if decimal part is not zero). After that you can compare the integer- and float-representation of the input in order to find out if the input was an integer or not.
I added <code>.replace()</code> in order to support both european and american/english decimal notation using commas.</p>
| 0 | 2016-07-21T11:23:21Z | [
"python",
"int",
"isinstance"
] |
how to check if a datetime data is in the index of a dataframe | 38,497,140 | <p>i have a dataframe <code>df_hq</code> showed as follow</p>
<p><a href="http://i.stack.imgur.com/gU4KH.png" rel="nofollow"><img src="http://i.stack.imgur.com/gU4KH.png" alt="enter image description here"></a></p>
<pre><code>df_hq.index.values
Out[26]:
array([('000001.SZ', Timestamp('2009-01-05 00:00:00')),
('000001.SZ', Timestamp('2009-01-06 00:00:00')),
('000001.SZ', Timestamp('2009-01-07 00:00:00')), ...,
('603999.SH', Timestamp('2016-03-30 00:00:00')),
('603999.SH', Timestamp('2016-03-31 00:00:00')),
('603999.SH', Timestamp('2016-04-01 00:00:00'))], dtype=object)
</code></pre>
<p>i want to know if the date in the index before i access data with the date.i try the following methodãNone of them workedã</p>
<pre><code>'000001.SZ' in df_hq.index
Out[27]: True
'2009-01-05 00:00:00' in df_hq.index
Out[28]: False
pandas.Timestamp('2009-01-05 00:00:00') in df_hq.index
Out[29]: False
datetime.date(2009,1,5) in df_hq.index
Out[30]: False
</code></pre>
<p>the date 2009-01-05 actually is in the index ,however ,the answer above is false
how to check if a date in the index?</p>
| 1 | 2016-07-21T07:01:07Z | 38,497,237 | <p>If this is an index with tuples, you can only search easily for specific tuples.</p>
<pre><code>('000001.SZ', Timestamp('2009-01-05 00:00:00')) in df_hq.index
</code></pre>
<p>I'd change it to a MultiIndex though for better functionality.</p>
<pre><code>df_hq.index = pd.MultiIndex.from_tuples(df_hq.index.values)
</code></pre>
<p>Then you can see if <code>Timestamp('2009-01-05 00:00:00')</code> is in the index regardless of the first part of the tuple:</p>
<pre><code>Timestamp('2009-01-05 00:00:00') in df_hq.index.levels[1]
</code></pre>
| 1 | 2016-07-21T07:05:41Z | [
"python",
"pandas"
] |
Python OpenCV - VideoCapture.release() won't work in Linux | 38,497,384 | <p>I'm using OpenCV 2.4.9 and Python 2.7.11.</p>
<p>I've written a small program that shows the camera output, and when pressing 'q', closes the camera but doesn't exit the application (for further work...).</p>
<p>The issue is that the webcam is not really released, the LED keeps on and when I try again to open it, it says that the resource is busy, until I completely exit the program.
It DOES work ok in Windows, though...</p>
<p>Here's the code:</p>
<pre><code>import cv2
import sys
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if frame is None:
print "BYE"
break
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
while True:
cv2.waitKey(1)
</code></pre>
<p>What am I missing? Is there a way to free the camera without exiting the program?
Thanks in advance</p>
| 1 | 2016-07-21T07:13:11Z | 38,498,216 | <p>The way to free the camera (without exiting) is indeed release(). I've tested your code in a Linux Mint 18 (64bit) environment running both OpenCV 2.4.13 and also OpenCV 3.1 with Python 2.7.12. There were no issues. </p>
<p>Here is a way for you to see what is going on in your code:</p>
<pre><code>import cv2
import sys
#print "Before cv2.VideoCapture(0)"
#print cap.grab()
cap = cv2.VideoCapture(0)
print "After cv2.VideoCapture(0): cap.grab() --> " + str(cap.grab()) + "\n"
while True:
ret, frame = cap.read()
if frame is None:
print "BYE"
break
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print "After breaking, but before cap.release(): cap.grab() --> " + str(cap.grab()) + "\n"
cap.release()
print "After breaking, and after cap.release(): cap.grab() --> " + str(cap.grab()) + "\n"
cap.open(0)
print "After reopening cap with cap.open(0): cap.grab() --> " + str(cap.grab()) + "\n"
cv2.destroyAllWindows()
while True:
cv2.waitKey(1)
</code></pre>
<p>You may want to think about reinstalling OpenCV on your system. I recommend checking out the awesome guides on PyImageSearch --> <a href="http://www.pyimagesearch.com/opencv-tutorials-resources-guides/" rel="nofollow">http://www.pyimagesearch.com/opencv-tutorials-resources-guides/</a></p>
<p><em>Let me know if this helps!</em></p>
| 2 | 2016-07-21T07:53:20Z | [
"python",
"linux",
"opencv",
"video-capture"
] |
Get correct brace grouping from string | 38,497,452 | <p>I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.</p>
<p>The brace grouping <code>{{ {} {} } } {{}} {{{}}}</code> should already be correct</p>
<p>How can I grab all the top-level braces, correctly grouped, as separate strings?</p>
| 0 | 2016-07-21T07:15:59Z | 38,497,614 | <p>Using the <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code> module</a>:</p>
<pre><code>In [1]: import regex
In [2]: braces = regex.compile(r"\{(?:[^{}]++|(?R))*\}")
In [3]: braces.findall("{{ {} {} } } {{}} {{{}}}")
Out[3]: ['{{ {} {} } }', '{{}}', '{{{}}}']
</code></pre>
| 1 | 2016-07-21T07:23:39Z | [
"python"
] |
Get correct brace grouping from string | 38,497,452 | <p>I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.</p>
<p>The brace grouping <code>{{ {} {} } } {{}} {{{}}}</code> should already be correct</p>
<p>How can I grab all the top-level braces, correctly grouped, as separate strings?</p>
| 0 | 2016-07-21T07:15:59Z | 38,497,689 | <p>If you don't want to install any extra modules simple function will do:</p>
<pre><code>def top_level(s):
depth = 0
start = -1
for i, c in enumerate(s):
if c == '{':
if depth == 0:
start = i
depth += 1
elif c == '}' and depth:
depth -= 1
if depth == 0:
yield s[start:i+1]
print(list(top_level('{{ {} {} } } {{}} {{{}}}')))
</code></pre>
<p>Output:</p>
<pre><code>['{{ {} {} } }', '{{}}', '{{{}}}']
</code></pre>
<p>It will skip invalid braces but could be easily modified to report an error when they are spotted.</p>
| 2 | 2016-07-21T07:26:57Z | [
"python"
] |
Get correct brace grouping from string | 38,497,452 | <p>I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.</p>
<p>The brace grouping <code>{{ {} {} } } {{}} {{{}}}</code> should already be correct</p>
<p>How can I grab all the top-level braces, correctly grouped, as separate strings?</p>
| 0 | 2016-07-21T07:15:59Z | 38,498,038 | <p><code>pyparsing</code> can be really helpful here. It will handle pathological cases where you have braces inside strings, etc. It might be a little tricky to do all of this work yourself, <em>but</em> fortunately, somebody (the author of the library) has already done the <a href="http://pyparsing.wikispaces.com/file/view/jsonParser.py" rel="nofollow">hard stuff for us...</a>. I'll reproduce the code here to prevent link-rot:</p>
<pre><code># jsonParser.py
#
# Implementation of a simple JSON parser, returning a hierarchical
# ParseResults object support both list- and dict-style data access.
#
# Copyright 2006, by Paul McGuire
#
# Updated 8 Jan 2007 - fixed dict grouping bug, and made elements and
# members optional in array and object collections
#
json_bnf = """
object
{ members }
{}
members
string : value
members , string : value
array
[ elements ]
[]
elements
value
elements , value
value
string
number
object
array
true
false
null
"""
from pyparsing import *
TRUE = Keyword("true").setParseAction( replaceWith(True) )
FALSE = Keyword("false").setParseAction( replaceWith(False) )
NULL = Keyword("null").setParseAction( replaceWith(None) )
jsonString = dblQuotedString.setParseAction( removeQuotes )
jsonNumber = Combine( Optional('-') + ( '0' | Word('123456789',nums) ) +
Optional( '.' + Word(nums) ) +
Optional( Word('eE',exact=1) + Word(nums+'+-',nums) ) )
jsonObject = Forward()
jsonValue = Forward()
jsonElements = delimitedList( jsonValue )
jsonArray = Group(Suppress('[') + Optional(jsonElements) + Suppress(']') )
jsonValue << ( jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL )
memberDef = Group( jsonString + Suppress(':') + jsonValue )
jsonMembers = delimitedList( memberDef )
jsonObject << Dict( Suppress('{') + Optional(jsonMembers) + Suppress('}') )
jsonComment = cppStyleComment
jsonObject.ignore( jsonComment )
def convertNumbers(s,l,toks):
n = toks[0]
try:
return int(n)
except ValueError, ve:
return float(n)
jsonNumber.setParseAction( convertNumbers )
</code></pre>
<p>Phew! That's a lot ... Now how do we use it? The general strategy here will be to scan the string for matches and then slice those matches out of the original string. Each scan result is a tuple of the form <code>(lex-tokens, start_index, stop_index)</code>. For our use, we don't care about the lex-tokens, just the start and stop. We could do: <code>string[result[1], result[2]]</code> and it would work. We can also do <code>string[slice(*result[1:])]</code> -- Take your pick.</p>
<pre><code>results = jsonObject.scanString(testdata)
for result in results:
print '*' * 80
print testdata[slice(*result[1:])]
</code></pre>
| 1 | 2016-07-21T07:44:03Z | [
"python"
] |
Python: How to override text area in form using CSS | 38,497,666 | <p>Hi I would like to ask on how to override the text area in form using CSS.
This is my codes:</p>
<p>forms.py</p>
<pre><code>description = forms.CharField(widget=forms.Textarea(attrs={'class': 'comment-control'}))
</code></pre>
<p>CSS:</p>
<pre><code>.comment-control {
background-color: #fff;
width: 830px;
height: 110px;
}
</code></pre>
<p>HTML</p>
<pre><code><form name="add_comment" id="comment-form" action="{% url 'comment:create' refId=refApp.id refApp=thisApp %}" method="post">
{% csrf_token %}
{{ form }}
</form>
</code></pre>
<p>I want to change the layout of the textarea of form using CSS but it is not being inherited, I appreciate your help. Thank you </p>
| 1 | 2016-07-21T07:25:49Z | 38,497,893 | <p>you should do something like this:</p>
<pre><code>description = forms.CharField(widget=forms.Textarea(attrs={'cols':'4', 'rows':'50'}))
</code></pre>
| 1 | 2016-07-21T07:37:26Z | [
"python",
"html",
"css"
] |
np.nanmax() over all except one axis - is this the best way? | 38,497,845 | <p>For a numpy array of dimension <code>n</code>, I'd like to apply np.nanmax() to <code>n-1</code> dimensions producing a 1 dimensional array of maxima, ignoring all values set to <code>np.nan</code>.</p>
<pre><code>q = np.arange(5*4*3.).reshape(3,4,5) % (42+1)
q[q%5==0] = np.nan
</code></pre>
<p>producing:</p>
<pre><code>array([[[ nan, 1., 2., 3., 4.],
[ nan, 6., 7., 8., 9.],
[ nan, 11., 12., 13., 14.],
[ nan, 16., 17., 18., 19.]],
[[ nan, 21., 22., 23., 24.],
[ nan, 26., 27., 28., 29.],
[ nan, 31., 32., 33., 34.],
[ nan, 36., 37., 38., 39.]],
[[ nan, 41., 42., nan, 1.],
[ 2., 3., 4., nan, 6.],
[ 7., 8., 9., nan, 11.],
[ 12., 13., 14., nan, 16.]]])
</code></pre>
<p>If I know ahead of time that I want to use the <strong>last axis</strong> as the remaining dimension, I can use the <code>-1</code> feature in <code>.reshape()</code> and do this:</p>
<pre><code>np.nanmax(q.reshape(-1, q.shape[-1]), axis=0)
</code></pre>
<p>which produces the result I want:</p>
<pre><code>array([ 12., 41., 42., 38., 39.])
</code></pre>
<p>However, suppose I don't know ahead of time <em>to which one of the axes</em> that I don't want to apply the maximum? Suppose I started with <code>n=4</code> dimensions, and wanted it to apply to all axes except the <code>m</code>th axis, which could be 0, 1, 2, or 3? Would have to actually use a conditional if-elif-else ?</p>
<p>Is there something that would work like a hypothetical <code>exeptaxis=m</code>?</p>
| 1 | 2016-07-21T07:35:49Z | 38,498,357 | <p>The <code>axis</code> argument of <code>nanmax</code> can be a tuple of axes over which the maximum is computed. In your case, you want that tuple to contain all the axes except <code>m</code>. Here's one way you could do that:</p>
<pre><code>In [62]: x
Out[62]:
array([[[[ 4., 3., nan, nan],
[ 0., 2., 2., nan],
[ 4., 5., nan, 3.],
[ 2., 0., 3., 1.]],
[[ 2., 0., 0., 1.],
[ nan, 3., 0., nan],
[ 0., 1., nan, 2.],
[ 5., 4., 0., 1.]],
[[ 4., 0., 2., 0.],
[ 4., 0., 4., 5.],
[ 3., 4., 1., 0.],
[ 5., 3., 4., 3.]]],
[[[ 2., nan, 6., 4.],
[ 3., 1., 2., nan],
[ 5., 4., 1., 0.],
[ 2., 6., 0., nan]],
[[ 4., 1., 4., 2.],
[ nan, 1., 5., 5.],
[ 2., 0., 1., 1.],
[ 6., 3., 6., 5.]],
[[ 1., 0., 0., 1.],
[ 1., nan, 2., nan],
[ 3., 4., 0., 5.],
[ 1., 6., 2., 3.]]]])
In [63]: m = 0
In [64]: np.nanmax(x, axis=tuple(i for i in range(x.ndim) if i != m))
Out[64]: array([ 5., 6.])
</code></pre>
| 1 | 2016-07-21T08:01:02Z | [
"python",
"numpy"
] |
How to reshape an array | 38,497,892 | <p>I want to create 5*3 array like below without typing it explicitly. </p>
<pre><code>[[1, 6, 11],
[2, 7, 12],
[3, 8, 13],
[4, 9, 14],
[5, 10, 15]]
</code></pre>
<p>I used write following codes.</p>
<pre><code>np.arange(1, 16).T.reshape((5,3))
</code></pre>
<p>but it shows</p>
<pre><code>array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
</code></pre>
<p>How can I order numbers in ascending order so that it becomes the first array? </p>
| 2 | 2016-07-21T07:37:25Z | 38,498,030 | <p>That's what you are looking for:</p>
<pre><code>np.arange(1, 16).reshape((3,5)).T
</code></pre>
<p>In fact, in order: </p>
<ul>
<li><code>np.arange(1,16)</code> will return evenly spaced values within the interval 1 to 6 (default step size is 1) [<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html</a> ]; </li>
<li><code>.reshape((3,5))</code> is giving new shape to the previously formed array [<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html</a> ]. The new array will have 3 rows and 5 columns; </li>
<li><code>.T</code> will transpose the previously reshaped array [<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.T.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.T.html</a> ]</li>
</ul>
| 5 | 2016-07-21T07:43:37Z | [
"python",
"numpy"
] |
How to reshape an array | 38,497,892 | <p>I want to create 5*3 array like below without typing it explicitly. </p>
<pre><code>[[1, 6, 11],
[2, 7, 12],
[3, 8, 13],
[4, 9, 14],
[5, 10, 15]]
</code></pre>
<p>I used write following codes.</p>
<pre><code>np.arange(1, 16).T.reshape((5,3))
</code></pre>
<p>but it shows</p>
<pre><code>array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
</code></pre>
<p>How can I order numbers in ascending order so that it becomes the first array? </p>
| 2 | 2016-07-21T07:37:25Z | 38,526,677 | <p>For completeness, it is worth noticing that there is no need to transpose the array as suggested in the currently accepted answer. You just need to invoke <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html#numpy.reshape" rel="nofollow"><code>numpy.reshape</code></a> with the following arguments:</p>
<ul>
<li><p><code>(5, 3)</code>, which corresponds to the positional parameter <code>newshape</code>, i.e. the shape of the array you wish to create.</p></li>
<li><p><code>order='F'</code>. The default value is <code>'C'</code>.</p>
<p>Here is an excerpt from the <strong>docs</strong> on the <code>order</code> optional parameter:</p>
<blockquote>
<p>âCâ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. âFâ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. </p>
</blockquote></li>
</ul>
<p>By doing so, the numbers are arranged column-wise:</p>
<pre><code>In [45]: np.arange(1, 16).reshape((5, 3), order='F')
Out[45]:
array([[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14],
[ 5, 10, 15]])
</code></pre>
| 1 | 2016-07-22T12:39:12Z | [
"python",
"numpy"
] |
Parse json array with out object in python | 38,497,905 | <p>I have a below json array file with out object. How do I parse it in python. I would like to construct all dataNomTime into a array.</p>
<pre><code>[{
"id": 8916,
"objectPaths": ["/thmo/help"],
"dataTime": 1464961203,
"dataNomTime": 1464818400,
"dataEndTime": 1464904800,
"attribs": null
}, {
"id": 8917,
"objectPaths": ["/thmo/help"],
"dataTime": 1464961203,
"dataNomTime": 1464818400,
"dataEndTime": 1464904800,
"attribs": null
}]
</code></pre>
<p>My code </p>
<pre><code>import json
from pprint import pprint
with open('file.json') as data_file:
data = json.load(data_file)
#pprint(data)
pprint(data["dataNomTime"])
</code></pre>
<p>Exception </p>
<pre><code> pprint(data["dataNomTime"])
TypeError: list indices must be integers, not str
</code></pre>
| 0 | 2016-07-21T07:37:50Z | 38,497,968 | <p>Since you have a list of dictionaries, <code>data</code> is a list and should be treating as a list.</p>
<p>If you want to extract all the <code>dataNomTime</code> you should do:</p>
<pre><code>nom_times_list = []
for obj in data:
nom_times_list.append(obj['dataNomTime'])
</code></pre>
<p>Or as a list comprehension:</p>
<pre><code>nom_times_list = [obj['dataNomTime'] for obj in data]
</code></pre>
| 3 | 2016-07-21T07:40:59Z | [
"python"
] |
Capturing image from Webcam Using Python on Windows | 38,497,924 | <p>the code i am using now is :- </p>
<pre><code>from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')
</code></pre>
<p>using py 2.7
and imported pygame and all and videocapture
i am getting this error in pycharm :- </p>
<pre><code>C:\Python27\python.exe F:/Xtraz/Orion/Key-Logger.py
Traceback (most recent call last):
File "F:/Xtraz/Orion/Key-Logger.py", line 3, in <module>
cam.saveSnapshot('image.jpg')
File "C:\Python27\lib\VideoCapture.py", line 200, in saveSnapshot
self.getImage(timestamp, boldfont, textpos).save(filename, **keywords)
File "C:\Python27\lib\VideoCapture.py", line 138, in getImage
im = Image.fromstring('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
File "C:\Users\admin\AppData\Roaming\Python\Python27\site-packages\PIL\Image.py", line 2080, in fromstring
"Please call frombytes() instead.")
NotImplementedError: fromstring() has been removed. Please call frombytes() instead.
Process finished with exit code 1
</code></pre>
<p>the webcam LED lights onn , and then switches off immediately .
or help me with any other code and library that works well with py 2.7 and pycharm on windows only ! and i just want to save the image , not display it !</p>
| 0 | 2016-07-21T07:38:48Z | 38,498,821 | <p>You might want to downgrade you version of PIL, it seems like VideoCapture hasn't been updated for a while and is still relying on outdated versions of PIL.</p>
<p>PIL 2.x seems to have a working <code>fromstring</code> method: <a href="https://github.com/python-pillow/Pillow/blob/2.9.0/PIL/Image.py#L750" rel="nofollow">https://github.com/python-pillow/Pillow/blob/2.9.0/PIL/Image.py#L750</a></p>
<p>Otherwise you can try to change the line 138 in <code>VideoCapture.py</code> from <code>im = Image.fromstring(...)</code> to <code>im = Image.frombytes(...)</code>; hopefully it's the only thing that prevents it from working.</p>
<h2>Solution #1: Downgrade PIL</h2>
<p>If you're using <code>pip</code>, you can just uninstall you current version using <code>pip uninstall Pillow</code> and then install an older one using <code>pip install Pillow==2.9.0</code> (<code>Pillow</code> is a fork of PIL, PIL being basically dead).</p>
<h2>Solution #2: Update VideoCatpure</h2>
<p>Open the file <code>C:\Python27\lib\VideoCapture.py</code> and go to line 138. You should have something like that:</p>
<pre><code>im = Image.fromstring('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
</code></pre>
<p>Replace this line with this:</p>
<pre><code>im = Image.frombytes('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
</code></pre>
| 0 | 2016-07-21T08:22:31Z | [
"python",
"image",
"save",
"webcam",
"capture"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.