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 make arrow that loops in matplotlib?
37,512,502
<p>what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried:</p> <pre><code>plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", ...
9
2016-05-29T16:50:23Z
38,287,530
<p>Another possibility is to use tikz to generate the figure:</p> <pre><code> \documentclass {minimal} \usepackage {tikz} \begin{document} \usetikzlibrary {arrows} \begin {tikzpicture}[scale=1.8] \draw[-angle 90, line width=5.0mm, rounded corners=20pt] (0.25,0)-- (1.0, 0.0) -- (1.0, -3.0)...
0
2016-07-10T00:33:53Z
[ "python", "matplotlib" ]
Substitute specific matches using regex
37,512,580
<p>I want to execute substitutions using regex, not for all matches but only for specific ones. However, <code>re.sub</code> substitutes for all matches. How can I do this?</p> <p>Here is an example. Say, I have a string with the following content:</p> <pre><code>FOO=foo1 BAR=bar1 FOO=foo2 BAR=bar2 BAR=bar3 </code></...
3
2016-05-29T16:57:49Z
37,512,683
<p>You could</p> <ol> <li>Split your string using s.splitlines()</li> <li>Iterate over the individual lines in a for loop</li> <li>Track how many matches you have found so far</li> <li>Only perform substitutions on those matches in the numerical ranges you want (e.g. matches 1 and 2)</li> <li>And then join them back i...
0
2016-05-29T17:08:01Z
[ "python", "regex" ]
Substitute specific matches using regex
37,512,580
<p>I want to execute substitutions using regex, not for all matches but only for specific ones. However, <code>re.sub</code> substitutes for all matches. How can I do this?</p> <p>Here is an example. Say, I have a string with the following content:</p> <pre><code>FOO=foo1 BAR=bar1 FOO=foo2 BAR=bar2 BAR=bar3 </code></...
3
2016-05-29T16:57:49Z
37,512,705
<p>You could pass replacement function to <code>re.sub</code> that keeps track of count and checks if the given index should be substituted:</p> <pre><code>import re s = '''FOO=foo1 BAR=bar1 FOO=foo2 BAR=bar2 BAR=bar3''' i = 0 index = {1, 2} def repl(x): global i if i in index: res = '#' + x.group(0...
3
2016-05-29T17:10:32Z
[ "python", "regex" ]
How can i check if there is a global or local variable
37,512,712
<p>I want to check if that variable exists and print it if it does.</p> <pre><code>x = 10 def example(): z = 5 print("X (Global variable) : ",x) print("Z (example() : ",z) example() print(z) </code></pre> <p>When i add <code>print(z)</code> it will obviously raises an error because there is no variable call...
0
2016-05-29T17:11:12Z
37,512,745
<p>The built-in methods <code>locals()</code> and <code>globals()</code> return a dictionary of local/global variable names and their values.</p> <pre><code>if 'z' in locals(): print(z) </code></pre>
3
2016-05-29T17:14:12Z
[ "python", "function", "variables", "global", "local" ]
How can i check if there is a global or local variable
37,512,712
<p>I want to check if that variable exists and print it if it does.</p> <pre><code>x = 10 def example(): z = 5 print("X (Global variable) : ",x) print("Z (example() : ",z) example() print(z) </code></pre> <p>When i add <code>print(z)</code> it will obviously raises an error because there is no variable call...
0
2016-05-29T17:11:12Z
37,512,752
<pre><code>try: print(z) except NameError: print("No variable named z!") </code></pre> <p>This code try's to print z and if there is no variable named z, it will run the code under except.</p>
0
2016-05-29T17:14:47Z
[ "python", "function", "variables", "global", "local" ]
How can i check if there is a global or local variable
37,512,712
<p>I want to check if that variable exists and print it if it does.</p> <pre><code>x = 10 def example(): z = 5 print("X (Global variable) : ",x) print("Z (example() : ",z) example() print(z) </code></pre> <p>When i add <code>print(z)</code> it will obviously raises an error because there is no variable call...
0
2016-05-29T17:11:12Z
37,512,765
<p>The most straight forward way would be to try to use it and if it fails do something else:</p> <pre><code>try: something_with(z) except NameError: fallback_code() </code></pre> <p>you could also check dictionaries of <code>locals()</code> and <code>globals()</code> </p> <pre><code>if 'z' in locals() or 'z...
3
2016-05-29T17:15:36Z
[ "python", "function", "variables", "global", "local" ]
discrepancy in numbers of installed modules between ipython and ipython notebook
37,512,737
<p>Hi I have a curious (and maybe trivial who knows?) problem.</p> <p>For the requirements of a course on coursera I have created a python 2.7 environment in my anaconda distribution and installed DATOs' GraphLab Create modules.</p> <p>While the simple "import graphlab" functions properly from the python command lin...
0
2016-05-29T17:13:17Z
37,513,502
<p>As you said you have created an environment with Python 2.7, you thus <strong>need to register</strong> this environment with the notebook.</p> <p>Activate the environement:</p> <pre><code>$ source activate myenv </code></pre> <p>Then install the kernelspec for this environment:</p> <pre><code>(myenv)$ python -m...
1
2016-05-29T18:33:54Z
[ "python", "import", "jupyter" ]
Is there a way in Python to search directories, subdirectories and files recursively without using os.walk, glob, or fnmatch?
37,512,817
<p>I know that using these modules makes life a lot easier but as I learn Python, I want to be able to solidify the foundation and then go onto the shortcuts. That way, when presented with the bigger issue, I can analyze and solve it.</p> <p>I want to be able to return the number of total folders and files in 1 direct...
-2
2016-05-29T17:22:19Z
37,531,385
<p>You cannot get the number of all files under a directory (recursively) without using <code>os.walk</code> or something that uses the same thing. </p> <p>This information requires this job and you cannot do it another way. Obviously that there are other libraries that are doing a similar job with some variations but...
0
2016-05-30T17:59:23Z
[ "python", "python-3.x", "recursion", "directory" ]
Is there a way in Python to search directories, subdirectories and files recursively without using os.walk, glob, or fnmatch?
37,512,817
<p>I know that using these modules makes life a lot easier but as I learn Python, I want to be able to solidify the foundation and then go onto the shortcuts. That way, when presented with the bigger issue, I can analyze and solve it.</p> <p>I want to be able to return the number of total folders and files in 1 direct...
-2
2016-05-29T17:22:19Z
37,531,748
<p>This is the code to do just as os.walk would do. It's manual recursion. </p> <pre><code>import os def fcount(path): count = 0 for f in os.listdir(path): file = os.path.join(path, f) if os.path.isdir(file): file_count = fcount(file) count += file_count + 1 for...
0
2016-05-30T18:26:30Z
[ "python", "python-3.x", "recursion", "directory" ]
Attempting to execute .jar file using python
37,512,894
<p>I have a .jar file that I need to execute via Python.</p> <p>My current code is</p> <pre><code>import subprocess subprocess.check_output(['java', '-jar', 'StatsCalc.jar']) </code></pre> <p>I printed out the error message:</p> <pre><code>Traceback (most recent call last): File "C:\Users\ali\Documents\Java Stuff\R...
0
2016-05-29T17:32:38Z
37,513,264
<p>One thing that frequently works is using <code>shell=True</code> option on the subprocess, this executes the command as if it was done in a shell (batch file or command prompt) </p> <p>So using:</p> <pre><code>import subprocess subprocess.call(['java', '-jar', 'StatsCalc.jar'],shell=True) </code></pre> <p>Should ...
1
2016-05-29T18:11:25Z
[ "python" ]
Taking from a list of numbers and making a new one
37,513,043
<p>Here's the problem:</p> <p>Given a list of integers, make it so that the first and last integers are added and that result will be the first integer of the new list, the second and second-to-last integers are added and the result will be the second integer of that new list and so on. if your list is odd, leave the ...
0
2016-05-29T17:49:46Z
37,513,088
<pre><code>import itertools n=len(myList) new_list=[e+f for e, f in itertools.izip(myList[:n/2], reversed(myList)[:n/2])] </code></pre> <p>myList[:n/2] extract the first part of the list [1,2,3]<br> reversed(myList) reverse the initial list [6,5,4,3,2,1] then truncate using [:n/2]</p> <p>Then it is possible to iterat...
-1
2016-05-29T17:53:19Z
[ "python", "python-3.x" ]
Taking from a list of numbers and making a new one
37,513,043
<p>Here's the problem:</p> <p>Given a list of integers, make it so that the first and last integers are added and that result will be the first integer of the new list, the second and second-to-last integers are added and the result will be the second integer of that new list and so on. if your list is odd, leave the ...
0
2016-05-29T17:49:46Z
37,513,127
<p><strong>Update:</strong> After going through all the zipping, summing, mapping, slicing and reversing, this solution struck me as surprisingly simple, actually:</p> <pre><code>def switch(my_list): new_list = my_list[:] # make a copy not to harm the original for i in range(len(my_list)//2): # at the appro...
4
2016-05-29T17:57:40Z
[ "python", "python-3.x" ]
Taking from a list of numbers and making a new one
37,513,043
<p>Here's the problem:</p> <p>Given a list of integers, make it so that the first and last integers are added and that result will be the first integer of the new list, the second and second-to-last integers are added and the result will be the second integer of that new list and so on. if your list is odd, leave the ...
0
2016-05-29T17:49:46Z
37,513,353
<pre><code>def switch(a_list): N = len(a_list) HALF = N//2 new_list = [] for i in range(HALF): j = N-i-1 new_list.append(a_list[i] + a_list[j]) if N % 2: new_list.append(a_list[HALF]) return new_list print(switch([1,2,3,4,5,6])) # -&gt; [7, 7, 7] print(switch([1,2,3...
0
2016-05-29T18:19:10Z
[ "python", "python-3.x" ]
Tensorflow's Inception - Number of Classes
37,513,147
<p>I'm wondering about the number of classes in Tensorflow's <a href="https://github.com/tensorflow/models/tree/master/inception" rel="nofollow">Inception</a> implementation. </p> <p>In their <a href="https://github.com/tensorflow/models/blob/master/inception/inception/inception_train.py" rel="nofollow">training scrip...
4
2016-05-29T17:59:18Z
39,566,548
<blockquote> <p>It's a convention we use for all our image datasets, and it didn't seem worth the trouble to break it for this particular model. As an aside, I wish all academic classification datasets had a <strong>'none of the above' class</strong> in their test evaluation. A classifier which doesn't know when it...
0
2016-09-19T06:20:44Z
[ "python", "tensorflow" ]
Python - String changing after decoding and encoding again (zlib + base64)
37,513,178
<p>I have this very simple Python code:</p> <pre><code>in_data = "eNrtmD1Lw0AY..." print("Input: " + in_data) out_data = in_data.decode('base64').decode('zlib').encode('zlib').encode('base64') print("Output: " + out_data) </code></pre> <p>It outputs: </p> <pre><code>Input: eNrtmD1Lw0AY... Output: eJztmE1LAkEY... </c...
0
2016-05-29T18:01:58Z
37,513,299
<p>Your data on input starts with the hex bytes <code>78 DA</code>, your output starts with <code>78 9C</code>:</p> <pre><code>&gt;&gt;&gt; 'eNrt'.decode('base64').encode('hex')[:4] '78da' &gt;&gt;&gt; 'eJzt'.decode('base64').encode('hex')[:4] '789c' </code></pre> <p><code>DA</code> is the highest compression level, ...
1
2016-05-29T18:14:40Z
[ "python", "base64", "zlib" ]
Scoring in Python game does not work
37,513,258
<p>I am new to Python, trying to pick up the language outside of my school courses. This Rock Paper Scissors game I am working on functions correctly, although the score output does not show anything. Here is the code...</p> <pre><code> #!/usr/bin/env python2 # Extra modules used import random import time # Set each...
0
2016-05-29T18:10:46Z
37,513,298
<p>Your <code>print</code> statements are a little off. You should be including the arguments inside the <code>print</code> statement</p> <p><code>print("Player: ", player_score)</code></p> <p><strong>Edit:</strong> To speak a little more to printing. You could also use <code>print("Player: {}".format(player_score))<...
1
2016-05-29T18:14:35Z
[ "python", "function", "variables", "syntax", "global" ]
Scoring in Python game does not work
37,513,258
<p>I am new to Python, trying to pick up the language outside of my school courses. This Rock Paper Scissors game I am working on functions correctly, although the score output does not show anything. Here is the code...</p> <pre><code> #!/usr/bin/env python2 # Extra modules used import random import time # Set each...
0
2016-05-29T18:10:46Z
37,513,501
<p>You need the variables inside the brackets so:</p> <p><code>print ("Player: "), player_score print ("Computer: "), computer_score </code></p> <p>becomes</p> <pre><code>print ("Player: ", player_score) print ("Computer: ", computer_score) </code></pre> <p>Alternatively, </p> <pre><code>print ("Player: {}".fo...
1
2016-05-29T18:33:47Z
[ "python", "function", "variables", "syntax", "global" ]
Using setuptools, how can I download external data upon installation?
37,513,279
<p>I'd like to create some ridiculously-easy-to-use pip packages for loading common machine-learning datasets in Python. (Yes, some stuff already exists, but I want it to be even simpler.)</p> <p>What I'd like to achieve is this:</p> <ul> <li>User runs <code>pip install dataset</code></li> <li>pip downloads the datas...
1
2016-05-29T18:12:43Z
37,531,324
<p>Python package installation states that it should never execute Python code in order to install Python packages. This means that you may not be able to download stuff during the installation process.</p> <p>If you want to download some additional data, do it after you install the package , for example when you impo...
0
2016-05-30T17:54:33Z
[ "python", "pip", "setuptools" ]
Using setuptools, how can I download external data upon installation?
37,513,279
<p>I'd like to create some ridiculously-easy-to-use pip packages for loading common machine-learning datasets in Python. (Yes, some stuff already exists, but I want it to be even simpler.)</p> <p>What I'd like to achieve is this:</p> <ul> <li>User runs <code>pip install dataset</code></li> <li>pip downloads the datas...
1
2016-05-29T18:12:43Z
37,532,267
<blockquote> <p>Note that the data does not reside in the python package itself, but is downloaded from somewhere else.</p> </blockquote> <p>Please do not do this.</p> <p>The whole point of Python packaging is to provide a completely deterministic, repeatable, and reusable means of installing <em>exactly the same t...
0
2016-05-30T19:07:58Z
[ "python", "pip", "setuptools" ]
Using setuptools, how can I download external data upon installation?
37,513,279
<p>I'd like to create some ridiculously-easy-to-use pip packages for loading common machine-learning datasets in Python. (Yes, some stuff already exists, but I want it to be even simpler.)</p> <p>What I'd like to achieve is this:</p> <ul> <li>User runs <code>pip install dataset</code></li> <li>pip downloads the datas...
1
2016-05-29T18:12:43Z
37,553,710
<p>As alluded to by Kevin, Python package installs should be completely reproducible, and any potential external-download issues should be pushed to runtime. This therefore shouldn't be handled with setuptools.</p> <p>Instead, to avoid burdening the user, consider downloading the data in a lazy way, upon load. Example...
1
2016-05-31T19:05:28Z
[ "python", "pip", "setuptools" ]
regex backreference findall not working python
37,513,320
<p>I have recently been using regexes in a program. In this program I used them to find words in a list of words that matched a certain RE. However, when i tried backreferencing with this program, I got an interesting result.</p> <p>Here is the code:</p> <pre><code>import re pattern = re.compile(r"[abcgr]([a-z])\1[ld...
2
2016-05-29T18:16:36Z
37,513,414
<p>The <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><code>re.findall</code></a> only returns captured values captured with <em>capturing groups</em> inside the regex pattern. </p> <p>Use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>re.finditer</c...
2
2016-05-29T18:25:02Z
[ "python", "regex", "python-3.x", "findall", "backreference" ]
Converting Pandas dataframe into Spark dataframe error
37,513,355
<p>I'm trying to convert Pandas DF into Spark one. DF head:</p> <pre><code>10000001,1,0,1,12:35,OK,10002,1,0,9,f,NA,24,24,0,3,9,0,0,1,1,0,0,4,543 10000001,2,0,1,12:36,OK,10002,1,0,9,f,NA,24,24,0,3,9,2,1,1,3,1,3,2,611 10000002,1,0,4,12:19,PA,10003,1,1,7,f,NA,74,74,0,2,15,2,0,2,3,1,2,2,691 </code></pre> <p>Code:</p> <...
1
2016-05-29T18:19:19Z
37,517,439
<p>I have tried this with your data and it is working :</p> <pre><code>%pyspark import pandas as pd from pyspark.sql import SQLContext print sc df = pd.read_csv("test.csv") print type(df) print df sqlCtx = SQLContext(sc) sqlCtx.createDataFrame(df).show() </code></pre>
0
2016-05-30T04:04:53Z
[ "python", "pandas", "apache-spark", "spark-dataframe" ]
List of values to dictionary
37,513,483
<p>I'm trying to make a list of values to a list of dictionary's based on my set keys. I tried the following but i'm loosing all the other values because of the duplicate key names.</p> <pre><code>&gt;&gt;&gt; values = ['XS ', '1', 'S ', '10', 'M ', '1', 'L ', '10', 'XL ', '10'] &gt;&gt;&gt; keys = ['size', 'stock'] *...
1
2016-05-29T18:31:48Z
37,513,517
<p>Usually the point of using a <code>dict</code> is to associate unique keys to associated values, you were originally trying to associate <code>size: ...</code> and <code>stock: ...</code> for each item but why not link the size to stock? In that case you would simply do:</p> <pre><code>result = dict(zip(values[::2...
2
2016-05-29T18:35:03Z
[ "python" ]
List of values to dictionary
37,513,483
<p>I'm trying to make a list of values to a list of dictionary's based on my set keys. I tried the following but i'm loosing all the other values because of the duplicate key names.</p> <pre><code>&gt;&gt;&gt; values = ['XS ', '1', 'S ', '10', 'M ', '1', 'L ', '10', 'XL ', '10'] &gt;&gt;&gt; keys = ['size', 'stock'] *...
1
2016-05-29T18:31:48Z
37,513,520
<p>You can use a list comprehension like following:</p> <pre><code>&gt;&gt;&gt; values = ['XS ', '1', 'S ', '10', 'M ', '1', 'L ', '10', 'XL ', '10'] &gt;&gt;&gt; [{'size':i, 'stock':j} for i, j in zip(values[0::2], values[1::2])] [{'stock': '1', 'size': 'XS '}, {'stock': '10', 'size': 'S '}, {'stock': '1', 'size': 'M...
3
2016-05-29T18:35:23Z
[ "python" ]
change a list into dictionary
37,513,515
<p>How do I change a list like this:</p> <pre><code>[[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996], [2, 'Notting Hill Gate', 40.279999999999994], [3, 'Mile End', 68.86999999999999]] </code></pre> <p>to a dictionary like</p> ...
0
2016-05-29T18:34:55Z
37,513,725
<p>Here is a specific example of how you would do that:</p> <pre><code>l = [[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996], [2, 'Notting Hill Gate', 40.279999999999994], [3, 'Mile End', 68.86999999999999]] ...
0
2016-05-29T18:59:12Z
[ "python", "list", "dictionary", "key-value-store" ]
change a list into dictionary
37,513,515
<p>How do I change a list like this:</p> <pre><code>[[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996], [2, 'Notting Hill Gate', 40.279999999999994], [3, 'Mile End', 68.86999999999999]] </code></pre> <p>to a dictionary like</p> ...
0
2016-05-29T18:34:55Z
37,513,786
<p>A similar answer to Majora but using <code>groupby</code> first. No false lookups, but could need a sort beforehand.</p> <pre><code>from itertools import groupby lst = [[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996],...
0
2016-05-29T19:05:27Z
[ "python", "list", "dictionary", "key-value-store" ]
change a list into dictionary
37,513,515
<p>How do I change a list like this:</p> <pre><code>[[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996], [2, 'Notting Hill Gate', 40.279999999999994], [3, 'Mile End', 68.86999999999999]] </code></pre> <p>to a dictionary like</p> ...
0
2016-05-29T18:34:55Z
37,513,789
<pre><code>b = {} for i in a: if b.has_key(i[0]): b[i[0]]['interchange'].append(i[1]) else: b[i[0]] = {'length': i[2], 'interchange': [i[1]]} </code></pre>
0
2016-05-29T19:05:39Z
[ "python", "list", "dictionary", "key-value-store" ]
change a list into dictionary
37,513,515
<p>How do I change a list like this:</p> <pre><code>[[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996], [2, 'Notting Hill Gate', 40.279999999999994], [3, 'Mile End', 68.86999999999999]] </code></pre> <p>to a dictionary like</p> ...
0
2016-05-29T18:34:55Z
37,513,801
<p>Here is an approach which requires two passes. It has the advantage of being easy to understand.</p> <pre><code>import pprint if __name__ == '__main__': rows = [ [0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59....
0
2016-05-29T19:06:18Z
[ "python", "list", "dictionary", "key-value-store" ]
change a list into dictionary
37,513,515
<p>How do I change a list like this:</p> <pre><code>[[0, 'Ealing Broadway', 103.89], [0, 'Notting Hill Gate', 103.89], [0, 'Mile End', 103.89], [1, 'Ealing Broadway', 59.089999999999996], [2, 'Notting Hill Gate', 40.279999999999994], [3, 'Mile End', 68.86999999999999]] </code></pre> <p>to a dictionary like</p> ...
0
2016-05-29T18:34:55Z
37,514,060
<p>Please consider my answer as a demonstration of <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">Pandas</a> (powerful Python data analysis toolkit) module approach.</p> <p>I'm pretty sure if you want to process a lot of data <strong>fast</strong> - pandas is your tool...</p> <pre><co...
0
2016-05-29T19:31:11Z
[ "python", "list", "dictionary", "key-value-store" ]
Python GUI only shows one label instead of two
37,513,519
<p>So I'm making a game and I was wondering why the num of rows/columns show one instead of showing both. When I comment one out, the other shows and vice versa instead of both showing. </p> <pre><code>class OthelloGUI(): def __init__(self): self._root_window = tkinter.Tk() self._root_window.tit...
0
2016-05-29T18:35:13Z
37,513,571
<p>You are calling <code>grid</code> with the same coordinates:</p> <pre><code>row_label.grid(row=1, column = 0, padx = 10, pady=10, sticky = tkinter.W+tkinter.N) column_label.grid(row=1, column = 0, padx = 10, pady=50, sticky = tkinter.W+tkinter.N) </code></pre> <p>When you grid both at (1, 0), the second one will ...
1
2016-05-29T18:41:40Z
[ "python", "user-interface" ]
'ColorField' object has no attribute 'model' django
37,513,563
<p>I am using ColorField that I found on the internet, and it is working alright when I set the color from admin site, but when I create my own form I get this error: </p> <pre><code>'ColorField' object has no attribute 'model' </code></pre> <p>It says "Error during template rendering", and showing that the error is ...
0
2016-05-29T18:40:25Z
37,513,698
<p>You're using the <strong>model</strong> <code>ColorField</code> in your <strong>form</strong>, but those are two completely different contexts. It also looks like you're trying to use a regular form as a <code>ModelForm</code>.</p> <p><a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/" rel="nof...
1
2016-05-29T18:57:00Z
[ "python", "django" ]
How to manipulate CSV data?
37,513,606
<p>I am trying to make a bank program in which you for now you have the option to change your password in choice '2'.I tried doing it but of no avail.Can anyone tell me how do I change the password which is stored in row 2 in 'store.txt'.<br> Example:<br> This is my data stored in file 'store.txt' </p> <pre><code>hel...
1
2016-05-29T18:46:47Z
37,519,506
<p>To replace a value in a file:</p> <pre><code>with open('store.txt','r') as f: reader = list(csv.reader(f)) for row in reader: row[1] = "some-new-value" with open('store.txt','w') as f: wr = csv.writer(f) for row in reader: wr.writerow(row) </code></pre> <p>There are also many ways ...
0
2016-05-30T07:02:53Z
[ "python", "python-2.7", "csv", "row" ]
Why in comparing python tuples of objects is __eq__ and then __cmp__ called?
37,513,671
<p>When comparing tuples of objects apparently the <code>__eq__</code> method of the object is called and then the compare method:</p> <pre><code>import timeit setup = """ import random import string import operator random.seed('slartibartfast') d={} class A(object): eq_calls = 0 cmp_calls = 0 def __ini...
1
2016-05-29T18:53:45Z
37,514,483
<p>It is just how tuple comparison is implemented: <a href="https://bitbucket.org/python_mirrors/cpython/src/d81d4b3059e4e5dca67515315c2ada6dfe1c52a4/Objects/tupleobject.c?at=default&amp;fileviewer=file-view-default#tupleobject.c-583" rel="nofollow">tuplerichcompare</a></p> <p>it searches the first index where items a...
2
2016-05-29T20:11:50Z
[ "python", "python-2.7", "sorting", "compare", "tuples" ]
Selenium on Anaconda 2 not opening firefox
37,513,710
<p>I'm a beginner python user and try to use selenium to open Firefox on Win 10 and Anaconda 2.5. I just downloaded Firefox and installed selenium on Anaconda, so they are up to date. When I type the following:</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() </code></pre> <p>Firefox open i...
0
2016-05-29T18:57:51Z
37,549,735
<p>Thanks guys who viewed my posts. I figured out the solution. I googled "anaconda selenium install" and there is a hit on top and I followed it. The thing is its command installs Selenium 2.40 but the current version is 2.53. Anaconda does not have Selenium package so "conda install selenium" does not work. BUT you c...
0
2016-05-31T15:24:42Z
[ "python", "selenium", "firefox" ]
Python:Got \xa0 instead of space in CSV and cannot remove or convert
37,513,720
<p>I have a problem related to the encoding problem in python (IPython notebook ). As these kind of problems is very common and simple, but I still cannot really fix it.</p> <p>I have a <a href="http://www.montefiore.ulg.ac.be/~glouppe/2012-2013/challenge/train.csv" rel="nofollow">CSV</a> file here, as you can see we ...
1
2016-05-29T18:58:31Z
37,513,810
<p>The character represented by <code>\xa0</code> is <a href="http://www.fileformat.info/info/unicode/char/00a0/index.htm" rel="nofollow">U+00A0: NO-BREAK SPACE</a>.</p> <p>However, your string doesn't include the character <code>"\xa0"</code>; it includes the <strong>literal text</strong> <code>\xa0</code> (i.e, the ...
2
2016-05-29T19:07:02Z
[ "python", "csv", "encoding", "utf-8" ]
Python:Got \xa0 instead of space in CSV and cannot remove or convert
37,513,720
<p>I have a problem related to the encoding problem in python (IPython notebook ). As these kind of problems is very common and simple, but I still cannot really fix it.</p> <p>I have a <a href="http://www.montefiore.ulg.ac.be/~glouppe/2012-2013/challenge/train.csv" rel="nofollow">CSV</a> file here, as you can see we ...
1
2016-05-29T18:58:31Z
37,513,826
<p>The <code>\xa0</code> that you see is a sequence of 4 characters: <code>\</code> <code>x</code> <code>a</code> <code>0</code>. All these characters are plain ASCII, so no character set problem here.</p> <p>Apparently, you are supposed to interpret these escape sequences. Your idea of replacing them with a space is ...
1
2016-05-29T19:08:28Z
[ "python", "csv", "encoding", "utf-8" ]
Counting rows by date in sql alchemy
37,513,793
<p>I am executing some code in python, but need to access some data from my database. This is my first time I have used sql alchemy</p> <p>I have a table in my database called reports.bigjoin it has columns with the following types</p> <pre><code>id (varchar) id2 (varchar) ts_min (int4) ts_local_min (int4) 10_meter_c...
0
2016-05-29T19:05:56Z
37,515,088
<p>After searching a bit and applying </p> <p><a href="http://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python">How to use variables in SQL statement in Python?</a></p> <p>I found that </p> <pre><code>connection = create_engine('url').connect() result = connection.execute("select c...
0
2016-05-29T21:18:16Z
[ "python", "sql", "sqlalchemy" ]
Counting rows by date in sql alchemy
37,513,793
<p>I am executing some code in python, but need to access some data from my database. This is my first time I have used sql alchemy</p> <p>I have a table in my database called reports.bigjoin it has columns with the following types</p> <pre><code>id (varchar) id2 (varchar) ts_min (int4) ts_local_min (int4) 10_meter_c...
0
2016-05-29T19:05:56Z
37,517,482
<pre><code>cnt = ( session .query(func.count('*').label('cnt')) .filter(moz_bookmarks.c.ds &gt;= '2016-01-01') .filter(moz_bookmarks.c.ds &lt;= '2016-01-04') ) print(cnt) </code></pre>
0
2016-05-30T04:10:01Z
[ "python", "sql", "sqlalchemy" ]
How to appropriatly use QThreadPool for multiple massive calculation tasks?
37,513,798
<p>I am facing an issue that should be easy to resolve, yet I do feel that I tap in the dark. I was writing a simple framework which consists of the following classes:</p> <p>First there is an Algorithm class which simply contains numerical procedures:</p> <pre><code>class Algorithm(object): . . . @staticmethod def c...
0
2016-05-29T19:06:12Z
37,556,705
<p>One limitation of the most common implementation of Python (CPython) is that its parser uses a <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">Global Interpreter Lock</a> which means that only one thread can be parsing Python bytes at a time. It is possible for multiple Python threads to...
1
2016-05-31T22:31:42Z
[ "python", "multithreading", "pyqt4" ]
How to make custom Op in TensorFlow importable in Python?
37,513,816
<p>I have implemented a kernel for my custom Op, and put it into <code>/tensorflow/core/user_ops</code> as <code>custom_op.cc</code>. Inside the Op I do all the registering stuff, like <code>REGISTER_OP</code> and <code>REGISTER_KERNEL_BUILDER</code>.</p> <p>Then I implemented gradient for this Op in Python, and I put...
0
2016-05-29T19:07:18Z
37,531,540
<p>Ok, I found the solution. I just removed the <code>BUILD</code> file, and my custom Op was successfully built and was importable in Python using <code>tensorflow.user_ops.custom_op()</code>. </p> <p>To use the gradient I had to put it's code directly inside the <code>tensorflow/python/user_ops/user_ops.py</code>. N...
0
2016-05-30T18:12:03Z
[ "python", "machine-learning", "neural-network", "tensorflow", "bazel" ]
Nested loop not starting at 0
37,513,865
<p>I have a nested for loop for when someone enters the race. The problem i'm having is that if a user selects a date that is not on the dates held I am pushing them to the next 'official' date. I have a list of dates in a csv file and i'm reading it well. My problem is my nested loop keeps incrementing its starting...
0
2016-05-29T19:11:54Z
37,513,942
<p>The <code>csv</code> variable is masking the <code>csv</code> module. This is a future bug waiting to happen.</p> <p>That said, the <code>csv</code> variable is also a wrapper around a file reader. You don't reset that, so it's going to just pull in higher and higher lines.</p> <p>If you want to restart the iterat...
1
2016-05-29T19:20:04Z
[ "python", "python-2.7", "csv" ]
Nested loop not starting at 0
37,513,865
<p>I have a nested for loop for when someone enters the race. The problem i'm having is that if a user selects a date that is not on the dates held I am pushing them to the next 'official' date. I have a list of dates in a csv file and i'm reading it well. My problem is my nested loop keeps incrementing its starting...
0
2016-05-29T19:11:54Z
37,514,011
<p>Because you intialize csv with enumerator at the beginning of the outer loop. So it just keeps pulling next values from the reader. </p> <p>If you want to start over every time you enter the inner loop, either read all the values into the list first as Austing suggested or create new reader and enumerator right ...
0
2016-05-29T19:25:44Z
[ "python", "python-2.7", "csv" ]
django repeated data sometimes
37,513,902
<p>I am getting repeated results from my queries. There are only a few of my results that are being repeated. I am using django 1.8 and sqlite as my database. The repeated results seem to be the same entry id #4 and id #14. I have checked with an sql lite browser and confirmed that there is only one entry for each ID. ...
0
2016-05-29T19:15:59Z
37,514,077
<p><strong>Updated</strong></p> <p>If you really are sure that your data is valid, than calling <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#only" rel="nofollow">only</a> on your query should fix this. I think the problem is that you are giving list of dicts after calling <code>values</code> on...
1
2016-05-29T19:32:41Z
[ "python", "django", "sqlite" ]
Does Python GIL need to be taken care when work with multi-thread C++ extension?
37,513,957
<p>I'm now implementing a data subscriber with Python, which subscribes to a data publisher (actually a ZeroMQ publisher socket) and will get notified once any new messages are fed. In my subscriber, the messages are dumped to a data processor after received. The subscriber will also get notified by the processor when ...
0
2016-05-29T19:21:08Z
37,514,285
<p>The Global Interpreter Lock, by itself, will not prevent threads from being scheduled. The Python C API does not run around injecting itself into the pthread library everywhere. This is both good and bad.</p> <p>It is good because you can actually do multiple things at once in a C or C++ extension.</p> <p>It is ...
4
2016-05-29T19:52:41Z
[ "python", "c++", "multithreading", "gil" ]
Does Python GIL need to be taken care when work with multi-thread C++ extension?
37,513,957
<p>I'm now implementing a data subscriber with Python, which subscribes to a data publisher (actually a ZeroMQ publisher socket) and will get notified once any new messages are fed. In my subscriber, the messages are dumped to a data processor after received. The subscriber will also get notified by the processor when ...
0
2016-05-29T19:21:08Z
37,546,482
<p>There is my solution to the question and my understanding to Python thread and pthread native ones.</p> <p>Python threads, though protected by GIL, are actually system threads. The only thing makes them different is that when running, the Python thread is protected by GIL. Threads spawned by <code>threading.Thread<...
0
2016-05-31T12:59:44Z
[ "python", "c++", "multithreading", "gil" ]
matplotlib: Why is my Y-Axis distorting?
37,513,999
<p>The statement that I use to plot my MovingAverages, <code>ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5)</code>, is causing my y-axis ticks to go beyond the end of the plot window. As a result, I am unable to eliminate clutter at the upper end of the y-axis by using <code>prune</code> to get rid of th...
0
2016-05-29T19:24:51Z
37,531,442
<p>I had to set the axis limits and ticks/tick labels explicitly using <code>plt.axis([xLength[0], xLength[-1], ax1.get_ylim()[0], ax1.get_ylim()[1]])</code> and then prune the resulting axis with <code>plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))</code></p> <p>Now my Chart is displaying the c...
0
2016-05-30T18:03:41Z
[ "python", "matplotlib" ]
Selecting and editing specific markers using matplotlib
37,514,039
<p>I'm trying to make individual markers along a Line2d object draggable. I've seen how this was done using bar() in <a href="http://matplotlib.org/users/event_handling.html" rel="nofollow">Matplotlib's draggable rectangle example.</a> The fundamental difference here is that <code>ax.bar(...)</code> generates a set of ...
2
2016-05-29T19:28:55Z
37,514,423
<p>There are a few ways for you to do this. I doubt there is an easy way for you to drag the line itself. To drag the line markers (but without seeing any) just make sure they exist but are transparent. I'm going to use an example from matplotlib documentation: <a href="http://matplotlib.org/examples/event_handling/pat...
1
2016-05-29T20:06:46Z
[ "python", "matplotlib" ]
Attribute filtering by comparing cause errors
37,514,089
<p>Model:</p> <pre><code>class Thing(db.Model): __tablename__ = 'things' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) type_id = db.Column(db.Integer, db.ForeignKey('types_of_things.id')) class TypeOfThing(db.Model): __tablename__ = 'types_of_things' id = db.Col...
1
2016-05-29T19:33:45Z
37,514,182
<p>Seems like I need do it so:</p> <pre><code>Thing.query.join(TypeOfThing).filter(TypeOfThing.number&lt;=1).first() </code></pre>
1
2016-05-29T19:42:51Z
[ "python", "sqlalchemy" ]
Python - need to display graphic for Hangman game
37,514,165
<p>I am working on a Python tutorial to code a game of Hangman. I have Python 3.5 installed to my computer, but the tutorial utilizes Python 2.7 The game works except for displaying the image. Is it a syntax problem, or is there a different way to approach this from what I have been learning? Here is my code...</p> <p...
0
2016-05-29T19:40:58Z
37,514,271
<p>It seems that your <code>hangedman</code> method isn't actually printing anything or using the hardcoded list of graphics. Try adding this line of code underneath the <code>graphic</code> list, at the end of the <code>hangedman</code> method:</p> <pre><code>print(graphic[hangman]) </code></pre>
2
2016-05-29T19:51:50Z
[ "python", "python-3.5" ]
How to make enemies pace back and forth pygame?
37,514,176
<p>I made a sprite group and displayed them on the screen, but I don't know how to make them all move? I think I understand how to move one sprite as a class, but I have an entire group now. I want to have them pacing back and forth on the platforms (like left and right constantly). I know how to work with the movement...
0
2016-05-29T19:42:07Z
37,514,995
<p>You need to define the <code>update</code> method for the Sprite to make them move around. Then you can call the <code>enemy_list.update()</code> in order to make the update on each sprite in the group.</p> <p>For reference check <a href="http://www.pygame.org/docs/ref/sprite.html" rel="nofollow">the docs</a>.</p> ...
0
2016-05-29T21:07:37Z
[ "python", "pygame", "sprite", "move" ]
Python Server socket.error: [Errno 92] Protocol not available
37,514,180
<p>I wanted to make a server, that recives an command from a client, in the form of a String and send a String(or a List of Strings) back. The first time, I run the server and the client, it works perfectly fine, but after the server send the String to the client, the server crashes with the message:</p> <pre><code>so...
0
2016-05-29T19:42:41Z
37,514,628
<p>In the server code, could you comment (or remove) the following line:</p> <pre><code>s.setsockopt(socket.AF_INET, socket.SOCK_STREAM, 1) </code></pre> <p>The setsockopt operation is to define the options of the socket. The level should be SOL_SOCKET and the differents options can be found in setsockopt man page: <...
1
2016-05-29T20:26:51Z
[ "python" ]
Efficiently applying function over moving window numpy array
37,514,204
<p>I have around 100,000 two dimensional arrays where I need to apply local filters. Both dimensions have an even size and the window is over a 2x2 piece and shifts 2 pieces further, so that every element is in a window once. The output is a binary two dimensional array of the same size and my filter is a binary 2x2 pi...
5
2016-05-29T19:45:22Z
37,514,765
<p>You can split each <code>2x2</code> subarray and then reshape such that each windowed block becomes a row in a <code>2D</code> array. From each row, extract out the elements corresponding to <code>f==1</code> positions using <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-i...
4
2016-05-29T20:41:00Z
[ "python", "performance", "python-2.7", "numpy" ]
Reading Specific Python list from a text file
37,514,272
<p>I am currently Trying to read all data Occurring after a colon ':' in a file for example. In a text file containing only:</p> <blockquote> <p>SAM Account Type : 805306368</p> </blockquote> <pre><code>with open("Sample.txt") as myfile: for line in myfile: flag=0 if ("SAM Account Type" in line): ...
1
2016-05-29T19:51:51Z
37,514,380
<p>As you are scanning for specific strings (ie those in A) I would create a list of each line in your file.</p> <p>Split each line by <code>' : '</code> which seems to be the standard break between your key and your values in your txt file.</p> <p>You now have a list that you can scan <code>B</code> and compare the ...
1
2016-05-29T20:02:51Z
[ "python", "python-3.x" ]
Reading Specific Python list from a text file
37,514,272
<p>I am currently Trying to read all data Occurring after a colon ':' in a file for example. In a text file containing only:</p> <blockquote> <p>SAM Account Type : 805306368</p> </blockquote> <pre><code>with open("Sample.txt") as myfile: for line in myfile: flag=0 if ("SAM Account Type" in line): ...
1
2016-05-29T19:51:51Z
37,514,437
<p>I think you can read all lines and process them as per your requirement. You can split a sentence based on ":" and use tokens. </p> <p><em>Note: As time also has : in it, you may want to use " : " (colon with 2 spaces)</em> </p> <p>sample code:</p> <pre><code>In [1]: with open("./input.txt") as f: ...: da...
5
2016-05-29T20:07:57Z
[ "python", "python-3.x" ]
Reading Specific Python list from a text file
37,514,272
<p>I am currently Trying to read all data Occurring after a colon ':' in a file for example. In a text file containing only:</p> <blockquote> <p>SAM Account Type : 805306368</p> </blockquote> <pre><code>with open("Sample.txt") as myfile: for line in myfile: flag=0 if ("SAM Account Type" in line): ...
1
2016-05-29T19:51:51Z
37,515,215
<p>If all you're trying to do is print values to the right of the first colon if they have a string in A, then you could:</p> <pre><code>for line in myfile: split_line = line.split(' : ', 1) #splits into list of two elements at first colon unless colon is not found, then a list of one element if split_line[0] ...
0
2016-05-29T21:35:53Z
[ "python", "python-3.x" ]
python remove element from nested list if it exists in another list +
37,514,289
<p>lets say I have a list:</p> <pre><code>A = ['x', 'y', 'z'] </code></pre> <p>and another one - nested:</p> <pre><code>B = [['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c', 'z']] </code></pre> <p>how can I remove 'z' from the last sublist in list B based on the knowledge that 'z' is in A and also every first elem...
-1
2016-05-29T19:53:36Z
37,514,305
<p>Use a list comprehension to update a list in-place:</p> <pre><code>for sublist in B: if sublist[0] in A: sublist[1:] = [v for v in sublist[1:] if v not in A] </code></pre> <p><code>j</code> in your loop is only another reference to a value in a sublist. <code>del j</code> removes that one reference, bu...
1
2016-05-29T19:55:01Z
[ "python", "list" ]
python remove element from nested list if it exists in another list +
37,514,289
<p>lets say I have a list:</p> <pre><code>A = ['x', 'y', 'z'] </code></pre> <p>and another one - nested:</p> <pre><code>B = [['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c', 'z']] </code></pre> <p>how can I remove 'z' from the last sublist in list B based on the knowledge that 'z' is in A and also every first elem...
-1
2016-05-29T19:53:36Z
37,514,335
<p>You can use a nested list comprehension:</p> <pre><code>&gt;&gt;&gt; [sub[:1]+[i for i in sub[1:] if not(sub[0] in A and i in A)] for sub in B] [['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c']] </code></pre> <p>Here you'll preserve the items from sublists (from second item to end) that doesn't met your condition...
1
2016-05-29T19:58:04Z
[ "python", "list" ]
View a file whilst it is being written - Python
37,514,466
<p>I am making a game in python 2.7 for fun and am trying to make a map to go along with it. I am using file I/O to read and write the map and have also got notepad ++ set to silent update, however I can only see the changes once my program has fully run and want to view the file as it is updated.</p> <p>I have this c...
2
2016-05-29T20:10:04Z
37,514,513
<p>By default Python uses buffered I/O. This means that written data is stored in memory before actually written to the file. Calling file's <a href="https://docs.python.org/2/library/stdtypes.html#file.flush" rel="nofollow"><code>flush</code></a> method causes the data to be written to the file.</p>
4
2016-05-29T20:15:04Z
[ "python" ]
Unique string before writing to file - python
37,514,485
<p>Why can't this work? I want to unique the results I get from the Rest api before I write it to the file --</p> <pre><code>MISP_HOST="https://192.168.1.8" API_KEY="asdfasdfas" EXPORT_DATA="attributes/text/download/md5" OUTPUT_FILE="md5-"+today def main(): URL="%s/%s" % (MISP_HOST, EXPORT_DATA) request = url...
0
2016-05-29T20:12:09Z
37,514,606
<p>If your result is plain text, you can use a regular expression to find all of the words in the text and then build a set from there. This example also lower cases the words so that the set is case insensitive and writes each word on its own line.</p> <pre><code>import re MISP_HOST="https://192.168.1.8" API_KEY="as...
2
2016-05-29T20:25:00Z
[ "python" ]
Python script using import RE to put list of words into bracket
37,514,516
<p>I have written below python script: </p> <pre><code>import re mystr = """ MA1-ETLP-01 MA1-ETLP-02 MA1-ETLP-03 MA1-ETLP-04 MA1-ETLP-05 """ wordList = re.sub("[^\w]"," ",mystr).split() print wordList </code></pre> <p>When I run the script it is giving me an output with:</p> <pre><code>-MacBook-Pro-2:Finali...
-4
2016-05-29T20:15:24Z
37,514,549
<p>The following will do the trick:</p> <pre><code>mystr.split() </code></pre>
3
2016-05-29T20:19:13Z
[ "python", "import" ]
Python script using import RE to put list of words into bracket
37,514,516
<p>I have written below python script: </p> <pre><code>import re mystr = """ MA1-ETLP-01 MA1-ETLP-02 MA1-ETLP-03 MA1-ETLP-04 MA1-ETLP-05 """ wordList = re.sub("[^\w]"," ",mystr).split() print wordList </code></pre> <p>When I run the script it is giving me an output with:</p> <pre><code>-MacBook-Pro-2:Finali...
-4
2016-05-29T20:15:24Z
37,514,559
<p>You don't need a regular expression for that. Just send the string to <code>split()</code>.</p> <pre><code>&gt;&gt;&gt; mystr = """ ... ... ... MA1-ETLP-01 ... MA1-ETLP-02 ... MA1-ETLP-03 ... MA1-ETLP-04 ... MA1-ETLP-05 ... ... """ &gt;&gt;&gt; mystr.split() ['MA1-ETLP-01', 'MA1-ETLP-02', 'MA1-ETLP-03', 'MA1-ETLP-0...
6
2016-05-29T20:19:40Z
[ "python", "import" ]
Python script using import RE to put list of words into bracket
37,514,516
<p>I have written below python script: </p> <pre><code>import re mystr = """ MA1-ETLP-01 MA1-ETLP-02 MA1-ETLP-03 MA1-ETLP-04 MA1-ETLP-05 """ wordList = re.sub("[^\w]"," ",mystr).split() print wordList </code></pre> <p>When I run the script it is giving me an output with:</p> <pre><code>-MacBook-Pro-2:Finali...
-4
2016-05-29T20:15:24Z
37,514,644
<p>If you can have spaces in the lines you will want <em>splitlines</em> instead of split and to filter the empty lines:</p> <pre><code>mystr = """ MA1-ETLP-01 MA1-ETLP-02 MA1-ETLP-03 MA1-ETLP-04 MA1-ETLP-05 """ print([line for line in mystr.splitlines() if line]) </code></pre> <p>Based on the script name <code>...
1
2016-05-29T20:28:25Z
[ "python", "import" ]
Django Sum of Multiplied Values
37,514,626
<p>I am trying to show the total weight of assets I have presented on a table.</p> <p>Each Asset has a weight and a quantity and I can present the total weight of each asset as below:</p> <pre><code>def by_item_weight(self): """This Method gives the total value of the asset. Weight * Qnty""" total = self.asse...
0
2016-05-29T20:26:35Z
37,514,879
<p>You could use the <a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/" rel="nofollow">ExpressionWrapper()</a> <em>(mostly Django 1.8+)</em></p> <pre><code>assets = Asset.objects.all().annotate( total_weight=ExpressionWrapper(F('asset_quantity') * F('asset_weight'), ...
2
2016-05-29T20:53:51Z
[ "python", "django" ]
Good way to count number of functions of a python file, given path
37,514,636
<p>I do not want to import my module. I have to count the number of functions given the .py file path. What is the best way to do so?</p> <p>One thing I thought about was to count the number of "def" in my code, but it does not seem like the best way to go about this. Is there any better way to count the number of fun...
4
2016-05-29T20:27:27Z
37,514,849
<p>you can use the <code>pyclbr</code> module to get results of the module, the only catch is that you need to use the name of the module as you would import it instead of the file path, this benefits from also recognizing <code>from X import Y</code> for python source based modules (not builtin ones like <code>math</c...
0
2016-05-29T20:50:42Z
[ "python", "parsing" ]
Good way to count number of functions of a python file, given path
37,514,636
<p>I do not want to import my module. I have to count the number of functions given the .py file path. What is the best way to do so?</p> <p>One thing I thought about was to count the number of "def" in my code, but it does not seem like the best way to go about this. Is there any better way to count the number of fun...
4
2016-05-29T20:27:27Z
37,514,858
<p>You can use <code>ast.NodeVisitor</code>:</p> <pre><code>import inspect import importlib import ast class CountFunc(ast.NodeVisitor): func_count = 0 def visit_FunctionDef(self, node): self.func_count += 1 mod = "/path/to/some.py" p = ast.parse(open(mod).read()) f = CountFunc() f.visit(p) print...
3
2016-05-29T20:51:27Z
[ "python", "parsing" ]
Good way to count number of functions of a python file, given path
37,514,636
<p>I do not want to import my module. I have to count the number of functions given the .py file path. What is the best way to do so?</p> <p>One thing I thought about was to count the number of "def" in my code, but it does not seem like the best way to go about this. Is there any better way to count the number of fun...
4
2016-05-29T20:27:27Z
37,514,895
<p>To count the top level definition, use <code>ast</code> module like this:</p> <pre><code>import ast with open(filename) as f: tree = ast.parse(f.read()) sum(isinstance(exp, ast.FunctionDef) for exp in tree.body) </code></pre>
2
2016-05-29T20:55:38Z
[ "python", "parsing" ]
Good way to count number of functions of a python file, given path
37,514,636
<p>I do not want to import my module. I have to count the number of functions given the .py file path. What is the best way to do so?</p> <p>One thing I thought about was to count the number of "def" in my code, but it does not seem like the best way to go about this. Is there any better way to count the number of fun...
4
2016-05-29T20:27:27Z
37,514,953
<p>Padraic beats me to it, but here is my code, which works with Python 2 and Python 3. </p> <pre><code>from __future__ import print_function import ast class FunctionCounter(ast.NodeVisitor): def __init__(self, filename): self.function_count = 0 with open(filename) as f: module = ast....
1
2016-05-29T21:01:10Z
[ "python", "parsing" ]
Pygame Bullets (python 3.2.5)
37,514,762
<p>I'm doing a python coding project for school and I need to code a pygame that shoots bullets from a specific blit. </p> <p>I tried using this code, </p> <pre><code>if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_SPACE): screen.blit(projectile,(projectilex,projectiley))...
0
2016-05-29T20:40:54Z
37,515,070
<p><code>screen.blit</code> only displays something for the duration of a single frame. You need to draw the bullet each frame. Use separate variables to track the bullet's X and Y position and whether to display the bullet. E.g.,</p> <pre><code>if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_SP...
1
2016-05-29T21:16:05Z
[ "python", "pygame" ]
Pygame Bullets (python 3.2.5)
37,514,762
<p>I'm doing a python coding project for school and I need to code a pygame that shoots bullets from a specific blit. </p> <p>I tried using this code, </p> <pre><code>if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_SPACE): screen.blit(projectile,(projectilex,projectiley))...
0
2016-05-29T20:40:54Z
37,515,199
<p>Try to insert in your code this:</p> <pre><code>pygame.key.set_repeat (1, 50) </code></pre> <p>This allow code to repeate KEY_DOWN check: 1=delay, 50= time repeat</p> <p>So:</p> <pre><code>pygame.key.set_repeat (1, 50) if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_SPACE): ...
0
2016-05-29T21:32:59Z
[ "python", "pygame" ]
Adding second instance of Firefox with Marionette (change port)
37,514,778
<p>I'm having great difficulties creating two instances of firefox via marionette. Having one instance works fine: </p> <p>Starting up Firefox with marionette enabled:</p> <pre><code>firefox.exe -marionette </code></pre> <p>Controlling it with python:</p> <pre><code>from marionette import Marionette client = Marion...
1
2016-05-29T20:42:19Z
37,666,112
<p>You have to use different profiles to make firefox listen on different ports.<br> Edit <code>&lt;path-to-profile&gt;/prefs.js</code> add the following and save <strong>when firefox is not using this profile</strong>;</p> <pre><code>user_pref("marionette.defaultPrefs.port", 2829); </code></pre> <p>Now, start firefo...
2
2016-06-06T20:15:27Z
[ "python", "firefox", "firefox-marionette" ]
How do I define custom comparison (0 < mytype) in python?
37,514,787
<p>So I'm currently (ab)using python notation to create a domain specific language. As part of this I'm overriding comparison functions to return non-boolean values.</p> <p>So, for (mytype1 &lt; mytype2) and (mytype &lt; 0) I can easily do this by defining the __lt__() magic method.</p> <p>However, I cannot figure ou...
3
2016-05-29T20:43:08Z
37,514,821
<p>As per <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__" rel="nofollow">the documentation</a> the reflected form of <code>__lt__()</code> is <code>__gt__()</code>.</p> <blockquote> <p>There are no swapped-argument versions of these methods (to be used when the left argument does not suppo...
4
2016-05-29T20:47:34Z
[ "python" ]
How to get the region of the current user from boto?
37,514,810
<p>Problem:</p> <p>I'm trying to get the region of the authenticated user from boto3.</p> <p>Use case:</p> <p>I'm working on adding cache to <a href="https://github.com/pmazurek/aws-fuzzy-finder" rel="nofollow">https://github.com/pmazurek/aws-fuzzy-finder</a>. I would prefer to cache the result on <em>per-region</em...
1
2016-05-29T20:45:58Z
37,519,906
<p>You should be able to read the <a href="https://boto3.readthedocs.io/en/latest/reference/core/session.html#boto3.session.Session.region_name" rel="nofollow"><code>region_name</code></a> from the <code>session.Session</code> object like</p> <pre><code>my_session = boto3.session.Session() my_region = my_session.regio...
2
2016-05-30T07:26:13Z
[ "python", "amazon-web-services", "amazon-ec2", "boto", "aws-sdk" ]
Eigen missing from the installation for OpenCV3
37,515,010
<p>I have been trying to install Opencv3 using <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">this</a> installation guide. </p> <p>I had trouble building <code>opencv_contrib</code> extras, can’t find <code>unsupported/Eigen</code>, in step 8 of the guide. ...
0
2016-05-29T21:09:03Z
37,515,041
<p>I figured out how to solve it by using <a href="http://www.alecjacobson.com/weblog/?tag=eigen" rel="nofollow">this</a> blog post.</p> <p>You just have to run the following line of code:</p> <p><code>cmake -DOPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -DEIGEN_INCLUDE_PATH=/usr/local/include/eigen3/ ..</code>...
0
2016-05-29T21:12:10Z
[ "python", "opencv", "installation", "opencv3.0" ]
Programming Metronome Python Script with PubNub for Raspberry Pi
37,515,027
<p>I have created an Android mobile app which sends a BPM variable (between 0 and 160) over PubNub. </p> <p>My goal here is to make a LED blink on my Raspberry Pi (GPIO 18) on every beat based off on the BPM value. As you can see in the code. However, when I launch my script. Nothing seems to be happening. The LED sta...
0
2016-05-29T21:10:33Z
37,531,304
<p>I've found the solution and it works right now. I'll share it here. I still have a problem that it's stuck in a loop because of the "while: True". I can't find a way to exit the loop once a new BPM value has been sent to the Pi. So I have to rerun the script every time I want to get a different tempo.</p> <pre><cod...
0
2016-05-30T17:53:20Z
[ "android", "python", "raspberry-pi" ]
RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
37,515,053
<p>I'm going through the API tutorial on New Coder (<a href="http://newcoder.io/api/" rel="nofollow">this one</a>) and got the following error when I try to run the program:</p> <pre><code>RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9Traceback (most recent call last): File "a...
1
2016-05-29T21:14:00Z
37,774,182
<p>Installing packets from file with requirements may cause failures. I mean something like <code>pip install -r requirements.txt</code></p> <p>It seems to me that pip just installs packets in order without dependencies (first line from file, second line, ...).</p> <p>I had same issue because of having installed nump...
0
2016-06-12T12:19:58Z
[ "python", "api", "numpy", "matplotlib" ]
Dictionary operation on a list of items
37,515,153
<p>I have a dictionary</p> <pre><code>{ 'a': 1.0, 'b': 1.1, 'c': 0.9, # ... 'z': 0.97 } </code></pre> <p>I have a list of items say <code>['a', 'b', 'c']</code>. I want to find the average of the values of this list from the dictionary. Of course I can iterate through my list, finding and summing the values, ...
0
2016-05-29T21:27:04Z
37,515,181
<p>You <em>have</em> to have a loop. You can hide the loop however.</p> <p>You could use a <a href="https://docs.python.org/2/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter()</code> object</a> to do this for you, for example:</p> <pre><code>from operator import itemgetter average...
2
2016-05-29T21:30:34Z
[ "python", "performance", "dictionary", "hash", "iterator" ]
Dictionary operation on a list of items
37,515,153
<p>I have a dictionary</p> <pre><code>{ 'a': 1.0, 'b': 1.1, 'c': 0.9, # ... 'z': 0.97 } </code></pre> <p>I have a list of items say <code>['a', 'b', 'c']</code>. I want to find the average of the values of this list from the dictionary. Of course I can iterate through my list, finding and summing the values, ...
0
2016-05-29T21:27:04Z
37,515,189
<p>If your dict is called <code>values</code> and your list is called <code>items</code>, there's a very short solution:</p> <pre><code>arithmetic_mean_inexact = sum(values[i] for i in items) / len(items) </code></pre> <p>Note that this doesn't support an empty <code>items</code> list, as this will result in a <code>...
2
2016-05-29T21:31:22Z
[ "python", "performance", "dictionary", "hash", "iterator" ]
Dictionary operation on a list of items
37,515,153
<p>I have a dictionary</p> <pre><code>{ 'a': 1.0, 'b': 1.1, 'c': 0.9, # ... 'z': 0.97 } </code></pre> <p>I have a list of items say <code>['a', 'b', 'c']</code>. I want to find the average of the values of this list from the dictionary. Of course I can iterate through my list, finding and summing the values, ...
0
2016-05-29T21:27:04Z
37,515,224
<p>If you are using python3 you could use <em>statistics.mean:</em></p> <pre><code>d = { "a": 1.0, "b": 1.1, "c": 0.9, "z": 0.97 } lst = ["a", "b", "c"] from statistics import mean print(mean(map(d.get, lst))) </code></pre> <p>Or just using sum:</p> <pre><code>print(sum(map(d.get, lst)) / len(lst)) </code>...
2
2016-05-29T21:37:54Z
[ "python", "performance", "dictionary", "hash", "iterator" ]
Python: else ValueError: (Specifically ValueError In This Case)
37,515,172
<p>I have a question which is unrelated to my code. I'm just curious. Why is it that I (I don't know about you) can only use a ValueError with a try and except loop? for example:</p> <pre><code>print("What is 1 + 1?") while(True): try: UserInput = int(input(("Your answer here:")) if(UserInput == 2)...
0
2016-05-29T21:29:37Z
37,515,211
<p>The SyntaxError in the second example comes from the fact, that <code>else</code> needs no condition. The first example is totally ok.</p> <p>Still better, keep the try-block as short as possible:</p> <pre><code>print("What is 1 + 1?") while True: try: UserInput = int(input(("Your answer here:")) e...
3
2016-05-29T21:35:10Z
[ "python", "python-3.x", "if-statement", "while-loop", "try-except" ]
Python: else ValueError: (Specifically ValueError In This Case)
37,515,172
<p>I have a question which is unrelated to my code. I'm just curious. Why is it that I (I don't know about you) can only use a ValueError with a try and except loop? for example:</p> <pre><code>print("What is 1 + 1?") while(True): try: UserInput = int(input(("Your answer here:")) if(UserInput == 2)...
0
2016-05-29T21:29:37Z
37,515,256
<p><code>try</code> and <code>except</code> are a form of control flow. Essentially, it means <code>try</code> to run this code, <code>except</code> if an exception occurs (such as <code>ValueError</code>) do something else.</p> <p><code>if</code> and <code>else</code> are another form of control flow. Together, they ...
2
2016-05-29T21:42:53Z
[ "python", "python-3.x", "if-statement", "while-loop", "try-except" ]
The view producer.pfviews.podcastsetup didn't return an HttpResponse object. It returned None instead
37,515,289
<p>I am creating a podcast management website where you have to register a user w/ django redux registration and provide a username, email &amp; password. When thats done, it takes them straight to a dashboard where they can setup their podcast. When they are going to set it up, I want them to provide me with a <code>c...
0
2016-05-29T21:48:09Z
37,515,366
<pre><code>def podcastsetup(request): title = 'Podcast Setup' title_align_center = True form = PodcastSetupForm(request.POST or None) context = { "title": title, "form": form } if form.is_valid(): instance = form.save(commit=False) company_name = form.cleaned_...
1
2016-05-29T21:58:48Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
Django Shortcut nested foreign key
37,515,302
<p>Suppose I have the following in my models.py:</p> <pre><code>class Book: pass class Part: book = models.ForeignKey(Book) class Chapter: part = models.ForeignKey(Part) number = models.IntegerField() </code></pre> <p>I would like to do</p> <pre><code>book = Book.objects.get(id=someID) chapters = B...
0
2016-05-29T21:50:25Z
37,515,546
<p>Using related_name arguments for FK fields, coupled with prefetch_related for a queryset, will allow you to fetch all info related to a book with minimal performance hit (each prefetch_related param calls a separate query). </p> <pre><code>class Book: pass class Part: book = models.ForeignKey(Book, related...
0
2016-05-29T22:25:18Z
[ "python", "django", "nested", "foreign-key-relationship" ]
How to use mocks in Python?
37,515,310
<p>I know that there are tutorials and other posts about mocks in Python but I'm new to testing and mocks, I read some posts and watched a tutorial but they confused me more. I have two examples that I just wrote fast and I wanna know how can I use mocks to test two examples.</p> <p>In the first example test the the v...
0
2016-05-29T21:51:30Z
37,515,555
<p>In the first example, you want to mock <code>requests.get</code> so that you can control its return value. Since <code>requests.get</code> is actually a Mock object when you call <code>get_link_tags</code>, its return value will be as well, so you can configure its <code>text</code> attribute to be whatever data you...
3
2016-05-29T22:26:05Z
[ "python", "unit-testing", "mocking", "python-unittest" ]
Python static variable reassignment
37,515,328
<p>Trying to understand Python static variables, and the following confuses me:</p> <pre><code>&gt;&gt;&gt; class Foo(): ... a = [1] ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; Foo.a.append(2) &gt;&gt;&gt; Foo.a [1, 2] &gt;&gt;&gt; f.a [1, 2] &gt;&gt;&gt; f.a.append(3) &gt;&gt;&gt; f.a [1, 2, 3] &gt;&gt;&gt; Foo.a [1...
0
2016-05-29T21:54:36Z
37,515,369
<p>I wouldn't call it syntactic sugar. Rather, it's a consequence of the name lookup order in Python scopes.</p> <p>Given an instance, Python will first attempt to look up a name on that instance. If that fails, it will fail back to looking it up in the class. This is what is happening in your case; at first, the name...
2
2016-05-29T21:59:24Z
[ "python", "variables", "static", "instance" ]
How to execute a python script with selenium called by php through apache server?
37,515,412
<p>I want to execute the following script in Python through my site in local apache server:</p> <pre><code>#!/Python34/python from selenium import webdriver driver=webdriver.Firefox() driver.get("C:\wamp64\www\desenvol\index.html") elem1 = driver.find_element_by_link_text("call another page") elem1.click() </code></p...
1
2016-05-29T22:04:37Z
37,515,643
<p>Provide the full path to the python script, i.e.:</p> <pre><code>shell_exec('python /full/path/to/hello.py'); </code></pre> <p>If you want to play safe, also provide the full path to the python binary.</p> <pre><code>shell_exec('/usr/local/bin/python /full/path/to/hello.py'); </code></pre> <p>To find the full pa...
0
2016-05-29T22:39:38Z
[ "php", "python", "html", "apache", "selenium" ]
How to execute a python script with selenium called by php through apache server?
37,515,412
<p>I want to execute the following script in Python through my site in local apache server:</p> <pre><code>#!/Python34/python from selenium import webdriver driver=webdriver.Firefox() driver.get("C:\wamp64\www\desenvol\index.html") elem1 = driver.find_element_by_link_text("call another page") elem1.click() </code></p...
1
2016-05-29T22:04:37Z
37,638,024
<p>I did not solve it in the easy way. So, that is what I do:</p> <ul> <li>First I created a database with one table and two columns (id and 'numero') </li> <li>Then I make a loop in python for take the value from 'numero' in a specific id (0) and to compare if this value is changed, if this happens the python will ex...
0
2016-06-05T03:01:05Z
[ "php", "python", "html", "apache", "selenium" ]
Sorting all rows in numpy matrix by target-column
37,515,461
<p>This seems been asked many times, however the answer I found not work now. Let's be simple, here I have a numpy matrix</p> <pre><code>data = np.matrix([[9, 8], [7, 6], [5, 7], [3, 2], [1, 0]]) </code></pre> <p>Then sort by second column as below</p> <pre><code>[...
0
2016-05-29T22:11:22Z
37,515,668
<p>The approach in your link is working:</p> <pre><code>import numpy as np data = np.matrix([[9, 8], [7, 6], [5, 7], [3, 2], [1, 0]]) print(data[np.argsort(data.A[:, 1])]) [[1 0] [3 2] [7 6] [5 7] [9 8]] </code></pre> <p>And now an example where it's better to see:</p> <pre...
1
2016-05-29T22:45:31Z
[ "python", "sorting", "numpy", "matrix" ]
Sorting all rows in numpy matrix by target-column
37,515,461
<p>This seems been asked many times, however the answer I found not work now. Let's be simple, here I have a numpy matrix</p> <pre><code>data = np.matrix([[9, 8], [7, 6], [5, 7], [3, 2], [1, 0]]) </code></pre> <p>Then sort by second column as below</p> <pre><code>[...
0
2016-05-29T22:11:22Z
37,515,682
<p>You are a moving target.</p> <p>Sort each column independently:</p> <pre><code>In [151]: np.sort(data,axis=0) Out[151]: matrix([[1, 0], [3, 2], [5, 6], [7, 7], [9, 8]]) </code></pre> <p>Sort on the values of the second column</p> <pre><code>In [160]: ind=np.argsort(data[:,1],axis...
3
2016-05-29T22:47:57Z
[ "python", "sorting", "numpy", "matrix" ]
TensorFlow gradient does not respond when using while_loop
37,515,503
<p>I'm using TensorFlow to build a deep learning model. (The entire model is very complicated.) In the model, I need to use <code>while_loop</code> to dynamically control the computation flow based on my input sentences number. Previously, I used <code>for</code> loop instead of <code>while_loop</code>. After I switche...
0
2016-05-29T22:18:44Z
37,623,718
<p>refer to <a href="http://stackoverflow.com/questions/37571017/tensorflow-stuck-into-endless-loop-using-tf-while-loop">TensorFlow stuck into endless loop using tf.while_loop()</a>. note that if the body contains trainable variables, you need use variable scope</p>
0
2016-06-03T21:28:53Z
[ "python", "tensorflow" ]
find if the xss injection bypassed the filter from python
37,515,522
<p>I'm writing a crawler, (in python 2.7, windows 10) that receive an address of a web page (like <a href="https://www.wikipedia.com" rel="nofollow">https://www.wikipedia.com</a> ) and crawle to find all the pages. once this is done the program should go on all the pages and try to find an xss vulnerability, my problem...
1
2016-05-29T22:21:10Z
37,555,755
<p>You can use Selenium and <code>switch_to.alert()</code> to identify the successful invocation of alert. </p>
0
2016-05-31T21:15:28Z
[ "python", "python-2.7", "xss" ]
Python intersection with substrings
37,515,531
<p>I have two sets:</p> <pre><code>a = set(['this', 'is', 'an', 'apple!']) b = set(['apple', 'orange']) </code></pre> <p>I want to find if there are any (b) in (a) including substrings. normally I would do:</p> <pre><code>c = a.intersection(b) </code></pre> <p>However, in this example it would return an empty set ...
2
2016-05-29T22:23:02Z
37,515,561
<p>The best thing to do is:</p> <pre><code>any(x in y for x in b for y in a) </code></pre> <p>It's a loop, but you can't escape that. Any solution will at least have an implied loop somewhere.</p>
0
2016-05-29T22:27:15Z
[ "python", "string", "set", "substring", "intersection" ]
Python intersection with substrings
37,515,531
<p>I have two sets:</p> <pre><code>a = set(['this', 'is', 'an', 'apple!']) b = set(['apple', 'orange']) </code></pre> <p>I want to find if there are any (b) in (a) including substrings. normally I would do:</p> <pre><code>c = a.intersection(b) </code></pre> <p>However, in this example it would return an empty set ...
2
2016-05-29T22:23:02Z
37,515,571
<p>Instead of doing the equality check via <code>==</code>, you can use <code>in</code> for substring match which also covers equality:</p> <pre><code>&gt;&gt;&gt; [x for ele in a for x in b if x in ele] ["apple"] </code></pre>
3
2016-05-29T22:28:35Z
[ "python", "string", "set", "substring", "intersection" ]
Python intersection with substrings
37,515,531
<p>I have two sets:</p> <pre><code>a = set(['this', 'is', 'an', 'apple!']) b = set(['apple', 'orange']) </code></pre> <p>I want to find if there are any (b) in (a) including substrings. normally I would do:</p> <pre><code>c = a.intersection(b) </code></pre> <p>However, in this example it would return an empty set ...
2
2016-05-29T22:23:02Z
37,515,843
<p>Using sets is actually of little benefit if you are not searching for exact matches, if the words always start with the same substring, sorting and bisecting will be a more efficient approach i.e <code>O(n log n)</code> vs <code>O(n^2)</code>:</p> <pre><code>a = set(['this', 'is', 'an', 'apple!']) b = set(['apple',...
0
2016-05-29T23:15:56Z
[ "python", "string", "set", "substring", "intersection" ]
Using the recursive code, I want to return a set of 2 values (total files, folders)
37,515,573
<p>I've written this program that does not use os.walk(), glob or fnmatch and that is intentional. It looks at the directory and all the subdirectories and files in that specified directory and returns how many files + folders are in there.</p> <pre><code>import os def fcount(path): count = 0 '''Folders''' ...
0
2016-05-29T22:28:44Z
37,515,652
<p>Keep two counts and return them as a tuple:</p> <pre><code>total_count = dir_count = 0, 0 # .. increment either as needed return total_count, dir_count </code></pre> <p>You only need to loop over <code>os.listdir()</code> <em>once</em>; you already detect if something is a file or a directory so just differentiate...
2
2016-05-29T22:40:53Z
[ "python", "python-3.x", "recursion", "tuples", "subdirectories" ]
How to check if a file is already opened (in the same process)
37,515,574
<p>And I'd like to specifically achieve that with the try catch construct.</p> <p>This <a href="http://stackoverflow.com/questions/6825994/check-if-a-file-is-open-in-python">related question</a> suggests that I can do:</p> <pre><code>try: open(fileName, 'wb+') except: print("File already opened!") raise <...
3
2016-05-29T22:28:45Z
37,515,789
<p>You open the same file but assign them to different variables. What you should do is:</p> <pre><code>fileobj=open(filename,"wb+") if not fileobj.closed: print("file is already opened")` </code></pre> <p>I'm writing with my phone so the styling may not be good but you will get the point. By the way the <code>....
-1
2016-05-29T23:05:40Z
[ "python", "file-io", "raspbian", "python-3.5" ]
How to check if a file is already opened (in the same process)
37,515,574
<p>And I'd like to specifically achieve that with the try catch construct.</p> <p>This <a href="http://stackoverflow.com/questions/6825994/check-if-a-file-is-open-in-python">related question</a> suggests that I can do:</p> <pre><code>try: open(fileName, 'wb+') except: print("File already opened!") raise <...
3
2016-05-29T22:28:45Z
37,515,805
<p>I would suggest using something like this.</p> <pre><code>def is_open(file_name): if os.path.exists(file_name): try: os.rename(file_name, file_name) #can't rename an open file so an error will be thrown return False except: return True raise NameError </co...
1
2016-05-29T23:09:00Z
[ "python", "file-io", "raspbian", "python-3.5" ]
run a basic digital clock in the python shell
37,515,587
<p>I want to code simple digital clock in the python shell. I want to avoid using tkinter if possible. This is what I currently have;</p> <pre><code>import time while True: from datetime import datetime now = datetime.now() print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now....
2
2016-05-29T22:31:26Z
37,515,630
<p>If you're just printing out a fixed length output like this each time, you can use the carriage return character to rewind to the start of the line, as long as you don't print a newline. Example:</p> <pre><code># Note trailing comma, that suppresses the newline in Python print ("%s/%s/%s %s:%s:%s" % (now.month,now....
6
2016-05-29T22:37:09Z
[ "python", "shell", "clock", "digital" ]
run a basic digital clock in the python shell
37,515,587
<p>I want to code simple digital clock in the python shell. I want to avoid using tkinter if possible. This is what I currently have;</p> <pre><code>import time while True: from datetime import datetime now = datetime.now() print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now....
2
2016-05-29T22:31:26Z
37,542,120
<p>Thanks for the help everyone, got it to work in the end in the cmd interpreter wow such a relief! =) IDLE was no help, going to check out the alternatives.</p>
0
2016-05-31T09:38:33Z
[ "python", "shell", "clock", "digital" ]
Installing XGBoost
37,515,599
<p>I am trying use the XGBoost package, but I am having trouble installing it. I am following the installation guide here <a href="https://xgboost.readthedocs.io/en/latest/build.html#python-package-installation" rel="nofollow">https://xgboost.readthedocs.io/en/latest/build.html#python-package-installation</a>. I have ...
0
2016-05-29T22:32:52Z
37,530,742
<p>If you have <code>python</code> in your <code>/usr/bin/</code> directory, all you need to do is to add that directory to your path.</p> <p>Add this line to your <code>.bash_profile</code> and restart your shell.</p> <p><code>export PATH="$PATH:/usr/bin"</code></p> <p>Then you should be able to use any of the pyth...
0
2016-05-30T17:08:34Z
[ "python", "osx", "terminal" ]
Python Selenium WebElement elemet - invalid syntax
37,515,755
<p>Im trying to scroll to a particular element on a page but before I do that Im trying to set myelement to be a WebElement object, heres the code</p> <pre><code>from selenium import webdriver browser.get("http://www.agoda.com/the-coast-resort-koh-phangan/hotel/koh-phangan-th.html") WebElement myelement = browser.fin...
1
2016-05-29T22:58:55Z
37,515,773
<p>Python isn't Java. (WebElement element = ...;)</p> <p>Here's a link to the <a href="http://selenium-python.readthedocs.io/" rel="nofollow">documentation</a> for the python methods etc.</p> <p>What you actually want is:</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() browser.get("http:...
4
2016-05-29T23:02:22Z
[ "python", "selenium-webdriver" ]