title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
How to get the Incorrectly clustered instances after ClusterEvaluation through the latest weka-python-wrapper 0.3.8? | 39,818,194 | <p>I'm learning the Clustering of Weka and trying to get the "Incorrectly clustered instances" after 'ClusterEvaluation' with the python-weka-wrapper 0.3.8 (python 2.7).</p>
<p>Currently, I have the class attribute in the input arff file, build the data model successfully, and can get the output of num of clusters & cluster_assignments & Clustered Instances of each cluster in the training set ...etc (which all followed the example of python-weka-wrapper-examples/src/wekaexamples/clusterers/clusterers.py)</p>
<p>However, I want to know whether each instance clustered correctly as the labeled class of input arff or not, and also the ratio of incorrectly clustered instances (just like the output result from Weka GUI).</p>
<p>I'm not sure where to set the options like <a href="http://i.stack.imgur.com/HhAAO.png" rel="nofollow">this</a> from Weka GUI v3.8.0 /Explore/Cluster/Cluster mode/Classes to Clusters evaluation before I run the weka.clusterers.ClusterEvaluation module.</p>
<p>Is there anyone know how to do the mapClasses(<a href="http://weka.sourceforge.net/doc.stable/weka/clusterers/ClusterEvaluation.html#mapClasses-int-int-int:A:A-int:A-double:A-double:A-int-" rel="nofollow">http://weka.sourceforge.net/doc.stable/weka/clusterers/ClusterEvaluation.html#mapClasses-int-int-int:A:A-int:A-double:A-double:A-int-</a>) via python-weka-wrapper?<br/> Or anyway to get the ratio of clustered instances result v.s labeled class attribute?</p>
<p>Appreciate!</p>
| 0 | 2016-10-02T14:50:28Z | 39,821,203 | <p>If your <code>Instances</code> object for testing has a class attribute set when you perform cluster evaluation using the <code>ClusterEvaluation</code> class, you can use the <code>classes_to_clusters</code> property to obtain the mapping that has been collected while evaluating the clusterer. The equivalent Java method is <a href="http://weka.sourceforge.net/doc.dev/weka/clusterers/ClusterEvaluation.html#getClassesToClusters--" rel="nofollow">ClusterEvaluation.getClassesToClusters</a>.
The <code>mapClasses</code> method hasn't been exposed as Python function.</p>
| 0 | 2016-10-02T20:10:21Z | [
"python",
"weka"
]
|
how to .writerow() to only 1 row in csv file ? | 39,818,202 | <p>guys currently in my code it changes the 3rd row but for all rows , I want it to only change the row with the entered GTIN by the user.</p>
<p>current code :</p>
<pre><code>file=open("stock.csv")
stockfile= csv.reader(file)
for line in stockfile:
if GTIN in line:
currentstock= line[2]
targetstock = line[3]
newstock = (int(currentstock) - int(Quantity))
currentstock = str(currentstock)
targetstock = str(targetstock)
newstock = str(newstock)
if newstock < targetstock :
import csv
reader = csv.reader(open('stock.csv',"r"))
new = csv.writer(open('out.csv',"w"))
for line in reader:
new.writerow([line[0], line[1], newstock , line[3]])
</code></pre>
<p>output in file ( it changes all numbers in 3rd column):</p>
<pre><code>86947367,banana,1,40
78364721,apple,1,20
35619833,orange,1,30
84716491,sweets,1,90
46389121,chicken,1,10
</code></pre>
<p>How can I only chnage the row with the GTIN the user enters ?</p>
| 0 | 2016-10-02T14:51:16Z | 39,818,534 | <p>use the <code>csv</code> module:
<a href="https://docs.python.org/3/library/csv.html" rel="nofollow">https://docs.python.org/3/library/csv.html</a></p>
<p>It has a <code>csv.reader()</code> and <code>csv.writer()</code>. Read the file into memory, iterate over it doing calcs/replacements, then write each row to a new list. Finally, generate a new data file to replace the old one.</p>
| 1 | 2016-10-02T15:27:26Z | [
"python",
"file",
"python-3.x",
"csv"
]
|
how to .writerow() to only 1 row in csv file ? | 39,818,202 | <p>guys currently in my code it changes the 3rd row but for all rows , I want it to only change the row with the entered GTIN by the user.</p>
<p>current code :</p>
<pre><code>file=open("stock.csv")
stockfile= csv.reader(file)
for line in stockfile:
if GTIN in line:
currentstock= line[2]
targetstock = line[3]
newstock = (int(currentstock) - int(Quantity))
currentstock = str(currentstock)
targetstock = str(targetstock)
newstock = str(newstock)
if newstock < targetstock :
import csv
reader = csv.reader(open('stock.csv',"r"))
new = csv.writer(open('out.csv',"w"))
for line in reader:
new.writerow([line[0], line[1], newstock , line[3]])
</code></pre>
<p>output in file ( it changes all numbers in 3rd column):</p>
<pre><code>86947367,banana,1,40
78364721,apple,1,20
35619833,orange,1,30
84716491,sweets,1,90
46389121,chicken,1,10
</code></pre>
<p>How can I only chnage the row with the GTIN the user enters ?</p>
| 0 | 2016-10-02T14:51:16Z | 39,820,470 | <p>I answered one of your other questions before you were using csvreader but it looks like it got deleted. But the principle is the same. As I stated in one of the comments, I don't think you should keep reopening/rereading <code>stock.txt</code>. Just read it line by line then write line by line to an output file:</p>
<pre><code>stock_number = input('Enter the stock number: ')
new_item = input('Enter item to add to above stock listing: ')
lines = []
with open('stock.txt', 'r') as infile:
for line in infile:
lines.append(line)
# can call this 'output.txt' if you don't want to overwrite original
with open('stock.txt', 'w') as outfile:
for line in lines:
if stock_number in line:
# strip newline, add new item, add newline
line = '{},{}\n'.format(line.strip(), new_item)
outfile.write(line)
</code></pre>
<p>Edit: here it is with <code>csv</code> module instead. This makes it a little more straightforward because the <code>csv</code> module gives you a list of strings for each line, then you can add to or modify them as desired. Then you can just write the list back line by line, without worrying about newlines or delimiters. </p>
<pre><code>import csv
stock_number = input('Enter the stock number: ')
new_item = input('Enter item to add to above stock listing: ')
lines = []
with open('stock.txt', 'r') as infile:
for line in csv.reader(infile):
lines.append(line)
# change this to 'stock.txt' to overwrite original file
with open('output.txt', 'w') as outfile:
writer = csv.writer(outfile)
for line in lines:
if stock_number in line:
line.append(new_item)
writer.writerow(line)
</code></pre>
<p>Also you shouldn't really <code>import</code> anything in the middle of the code like that. Imports generally go at the top of your file. </p>
| 0 | 2016-10-02T18:51:44Z | [
"python",
"file",
"python-3.x",
"csv"
]
|
How to save multiple output in multiple file where each file has a different title coming from an object in python? | 39,818,241 | <p>I'm scraping rss feed from a web site (<a href="http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&type=rss" rel="nofollow">http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&type=rss</a>).
I have wrote down a script to extract and purifie the text from every of the feed. My main problem is to save each text of each item in a different file, I also need to name each file with it's proper title exctractet from the item.
My code is:</p>
<pre><code>for item in myFeed["items"]:
time_structure=item["published_parsed"]
dt = datetime.fromtimestamp(mktime(time_structure))
if dt>t:
link=item["link"]
response= requests.get(link)
doc=Document(response.text)
doc.summary(html_partial=False)
# extracting text
h = html2text.HTML2Text()
# converting
h.ignore_links = True #ignoro i link
h.skip_internal_links=True #ignoro i link esterni
h.inline_links=True
h.ignore_images=True #ignoro i link alle immagini
h.ignore_emphasis=True
h.ignore_anchors=True
h.ignore_tables=True
testo= h.handle(doc.summary()) #testo estratto
s = doc.title()+"."+" "+testo #contenuto da stampare nel file finale
tit=item["title"]
# save each file with it's proper title
with codecs.open("testo_%s", %tit "w", encoding="utf-8") as f:
f.write(s)
f.close()
</code></pre>
<p>The error is:</p>
<pre><code>File "<ipython-input-57-cd683dec157f>", line 34 with codecs.open("testo_%s", %tit "w", encoding="utf-8") as f:
^
SyntaxError: invalid syntax
</code></pre>
| 0 | 2016-10-02T14:54:58Z | 39,818,526 | <p>You need to put the comma after <code>%tit</code></p>
<p>should be:</p>
<pre><code>#save each file with it's proper title
with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
f.close()
</code></pre>
<p>However, if your file name has invalid characters it will return an error (i.e <code>[Errno 22]</code>)</p>
<p>You can try this code:</p>
<pre><code>...
tit = item["title"]
tit = tit.replace(' ', '').replace("'", "").replace('?', '') # Not the best way, but it could help for now (will be better to create a list of stop characters)
with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
f.close()
</code></pre>
<p>Other way using <code>nltk</code>:</p>
<pre><code>from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tit = item["title"]
tit = tokenizer.tokenize(tit)
tit = ''.join(tit)
with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
f.close()
</code></pre>
| 0 | 2016-10-02T15:26:58Z | [
"python",
"rss",
"feed"
]
|
How to save multiple output in multiple file where each file has a different title coming from an object in python? | 39,818,241 | <p>I'm scraping rss feed from a web site (<a href="http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&type=rss" rel="nofollow">http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&type=rss</a>).
I have wrote down a script to extract and purifie the text from every of the feed. My main problem is to save each text of each item in a different file, I also need to name each file with it's proper title exctractet from the item.
My code is:</p>
<pre><code>for item in myFeed["items"]:
time_structure=item["published_parsed"]
dt = datetime.fromtimestamp(mktime(time_structure))
if dt>t:
link=item["link"]
response= requests.get(link)
doc=Document(response.text)
doc.summary(html_partial=False)
# extracting text
h = html2text.HTML2Text()
# converting
h.ignore_links = True #ignoro i link
h.skip_internal_links=True #ignoro i link esterni
h.inline_links=True
h.ignore_images=True #ignoro i link alle immagini
h.ignore_emphasis=True
h.ignore_anchors=True
h.ignore_tables=True
testo= h.handle(doc.summary()) #testo estratto
s = doc.title()+"."+" "+testo #contenuto da stampare nel file finale
tit=item["title"]
# save each file with it's proper title
with codecs.open("testo_%s", %tit "w", encoding="utf-8") as f:
f.write(s)
f.close()
</code></pre>
<p>The error is:</p>
<pre><code>File "<ipython-input-57-cd683dec157f>", line 34 with codecs.open("testo_%s", %tit "w", encoding="utf-8") as f:
^
SyntaxError: invalid syntax
</code></pre>
| 0 | 2016-10-02T14:54:58Z | 39,820,854 | <p>First off, you misplaced the comma, it should be after the <code>%tit</code> not before.</p>
<p>Secondly, you don't need to close the file because the <code>with</code> statement that you use, does it automatically for you. And where did the codecs came from? I don't see it anywhere else.... anyway, the correct <code>with</code> statement would be:</p>
<pre><code>with open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
</code></pre>
| 0 | 2016-10-02T19:34:03Z | [
"python",
"rss",
"feed"
]
|
How to make indexing work with ItemLoader's add_xpath method | 39,818,248 | <p>I'm trying to rewrite this piece of code to use <code>ItemLoader</code> class:</p>
<pre><code>import scrapy
from ..items import Book
class BasicSpider(scrapy.Spider):
...
def parse(self, response):
item = Book()
# notice I only grab the first book among many there are on the page
item['title'] = response.xpath('//*[@class="link linkWithHash detailsLink"]/@title')[0].extract()
return item
</code></pre>
<p>The above works perfectly well. And now the same with <code>ItemLoader</code>:</p>
<pre><code>from scrapy.loader import ItemLoader
class BasicSpider(scrapy.Spider):
...
def parse(self, response):
l = ItemLoader(item=Book(), response=response)
l.add_xpath('title', '//*[@class="link linkWithHash detailsLink"]/@title'[0]) # this does not work - returns an empty dict
# l.add_xpath('title', '//*[@class="link linkWithHash detailsLink"]/@title') # this of course work but returns every book title there is on page, not just the first one which is required
return l.load_item()
</code></pre>
<p>So I only want to grab the first book title, how do I achieve that?</p>
| 0 | 2016-10-02T14:55:43Z | 39,819,264 | <p>A problem with your code is that Xpath uses one-based indexing. Another problem is that the index bracket should be inside the string you pass to the add_xpath method.</p>
<p>So the correct code would look like this:</p>
<pre><code>l.add_xpath('title', '(//*[@class="link linkWithHash detailsLink"]/@title)[1]')
</code></pre>
| 0 | 2016-10-02T16:43:13Z | [
"python",
"xpath",
"scrapy"
]
|
Why don't string variables update when they are changed | 39,818,267 | <p>Say we have some code like so :</p>
<pre><code>placehold = "6"
string1 = "this is string one and %s" % placehold
print string1
placehold = "7"
print string1
</code></pre>
<p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was changed to 7, so why does it not dynamically reflect in the string?</p>
<p>Also, would you be able to suggest a way to make the string return with 7?</p>
<p>Thank you</p>
| 0 | 2016-10-02T14:58:07Z | 39,818,297 | <p><code>string1</code> will use whatever value of <code>placehold</code> existed at the time <code>string1</code> was declared. In your example, that value happens to be <code>"6"</code>. To get <code>string1</code> to "return with 7" you would need to reassign it (<code>string1 = "this is string one and %s" % placehold</code>) after changing the value of <code>placehold</code>.</p>
| 1 | 2016-10-02T15:01:36Z | [
"python",
"string"
]
|
Why don't string variables update when they are changed | 39,818,267 | <p>Say we have some code like so :</p>
<pre><code>placehold = "6"
string1 = "this is string one and %s" % placehold
print string1
placehold = "7"
print string1
</code></pre>
<p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was changed to 7, so why does it not dynamically reflect in the string?</p>
<p>Also, would you be able to suggest a way to make the string return with 7?</p>
<p>Thank you</p>
| 0 | 2016-10-02T14:58:07Z | 39,818,302 | <p>Because you have already assigned a value to that variable once you execute the statement.</p>
<p>It sounds like you'd rather need a function such as:</p>
<pre><code>def f(placehold):
return "this is string one and %s" % placehold
</code></pre>
<p>Now you can <code>print(f("7"))</code> to achieve the desired functionality.</p>
| 4 | 2016-10-02T15:02:44Z | [
"python",
"string"
]
|
Why don't string variables update when they are changed | 39,818,267 | <p>Say we have some code like so :</p>
<pre><code>placehold = "6"
string1 = "this is string one and %s" % placehold
print string1
placehold = "7"
print string1
</code></pre>
<p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was changed to 7, so why does it not dynamically reflect in the string?</p>
<p>Also, would you be able to suggest a way to make the string return with 7?</p>
<p>Thank you</p>
| 0 | 2016-10-02T14:58:07Z | 39,818,365 | <p>When you do:</p>
<pre><code>string1 = "this is string one and %s" % placehold
</code></pre>
<p>You are creating a string <code>string1</code> with <code>%s</code> replaced by the value of <code>placehold</code> On later changing the value of <code>placehold</code> it won't have any impact on <code>string1</code> as string does not hold the dynamic property of variable. In order to reflect the string with changed value, you have to again re-assign the string.</p>
<p>Alternatively, you may use <code>.format()</code> as:</p>
<pre><code>string1 = "this is string one and {}"
placeholder = 6
print string1.format(placeholder)
# prints: this is string one and 6
placeholder = 7
print string1.format(placeholder)
# prints: this is string one and 7
</code></pre>
| 3 | 2016-10-02T15:08:29Z | [
"python",
"string"
]
|
Why don't string variables update when they are changed | 39,818,267 | <p>Say we have some code like so :</p>
<pre><code>placehold = "6"
string1 = "this is string one and %s" % placehold
print string1
placehold = "7"
print string1
</code></pre>
<p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was changed to 7, so why does it not dynamically reflect in the string?</p>
<p>Also, would you be able to suggest a way to make the string return with 7?</p>
<p>Thank you</p>
| 0 | 2016-10-02T14:58:07Z | 39,818,453 | <p>Strings are immutable and can't be changed, but what you're trying to do doesn't work with mutable objects either, so mutability (or lack of it) is something of a red herring here.</p>
<p>The real reason is that Python does not work like Excel. Objects do not remember all the operations that have been performed on them, and then re-do those operations when you change any of the information that went into them. For Python to work that way, the language would need to retain either every state that every object had ever been in, or all the operations that had ever been performed on them along with their parameters. Either would make your programs use a lot more memory and run much more slowly. On top of that, suppose you used <code>string1</code> in another expression: that value, too, would need to be updated. In Python 3, <code>print()</code> is a function; should it be called again when the variable printed is changed?</p>
<p>There are languages that work like that, to some extent, but Python isn't one of them. Unless you explicitly arrange things otherwise (by writing and calling a function), Python evaluates an expression once and uses that exact result going forward.</p>
<p>In fact, what you want isn't even possible in Python. When you do string interpolation (the <code>%</code> operation), the code that does it sees only the value of what you're interpolating. It doesn't know that the <code>"6"</code> is coming from a variable called <code>placehold</code>. Therefore it couldn't change the string later even if it wanted to, because there's no way for it to know that there's any relationship between <code>placehold</code> and <code>string1</code>. (Also, consider that you needn't be interpolating a single variable: it could be an expression such as <code>placehold + "0"</code>. So Python would need to remember the entire expression, not just the variable name, to re-evaluate it later.)</p>
<p>You can write your own string subclass to provide the specific behavior you want:</p>
<pre><code>class UpdatingString(str):
def __str__(self):
return self % placehold
placehold = "6"
string1 = UpdatingString("this is string one and %s")
print(string1)
placehold = "7"
print(string1)
</code></pre>
<p>But this is fraught with scoping issues (basically, the class needs to be able to see <code>placehold</code>, which means that variable and the class need to be defined in the same function or in the global scope). Also, if you use this special string in an operation with another string, say concatenation, it will almost certainly cease being special. To fix these issues is possible, but... hairy. I don't recommend it.</p>
| 2 | 2016-10-02T15:18:34Z | [
"python",
"string"
]
|
/bin/sh: 1: python: not found while running docker container | 39,818,273 | <p>This is my docker file</p>
<pre><code>FROM ubuntu:14.04
ADD ./file.py ./
CMD python file.py
</code></pre>
<p>I am building using below command: </p>
<pre><code>docker build -t myimage .
</code></pre>
<p>And running using this: </p>
<pre><code>docker run myimage
</code></pre>
<p>And then getting below error after running:</p>
<pre><code>/bin/sh: 1: python: not found
</code></pre>
<p>What should I do so the file file.py will be executed using python ? </p>
| 0 | 2016-10-02T14:59:10Z | 39,818,905 | <p>Use <a href="https://hub.docker.com/_/python" rel="nofollow">official Python Docker image</a>:</p>
<pre><code>FROM python:3.5
COPY ./file.py ./
CMD python file.py
</code></pre>
| 1 | 2016-10-02T16:04:07Z | [
"python",
"docker"
]
|
Python Numpy : operands could not be broadcast together with shapes when producting matrix | 39,818,358 | <pre><code>import numpy as np
def grams(A):
(m,n) = A.shape
Q = A
R = np.zeros((n,n))
for i in range(0,n-1):
R[i,i] = np.linalg.norm(Q[:,i])
Q[:,i] =Q[:,i]/R[i,i]
R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
Q[:,i+1:n] = Q[:,i+1:n+1]-Q[:,i]*R[i,i+1:n]
R[n,n] = np.linalg.norm(Q[:,n])
Q[:,n] = Q[:,n]/R[n,n]
return Q, R
A = np.array( [[1,1,2],[4,3,1],[1,6,6]] )
print grams(A)
</code></pre>
<p>The error is on the line </p>
<pre><code>R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
</code></pre>
<p>The error is </p>
<pre><code>ValueError:
operands could not be broadcast together with shapes (3,) (3,2)
</code></pre>
| 0 | 2016-10-02T15:08:07Z | 39,818,677 | <p>Asterisk <code>*</code> performs <strong>elementwise multiplication</strong> in <code>numpy</code>. Your code reads:</p>
<pre><code>R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
</code></pre>
<p><code>np.transpose(Q[:,i])</code> has dimensions <code>(3, 1)</code> and <code>Q[:,i+1:n]</code> <code>(3, 2)</code>, so they cannot be elementwise multiplied together as dimensions don't match.</p>
<p>I suspect you may want to multiply <code>np.transpose(Q[:,i])</code> and <code>Q[:,i+1:n]</code> using <strong>matrix multiplication</strong>, in that case you can use <code>numpy.dot</code> as follows:</p>
<pre><code>R[i,i+1:n] = np.dot(np.transpose(Q[:,i]), Q[:,i+1:n])
</code></pre>
<p>but dimensions don't match for matrix multiplication either, so your algorithm's implementation is probably wrong somewhere before that line.</p>
| 0 | 2016-10-02T15:42:03Z | [
"python",
"numpy"
]
|
Python Numpy : operands could not be broadcast together with shapes when producting matrix | 39,818,358 | <pre><code>import numpy as np
def grams(A):
(m,n) = A.shape
Q = A
R = np.zeros((n,n))
for i in range(0,n-1):
R[i,i] = np.linalg.norm(Q[:,i])
Q[:,i] =Q[:,i]/R[i,i]
R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
Q[:,i+1:n] = Q[:,i+1:n+1]-Q[:,i]*R[i,i+1:n]
R[n,n] = np.linalg.norm(Q[:,n])
Q[:,n] = Q[:,n]/R[n,n]
return Q, R
A = np.array( [[1,1,2],[4,3,1],[1,6,6]] )
print grams(A)
</code></pre>
<p>The error is on the line </p>
<pre><code>R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
</code></pre>
<p>The error is </p>
<pre><code>ValueError:
operands could not be broadcast together with shapes (3,) (3,2)
</code></pre>
| 0 | 2016-10-02T15:08:07Z | 39,819,467 | <p>Lets recreate this in a small case</p>
<pre><code>In [105]: n=4
In [106]: m,n=2,4
In [107]: Q=np.arange(m*n).reshape(m,n)
In [108]: R=np.zeros((n,n))
</code></pre>
<p>So for one step, the target is a (3,) slot in <code>R</code></p>
<pre><code>In [109]: i=0
In [110]: R[i,i+1:n]
Out[110]: array([ 0., 0., 0.])
In [111]: Q[:,i]
Out[111]: array([0, 4])
In [112]: Q[:,i+1:n]
Out[112]:
array([[1, 2, 3],
[5, 6, 7]])
</code></pre>
<p>One array is (m,), the other (m,3). The only way to combine them and produce (3,) is with a <code>dot</code> (using last/only dim of one, and 2nd last dim of the other):</p>
<pre><code>In [113]: np.dot(Q[:,i],Q[:,i+1:n])
Out[113]: array([20, 24, 28])
</code></pre>
| 1 | 2016-10-02T17:04:41Z | [
"python",
"numpy"
]
|
How to reindex a python array to move polyline starting point? | 39,818,381 | <p>I have a python array defining the points for a polyline P(x,y,z). I need to align the points with points on another polyline - to be precise, the point with index 0 on polyline 1 should be close to the point with index 0 of the second polyline. </p>
<p>Think of a polyline circle. How can I move the "index number" or rather rearrange the points in an array so that the index number of the points moves clockwise or counter clockwise by x points?</p>
<p>Klausb</p>
| 0 | 2016-10-02T15:10:52Z | 39,820,075 | <p>To shift to left by x points(assuming x is less than the length of array):</p>
<pre><code>newPolyline = polyline[x:] + polyline[:x]
</code></pre>
<p>To shift right:</p>
<pre><code>newPolyline = polyline[len(polyline) - x:] + polyline[:len(polyline) - x]
</code></pre>
| 0 | 2016-10-02T18:10:48Z | [
"python",
"arrays",
"numpy"
]
|
Make view accessible only through redirect and from only one view in Django | 39,818,402 | <p>How do I make a view to be only accessible through <em>redirect</em> and from a only a particular <em>view</em>?</p>
<p><strong>urls.py</strong>:</p>
<pre><code>#Assuming namespace = 'myApp'
url(r'^redarekt/$', views.redarekt, name='redarekt'),
url(r'^reciva/$', views.reciva, name='reciva'),
</code></pre>
<p><strong>views.py</strong>:</p>
<pre><code>@login_required()
def redarekt(request):
if request.user.is_authenticated() and request.user.is_active:
return HttpResponseRedirect(reverse('myApp:reciva'))
@login_required()
def reciva(request):
if request.user.is_authenticated() and request.user.is_active:
#CHECK IF IT IS A REDIRECT AND COMING FROM redarekt
execute(request)
raise Http404
raise Http404
</code></pre>
<p>How do I make <code>reciva</code> to be only accessible through <em>redirect</em> and from a only <code>redarekt</code>?</p>
| 0 | 2016-10-02T15:11:52Z | 39,819,628 | <p>You can use <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/#using-sessions-in-views" rel="nofollow"><code>request.session</code></a></p>
<pre><code>@login_required()
def redarekt(request):
if request.user.is_authenticated() and request.user.is_active:
request.session['pp_redarekt'] = True
return HttpResponseRedirect(reverse('myApp:reciva'))
@login_required()
def reciva(request):
if request.user.is_authenticated() and request.user.is_active:
if 'pp_redarekt' in request.session:
execute(request)
del request.session['pp_redarekt']
raise Http404
raise Http404
</code></pre>
<p><code>'pp_redarekt'</code> stands for Previous Page 'redarekt'</p>
<p>So basically, before redirecting to <code>reciva(request)</code> view you're setting adding session key, that says that previous page was <code>redarekt</code>. When you handle your request in <code>reciva</code> view, you are deleting that key, so user won't be able to enter <code>reciva</code> twice or more.</p>
<p>But for doing so, you need to setup your sessions. <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/" rel="nofollow">Guide and docs</a></p>
| 1 | 2016-10-02T17:24:06Z | [
"python",
"django"
]
|
TypeError: sequence item 1: expected a bytes-like object, str found | 39,818,425 | <p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p>
<pre><code>with open('/Users/some/directory/title.txt', 'rb')as f:
text=f.read()
letters_only = re.sub(b"[^a-zA-Z]", " ", text)
words = letters_only.lower().split()
print(words)
</code></pre>
<p>But I am getting an error:</p>
<pre><code>TypeError: sequence item 1: expected a bytes-like object, str found
</code></pre>
<p>at the line: <code>letters_only = re.sub(b"[^a-zA-Z]", " ", text)</code></p>
<p>But, I am using <code>b''</code> to make output as byte type, below is a sample of the text file:</p>
<pre><code>Destroy-Oh-Boy!!
!!Fuck_you!!
!!Que_Corra_La_Voz!!
!!_(chess)
!!_(disambiguation)
!'O!Kung
!'O!Kung_language
!'O-!khung_language
!337$P34K
!=
!?
!?!
!?Revolution!?
!?_(chess)
!A_Luchar!
!Action_Pact!
!Action_pact!
!Adios_Amigos!
!Alabadle!
!Alarma!
!Alarma!_(album)
!Alarma!_(disambiguation)
!Alarma!_(magazine)
!Alarma!_Records
!Alarma!_magazine
!Alfaro_Vive,_Carajo!
!All-Time_Quarterback!
!All-Time_Quarterback!_(EP)
!All-Time_Quarterback!_(album)
!Alla_tu!
!Amigos!
!Amigos!_(Arrested_Development_episode)
!Arriba!_La_Pachanga
!Ask_a_Mexican!
!Atame!
!Ay,_Carmela!_(film)
!Ay,_caramba!
!BANG!
!Bang!
!Bang!_TV
!Basta_Ya!
!Bastardos!
!Bastardos!_(album)
!Bastardos_en_Vivo!
!Bienvenido,_Mr._Marshall!
!Ciauetistico!
!Ciautistico!
!DOCTYPE
!Dame!_!Dame!_!Dame!
!Decapitacion!
!Dos!
!Explora!_Science_Center_and_Children's_Museum
!F
!Forward,_Russia!
!Forward_Russia!
!Ga!ne_language
!Ga!nge_language
!Gã!ne
!Gã!ne_language
!Gã!nge_language
!HERO
!Happy_Birthday_Guadaloupe!
!Happy_Birthday_Guadalupe!
!Hello_Friends
</code></pre>
<p>I have searched online but could not succeed. Any help will be appreciated.</p>
| 1 | 2016-10-02T15:14:59Z | 39,818,449 | <p>You have to choose between binary and text mode.</p>
<p>Either you open your file as <code>rb</code> and then you can use <code>re.sub(b"[^a-zA-Z]", b" ", text)</code> (<code>text</code> is a <code>bytes</code> object)</p>
<p>Or you open your file as <code>r</code> and then you can use <code>re.sub("[^a-zA-Z]", " ", text)</code> (<code>text</code> is a <code>str</code> object)</p>
<p>The second solution is more "classical".</p>
| 2 | 2016-10-02T15:18:04Z | [
"python",
"regex",
"python-3.x"
]
|
TypeError: sequence item 1: expected a bytes-like object, str found | 39,818,425 | <p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p>
<pre><code>with open('/Users/some/directory/title.txt', 'rb')as f:
text=f.read()
letters_only = re.sub(b"[^a-zA-Z]", " ", text)
words = letters_only.lower().split()
print(words)
</code></pre>
<p>But I am getting an error:</p>
<pre><code>TypeError: sequence item 1: expected a bytes-like object, str found
</code></pre>
<p>at the line: <code>letters_only = re.sub(b"[^a-zA-Z]", " ", text)</code></p>
<p>But, I am using <code>b''</code> to make output as byte type, below is a sample of the text file:</p>
<pre><code>Destroy-Oh-Boy!!
!!Fuck_you!!
!!Que_Corra_La_Voz!!
!!_(chess)
!!_(disambiguation)
!'O!Kung
!'O!Kung_language
!'O-!khung_language
!337$P34K
!=
!?
!?!
!?Revolution!?
!?_(chess)
!A_Luchar!
!Action_Pact!
!Action_pact!
!Adios_Amigos!
!Alabadle!
!Alarma!
!Alarma!_(album)
!Alarma!_(disambiguation)
!Alarma!_(magazine)
!Alarma!_Records
!Alarma!_magazine
!Alfaro_Vive,_Carajo!
!All-Time_Quarterback!
!All-Time_Quarterback!_(EP)
!All-Time_Quarterback!_(album)
!Alla_tu!
!Amigos!
!Amigos!_(Arrested_Development_episode)
!Arriba!_La_Pachanga
!Ask_a_Mexican!
!Atame!
!Ay,_Carmela!_(film)
!Ay,_caramba!
!BANG!
!Bang!
!Bang!_TV
!Basta_Ya!
!Bastardos!
!Bastardos!_(album)
!Bastardos_en_Vivo!
!Bienvenido,_Mr._Marshall!
!Ciauetistico!
!Ciautistico!
!DOCTYPE
!Dame!_!Dame!_!Dame!
!Decapitacion!
!Dos!
!Explora!_Science_Center_and_Children's_Museum
!F
!Forward,_Russia!
!Forward_Russia!
!Ga!ne_language
!Ga!nge_language
!Gã!ne
!Gã!ne_language
!Gã!nge_language
!HERO
!Happy_Birthday_Guadaloupe!
!Happy_Birthday_Guadalupe!
!Hello_Friends
</code></pre>
<p>I have searched online but could not succeed. Any help will be appreciated.</p>
| 1 | 2016-10-02T15:14:59Z | 39,818,472 | <p>The problem is with the <code>repl</code> argument you supply, it isn't a <code>bytes</code> object:</p>
<pre><code>letters_only = re.sub(b"[^a-zA-Z]", " ", b'Hello2World')
# TypeError: sequence item 1: expected a bytes-like object, str found
</code></pre>
<p>Instead, supply <code>repl</code> as a bytes instance <code>b" "</code>:</p>
<pre><code>letters_only = re.sub(b"[^a-zA-Z]", b" ", b'Hello2World')
print(letters_only)
b'Hello World'
</code></pre>
<hr>
<p>Note: Don't prefix your literals with <code>b</code> and don't open the file with <code>rb</code> if you aren't looking for <code>byte</code> sequences. </p>
| 4 | 2016-10-02T15:21:04Z | [
"python",
"regex",
"python-3.x"
]
|
TypeError: sequence item 1: expected a bytes-like object, str found | 39,818,425 | <p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p>
<pre><code>with open('/Users/some/directory/title.txt', 'rb')as f:
text=f.read()
letters_only = re.sub(b"[^a-zA-Z]", " ", text)
words = letters_only.lower().split()
print(words)
</code></pre>
<p>But I am getting an error:</p>
<pre><code>TypeError: sequence item 1: expected a bytes-like object, str found
</code></pre>
<p>at the line: <code>letters_only = re.sub(b"[^a-zA-Z]", " ", text)</code></p>
<p>But, I am using <code>b''</code> to make output as byte type, below is a sample of the text file:</p>
<pre><code>Destroy-Oh-Boy!!
!!Fuck_you!!
!!Que_Corra_La_Voz!!
!!_(chess)
!!_(disambiguation)
!'O!Kung
!'O!Kung_language
!'O-!khung_language
!337$P34K
!=
!?
!?!
!?Revolution!?
!?_(chess)
!A_Luchar!
!Action_Pact!
!Action_pact!
!Adios_Amigos!
!Alabadle!
!Alarma!
!Alarma!_(album)
!Alarma!_(disambiguation)
!Alarma!_(magazine)
!Alarma!_Records
!Alarma!_magazine
!Alfaro_Vive,_Carajo!
!All-Time_Quarterback!
!All-Time_Quarterback!_(EP)
!All-Time_Quarterback!_(album)
!Alla_tu!
!Amigos!
!Amigos!_(Arrested_Development_episode)
!Arriba!_La_Pachanga
!Ask_a_Mexican!
!Atame!
!Ay,_Carmela!_(film)
!Ay,_caramba!
!BANG!
!Bang!
!Bang!_TV
!Basta_Ya!
!Bastardos!
!Bastardos!_(album)
!Bastardos_en_Vivo!
!Bienvenido,_Mr._Marshall!
!Ciauetistico!
!Ciautistico!
!DOCTYPE
!Dame!_!Dame!_!Dame!
!Decapitacion!
!Dos!
!Explora!_Science_Center_and_Children's_Museum
!F
!Forward,_Russia!
!Forward_Russia!
!Ga!ne_language
!Ga!nge_language
!Gã!ne
!Gã!ne_language
!Gã!nge_language
!HERO
!Happy_Birthday_Guadaloupe!
!Happy_Birthday_Guadalupe!
!Hello_Friends
</code></pre>
<p>I have searched online but could not succeed. Any help will be appreciated.</p>
| 1 | 2016-10-02T15:14:59Z | 39,818,516 | <p>You can't use a <code>byte</code> string for your regex match when the replacement string isn't.<br>
Essentially, you can't mix different objects (<code>byte</code>s and <code>string</code>s) when doing most tasks. In your code above, you are using a binary search string and a binary text, but your replacement string is a regular <code>string</code>. All arguments need to be of the same type, so there are 2 possible solutions to this.</p>
<p>Taking the above into account, your code could look like this (this will return regular <code>string</code> strings, not <code>byte</code> objects):</p>
<pre><code>with open('/Users/some/directory/title.txt', 'r')as f:
text=f.read()
letters_only = re.sub(r"[^a-zA-Z]", " ", text)
words = letters_only.lower().split()
print(words)
</code></pre>
<p>Note that the code does use a special type of string for the regex - a raw string, prefixed with <code>r</code>. This means that python won't interpret escape characters such as <code>\</code>, which is very useful for regexes. See <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="nofollow">the docs</a> for more details about raw strings.</p>
| 1 | 2016-10-02T15:25:42Z | [
"python",
"regex",
"python-3.x"
]
|
retrieve series of slices of column headers based on truth of dataframe values | 39,818,559 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((0, 1), (3, 3)),
columns=['blah', 'meep', 'zimp'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>question</em></strong><br>
what is the most efficient way to slice <code>df.columns</code> with each row of <code>df</code>?<br>
(for this example and at scale)</p>
<p><strong><em>expected results</em></strong></p>
<pre><code>0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
<hr>
<h1>At Scale</h1>
<p>I confirmed that @jezrael, @boud, and my answer all produce the same results. Below is the dataframe I used to test the scale of each solution</p>
<pre><code>from string import letters
import pandas as pd
import numpy as np
mux = pd.MultiIndex.from_product([list(letters), list(letters)])
df = pd.DataFrame(np.arange(52 ** 4).reshape(52 ** 2, -1) % 3 % 2, mux, mux)
</code></pre>
<p><strong><em>setup for boud</em></strong> </p>
<pre><code>s = pd.Series([[x] for x in df], df.columns)
</code></pre>
<p><strong><em>setup for pirsquared</em></strong></p>
<pre><code>num = df.columns.nlevels
lvls = list(range(num))
rlvls = [x * -1 - 1 for x in lvls]
xsl = lambda x: x.xs(x.name).index.tolist()
</code></pre>
<p><strong><em>results</em></strong> </p>
<p><a href="http://i.stack.imgur.com/HIHqb.png" rel="nofollow"><img src="http://i.stack.imgur.com/HIHqb.png" alt="enter image description here"></a></p>
<p><strong><em>small df</em></strong> </p>
<p><a href="http://i.stack.imgur.com/s0ZYx.png" rel="nofollow"><img src="http://i.stack.imgur.com/s0ZYx.png" alt="enter image description here"></a></p>
| 3 | 2016-10-02T15:29:22Z | 39,819,278 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a> with <code>list comprehension</code>:</p>
<pre><code>df = df.mul(df.columns.to_series(), axis=1)
print (df)
blah meep zimp
0 meep
1 blah
2 blah zimp
print ([list(filter(None, x)) for x in df.values.tolist()])
[['meep'], ['blah'], ['blah', 'zimp']]
print (pd.Series([list(filter(None, x)) for x in df.values.tolist()], index=df.index))
0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
| 3 | 2016-10-02T16:44:58Z | [
"python",
"pandas",
"numpy"
]
|
retrieve series of slices of column headers based on truth of dataframe values | 39,818,559 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((0, 1), (3, 3)),
columns=['blah', 'meep', 'zimp'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>question</em></strong><br>
what is the most efficient way to slice <code>df.columns</code> with each row of <code>df</code>?<br>
(for this example and at scale)</p>
<p><strong><em>expected results</em></strong></p>
<pre><code>0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
<hr>
<h1>At Scale</h1>
<p>I confirmed that @jezrael, @boud, and my answer all produce the same results. Below is the dataframe I used to test the scale of each solution</p>
<pre><code>from string import letters
import pandas as pd
import numpy as np
mux = pd.MultiIndex.from_product([list(letters), list(letters)])
df = pd.DataFrame(np.arange(52 ** 4).reshape(52 ** 2, -1) % 3 % 2, mux, mux)
</code></pre>
<p><strong><em>setup for boud</em></strong> </p>
<pre><code>s = pd.Series([[x] for x in df], df.columns)
</code></pre>
<p><strong><em>setup for pirsquared</em></strong></p>
<pre><code>num = df.columns.nlevels
lvls = list(range(num))
rlvls = [x * -1 - 1 for x in lvls]
xsl = lambda x: x.xs(x.name).index.tolist()
</code></pre>
<p><strong><em>results</em></strong> </p>
<p><a href="http://i.stack.imgur.com/HIHqb.png" rel="nofollow"><img src="http://i.stack.imgur.com/HIHqb.png" alt="enter image description here"></a></p>
<p><strong><em>small df</em></strong> </p>
<p><a href="http://i.stack.imgur.com/s0ZYx.png" rel="nofollow"><img src="http://i.stack.imgur.com/s0ZYx.png" alt="enter image description here"></a></p>
| 3 | 2016-10-02T15:29:22Z | 39,820,411 | <p>I suggest to use <code>dot</code> after building a series of atomic lists:</p>
<pre><code>s = pd.Series([[col] for col in df.columns])
s.index = df.columns
df.dot(s)
Out[35]:
0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
| 2 | 2016-10-02T18:46:06Z | [
"python",
"pandas",
"numpy"
]
|
retrieve series of slices of column headers based on truth of dataframe values | 39,818,559 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((0, 1), (3, 3)),
columns=['blah', 'meep', 'zimp'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>question</em></strong><br>
what is the most efficient way to slice <code>df.columns</code> with each row of <code>df</code>?<br>
(for this example and at scale)</p>
<p><strong><em>expected results</em></strong></p>
<pre><code>0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
<hr>
<h1>At Scale</h1>
<p>I confirmed that @jezrael, @boud, and my answer all produce the same results. Below is the dataframe I used to test the scale of each solution</p>
<pre><code>from string import letters
import pandas as pd
import numpy as np
mux = pd.MultiIndex.from_product([list(letters), list(letters)])
df = pd.DataFrame(np.arange(52 ** 4).reshape(52 ** 2, -1) % 3 % 2, mux, mux)
</code></pre>
<p><strong><em>setup for boud</em></strong> </p>
<pre><code>s = pd.Series([[x] for x in df], df.columns)
</code></pre>
<p><strong><em>setup for pirsquared</em></strong></p>
<pre><code>num = df.columns.nlevels
lvls = list(range(num))
rlvls = [x * -1 - 1 for x in lvls]
xsl = lambda x: x.xs(x.name).index.tolist()
</code></pre>
<p><strong><em>results</em></strong> </p>
<p><a href="http://i.stack.imgur.com/HIHqb.png" rel="nofollow"><img src="http://i.stack.imgur.com/HIHqb.png" alt="enter image description here"></a></p>
<p><strong><em>small df</em></strong> </p>
<p><a href="http://i.stack.imgur.com/s0ZYx.png" rel="nofollow"><img src="http://i.stack.imgur.com/s0ZYx.png" alt="enter image description here"></a></p>
| 3 | 2016-10-02T15:29:22Z | 39,820,773 | <p>Another solution using sum of products using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow"><code>np.sum</code></a> followed by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> as shown:</p>
<pre><code>sep = ' '
pd.Series((df.values*(df.columns.values + sep)).sum(1)).str.split()
0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
| 2 | 2016-10-02T19:25:23Z | [
"python",
"pandas",
"numpy"
]
|
retrieve series of slices of column headers based on truth of dataframe values | 39,818,559 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((0, 1), (3, 3)),
columns=['blah', 'meep', 'zimp'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>question</em></strong><br>
what is the most efficient way to slice <code>df.columns</code> with each row of <code>df</code>?<br>
(for this example and at scale)</p>
<p><strong><em>expected results</em></strong></p>
<pre><code>0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
<hr>
<h1>At Scale</h1>
<p>I confirmed that @jezrael, @boud, and my answer all produce the same results. Below is the dataframe I used to test the scale of each solution</p>
<pre><code>from string import letters
import pandas as pd
import numpy as np
mux = pd.MultiIndex.from_product([list(letters), list(letters)])
df = pd.DataFrame(np.arange(52 ** 4).reshape(52 ** 2, -1) % 3 % 2, mux, mux)
</code></pre>
<p><strong><em>setup for boud</em></strong> </p>
<pre><code>s = pd.Series([[x] for x in df], df.columns)
</code></pre>
<p><strong><em>setup for pirsquared</em></strong></p>
<pre><code>num = df.columns.nlevels
lvls = list(range(num))
rlvls = [x * -1 - 1 for x in lvls]
xsl = lambda x: x.xs(x.name).index.tolist()
</code></pre>
<p><strong><em>results</em></strong> </p>
<p><a href="http://i.stack.imgur.com/HIHqb.png" rel="nofollow"><img src="http://i.stack.imgur.com/HIHqb.png" alt="enter image description here"></a></p>
<p><strong><em>small df</em></strong> </p>
<p><a href="http://i.stack.imgur.com/s0ZYx.png" rel="nofollow"><img src="http://i.stack.imgur.com/s0ZYx.png" alt="enter image description here"></a></p>
| 3 | 2016-10-02T15:29:22Z | 39,822,673 | <p>use <code>where</code> and <code>stack</code> to drop <code>0</code>s then grab indices left over</p>
<pre><code># number of levels in columns
num = df.columns.nlevels
# handy list for stacking
lvls = list(range(num))
# reverse (sort of) list for unstacking
rlvls = [x * -1 - 1 for x in lvls]
# get just levels in index that used to be columns
xsl = lambda x: x.xs(x.name).index.tolist()
# where is faster than replace
# when I stack, I'll drop all np.nan
# then just grab the indices that are left
df.where(df, np.nan).stack(lvls).groupby(level=lvls).apply(xsl)
0 [meep]
1 [blah]
2 [blah, zimp]
dtype: object
</code></pre>
| 1 | 2016-10-02T23:10:40Z | [
"python",
"pandas",
"numpy"
]
|
Python How to re-assign a static variable value of a python class with a return value of method | 39,818,609 | <p>I am trying to declare a static variable inside the class. I am trying to add a return value of a code inside a function. </p>
<p>The return value is assigned to the static variable inside the class but when i try to create an object of the class and access the static variable value from another class, it still returns the old value.</p>
<pre><code>class Login(Base):
token = ''
def run(self):
token=keystone.get_raw_token_from_identity_service('http://localhost:35357/v3,
username=username, user_domain_name='default, password=passwrd, project_name=project, project_domain_name='default')
def auth_token(self,token):
self.token = token
return self.token
</code></pre>
<p>In another class, i am trying to call the static variable but it always prints the initial value declared in the first class i.e. token = ''</p>
<pre><code> credentials = Login(Base)
print(type(credentials.auth_token.__func__))
print(hasattr(credentials,'token'))
print(credentials.token)"""
</code></pre>
| 0 | 2016-10-02T15:34:05Z | 39,818,703 | <p>If you make auth_token a @classmethod, it will behave the way you want</p>
<pre><code> @classmethod
def auth_token(cls, token):
cls.token = token
return cls.token
</code></pre>
<p>I'm not sure I love the design, but that's your affair.</p>
<p>EDIT: Here's an example of this code in action, in response to comments:</p>
<pre><code>>>> class Login(object):
... token = ""
... @classmethod
... def auth_token(cls, token):
... cls.token = token
... return cls.token
...
>>> l = Login()
>>> l2 = Login()
>>> l.token
''
>>> l2.token
''
>>> l.auth_token("foo")
'foo'
>>> l2.token
'foo'
>>>
</code></pre>
| 0 | 2016-10-02T15:44:35Z | [
"python",
"python-2.7"
]
|
Parsing numbers in a given range with pyparsing | 39,818,622 | <p>How to extract numbers in a given range using pyparsing?
I tried:</p>
<pre><code># Number lower than 12:
number = Word(nums).addCondition(lambda tokens: int(tokens[0]) < 12)
test_data = "10 23 11 14 115"
print number.searchString(test_data)
</code></pre>
<p>but it returns:</p>
<pre><code>[['10'], ['3'], ['11'], ['4'], ['5']]
</code></pre>
<p>What I want is:</p>
<pre><code>[['10'], ['11']]
</code></pre>
<p>More specified example:
I want to extract all numbers that looks like part of a date and ignore others.
So, from this input:</p>
<pre><code>"""
This is a date: 12 03 2008
This too: 03 12 2008
And this not, values are too large: 123 333 11
"""
</code></pre>
<p>I want to get:</p>
<pre><code>[[12, 3, 2008], [3, 12, 2008]]
</code></pre>
| 1 | 2016-10-02T15:36:02Z | 39,821,614 | <p>The main issue here is that searchString (and the underlying scanString) go through the input string character by character looking for matches. So in your input (with position header for reference):</p>
<pre><code> 1
012345678901234 <- position
10 23 11 14 115
</code></pre>
<p>searchString goes through the following steps:</p>
<ul>
<li>finds number "10" at position 0, this matches the "less than 12" condition, and so this is a match</li>
<li>advance to position 2</li>
<li>skipping whitespace, advance to position 3</li>
<li>finds number "23" at position 3, but this fails the condition</li>
<li>advance one place to position 3</li>
<li>finds number "3", this matches the condition, so is accepted as a match</li>
<li>finds number "11", this is a match, advance to position 8</li>
<li>skips whitespace, advance to position 9</li>
<li>finds number "14", this fails the condition</li>
<li>advance one place to position 10</li>
<li>finds number "4", this passes the condition, so accepted as a match </li>
<li>advances and finds number "115", and fails</li>
<li>advances one place and finds the number "15", and fails</li>
<li>advances one place and finds the number "5", and accepts as a match</li>
</ul>
<p>giving the results as you posted, <code>[['10'], ['3'], ['11'], ['4'], ['5']]</code>.</p>
<p>A quick solution is to change your definition of <code>number</code> to add <code>asKeyword=True</code>:</p>
<pre><code>number = Word(nums, asKeyword=True)
</code></pre>
<p>As keyword forces the expression to match only if at the beginning of a space-separated word. In your case, this will prevent accidental parsing of the '3' in '23', and the '4' in '14', etc. This will give your desired result of <code>[['10'], ['11']]</code>.</p>
| 0 | 2016-10-02T20:54:02Z | [
"python",
"pyparsing"
]
|
scrapy NBA schedule not collating correctly | 39,818,661 | <p>Trying to get a simple web scrape up and running. The goal is to dump the dt gm tm and ntv classes into csv - eventually. Here it is json for clarity. One step at a time.</p>
<p>here's the spider:</p>
<pre><code>import scrapy
class QuotesSpider(scrapy.Spider):
name = "schedule"
start_urls = [
'http://www.nba.com/schedules/national_tv_schedule/',
]
def parse(self, response):
for game in response.css('td'):
yield {
'date': game.css('td.dt::text').extract(),
'time': game.css('td.tm::text').extract(),
}
</code></pre>
<p>really simple - but spits out like so: (truncated for brevity)</p>
<pre><code>[
{"date": ["Sat, Oct 1", " ", "Sun, Oct 2", "Mon, Oct 3", " ", " ", " ", " ", " ", " "], "time": ["7:30 pm", "8:00 pm", "8:00 pm", "2:30 pm", "8:00 pm", "8:00 pm", "8:30 pm", "9:00 pm", "10:00 pm", "10:00 pm", "7:00 pm", "7:00 pm", "8:00 pm", "8:00 pm", "10:00 pm", "10:30 pm", "2:30 pm", "7:00 pm", "10:00 pm", "10:30 pm", "7:00 pm", "7:00 pm", "7:30 pm", "7:30 pm", "8:00 pm", "10:30 pm", "10:00 pm"]},
{"date": [], "time": []},
{"date": [], "time": []},
{"date": [], "time": []},
{"date": [], "time": []},
{"date": [], "time": []},
{"date": ["Sat, Oct 1"], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["7:30 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["8:00 pm"]},
{"date": [], "time": []},
{"date": ["Sun, Oct 2"], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["8:00 pm"]},
{"date": [], "time": []},
{"date": ["Mon, Oct 3"], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["2:30 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["8:00 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["8:00 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["8:30 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["9:00 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["10:00 pm"]},
{"date": [], "time": []},
{"date": [" "], "time": []},
{"date": [], "time": []},
{"date": [], "time": ["10:00 pm"]},
{"date": [], "time": []}
]
</code></pre>
<p>The first dict has the right data in the right order, but not collated. The following dicts have not matched up the data in the first dict correctly. I tried a while statement to take out newlines but was unsuccessful.</p>
<p>Any suggestions? I built this using the Scrapy tutorial. I know that I will eventually need to insert the correct dates.</p>
| 0 | 2016-10-02T15:40:47Z | 39,828,487 | <p>You probably want to be more specific on the table and rows you select.</p>
<p>Take a look at the HTML for the start of the schedule:</p>
<pre><code> <div id="scheduleMain" style="margin:0 5px 0 0!important;">
<table border="0" cellpadding="0" cellspacing="0" class="genSchedTable tvindex">
<tr class="header">
<td colspan="4">NATIONAL TV SCHEDULE - 2016-17</td>
</tr>
<tr class="title">
<td class="date">Date</td>
<td class="game">Teams</td>
<td class="time">Time (ET)</td>
<td class="natTV">Network</td>
</tr>
<tr>
<td class="dt">Mon, Oct 3</td>
<td class="gm"><a href="/thunder">Oklahoma City</a> @ <a href="/real_madrid">Real Madrid</a><br>Preseason
</td>
<td class="tm">2:30 pm</td>
<td class="ntv"><img border="0" src="http://i.cdn.turner.com/nba/nba/images/shrinkee_NBATV.gif"><img border="0" src="http://i.cdn.turner.com/nba/nba/images/shrinkee_NBAC.gif"></td>
</tr>
...
</code></pre>
<p>You can see that the table you're after is inside a <code><div id="scheduleMain"></code>.</p>
<p>And you should select table rows ( <code><tr></code>), not table cells in your for loop, and in each loop iteration, select the cells for time and date:</p>
<pre><code>def parse(self, response):
for game in response.css('#scheduleMain > table tr:nth-child(n+3)'):
yield {
'date': game.css('td.dt::text').extract(),
'time': game.css('td.tm::text').extract(),
}
</code></pre>
<p><code>tr:nth-child(n+3)</code> is used to select rows 3, 4, 5... (the 1st 2 rows are headers)</p>
| 0 | 2016-10-03T09:32:33Z | [
"python",
"scrapy"
]
|
Python: dynamically accessing nested dictionary keys? | 39,818,669 | <p>Is there some simple way to access nested dictionary key when at first you don't know which key you will be accessing?</p>
<p>For example:</p>
<pre><code>dct = {'label': 'A', 'config': {'value': 'val1'}}
</code></pre>
<p>In this dictionary I will need to access either <code>label</code> key or <code>value</code> key inside another dict that is accessible through <code>config</code> key.</p>
<p>It depends on state.</p>
<p>For example if we have variable called <code>label</code>, so if:</p>
<pre><code>label = True
if label:
key = 'label'
</code></pre>
<p>in this case its kind of easy:</p>
<pre><code>dct[key]
</code></pre>
<p>Now if label is false and I need to access nested dictionary, how can I dynamically specify it so I would not need to use ifs on every iterated item (I mean check everytime if <code>label</code> is used instead of <code>value</code>, because I will know that before starting iteration on dictionary full of <code>dct</code> dictionaries)? </p>
<p>like:</p>
<pre><code>label = False
if label:
key = 'label'
else:
key = 'config..?' # it should be something like ['config']['value']
</code></pre>
| 0 | 2016-10-02T15:41:09Z | 39,820,877 | <p>If you know the key to be traversed, you can try out the following. This would work for any level of nested dicts. </p>
<pre><code>dct = {'label': 'A', 'config': {'value': 'val1'}}
label = True
key = ('label',)
if not label:
key = ('config', 'value')
ret = dct
for k in key:
ret = ret[k]
print ret
</code></pre>
| 1 | 2016-10-02T19:36:20Z | [
"python",
"python-2.7",
"dictionary"
]
|
How do you get data from QTableWidget that user has edited (Python with PyQT) | 39,818,680 | <p>I asked a similar question before, but the result didn't work, and I don't know why.
Here was the original code:</p>
<pre><code>def click_btn_printouts(self):
self.cur.execute("""SELECT s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.RestrictedDate, m.DefensiveDate FROM
StudentProfile s LEFT JOIN Mailouts m ON s.studentID=m.studentID""")
self.all_data = self.cur.fetchall()
self.search_results()
self.table.setRowCount(len(self.all_data))
self.tableFields = ["Check","Full name","Previously mailed?","Next mail","learnersDate","Restricted date","Defensive driving date"]
self.table.setColumnCount(len(self.tableFields))
self.table.setHorizontalHeaderLabels(self.tableFields)
self.checkbox_list = []
for i, self.item in enumerate(self.all_data):
FullName = QtGui.QTableWidgetItem(str(self.item[0]))
PreviouslyMailed = QtGui.QTableWidgetItem(str(self.item[1]))
LearnersDate = QtGui.QTableWidgetItem(str(self.item[2]))
RestrictedDate = QtGui.QTableWidgetItem(str(self.item[3]))
DefensiveDate = QtGui.QTableWidgetItem(str(self.item[4]))
NextMail = QtGui.QTableWidgetItem(str(self.item[5]))
self.table.setItem(i, 1, FullName)
self.table.setItem(i, 2, PreviouslyMailed)
self.table.setItem(i, 3, LearnersDate)
self.table.setItem(i, 4, RestrictedDate)
self.table.setItem(i, 5, DefensiveDate)
self.table.setItem(i, 6, NextMail)
chkBoxItem = QtGui.QTableWidgetItem()
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
self.checkbox_list.append(chkBoxItem)
self.table.setItem(i, 0, self.checkbox_list[i])
</code></pre>
<p>The suggested code to add was this (indentation accurate) to the end of the function:</p>
<pre><code> self.changed_items = set()
self.table.itemChanged.connect(self.log_change)
</code></pre>
<p>And add the following function:</p>
<pre><code>def log_change(self):
self.changed_items.add(self.item)
print(self.item)
</code></pre>
<p>The expected print was the edited data, but what I get is the data before it was edited.</p>
<p>I can't use QTableView and QtSql unless I can find a way to use it with an SQL query, get every selected record into a list, and stop certain columns from being edited. If anybody knows how to do these, that would be great, I just really have no time to go through all the documentation myself at the moment.</p>
<p>All I want to do is have the user be able to change data from the QTableWidget, and get that changed data as a record.</p>
<p>Basically, my end goal is to have the equivalent of <code>setEditStrategy(QSqlTableModel.OnManualSubmit)</code> for QTableWidget.</p>
<p>I have been trying to figure this out for a while now and I just want it sorted out, it is the last thing I need to do to finish this program for a client.</p>
| 0 | 2016-10-02T15:42:35Z | 39,837,800 | <p>It is always difficult to answer without a minimal working example, so I produced one myself and put the suggestion from the <a href="http://stackoverflow.com/questions/39742199/how-do-i-get-the-information-that-the-user-has-changed-in-a-table-in-pyqt-with-p">other post</a> in, modifying it, such that it outputs the changed item's text and its position inside the table. </p>
<pre><code># runs with Python 2.7 and PyQt4
from PyQt4 import QtGui, QtCore
import sys
class App(QtGui.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent)
self.setMinimumSize(600,200)
self.all_data = [["John", True, "01234", 24],
["Joe", False, "05671", 13],
["Johnna", True, "07145", 44] ]
self.mainbox = QtGui.QWidget(self)
self.layout = QtGui.QVBoxLayout()
self.mainbox.setLayout(self.layout)
self.setCentralWidget(self.mainbox)
self.table = QtGui.QTableWidget(self)
self.layout.addWidget(self.table)
self.button = QtGui.QPushButton('Update',self)
self.layout.addWidget(self.button)
self.click_btn_printouts()
self.button.clicked.connect(self.update)
def click_btn_printouts(self):
self.table.setRowCount(len(self.all_data))
self.tableFields = ["Name", "isSomething", "someProperty", "someNumber"]
self.table.setColumnCount(len(self.tableFields))
self.table.setHorizontalHeaderLabels(self.tableFields)
self.checkbox_list = []
for i, self.item in enumerate(self.all_data):
FullName = QtGui.QTableWidgetItem(str(self.item[0]))
FullName.setFlags(FullName.flags() & ~QtCore.Qt.ItemIsEditable)
PreviouslyMailed = QtGui.QTableWidgetItem(str(self.item[1]))
LearnersDate = QtGui.QTableWidgetItem(str(self.item[2]))
RestrictedDate = QtGui.QTableWidgetItem(str(self.item[3]))
self.table.setItem(i, 0, FullName)
self.table.setItem(i, 1, PreviouslyMailed)
self.table.setItem(i, 2, LearnersDate)
self.table.setItem(i, 3, RestrictedDate)
self.changed_items = []
self.table.itemChanged.connect(self.log_change)
def log_change(self, item):
self.table.blockSignals(True)
item.setBackgroundColor(QtGui.QColor("red"))
self.table.blockSignals(False)
self.changed_items.append(item)
print item.text(), item.column(), item.row()
def update(self):
print "Updating "
for item in self.changed_items:
self.table.blockSignals(True)
item.setBackgroundColor(QtGui.QColor("white"))
self.table.blockSignals(False)
self.writeToDatabase(item)
def writeToDatabase(self, item):
text, col, row = item.text(), item.column(), item.row()
#write those to database with your own code
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
thisapp = App()
thisapp.show()
sys.exit(app.exec_())
</code></pre>
<p>You may use this example now to refer to any further problems.</p>
| 1 | 2016-10-03T18:07:44Z | [
"python",
"pyqt"
]
|
Create dictionary where keys are variable names | 39,818,733 | <p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code> (typically to return data at the end of a function).</p>
<p>Is there any (ideally built in) ways in python of automatically doing this? i.e to have a function such that <code>create_dictionary(a,b)</code> returns <code>{"a":a, "b":b}</code></p>
| 0 | 2016-10-02T15:47:33Z | 39,818,804 | <p>Have you tried something like:</p>
<pre><code>a, b, c, d = 1, 2, 3, 4
dt = {k:v for k, v in locals().items() if not k.startswith('__')}
print(dt)
{'a': 1, 'd': 4, 'b': 2, 'c': 3}
</code></pre>
| 0 | 2016-10-02T15:54:33Z | [
"python",
"python-3.x"
]
|
Create dictionary where keys are variable names | 39,818,733 | <p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code> (typically to return data at the end of a function).</p>
<p>Is there any (ideally built in) ways in python of automatically doing this? i.e to have a function such that <code>create_dictionary(a,b)</code> returns <code>{"a":a, "b":b}</code></p>
| 0 | 2016-10-02T15:47:33Z | 39,818,967 | <p>You can write your own function for <code>create_dict</code></p>
<pre><code>def create_dict(*args):
return dict({i:eval(i) for i in args})
a = "yo"
b = 7
print (create_dict("a", "b"))
</code></pre>
<p>Which gives <code>{'a': 'yo', 'b': 7}</code> output.<br>
Here's a simple generator for the same:</p>
<pre><code>vars = ["a", "b"]
create_dict = {i:eval(i) for i in args}
</code></pre>
<p>or you can use this one-liner lambda function</p>
<pre><code>create_dict = lambda *args: {i:eval(i) for i in args}
print (create_dict("a", "b"))
</code></pre>
<p>But if you want to pass the variables to the function instead of the variable name as string, then its pretty messy to actually get the name of the variable as a string. But if thats the case then you should probably try using <code>locals()</code>, <code>vars()</code>, <code>globals()</code> as used by <a href="http://stackoverflow.com/users/6335503/nf4r">Nf4r</a> </p>
| 0 | 2016-10-02T16:10:06Z | [
"python",
"python-3.x"
]
|
Create dictionary where keys are variable names | 39,818,733 | <p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code> (typically to return data at the end of a function).</p>
<p>Is there any (ideally built in) ways in python of automatically doing this? i.e to have a function such that <code>create_dictionary(a,b)</code> returns <code>{"a":a, "b":b}</code></p>
| 0 | 2016-10-02T15:47:33Z | 39,819,722 | <p>Have you considered creating a class? A class can be viewed as a wrapper for a dictionary. </p>
<pre><code># Generate some variables in the workspace
a = 9; b = ["hello", "world"]; c = (True, False)
# Define a new class and instantiate
class NewClass(object): pass
mydict = NewClass()
# Set attributes of the new class
mydict.a = a
mydict.b = b
mydict.c = c
# Print the dict form of the class
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
</code></pre>
<p>Or you could use the <code>setattr</code> function if you wanted to pass a list of variable names:</p>
<pre><code>mydict = NewClass()
vars = ['a', 'b', 'c']
for v in vars:
setattr(mydict, v, eval(v))
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
</code></pre>
| 0 | 2016-10-02T17:34:23Z | [
"python",
"python-3.x"
]
|
How do I return combination of same level nodes in one webelement in selenium? | 39,818,842 | <p>my knowledge of selenium at this point is a bit limited, but from what I understand driver.find_elements_by_xpath() returns a list of webelements. One can then iterate over the elements and do whatever one wants, like printing text.
That part is easy.
But now assume on a given page I would be looking for every combination of 3 nodes:</p>
<pre><code><parent>
<h1>text</h1>
<div class="identifier">more stuff</div>
<h3>text2</h3>
<h1>other text</h1>
<div class="identifier">other more stuff</div>
<h3>other text2</h3>
...
</parent>
</code></pre>
<p>These 3 nodes (here h1, div with class, and h3) are on the same level of hierarchy and there are many of them there since its a list. Is there a way to have selenium return them "packaged"? In this case I could make sure I get the correct data together. The way I am doing it right now is getting the middle element and then preceding and following sibling with the specified tag. But I feel like thats whacky at best.</p>
<p>Thx alot.</p>
| 1 | 2016-10-02T15:58:08Z | 39,827,188 | <p>Your approach is fine -- just find the first element and then check to make sure the next one (and one after) are the ones you are expecting, otherwise continue searching.</p>
<p>For more complex cases like this, it might be easier to pull out the HTML of the body as text and run a (more powerful) regex on it. </p>
| 0 | 2016-10-03T08:16:33Z | [
"python",
"html",
"selenium",
"xpath"
]
|
How do I return combination of same level nodes in one webelement in selenium? | 39,818,842 | <p>my knowledge of selenium at this point is a bit limited, but from what I understand driver.find_elements_by_xpath() returns a list of webelements. One can then iterate over the elements and do whatever one wants, like printing text.
That part is easy.
But now assume on a given page I would be looking for every combination of 3 nodes:</p>
<pre><code><parent>
<h1>text</h1>
<div class="identifier">more stuff</div>
<h3>text2</h3>
<h1>other text</h1>
<div class="identifier">other more stuff</div>
<h3>other text2</h3>
...
</parent>
</code></pre>
<p>These 3 nodes (here h1, div with class, and h3) are on the same level of hierarchy and there are many of them there since its a list. Is there a way to have selenium return them "packaged"? In this case I could make sure I get the correct data together. The way I am doing it right now is getting the middle element and then preceding and following sibling with the specified tag. But I feel like thats whacky at best.</p>
<p>Thx alot.</p>
| 1 | 2016-10-02T15:58:08Z | 39,837,076 | <p>I'm not sure what code you are using for your approach but I would do something like this.</p>
<pre><code>headings = driver.find_elements_by_css_selector("parent > h1"))
for i in range(len(headings)):
heading = driver.find_element_by_css_selector("parent > h1:nth-of-type(" + i + ")"))
identifier = driver.find_element_by_css_selector("parent > div.identifier:nth-of-type(" + i + ")"))
subheading = driver.find_element_by_css_selector("parent > h3:nth-of-type(" + i + ")"))
// do something with each element here
</code></pre>
<p>Now you can reference each of the elements.</p>
<p>NOTE: This assumes that each of the elements always exists. If you are ever missing an <code>h3</code>, etc. this code will mismatch the groups.</p>
| 1 | 2016-10-03T17:24:01Z | [
"python",
"html",
"selenium",
"xpath"
]
|
how to make vpython .exe using pyinstaller | 39,818,847 | <p>I have a simple script using vpython (just testing) and I want to create a .exe file with pyinstaller.</p>
<p>This is the script:</p>
<pre><code>from visual import*
box()
</code></pre>
<p>Then I run in the console:</p>
<pre><code>pyinstaller sss.py
</code></pre>
<p>But the .exe dont work(obviously)</p>
<p>I've been googling about how to make the .spec file for vpython but dont find nothing.</p>
<p>Also tried making this .spec file</p>
<pre><code># -*- mode: python -*-
block_cipher = None
a = Analysis(['sss.py'],
pathex=['C:\\Users\\hdfh\\Documents\\Python Scripts'],
binaries=None,
datas=None,
hiddenimports=(['visual','vis','visual_common','viddle']),
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='sss.exe',
debug=False,
strip=None,
upx=True,
console=False )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='sss')
</code></pre>
<p>But it dindt work</p>
| 1 | 2016-10-02T15:58:27Z | 39,822,549 | <p>I will reponse myself, maybe it helps someone.</p>
<p>When pyinstaller is used with vpython and you try to run the .exe file, it has problem for find the TGA archives placed in </p>
<pre><code>C:\Anaconda2\Lib\site-packages\visual_common
</code></pre>
<p>So we have to edit the archive materials.py</p>
<pre><code>C:\Anaconda2\Lib\site-packages\visual_common\materials.py
</code></pre>
<p>Here we look for the code</p>
<pre><code>import sys
if hasattr(sys,'frozen') and (sys.frozen=="windows_exe" or sys.frozen=="console_exe"):
texturePath="visual\\"
else:
texturePath = os.path.split( __file__ )[0] + "/"
del sys
</code></pre>
<p>For me worked change <code>texturePath=...</code>to another directory, for example C:</p>
<pre><code>import sys
if hasattr(sys,'frozen') and (sys.frozen=="windows_exe" or sys.frozen=="console_exe"):
texturePath=os.path.abspath("C:/")
else:
texturePath = os.path.abspath("C:/")
del sys
</code></pre>
<p>Save it and MOVE the TGA archives from visual_common to C:/ (or to the chosen place) and finally try to build the .exe from the console</p>
<pre><code>pyinstaller test.py
</code></pre>
<p>For this works...</p>
| 0 | 2016-10-02T22:52:11Z | [
"python",
"pyinstaller",
"vpython"
]
|
pickle.load: ImportError: No module named k_means_ | 39,818,859 | <p>I'm dumping a <code>sklearn.cluster.KMeans</code> object using <code>pickle</code> like this:</p>
<pre><code>kmeans = KMeans(n_clusters=7)
kmeans.fit(X)
pickle.dump(kmeans, open(model_fname, "w"), protocol=2)
</code></pre>
<p>However, if I try to reload this pickle file:</p>
<pre><code>if os.path.exists(model_fname):
print "Loading existing model .."
return pickle.load(open(model_fname, "rb"))
</code></pre>
<p>I'm getting:</p>
<pre><code> File "C:\Python27\lib\pickle.py", line 1130, in find_class
__import__(module)
ImportError: No module named k_means_
</code></pre>
<p>How can I load this file?</p>
| 2 | 2016-10-02T15:59:19Z | 39,819,394 | <p>I just replaced <code>pickle</code> by <code>joblib</code>:</p>
<pre><code>from sklearn.externals import joblib
</code></pre>
| 2 | 2016-10-02T16:56:18Z | [
"python",
"scikit-learn",
"pickle"
]
|
using a nested if statement within a for loop | 39,818,863 | <p>i'm trying to read through a string (with no spaces) pull out instances where there is a single lowercase letter surrounded on both sides by 3 upper cases (i.e. HHSkSIO). I've written the code below:</p>
<pre><code>def window(fseq, window_size=7):
for i in xrange(len(fseq) - window_size + 1):
yield fseq[i:i+window_size]
for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
if seq[0].isupper and seq[1].isupper and seq[2].isupper and seq[3].islower and seq[4].isupper and seq[5].isupper and seq[6].isupper:
print seq
</code></pre>
<p>where the first function window allows me to iterate through the string using a sliding window of 7 and the second part, the for statement, checks whether the characters within each window are higher higher higher lower higher higher higher. When I run the code, it comes out with:</p>
<pre><code>asjdjdf
sjdjdfk
jdjdfkj
djdfkjd
jdfkjdh
dfkjdhf
fkjdhfk
kjdhfkd
jdhfkdj
dhfkdjh
hfkdjhs
fkdjhsd
kdjhsdf
djhsdfk
jhsdfkj
hsdfkjs
sdfkjsd
dfkjsdH
fkjsdHJ
kjsdHJJ
jsdHJJn
sdHJJnJ
dHJJnJs
HJJnJsd
JJnJsdj
JnJsdjk
nJsdjkd
Jsdjkds
sdjkdsa
djkdsad
</code></pre>
<p>How can I make the for statement <strong>only</strong> print out the sliding window which conforms to the above if statement, rather than printing out all of them? P.S i know this is probably a very clunky way of doing it, I'm a beginner and it was the only thing i could think of!</p>
| 0 | 2016-10-02T15:59:52Z | 39,818,899 | <p>You have to call the <code>isupper</code> and <code>islower</code> methods:</p>
<pre><code> if seq[:3].isupper() and seq[3].islower() and seq[4:].isupper():
print seq
</code></pre>
| 1 | 2016-10-02T16:03:43Z | [
"python",
"string",
"iteration"
]
|
using a nested if statement within a for loop | 39,818,863 | <p>i'm trying to read through a string (with no spaces) pull out instances where there is a single lowercase letter surrounded on both sides by 3 upper cases (i.e. HHSkSIO). I've written the code below:</p>
<pre><code>def window(fseq, window_size=7):
for i in xrange(len(fseq) - window_size + 1):
yield fseq[i:i+window_size]
for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
if seq[0].isupper and seq[1].isupper and seq[2].isupper and seq[3].islower and seq[4].isupper and seq[5].isupper and seq[6].isupper:
print seq
</code></pre>
<p>where the first function window allows me to iterate through the string using a sliding window of 7 and the second part, the for statement, checks whether the characters within each window are higher higher higher lower higher higher higher. When I run the code, it comes out with:</p>
<pre><code>asjdjdf
sjdjdfk
jdjdfkj
djdfkjd
jdfkjdh
dfkjdhf
fkjdhfk
kjdhfkd
jdhfkdj
dhfkdjh
hfkdjhs
fkdjhsd
kdjhsdf
djhsdfk
jhsdfkj
hsdfkjs
sdfkjsd
dfkjsdH
fkjsdHJ
kjsdHJJ
jsdHJJn
sdHJJnJ
dHJJnJs
HJJnJsd
JJnJsdj
JnJsdjk
nJsdjkd
Jsdjkds
sdjkdsa
djkdsad
</code></pre>
<p>How can I make the for statement <strong>only</strong> print out the sliding window which conforms to the above if statement, rather than printing out all of them? P.S i know this is probably a very clunky way of doing it, I'm a beginner and it was the only thing i could think of!</p>
| 0 | 2016-10-02T15:59:52Z | 39,818,932 | <p>The problem is that you are missing the () in your calls to .isupper, which always evaluate to true.</p>
<p>Try:</p>
<pre><code>def window(fseq, window_size=7):
for i in range(len(fseq) - window_size + 1):
yield fseq[i:i+window_size]
for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
if seq[0].isupper() and seq[1].isupper() and seq[2].isupper() and seq[3].islower() and seq[4].isupper() and seq[5].isupper() and seq[6].isupper():
print (seq)
</code></pre>
<p>The other way of doing it, would be:</p>
<pre><code>import re
s = re.compile(r'[A-Z]{3}[a-z][A-Z]{3}')
def window(fseq, window_size=7):
for i in range(len(fseq) - window_size + 1):
yield fseq[i:i+window_size]
for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
result = s.search(seq)
if result is not None:
print(result.group())
</code></pre>
| 1 | 2016-10-02T16:06:56Z | [
"python",
"string",
"iteration"
]
|
Creating a dictionary with multiple values per key from a list of dictionaries | 39,818,875 | <p>I have the following list of dictionaries:</p>
<pre><code>listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2},
{'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4},
{'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6},
{'StrId': 34, 'ProjId': 7}]
</code></pre>
<p>I need to get all <code>ProjId</code> values for <code>StrId</code> that are duplicate. So this is the output I'm looking for:</p>
<pre><code>new_listofdics = [{11:[1,2]}, {22:[3,4]}, {33:[5,6]], {34:[7]}]
</code></pre>
<p>I wrote a function that creates a list of dictionaries with <code>StrId</code> values as keys, and a list with all <code>ProjId</code> that share the same key as values. Here it is:</p>
<pre><code>def compare_projids(listofdics):
proj_ids_dups = {}
for row in listofdics:
id_value = row['StrId']
proj_id_value = row['ProjId']
proj_ids_dups[id_value]=proj_id_value
if row['StrId'] == id_value:
sum_ids = []
sum_ids.append(proj_id_value)
proj_ids_dups[id_value]=sum_ids
return proj_ids_dups
</code></pre>
<p>This is the output I get now:</p>
<pre><code>new_listofdics= {33: [6], 34: [7], 11: [2], 22: [4]}
</code></pre>
<p>What I see is that<code>append</code> replaces each <code>ProjId</code> value with the last one iterated, instead of adding them at the end of the list.</p>
<p>How can I fix this?...</p>
| 0 | 2016-10-02T16:01:12Z | 39,819,029 | <p>It's unclear why you need to have such output <code>new_listofdics = [{11:[1,2]}, {22:[3,4]}, {33:[5,6]], {34:[7]}]</code>, because it's better to have just <code>dict</code> object.</p>
<p>So program would look like this</p>
<pre><code>>>> from collections import defaultdict
>>> listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2},
{'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4},
{'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6},
{'StrId': 34, 'ProjId': 7}]
>>> output = defaultdict(list)
>>> for item in listofdics:
... output[item.get('StrId')].append(item.get('ProjId'))
>>> dict(output)
{11: [1, 2], 22: [3, 4], 33: [5, 6], 34: [7]}
</code></pre>
<p>It's much easier to go through that dict that your desired output.</p>
| 2 | 2016-10-02T16:18:29Z | [
"python",
"dictionary"
]
|
My accumulator is registering as a string....SO LOST | 39,818,882 | <p>My problem is probably simple as usual guys and gals, I've been working on this thing for 13 hours now and I can't get this this to accumulate the names variable.</p>
<p>I need it to count players that I have input data for. This is the error message I'm getting:</p>
<pre><code>line 25, in main
name += 1
TypeError: Can't convert 'int' object to str implicitly
</code></pre>
<p>For this input/output:</p>
<pre><code>You will be asked to enter players names and scores
When you have no more names, enter End
Enter Player's Name or end to end program:vxzcvzvc
Enter vxzcvzvc's golf score: 3
Enter Player's Name or end to end program:zcvxcxzvxzv5
Enter zcvxcxzvxzv5's golf score: 6
Enter Player's Name or end to end program:zcvxvczx
Enter zcvxvczx's golf score: 5
Enter Player's Name or end to end program:end
You have written end players records to golf.txt
</code></pre>
<p>This is my code:</p>
<pre><code>def main():
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#define name
name = 0
name += 1
# introduction to user explaining required information to be entered
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
print("\n")
#Enter input, leave blank to quit program
while True:
name = input("Enter Player's Name or end to end program:")
if name == "end":
break
score = input("Enter "+ str(name)+"'s golf score: ")
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
#output for number of names recorded
print("You have written", name,"players records to golf.txt")
outfile.close()
main()
</code></pre>
| 0 | 2016-10-02T16:02:00Z | 39,819,017 | <p>You need a separate variable for counting the number of scores that have been written:</p>
<pre><code>def main():
outfile = open('golf.txt', 'w')
# Change this:
count = 0
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
print("\n")
while True:
name = input("Enter Player's Name or end to end program:")
if name == "end":
break
score = input("Enter {}'s golf score: ".format(name))
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
# add this:
count += 1
# change this:
print("You have written {} players records to golf.txt".format(count))
outfile.close()
main()
</code></pre>
| 1 | 2016-10-02T16:16:50Z | [
"python",
"accumulator"
]
|
Send excel file for downloading GAE python | 39,818,916 | <p>I am using Google App Engine with python 2.7. And there is need to generate in-memory xls-file and send it to user for downloading.</p>
<p>I found amount of topics in web, but any of them can't help me.
Related topics that I've tried to use: 1) <a href="http://stackoverflow.com/questions/7254317/how-can-i-store-excel-file-created-using-pyexcelerator-as-input-for-db-blobprope#">this is with Blobs, I tried at first</a>, 2) <a href="http://stackoverflow.com/questions/10490106/appengine-send-data-as-a-file-download">without Blob</a>, 3) <a href="http://stackoverflow.com/questions/10490106/appengine-send-data-as-a-file-download">with force-download MIME type</a>, also I've tried to use googlecloudstorage (can't find links to topics).</p>
<p>Here is my code:</p>
<pre><code>import StringIO
class ExcelHandler(BaseHandler):
def post(self):
"""Save members to excel document and send to user"""
sheet = pyexcel.Sheet([[1, 2], [3, 4]])
filesheet = StringIO.StringIO()
sheet.save_to_memory('xls', filesheet)
filesheet.close()
self.response.write(sheet)
self.response.headers['Content-Type'] = 'application/force-download'
self.response.headers['Content-Transfer-Encoding'] = 'utf-8'
self.response.headers['Content-Disposition'] = 'attachment; filename=test.xlsx'
</code></pre>
<p>The problem is in sending response (not in creating file). I tried different 'Content-Type':
'application/vnd.ms-excel',
'application/download',
'application/force-download',
'application/octet-stream',
'application/vnd.openxmlformats - officedocument.spreadsheetml.sheet' </p>
<p>But the best response I've achieved is as on picture:</p>
<p><a href="http://i.stack.imgur.com/alwso.png" rel="nofollow"><img src="http://i.stack.imgur.com/alwso.png" alt=""></a></p>
<p>I can't enforce my browser to start downloading data from server. I guess there may be something in my Request that should say to server 'Hey, I want to download', but it is only my thoughts, I've not found anything about that. Will appreciate any help!</p>
<p>Here is also my Request:</p>
<pre><code>POST /reg/excel HTTP/1.1
Host: 0.0.0.0:8080
Connection: keep-alive
Content-Length: 0
Accept: */*
Origin: http://0.0.0.0:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
Referer: http://0.0.0.0:8080/competition?dbKey=agpkZXZ- dG1tb3NjchgLEgtDb21wZXRpdGlvbhiAgICAgICgCww
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
</code></pre>
<p>and Response at debugger:</p>
<pre><code>HTTP/1.1 200 OK
content-disposition: attachment; filename=test.xlsx
content-transfer-encoding: utf-8
cache-control: no-cache
content-type: application/force-download
Content-Length: 64
Server: Development/2.0
Date: Sun, 02 Oct 2016 15:36:20 GMT
</code></pre>
<p><strong>EDIT 1:</strong> (try answer by voscausa)</p>
<p><a href="http://i.stack.imgur.com/TUbMW.png" rel="nofollow"><img src="http://i.stack.imgur.com/TUbMW.png" alt="Response changed its format. I am going to try to write another data structure (not Sheet) to response"></a></p>
| 0 | 2016-10-02T16:05:22Z | 39,819,521 | <p>Try this:</p>
<pre><code>output = StringIO.StringIO()
.......
self.response.headers[b'Content-Type'] = b'application/vnd.ms-excel; charset=utf-8'
self.response.headers[b'Content-Disposition'] = b'attachment; filename=test.xlsx'
self.response.write(output.getvalue())
</code></pre>
| 1 | 2016-10-02T17:11:47Z | [
"python",
"excel",
"google-app-engine"
]
|
function that reverses digits, takes into consideration the sign | 39,818,994 | <p>I've looked on the site to try and figure out how to do this but I'm still stuck. </p>
<p>My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :</p>
<pre><code>def reverse_digits(num):
return int(str(num)[::-1])
</code></pre>
<p>However, my code needs to 1) test if it is a negative and keep it negative (so -8765 returns -5678) and 2) I think I should test to see if num is actually an int. </p>
<p>So far I have </p>
<pre><code>def reverse_digits(num):
num = str(num)[::-1]
if num == '-':
minus = 1
num = num[:-1]
else:
minus = 0
int(num)
if minus == 1:
num = num*-1
else:
num = num
return num
</code></pre>
<p>It works for digits without a '-', but returns '' when it has a '-'. </p>
<p>I was originally trying to put the test to see if it is an int at the beginning od the loop like</p>
<pre><code>if (num != int):
print("wrong type")
sys.exit()
else:
(the rest of my above code)
</code></pre>
<p>but that wouldn't work for me. Should I put all the code in a while loop so I can use continue/break?
Thanks!</p>
| 0 | 2016-10-02T16:13:00Z | 39,819,027 | <p>Try to use the isdigit() string method.</p>
<pre><code>def reverse_digit(num):
num_str = str(num)[::-1].strip('-')
if not num_str.isdigit():
<do what u want>
if num < 0:
return -int(num_str)
else:
return int(num_str)
</code></pre>
| 2 | 2016-10-02T16:18:14Z | [
"python"
]
|
function that reverses digits, takes into consideration the sign | 39,818,994 | <p>I've looked on the site to try and figure out how to do this but I'm still stuck. </p>
<p>My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :</p>
<pre><code>def reverse_digits(num):
return int(str(num)[::-1])
</code></pre>
<p>However, my code needs to 1) test if it is a negative and keep it negative (so -8765 returns -5678) and 2) I think I should test to see if num is actually an int. </p>
<p>So far I have </p>
<pre><code>def reverse_digits(num):
num = str(num)[::-1]
if num == '-':
minus = 1
num = num[:-1]
else:
minus = 0
int(num)
if minus == 1:
num = num*-1
else:
num = num
return num
</code></pre>
<p>It works for digits without a '-', but returns '' when it has a '-'. </p>
<p>I was originally trying to put the test to see if it is an int at the beginning od the loop like</p>
<pre><code>if (num != int):
print("wrong type")
sys.exit()
else:
(the rest of my above code)
</code></pre>
<p>but that wouldn't work for me. Should I put all the code in a while loop so I can use continue/break?
Thanks!</p>
| 0 | 2016-10-02T16:13:00Z | 39,819,041 | <p>Just don't put the <code>-</code> into the reversed string:</p>
<pre><code>def reverse_digits(num):
return (-1 if num<0 else 1) * int(str(abs(num))[::-1])
</code></pre>
| 4 | 2016-10-02T16:20:06Z | [
"python"
]
|
Comparing 2 different dictionaries with random function | 39,819,061 | <p>So, what I am trying to achieve here is to take 2 dictionaries, take the values of both dictionaries in the same "spot" and be able to apply any function to it. Here's an example of some pseudo code:</p>
<pre><code>If f(a, b) returns a + b
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
then function(d1, d2) returns ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
If f(a, b) returns a > b
d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
then function(d1, d2) returns ({1: False, 2: False, 3: False}, {})
</code></pre>
| 2 | 2016-10-02T16:22:15Z | 39,819,513 | <p>Although there maybe a more efficient way to achieve what you want, i used the information <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">here</a> to create the following functions:</p>
<pre><code>def f1(a,b):
return a+b
def f2(a,b):
return a>b
def function2(d1,d2):
out1 = {}
out2 = {}
#use the set operations to take the common keys
commons = set(set(d1) & set(d2))
for i in commons:
out1[i] = d1[i] > d2[i]
#all the non-common keys go to out2
for i in d1:
if i not in commons:
out2[i] = d1[i]
for i in d2:
if i not in commons:
out2[i] = d2[i]
return (out1,out2)
def function1(d1,d2):
out1 = {}
out2 = {}
#use the set operations to take the common keys
commons = set(set(d1) & set(d2))
for i in commons: out1[i] = f1(d1[i],d2[i])
#all the non-common keys go to out2
for i in d1:
if i not in commons:
out2[i] = d1[i]
for i in d2:
if i not in commons:
out2[i] = d2[i]
return (out1,out2)
def main():
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
d1,d2 = function1(d1,d2)
for i in d1:print(i,d1[i])
print('\n')
for i in d2:print(i,d2[i])
print('\n\n')
d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
d1,d2 = function2(d1,d2)
for i in d1:print(i,d1[i])
print('\n')
for i in d2:print(i,d2[i])
if __name__ == '__main__':
main()
</code></pre>
<p>I tried to make my code as clear as possible.I hope it helps.</p>
| 0 | 2016-10-02T17:10:34Z | [
"python"
]
|
Comparing 2 different dictionaries with random function | 39,819,061 | <p>So, what I am trying to achieve here is to take 2 dictionaries, take the values of both dictionaries in the same "spot" and be able to apply any function to it. Here's an example of some pseudo code:</p>
<pre><code>If f(a, b) returns a + b
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
then function(d1, d2) returns ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
If f(a, b) returns a > b
d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
then function(d1, d2) returns ({1: False, 2: False, 3: False}, {})
</code></pre>
| 2 | 2016-10-02T16:22:15Z | 39,820,980 | <p>Firstly find the intersection and the unions of the two dictionaries (as sets)
The intersections are used for the first item of the tuple
The differences are used for the second item of the tuple.</p>
<p>The functor is the operation to perform on dictionary items with keys from the intersection values. This is the final result used in the first tuple item.</p>
<p>To get the final results for the second tuple, find the merged dictionary of d1 and d2, then return only the dictionary key values with keys from the differences</p>
<pre><code>def func(d1, d2, functor):
s_intersection = set(d1) & set(d2)
s_difference = set(d1) ^ set(d2)
merged = d1.copy()
merged.update(d2)
return {k: functor(d1[k], d2[k]) for k in s_intersection}, {k: merged[k] for k in s_difference}
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
print func(d1, d2, lambda x, y: x+y)
d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
print func(d1, d2, lambda x, y: x>y)
</code></pre>
| 0 | 2016-10-02T19:44:52Z | [
"python"
]
|
For loop to evaluate accuracy doesn't execute | 39,819,090 | <p>So I've the following numpy arrays.</p>
<ul>
<li>X validation set, X_val: (47151, 32, 32, 1)</li>
<li>y validation set (labels), y_val_dummy: (47151, 5, 10) </li>
<li>y validation prediction set, y_pred: (47151, 5, 10)</li>
</ul>
<p>When I run the code, it seems to take forever. Can someone suggest why? I believe it's a code efficiency problem. I can't seem to complete the process.</p>
<pre><code>y_pred_list = model.predict(X_val)
correct_preds = 0
# Iterate over sample dimension
for i in range(X_val.shape[0]):
pred_list_i = [y_pred_array[i] for y_pred in y_pred_array]
val_list_i = [y_val_dummy[i] for y_val in y_val_dummy]
matching_preds = [pred.argmax(-1) == val.argmax(-1) for pred, val in zip(pred_list_i, val_list_i)]
correct_preds = int(np.all(matching_preds))
total_acc = correct_preds / float(x_val.shape[0])
</code></pre>
| 1 | 2016-10-02T16:25:44Z | 39,841,336 | <p>You're main problem is that you're generating a massive number of very large lists for no real reason</p>
<pre><code>for i in range(X_val.shape[0]):
# this line generates a 47151 x 5 x 10 array every time
pred_list_i = [y_pred_array[i] for y_pred in y_pred_array]
</code></pre>
<p>What's happening is that iterating over an nd numpy array iterates over the slowest varying index (i.e. the leftmost), so every list comprehension is running operating on 47K entries.</p>
<p>Marginally better would be </p>
<pre><code>for i in range(X_val.shape[0]):
pred_list_i = [y_pred for y_pred in y_pred_array[i]]
val_list_i = [y_val for y_val in y_val_dummy[i]]
matching_preds = [pred.argmax(-1) == val.argmax(-1) for pred, val in zip(pred_list_i, val_list_i)]
correct_preds = int(np.all(matching_preds))
</code></pre>
<p>But you're still copying a lot of arrays for no real purpose. The following code should do the same, without the useless copying.</p>
<pre><code>correct_preds = 0.0
for pred, val in zip(y_pred_array, y_val_dummy):
correct_preds += all(p.argmax(-1) == v.argmax(-1)
for p, v in zip(pred, val))
total_accuracy = correct_preds / x_val.shape[0]
</code></pre>
<p>This assumes that your criteria for a correct prediction is accurate.
You can probably avoid the explicit loop entirely with a couple of calls to <code>np.argmax</code>, but you'll have to work that out on your own.</p>
| 0 | 2016-10-03T22:23:32Z | [
"python",
"numpy"
]
|
How to pass slice into a function by reference | 39,819,104 | <p>If I have</p>
<pre><code>a = [1, 2, 3]
def foo (arr):
for i in len (arr): arr [i] += 1
def bar (arr):
foo (arr[:2])
bar (a)
print (a)
</code></pre>
<p>I want output as </p>
<pre><code>>>> [2, 3, 3 ]
</code></pre>
<p>How do I go about this?</p>
<p>Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush() . But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.</p>
| 0 | 2016-10-02T16:27:59Z | 39,819,137 | <p>Use a <em>list comprehension</em> and update the initial list using a full slice assignment with <code>[:]</code>:</p>
<pre><code>def foo(arr):
arr[:] = [x+1 for x in arr]
</code></pre>
<p><em>Trial:</em></p>
<pre><code>>>> a = [1, 2, 3]
>>> def foo(arr):
... arr[:] = [x+1 for x in arr]
...
>>> foo(a)
>>> a
[2, 3, 4]
</code></pre>
| 1 | 2016-10-02T16:30:53Z | [
"python",
"python-3.x",
"pass-by-reference",
"slice"
]
|
How to pass slice into a function by reference | 39,819,104 | <p>If I have</p>
<pre><code>a = [1, 2, 3]
def foo (arr):
for i in len (arr): arr [i] += 1
def bar (arr):
foo (arr[:2])
bar (a)
print (a)
</code></pre>
<p>I want output as </p>
<pre><code>>>> [2, 3, 3 ]
</code></pre>
<p>How do I go about this?</p>
<p>Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush() . But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.</p>
| 0 | 2016-10-02T16:27:59Z | 39,819,154 | <p><em>Slicing the list will create a new list with the sliced contents</em>, as such <code>arr[:2]</code> loses the reference to the original <code>a</code>.</p>
<p>Apart from that, iterating as you did won't change the list at all, it just changes an <code>item</code> and disregards the value.</p>
<p>If you want to alter specific parts of the list, you must carry with you a reference to the original list. For example, keep <code>arr</code>, iterate through a slice of it with <code>enumerate(arr[:2])</code> and then alter <code>arr</code>:</p>
<pre><code>a = [1, 2, 3]
def foo(arr):
for i, item in enumerate(arr[:2]):
arr[i] = item + 1
def bar(arr):
foo(arr)
bar(a)
print(a)
</code></pre>
<p>Printing now yields <code>[2, 3, 3]</code>, removing the slice in <code>enumerate</code> results in <code>[2, 3, 4]</code>. Of course, <code>bar</code> here serves no purpose, you could drop it and just keep <code>foo</code> and call <code>foo(a)</code> immediately.</p>
| 0 | 2016-10-02T16:32:28Z | [
"python",
"python-3.x",
"pass-by-reference",
"slice"
]
|
How to pass slice into a function by reference | 39,819,104 | <p>If I have</p>
<pre><code>a = [1, 2, 3]
def foo (arr):
for i in len (arr): arr [i] += 1
def bar (arr):
foo (arr[:2])
bar (a)
print (a)
</code></pre>
<p>I want output as </p>
<pre><code>>>> [2, 3, 3 ]
</code></pre>
<p>How do I go about this?</p>
<p>Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush() . But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.</p>
| 0 | 2016-10-02T16:27:59Z | 39,819,234 | <p>To be honest instead of going for slice, I would just pass the indexes;</p>
<pre><code>a = [1, 2, 3]
def foo(array, start, stop, jmp= 1):
for idx in range(start, stop + 1, jmp):
array[idx] += 1
def bar(array):
foo(array, 1, 2)
bar(a)
print(a)
[1, 3, 4]
</code></pre>
| 0 | 2016-10-02T16:40:24Z | [
"python",
"python-3.x",
"pass-by-reference",
"slice"
]
|
Flask request.form contains data but request.data is empty and request.get_json() returns error | 39,819,151 | <p>I am trying to create a data entry form "dynamically" (currently, I am using an array with 3 values, but in the future the number of elements in the array might vary) with nested dictionaries. This seems to work fine and the form is "properly" renders the html template (properly = I see what I would expect to see which is a form with 3 rows for each element in the array with 4 columns).</p>
<p>The problem is when I enter data in the form through the browser and click the "Save Data" button. At that point I want to get data entered in the form by the user and do something with it (do calculations, save it, etc.).</p>
<p>Getting request data seems like a fairly straightforward task when the form does <strong>not</strong> have nested fields (based on all examples I have seen), but in my case it is driving me nuts.</p>
<p>So far, the only way I get to see the data submitted by the user is with "request.form" but that is a MultiDict object and has no structure.
The weird part to me is request.data returns an empty string and request.get_json() gives an error ("Failed to decode JSON")</p>
<p><strong>The specific question is:</strong> If I want to get the form data in json or dictionary format (structure I defined), what am I doing wrong? What else should I include in my code. Otherwise, if this behavior is expected and all I can get is a MultiDict, what is the best way to then reconstruct the data to json object?</p>
<p>This is my view.py code:
The GET method first create the form structure "dynamically" and render the report.htlm template.
The POST method is supposed to check what form button was clicked by the user and, get the data entered by the user and do something with it. Note that for now I only have "print" statements to see what I was getting. </p>
<pre><code>@app.route('/report', methods=['GET', 'POST'])
def report():
if request.method == 'POST':
if request.form['submit'] == 'Save Data':
print (request.form)
print(request.get_json(force=True)
print (request.data)
return redirect(url_for('report'))
elif request.form['submit'] == 'View Data':
return redirect(url_for('report'))
elif request.method == 'GET':
jsonForm = populate_Form()
form = ProductionReport.from_json(jsonForm)
return render_template('report.html',
title='Report',
form=form)
def populate_Form():
j = {"line_production": []}
lines = ["Standard","Sport","Luxury"]
for l in lines:
j["line_production"].append(
{"line": l, "sku": "", "qty": "", "price": ""})
return j
</code></pre>
<p>These are my forms:</p>
<pre><code>from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, IntegerField, FieldList, FormField, FloatField
from wtforms.validators import DataRequired
import wtforms_json
wtforms_json.init()
class LineProduction(Form):
line = StringField('line')
sku = IntegerField('sku', default = 0)
qty = IntegerField('qty', default = 0)
price = IntegerField('price', default = 0)
class ProductionReport(Form):
factory_id = StringField('Factory ID')
year = StringField('Year')
month = StringField('Month')
line_production = FieldList(FormField(LineProduction), label='line_production')
</code></pre>
| 1 | 2016-10-02T16:32:17Z | 39,819,328 | <p>As it was mentioned <a href="http://stackoverflow.com/a/16664376/3124746">here</a></p>
<blockquote>
<p><code>request.data</code> Contains the incoming request data as string in case it came with a mimetype Flask does not handle.</p>
</blockquote>
<p>That's why you get empty string in <code>request.data</code></p>
<p>You can convert <code>request.form</code> to dict, as you mentioned, it's <code>MultiDict</code> object, but it can be simply be converted to <code>dict</code> object with <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict.to_dict" rel="nofollow"><code>to_dict</code></a> method. And with <code>dict</code> object you can do whatever you like.</p>
| 0 | 2016-10-02T16:49:57Z | [
"python",
"flask",
"wtforms",
"wtforms-json"
]
|
Does Python's distutils set include paths for frameworks (osx) when compiling extensions? | 39,819,220 | <p>I've been working on an extension module for Python but in OSX Sierra it no longer finds headers belonging to the frameworks I'm linking to. It always found them before without any special effort. Has something changed lately regarding include paths in this tool chain?</p>
| 0 | 2016-10-02T16:38:46Z | 39,820,702 | <p>I have to pass <code>cc -F /Library/Frameworks</code> for clang 7.2.0 and 8.0.0. Then it can find the headers.</p>
| 0 | 2016-10-02T19:19:03Z | [
"python",
"distutils",
"macos-sierra"
]
|
How can I use an if-else condition inside a list comprehension to overwrite an existing list? | 39,819,236 | <p>I'm trying to multiply numbers greater than 3 by two, and subtract one from everything else. However, nothing happens to the list.
This is my code:</p>
<pre><code>lst = [1,2,3,4,5,6,7,8,9,10]
print (lst)
[x*2 if x > 3 else x-1 for x in lst]
print (lst)
</code></pre>
<p>Why aren't the contents of the <em>lst</em> variable modified by the list comprehension?</p>
| -1 | 2016-10-02T16:40:35Z | 39,819,267 | <p>You didnt re-assigned it to the variable name.</p>
<pre><code>lst = [1,2,3,4,5,6,7,8,9,10]
print (lst)
lst = [x*2 if x > 3 else x-1 for x in lst]
print (lst)
</code></pre>
| 0 | 2016-10-02T16:43:28Z | [
"python",
"list-comprehension",
"in-place"
]
|
How can I use an if-else condition inside a list comprehension to overwrite an existing list? | 39,819,236 | <p>I'm trying to multiply numbers greater than 3 by two, and subtract one from everything else. However, nothing happens to the list.
This is my code:</p>
<pre><code>lst = [1,2,3,4,5,6,7,8,9,10]
print (lst)
[x*2 if x > 3 else x-1 for x in lst]
print (lst)
</code></pre>
<p>Why aren't the contents of the <em>lst</em> variable modified by the list comprehension?</p>
| -1 | 2016-10-02T16:40:35Z | 39,819,300 | <h2>List Comprehensions and Assignment</h2>
<p>You're missing an assignment. <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List comprehensions</a> like yours don't do in-place modifications to the list elements. Instead, the expression returns a new list, so you must <em>assign</em> the result of the list comprehension expression back to a variable. For example:</p>
<pre><code>list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list = [x*2 if x > 3 else x-1 for x in list]
print(list)
</code></pre>
<p>In Ruby, there are certainly methods for performing self-mutating operations, but I'm not personally aware of a Python equivalent that retains the semantics that you're trying to use here.</p>
| 0 | 2016-10-02T16:47:09Z | [
"python",
"list-comprehension",
"in-place"
]
|
Python pexpect Check if server is up | 39,819,284 | <p>I am automating few configuration steps on CentOS. In order to do so i need to reboot the system also. I am invoking the "reboot" command the via python pexepct, however i need to wait till the systems boots up for remaining script to executes. For that i am have written this small piece of code.</p>
<pre><code> while True:
result = commands.getoutput("ping -c 4 192.168.36.134")
if result.find("Unreachable") == 1:
result = False
print 'Rebooting the Systems.'
else:
result = True
print 'Connected!'
break
</code></pre>
<p>Is there any better way to do this? Also, can we achieve this with the pexepct itself?</p>
| 1 | 2016-10-02T16:45:21Z | 39,823,601 | <p>You can try this:</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# wait host to finish reboot, check specific port connection (usually ssh port if you want to exec remote commands)
while True:
try:
s.connect(('hostname', 22))
print "Port 22 reachable"
break
except socket.error as e:
print "rebooting..."
# continue
s.close()
</code></pre>
<p>This example is more effective then using ping</p>
| 2 | 2016-10-03T01:55:18Z | [
"python",
"pexpect"
]
|
sockets irc bot not sending complete message | 39,819,305 | <p>I am trying to make an irc bot. It connects but doesn't send the complete message. If I want to send "hello world" it only sends "hello". It just sends everything until the first space. </p>
<p>In this program if you type hello in irc, the bot is supposed to send hello world. But it only sends hello.</p>
<pre><code>import socket
channel = "#bots"
server = "chat.freenode.org"
nickname = "my_bot"
class IRC:
irc = socket.socket()
def __init__(self):
self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def send(self, chan, msg):
self.irc.send("PRIVMSG " + chan + " " + msg + "\n")
def connect(self, server, channel, botnick):
# defines the socket
print("connecting to: " + server)
self.irc.connect((server, 6667)) # connects to the server
self.irc.send("NICK %s\n" % botnick)
self.irc.send("USER %s %s Ibot :%s\n" % (botnick, botnick, botnick))
self.irc.send("JOIN %s\n" % channel)
self.irc.send("PRIVMSG %s :Hello Master\n" % channel)
def get_text(self):
text = self.irc.recv(2040) # receive the text
if text.find('PING') != -1:
self.irc.send('PONG ' + text.split()[1] + 'rn')
return text
irc = IRC()
irc.connect(server, channel, nickname)
while True:
text = irc.get_text().strip()
if "hello" in text.lower():
irc.send(channel, "hello world")
print text
</code></pre>
| 0 | 2016-10-02T16:47:37Z | 39,819,779 | <p>You forgot a : before the message. This should work:</p>
<pre><code>def send(self, chan, msg):
self.irc.send("PRIVMSG " + chan + " :" + msg + "\n")
</code></pre>
| 2 | 2016-10-02T17:40:32Z | [
"python",
"sockets",
"irc"
]
|
Dealing with multiple Python versions? | 39,819,314 | <p>I have a problem with my Pip version. I am trying out to install the pyDatalog package, which isn't supported by Anaconda.</p>
<pre><code> The following specifications were found to be in conflict:
- pydatalog
- python 3.5*
</code></pre>
<p>In my Ubuntu, I have two versions of Python (2.7 and Anaconda with 3.5). For Python 2.7 I don't even know whether or not Pip is installed.</p>
<p>How can I have two different versions of Pip for different versions of Python on one computer? Can I use one version of Pip for both version of Python?</p>
| 0 | 2016-10-02T16:48:23Z | 39,821,908 | <p>Take a look at pyenv located in <a href="https://github.com/yyuu/pyenv/blob/master/README.md" rel="nofollow">https://github.com/yyuu/pyenv/blob/master/README.md</a>. </p>
<p>You can install multiple versions of python and pip. </p>
<p>The README has instructions for installing pyenv, installing wanted python versions and switching between them. </p>
| 1 | 2016-10-02T21:31:34Z | [
"python",
"python-2.7",
"pip",
"conda",
"pydatalog"
]
|
How to do logical operation between DataFrame and Series? | 39,819,323 | <p>Suppose I have a bool <code>DataFrame df</code> and a bool <code>Series x</code> with the same index, and I want to do logical operation between <code>df</code> and <code>x</code> per column. Is there any short and fast way like <code>DataFrame.sub</code> compare to using <code>DataFrame.apply</code>?</p>
<pre><code>In [31]: df
Out[31]:
x y z u
A False False True True
B True True True True
C True False False False
In [32]: x
Out[32]:
A True
B False
C True
dtype: bool
In [33]: r = df.apply(lambda col: col & x) # Any other way ??
In [34]: r
Out[34]:
x y z u
A False False True True
B False False False False
C True False False False
</code></pre>
| 2 | 2016-10-02T16:48:59Z | 39,819,434 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a>, but need cast to <code>int</code> and then to <code>bool</code>, because <code>UserWarning</code>:</p>
<pre><code>print (df.astype(int).mul(x.values, axis=0).astype(bool))
x y z u
A False False True True
B False False False False
C True False False False
</code></pre>
<p>Similar solution:</p>
<pre><code>print (df.mul(x.astype(int), axis=0).astype(bool))
x y z u
A False False True True
B False False False False
C True False False False
</code></pre>
<hr>
<pre><code>print (df.mul(x.values, axis=0))
x y z u
A False False True True
B False False False False
C True False False False
</code></pre>
<blockquote>
<p>C:\Anaconda3\lib\site-packages\pandas\computation\expressions.py:181: UserWarning: evaluating in Python space because the '*' operator is not supported by numexpr for the bool dtype, use '&' instead
unsupported[op_str]))</p>
</blockquote>
<p>Another <code>numpy</code> solution with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="nofollow"><code>np.logical_and</code></a>:</p>
<pre><code>print (pd.DataFrame(np.logical_and(df.values, x.values[:, None]),
index=df.index,
columns=df.columns))
x y z u
A False False True True
B False False False False
C True False False False
</code></pre>
| 4 | 2016-10-02T17:00:45Z | [
"python",
"pandas",
"dataframe",
"boolean",
"logical-operators"
]
|
Convert 12 hour time string into datetime or time | 39,819,384 | <p>Ive been trying to use <code>time.strptime(string1,'%H:%M')</code>, with no success</p>
<p>How can I get the following:</p>
<pre><code>Input Output
3:14AM -> 03:14
9:33PM -> 21:33
12:21AM -> 00:21
12:15PM -> 12:15
</code></pre>
| -1 | 2016-10-02T16:55:06Z | 39,819,437 | <p>You're missing <code>%p</code> (Localeâs equivalent of either AM or PM).</p>
<pre><code>time.strptime(string1,'%H:%M%p')
</code></pre>
| 0 | 2016-10-02T17:01:12Z | [
"python",
"datetime",
"time"
]
|
Convert 12 hour time string into datetime or time | 39,819,384 | <p>Ive been trying to use <code>time.strptime(string1,'%H:%M')</code>, with no success</p>
<p>How can I get the following:</p>
<pre><code>Input Output
3:14AM -> 03:14
9:33PM -> 21:33
12:21AM -> 00:21
12:15PM -> 12:15
</code></pre>
| -1 | 2016-10-02T16:55:06Z | 39,819,463 | <p>The problem requires that you first <code>strptime</code> using <code>%I</code> for the 12 hour time and adding the directive <code>%p</code> for AM or PM to get a time object; altogther <code>'%I:%M%p'</code>. Then use <code>strftime</code> to format the time object into a string:</p>
<hr>
<p><em>Trials:</em></p>
<pre><code>>>> tm = time.strptime('12:33AM', '%I:%M%p')
>>> time.strftime('%H:%M', tm)
'00:33'
>>> tm = time.strptime('9:33PM', '%H:%M%p')
>>> time.strftime('%H:%M', tm)
'09:33'
</code></pre>
<p>Doc reference: <a href="https://docs.python.org/2/library/time.html" rel="nofollow">https://docs.python.org/2/library/time.html</a></p>
| 1 | 2016-10-02T17:04:15Z | [
"python",
"datetime",
"time"
]
|
Convert 12 hour time string into datetime or time | 39,819,384 | <p>Ive been trying to use <code>time.strptime(string1,'%H:%M')</code>, with no success</p>
<p>How can I get the following:</p>
<pre><code>Input Output
3:14AM -> 03:14
9:33PM -> 21:33
12:21AM -> 00:21
12:15PM -> 12:15
</code></pre>
| -1 | 2016-10-02T16:55:06Z | 39,819,464 | <p>Use <code>%I</code> for 12 hour times and <code>%p</code> for the <code>am</code> or <code>pm</code> as follows:</p>
<pre><code>from datetime import datetime
for t in ["3:14AM", "9:33PM", "12:21AM", "12:15PM"]:
print datetime.strptime(t, '%I:%M%p').strftime("%H:%M")
</code></pre>
<p>Giving you the following output:</p>
<pre><code>03:14
21:33
00:21
12:15
</code></pre>
<p>The formats used are documented in <a href="https://docs.python.org/2/library/datetime.html?highlight=strptime#strftime-strptime-behavior" rel="nofollow">strftime() and strptime() Behavior</a></p>
| 1 | 2016-10-02T17:04:23Z | [
"python",
"datetime",
"time"
]
|
Average function excluding value for each row in Pandas DataFrame | 39,819,391 | <p>Is there a simple way to calculate the average for each column in a pandas DataFrame and for each row <em>exclude</em> the specific value? The <code>x</code> in each row below marks the value in each iteration to be excluded from the calculation:</p>
<pre><code> a b a b a b
0 1 2 0 x x 0 1 2
1 2 4 first loop 1 2 4 second loop 1 x x etc.
2 3 6 ---> 2 3 6 ---> 2 3 6 --->
3 4 8 3 4 8 3 4 8
4 5 10 4 5 10 4 5 10
____________ _____________
col_avg: 3.5 7.0 col_avg: 3.25 6.5
Using only 4 values at each iteration, as the "x" is excluded from data set
</code></pre>
<p>resulting in a new DataFrame</p>
<pre><code> a_x b_x
0 3.5 7.0
1 3.25 6.5
2 3.0 6.0
3 2.75 5.5
4 2.5 5.0
</code></pre>
<p>Thanks</p>
<p>/N</p>
| 2 | 2016-10-02T16:55:59Z | 39,819,536 | <p>To start off with the first step, let's say we were interested in summing instead of calculating the average values. In that case, we would be adding all elems along each col except the current elem. Other way to look at it/solve it would be to sum all elems along each col and subtract the current elem itself. So, essentially we could get the sum for all columns with <code>df.sum(0)</code> and simply subtract <code>df</code> from it, keeping the axis
aligned. <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>Broadcasting</code></a> would take care of performing these operations across all cols in one go.</p>
<p>To get the second step of averaging, we simply divide by the number of elems involved for each col's summing, i.e. <code>df.shape[0]-1</code>.</p>
<p>Thus, we would have a vectorized solution, like so -</p>
<pre><code>df_out = (df.sum(0) - df)/float(df.shape[0]-1)
</code></pre>
<p>Sample run -</p>
<pre><code>In [128]: df
Out[128]:
a b
0 1 2
1 2 4
2 3 6
3 4 8
4 5 10
In [129]: (df.sum(0) - df)/float(df.shape[0]-1)
Out[129]:
a b
0 3.50 7.0
1 3.25 6.5
2 3.00 6.0
3 2.75 5.5
4 2.50 5.0
</code></pre>
<p>To set the column names to the desired ones, do : <code>df_out.columns = ['a_x','b_x']</code>.</p>
| 3 | 2016-10-02T17:13:49Z | [
"python",
"pandas"
]
|
Display url variable from views.py in Django template | 39,819,505 | <p>I want have my <em>url</em> come from <strong>views.py</strong> and then I can pass it as variable to <code>href</code> tag in template.</p>
<p><strong>views.py:</strong></p>
<pre><code>context {
'urlLink': "{% url 'myapp:theURL' %}"
...
}
</code></pre>
<p><strong>index.html:</strong></p>
<pre><code><a href="{{ urlLink }}" LINK 1 </a>
</code></pre>
<p>I have the above and it is not working. I have also tried <code><a href="{{ urlLink|escape }}" LINK 1 </a></code> but no success. </p>
| 1 | 2016-10-02T17:09:36Z | 39,819,537 | <p>you need <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse" rel="nofollow">reverse</a></p>
<pre><code>context {
'urlLink': "%s" % reverse('view_name')
}
</code></pre>
<p>you cannot use <code>{% url 'myapp:theURL' %}</code> in views.py since this is a template tag</p>
| 1 | 2016-10-02T17:13:52Z | [
"python",
"django"
]
|
Display url variable from views.py in Django template | 39,819,505 | <p>I want have my <em>url</em> come from <strong>views.py</strong> and then I can pass it as variable to <code>href</code> tag in template.</p>
<p><strong>views.py:</strong></p>
<pre><code>context {
'urlLink': "{% url 'myapp:theURL' %}"
...
}
</code></pre>
<p><strong>index.html:</strong></p>
<pre><code><a href="{{ urlLink }}" LINK 1 </a>
</code></pre>
<p>I have the above and it is not working. I have also tried <code><a href="{{ urlLink|escape }}" LINK 1 </a></code> but no success. </p>
| 1 | 2016-10-02T17:09:36Z | 39,819,538 | <p>If you need to use something similar to the <code>{% url %}</code> template tag in your view code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse" rel="nofollow">reverse</a> function has the following signature:</p>
<pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None)
</code></pre>
<p>So in your context:</p>
<pre><code>context {
'urlLink': reverse('viewname')
}
</code></pre>
<p>Then you can use in your template:</p>
<pre><code><a href="{{urlLink}}">Link1</a>
</code></pre>
| 2 | 2016-10-02T17:14:00Z | [
"python",
"django"
]
|
Print "Match Found" for each line the search is in and "Match not Found" if the search isnt in the whole file | 39,819,548 | <p>I want to print "Match Found" and the line that the match is in if the search is in a line in the file. Note - the match can be in more than one line and if so it should print every line the match is in. I have got this part working but i want to print "Match Not Found" once if the search isn't in the whole file. So far whatever I have tried either prints "Match Not Found" for every line the search isnt in or it prints "Match not Found" after printing the lines the search is in.</p>
<pre><code>f = open("cars.txt", "r+")
search = input("What do you want to search for? ")
for line_split in f:
if search in line_split:
print ("You searched for %s." % search)
print ("Match Found.")
print (line_split)
print ("--------------------")
else:
print ("You searched for %s" % search)
print ("Match Not Found.")
print ("--------------------")
f.close
</code></pre>
| 0 | 2016-10-02T17:14:36Z | 39,819,677 | <p>The <code>else</code> block of the <code>for</code> would have been a great choice if you had to <code>break</code> the iteration once an item is found; but that isn't the case.</p>
<p>I think you may want to set a <em>flag</em> instead of using the <code>else</code> and testing after the <code>for</code> is completed:</p>
<pre><code>found = None
for line_split in f:
if search in line_split:
...
if not found:
found = True
if not found:
print ("You searched for %s" % search)
print ("Match Not Found.")
</code></pre>
| 0 | 2016-10-02T17:30:13Z | [
"python",
"python-3.x"
]
|
Print "Match Found" for each line the search is in and "Match not Found" if the search isnt in the whole file | 39,819,548 | <p>I want to print "Match Found" and the line that the match is in if the search is in a line in the file. Note - the match can be in more than one line and if so it should print every line the match is in. I have got this part working but i want to print "Match Not Found" once if the search isn't in the whole file. So far whatever I have tried either prints "Match Not Found" for every line the search isnt in or it prints "Match not Found" after printing the lines the search is in.</p>
<pre><code>f = open("cars.txt", "r+")
search = input("What do you want to search for? ")
for line_split in f:
if search in line_split:
print ("You searched for %s." % search)
print ("Match Found.")
print (line_split)
print ("--------------------")
else:
print ("You searched for %s" % search)
print ("Match Not Found.")
print ("--------------------")
f.close
</code></pre>
| 0 | 2016-10-02T17:14:36Z | 39,819,799 | <p>First of all, I think you are misunderstanding the way of how "else" statement after the for loop works. It will execute only if the for loop wasn't break.</p>
<pre><code>n = 10
for idx in range(n):
if idx > 11:
print('Yey, we reached {}'.format(idx))
break
else:
print('Damn, we almost had it!')
</code></pre>
<p>This code will result in:</p>
<pre><code>Damn, we almost had it!
</code></pre>
<p>But if we change n = 20, we will get:</p>
<pre><code>Yey, we reached 12
</code></pre>
<p>I see no "break" in your code, so it's either an intendation error, or you just didn't realized that.</p>
<p>I will not post the next way of solving the problem, when it was already been told. I just wanted u to know the difference in using "else" statement outside the for loop. </p>
| 0 | 2016-10-02T17:42:23Z | [
"python",
"python-3.x"
]
|
Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer | 39,819,700 | <p>I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).<br>
An answer to a similar question here <a href="http://stackoverflow.com/questions/13550076/replace-centralwidget-in-mainwindow">Replace CentralWidget in MainWindow</a>, suggests using QStackedWidgets but they did not use Qt Designer to make their GUI apps whereas I have two .py files, one is the main window file and the other of window that i want to show after a button press take place, hence i don't know how to combine these two in my main.py file.
For Example my main window looks like this:<br>
<a href="http://i.stack.imgur.com/soSsW.png" rel="nofollow"><img src="http://i.stack.imgur.com/soSsW.png" alt="Main Window"></a><br>
And after clicking on the button it should replace the existing window with this:<br>
<a href="http://i.stack.imgur.com/jmgk4.png" rel="nofollow"><img src="http://i.stack.imgur.com/jmgk4.png" alt="New Window"></a><br>
I would also like to know if the second window should be of type QStackedWindow, QDialog or QWidget?<br>
Here is my main.py code </p>
<pre><code>from PyQt4 import QtGui
import sys
import design, design1
import os
class ExampleApp(QtGui.QMainWindow, design.Ui_MainWindow):
def __init__(self, parent=None):
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
self.btnBrowse.clicked.connect(self.doSomething)
def doSomething(self):
# Code to replace the main window with a new window
pass
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-10-02T17:32:23Z | 39,838,313 | <p>You probably don't want to actually create and delete a bunch of windows, but if you really want to, you could do it like this</p>
<pre><code>def doSomething(self):
# Code to replace the main window with a new window
window = OtherWindow()
window.show()
self.close()
</code></pre>
<p>The in the <code>OtherWindow</code> class</p>
<pre><code>class OtherWindow(...):
...
def doSomething(self):
window = ExampleApp()
window.show()
self.close()
</code></pre>
<p>You actually probably don't want to do this. It would be much better if you simply created 1 main window, with a <code>QStackedWidget</code> and put the different controls and widgets on different tabs of the stacked widget and just switch between them in the same window.</p>
| 0 | 2016-10-03T18:41:54Z | [
"python",
"pyqt",
"qt-designer"
]
|
Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer | 39,819,700 | <p>I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).<br>
An answer to a similar question here <a href="http://stackoverflow.com/questions/13550076/replace-centralwidget-in-mainwindow">Replace CentralWidget in MainWindow</a>, suggests using QStackedWidgets but they did not use Qt Designer to make their GUI apps whereas I have two .py files, one is the main window file and the other of window that i want to show after a button press take place, hence i don't know how to combine these two in my main.py file.
For Example my main window looks like this:<br>
<a href="http://i.stack.imgur.com/soSsW.png" rel="nofollow"><img src="http://i.stack.imgur.com/soSsW.png" alt="Main Window"></a><br>
And after clicking on the button it should replace the existing window with this:<br>
<a href="http://i.stack.imgur.com/jmgk4.png" rel="nofollow"><img src="http://i.stack.imgur.com/jmgk4.png" alt="New Window"></a><br>
I would also like to know if the second window should be of type QStackedWindow, QDialog or QWidget?<br>
Here is my main.py code </p>
<pre><code>from PyQt4 import QtGui
import sys
import design, design1
import os
class ExampleApp(QtGui.QMainWindow, design.Ui_MainWindow):
def __init__(self, parent=None):
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
self.btnBrowse.clicked.connect(self.doSomething)
def doSomething(self):
# Code to replace the main window with a new window
pass
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-10-02T17:32:23Z | 39,838,590 | <p>You can use the QStackedWindow to create a entire new window and hten connect it to the main window through onclick() event.</p>
<pre><code>button.clicked.connect(self.OtherWindow)
</code></pre>
<p>Or else you can simply use the</p>
<pre><code>class OtherWindow(self):
Owindow = OtherWindow()
Owindow.show()
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-10-03T18:59:16Z | [
"python",
"pyqt",
"qt-designer"
]
|
Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer | 39,819,700 | <p>I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).<br>
An answer to a similar question here <a href="http://stackoverflow.com/questions/13550076/replace-centralwidget-in-mainwindow">Replace CentralWidget in MainWindow</a>, suggests using QStackedWidgets but they did not use Qt Designer to make their GUI apps whereas I have two .py files, one is the main window file and the other of window that i want to show after a button press take place, hence i don't know how to combine these two in my main.py file.
For Example my main window looks like this:<br>
<a href="http://i.stack.imgur.com/soSsW.png" rel="nofollow"><img src="http://i.stack.imgur.com/soSsW.png" alt="Main Window"></a><br>
And after clicking on the button it should replace the existing window with this:<br>
<a href="http://i.stack.imgur.com/jmgk4.png" rel="nofollow"><img src="http://i.stack.imgur.com/jmgk4.png" alt="New Window"></a><br>
I would also like to know if the second window should be of type QStackedWindow, QDialog or QWidget?<br>
Here is my main.py code </p>
<pre><code>from PyQt4 import QtGui
import sys
import design, design1
import os
class ExampleApp(QtGui.QMainWindow, design.Ui_MainWindow):
def __init__(self, parent=None):
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
self.btnBrowse.clicked.connect(self.doSomething)
def doSomething(self):
# Code to replace the main window with a new window
pass
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-10-02T17:32:23Z | 39,860,670 | <p>Here is a simple example, you just have to use your own logistic but it's a simple way to represent what you are looking for.</p>
<p>You can use QWindow instead of QWidgets if your prefer, or different layout to dispose your "objects" or whatever. Maybe change a bit how to add items inside layout if not widget... things like that. :)</p>
<pre><code>from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QStackedLayout
from PyQt5.QtWidgets import QWidget, QApplication
class MyWindow(QMainWindow):
front_wid = None
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
# MAIN WINDOW size
self.setFixedSize(200,200)
# CENTRAL WIDGET
self.central_wid = QWidget()
self.layout_for_wids = QStackedLayout()
# BUTTON TO SWITCH BETWEEN WIDGETS
self.btn_switch = QPushButton("Switch")
self.btn_switch.clicked.connect(self.switch_wids)
self.btn_switch.setFixedSize(50,50)
self.btn_switch
# 2 WIDGETS
self.wid1 = QWidget()
self.wid1.setStyleSheet("""background: blue;""")
self.wid1.setFixedSize(200,200)
self.wid1.move(100, 100)
self.wid2 = QWidget()
self.wid2.setStyleSheet("""background: green;""")
self.wid2.setFixedSize(200, 200)
self.wid2.move(100, 100)
# LAYOUT CONTAINER FOR WIDGETS AND BUTTON
self.layout_for_wids.addWidget(self.btn_switch)
self.layout_for_wids.addWidget(self.wid1)
self.layout_for_wids.addWidget(self.wid2)
# ENTERING LAYOUT
self.central_wid.setLayout(self.layout_for_wids)
# CHOOSE YOUR CENTRAL WIDGET
self.setCentralWidget(self.central_wid)
# WHICH WIDGET IS ON THE FRONT
self.front_wid = 1
def switch_wids(self):
# LOGIC TO SWITCH
if self.front_wid == 1:
self.wid1.hide()
self.wid2.show()
self.front_wid = 2
else:
self.wid1.show()
self.wid2.hide()
self.front_wid = 1
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.resize(222, 222)
main.show()
sys.exit(app.exec_())
</code></pre>
<p><strong>By the way it's PyQt5, if you want to use PyQt4 you have to change the imports that's all.</strong></p>
| 0 | 2016-10-04T19:52:06Z | [
"python",
"pyqt",
"qt-designer"
]
|
Duplicate results in Xpath and not CSS selectors in scrapy | 39,819,860 | <p>So I am playing around with scrapy through the <a href="https://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">tutorial</a>. I am trying to scrape the text, author and tags of each quote in the <a href="http://quotes.toscrape.com/page/1/" rel="nofollow">companion website</a>
when using CSS selectors like mentioned there:</p>
<pre><code>for quote in response.css('div.quote'):
print quote.css('span.text::text').extract()
print quote.css('span small::text').extract()
print quote.css('div.tags a.tag::text').extract()
</code></pre>
<p>I get the desired result (i.e: print of each text, author and quotes once).
But once using Xpath selectors like this:</p>
<pre><code>for quote in response.xpath("//*[@class='quote']"):
print quote.xpath("//*[@class='text']/text()").extract()
print quote.xpath("//*[@class='author']/text()").extract()
print quote.xpath("//*[@class='tag']/text()").extract()
</code></pre>
<p>I get duplicates results! </p>
<p>I still can't find why there is such a difference between the 2.</p>
| 1 | 2016-10-02T17:48:09Z | 39,821,410 | <p>Try <code>.//</code> instead of <code>//</code> for your relative searches e.g. </p>
<p><code>print quote.xpath(".//*[@class='text']/text()").extract()</code></p>
<p>When you use <code>//</code>, although you're searching from <code>quote</code>, it takes this to mean an absolute search so its context is still the root of the document. <code>.//</code> however, means to search from <code>.</code> - the current node - and the context of this search will be limited to the elements nested under <code>quote</code>.</p>
<p>As a side note, if you're looking to get the exact same results, you should consider changing <code>*</code> to the tags you used in the CSS search - <code>span</code> or <code>div</code>. In this case it doesn't make any difference but just a head's up for future reference.</p>
| 2 | 2016-10-02T20:31:50Z | [
"python",
"xpath",
"css-selectors",
"scrapy"
]
|
Duplicate results in Xpath and not CSS selectors in scrapy | 39,819,860 | <p>So I am playing around with scrapy through the <a href="https://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">tutorial</a>. I am trying to scrape the text, author and tags of each quote in the <a href="http://quotes.toscrape.com/page/1/" rel="nofollow">companion website</a>
when using CSS selectors like mentioned there:</p>
<pre><code>for quote in response.css('div.quote'):
print quote.css('span.text::text').extract()
print quote.css('span small::text').extract()
print quote.css('div.tags a.tag::text').extract()
</code></pre>
<p>I get the desired result (i.e: print of each text, author and quotes once).
But once using Xpath selectors like this:</p>
<pre><code>for quote in response.xpath("//*[@class='quote']"):
print quote.xpath("//*[@class='text']/text()").extract()
print quote.xpath("//*[@class='author']/text()").extract()
print quote.xpath("//*[@class='tag']/text()").extract()
</code></pre>
<p>I get duplicates results! </p>
<p>I still can't find why there is such a difference between the 2.</p>
| 1 | 2016-10-02T17:48:09Z | 39,827,996 | <p>When you use // it will get all results from response. If you use .// then it scope will be limited to that selector. Try <code>.//</code> instead of <code>//</code>. It will solve your problem :-)</p>
| 0 | 2016-10-03T09:07:18Z | [
"python",
"xpath",
"css-selectors",
"scrapy"
]
|
In which way are these two PowerPoint Shapes different (accessed via API) | 39,819,876 | <p>As part of an open source assistive technology project (<a href="https://hackaday.io/project/15567-the-open-voice-factory" rel="nofollow">here</a>), I am accessing a PowerPoint file by python API (<a href="https://python-pptx.readthedocs.io/en/latest/" rel="nofollow">python-pptx</a>). </p>
<p>Some shapes are causing exceptions when I look at color. But it's hard to see which. </p>
<p>I've created this minimal example: <a href="https://www.dropbox.com/s/o5z22lqwb66jemq/forUpload.pptx?dl=0" rel="nofollow">https://www.dropbox.com/s/o5z22lqwb66jemq/forUpload.pptx?dl=0</a> </p>
<p>and indeed, here's a screenshot: </p>
<p><a href="http://i.stack.imgur.com/w3k75.png" rel="nofollow"><img src="http://i.stack.imgur.com/w3k75.png" alt="enter image description here"></a></p>
<p>It consists of a single slide, with shapes that work on the left, and shapes that fail on the right. Using the format painter will make a shape work (or not, depending on the source of the formatting) but I've been through every way of checking the formats that I can think of, and both sets of shapes appear identical. </p>
<p>How are the two sets of shapes in the minimal example different?</p>
<p>(for those who might be interested from a API point of view. The line that causes the problem is: </p>
<pre><code>self.colours[co][ro] = shape.fill.fore_colour.rgb
</code></pre>
<p>which is in <a href="https://github.com/joereddington/TheOpenVoiceFactory/blob/master/grab_text.py" rel="nofollow">https://github.com/joereddington/TheOpenVoiceFactory/blob/master/grab_text.py</a></p>
<p>and the exception is:</p>
<pre><code>Traceback (most recent call last): File "grab_text.py", line 374, in <module>
grids = extract_grid(prs) File "grab_text.py", line 353, in extract_grid
grids.append(Grid(prs, slide, gridSize)) File "grab_text.py", line 119, in __init__
self.process_shape(shape) File "grab_text.py", line 164, in process_shape
ro] = shape.fill.fore_color.rgb File "/Library/Python/2.7/site-packages/pptx/dml/fill.py", line 43, in fore_color
return self._fill.fore_color File "/Library/Python/2.7/site-packages/pptx/dml/fill.py", line 161, in fore_color
raise TypeError(tmpl) TypeError: a transparent (background) fill has no foreground color
</code></pre>
<p>)</p>
| 1 | 2016-10-02T17:49:26Z | 39,913,256 | <p>You need to call:</p>
<pre><code>shape.fill.solid()
</code></pre>
<p>before attempting to access the <code>fore_color</code> attribute.</p>
<p>A fill can have several types, each of which have a different attribute set. The <code>.fore_color</code> attribute is particular to a solid fill. By default, the fill is transparent (i.e. None).</p>
<p>A little more about it in the documentation here:
<a href="http://python-pptx.readthedocs.io/en/latest/user/autoshapes.html#fill" rel="nofollow">http://python-pptx.readthedocs.io/en/latest/user/autoshapes.html#fill</a></p>
| 0 | 2016-10-07T08:52:40Z | [
"python",
"powerpoint"
]
|
Quicksort with insertion sort Python not working | 39,819,878 | <p>I've been trying to run the quicksort with a switch to insertion sort when the sub array size is less than 10. So it turns out, i'm not getting a sorted list.</p>
<p>Where am i going wrong?</p>
<pre><code>import random
import time
m = 0
def quicksort(numList, first, last):
if first<last:
sizeArr = last - first + 1
if(sizeArr < m):
insert_sort(numList, first, last)
else:
mid = partition(numList, first, last)
quicksort(numList, first, mid-1)
quicksort(numList, mid + 1, last)
def partition(numList, first, last):
piv = numList[last]
i = first-1
for j in range(first,last):
if numList[j] < piv:
i += 1
temp = numList[i]
numList[i] = numList[j]
numList[j] = temp
tempo = numList[i+1]
numList[i+1] = numList[last]
numList[last] = tempo
return i+1
def insert_sort(numList, first, last):
for x in range(first, last):
key = numList[x]
y = x-1
while y > -1 and numList[y]> key:
numList[y+1] = numList[y]
y = y-1
numList[y+1] = key
if __name__ == '__main__':
start = time.time()
numList = random.sample(range(5000), 100)
m = 10
quicksort(numList, 0, len(numList) - 1)
print numList
print "Time taken: " + str(time.time() - start)
</code></pre>
<p>input is some random array of sizes between 100 - 1000000. I'm using a random generator as you can see. </p>
<p>Please help me.</p>
| 0 | 2016-10-02T17:49:48Z | 39,819,992 | <p>You have an off-by-one error in <code>insert_sort</code> function. Iterate over <code>range(first, last+1)</code> and it will sort correctly.</p>
| 0 | 2016-10-02T18:02:10Z | [
"python",
"quicksort",
"insertion-sort"
]
|
How the below program is possible in python | 39,819,922 | <p>I came with a situation where the method of class A to be called from class B.</p>
<pre><code>class A(object):
def __init__(self, a):
self.a = a
def abc(self):
print self.a
class B(A):
def __init__(self):
super(B, self).abc()
def method1():
a = A(2)
method1()
b = B()
Expecting Output: 2
</code></pre>
<p>Is it possible to call method 'abc' from class B with changing class A and should not create class A object in class B. If yes, then please let me know the solution.</p>
<p>The above program which I tried is giving error.</p>
<p>And the error I am getting is below</p>
<pre><code>Traceback (most recent call last):
File "a.py", line 12, in <module>
b = B()
File "a.py", line 10, in __init__
super(B, self).abc()
File "a.py", line 6, in abc
print self.a
AttributeError: 'B' object has no attribute 'a'
</code></pre>
| -1 | 2016-10-02T17:54:16Z | 39,820,045 | <p>Your B class __init__ method is not taking any argument, while the __init__ of class A require you to pass one (named "a"), and yet, you are not providing it. Neither in your B class or by passing it to A.</p>
<p>However, this would work.</p>
<pre><code>class A(object):
def __init__(self, a):
self.a = a
def abc(self):
print self.a
class B(A):
def __init__(self):
self.a = 10
super(B, self).abc()
</code></pre>
<p>Or:</p>
<pre><code>class B(A):
def __init__(self):
super(B, self).__init__(10)
inst = B()
inst.abc() # 10
</code></pre>
| 2 | 2016-10-02T18:07:46Z | [
"python",
"python-2.7"
]
|
How the below program is possible in python | 39,819,922 | <p>I came with a situation where the method of class A to be called from class B.</p>
<pre><code>class A(object):
def __init__(self, a):
self.a = a
def abc(self):
print self.a
class B(A):
def __init__(self):
super(B, self).abc()
def method1():
a = A(2)
method1()
b = B()
Expecting Output: 2
</code></pre>
<p>Is it possible to call method 'abc' from class B with changing class A and should not create class A object in class B. If yes, then please let me know the solution.</p>
<p>The above program which I tried is giving error.</p>
<p>And the error I am getting is below</p>
<pre><code>Traceback (most recent call last):
File "a.py", line 12, in <module>
b = B()
File "a.py", line 10, in __init__
super(B, self).abc()
File "a.py", line 6, in abc
print self.a
AttributeError: 'B' object has no attribute 'a'
</code></pre>
| -1 | 2016-10-02T17:54:16Z | 39,820,728 | <p>Here:</p>
<pre><code>class B(A):
def __init__(self):
super(B, self).abc()
</code></pre>
<p>The constructor of <code>A</code> is never called, so the initialization done in <code>A.__init__</code> is missing. It fails in <code>print self.a</code>, because there is no <code>a</code>.
The super constructor should be called.</p>
<p>Furthermore, <code>super(B, self).abc()</code> is the same as <code>self.abc()</code>.</p>
<p>If there was a method named <code>abc</code> defined in <code>B</code>, then <code>self.abc()</code> would call the method from <code>B</code>, whereas <code>super(B, self).abc()</code> would call the method from the superclass.</p>
<p>So, since those are the same, I would not use the ugly one. It just makes the code less readable.</p>
<p>With those two fixes:</p>
<pre><code>class B(A):
def __init__(self):
super(B, self).__init__(1000) # whatever default value
self.abc()
</code></pre>
| 0 | 2016-10-02T19:20:46Z | [
"python",
"python-2.7"
]
|
Selenium webdriver seems not working properly with Firefox 49.0. Am I missing something? | 39,819,937 | <p>I have gone through previous questions but did not find anyone else running into my issue.</p>
<p>This simple code hangs</p>
<pre><code>from selenium import webdriver
d = webdriver.Firefox();
</code></pre>
<p>The browser gets launched, but it just hangs there. After sometime, it crashes and I get the error</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile.
Profile Dir: /tmp/tmpn_MQnf If you specified a log_file in the
FirefoxBinary constructor, check it for details.
</code></pre>
<p>I have Firefox49 on Ubuntu 14.04 LTS. I had selenium 2.53.6 and reading a previous post, I upgraded to selenium 3.0.0.b3. I also downloaded geckdriver and put it in /usr/bin</p>
<p>It looks like I was still running older version of selenium. But when I uninstalled that and installed selenium 3.0.0.b3, I see the following error -</p>
<pre><code>selenium.ââcommon.exceptions.WeââbDriverException:
Message: Service geckodriver unexpectedly exited. Status code was: 2
</code></pre>
<p>What am I missing?</p>
| 1 | 2016-10-02T17:56:38Z | 39,824,443 | <p>Selenium 3 is still in beta state, and geckodriver is highly unstable. Dig deep and you will find the reported issues with geckodriver.</p>
| 0 | 2016-10-03T04:00:18Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver",
"ubuntu-14.04"
]
|
Selenium webdriver seems not working properly with Firefox 49.0. Am I missing something? | 39,819,937 | <p>I have gone through previous questions but did not find anyone else running into my issue.</p>
<p>This simple code hangs</p>
<pre><code>from selenium import webdriver
d = webdriver.Firefox();
</code></pre>
<p>The browser gets launched, but it just hangs there. After sometime, it crashes and I get the error</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile.
Profile Dir: /tmp/tmpn_MQnf If you specified a log_file in the
FirefoxBinary constructor, check it for details.
</code></pre>
<p>I have Firefox49 on Ubuntu 14.04 LTS. I had selenium 2.53.6 and reading a previous post, I upgraded to selenium 3.0.0.b3. I also downloaded geckdriver and put it in /usr/bin</p>
<p>It looks like I was still running older version of selenium. But when I uninstalled that and installed selenium 3.0.0.b3, I see the following error -</p>
<pre><code>selenium.ââcommon.exceptions.WeââbDriverException:
Message: Service geckodriver unexpectedly exited. Status code was: 2
</code></pre>
<p>What am I missing?</p>
| 1 | 2016-10-02T17:56:38Z | 39,853,263 | <p>Try renaming the downloaded Gecko Driver to Wires and Set the Capabilities as mentioned Below.</p>
<pre><code>System.setProperty("webdriver.gecko.driver", "//home//.....//BrowserDrivers//wires");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
Driver = new MarionetteDriver(capabilities);
</code></pre>
<p>I tried with the Above code on FireFox 49 on Linux Ubuntu 14.04 LTS... Code Works Fine For Me in Java..
Also try to downgrade the selenium WebDriver from Beta to 2.53 as Beta version is unstable..</p>
| 0 | 2016-10-04T13:10:27Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver",
"ubuntu-14.04"
]
|
Selenium webdriver seems not working properly with Firefox 49.0. Am I missing something? | 39,819,937 | <p>I have gone through previous questions but did not find anyone else running into my issue.</p>
<p>This simple code hangs</p>
<pre><code>from selenium import webdriver
d = webdriver.Firefox();
</code></pre>
<p>The browser gets launched, but it just hangs there. After sometime, it crashes and I get the error</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile.
Profile Dir: /tmp/tmpn_MQnf If you specified a log_file in the
FirefoxBinary constructor, check it for details.
</code></pre>
<p>I have Firefox49 on Ubuntu 14.04 LTS. I had selenium 2.53.6 and reading a previous post, I upgraded to selenium 3.0.0.b3. I also downloaded geckdriver and put it in /usr/bin</p>
<p>It looks like I was still running older version of selenium. But when I uninstalled that and installed selenium 3.0.0.b3, I see the following error -</p>
<pre><code>selenium.ââcommon.exceptions.WeââbDriverException:
Message: Service geckodriver unexpectedly exited. Status code was: 2
</code></pre>
<p>What am I missing?</p>
| 1 | 2016-10-02T17:56:38Z | 39,854,643 | <p><a href="http://stackoverflow.com/questions/39715653/selenium-starts-but-does-not-load-a-page/39720178#39720178">Duplicate Question</a></p>
<p>There is some issue with Firefox version greater than 48.Better you downgrade the Firefox to lower than 47. I was having the same problem.</p>
| 0 | 2016-10-04T14:15:08Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver",
"ubuntu-14.04"
]
|
Python - Override parent class argument | 39,819,959 | <p>I have a super class and a sub class.</p>
<pre><code>class Vehicle:
def __init__(self, new_fuel, new_position):
self.fuel = new_fuel
self.position = new_position
class Car(Vehicle):
# Here, I am stating that when Car is initialized, the position will be
# at (0, 0), so when you call it, you do not have to give it a new_position argument
def __init__(self, new_fuel, new_position=(0, 0)):
super(Car, self).__init__(new_fuel, new_position)
self.new_position = new_position
</code></pre>
<p><strong>Problem:</strong></p>
<p>I want this to initialize a Car object with 10 fuel and position of (0, 0)
but I don't want to put in an argument for new_position because I've stated that when all cars are initialized, they have a position of (0, 0). Also, I don't want to change any arguments in the parent class (vehicle), I just want to override them within the sub classes (such as Car).</p>
<pre><code>test_car = Car(10)
print(test_car.new_position)
>>> (0,0)
</code></pre>
<p>However, it keeps giving me this error and asks to put in an argument for new_position</p>
<pre><code>TypeError: __init__() missing 1 required positional argument: 'new_position'
</code></pre>
| -1 | 2016-10-02T17:58:48Z | 39,820,234 | <p>As far as I understand what you are trying to achieve, just simply delete the "new_position" parameter from your Car __init__ method.</p>
<pre><code>class Vehicle:
def __init__(self, new_fuel, new_position):
self.fuel = new_fuel
self.position = new_position
class Car(Vehicle):
# Here, I am stating that when Car is initialized, the position will be
# at (0, 0), so when you call it, you do not have to give it a new_position argument
def __init__(self, new_fuel):
super(Car, self).__init__(new_fuel, new_position= (0, 0))
</code></pre>
<p>Later when any method from the Car class will need a "position" argument, it will search inside the Car class and when not found, it will jump into Vehicle and will find it.</p>
<p>Lets say that you've implemented get_position() method in your Vehicle class.</p>
<pre><code>class Vehicle:
<everything as always>
def get_position(self):
return self.position
class Car(Vehicle):
<everything as always>
a = Car(10)
a.get_position() # Returns (0, 0)
</code></pre>
<h1>Edit to comment:</h1>
<pre><code>class Vehicle:
def __init__(self, new_fuel):
self.fuel = new_fuel
def get_position(self):
return self.__class__.POSITION
class Car(Vehicle):
POSITION = (0, 0)
# Here, I am stating that when Car is initialized, the position will be
# at (0, 0), so when you call it, you do not have to give it a new_position argument
def __init__(self, new_fuel):
super(Car, self).__init__(new_fuel)
def new_position(self, value):
self.__class__.POSITION = value
a = Car(10)
b = Car(20)
c = Car(30)
for each in [a, b, c]:
print(each.get_position())
(0, 0)
(0, 0)
(0, 0)
c.new_position((0, 1))
for each in [a, b, c]:
print(each.get_position())
(0, 1)
(0, 1)
(0, 1)
</code></pre>
| 1 | 2016-10-02T18:26:43Z | [
"python"
]
|
Beautifulsoup get text based on nextSibling tag name | 39,820,006 | <p>I'm scraping multiple pages that all have a similar format, but it changes a little here and there and there are no classes to use to search for what I need.</p>
<p>The format looks like this:</p>
<pre><code><div id="mainContent">
<p>Some Text I don't want</p>
<p>Some Text I don't want</p>
<p>Some Text I don't want</p>
<span> More text I don't want</span>
<ul>...unordered-list items..</ul>
<p>Text I WANT</p>
<ol>...ordered-list items..</ol>
<p>Text I WANT</p>
<ol>...ordered-list items..</ol>
</div>
</code></pre>
<p>The number of ordered/unordered lists and other tags changes depending on the page, but what stays the same is I always want the text from the <code><p></code> tag that is the previous sibling of the <code><ol></code> tag.</p>
<p>What I'm trying (and isn't working) is:</p>
<pre><code>main = soup.find("div", {"id":"mainContent"})
for d in main.children:
if d.name == 'p' and d.nextSibling.name == 'ol':
print(d.text)
else:
print("fail")
</code></pre>
<p>The out put of this is <code>fail</code> for every iteration. In trying to figure out why this isn't working I tried:</p>
<pre><code>for d in main.children:
if d.name == 'p':
print(d.nextSibling.name)
else:
print("fail")
</code></pre>
<p>The output of this is something like:</p>
<pre><code>fail
None
fail
None
fail
None
fail
fail
fail
fail
fail
None
fail
</code></pre>
<p>etc...</p>
<p>Why is this not working like I think it would? How could I get the text from a <code><p></code> element <em>only</em> if the next tag is <code><ol></code>?</p>
| 2 | 2016-10-02T18:03:22Z | 39,820,505 | <p>You want only the <code>p</code> tags which are before <code>ol</code> tag. Find the <code>ol</code> tags first and then find the previous <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#tag" rel="nofollow">Tag</a> objects which are in this case, the <code>p</code> tag. Now your code is not working because, there is a newline between the <code>Tag</code> elements which are <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring" rel="nofollow">NavigableString</a> type objects. And <code>d.nextSibling</code> yields you those newlines also. So You have to check the type of the object here. </p>
<pre><code>from bs4 import Tag
# create soup
# find the ols
ols = soup.find_all('ol')
for ol in ols:
prev = ol.previous_sibling
while(not isinstance(prev, Tag)):
prev = prev.previous_sibling
print(prev.text)
</code></pre>
<p>This will give you the text you want.</p>
<pre><code>Text I WANT
Text I WANT
</code></pre>
| 2 | 2016-10-02T18:55:39Z | [
"python",
"html",
"beautifulsoup"
]
|
Beautifulsoup get text based on nextSibling tag name | 39,820,006 | <p>I'm scraping multiple pages that all have a similar format, but it changes a little here and there and there are no classes to use to search for what I need.</p>
<p>The format looks like this:</p>
<pre><code><div id="mainContent">
<p>Some Text I don't want</p>
<p>Some Text I don't want</p>
<p>Some Text I don't want</p>
<span> More text I don't want</span>
<ul>...unordered-list items..</ul>
<p>Text I WANT</p>
<ol>...ordered-list items..</ol>
<p>Text I WANT</p>
<ol>...ordered-list items..</ol>
</div>
</code></pre>
<p>The number of ordered/unordered lists and other tags changes depending on the page, but what stays the same is I always want the text from the <code><p></code> tag that is the previous sibling of the <code><ol></code> tag.</p>
<p>What I'm trying (and isn't working) is:</p>
<pre><code>main = soup.find("div", {"id":"mainContent"})
for d in main.children:
if d.name == 'p' and d.nextSibling.name == 'ol':
print(d.text)
else:
print("fail")
</code></pre>
<p>The out put of this is <code>fail</code> for every iteration. In trying to figure out why this isn't working I tried:</p>
<pre><code>for d in main.children:
if d.name == 'p':
print(d.nextSibling.name)
else:
print("fail")
</code></pre>
<p>The output of this is something like:</p>
<pre><code>fail
None
fail
None
fail
None
fail
fail
fail
fail
fail
None
fail
</code></pre>
<p>etc...</p>
<p>Why is this not working like I think it would? How could I get the text from a <code><p></code> element <em>only</em> if the next tag is <code><ol></code>?</p>
| 2 | 2016-10-02T18:03:22Z | 39,820,600 | <p>You can use a <em>css selector</em>, i.e <code>ul ~ p</code> to find all the p tags preceded by the <em>ul</em>:</p>
<pre><code>html = """<div id="mainContent">
<p>Some Text I don't want</p>
<p>Some Text I don't want</p>
<p>Some Text I don't want</p>
<span> More text I don't want</span>
<ul>...unordered-list items..</ul>
<p>Text I WANT</p>
<ol>...ordered-list items..</ol>
<p>Text I WANT</p>
<ol>...ordered-list items..</ol>
</div>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
print([p.text for p in soup.select("#mainContent ul ~ p")])
</code></pre>
<p>Which will give you:</p>
<pre><code>['Text I WANT', 'Text I WANT']
</code></pre>
<p>Or find the ol's and then look for the <em>previous sibling</em> p:</p>
<pre><code>print([ol.find_previous_sibling("p").text for ol in soup.select("#mainContent ol")])
</code></pre>
<p>Which would also give you:</p>
<pre><code>['Text I WANT', 'Text I WANT']
</code></pre>
| 2 | 2016-10-02T19:06:55Z | [
"python",
"html",
"beautifulsoup"
]
|
How to dynamically display time data stream on matplotlib | 39,820,036 | <p>I'm using matplotlib to display data saved on a csv file periodically,
now the data is plotted well but the time axis is hardly moving, in fact
the script is trying to show all the data stored on that file, I want to see only latest data and be able to scrol horizontaly to see older data
this is a part of the script : </p>
<pre><code>style.use('grayscale')
fig = plt.figure()
ax0= fig.add_subplot(511)
def animate(i):
graph_data = open('filelocation','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines :
if len(line)>1:
time0 , quantity0 = line.split (',')
xs.append(dt.datetime.strptime(time0,'%H:%M:%S.%f'))
ys.append(quantity0)
ax0.clear()
ax0.plot(xs,ys)
xs = matplotlib.dates.date2num(xs)
hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')
ax0.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax0.set_ylabel('risk')
ax0.xaxis.set_major_formatter(hfmt)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.ticklabel_format(style='sci',axis ='y' , scilimits = (0,0))
plt.show()
plt.clear()
</code></pre>
| 0 | 2016-10-02T18:06:18Z | 39,821,197 | <p>From that video, it looks like you want something like the following - I can still see a scrolling window in the video you posted so I'm still a little confused as to what you want. This uses <code>fig.canvas.draw</code> but there are other options using the matplotlib animation module (you didn't specify that it had to be using that module). </p>
<pre><code>import numpy as np, time
from matplotlib import pyplot as plt
import matplotlib
matplotlib.interactive(True)
rest_time = 0.001
data_stream = np.random.randn(200)
# Define the width of the viewing window (xaxis limits),
# and the number of points to be displayed until a scrolling window starts
window_width = 40
n = 60
fig, ax = plt.subplots()
plotted_data, = ax.plot([], [], 'bo-', lw = 1.5)
x = []
y = []
ax.set_xlim([0, window_width])
ax.set_ylim([-4, 4])
for t, d in enumerate(data_stream):
x.append(t)
y.append(d)
plotted_data.set_xdata(x)
plotted_data.set_ydata(y)
if t > window_width:
ax.set_xlim([0, t])
if len(x) > n:
ax.set_xlim([t-n, t])
time.sleep(rest_time)
fig.canvas.draw()
</code></pre>
| 0 | 2016-10-02T20:09:59Z | [
"python",
"python-2.7",
"python-3.x",
"matplotlib",
"plot"
]
|
Python 3 regex How to use grouping properly? | 39,820,159 | <p><strong>EDIT: Sorry, I am just allowed to insert 2 links, the other ones are as plain text here.</strong></p>
<p>Hi
I am very new to Python and regex. I searched at regex101 and many other sites how to use it properly but it just isn't working and I don't know what to do any more.</p>
<p>I have some IP cameras at home and they send over ftp pictures.
They have a names like (I removed MAC and serial from the strings):</p>
<ul>
<li>image_20130225_175225_9.jpg</li>
<li>AABBCCDDEEFF(UserNameOfCam)_0_20150905215835_0.jpg</li>
<li>112233445566(0000serial)_0_20130625223148_1337167.jpg</li>
<li>012345-6789ABCDEF01-234567_20160724_180030.jpg</li>
<li>AA_BB_CC_DD_EE_FF_OPI-012345-QWERT_0_20130724133101_8.jpg</li>
</ul>
<p>To free up space once a day all those jpeg pictures will be converted to a mp4 over mencoder with a batch file (windows). That is already working BUT in the image is not burned in the time information. It's just a plain picture without a OSD. </p>
<p>So I tried making a .srt file to show the time and date as subtitle in the video player. Because I just learned C in school I hardcoded a ugly way to produce it with looking at each filename and searched manually what part in the string determines each cam e.g. the first cam always starts with "image_" the second with the name of the cam, the third would be the serial in the filename and so on.</p>
<p>It looks like that:</p>
<pre><code>if(strstr(temp_line, "image")) //for the first cam
{ do extracting info }
else if(strstr(temp_line, "(UserNameOfCam)_")) //for the second
{ do extracting info }
else if(...
</code></pre>
<p>It was very unflexible and if I want to rename the 2nd cam, I had to change the sourcecode of the srt generator manually in C and recompile it every time. </p>
<p>Then I thought "Hell, lets try Python, it was made for scripting like that" and after several days and hour of hours programming and googling I made the script. Then I wanted to do it with regex because it would fit perfect.</p>
<p>Because of the beginner I am, I use <strong>debuggex</strong> to visualize the regex making and <strong>pythex</strong> for the matching. So far it can recognise the first camera and I was happy :) but after now several hours of trying getting it recognise more then 1 pattern I don't know what I am doing wrong. I tried the \g the (?P= and many other methodes of those but none are working. I am doing something completly wrong and don't know what.</p>
<p>Here is the pattern of the first cam</p>
<blockquote>
<p>www.debuggex.com/r/kvd5IZc760Z-cZmz</p>
</blockquote>
<p><a href="http://pythex.org/?regex=(%3FP%3Ccam00%3E%20%5E%20(%3F%3Aimage_)%20(%3FP%3Cyear%3E(%3F%3A19%7C20)%5Cd%5Cd)%20(%3FP%3Cmonth%3E0%5B1-9%5D%7C1%5B012%5D)%20(%3FP%3Cday%3E0%5B1-9%5D%7C%5B12%5D%5B0-9%5D%7C3%5B01%5D)%20(%3F%3A_)%20(%3FP%3Chour%3E0%5B0-9%5D%7C1%5B0-9%5D%7C2%5B0-4%5D)%20(%3FP%3Cminute%3E%5B0-5%5D%5B0-9%5D)%20(%3FP%3Csecond%3E%5B0-5%5D%5B0-9%5D)%20(%3F%3A_%5Cd%7B1%2C2%7D.jpg)%20%24%20)&test_string=image_20130225_175225_9.jpg&ignorecase=0&multiline=0&dotall=0&verbose=1" rel="nofollow">Here is the matching of the first cam</a></p>
<p>Here is the not working try for the first two cams</p>
<blockquote>
<p>www.debuggex.com/r/C0TwsxHS9QZoXIFc</p>
</blockquote>
<p>And here is the Python script of making the srt if needed.</p>
<blockquote>
<p>pastebin.com/kZPQnu9T</p>
</blockquote>
<p>Any hints or recommendation what to do to make it work, or where I made the wrong steps?</p>
<p><strong>EDIT2:</strong> I forgot to mention that I need information extracted from the regex as the time and dates are stores IN the filename. </p>
<p><strong>EDIT3:</strong> Thanks for the replya. I thought placing everything in one regex would make it faster, as it has to parse up to 100k lines. Also I tried to extract information out of the regex, as it is possible to name pattern as groups like "year". The Year information is always the same, so I thought, well make the year pattern once and just reuse it when needed, the extraction is then also handled....though it's not working that way. It can extract all the usefull information out from the first cam, but I don't get any match for the 2nd one if I try to reuse the pattern from the first cam. The "(?P=year)" line isnt matching and if I replase it with the same line as the first cam, it has a error because the year group is now doubled. Though it works IF i remove the whole pattern of the first cam.</p>
| 0 | 2016-10-02T18:18:51Z | 39,820,289 | <p>You don't need to make one gigantic regex that matches everything. It's better to make several smaller regex that matches the specific camera. </p>
<p>So if you have want to process the camera 1 and camera 2 the same your code could look something like this. </p>
<pre><code>import re
cam1 = re.compile(r'some regex')
cam2 = re.compile(r'something else')
if cam1.match(filename) and cam2.match(filename):
process_data()
</code></pre>
<p>Also, you'll only need grouping if you want to extract information from the regex. Otherwise grouping isn't really needed (unless perhaps you want to make the regex more legible). </p>
| 0 | 2016-10-02T18:31:21Z | [
"python",
"scripting",
"subtitle"
]
|
When to use a class instead of a dict | 39,820,214 | <p>User data, as follows:</p>
<pre><code>user = {"id": 1, "firstName": "Bar", "surname": "Foosson", "age": 20}
</code></pre>
<p>is sent to an application via json. </p>
<p>In many places in the code the following it done:</p>
<pre><code>user["firstName"] + " " + user["surname"]
</code></pre>
<p>which leads me to believe a function should be used:</p>
<pre><code>def name(user):
return user["firstName"] + " " + user["surname"]
</code></pre>
<p>which in turn leads me to believe that the code should be refactored with the use of a <code>User</code> class instead, with a <code>name</code> method. Do you agree and is there any argument for not refactoring the code to use a class instead?</p>
| 0 | 2016-10-02T18:24:23Z | 39,820,446 | <p>I'm sure you are hesitant to use classes because of the need to write boilerplate code.</p>
<p>But there's a nice library that may make your life easier: <a href="https://attrs.readthedocs.io/en/stable/" rel="nofollow"><code>attrs</code></a>.</p>
<p>Glyph has a post with a self-speaking title: <a href="https://glyph.twistedmatrix.com/2016/08/attrs.html" rel="nofollow">The One Python Library Everyone Needs</a>. Of course, it's an opinionated piece, but here's a quote from its <a href="https://attrs.readthedocs.io/en/stable/examples.html" rel="nofollow">Examples page</a>:</p>
<blockquote>
<pre><code>>>> @attr.s
... class Coordinates(object):
... x = attr.ib()
... y = attr.ib()
</code></pre>
<p>By default, all features are added, so you immediately have a fully functional data class with a nice <code>repr</code> string and comparison methods.</p>
<pre><code>>>> c1 = Coordinates(1, 2)
>>> c1
Coordinates(x=1, y=2)
>>> c2 = Coordinates(x=2, y=1)
>>> c2
Coordinates(x=2, y=1)
>>> c1 == c2
False
</code></pre>
</blockquote>
<p>It's a quite handy library, so check it out.</p>
<p>Here's an example of your <code>User</code> class:</p>
<pre><code>import attr
@attr.s
class User(object):
id = attr.ib()
firstName = attr.ib()
surname = attr.ib()
age = attr.ib()
@property
def name(self):
return '{0.firstName} {0.surname}'.format(self)
user_dict = {'id': 1, 'firstName': 'Bar', 'surname': 'Foosson', 'age': 20}
user = User(**user_dict)
assert user.name == 'Bar Foosson'
</code></pre>
| 1 | 2016-10-02T18:49:14Z | [
"python"
]
|
When to use a class instead of a dict | 39,820,214 | <p>User data, as follows:</p>
<pre><code>user = {"id": 1, "firstName": "Bar", "surname": "Foosson", "age": 20}
</code></pre>
<p>is sent to an application via json. </p>
<p>In many places in the code the following it done:</p>
<pre><code>user["firstName"] + " " + user["surname"]
</code></pre>
<p>which leads me to believe a function should be used:</p>
<pre><code>def name(user):
return user["firstName"] + " " + user["surname"]
</code></pre>
<p>which in turn leads me to believe that the code should be refactored with the use of a <code>User</code> class instead, with a <code>name</code> method. Do you agree and is there any argument for not refactoring the code to use a class instead?</p>
| 0 | 2016-10-02T18:24:23Z | 39,820,587 | <p>Dictionaries are great for storage and retrieval, but if you need more functionality on top of that, a class is usually the way to go. That way you can also assure certain attributes are set, etc.</p>
<p>For your situation, if a user's attributes are read-only, my approach would actually be using <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow"><code>namedtuple</code></a>. You get immutability of attributes, memory efficiency, and you can still set <code>name</code> to a pre-defined method to be used just like you'd use <code>property</code> on a class:</p>
<pre><code>from collections import namedtuple
@property
def name(self):
return '{} {}'.format(self.firstName, self.surname)
User = namedtuple('User', 'id firstName surname age')
User.name = name
user = User(1, 'Bar', 'Foosson', 20)
print(user.name) # Bar Foosson
user = User(2, 'Another', 'Name', 1)
print(user.name) # Another Name
</code></pre>
| 1 | 2016-10-02T19:05:37Z | [
"python"
]
|
Python: Connect using sockets via external IP | 39,820,253 | <p>Today, I have made my very first sockets program - I made a client and a server that message each other (kind of like a chat) using sockets. When using the internal IP as 'host', The connection is established, otherwise using the external IP, no connection is established.</p>
<p>Edit 1:</p>
<pre><code>#Client
s = socket.socket()
host = '123.123.123.123'
port = 9999
s.connect((host, port))
#Server
host = ''
port = 9999
s = socket.socket()
s.bind((host, port))
s.listen(5)
connection, address = s.accept()
</code></pre>
<p>How will this work properly with, for example, a laptop? Since your IP changes each time you switch Wifi, how would I be able to create a program that would permanently work with this specific laptop?</p>
<p>I understand that I have to port-forward the specific port to a specific internal machine such as 192.168.0.5. but what if I'm using a laptop and I don't have access to the WIFI router. I wouldn't have access to every router a laptop uses.</p>
<p>I want the code to be permanently compatible.</p>
| 0 | 2016-10-02T18:28:01Z | 39,820,511 | <p>Use <code>DynDNS.com</code> or <code>NoIP.com</code> portal. You install program on laptop which check your IP frequencly and sends current IP to portal which assigns this IP to your address like "my_laptop.noip.com". Then people can access your laptop using "my_laptop.noip.com" instead of IP address.</p>
<p>You always assign socket to IP of local network card (NIC) like WiFi. You can't assing to external IP. You have to config your router so requests to external IP:port will be send to your local IP:port. Of course Internet Provider routers can block your ports and it will not work.</p>
| 0 | 2016-10-02T18:57:17Z | [
"python",
"sockets",
"networking"
]
|
ValueError in computing precision using scikit-learn | 39,820,260 | <pre><code>from sklearn.metrics import precision_score
precision_score(expected, predicted)
</code></pre>
<p>where expected is <code>array([ 4., 3.])</code></p>
<p>and predicted is <code>array([ 2., 4.])</code></p>
<p>I get the foll. error: <code>*** ValueError: pos_label=1 is not a valid label: array([ 2., 3., 4.])</code></p>
<p>How can this be fixed?</p>
| 1 | 2016-10-02T18:28:39Z | 39,820,415 | <p>You need the <code>average</code> parameter for <em>multiclass</em> labels.</p>
<p>Else you would need to set <code>pos_label</code> as one of the class labels in both arrays i.e. 2, 3 or 4:</p>
<pre><code>>>> # score for all classes
>>> precision_score(expected, predicted, average=None)
array([ 0., 0., 0.])
>>> # score for each class
>>> precision_score(expected, predicted, pos_label=2)
0.0
>>> precision_score(expected, predicted, pos_label=3)
0.0
>>> precision_score(expected, predicted, pos_label=4)
0.0
</code></pre>
<p>Reference:
<a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html" rel="nofollow"><code>sklearn.metrics.precision_score</code></a></p>
| 1 | 2016-10-02T18:46:17Z | [
"python",
"scikit-learn",
"precision"
]
|
how to import scripts as modules in ipyhon? | 39,820,350 | <p>So, I've two python files:</p>
<p>the 1st "m12345.py"</p>
<pre><code>def my():
return 'hello world'
</code></pre>
<p>the 2nd "1234.py":</p>
<pre><code>from m12345 import *
a = m12345.my()
print(a)
</code></pre>
<p>On ipython I try to exec such cmds:</p>
<pre><code>exec(open("f:\\temp\\m12345.py").read())
exec(open("f:\\temp\\1234.py").read())
</code></pre>
<p>the error for the 2nd command is:</p>
<pre><code>ImportError: No module named 'm12345'
</code></pre>
<p>Please, help how to add the 1st file as a module for the 2nd?</p>
| 1 | 2016-10-02T18:39:37Z | 39,820,619 | <p>You have to create a new module (for example <code>m12345</code>) by calling <code>m12345 = imp.new_module('m12345')</code> and then exec the python script in that module by calling <code>exec(open('path/m12345.py').read(), m12345.__dict__)</code>. See the example below:</p>
<pre><code>import imp
pyfile = open('path/m12345.py').read()
m12345 = imp.new_module('m12345')
exec(pyfile, m12345.__dict__)
</code></pre>
<p>If you want the module to be in system path, you can add</p>
<pre><code>sys.modules['m12345'] = m12345
</code></pre>
<p>After this you can do</p>
<pre><code>import m12345
</code></pre>
<p>or</p>
<pre><code>from m12345 import *
</code></pre>
| 1 | 2016-10-02T19:09:34Z | [
"python",
"ipython",
"python-import"
]
|
how to import scripts as modules in ipyhon? | 39,820,350 | <p>So, I've two python files:</p>
<p>the 1st "m12345.py"</p>
<pre><code>def my():
return 'hello world'
</code></pre>
<p>the 2nd "1234.py":</p>
<pre><code>from m12345 import *
a = m12345.my()
print(a)
</code></pre>
<p>On ipython I try to exec such cmds:</p>
<pre><code>exec(open("f:\\temp\\m12345.py").read())
exec(open("f:\\temp\\1234.py").read())
</code></pre>
<p>the error for the 2nd command is:</p>
<pre><code>ImportError: No module named 'm12345'
</code></pre>
<p>Please, help how to add the 1st file as a module for the 2nd?</p>
| 1 | 2016-10-02T18:39:37Z | 39,820,717 | <p>First off, if you use the universal import (<code>from m12345 import *</code>) then you just call the <code>my()</code> function and not the <code>m12345.my()</code> or else you will get a </p>
<blockquote>
<p>NameError: name 'm12345' is not defined</p>
</blockquote>
<p>Secondly, you should add the following snippet in every script in which you want to have the ability of directly running it or not (when importing it).</p>
<pre><code>if "__name__" = "__main__":
pass
</code></pre>
<p>PS. Add this to the 1st script ("m12345.py").
PS2. Avoid using the universal import method since it has the ability to mess the namespace of your script. (For that reason, it isn't considered best practice).</p>
<p><strong>edit:</strong> Is the m12345.py located in the python folder (where it was installed in your hard drive)? If not, then you should add the directory it is located in the sys.path with:</p>
<pre><code>import sys
sys.path.append(directory)
</code></pre>
<p>where directory is the string of the location where your m12345.py is located. Note that if you use Windows you should use <code>/</code> and not <code>\</code>.
However it would be much easier to just relocate the script (if it's possible).</p>
| 2 | 2016-10-02T19:19:47Z | [
"python",
"ipython",
"python-import"
]
|
Computing product of ith row of array1 and ith column of array2 - NumPy | 39,820,372 | <p>I have a matrix <code>M1</code> of shape <code>(N*2)</code> and another matrix <code>M2</code> <code>(2*N)</code>, I want to obtain a result of <code>(N)</code>, each element <code>i</code> is the product of <code>i</code>th row of <code>M1</code> and <code>i</code>th column of <code>M2</code>.
I tried to use dot in NumPy, but it can only give me the matrix multiplication result, which is <code>(N*N)</code>, of course, I can take the diagonal which is what I want, I would like to know is there a better way to do this?</p>
| 1 | 2016-10-02T18:41:38Z | 39,820,461 | <p><strong>Approach #1</strong></p>
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p>
<pre><code>np.einsum('ij,ji->i',M1,M2)
</code></pre>
<p><strong>Explanation :</strong> </p>
<p>The original loopy solution would look something like this -</p>
<pre><code>def original_app(M1,M2):
N = M1.shape[0]
out = np.zeros(N)
for i in range(N):
out[i] = M1[i].dot(M2[:,i])
return out
</code></pre>
<p>Thus, for each iteration, we have :</p>
<pre><code>out[i] = M1[i].dot(M2[:,i])
</code></pre>
<p>Looking at the iterator, we need to align the first axis of <code>M1</code> with the second axis of <code>M2</code>. Again, since we are performing <code>matrix-multiplication</code> and that by its very definition is aligning the second axis of <code>M1</code> with the first axis of <code>M2</code> and also sum-reducing these elements at each iteration.</p>
<p>When porting over to <code>einsum</code>, keep the axes to be aligned between the two inputs to have the same string when specifying the string notation to it. So, the inputs would be <code>'ij,ji</code> for <code>M1</code> and <code>M2</code> respectively. The output after losing the second string from <code>M1</code>, which is same as first string from <code>M2</code> in that sum-reduction, should be left as <code>i</code>. Thus, the complete string notation would be : <code>'ij,ji->i'</code> and the final solution as : <code>np.einsum('ij,ji->i',M1,M2)</code>.</p>
<p><strong>Approach #2</strong></p>
<p>The number of cols in <code>M1</code> or number of rows in <code>M2</code> is <code>2</code>. So, alternatively, we can just slice, perform the element-wise multiplication and sum up those, like so -</p>
<pre><code>M1[:,0]*M2[0] + M1[:,1]*M2[1]
</code></pre>
<hr>
<p><strong>Runtime test</strong></p>
<pre><code>In [431]: # Setup inputs
...: N = 1000
...: M1 = np.random.rand(N,2)
...: M2 = np.random.rand(2,N)
...:
In [432]: np.allclose(original_app(M1,M2),np.einsum('ij,ji->i',M1,M2))
Out[432]: True
In [433]: np.allclose(original_app(M1,M2),M1[:,0]*M2[0] + M1[:,1]*M2[1])
Out[433]: True
In [434]: %timeit original_app(M1,M2)
100 loops, best of 3: 2.09 ms per loop
In [435]: %timeit np.einsum('ij,ji->i',M1,M2)
100000 loops, best of 3: 13 µs per loop
In [436]: %timeit M1[:,0]*M2[0] + M1[:,1]*M2[1]
100000 loops, best of 3: 14.2 µs per loop
</code></pre>
<p>Massive speedup there!</p>
| 1 | 2016-10-02T18:50:40Z | [
"python",
"numpy",
"matrix"
]
|
Extract header names from a CSV and use it to plot against each other in Python? | 39,820,386 | <p>I am pretty new to python and coding in general. I have this code so far.</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 numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.csv', delimiter=',', skiprows=1)
mSec = data[:,0]
Airspeed = data[:,10]
AS_Cmd = data[:,25]
airspeed = data[:,3]
plt.rc('xtick', labelsize=25) #increase xaxis tick size
plt.rc('ytick', labelsize=25) #increase yaxis tick size
fig, ax = plt.subplots(figsize=(40,40), edgecolor='b')
ax.patch.set_facecolor('white')
ax.plot(mSec, Airspeed, label='Ground speed [m/s]')
ax.plot(mSec, AS_Cmd, label='Voltage [V]')
plt.legend(loc='best',prop={'size':20})
fig.savefig('trans2.png', dpi=(200), bbox_inches='tight') #borderless on save</code></pre>
</div>
</div>
</p>
<p>However, I don't want to individually read every data column there is. I want to be able to load a csv file and have it read out all column names, then asks the users what you want for your x-axis and y-axis and plots that graph. The csv file format is:</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>time(s),speed(mph),heading,bvoltage(v)
20,30,50,10
25,45,50,10
30,50,55,9</code></pre>
</div>
</div>
</p>
<p>Here is my attempt at the code but I am missing a lot of information:</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 numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.csv', delimiter=',')
## names = where I will store the column names
white True:
## display names to user
print ('Pick your x-axis')
xaxis = input()
print ('Pick your y-axis')
yaxis1 = input()
print('pick a 2nd y-axis or enter none')
yaxis2 = input()
if input()= 'none'
break;
else continue
#plot xaxis vs yaxis vs 2nd yaxis</code></pre>
</div>
</div>
</p>
<p>I understand the loop is not correct. I don't want anyone to correct me on that I will figure it out myself, however, I would like a way to access those values from the CSV file so that I can use it in that method.</p>
| 0 | 2016-10-02T18:42:36Z | 39,822,297 | <p>If you don't mind using/installing another module then <strong>pandas</strong> should do it. </p>
| 0 | 2016-10-02T22:16:53Z | [
"python",
"matplotlib"
]
|
Extract header names from a CSV and use it to plot against each other in Python? | 39,820,386 | <p>I am pretty new to python and coding in general. I have this code so far.</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 numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.csv', delimiter=',', skiprows=1)
mSec = data[:,0]
Airspeed = data[:,10]
AS_Cmd = data[:,25]
airspeed = data[:,3]
plt.rc('xtick', labelsize=25) #increase xaxis tick size
plt.rc('ytick', labelsize=25) #increase yaxis tick size
fig, ax = plt.subplots(figsize=(40,40), edgecolor='b')
ax.patch.set_facecolor('white')
ax.plot(mSec, Airspeed, label='Ground speed [m/s]')
ax.plot(mSec, AS_Cmd, label='Voltage [V]')
plt.legend(loc='best',prop={'size':20})
fig.savefig('trans2.png', dpi=(200), bbox_inches='tight') #borderless on save</code></pre>
</div>
</div>
</p>
<p>However, I don't want to individually read every data column there is. I want to be able to load a csv file and have it read out all column names, then asks the users what you want for your x-axis and y-axis and plots that graph. The csv file format is:</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>time(s),speed(mph),heading,bvoltage(v)
20,30,50,10
25,45,50,10
30,50,55,9</code></pre>
</div>
</div>
</p>
<p>Here is my attempt at the code but I am missing a lot of information:</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 numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.csv', delimiter=',')
## names = where I will store the column names
white True:
## display names to user
print ('Pick your x-axis')
xaxis = input()
print ('Pick your y-axis')
yaxis1 = input()
print('pick a 2nd y-axis or enter none')
yaxis2 = input()
if input()= 'none'
break;
else continue
#plot xaxis vs yaxis vs 2nd yaxis</code></pre>
</div>
</div>
</p>
<p>I understand the loop is not correct. I don't want anyone to correct me on that I will figure it out myself, however, I would like a way to access those values from the CSV file so that I can use it in that method.</p>
| 0 | 2016-10-02T18:42:36Z | 39,822,357 | <p>Using <code>pandas</code> you can do:</p>
<pre><code>import pandas as pd
data = pd.read_csv("yourFile.csv", delimiter=",")
</code></pre>
<p>and plot columns with names <code>ColName1</code>, <code>ColName2</code> against each other with:</p>
<pre><code>data.plot(x='Col1', y='Col2')
</code></pre>
<p>If you have a first line in the csv file with the desired names of the columns, <code>pandas</code> will pick those automatically, otherwise you can play with the <code>header</code> argument of <code>read_csv</code>.</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html</a></p>
| 0 | 2016-10-02T22:25:26Z | [
"python",
"matplotlib"
]
|
C# - Using method from a Python file | 39,820,443 | <p>I have two files, a regular python (.py) file and a visual studio C# file (.cs). I want to use a function in the python file which returns a string and use that string in the C# file. </p>
<p>Basically:</p>
<pre><code>#This is the Python file!
def pythonString():
return "Some String"
</code></pre>
<p>and</p>
<pre><code>//This is the C# file!
namespace VideoLearning
{
string whatever = pythonString(); // This is from the Python file.
}
</code></pre>
<p>How can I sort of link these two files together? Thanks.</p>
| 2 | 2016-10-02T18:48:53Z | 39,820,925 | <p>Check out IronPython! :)</p>
<p>Good declaration:
<a href="https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/" rel="nofollow">https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/</a></p>
<p>Hope this helps, it's pretty ez ;)</p>
<pre><code>var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("Test.py");
test.pythonString(); //python-function to execute
</code></pre>
<p>just replace "pythonString()" with your function (already did this).</p>
| 2 | 2016-10-02T19:40:26Z | [
"c#",
"python",
".net",
"ironpython",
"python.net"
]
|
C# - Using method from a Python file | 39,820,443 | <p>I have two files, a regular python (.py) file and a visual studio C# file (.cs). I want to use a function in the python file which returns a string and use that string in the C# file. </p>
<p>Basically:</p>
<pre><code>#This is the Python file!
def pythonString():
return "Some String"
</code></pre>
<p>and</p>
<pre><code>//This is the C# file!
namespace VideoLearning
{
string whatever = pythonString(); // This is from the Python file.
}
</code></pre>
<p>How can I sort of link these two files together? Thanks.</p>
| 2 | 2016-10-02T18:48:53Z | 39,898,727 | <p>You can also try pythonnet:</p>
<p><a href="http://www.python4.net" rel="nofollow">python4.net</a></p>
| 0 | 2016-10-06T14:30:47Z | [
"c#",
"python",
".net",
"ironpython",
"python.net"
]
|
Edit distance specifc implementation for number . PYTHON | 39,820,462 | <p>I got a question on code chef asking the modified version of edit distance , where it is edit distance between 2 numbers , where only deletion operation is allowed and deletion cost = deleted number .</p>
<p>So I tried this to implement on python . But getting </p>
<pre><code>TypeError: 'function' object has no attribute '__getitem__'
</code></pre>
<p>I am getting this error in the last line i.e return line in EditDisRec function</p>
<p>Here is the code</p>
<pre><code>def ISTHERE(x,y):
a=len(str(y))
b=y
for i in range(0,a):
if b%10 == x:
return(True)
break
else:
b=b/10
return(False)
def sum_digits(N):
n=int(N)
s = 0
while n:
s += n % 10
n //= 10
return s
def delt(x,y):
if int(x)==int(y):
return 0
else:
return int(x)+int(y)
def EditDistRec(S,T):
if S==0:
return sum_digits(T)
elif T==0:
return sum_digits(S)
elif (S==1 or S==2 or S==3 or S==4 or S==5 or S==6 or S==7 or S==8 or S==9 ):
if ISTHERE(S,T)==True :
return sum_digits(T) - S
elif ISTHERE(S,T)==False:
return sum_digits(T)
elif (T==1 or T==2 or T==3 or T==4 or T==5 or T==6 or T==7 or T==8 or T==9 ):
if ISTHERE(T,S)==True :
return sum_digits(S) - T
elif ISTHERE(T,S)==False:
return sum_digits(S)
return min(EditDistRec(S/10,T/10) + delt[S%10,T%10],(EditDistRec(S ,T/10) + int(T%10)),(EditDistRec(S/10,T ) + int(S%10)))
print(EditDistRec(7315,713))
</code></pre>
| 1 | 2016-10-02T18:50:47Z | 39,820,516 | <p>you have typo here <code>delt[S%10,T%10]</code> </p>
<p>This means that you cannot index them like a list because <strong>getitem</strong> is the method which handles this operation.<code>delt</code> is a function, not a list </p>
<p>Corrected: </p>
<pre><code>return min(EditDistRec(S/10,T/10) + delt(S%10,T%10),(EditDistRec(S ,T/10) + int(T%10)),(EditDistRec(S/10,T ) + int(S%10)))
</code></pre>
<p>Output:</p>
<pre><code>sh-4.3$ python main.py
7
sh-4.3$
</code></pre>
| 1 | 2016-10-02T18:57:30Z | [
"python",
"python-2.7"
]
|
How to programmatically catch which command failed on a try block | 39,820,476 | <p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of the method is like that; </p>
<pre><code>return {
'foo': data['foo'],
'bar': data['bar']
}
</code></pre>
<p>If a field is missing from the data, this throughs a KeyError. Is it possible to catch programmatically which field produced the error, in a single try-except block and not write a try-except block for every field?</p>
<pre><code>try:
ret_dict = {
'foo': data['foo'],
'bar': data['bar']
}
except KeyError:
ret_dict[thefailurekey] = '_'
</code></pre>
<p>instead of </p>
<pre><code>ret_dict = {}
try:
ret_dict['foo'] = data['foo']
except KeyError:
ret_dict['foo'] = '_'
try:
ret_dict['bar'] = data['bar']
except:
ret_dict['bar'] = '_'
</code></pre>
<p>Thank you</p>
| 1 | 2016-10-02T18:52:41Z | 39,820,500 | <p>You can probably get that information from the members of the <code>KeyError</code> exception object, but a simpler way would be to just use <code>get()</code> that will return a default value if the key is not there.</p>
<pre><code>return {
'foo': data.get('foo', '_'),
'bar': data.get('bar', '_'),
}
</code></pre>
<p>Another reason this is better than handling an exception is that you can only handle one exception. What happens if two keys are missing? And on top of that, <code>ret_dict</code> will not even be defined in your example because the code failed.</p>
| 3 | 2016-10-02T18:55:09Z | [
"python"
]
|
How to programmatically catch which command failed on a try block | 39,820,476 | <p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of the method is like that; </p>
<pre><code>return {
'foo': data['foo'],
'bar': data['bar']
}
</code></pre>
<p>If a field is missing from the data, this throughs a KeyError. Is it possible to catch programmatically which field produced the error, in a single try-except block and not write a try-except block for every field?</p>
<pre><code>try:
ret_dict = {
'foo': data['foo'],
'bar': data['bar']
}
except KeyError:
ret_dict[thefailurekey] = '_'
</code></pre>
<p>instead of </p>
<pre><code>ret_dict = {}
try:
ret_dict['foo'] = data['foo']
except KeyError:
ret_dict['foo'] = '_'
try:
ret_dict['bar'] = data['bar']
except:
ret_dict['bar'] = '_'
</code></pre>
<p>Thank you</p>
| 1 | 2016-10-02T18:52:41Z | 39,820,521 | <p>Instead of using try block, you can use <code>dict.get(key, default_val)</code></p>
<p>For example:</p>
<pre><code>ret_dict = dict(
foo=data.get('foo', '-'),
bar=data.get('bar', '-')
)
return ret_dict
</code></pre>
| 2 | 2016-10-02T18:58:15Z | [
"python"
]
|
How to programmatically catch which command failed on a try block | 39,820,476 | <p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of the method is like that; </p>
<pre><code>return {
'foo': data['foo'],
'bar': data['bar']
}
</code></pre>
<p>If a field is missing from the data, this throughs a KeyError. Is it possible to catch programmatically which field produced the error, in a single try-except block and not write a try-except block for every field?</p>
<pre><code>try:
ret_dict = {
'foo': data['foo'],
'bar': data['bar']
}
except KeyError:
ret_dict[thefailurekey] = '_'
</code></pre>
<p>instead of </p>
<pre><code>ret_dict = {}
try:
ret_dict['foo'] = data['foo']
except KeyError:
ret_dict['foo'] = '_'
try:
ret_dict['bar'] = data['bar']
except:
ret_dict['bar'] = '_'
</code></pre>
<p>Thank you</p>
| 1 | 2016-10-02T18:52:41Z | 39,820,536 | <p>Use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>.get</code></a> method of <a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict" rel="nofollow"><code>dict</code></a>:</p>
<pre><code>def get_data(data):
return {
# If you want to accept falsy values from API:
'foo': data.get('foo', '_'),
# If you want to override falsy values from API:
'bar': data.get('bar') or '_',
}
</code></pre>
<p><code>.get</code> returns its second argument (<code>None</code> by default) if a dict doesn't have requested key, so it is always safe to use it in uncertain situations. </p>
<p>Example:</p>
<pre><code>>>> data = {'foo': False, 'bar': False}
>>> get_data(data)
{'bar': '_', 'foo': False}
</code></pre>
| 2 | 2016-10-02T19:00:09Z | [
"python"
]
|
How to programmatically catch which command failed on a try block | 39,820,476 | <p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of the method is like that; </p>
<pre><code>return {
'foo': data['foo'],
'bar': data['bar']
}
</code></pre>
<p>If a field is missing from the data, this throughs a KeyError. Is it possible to catch programmatically which field produced the error, in a single try-except block and not write a try-except block for every field?</p>
<pre><code>try:
ret_dict = {
'foo': data['foo'],
'bar': data['bar']
}
except KeyError:
ret_dict[thefailurekey] = '_'
</code></pre>
<p>instead of </p>
<pre><code>ret_dict = {}
try:
ret_dict['foo'] = data['foo']
except KeyError:
ret_dict['foo'] = '_'
try:
ret_dict['bar'] = data['bar']
except:
ret_dict['bar'] = '_'
</code></pre>
<p>Thank you</p>
| 1 | 2016-10-02T18:52:41Z | 39,820,785 | <p>If you want to avoid the repetitiveness of typing <code>.get(attr, '_')</code> for each key, you can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>, setting it to return <code>_</code> when a key is trying to be accessed but missing.</p>
<pre><code>from collections import defaultdict
data = {
'foo': 'foo_value',
}
ret_dict = defaultdict(lambda: '_')
ret_dict.update(data)
print(ret_dict['foo']) # 'foo_value'
print(ret_dict['bar']) # '_'
</code></pre>
| 1 | 2016-10-02T19:26:35Z | [
"python"
]
|
In Django, how do I update a user profile if a model is added to database? | 39,820,496 | <p>I'm creating a site where users can upload files. I have my upload form working, and it correctly associates the current user with the uploaded file. Once it's uploaded however, I would like the User Profile model to update the number of files uploaded for that specific user. I'm using django-allauth with a custom admin model.<br><br></p>
<p>models.py (works to recognize current user)</p>
<pre><code>class ConfigFiles(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True)
Printer = models.CharField(_('Printer Model'),
max_length=100, blank=True, null=True, unique=False, help_text="Something like 'i3'")
printerbrand = models.CharField(_('Printer Brand'),
max_length=100, blank=True, null=True, unique=False, help_text="Something like 'Prusa'")
Plastic = models.CharField(_('Plastic'),
max_length=40, blank=True, null=True, unique=False, help_text="Something like 'ABS' or 'Nylon'")
HDConfig = models.FileField(_('High Detail, Slow Speed'),
upload_to=UploadedConfigPath, validators=[validate_file_extension], help_text="Displayed as HD on Infinity-Box")
LDConfig = models.FileField(_('Fast speed, Low Detail'),
upload_to=UploadedConfigLDPath, validators=[validate_file_extension], help_text="Displayed as FAST on Infinity-Box")
pub_date = models.DateTimeField(_('date_joined'),
default=timezone.now)
</code></pre>
<p>And here's my custom admin models.py (doesn't auto update configuploaded)</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(DemoUser, primary_key=True, verbose_name='user', related_name='profile')
avatar_url = models.CharField(max_length=256, blank=True, null=True)
configuploaded = models.IntegerField(_('Number of uploaded Config files'), default=0, unique=False)
filesuploaded = models.IntegerField(_('Number of uploaded STL files'), default=0, unique=False)
dob=models.DateField(verbose_name="dob", blank=True, null=True)
def __str__(self):
return force_text(self.user.email)
class Meta():
db_table = 'user_profile'
</code></pre>
<p><strong>EDIT 1</strong></p>
<p>Here's view.py.</p>
<pre><code>@login_required
def uplist(request):
if request.method == 'POST':
form = ConfigUpload(request.POST, request.FILES)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
#newdoc = ConfigFiles(HDConfig=request.FILES['HD file'])
comment.save()
messages.add_message(request, messages.SUCCESS, "Configuration added")
# Redirect to the document list after POST
return HttpResponseRedirect(reverse_lazy('list'))
else:
form = ConfigUpload() # A empty, unbound form
print (request.user.first_name)
# Load documents for the list page
documents = ConfigFiles.objects.all()
# Render list page with the documents and the form
return render(
request,
'visitor/configupload.html',
{
'documents': documents,
'form': form,
}
)
</code></pre>
<p>Ideally, whenever the user uploads a file the configuploaded variable increase correspondingly. Is there a simple way to do this within models or should I do if from my views.py?</p>
| 1 | 2016-10-02T18:54:55Z | 39,821,139 | <p>You can use Post Save Signal in Django</p>
<pre><code>from django.db.models.signals import *
from django.db.models import F
def file_upload_count(sender, instance, created, *args, **kwargs):
if created:
UserProfile.objects.filter(user = instance).update(filesuploaded = F('filesuploaded')+1)
post_save.connect(file_upload_count, sender=ConfigFiles)
</code></pre>
<p>Whenever a new file is uploaded this will perform the function defined and will increment the value or whatever u want.</p>
<p>Try adding this code in your models file</p>
| 0 | 2016-10-02T20:04:01Z | [
"python",
"django",
"django-allauth"
]
|
In Django, how do I update a user profile if a model is added to database? | 39,820,496 | <p>I'm creating a site where users can upload files. I have my upload form working, and it correctly associates the current user with the uploaded file. Once it's uploaded however, I would like the User Profile model to update the number of files uploaded for that specific user. I'm using django-allauth with a custom admin model.<br><br></p>
<p>models.py (works to recognize current user)</p>
<pre><code>class ConfigFiles(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True)
Printer = models.CharField(_('Printer Model'),
max_length=100, blank=True, null=True, unique=False, help_text="Something like 'i3'")
printerbrand = models.CharField(_('Printer Brand'),
max_length=100, blank=True, null=True, unique=False, help_text="Something like 'Prusa'")
Plastic = models.CharField(_('Plastic'),
max_length=40, blank=True, null=True, unique=False, help_text="Something like 'ABS' or 'Nylon'")
HDConfig = models.FileField(_('High Detail, Slow Speed'),
upload_to=UploadedConfigPath, validators=[validate_file_extension], help_text="Displayed as HD on Infinity-Box")
LDConfig = models.FileField(_('Fast speed, Low Detail'),
upload_to=UploadedConfigLDPath, validators=[validate_file_extension], help_text="Displayed as FAST on Infinity-Box")
pub_date = models.DateTimeField(_('date_joined'),
default=timezone.now)
</code></pre>
<p>And here's my custom admin models.py (doesn't auto update configuploaded)</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(DemoUser, primary_key=True, verbose_name='user', related_name='profile')
avatar_url = models.CharField(max_length=256, blank=True, null=True)
configuploaded = models.IntegerField(_('Number of uploaded Config files'), default=0, unique=False)
filesuploaded = models.IntegerField(_('Number of uploaded STL files'), default=0, unique=False)
dob=models.DateField(verbose_name="dob", blank=True, null=True)
def __str__(self):
return force_text(self.user.email)
class Meta():
db_table = 'user_profile'
</code></pre>
<p><strong>EDIT 1</strong></p>
<p>Here's view.py.</p>
<pre><code>@login_required
def uplist(request):
if request.method == 'POST':
form = ConfigUpload(request.POST, request.FILES)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
#newdoc = ConfigFiles(HDConfig=request.FILES['HD file'])
comment.save()
messages.add_message(request, messages.SUCCESS, "Configuration added")
# Redirect to the document list after POST
return HttpResponseRedirect(reverse_lazy('list'))
else:
form = ConfigUpload() # A empty, unbound form
print (request.user.first_name)
# Load documents for the list page
documents = ConfigFiles.objects.all()
# Render list page with the documents and the form
return render(
request,
'visitor/configupload.html',
{
'documents': documents,
'form': form,
}
)
</code></pre>
<p>Ideally, whenever the user uploads a file the configuploaded variable increase correspondingly. Is there a simple way to do this within models or should I do if from my views.py?</p>
| 1 | 2016-10-02T18:54:55Z | 39,822,404 | <p>Theres a few ways to solve this, how best to go about it depends on your use case. In my current site I use a mix of properties and signals to acheive this functionality.</p>
<p>Using a property - less db writes works & even if you execute bulk deletes on a model, but generates a query everytime you display it.</p>
<pre><code>class UserProfile(models.Model):
#your stuff
def _get_uploaded_files(self):
return ConfigFiles.objects.filter(some_appropriate_filter).count()
uploaded_files = property(_get_uploaded_files)
</code></pre>
<p>Override the save method to increment your field:</p>
<pre><code>class ConfigFiles(models.Model):
#your model definition here
def save(self, *args, **kwargs):
super(ConfigFiles, self).save(*args, **kwargs)
self.user.filesuploaded += 1
</code></pre>
<p>You can also use the postsave signals as per Atul Yadav's answer. However IMO they are somewhat less clear (because you end up defining functionality outside of the model) although they are useful if you need to do several things</p>
| 0 | 2016-10-02T22:31:22Z | [
"python",
"django",
"django-allauth"
]
|
TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop | 39,820,542 | <p>I'm working on a python script that will add a folder and all of its contents to a zip file using both <code>zipfile</code> and <code>os</code>.</p>
<pre><code>z = ZipFile("mynewfile.zip", "w")
z.write(os.walk(directory))
z.printdir()
z.close()
</code></pre>
<p>Unfortunatly I've found that this is considered a list when using <code>os.walk</code>, which causes the error:</p>
<pre><code>TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop
</code></pre>
<p>Looking around at this error, I think I need a loop to cycle through each item in the list. My problem is that I can't figure out how to translate previous answers for my specific needs.
e.g <a href="http://stackoverflow.com/questions/21580270/typeerror-coercing-to-unicode-need-string-or-buffer-list-found">TypeError: coercing to Unicode: need string or buffer, list found</a></p>
<p>I have also tried </p>
<pre><code>for root dirs files in os.walk(directory)
z.write(files)
</code></pre>
<p>which also causes the same error to occur.</p>
<p>However using</p>
<pre><code>for root dirs files in os.walk(directory)
z.write(root)
</code></pre>
<p>displays all the folders within the directory, but no files. I'm not sure why this does not count as a list.</p>
<p>I assume I need to somehow combine these 2 ideas, any help doing so would be greatly appeciated.</p>
| -1 | 2016-10-02T19:01:04Z | 39,821,453 | <p>The following code should do it. Since files is a list. You simply iterate over that list and write the filenames to the zipfile. In the code below I'm also using the context manager <code>with</code> with that I don't need to close the file manually, because it does that for me. </p>
<pre><code>from zipfile import Zipfile
for root, dirs, files in os.walk(directory):
for f in files:
with Zipfile('new_zip.zip', 'w') as z:
z.write(f)
</code></pre>
| 0 | 2016-10-02T20:36:48Z | [
"python"
]
|
Python: How to connect to a server database? | 39,820,550 | <p>Which modules would you recommand for connecting a SQL database on the server and how to install and use them?</p>
<p>I'm developing with Python and PyQt5 an application which needs results from a server database.</p>
| -1 | 2016-10-02T19:02:14Z | 39,820,609 | <p>I suppose it depends on what database you're looking to use. If you're using mysql you might want to check out <a href="https://github.com/PyMySQL" rel="nofollow">https://github.com/PyMySQL</a> . I have been using it and seems to be working out quite nicely. </p>
| 1 | 2016-10-02T19:07:54Z | [
"python",
"sql",
"database",
"client"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.