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 |
---|---|---|---|---|---|---|---|---|---|
Parse arithmetic string with regular expression | 39,820,551 | <p>I need to parse an arithmetic string with only <em>times</em> (<code>*</code>) and <em>add</em> (<code>+</code>), e.g., <code>300+10*51+20+2*21</code>, use regular expressions. </p>
<p>I have the working code below: </p>
<pre><code>import re
input_str = '300+10*51+20+2*21'
#input_str = '1*2+3*4'
prod_re = re.compile(r"(\d+)\*(\d+)")
sum_re = re.compile(r"(\d+)\+?")
result = 0
index = 0
while (index <= len(input_str)-1):
#-----
prod_match = prod_re.match(input_str, index)
if prod_match:
# print 'find prod', prod_match.groups()
result += int(prod_match.group(1))*int(prod_match.group(2))
index += len(prod_match.group(0))+1
continue
#-----
sum_match = sum_re.match(input_str, index)
if sum_match:
# print 'find sum', sum_match.groups()
result += int(sum_match.group(1))
index += len(sum_match.group(0))
continue
#-----
if (not prod_match) and (not sum_match):
print 'None match, check input string'
break
print result
</code></pre>
<p>I am wondering if there is a way to avoid creating the variable <code>index</code> above? </p>
| 0 | 2016-10-02T19:02:17Z | 39,821,045 | <p>The algorithm seems not correct. An input of <code>1*2+3*4</code> does not yield a correct result. It seems wrong that after resolving one multiplication you continue to resolve an addition, while in some cases you would have to first resolve more multiplications before doing any additions.</p>
<p>With some change in the regular expressions and loops, you can achieve what you want as follows:</p>
<pre><code>import re
input_str = '3+1*2+3*4'
# match terms, which may include multiplications
sum_re = re.compile(r"(\d+(?:\*\d+)*)(?:\+|$)")
# match factors, which can only be numbers
prod_re = re.compile(r"\d+")
result = 0
# find terms
for sum_match in sum_re.findall(input_str):
# for each term, determine its value by applying the multiplications
product = 1
for prod_match in prod_re.findall(sum_match):
product *= int(prod_match)
# add the term's value to the result
result += product
print (result)
</code></pre>
<h3>Explanation</h3>
<p>This regular expression:</p>
<pre><code>(\d+(?:\*\d+)*)(?:\+|$)
</code></pre>
<p>... matches an integer followed by zero or more multiplications:</p>
<pre><code>(?:\*\d+)*
</code></pre>
<p>The <code>(?:</code> makes it a non-capture group. Without <code>?:</code> the method <code>findall</code> would assign this part of the match to a separate list element, which we don't want.</p>
<p><code>\*\d+</code> is: a literal asterisk followed by digits.</p>
<p>The final <code>(?:\+|$)</code> is again a non-capture group, that requires either a literal <code>+</code> to follow, or the end of the input (<code>$</code>).</p>
| 1 | 2016-10-02T19:52:17Z | [
"python",
"regex",
"math"
]
|
Parse arithmetic string with regular expression | 39,820,551 | <p>I need to parse an arithmetic string with only <em>times</em> (<code>*</code>) and <em>add</em> (<code>+</code>), e.g., <code>300+10*51+20+2*21</code>, use regular expressions. </p>
<p>I have the working code below: </p>
<pre><code>import re
input_str = '300+10*51+20+2*21'
#input_str = '1*2+3*4'
prod_re = re.compile(r"(\d+)\*(\d+)")
sum_re = re.compile(r"(\d+)\+?")
result = 0
index = 0
while (index <= len(input_str)-1):
#-----
prod_match = prod_re.match(input_str, index)
if prod_match:
# print 'find prod', prod_match.groups()
result += int(prod_match.group(1))*int(prod_match.group(2))
index += len(prod_match.group(0))+1
continue
#-----
sum_match = sum_re.match(input_str, index)
if sum_match:
# print 'find sum', sum_match.groups()
result += int(sum_match.group(1))
index += len(sum_match.group(0))
continue
#-----
if (not prod_match) and (not sum_match):
print 'None match, check input string'
break
print result
</code></pre>
<p>I am wondering if there is a way to avoid creating the variable <code>index</code> above? </p>
| 0 | 2016-10-02T19:02:17Z | 39,830,803 | <p>The solution to your problem should be a possible sign preceded <code>term</code> followed by a list of terms, separated by an adding operator like in</p>
<pre><code>[+-]?({term}([+-]{term})*)
</code></pre>
<p>in which each term is one factor, followed by a possible empty list of a multiplicative operator and another factor, like this:</p>
<pre><code>{factor}([*/]{factor})*
</code></pre>
<p>where factor is a sequence of digits <code>[0-9]+</code>, so substituting, leads to:</p>
<pre><code>[+-]?([0-9]+([*/][0-9]+)*([+-][0-9]+([*/][0-9]+)*)*)
</code></pre>
<p>This will be a possible regexp that you can have, It assumes the structure of precedence between the operators that you can have. But it doesn't allow you to extract the different elements, as is demonstrated easily: the regexp has only 4 group elements inside (4 left parenthesis) so you can only match four of these (the first term, the last factor of the first term, the last term, and the last factor of the last term. If you begin to surround subexpressions with parenthesis, you can get more, but thing that the number of groups in a regexp is <strong>finite</strong>, and you can construct a possible infinitely long regular expression.</p>
<p>Said this (that you will not be able to separate all groups of things from the regexp structure) a different approach is taken: first sign is optional, and can be followed by an undefined number of terms, separated by either multiplicative operators or by additive ones:</p>
<pre><code>[+-]?([0-9]+([*/+-][0-9]+)*
</code></pre>
<p>will do the work also (it matches the same set of expressions. Even if you restrict to the fact that only one operator can be interspesed in any secuence of 1 or more digits, the resulting regexp could be simplified to:</p>
<pre><code>[-+]?[0-9]([*/+-]?[0-9])*
</code></pre>
<p>or with the usual notations used nowadays, to:</p>
<pre><code>[-+]?\d([*/+-]?\d)*
</code></pre>
| 0 | 2016-10-03T11:43:46Z | [
"python",
"regex",
"math"
]
|
Using pathlib/os.path etc correctly | 39,820,595 | <p>I was wondering how to use the os.path and pathlib correctly. I'm supposed to search for a directory(which I already did) and then after that enter a letter and space and it will decide what it will do.</p>
<p>import os
import os.path
import shutil
from pathlib import Path</p>
<pre><code>def search_files():
directory = input()
exist = Path(directory)
if exist.exists():
return directory
else:
print("Error")
print("Try again: ")
return search_files()
def search_characteristics(directory):
interesting = input()
exist = os.path.exists(directory)
if interesting[0] == 'N':
return os.path.join(directory, interesting)
else:
print("Error")
return search_characteristics()
if __name__ == '__main__':
directory = input()
search_files()
search_characteristics(directory)
</code></pre>
<p>For this as you can see, search_files looks for a directory which works.
The next part is the one where I'm confused. Basically after it searches for a directory, C:\Program Files or something, I would enter N in the new line to search for what I want in the directory. </p>
<p>Say like </p>
<blockquote>
<p>C:\Users\Desktop\stuff</p>
<p>N something.txt</p>
</blockquote>
<p>The N would look for the exact name of the file. </p>
<p>Am I doing it correctly or is there another way to do it?</p>
| 0 | 2016-10-02T19:06:04Z | 39,822,114 | <p>This script will do what you want. Along with using the result of your directory search function for the next call, I also changed the compare to use <code>.startswith</code> so that a emtpy string response doesn't crash the program.</p>
<pre><code>import os
from pathlib import *
def search_files():
directory = input()
exist = Path(directory)
if exist.exists():
return directory
else:
print("Error")
print("Try again: ")
return search_files()
def search_characteristics(directory):
interesting = input()
exist = os.path.exists(directory)
if interesting.startswith('N'):
return os.path.join(directory, interesting)
else:
print("Error")
return search_characteristics(directory)
if __name__ == '__main__':
directory = search_files()
fn = search_characteristics(directory)
print(fn)
</code></pre>
| 0 | 2016-10-02T21:55:58Z | [
"python"
]
|
Cannot find the json via ajax | 39,820,695 | <p>I am trying to implement a simple web using flask. When I tried to read a local json data from python and pass it to the front end. It failed.</p>
<p>My file hierarchy:</p>
<pre><code>-app
-static
-data
predict.json
scripts.js
-templates
index.html
models.py
views.py
__init__.py
run.py
</code></pre>
<p>Related python part:</p>
<pre><code>import os
from app import app
@app.route("/test",methods=['GET'])
def get_local_json():
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
json_url = os.path.join(SITE_ROOT, "static/data",'predict.json')
data = json.load(open(json_url))
return data
</code></pre>
<p>Related JS part in scripts.js:</p>
<pre><code>$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT + "/test", function (data) { ...}
</code></pre>
<p>When I run this web on my computer, the console log shows:</p>
<blockquote>
<p>jquery-3.1.0.min.js:4 GET <a href="http://127.0.0.1:5000/predict.json" rel="nofollow">http://127.0.0.1:5000/predict.json</a> 404 (NOT
FOUND)</p>
</blockquote>
<p>It seems not detect my modification (my first version just reads the data from JS).</p>
<p>Any hints are highly appreciated!</p>
| 0 | 2016-10-02T19:18:08Z | 39,858,185 | <p>The problem here is that the browser cache the javascript file, so that no matter what modification I made, it just failed to detect it.</p>
<p>To avoid it, a smart way is to add change the js statement in html to href="xxx.js?ver=1.0"</p>
| 0 | 2016-10-04T17:17:01Z | [
"jquery",
"python",
"json",
"ajax",
"flask"
]
|
SyntaxError at Cloud9 IDE? Is this a bug or did I do something wrong? | 39,820,713 | <p>I believe I have found a bug with the Cloud9 IDE, as I get a syntax error in the following code: </p>
<pre><code> for x in optionMenu:
print x[0], x[1]
action = raw_input ("Please select an action: ")
if action == "1":
direction = directionMenu()
if direction == "East":
validAction = True
print "You raise the portcullis and enter the palace."
room2(character)
else:
print "You can't go that way!"
elif action == "2":
characterMenu(character)
elif action == "3":
if searched_yet1 == False:
skill_pass = skillCheck(1, character.search)
if skill_pass == True:
print "The double portcullis seems moveable with some effort."
searched_yet1 = True
else:
print "You fail to find anything worthy of note. "
searched_yet1 = True
else:
print "You have already attempted that action!"
elif action == "4":
if listened_yet1 == False:
skill_pass = skillCheck(5, character.listen)
if skill_pass == True:
print "Sounds coming from deep in the palace can be heard every few minutes."
listened_yet1 = True
else:
print "You fail to hear anything worth of note. "
listened_yet1 = True
else:
print "You have already attempted that action!"
</code></pre>
<p>The syntax error occurs at <code>"elif action == "4":</code>. AmI doing something wrong or have I found a bug with the Cloud9 IDE? I have tried adjusting the spacing. Is there an error with the above print statement?</p>
<p>EDIT: Version is Python 2.7.6, error is </p>
<pre><code>File "/home/ubuntu/workspace/dungeonMap.py", line 63
elif action == "4":
^
SyntaxError: invalid syntax
</code></pre>
| 0 | 2016-10-02T19:19:38Z | 39,820,907 | <p>As I examine your code as posted here, the line <code>elif action == 4:</code> is preceded by 4 spaces then 2 tabs. Mixing spaces and tabs in Python is <em>a very bad idea</em>. I also see that some lines, such as the preceding one, use only spaces for indentation.</p>
<p>Replace those two tabs, as well as any others, with spaces, and configure your IDE to use only spaces when indenting. See if that solves the problem.</p>
<hr>
<p>After looking more closely, I now see the direct problem. I believe that Python treats a tab as 8 spaces, no matter how it appears in your editor. Given that, your line two lines above your problem line is an <code>else:</code> but is indented to conclude the <code>if action == "1":</code> line rather than the <code>if searched_yet1 == False:</code> line that you intended. Python then sees your <code>elif action == 4:</code> line as an <code>elif</code> without a corresponding prior <code>if</code>.</p>
<p>Again, replacing all those tabs with spaces and then getting the indentation to look right will solve that problem and others.</p>
| 1 | 2016-10-02T19:38:54Z | [
"python",
"syntax"
]
|
Using Selenium for Python Scripting | 39,820,726 | <p>I have written a <code>Python</code> code to open my gmail account. Here is the code that I am using:</p>
<pre><code>from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.gmail.com')
emailElem = browser.find_element_by_id('email')
emailElem.send_keys(myemail)
emailElem = browser.find_element_by_id('password')
emailElem.send_keys(mypassword)
emailElem = browser.find_element_by_id('signInSubmit')
emailElem.submit()
</code></pre>
<p>Everything is working fine. I have also found out that there are sites that lets one <code>Log In</code> only after entering a <code>Captcha</code>, to prevent scripts from logging in. </p>
<p><strong>Is there a way in which I can use my above code get around this problem??</strong></p>
| -1 | 2016-10-02T19:20:41Z | 39,820,787 | <p>Experimentation. If the site is not showing a captcha to normal users you'll have to mimic being a human with your code. So that could mean that you use <code>time.sleep(x)</code> to make it seem like it takes a while before certain actions happen. </p>
<p>Otherwise there are services out there that solve captchas for you. </p>
| 0 | 2016-10-02T19:26:41Z | [
"python",
"selenium",
"browser",
"scripting"
]
|
Using Selenium for Python Scripting | 39,820,726 | <p>I have written a <code>Python</code> code to open my gmail account. Here is the code that I am using:</p>
<pre><code>from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.gmail.com')
emailElem = browser.find_element_by_id('email')
emailElem.send_keys(myemail)
emailElem = browser.find_element_by_id('password')
emailElem.send_keys(mypassword)
emailElem = browser.find_element_by_id('signInSubmit')
emailElem.submit()
</code></pre>
<p>Everything is working fine. I have also found out that there are sites that lets one <code>Log In</code> only after entering a <code>Captcha</code>, to prevent scripts from logging in. </p>
<p><strong>Is there a way in which I can use my above code get around this problem??</strong></p>
| -1 | 2016-10-02T19:20:41Z | 39,824,386 | <p>If you perform the same actions repetitively, gmail(or any other site which tries to block automation) will identify your actions as automated ones. To get around this you need to pass random sleep time in your script. Also, switching between multiple credential helps.</p>
| 0 | 2016-10-03T03:54:45Z | [
"python",
"selenium",
"browser",
"scripting"
]
|
Using Selenium for Python Scripting | 39,820,726 | <p>I have written a <code>Python</code> code to open my gmail account. Here is the code that I am using:</p>
<pre><code>from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.gmail.com')
emailElem = browser.find_element_by_id('email')
emailElem.send_keys(myemail)
emailElem = browser.find_element_by_id('password')
emailElem.send_keys(mypassword)
emailElem = browser.find_element_by_id('signInSubmit')
emailElem.submit()
</code></pre>
<p>Everything is working fine. I have also found out that there are sites that lets one <code>Log In</code> only after entering a <code>Captcha</code>, to prevent scripts from logging in. </p>
<p><strong>Is there a way in which I can use my above code get around this problem??</strong></p>
| -1 | 2016-10-02T19:20:41Z | 39,825,967 | <p>For that you must used some Captcha resolver API. Here I will provide you website which provide text code of captcha <a href="https://2captcha.com/" rel="nofollow">https://2captcha.com/</a></p>
| 0 | 2016-10-03T06:53:59Z | [
"python",
"selenium",
"browser",
"scripting"
]
|
Print the string, if string in the line ends with specific characters | 39,820,840 | <p>How do I print every string that ends on 'je' in a line</p>
<p>For example : </p>
<pre><code>for line in sys.stdin:
for string in line:
if string ends with 'je':
print string
</code></pre>
<p>And only if the string ends with '....je' , so no 'je' included. And if the string ends with '....je?' or '....je.' remove '? , . ' . Then it should print the string. Help would be appreciated.</p>
| -3 | 2016-10-02T19:32:22Z | 39,820,903 | <p>Assuming that your string name dosent allow '?,.' at all, it should work.</p>
<pre><code>for line in sys.stdin:
for string in line:
string = string.strip('.,?')
if string.endswith('je'):
print(string)
</code></pre>
| 1 | 2016-10-02T19:38:39Z | [
"python",
"string",
"file",
"character",
"line"
]
|
Print the string, if string in the line ends with specific characters | 39,820,840 | <p>How do I print every string that ends on 'je' in a line</p>
<p>For example : </p>
<pre><code>for line in sys.stdin:
for string in line:
if string ends with 'je':
print string
</code></pre>
<p>And only if the string ends with '....je' , so no 'je' included. And if the string ends with '....je?' or '....je.' remove '? , . ' . Then it should print the string. Help would be appreciated.</p>
| -3 | 2016-10-02T19:32:22Z | 39,820,971 | <p>There are two problems in your code. <code>for string in line:</code> will go through every single character, not through every word. By the way, you should not name your variable <code>string</code>. <code>for word in line.split():</code> will do what you expect.</p>
<p>Also, <code>if string ends with 'je':</code> should be <code>if word.endswith('je'):</code>. If you don't want to match the exact word "je", you can change that to <code>if word.endswith('je') and word != "je":</code>.</p>
<p>Final code, including the removal of <code>!</code> and <code>?</code>:</p>
<pre><code>f = open("a.txt", "r")
for line in f:
for word in line.split():
word = word.rstrip("!?")
if word.endswith('je') and word != "je":
print(word)
</code></pre>
<p>Note that if a word ends with several <code>?</code> or <code>!</code>, they will all get removed.</p>
| 1 | 2016-10-02T19:44:05Z | [
"python",
"string",
"file",
"character",
"line"
]
|
iPython (python 2) - ImportError: No module named model_selection | 39,820,893 | <p>iPython Notebook
Python 2</p>
<p>Complaining about this line:</p>
<pre><code>from sklearn.model_selection import train_test_split
</code></pre>
<p>Why isn't model selection working?</p>
| 0 | 2016-10-02T19:37:35Z | 39,830,815 | <p>In order to remedy this issue, you need to first find out if you are importing the actual <code>sklearn</code> package, and not just some script with the name <code>sklearn.py</code> saved somewhere in your working directory. The way Python imports modules is somewhat similar to the way it finds variables in its namespace (<code>Local</code>, <code>Enclosed</code>, <code>Global</code>, <code>Built-in</code>). In this case, Python will start importing module by first looking in the current directory and then the <code>site-packages</code>. If it looks in the current working directory and finds a python script with the same name as the module you are trying to import, then it will import that script instead of the actual module.</p>
<p>You can usually find out whether or not the actual module is imported by checking its <code>__file__</code> or <code>__path__</code> attribute:</p>
<pre><code>import sklearn
print(sklearn.__file__)
print(sklearn.__path__)
</code></pre>
<p>Reviewing the output of those print statements will tell you whether the imported package is the module you are after, or just some script lying somewhere in your working directory. If, in case, the output does not point to the <code>site-packages</code> of your Python version then you have imported some script somewhere that's not the module itself. Your quick fix would be to exit the console first, rename the <code>.py</code> script and its compiled version (the <code>.pyc</code> file) and go back to your console and try again.</p>
<p>However, if the output points to your python version's site-packages, then there is something wrong with how the package was installed in the first place. In which case, you will probably need to update or reinstall it.</p>
<p>Particular to this, it turns out that the issue is with the version of <code>sklearn</code> you are using; because the <code>model_selection</code> module in <code>sklearn</code> is available in versions <code>0.18+</code>. If you're using a version number (<code>sklearn.__version__</code>) lower than <code>0.18</code>, then you will have to use the old <code>cross_validation</code> module instead of the <code>model_selection</code> module:</p>
<pre><code>from sklearn.cross_validation import train_test_split
</code></pre>
<p>You can also just upgrade to the latest version of the package with your preferred package management system.</p>
<p>I hope this is helpful.</p>
| 0 | 2016-10-03T11:44:23Z | [
"python",
"scikit-learn",
"ipython",
"sklearn-pandas"
]
|
do action while raw_input is empty | 39,820,909 | <p>I'd like to do some actions while waiting for a user input:
I was thinking of:</p>
<pre><code>var = raw_input("what are you thinking about")
while var == None:
dosomethingwhilewaiting()
print "input is:", var
</code></pre>
<p>but raw_input is blocking until a user input come in.
Any ideas?</p>
| 0 | 2016-10-02T19:39:03Z | 39,821,033 | <p>you can use threads. </p>
<pre><code>import thread
import time
var = None
def get_input():
global var
var = raw_input("what are you thinking about")
thread.start_new_thread(get_input, ())
i = 0
while var == None:
i += 0.1
time.sleep(0.1)
print "input is:", var
print "it took you %d seconds to answer" % i
</code></pre>
| 1 | 2016-10-02T19:50:37Z | [
"python",
"input"
]
|
Fastest way to select rows where value of column of strings is in a set | 39,820,963 | <p>I have a <code>set</code> of email addresses that I've selected from one set of values. I'd like to subset a <code>pandas DataFrame</code> to include only rows where the <code>unique_id</code> column value is not contained in the set. Here's what I've done that is running very slow:</p>
<pre><code>signup_emails = set(online_signup.unique_id)
non_email_signup_event_emails = event_attendees[event_attendees.unique_id.apply(lambda x: x in signup_emails) == False].email
</code></pre>
<p>The table is several hundred thousand rows, but my computer just freezes up on this command, shows a high CPU load, and doesn't terminate even after long waits (20 minutes). How can I do this faster?</p>
| -2 | 2016-10-02T19:43:21Z | 39,821,075 | <p>Use the <code>isin</code> method.</p>
<pre><code>event_attendees[event_attendees.isin(signup_emails)]
</code></pre>
<p>For not in the signup_emails, you can do</p>
<pre><code>event_attendees[event_attendees.isin(signup_emails) == False]
</code></pre>
| 1 | 2016-10-02T19:56:08Z | [
"python",
"pandas"
]
|
Merge lists in specific order | 39,821,023 | <p>I have a list of lists and i want to merge the lists with an specific order. See example:</p>
<pre><code>id list 0 1 2
[[0], [2, 6, 1, 4], [3, 7, 5]]
Order Resulting List
[1, 0, 2] = [2, 6, 1, 4, 0, 3, 7, 5]
[0, 2, 1] = [0, 3, 7, 5, 2, 6, 1, 4]
[2, 1, 0] = [3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>Someone can suggest a more elegant algorithm that proposed below?</p>
<pre><code> groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[1, 0, 2], [0, 2, 1], [2, 1, 0]]
for order in orders:
LC = []
for i in order:
LC += groups[i]
return LC
</code></pre>
<p>Let me explain a bit better what I need:</p>
<pre><code>groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Order of each group in LC
solutions = [] # I want to put the created LC here
for order in orders:
LC = [] # I need this because a want LCs individualy and not one with all
for i in order: # for each order I pick de index (i) of the group
LC += grupos[i] # and merge then according with index of group
solutions.append([LC])
print(solutions)
</code></pre>
<p>I want this (one LC for each order):</p>
<pre><code>[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
</code></pre>
<p>and not this:</p>
<pre><code>[0, 3, 7, 5, 2, 6, 1, 4, 2, 6, 1, 4, 0, 3, 7, 5, 3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>The algorithm above works, but a need a another one more elegant and efficient.</p>
<p>Some examples of output:</p>
<pre><code>groups = [[0], [2, 1], [3, 7, 5], [4], [6]]
Order = [1, 0, 2, 3, 4]
LC = [2, 1, 0, 3, 7, 5, 4, 6]
[2, 1, 0, 3, 4]
[3, 7, 5, 2, 1, 0, 4, 6]
[3, 1, 2, 0, 4]
[4, 2, 1, 3, 7, 5, 0, 6]
[4, 1, 2, 3, 0]
[6, 2, 1, 3, 7, 5, 4, 0]
[0, 2, 1, 3, 4]
[0, 3, 7, 5, 2, 1, 4, 6]
[0, 3, 2, 1, 4]
[0, 4, 3, 7, 5, 2, 1, 6]
[0, 4, 2, 3, 1]
[0, 6, 3, 7, 5, 4, 2, 1]
[0, 1, 3, 2, 4]
[0, 2, 1, 4, 3, 7, 5, 6]
[0, 1, 4, 3, 2]
[0, 2, 1, 6, 4, 3, 7, 5]
[0, 1, 2, 4, 3]
[0, 2, 1, 3, 7, 5, 6, 4]
</code></pre>
| 0 | 2016-10-02T19:49:49Z | 39,821,052 | <p>This solution is basically identical to the one you proposed, but more Python-esque, using a list comprehension.</p>
<pre><code>>>> def merge_lists(desired_order):
... merged_list = [element for i in desired_order for element in parts[i]]
... return merged_list
...
>>> desired_order = orders[0]
>>> merge_lists(desired_order)
[2, 6, 1, 4, 0, 3, 7, 5]
</code></pre>
| 1 | 2016-10-02T19:53:32Z | [
"python",
"list",
"merge"
]
|
Merge lists in specific order | 39,821,023 | <p>I have a list of lists and i want to merge the lists with an specific order. See example:</p>
<pre><code>id list 0 1 2
[[0], [2, 6, 1, 4], [3, 7, 5]]
Order Resulting List
[1, 0, 2] = [2, 6, 1, 4, 0, 3, 7, 5]
[0, 2, 1] = [0, 3, 7, 5, 2, 6, 1, 4]
[2, 1, 0] = [3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>Someone can suggest a more elegant algorithm that proposed below?</p>
<pre><code> groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[1, 0, 2], [0, 2, 1], [2, 1, 0]]
for order in orders:
LC = []
for i in order:
LC += groups[i]
return LC
</code></pre>
<p>Let me explain a bit better what I need:</p>
<pre><code>groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Order of each group in LC
solutions = [] # I want to put the created LC here
for order in orders:
LC = [] # I need this because a want LCs individualy and not one with all
for i in order: # for each order I pick de index (i) of the group
LC += grupos[i] # and merge then according with index of group
solutions.append([LC])
print(solutions)
</code></pre>
<p>I want this (one LC for each order):</p>
<pre><code>[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
</code></pre>
<p>and not this:</p>
<pre><code>[0, 3, 7, 5, 2, 6, 1, 4, 2, 6, 1, 4, 0, 3, 7, 5, 3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>The algorithm above works, but a need a another one more elegant and efficient.</p>
<p>Some examples of output:</p>
<pre><code>groups = [[0], [2, 1], [3, 7, 5], [4], [6]]
Order = [1, 0, 2, 3, 4]
LC = [2, 1, 0, 3, 7, 5, 4, 6]
[2, 1, 0, 3, 4]
[3, 7, 5, 2, 1, 0, 4, 6]
[3, 1, 2, 0, 4]
[4, 2, 1, 3, 7, 5, 0, 6]
[4, 1, 2, 3, 0]
[6, 2, 1, 3, 7, 5, 4, 0]
[0, 2, 1, 3, 4]
[0, 3, 7, 5, 2, 1, 4, 6]
[0, 3, 2, 1, 4]
[0, 4, 3, 7, 5, 2, 1, 6]
[0, 4, 2, 3, 1]
[0, 6, 3, 7, 5, 4, 2, 1]
[0, 1, 3, 2, 4]
[0, 2, 1, 4, 3, 7, 5, 6]
[0, 1, 4, 3, 2]
[0, 2, 1, 6, 4, 3, 7, 5]
[0, 1, 2, 4, 3]
[0, 2, 1, 3, 7, 5, 6, 4]
</code></pre>
| 0 | 2016-10-02T19:49:49Z | 39,821,066 | <p>You could use some other technique like a comprehension. The following will return a flat list:</p>
<pre><code>return [part for order in orders for i in order for part in parts[i]]
</code></pre>
<p>And the following will return a 2D list:</p>
<pre><code>return [[part for i in order for part in parts[i]] for order in orders]
</code></pre>
| 2 | 2016-10-02T19:55:24Z | [
"python",
"list",
"merge"
]
|
Merge lists in specific order | 39,821,023 | <p>I have a list of lists and i want to merge the lists with an specific order. See example:</p>
<pre><code>id list 0 1 2
[[0], [2, 6, 1, 4], [3, 7, 5]]
Order Resulting List
[1, 0, 2] = [2, 6, 1, 4, 0, 3, 7, 5]
[0, 2, 1] = [0, 3, 7, 5, 2, 6, 1, 4]
[2, 1, 0] = [3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>Someone can suggest a more elegant algorithm that proposed below?</p>
<pre><code> groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[1, 0, 2], [0, 2, 1], [2, 1, 0]]
for order in orders:
LC = []
for i in order:
LC += groups[i]
return LC
</code></pre>
<p>Let me explain a bit better what I need:</p>
<pre><code>groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Order of each group in LC
solutions = [] # I want to put the created LC here
for order in orders:
LC = [] # I need this because a want LCs individualy and not one with all
for i in order: # for each order I pick de index (i) of the group
LC += grupos[i] # and merge then according with index of group
solutions.append([LC])
print(solutions)
</code></pre>
<p>I want this (one LC for each order):</p>
<pre><code>[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
</code></pre>
<p>and not this:</p>
<pre><code>[0, 3, 7, 5, 2, 6, 1, 4, 2, 6, 1, 4, 0, 3, 7, 5, 3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>The algorithm above works, but a need a another one more elegant and efficient.</p>
<p>Some examples of output:</p>
<pre><code>groups = [[0], [2, 1], [3, 7, 5], [4], [6]]
Order = [1, 0, 2, 3, 4]
LC = [2, 1, 0, 3, 7, 5, 4, 6]
[2, 1, 0, 3, 4]
[3, 7, 5, 2, 1, 0, 4, 6]
[3, 1, 2, 0, 4]
[4, 2, 1, 3, 7, 5, 0, 6]
[4, 1, 2, 3, 0]
[6, 2, 1, 3, 7, 5, 4, 0]
[0, 2, 1, 3, 4]
[0, 3, 7, 5, 2, 1, 4, 6]
[0, 3, 2, 1, 4]
[0, 4, 3, 7, 5, 2, 1, 6]
[0, 4, 2, 3, 1]
[0, 6, 3, 7, 5, 4, 2, 1]
[0, 1, 3, 2, 4]
[0, 2, 1, 4, 3, 7, 5, 6]
[0, 1, 4, 3, 2]
[0, 2, 1, 6, 4, 3, 7, 5]
[0, 1, 2, 4, 3]
[0, 2, 1, 3, 7, 5, 6, 4]
</code></pre>
| 0 | 2016-10-02T19:49:49Z | 39,821,172 | <p>Just call itertools.chain on the indexes and combine with with <em>operator.itemgetter</em>:</p>
<pre><code> frIn [9]: groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
In [10]: orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Ord
In [11]: from itertools import chain
In [12]: from operator import itemgetter
In [13]: [list(chain(*itemgetter(*o)(groups))) for o in orders]
[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
</code></pre>
<p>In you own code, you only return the last LC so it could not work correctly:</p>
<pre><code>for order in orders:
LC = [] # overwritten each iteration so you only get the last sublists.
for i in order:
LC += parts[i]
return LC
</code></pre>
| 1 | 2016-10-02T20:07:22Z | [
"python",
"list",
"merge"
]
|
Merge lists in specific order | 39,821,023 | <p>I have a list of lists and i want to merge the lists with an specific order. See example:</p>
<pre><code>id list 0 1 2
[[0], [2, 6, 1, 4], [3, 7, 5]]
Order Resulting List
[1, 0, 2] = [2, 6, 1, 4, 0, 3, 7, 5]
[0, 2, 1] = [0, 3, 7, 5, 2, 6, 1, 4]
[2, 1, 0] = [3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>Someone can suggest a more elegant algorithm that proposed below?</p>
<pre><code> groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[1, 0, 2], [0, 2, 1], [2, 1, 0]]
for order in orders:
LC = []
for i in order:
LC += groups[i]
return LC
</code></pre>
<p>Let me explain a bit better what I need:</p>
<pre><code>groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Order of each group in LC
solutions = [] # I want to put the created LC here
for order in orders:
LC = [] # I need this because a want LCs individualy and not one with all
for i in order: # for each order I pick de index (i) of the group
LC += grupos[i] # and merge then according with index of group
solutions.append([LC])
print(solutions)
</code></pre>
<p>I want this (one LC for each order):</p>
<pre><code>[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
</code></pre>
<p>and not this:</p>
<pre><code>[0, 3, 7, 5, 2, 6, 1, 4, 2, 6, 1, 4, 0, 3, 7, 5, 3, 7, 5, 2, 6, 1, 4, 0]
</code></pre>
<p>The algorithm above works, but a need a another one more elegant and efficient.</p>
<p>Some examples of output:</p>
<pre><code>groups = [[0], [2, 1], [3, 7, 5], [4], [6]]
Order = [1, 0, 2, 3, 4]
LC = [2, 1, 0, 3, 7, 5, 4, 6]
[2, 1, 0, 3, 4]
[3, 7, 5, 2, 1, 0, 4, 6]
[3, 1, 2, 0, 4]
[4, 2, 1, 3, 7, 5, 0, 6]
[4, 1, 2, 3, 0]
[6, 2, 1, 3, 7, 5, 4, 0]
[0, 2, 1, 3, 4]
[0, 3, 7, 5, 2, 1, 4, 6]
[0, 3, 2, 1, 4]
[0, 4, 3, 7, 5, 2, 1, 6]
[0, 4, 2, 3, 1]
[0, 6, 3, 7, 5, 4, 2, 1]
[0, 1, 3, 2, 4]
[0, 2, 1, 4, 3, 7, 5, 6]
[0, 1, 4, 3, 2]
[0, 2, 1, 6, 4, 3, 7, 5]
[0, 1, 2, 4, 3]
[0, 2, 1, 3, 7, 5, 6, 4]
</code></pre>
| 0 | 2016-10-02T19:49:49Z | 39,821,173 | <pre><code>inputs = [[1,2,3], [4,5,6], [7]]
orders = [[0,1,2], [2,1,0]]
result = [input_element for order in orders for order_element in order for input_element in inputs[order_element]]
print(result)
</code></pre>
| 0 | 2016-10-02T20:07:27Z | [
"python",
"list",
"merge"
]
|
Limits of hashes comparisons | 39,821,040 | <p>I'm storing hash codes in a file, one hash per line.</p>
<p>When I have a new hash code, I open the file and check if
the hash code already exists and if it doesn't exist,
I save it to that file.</p>
<pre><code>f = open("hashes.txt", "w")
hashes = f.readlines()
hash_code = "ff071fdf1e060400"
if not hash_code in hashes:
hashes.append(hash_code)
for h in hashes:
f.write(h)
f.close()
</code></pre>
<p>This code may be slow, when the number of lines in hashes.txt grows.
Is there some better storage mechanism and check to make it faster
in that case? I need fastest possible check (within a few seconds).</p>
| -1 | 2016-10-02T19:51:27Z | 39,821,152 | <p>I would agree with Bert on this. If you expect that there will be a lot of hashes it would be better to use a database. If this only happens locally a sqlite database is fine. There is an excellent orm library that works for sqlite; <a href="http://docs.peewee-orm.com/en/latest/" rel="nofollow">Peewee</a>. It got some excellent documentation that will get you started. </p>
| 1 | 2016-10-02T20:05:19Z | [
"python",
"hash"
]
|
Limits of hashes comparisons | 39,821,040 | <p>I'm storing hash codes in a file, one hash per line.</p>
<p>When I have a new hash code, I open the file and check if
the hash code already exists and if it doesn't exist,
I save it to that file.</p>
<pre><code>f = open("hashes.txt", "w")
hashes = f.readlines()
hash_code = "ff071fdf1e060400"
if not hash_code in hashes:
hashes.append(hash_code)
for h in hashes:
f.write(h)
f.close()
</code></pre>
<p>This code may be slow, when the number of lines in hashes.txt grows.
Is there some better storage mechanism and check to make it faster
in that case? I need fastest possible check (within a few seconds).</p>
| -1 | 2016-10-02T19:51:27Z | 39,821,156 | <p>A <a href="https://docs.python.org/3.6/library/stdtypes.html#set" rel="nofollow">set</a> can be used for fast membership lookups. Since files can be used as an iterator, passing an open file handle to the set constructor will read entries into the set by line without first filling an intermediate in-memory array.</p>
<p>After this, you can simply use the set difference <code>-</code> operator to efficiently check which hashes are new and the union operator <code>|</code> to add the newly found elements to the list of known hashes:</p>
<pre><code># at program start, init list of known hashes
# open hashes_in.txt, read line by line and add to set
# set removes duplicate elements
with open("hashes.txt", "r") as f:
hashes = set(f)
# as new hashes are encountered, use this to check if they have been seen before
def compare_hashes(search_hashes, hashes):
search_hashes = set(search_hashes)
# find new hashes
new_hashes = search_hashes - hashes
# update list of known hashes
hashes |= new_hashes
# write out new hashes
with open("hashes.txt", "a") as f:
for h in new_hashes:
f.write(h)
return new_hashes, hashes
with open("hashes2.txt", "r") as f:
new_hashes, hashes = compare_hashes(f, hashes)
print(new_hashes)
</code></pre>
<p>This answer assumes that both your list of known entries and search entries will come from files and thus have trailing newlines that will be part of the matching. If this is not what you want, you can strip newlines for a small performance overhead:</p>
<pre><code>strip_newlines = lambda hashes: (h.strip() for h in hashes)
</code></pre>
<p>Use it like so:</p>
<pre><code>hashes = set(strip_newlines(f))
new_hashes, hashes = compare_hashes(strip_newlines(f), hashes)
</code></pre>
| 1 | 2016-10-02T20:05:43Z | [
"python",
"hash"
]
|
Limits of hashes comparisons | 39,821,040 | <p>I'm storing hash codes in a file, one hash per line.</p>
<p>When I have a new hash code, I open the file and check if
the hash code already exists and if it doesn't exist,
I save it to that file.</p>
<pre><code>f = open("hashes.txt", "w")
hashes = f.readlines()
hash_code = "ff071fdf1e060400"
if not hash_code in hashes:
hashes.append(hash_code)
for h in hashes:
f.write(h)
f.close()
</code></pre>
<p>This code may be slow, when the number of lines in hashes.txt grows.
Is there some better storage mechanism and check to make it faster
in that case? I need fastest possible check (within a few seconds).</p>
| -1 | 2016-10-02T19:51:27Z | 39,821,643 | <p>I would do this:</p>
<pre><code>class Hashes(object):
def __init__(self, filename):
self.filename = filename
with open(filename, 'rt') as f: # read the file only once
self.hashes = set(line.strip() for line in f)
def add_hash(self, hash):
if hash not in self.hashes: # this is very fast with sets
self.hashes.add(hash)
with open(self.filename, 'at') as f:
print(hash, file=f) # write only one hash
hashes = Hashes("hashes.txt")
hashes.add_hash("ff071fdf1e060400")
</code></pre>
<p>Because:</p>
<ul>
<li>the file is read only once</li>
<li>checking whether a hash exists is very fast with sets (no need to read all of them)</li>
<li>hashes are added by writing only the new hash</li>
<li>the class simplifies creation of mutiple hash files and cleanup of cached hashes, and it simplifies maintenance by organising the code</li>
</ul>
<p>The downside is that all hashes are kept in memory. If there are many millions of hashes, that could start causing problems, but until then it is fine. It is better than fine, if speed is important.</p>
| 2 | 2016-10-02T20:57:37Z | [
"python",
"hash"
]
|
What's the difference between Celery task and subtask? | 39,821,099 | <p>If I understood the tutorial correctly, Celery <em>subtask</em> supports almost the same API as <em>task</em>, but has the additional advantage that it can be passed around to other functions or processes.</p>
<p>Clearly, if that was the case, Celery would have simply replaced <em>tasks</em> with <em>subtasks</em> instead of keeping both (e.g., the <code>@app.task</code> decorator would have converted a function to a <em>subtask</em> instead of to a <em>task</em>, etc.). So I must be misunderstanding something.</p>
<p>What can a <em>task</em> do that a <em>subtask</em> can't?</p>
<p>Celery API changed quite a bit; my question is specific to version 3.1 (currently, the latest).</p>
<p>Edit:</p>
<p>I know the docs say <em>subtasks</em> are intended to be called from other <em>tasks</em>. My question is what prevents Celery from getting rid of tasks completely and using subtasks everywhere? They seem to be strictly more flexible/powerful than tasks:</p>
<pre><code># tasks.py
from celery import Celery
app = Celery(backend='rpc://')
@app.task
def add(x, y):
# just print out a log line for testing purposes
print(x, y)
# client.py
from tasks import add
add_subtask = add.subtask()
# in this context, it seems the following two lines do the same thing
add.delay(2, 2)
add_subtask.delay(2, 2)
# when we need to pass argument to other tasks, we must use add_subtask
# so it seems add_subtask is strictly better than add
</code></pre>
| 1 | 2016-10-02T19:59:50Z | 39,832,523 | <p>You will take the difference into account when you start using <a href="http://docs.celeryproject.org/en/latest/userguide/canvas.html" rel="nofollow">complex workflows</a> with celery.</p>
<blockquote>
<p>A signature() wraps the arguments, keyword arguments, and execution
options of a single task invocation in a way such that it can be
passed to functions or even serialized and sent across the wire.</p>
<p>Signatures are often nicknamed âsubtasksâ because they describe a task
to be called within a task.</p>
</blockquote>
<p>Also:</p>
<blockquote>
<p>subtaskâs are objects used to pass around the signature of a task
invocation, (for example to send it over the network)</p>
</blockquote>
<p><code>Task</code> is just a function definition wrapped with decorator, but <code>subtask</code> is a task with parameters passed, but not yet started. You may transfer the subtask serialized over network or, more used, call it within a group/chain/chord.</p>
| 1 | 2016-10-03T13:11:56Z | [
"python",
"celery"
]
|
reading *.lz4 file in python | 39,821,116 | <p>I have a huge number of tweet data that are compressed in lz4 formats. I'd like to open each file and decompress it, and extract some information from python. </p>
<p>When I decompress the file using <code>lz4c -d</code> command in Ubuntu, the file decompresses just fine. But when I use <code>lz4.loads('path_to_file')</code> in python, it complains that <code>ValueError: corrupt input at byte 6</code>. The same error message happens when I try to read() the file in bytes mode. What do I do? </p>
| 0 | 2016-10-02T20:00:57Z | 39,821,165 | <p><code>lz4.loads()</code> decompresses the string you pass to it and not the file path in that string. It doesn't seem like this library supports opening files, so you have to read the data yourself.</p>
<pre><code>lz4.loads(open('path_to_file', 'rb').read())
</code></pre>
| 0 | 2016-10-02T20:06:49Z | [
"python",
"lz4"
]
|
reading *.lz4 file in python | 39,821,116 | <p>I have a huge number of tweet data that are compressed in lz4 formats. I'd like to open each file and decompress it, and extract some information from python. </p>
<p>When I decompress the file using <code>lz4c -d</code> command in Ubuntu, the file decompresses just fine. But when I use <code>lz4.loads('path_to_file')</code> in python, it complains that <code>ValueError: corrupt input at byte 6</code>. The same error message happens when I try to read() the file in bytes mode. What do I do? </p>
| 0 | 2016-10-02T20:00:57Z | 39,821,362 | <p>Try with the lz4tools package instead: <a href="https://pypi.python.org/pypi/lz4tools" rel="nofollow">https://pypi.python.org/pypi/lz4tools</a></p>
<p>My test fails with <code>lz4</code></p>
<pre><code>>>> lz4.loads(open("test.js.lz4","rb").read())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: corrupt input at byte 10
</code></pre>
<p>But works with <code>lz4tools</code></p>
<pre><code>>>> lz4tools.open("test.js.lz4").read()
'[{\n "cc_emails": [],\n "fwd_emails": [],\n "reply_cc_emails": [],\n "fr_escalated": false,\n "spam": false,\n "emai.....
</code></pre>
| 0 | 2016-10-02T20:26:32Z | [
"python",
"lz4"
]
|
How to reverse the elements in a sublist? | 39,821,166 | <p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>
<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>
<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
print(i)
</code></pre>
<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>
<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>
<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>
| 4 | 2016-10-02T20:06:54Z | 39,821,179 | <pre><code>[sublist[::-1] for sublist in to_reverse[::-1]]
</code></pre>
<p>List comprehension works here. <code>[::-1]</code> is basically the same as <code>reversed</code>, but does not modify the list.</p>
<p>EDIT:</p>
<p>As pointed out below, <code>reversed</code> doesn't modify the list. It returns a <code>listreverseiterator</code> object </p>
<p>More Edit:</p>
<p>If you want a solution for lists of arbitrary depth, try:</p>
<pre><code>def deep_reverse(to_reverse):
if isinstance(to_reverse, list):
return list(map(deep_reverse, to_reverse[::-1]))
else:
return to_reverse
</code></pre>
<p>Even more Edit:</p>
<p>To mutate a list in a function:</p>
<pre><code>L[:] = new_list
</code></pre>
<p>Will modify the list in place.</p>
| 4 | 2016-10-02T20:08:48Z | [
"python",
"list",
"python-3.x",
"reverse",
"sublist"
]
|
How to reverse the elements in a sublist? | 39,821,166 | <p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>
<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>
<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
print(i)
</code></pre>
<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>
<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>
<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>
| 4 | 2016-10-02T20:06:54Z | 39,821,238 | <p>This looks very familiar :). I'm not going to give the whole working solution but here are some tips:</p>
<p>As you know, there are two steps, reverse each sub-list and then reverse the outer list (in place, without making a new list, so it will mutate the global <code>L</code>).</p>
<p>So you can loop through the outer list, and mutate each sub-list:</p>
<pre><code>for i in range(len(L)):
# if L[i] is a list:
# reverse with [::-1] and update L[i] to the reversed version
# reverse the outer list L, list.reverse() will operate in-place on L
</code></pre>
<p>Now remember, if you loop through the list like this:</p>
<pre><code>for item in list:
item = 'xxx'
</code></pre>
<p>You can't change <code>item</code> with the above code. <a class='doc-link' href="http://stackoverflow.com/documentation/python/3553/common-pitfalls/949/changing-the-sequence-you-are-iterating-over#t=201610022012362266711"><code>item</code> is a placeholder value, so changing it doesn't actually modify the list</a>. </p>
<p>You instead need to index the item in <code>L</code>, and enumerate can help with this, or you can use the less-preffered <code>range(len())</code> as above.</p>
<pre><code>for i, item in enumerate(L):
# do something with L[i]
L[i] = 'something'
</code></pre>
<p><strong>Edit: since there is so much confusion over this, I'll go ahead and post a working solution based on Stefan Pochmann's very elegant answer:</strong></p>
<pre><code>def deep_reverse(L):
L.reverse()
for sublist in L:
sublist.reverse()
</code></pre>
<p>Notice there is <strong>no return statement, and no print statement</strong>. This will correctly modify <code>L</code> in place. You <strong>cannot</strong> reassign <code>L</code> inside the function because then it will just create a new local version of <code>L</code>, and it will not modify the global <code>L</code>. You can use <code>list.reverse()</code> to modify <code>L</code> <strong>in place</strong> which is necessary based on the specifications. </p>
| 0 | 2016-10-02T20:14:27Z | [
"python",
"list",
"python-3.x",
"reverse",
"sublist"
]
|
How to reverse the elements in a sublist? | 39,821,166 | <p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>
<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>
<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
print(i)
</code></pre>
<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>
<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>
<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>
| 4 | 2016-10-02T20:06:54Z | 39,821,239 | <p>You could make this recursive, so it will work for arbitrarily deep nests.</p>
<p>something like (UNTESTED):</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
if len(i) > 1:
deep_reverse(i)
else:
print(i)
</code></pre>
| -1 | 2016-10-02T20:14:31Z | [
"python",
"list",
"python-3.x",
"reverse",
"sublist"
]
|
How to reverse the elements in a sublist? | 39,821,166 | <p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>
<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>
<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
print(i)
</code></pre>
<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>
<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>
<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>
| 4 | 2016-10-02T20:06:54Z | 39,821,379 | <p>This should do the trick.</p>
<pre><code>L = [[1, 2], [3, 4], [5, 6, 7]]
def deep_reverse(L):
for i in range(len(L)):
L[i]=L[i][::-1]
L=L[::-1]
return L
</code></pre>
| 1 | 2016-10-02T20:28:50Z | [
"python",
"list",
"python-3.x",
"reverse",
"sublist"
]
|
How to reverse the elements in a sublist? | 39,821,166 | <p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>
<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>
<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
print(i)
</code></pre>
<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>
<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>
<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>
| 4 | 2016-10-02T20:06:54Z | 39,821,514 | <p>Alternatively you use <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map()</code></a> to achieve this as:</p>
<pre><code>>>> map(lambda x: x[::-1], L[::-1]) # In Python 2.x
[[7, 6, 5], [4, 3], [2, 1]]
>>> list(map(lambda x: x[::-1], L[::-1])) # In Python 3.x
[[7, 6, 5], [4, 3], [2, 1]]
</code></pre>
<p>Check Blog on <a href="http://www.python-course.eu/lambda.php" rel="nofollow">Lambda, filter, reduce and map</a> to know how <code>lambda</code> functions and <code>map()</code> works in Python.</p>
| 0 | 2016-10-02T20:42:43Z | [
"python",
"list",
"python-3.x",
"reverse",
"sublist"
]
|
How to reverse the elements in a sublist? | 39,821,166 | <p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>
<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>
<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>
<pre><code>def deep_reverse(L)
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for i in reversed(L):
print(i)
</code></pre>
<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>
<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>
<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>
| 4 | 2016-10-02T20:06:54Z | 39,821,639 | <blockquote>
<p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist.</p>
</blockquote>
<p>Then do exactly those two things:</p>
<pre><code>L.reverse()
for sublist in L:
sublist.reverse()
</code></pre>
<hr>
<p>Full demo because you seem to be confused about what your function is supposed to do and how to test it:</p>
<pre><code>>>> def deep_reverse(L):
"""
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
L.reverse()
for sublist in L:
sublist.reverse()
>>> L = [[1, 2], [3, 4], [5, 6, 7]]
>>> deep_reverse(L)
>>> print(L)
[[7, 6, 5], [4, 3], [2, 1]]
</code></pre>
| 2 | 2016-10-02T20:57:03Z | [
"python",
"list",
"python-3.x",
"reverse",
"sublist"
]
|
Python PyQt on mac OSX Sierra | 39,821,177 | <p>Does anyone know if I can get to work PyQt 4 or 5 on a mac with the new OSX Sierra? It seems that I have to wait for a new version of PyQt but I am not sure if that is actually true.
Thanks</p>
| 0 | 2016-10-02T20:08:22Z | 39,974,832 | <p>The easiest way to install PyQt (4 or 5) on OSX is probably using <a href="http://homebrew.sh" rel="nofollow">Homebrew</a>. This will also install a separate standalone Python from the system Python, meaning it will continue to work without problems following any future system updates. </p>
<p>According to this <a href="https://github.com/Homebrew/homebrew-core/issues/1957#issuecomment-225806023" rel="nofollow">thread</a> PyQt4 is no longer supported on macOS Sierra, but PyQt5 will still work.</p>
<p>Once you've installed Homebrew, you can install PyQt5 with the following:</p>
<pre><code>brew install pyqt5 # for PyQt5
</code></pre>
<p><a href="https://i.stack.imgur.com/HVYSZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/HVYSZ.png" alt="enter image description here"></a></p>
| 0 | 2016-10-11T10:02:47Z | [
"python",
"osx",
"pyqt"
]
|
How to parse Omnifocus XML data for details about a particular task? | 39,821,208 | <p>Considering that Omnifocus does not have an API, I've created a script that pulls Omnifocus Data which is in XML format on a recurring basis</p>
<p><a href="https://gist.githubusercontent.com/ChrismCruz/3612fdbe9f7baeef0c668113ca15fd17/raw/e6c8ca70bedc23456f499bca8dcc499a787f4018/gistfile1.txt" rel="nofollow">See linked here for the full omnifocus data set</a></p>
<p>I'm trying my best to parse this data set so that I can get these attributes for a task that is called "This is a test task"</p>
<p>I want to pull the following attributes from this task from that xml data</p>
<ul>
<li>Task Name: "This is a test task"</li>
<li>Completed Date: "10/02/2016"</li>
<li>Added Date: "10/02/2016"</li>
<li>Project: "Test Project"</li>
<li>Due Date: "10/11/2016"</li>
<li>Duration: 10 minutes</li>
</ul>
<p>See below for my python script: </p>
<pre><code>from bs4 import BeautifulSoup
text_data = BeautifulSoup(xml_data_set)
list_of_tags = s.find_all(tag.has_attr('id'))
#This creates an array of strings. The string that I'm interested looks like the following:
#>> e.g. <task id="lyZY7EINc02" op="update"><added>2016-10-02T19:53:09.672Z</added><modified>2016-10-02T19:53:13.912Z</modified><name>This is a test task</name></task>
list_of_dicts = [loads(dumps(xmltodict.parse(str(i)))) for i in l]
#I then use xmltodict to change each tag into an a dictionary. The tag that I'm interested looks like the following:
#>> e.g. {'task_@id': 'lyZY7EINc02', 'task_modified': '2016-10-02T19:53:13.912Z', 'task_added': '2016-10-02T19:53:09.672Z', 'task_name': 'This is a test task', 'task_@op': 'update'}
</code></pre>
<p>Although, I can get the task_added date and the task_name, I can't get the other attributes I'm hoping to get. </p>
| 0 | 2016-10-02T20:10:31Z | 39,831,552 | <p>You just need to use the <em>name</em> text to find the node then just call <em>.parent</em> to get the <em>task</em> node.</p>
<pre><code>In [55]: task
Out[55]: <task id="lyZY7EINc02" op="update"><added>2016-10-02T19:53:09.672Z</added><modified>2016-10-02T19:53:13.912Z</modified><name>This is a test task</name></task>
</code></pre>
| 0 | 2016-10-03T12:22:39Z | [
"python",
"xml",
"parsing",
"beautifulsoup",
"omnifocus"
]
|
Convert number values into ascii characters? | 39,821,249 | <p>The part where I need to go from the number values I obtained to characters to spell out a word it not working, it says I need to use an integer for the last part?</p>
<p>accept string</p>
<pre><code>print "This program reduces and decodes a coded message and determines if it is a palindrome"
string=(str(raw_input("The code is:")))
</code></pre>
<p>change it to lower case </p>
<pre><code>string_lowercase=string.lower()
print "lower case string is:", string_lowercase
</code></pre>
<p>strip special characters</p>
<pre><code>specialcharacters="1234567890~`!@#$%^&*()_-+={[}]|\:;'<,>.?/"
for char in specialcharacters:
string_lowercase=string_lowercase.replace(char,"")
print "With the specials stripped out the string is:", string_lowercase
</code></pre>
<p>input offset</p>
<pre><code>offset=(int(raw_input("enter offset:")))
</code></pre>
<p>conversion of text to ASCII code</p>
<pre><code>result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
</code></pre>
<p>conversion from ASCII code to text</p>
<pre><code>text=''.join(chr(i) for i in result)
print "The decoded string is:", text.format(chr(result))
</code></pre>
| 0 | 2016-10-02T20:16:02Z | 39,821,326 | <p>It looks like you have a list of lists instead of a list of ints when you call <code>result.append([code-offset])</code>. This means later when you call <code>chr(i) for i in result</code>, you are passing a list instead of an int to <code>chr()</code>.</p>
<p>Try changing this to <code>result.append(code-offset)</code>.</p>
<p>Other small suggestions:</p>
<ul>
<li><a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>raw_input</code></a> already gives you a string, so there's no need to explicitly cast it.</li>
<li><p>Your removal of special characters can be more efficiently written as:</p>
<pre><code>special_characters = '1234567890~`!@#$%^&*()_-+={[}]|\:;'<,>.?/'
string_lowercase = ''.join(c for c in string_lowercase if string not in special_characters)
</code></pre>
<p>This allows you to only have to iterate through <code>string_lowercase</code> once instead of per character in <code>special_characters</code>.</p></li>
</ul>
| 0 | 2016-10-02T20:23:08Z | [
"python",
"ascii",
"chr"
]
|
Convert number values into ascii characters? | 39,821,249 | <p>The part where I need to go from the number values I obtained to characters to spell out a word it not working, it says I need to use an integer for the last part?</p>
<p>accept string</p>
<pre><code>print "This program reduces and decodes a coded message and determines if it is a palindrome"
string=(str(raw_input("The code is:")))
</code></pre>
<p>change it to lower case </p>
<pre><code>string_lowercase=string.lower()
print "lower case string is:", string_lowercase
</code></pre>
<p>strip special characters</p>
<pre><code>specialcharacters="1234567890~`!@#$%^&*()_-+={[}]|\:;'<,>.?/"
for char in specialcharacters:
string_lowercase=string_lowercase.replace(char,"")
print "With the specials stripped out the string is:", string_lowercase
</code></pre>
<p>input offset</p>
<pre><code>offset=(int(raw_input("enter offset:")))
</code></pre>
<p>conversion of text to ASCII code</p>
<pre><code>result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
</code></pre>
<p>conversion from ASCII code to text</p>
<pre><code>text=''.join(chr(i) for i in result)
print "The decoded string is:", text.format(chr(result))
</code></pre>
| 0 | 2016-10-02T20:16:02Z | 39,821,356 | <p>You are passing a list to <code>chr</code> when it only accepts integers. Try <code>result.append(code-offset)</code>. <code>[code-offset]</code> is a one-item list.</p>
<p>Specifically, instead of:</p>
<pre><code>result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
</code></pre>
<p>use:</p>
<pre><code>result=[]
for i in string_lowercase:
code=ord(i)
result.append(code-offset)
</code></pre>
<p>If you understand list comprehension, this works too: <code>result = [ord(i)-offset for i in string_lowercase]</code></p>
| 0 | 2016-10-02T20:25:48Z | [
"python",
"ascii",
"chr"
]
|
Convert number values into ascii characters? | 39,821,249 | <p>The part where I need to go from the number values I obtained to characters to spell out a word it not working, it says I need to use an integer for the last part?</p>
<p>accept string</p>
<pre><code>print "This program reduces and decodes a coded message and determines if it is a palindrome"
string=(str(raw_input("The code is:")))
</code></pre>
<p>change it to lower case </p>
<pre><code>string_lowercase=string.lower()
print "lower case string is:", string_lowercase
</code></pre>
<p>strip special characters</p>
<pre><code>specialcharacters="1234567890~`!@#$%^&*()_-+={[}]|\:;'<,>.?/"
for char in specialcharacters:
string_lowercase=string_lowercase.replace(char,"")
print "With the specials stripped out the string is:", string_lowercase
</code></pre>
<p>input offset</p>
<pre><code>offset=(int(raw_input("enter offset:")))
</code></pre>
<p>conversion of text to ASCII code</p>
<pre><code>result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
</code></pre>
<p>conversion from ASCII code to text</p>
<pre><code>text=''.join(chr(i) for i in result)
print "The decoded string is:", text.format(chr(result))
</code></pre>
| 0 | 2016-10-02T20:16:02Z | 39,821,406 | <p>While doing <code>.append()</code> to list, use <code>code-offset</code> instead of <code>[code-offset]</code>. As in later you are storing the value as a list (of one ASCII) instead of storing the ASCII value directly.</p>
<p>Hence your code should be:</p>
<pre><code>result = []
for i in string_lowercase:
code = ord(i)
result.append(code-offset)
</code></pre>
<p>However you may simplified this code as:</p>
<pre><code>result = [ord(ch)-offset for ch in string_lowercase]
</code></pre>
<p>You may even further simplify your code. The one line to get decoded string will be:</p>
<pre><code>decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase)
</code></pre>
<p><strong>Example</strong> with offset as 2:</p>
<pre><code>>>> string_lowercase = 'abcdefghijklmnopqrstuvwxyz'
>>> offset = 2
>>> decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase)
>>> decoded_string
'_`abcdefghijklmnopqrstuvwx'
</code></pre>
| 0 | 2016-10-02T20:31:32Z | [
"python",
"ascii",
"chr"
]
|
Why numpy performs worst on a more powerful computer? | 39,821,339 | <p>I have 2 computers:</p>
<ol>
<li>A 2012 Dell Latitude, with a Intel i5 processor, 4 gb of Ram.</li>
<li>A 2016 MacBook Pro, with a (last generation) Intel i5 processor 8 gb of ram.</li>
</ol>
<p>Then, I also have Python program that does extensive use of numpy's libraries, that is able to run on both the computers. This program works with very big float tensors (say with shape <code>500 X 500 X 500</code>)</p>
<p>I am concerned by the following fact: the execution of this code is significantly faster on the 2012 Dell then on 2016 mac, even if I was expecting the opposite behavior, being the newer PC most powerful, under all points of view.</p>
<p>Which might be the case of this behavior?
Might be important the fact that I used a precompiled numpy installation for the Dell, while I simply used </p>
<pre><code>pip install numpy
</code></pre>
<p>for the mac?</p>
<p><strong>Edit:</strong></p>
<p>This might be due to the different Blas/Lapack libraries installed on the two computers. If I run on the mac I run <code>np.show_config()</code>
I obtain</p>
<pre><code>lapack_opt_info:
extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
extra_compile_args = ['-msse3']
define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]
openblas_lapack_info:
NOT AVAILABLE
atlas_3_10_blas_threads_info:
NOT AVAILABLE
atlas_threads_info:
NOT AVAILABLE
atlas_3_10_threads_info:
NOT AVAILABLE
atlas_blas_info:
NOT AVAILABLE
atlas_3_10_blas_info:
NOT AVAILABLE
atlas_blas_threads_info:
NOT AVAILABLE
openblas_info:
NOT AVAILABLE
blas_mkl_info:
NOT AVAILABLE
blas_opt_info:
extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
extra_compile_args = ['-msse3', '-I/System/Library/Frameworks/vecLib.framework/Headers']
define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]
atlas_info:
NOT AVAILABLE
atlas_3_10_info:
NOT AVAILABLE
lapack_mkl_info:
NOT AVAILABLE
</code></pre>
<p>but I have no idea of how to interprete this..</p>
| -4 | 2016-10-02T20:24:29Z | 39,828,735 | <p>Valid question imo. If I had to guess, from most likely to less likely:</p>
<ol>
<li><p>The numpy on the 2012 system uses faster BLAS/LAPACK libraries. You can check which are used by running <code>numpy.show_config()</code> on both systems.</p></li>
<li><p>The processor in the 2012 system may actually be faster than the one in the 2016 system. Your macbook has a i5-5287U most likely, with 2.7 ghz base clock and 3.1 ghz boost. In 2012 there exsisted already i5 laptop procssors with 2.9 ghz base clock and 3.6 ghz boost.</p></li>
<li><p>The 2016 system may be running slower than usual, for any number of reasons. Maybe it's overheating or has bloatware or something.</p></li>
</ol>
| 3 | 2016-10-03T09:45:33Z | [
"python",
"numpy"
]
|
python passlib verify doesn't match | 39,821,369 | <p>I am working with Flask and MongoDB, trying to implement username / password verification with passlib.</p>
<p>The class from models.py : </p>
<pre><code>from passlib.hash import sha256_crypt
class Users(object):
def __init__(self, username='', password='', collection=db.users, articles=''):
self.collection = collection
self.username = username
self.password = password
self.articles = []
def addUser(self):
self.collection.insert({'username': self.username, 'password': sha256_crypt.encrypt('self.password'), 'articles': self.articles})
</code></pre>
<p>From the python shell, I create the user alice with the password 'secret' :</p>
<pre><code>>>> import models
>>> alice = models.Users()
>>> alice.username = 'alice'
>>> alice.password = 'secret'
>>> alice.addUser()
</code></pre>
<p>From the mongo shell, I check that the document has been well created with a hash instead of the clear password :</p>
<pre><code>> db.users.find()
{ "_id" : ObjectId("57f15d9f815a0b6c1533427f"), "username" : "alice", "articles" : [ ], "password" : "$5$rounds=535000$Oq1hy1INzO59nu0q$FzMz1DtBWDwM.sw0AhrlVA8esgE30n8rr/NjOltB8.7" }
</code></pre>
<p>From now on, we should be able to verify the password from the python shell using the hash stored in the document, isn't it ?</p>
<pre><code>>>> sha256_crypt.verify('secret','$5$rounds=535000$Oq1hy1INzO59nu0q$FzMz1DtBWDwM.sw0AhrlVA8esgE30n8rr/NjOltB8.7')
False
</code></pre>
<p>But it doesn't, someone can explain to me why ?</p>
| 0 | 2016-10-02T20:27:26Z | 39,821,478 | <p>That is happening because you're encrypting not <code>self.password</code> but <code>'self.password'</code></p>
<p>So you need to change your <code>addUser</code> method to the following:</p>
<pre><code>def addUser(self):
self.collection.insert({'username': self.username, 'password': sha256_crypt.encrypt(self.password), 'articles': self.articles})
</code></pre>
| 0 | 2016-10-02T20:38:56Z | [
"python",
"mongodb",
"passlib"
]
|
Numpy not found in Python3 | 39,821,470 | <p>I am trying to run numpy in Python 3, using the WinPy distribution. I put #!python3 at the top of the script, because I was told that is something that Winpy has that allows you to make it run in a certain version. If I run the script in the shell(Eclipse) it works fine, but when I try to run it from the console, I get this error:</p>
<pre><code> Traceback (most recent call last):
File "C:\Users\Dax\workspace\Python3\TestofPython3.py", line 9, in <module>
import numpy
ImportError: No module named 'numpy'
</code></pre>
<p>If I don't put that at that the top of the script, it runs numpy fine until it gets to 'input()'. It works in the shell with or without #!python3.</p>
| 0 | 2016-10-02T20:38:10Z | 39,821,932 | <p>The "#!python3" is to help the console determine the right version of python. However you need to make sure the path is correct. Instead of putting "#!python3", put "#!/usr/bin/" and then your python version, so "python" or "python3". </p>
<p>Check this article for more information on this. <a href="http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script">Article on "#!" Scripts.</a></p>
| 0 | 2016-10-02T21:35:38Z | [
"python",
"numpy"
]
|
Many Selenium browsers doing the same task (python) | 39,821,619 | <p>I have a list of ids that identify websites. I need to do this:</p>
<pre><code>Open a browser
open a main website that allows a query
for id in ids:
-search in the main website the id,
so that I get the website corresponding to the id with the browser
-load the website corresponding to id with the browser
-do some stuff with the info in the website
</code></pre>
<p>Each of the loops can take 10 seconds. If I have many ids this is of course a problem.</p>
<p>I noticed that the loops are independent. This is, if I divide the ids list in 2, write 2 python scripts that look like the box above and run them from different terminals I will spend half the time. Is there a way to do the loops simultaneously (say, 6 loops at the same time) in different browsers? (actually all of them Firefox, but different windows).</p>
<p>What I want to do is to create a queue of ids, and have a number (say 6) of Firefox windows with the main website. The first id in the queue will go to the first window, and the loop starts. The second id... etc.... when a loop is done (say window number 3 finishes its loop earlier than every other window), then that window is available for a next loop, so the next id in the queue will be handled by that window.</p>
<p>Sorry if my language is not very technical. Thanks for your help.</p>
| 0 | 2016-10-02T20:54:45Z | 39,822,195 | <p>If you think that splitting it in two parts will help speed up things then you can do this (furthering the split technique).</p>
<p>1) Write a function that takes as argument the id of a website.</p>
<p>2) Write a for loop which calls the def again and again sending the nenxt id.</p>
<p>Something like this:</p>
<pre><code>def check(id):
open("id")
ids=[id1, id2, ...]
for id in ids:
check(id)
</code></pre>
| 0 | 2016-10-02T22:05:12Z | [
"python",
"selenium",
"parallel-processing"
]
|
List index out of range though appearing not to be | 39,821,646 | <p>I wrote a simple program to check if strings are substrings of eachother. The issue is I keep getting a list index out of bounds error.</p>
<p>I tried printing i and j with each iteration and they never go out of the bounds of the list. I even tried to insert elements at s[5] and s[6] to check the index but still get the same error. What could be the cause of this error?</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4:
j+=1
i=0
</code></pre>
<p>This is my console output</p>
<pre><code>Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Process finished with exit code 1
</code></pre>
| 0 | 2016-10-02T20:59:01Z | 39,821,680 | <p>You seem to increase j only when i is already 5 (notice the <code>and</code> in the if-clause). Thus, when i=5 you are still in the while loop (which only depends on j) and you try to access s[i] = s[5] which is undefined.</p>
| 0 | 2016-10-02T21:03:26Z | [
"python",
"python-3.x",
"indexing"
]
|
List index out of range though appearing not to be | 39,821,646 | <p>I wrote a simple program to check if strings are substrings of eachother. The issue is I keep getting a list index out of bounds error.</p>
<p>I tried printing i and j with each iteration and they never go out of the bounds of the list. I even tried to insert elements at s[5] and s[6] to check the index but still get the same error. What could be the cause of this error?</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4:
j+=1
i=0
</code></pre>
<p>This is my console output</p>
<pre><code>Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Process finished with exit code 1
</code></pre>
| 0 | 2016-10-02T20:59:01Z | 39,821,700 | <p>At the point when your code is raising the exception, the value of <code>i</code> is <code>5</code> and the value of <code>j</code> is 4. In your <code>print</code> statement you try to do <code>s[i]</code> i.e. <code>s[5]</code>and since max index of s is <code>4</code>, your code is raising <code>IndexError</code>.</p>
<p>I believe, in your code you need to do make modification in your <code>if</code> statement as:</p>
<pre><code>if i == 5 and j < 5: # Instead of j < 4
</code></pre>
<p>Then your code runs fine:</p>
<pre><code>>>> while j < 5:
... if s[j] in s[i]:
... print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
... i +=1
... if i == 5 and j < 5:
... j+=1
... i=0
...
"a b c" is in the string "a b c"
"a b c" is in the string "a b c d"
"a b c d" is in the string "a b c d"
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
</code></pre>
| 0 | 2016-10-02T21:05:33Z | [
"python",
"python-3.x",
"indexing"
]
|
List index out of range though appearing not to be | 39,821,646 | <p>I wrote a simple program to check if strings are substrings of eachother. The issue is I keep getting a list index out of bounds error.</p>
<p>I tried printing i and j with each iteration and they never go out of the bounds of the list. I even tried to insert elements at s[5] and s[6] to check the index but still get the same error. What could be the cause of this error?</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4:
j+=1
i=0
</code></pre>
<p>This is my console output</p>
<pre><code>Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Process finished with exit code 1
</code></pre>
| 0 | 2016-10-02T20:59:01Z | 39,821,712 | <p>The problem is in the line 18</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
print(s)
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4: <-- here
j+=1
i=0
</code></pre>
<p>At some point, your <code>i = 5</code> and <code>j = 4</code>, so the right side of this <code>if i == 5 and j < 4</code> statement is being False, and the <code>i</code> is not reseted to 0. So at the next loop, the <code>i</code> is equal to 5, and the maximum index is 4.</p>
<p>Better solution would be to use for loops.</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
for i in range(len(s)):
for j in range(len(s)):
if s[i] in s[j]:
print("\"" + s[i] + "\" is in the string \"" + s[j] + "\"")
</code></pre>
<h1>Edit to answer comment</h1>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < len(s):
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == len(s):
j+=1
i=0
</code></pre>
| 1 | 2016-10-02T21:07:20Z | [
"python",
"python-3.x",
"indexing"
]
|
List index out of range though appearing not to be | 39,821,646 | <p>I wrote a simple program to check if strings are substrings of eachother. The issue is I keep getting a list index out of bounds error.</p>
<p>I tried printing i and j with each iteration and they never go out of the bounds of the list. I even tried to insert elements at s[5] and s[6] to check the index but still get the same error. What could be the cause of this error?</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4:
j+=1
i=0
</code></pre>
<p>This is my console output</p>
<pre><code>Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Process finished with exit code 1
</code></pre>
| 0 | 2016-10-02T20:59:01Z | 39,821,791 | <p>Your i and j variables in while loop are incorrect. After changing values following code is working. </p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
print s
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 4 and j < 5:
j+=1
i=0
</code></pre>
| 0 | 2016-10-02T21:16:42Z | [
"python",
"python-3.x",
"indexing"
]
|
List index out of range though appearing not to be | 39,821,646 | <p>I wrote a simple program to check if strings are substrings of eachother. The issue is I keep getting a list index out of bounds error.</p>
<p>I tried printing i and j with each iteration and they never go out of the bounds of the list. I even tried to insert elements at s[5] and s[6] to check the index but still get the same error. What could be the cause of this error?</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j < 4:
j+=1
i=0
</code></pre>
<p>This is my console output</p>
<pre><code>Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Process finished with exit code 1
</code></pre>
| 0 | 2016-10-02T20:59:01Z | 39,821,826 | <p>Keeping your form it would be:</p>
<pre><code>s = []
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
j = 0
i = 0
while j < 5:
if s[j] in s[i]:
print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
i +=1
if i == 5 and j <= 4:
j+=1
i=0
</code></pre>
<p>The error is in the 2nd if in your <code>while</code> loop. It should be <code>j <= 4</code> or <code>j < 5</code> in order to work.</p>
| 0 | 2016-10-02T21:21:01Z | [
"python",
"python-3.x",
"indexing"
]
|
GnuPlot auto set xlabel (or ylabel), reading from column head of CSV file | 39,821,685 | <p>In GnuPlot, I can auto set a plot legend with <code>title columnhead</code> option in a plot command like:</p>
<pre><code>plot 'test.txt' using 0:1 w linespoints title columnhead
</code></pre>
<p>So it reads the column name from the CSV file and use it in the legend.</p>
<p><a href="http://i.stack.imgur.com/1YO6S.png" rel="nofollow"><img src="http://i.stack.imgur.com/1YO6S.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/TdF9v.png" rel="nofollow"><img src="http://i.stack.imgur.com/TdF9v.png" alt="enter image description here"></a></p>
<p>I would like the same to set xlabel and ylabel. Is is possible?</p>
<p>(Also, I'm interested in knowing how one will do such thing in Python. Is it better than GnuPlot? Should I learn Python instead?)</p>
| 0 | 2016-10-02T21:03:49Z | 39,838,857 | <p>as pointed out by @Christoph, the <code>system</code> command is probably the only viable solution - in your particular case, you could do:</p>
<pre><code>fname="test.txt"
getTitle(colNum)=system(sprintf("head -n1 '%s' | cut -f%d -d';'", fname, colNum+1))
set xlabel getTitle(0)
set ylabel getTitle(1)
</code></pre>
| 0 | 2016-10-03T19:16:23Z | [
"python",
"gnuplot"
]
|
Testing a time-dependent method | 39,821,687 | <p>I have a method that takes a datetime and returns what period of time this datetime belongs to, for example "yesterday" or "a month ago".</p>
<pre><code>from datetime import datetime
def tell_time_ago(basetime):
difference = datetime.now() - basetime
days = difference.days
seconds = difference.seconds
hours = seconds / 3600
minutes = seconds / 60
if days and days == 1:
return 'Yesterday'
elif days and days != 1 and days < 7:
return '%s days ago' % days
elif days and days != 1 and 7 < days < 31:
return 'Within this month'
elif days and days != 1 and 30 < days < 365:
return '%s months ago' % (days / 30)
elif days and days != 1 and 365 <= days < 730:
return 'A year ago'
elif days and days != 1 and days >= 730:
return '%s years ago' % (days / 365)
elif hours and hours == 1:
return 'An hour ago'
elif hours and hours != 1:
return '%s hours ago' % hours
elif minutes and minutes == 1:
return 'A minute ago'
elif minutes and minutes != 1:
return '%s minutes ago' % minutes
elif seconds and seconds == 1:
return 'A second ago'
elif seconds and seconds != 1:
return '%s seconds ago' % seconds
else:
return '0 second ago'
</code></pre>
<p>I want to extend this method so I'm going to write tests for it. If want to write a test for this method, should I change the current date of system to a specific date and revert it back to normal every time, so the test won't fail just because the date is changed? For example:</p>
<pre><code>class TestCase(unittest.TestCase):
def test_timedelta(self):
a_year_ago = datetime(2015, 5, 12, 23, 15, 15, 53000)
assert tell_time_ago(a_year_ago) == 'A year ago'
</code></pre>
<p>If I run this test two years from now, it will fail. What is the best approach?</p>
| 2 | 2016-10-02T21:04:11Z | 39,822,174 | <p>In general, I think it's a good idea to make your nontrivial functions and classes as close to mathematical functions (e.g., <code>sin(x)</code>), as possible. Given the same input, a mathematical function gives the same output each time, irrespective of the current date, random choices, and so forth. </p>
<ul>
<li><p>If your function performs nontrivial logic dependent on the current date or time, pass the current date or time externally to it.</p></li>
<li><p>If your function performs random choices, pass it a pseudo-random number generator.</p></li>
</ul>
<p>So, for example, instead of:</p>
<pre><code>import datetime
def foo():
...
now = datetime.datetime.now()
...
foo()
</code></pre>
<p>Use </p>
<pre><code>import datetime
def foo(now):
...
...
foo(datetime.datetime.now())
</code></pre>
<p>This makes your nontrivial code consistent across multiple executions.</p>
<ol>
<li><p>You can predictably test it.</p></li>
<li><p>If it fails in production, it is easier to reconstruct the problem.</p></li>
</ol>
| 1 | 2016-10-02T22:03:22Z | [
"python",
"unit-testing"
]
|
Scrapy - print pipeline data in a script's context | 39,821,693 | <p>After using <code>scrapy</code> <code>framework</code>, I would like to process my <code>pipeline.py</code> output within my <code>python</code> script context.</p>
<p>The pipeline output is <code>tracks.jl</code>, as follows:</p>
<p><strong>pipeline.py</strong></p>
<pre><code>class PitchforkTracks(object):
def __init__(self):
self.file = open('tracks.jl', 'wb')
</code></pre>
<p>a <code>json</code> file is generated on the same <code>script.py</code> <code>directory</code>:</p>
<pre><code> def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
</code></pre>
<p>here, I run <code>scrapy</code>.</p>
<p><strong>script.py</strong></p>
<pre><code>def output():
process = CrawlerProcess(get_project_settings())
response = process.crawl('pitchfork_tracks', domain='pitchfork.com')
# the script will block here until the crawling is finished
process.start()
#process pipelined file
tracks = []
time.sleep(5)
#here I pause so there is time for pipeline to build `tracks.jl` at directory
with open('tracks.jl', 'r+') as t:
for line in t:
tracks.append(json.loads(line))
print (tracks)
#process lines from here on
</code></pre>
<p>when I print <code>lines</code>, however, I get an empty <code>list</code> <code>[]</code>. </p>
<p>how do I print inside <code>python script</code> the output of <code>pipeline.py</code>?</p>
<p>EDIT:</p>
<p>this is my <code>log</code>when I run <code>scrapy crawl pitchfork_tracks</code>:</p>
<pre><code>2016-10-03 09:28:39 [scrapy] INFO: Scrapy 1.1.2 started (bot: blogs)
2016-10-03 09:28:39 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'blogs.spiders', 'SPIDER_MODULES': ['blogs.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'blogs'}
2016-10-03 09:28:39 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
2016-10-03 09:28:39 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-10-03 09:28:39 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-10-03 09:28:39 [scrapy] INFO: Enabled item pipelines:
['blogs.pipelines.PitchforkTracks',
'blogs.pipelines.PitchforkAlbums',
'blogs.pipelines.PitchforkReissues']
2016-10-03 09:28:39 [scrapy] INFO: Spider opened
2016-10-03 09:28:39 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-10-03 09:28:39 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-10-03 09:28:39 [scrapy] DEBUG: Crawled (200) <GET http://pitchfork.com/robots.txt> (referer: None)
2016-10-03 09:28:40 [scrapy] DEBUG: Crawled (200) <GET http://pitchfork.com/reviews/best/tracks/?page=1> (referer: None)
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Moses Sumney', 'track': u'Lonely World'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Cherry Glazerr', 'track': u"Told You I'd Be With the Guys"}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Danny Brown',
'track': u'Really Doe\u201d [ft. Kendrick Lamar, Ab-Soul, and Earl Sweatshirt]'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'NxWorries', 'track': u'Lyk Dis'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Nick Cave & the Bad Seeds', 'track': u'I Need You'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Merchandise', 'track': u'Lonesome Sound'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Weyes Blood', 'track': u'Do You Need My Love'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Kelly Lee Owens', 'track': u'CBM'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Sampha', 'track': u'Blood on Me'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Bon Iver', 'track': u'33 \u2018GOD\u2019'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Mick Jenkins', 'track': u'Drowning\u201d [ft. BADBADNOTGOOD]'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Chromatics', 'track': u'Dear Tommy'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Young Thug', 'track': u'Kanye West'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Vince Staples', 'track': u'Prima Donna\u201d [ft. A$AP Rocky]'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Angel Olsen', 'track': u'Sister'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Cass McCombs', 'track': u'Bum Bum Bum'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Hamilton Leithauser', 'track': u'A 1000 Times'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Danny Brown', 'track': u'Pneumonia'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Frank Ocean', 'track': u'Ivy'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Frank Ocean', 'track': u'Rushes'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Half Waif', 'track': u'Turn Me Around'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Rae Sremmurd', 'track': u'Black Beatles\u201d [ft. Gucci Mane]'}
2016-10-03 09:28:40 [scrapy] DEBUG: Scraped from <200 http://pitchfork.com/reviews/best/tracks/?page=1>
{'artist': u'Bon Iver',
'track': u'22 (OVER S\u221e\u221eN) [Bob Moose Extended Cab Version]'}
2016-10-03 09:28:40 [scrapy] INFO: Closing spider (finished)
2016-10-03 09:28:40 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 459,
'downloader/request_count': 2,
'downloader/request_method_count/GET': 2,
'downloader/response_bytes': 22624,
'downloader/response_count': 2,
'downloader/response_status_count/200': 2,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2016, 10, 3, 12, 28, 40, 425137),
'item_scraped_count': 23,
'log_count/DEBUG': 26,
'log_count/INFO': 7,
'response_received_count': 2,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2016, 10, 3, 12, 28, 39, 535638)}
2016-10-03 09:28:40 [scrapy] INFO: Spider closed (finished)
</code></pre>
| 0 | 2016-10-02T21:04:39Z | 39,834,084 | <p>I think it's because your pipeline never closes the file object. You should open a file in your pipeline's <code>open_spider()</code> method and close it in <code>close_spider()</code> method.</p>
<pre><code>class PitchforkTracks(object):
def open_spider(self, spider):
self.file = open('tracks.jl', 'wb')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
</code></pre>
| 0 | 2016-10-03T14:31:04Z | [
"python",
"scrapy"
]
|
Save a matrix as an image without changes after recovery | 39,821,756 | <p>I need to save matrix as an image, so, that after back reading, initial and recovered matrices be the same. I have the code:</p>
<pre><code>import scipy.misc
def get_matrix(N, M):
import random
matrix = [[ random.randint(1, 100) for j in range(M) ] for i in range(N)]
return matrix
def equal(matA, matB):
if len(matA) != len(matB):
return False
if (len(matA[0]) != len(matB[0])):
return False
for i in range(len(matA)):
for j in range(len(matA[i])):
if matA[i][j] != matB[i][j]:
return False
return True
init_matrix = get_matrix(10, 10)
scipy.misc.imsave('matrix.jpg', init_matrix)
recovered_matrix = scipy.misc.imread('matrix.jpg')
assert equal(init_matrix, recovered_matrix)
</code></pre>
<p>but after reading an image from disk, matrices are not equal. How to fix that?</p>
| 0 | 2016-10-02T21:12:52Z | 39,822,184 | <p>If you're willing to use matplotlib or scikit-image, these libraries have built-in functionality for what you want. Otherwise take a look at the imageio package.</p>
| 1 | 2016-10-02T22:04:08Z | [
"python",
"matrix",
"scikit-image"
]
|
Optional return type annotations? | 39,821,758 | <p>I have a function that will either return a generator (<code>types.GeneratorType</code>) or <code>list</code>, depending upon the value of an argument. For example:</p>
<pre><code>def foo(switch: bool) -> list: # return type of list || types.GeneratorType
... # create some generator object named f1
if switch:
return list(f1)
else:
return f1
</code></pre>
<p>How do I tell it that I can optionally return a list or another type? Or, for that matter, what about a bunch of different types?</p>
<p>I've looked over <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">documentation on a module <code>typing</code></a> but haven't as of yet found any methods there that allow for this. I haven't been able to find any examples by Googling either.</p>
| 0 | 2016-10-02T21:13:23Z | 39,821,835 | <p>The two solutions that immediately spring to mind are: </p>
<ol>
<li><p>Make a <a href="https://docs.python.org/3/library/typing.html#typing.Union" rel="nofollow"><code>Union</code></a> type</p>
<pre><code>def foo(switch: bool) -> Union[list, GeneratorType]:
</code></pre>
<p>which means <em>"returns either list or generator"</em> (you could also use <a href="https://docs.python.org/3/library/typing.html#typing.Generator" rel="nofollow"><code>Generator</code></a> and <a href="https://docs.python.org/3/library/typing.html#typing.List" rel="nofollow"><code>List</code></a>); or</p></li>
<li><p>Type based on the behaviour you can expect from <em>either</em> return value, e.g. that they are <a href="https://docs.python.org/3/library/typing.html#typing.Iterable" rel="nofollow"><code>Iterable</code></a>:</p>
<pre><code>def foo(switch: bool) -> Iterable:
</code></pre></li>
</ol>
<p>In both cases you could also provide more detail: list or generator/iterable <em>of what?</em></p>
<p>That said, something that returns either a list or a generator sounds like an odd interface, and it would be helpful to provide a bit more context around what consumers of your function should expect to do with whatever they receive. It may be that:</p>
<ul>
<li>a single function with two different returns isn't the right interface design; or </li>
<li>rather than <code>list</code> you could use the more general <a href="https://docs.python.org/3/library/typing.html#typing.Sequence" rel="nofollow"><code>Sequence</code></a>, to permit e.g. <code>tuple</code>s to be used instead.</li>
</ul>
| 3 | 2016-10-02T21:21:53Z | [
"python",
"python-3.x",
"annotations",
"type-hinting"
]
|
Optional return type annotations? | 39,821,758 | <p>I have a function that will either return a generator (<code>types.GeneratorType</code>) or <code>list</code>, depending upon the value of an argument. For example:</p>
<pre><code>def foo(switch: bool) -> list: # return type of list || types.GeneratorType
... # create some generator object named f1
if switch:
return list(f1)
else:
return f1
</code></pre>
<p>How do I tell it that I can optionally return a list or another type? Or, for that matter, what about a bunch of different types?</p>
<p>I've looked over <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">documentation on a module <code>typing</code></a> but haven't as of yet found any methods there that allow for this. I haven't been able to find any examples by Googling either.</p>
| 0 | 2016-10-02T21:13:23Z | 39,821,846 | <p>Wouldn't it be better to pass "type" as an argument? </p>
<pre><code>def foo(switch: type) -> list | tuple | gen_func
... # create some generator object named f1
return switch(f1)
foo(list) > list type
foo(tuple) > tuple
# And if you would want to get generator you would only need to provide
gen = lambda func_result: (el for el in func_result)
foo(gen)
</code></pre>
<p>Dont know if this is the case.</p>
| 0 | 2016-10-02T21:23:04Z | [
"python",
"python-3.x",
"annotations",
"type-hinting"
]
|
recurDescents(p) and recurAncestors(p) | 39,821,762 | <p>I need to write a Python script with two functions. One function is to return the descendants children of (p) and Take (p) and return ancestors of (p). </p>
<p>I made a script that returns the children of (p). </p>
<pre><code>parent = [("Homer","Bart"),("Homer","Lisa"),("Abe","Homer"),("Bart","Jim"),("Jim","Kim"),("Lisa","Lora")]
def child(p): #definition of child function()
result = []
for x in parent:
if x[0] == p:
print(x[1])
result.append(x[1])
return result
def grandChild (p):
result = []
children = child(p)
for x in children:
for y in parent:
if x == y[0]:
result.append(y(1))
return result
p = "Homer"
children = child(p) # my caller question
print(p, " has child ", children)
</code></pre>
<p>I just can't figure out what to do.</p>
| 0 | 2016-10-02T21:13:49Z | 39,821,844 | <p>Your return statements are in the wrong places. They should be outside the loops:</p>
<pre><code>def f():
for loop
stuff
return ...
</code></pre>
<p>If you want a slightly more concise version:</p>
<pre><code>#find children of parent p
[child for parent, child in list_of_parents if parent == p]
#find parent of child c
[parent for parent, child in list_of_parents if child == c]
</code></pre>
| 0 | 2016-10-02T21:22:43Z | [
"python",
"python-3.x"
]
|
try / except loop with bash terminal command as interrupt | 39,821,895 | <p>I'm using a simple python.py script in Linux. I need to run a while/counter loop and would like to stop the loop immediately by using a/any terminal command. I need to run the script using Screen. Simply stopping the Screen session doesn't work - it only stops the current process in the loop and then continues with the next process. The terminal command must preferably be specific for the loop in question.</p>
<p>I was looking at a Try / Except loop:</p>
<pre><code>x = 1
y = 100
try:
while x < y:
process x
time.sleep(10)
x = x + 1
except ?
</code></pre>
<p>I don't know where to start. I need help with the implementation or maybe a better way to do this.</p>
| 0 | 2016-10-02T21:30:26Z | 39,919,330 | <p>If this is linux then you can use Operating System Signals.
Just create a signal handler that throws an exception and catch that exception.
Register the signal handler with</p>
<pre><code>signal.signal(signal.SIGINT, handler)
</code></pre>
<p>This will register the handler function to be called when ever the SIGINT is sent to the process ID.</p>
<pre><code>import signal, time
class InterruptException(Exception):
pass
def handler(signum, frame):
raise InterruptException("Recieved SIGINT")
# Set the signal handler
signal.signal(signal.SIGINT, handler)
x = 1
y = 100
try:
while x < y:
print x
time.sleep(10)
x = x + 1
except InterruptException:
print "Iterrupted"
</code></pre>
<p>From bash you can use </p>
<pre><code>kill -2 PID
</code></pre>
<p>where PID is the process ID for the running script</p>
<p>You could always launch and kill from bash like</p>
<pre><code>python my.app &
MY_PID=$!
kill -2 $MY_ID
</code></pre>
| 0 | 2016-10-07T14:11:12Z | [
"python",
"gnu-screen"
]
|
How to correctly overload a variable in class inheritance with the same variables | 39,821,911 | <p>I need to override or overload a variable in a class inheritance. Here is what I am trying to achieve:</p>
<pre><code>class MainClass:
def __init__(self, a, b, c, d):
type(a) = str
class MyClass(MainClass):
def __init__(self, a, b, c, d):
type(a) = object of one of my classes.
</code></pre>
<p>How do I achieve this in Python 3? I have looked into inheritance but either this type of situation is not discussed or I don't get it.</p>
| -2 | 2016-10-02T21:32:25Z | 39,822,319 | <p>What it seems like you're trying to do is make each class able to access the other. However this is not how class inheritance works. Try using this for the classes to access each other. </p>
<pre><code>class MainClass:
def __init__(self, a, b, c): # main class with variables, a, b and c.
self.a = a
self.b = b
self.c = c
def printall(self): # this will be so we can see what happens
print(self.a)
print(self.b)
print(self.c)
class MyClass:
def __init__(self, class_inst, a): # another class of a class and a variable
self.a = a
self.class_inst = class_inst
def override(self): # this will override(or overload) the other class variable.
self.class_inst.a = self.a
</code></pre>
<p>Write some testing code for it like this. </p>
<pre><code>class_inst_one = MainClass("Hello","World","!")
class_inst_two = MyClass(class_inst_one, "Replacement")
class_inst_one.printall()
class_inst_two.override()
class_inst_one.printall()
</code></pre>
<p>Now you should get an output like this.</p>
<pre><code>Hello
World
!
Replacement
World
!
</code></pre>
| 0 | 2016-10-02T22:21:21Z | [
"python",
"python-3.x",
"inheritance"
]
|
How to correctly overload a variable in class inheritance with the same variables | 39,821,911 | <p>I need to override or overload a variable in a class inheritance. Here is what I am trying to achieve:</p>
<pre><code>class MainClass:
def __init__(self, a, b, c, d):
type(a) = str
class MyClass(MainClass):
def __init__(self, a, b, c, d):
type(a) = object of one of my classes.
</code></pre>
<p>How do I achieve this in Python 3? I have looked into inheritance but either this type of situation is not discussed or I don't get it.</p>
| -2 | 2016-10-02T21:32:25Z | 39,822,614 | <p>
So you are trying to <em>reset</em> the variable.<br>
Really, it's the same as creating the variable for the first time.</p>
<pre class="lang-py prettyprint-override"><code>class Base:
var = 12
class Cls(Base):
var = 'abc'
</code></pre>
<p>The class's variables are copied when you create a new class, so these variables <strong>belong</strong> the base, but <strong>gotten</strong> from the the new class. The new class redirects to it's base if this variable is not his. </p>
<p>So, editing the class (<em>see below</em>) makes the function reference to it's class, which references to it's base.</p>
<pre class="lang-py prettyprint-override"><code>class Class(Base):
def getVar(self):
return self.var
</code></pre>
<p>Same with editing and deleting. </p>
<p>To make variables <strong>copy</strong> into the class, there are 2 solutions: </p>
<p>One:</p>
<pre class="lang-py prettyprint-override"><code>class Base:
__var = 12
def __init__(self):
self.var = self.__var
class Class(Base):
var = _Base__var #add any methods to copy like list.copy()
def __init__(self):
pass
</code></pre>
<p>Two:</p>
<pre class="lang-py prettyprint-override"><code>class Base:
var = 12
class Class(Base):
pass
Class.var = Base.var #add any methods to copy like list.copy()
</code></pre>
<p>The first one works because of the rule that variables that start with two or more underscores (_) and don't match __{name}__ form are renamed to
_{class name}{variable name}.
Then the __init__ function creates a variable called var with the value of _Base__var.</p>
<ul>
<li>It is making the object weight more</li>
<li>You need to redefine the __init__ class</li>
<li>No code outside functions or classes</li>
</ul>
<p>Second one copies it from the outside. </p>
<ul>
<li>Code outside functions or classes</li>
</ul>
| 0 | 2016-10-02T23:03:57Z | [
"python",
"python-3.x",
"inheritance"
]
|
Error when trying to get the union, intersection and difference in a set | 39,821,918 | <p>As the title says, I am getting an error in my code here:</p>
<pre><code>#!/usr/bin/python3
import random
A = random.sample(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5)
B = random.sample(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5)
print(A | B)
print(A & B)
print(A - B)
</code></pre>
<p>The error I'm getting is <code>TypeError: unsupported operand type(s) for |: 'list' and 'list'.</code> I have also tried <code>random.sample(range(10), 5)</code>, which still does not work.</p>
<p>Is there anything I'm doing wrong?</p>
| 0 | 2016-10-02T21:33:37Z | 39,822,013 | <p>So, as error says, function: </p>
<pre><code>random.sample
</code></pre>
<p>returns <strong>list</strong> object not <strong>set</strong> , try convert them like this :</p>
<pre><code>A = set(random.sample(range(1,10), 5))
</code></pre>
| 0 | 2016-10-02T21:44:28Z | [
"python",
"python-3.x"
]
|
Error when trying to get the union, intersection and difference in a set | 39,821,918 | <p>As the title says, I am getting an error in my code here:</p>
<pre><code>#!/usr/bin/python3
import random
A = random.sample(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5)
B = random.sample(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5)
print(A | B)
print(A & B)
print(A - B)
</code></pre>
<p>The error I'm getting is <code>TypeError: unsupported operand type(s) for |: 'list' and 'list'.</code> I have also tried <code>random.sample(range(10), 5)</code>, which still does not work.</p>
<p>Is there anything I'm doing wrong?</p>
| 0 | 2016-10-02T21:33:37Z | 39,822,337 | <p>Try this:</p>
<pre><code>import random
A = set(random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))
B = set(random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))
print(A | B)
print(A & B)
print(A - B)
</code></pre>
<p>It should produce the following output:</p>
<pre><code>{2, 3, 4, 5, 6, 7, 10}
{2, 4, 6}
{10, 5}
</code></pre>
| 0 | 2016-10-02T22:23:12Z | [
"python",
"python-3.x"
]
|
TensorFlow feed an integer | 39,821,942 | <p>I am trying to do a convolution over variable input sizes. To achieve that, I am using a batch size of 1. However, one of the nodes is a max pooling node which needs the shape of the input as a list <code>ksize</code>:</p>
<pre><code> pooled = tf.nn.max_pool(
h,
ksize=[1, self.input_size - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
</code></pre>
<p>Now, clearly the input_size can be inferred from the input (which is a placeholder):</p>
<pre><code>self.input_x = tf.placeholder(tf.int32, [None, None], name="input_x")
</code></pre>
<p>But I can't use <code>self.input_x.get_shape()[0]</code> because the shape is dynamic. So I intend to pass the input size as feed_dict at each step. However, I can't figure out how to pass an integer in feed_dict. Every placeholder is a tensor, so if I do:</p>
<pre><code>self.input_size = tf.placeholder(tf.int32, shape=(), name="input_size")
</code></pre>
<p>I would have to do <code>self.input_size.eval()</code> to get the int value, which gives me an error that I need to feed <code>input_size</code>. I guess it happens because eval triggers the computation BEFORE the training step happens, at which point there is no value for input_size.</p>
<p>Is there a way I can dynamically get an op that calculates the shape of the input or a way to pass an integer to a training step?</p>
| 0 | 2016-10-02T21:36:57Z | 39,834,890 | <p>I'm not sure that it's the best way, but you can get dynamically the shape of <code>self.input_x</code> in a list with :</p>
<pre><code>input_shape = tf.unpack(tf.shape(self.input_x))
</code></pre>
<p><code>tf.shape(self.input_x)</code> give you a Tensor representing the shape of self.input_x and <code>f.unpack</code> convert it to a list of Tensor.</p>
<p>Now you can create your max pooling node with :</p>
<pre><code>pooled = tf.nn.max_pool(
h,
ksize=tf.pack([1, input_size[1] - filter_size + 1, 1, 1]),
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
</code></pre>
<p>(if you needed the 2nd dimension of input_x)</p>
| 0 | 2016-10-03T15:14:09Z | [
"python",
"neural-network",
"tensorflow",
"convolution",
"conv-neural-network"
]
|
Turtle and drawing tree with RapydScript | 39,822,008 | <p>today I want draw a tree in browser with RapydScript.
I have code in Python:</p>
<pre><code>import random
import turtle
def tree(size, myTurtle):
myTurtle.pensize(size / 20)
if size < random.randint(1,2) * 20:
myTurtle.color("green")
else:
myTurtle.color("brown")
if size > 5:
myTurtle.forward(size)
myTurtle.left(25)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.right(50)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.left(25)
myTurtle.penup()
myTurtle.backward(size)
myTurtle.pendown()
window = turtle.Screen()
window.setup(800,600)
window.bgcolor("white")
myTurtle = turtle.Turtle()
myTurtle.color("brown", "blue")
myTurtle.left(90)
myTurtle.speed(0)
myTurtle.penup()
myTurtle.setpos(0, -250)
myTurtle.pendown()
</code></pre>
<p>And I want to run it in browser to get this effect:</p>
<p><a href="http://i.stack.imgur.com/NpcHB.png" rel="nofollow"><img src="http://i.stack.imgur.com/NpcHB.png" alt="image"></a>
âDon't worry about text over the tree, is in polish ;) I run this in Skulpt, maybe you hear about it, effect you have above.
Now I want to run this in RapydScript and compare it to Skulpt and Brython.</p>
<p>I am wonder if it possible in RapydScript beacuse this code use turtle module.
I guess that I need to change this code somehow to run it on RapydScript.
Did RapydScript allow to import turtle module?</p>
<p>As you can see here:
<a href="http://www.transcrypt.org/live/turtle_site/turtle_site.html" rel="nofollow">http://www.transcrypt.org/live/turtle_site/turtle_site.html</a></p>
<p>Transcrypt(similiar tool to RapydScript) somehow can draw with turtle.</p>
<p>Can you help me with this?</p>
<p>Of course I want use Python, I know that RapydScript allows to use JavaScript, but I want Python :))</p>
| 1 | 2016-10-02T21:43:48Z | 39,825,291 | <p>See <code>src/lib</code> in <a href="https://github.com/atsepkov/RapydScript" rel="nofollow">RapydScript repo</a> - there is no <code>turtle</code> module. And it can't import turtle module from Python because it doesn't draw on canvas in browser. So you can't draw tree if you doesn't create turtle module.</p>
| 2 | 2016-10-03T05:53:21Z | [
"python",
"browser",
"turtle-graphics",
"rapydscript"
]
|
Turtle and drawing tree with RapydScript | 39,822,008 | <p>today I want draw a tree in browser with RapydScript.
I have code in Python:</p>
<pre><code>import random
import turtle
def tree(size, myTurtle):
myTurtle.pensize(size / 20)
if size < random.randint(1,2) * 20:
myTurtle.color("green")
else:
myTurtle.color("brown")
if size > 5:
myTurtle.forward(size)
myTurtle.left(25)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.right(50)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.left(25)
myTurtle.penup()
myTurtle.backward(size)
myTurtle.pendown()
window = turtle.Screen()
window.setup(800,600)
window.bgcolor("white")
myTurtle = turtle.Turtle()
myTurtle.color("brown", "blue")
myTurtle.left(90)
myTurtle.speed(0)
myTurtle.penup()
myTurtle.setpos(0, -250)
myTurtle.pendown()
</code></pre>
<p>And I want to run it in browser to get this effect:</p>
<p><a href="http://i.stack.imgur.com/NpcHB.png" rel="nofollow"><img src="http://i.stack.imgur.com/NpcHB.png" alt="image"></a>
âDon't worry about text over the tree, is in polish ;) I run this in Skulpt, maybe you hear about it, effect you have above.
Now I want to run this in RapydScript and compare it to Skulpt and Brython.</p>
<p>I am wonder if it possible in RapydScript beacuse this code use turtle module.
I guess that I need to change this code somehow to run it on RapydScript.
Did RapydScript allow to import turtle module?</p>
<p>As you can see here:
<a href="http://www.transcrypt.org/live/turtle_site/turtle_site.html" rel="nofollow">http://www.transcrypt.org/live/turtle_site/turtle_site.html</a></p>
<p>Transcrypt(similiar tool to RapydScript) somehow can draw with turtle.</p>
<p>Can you help me with this?</p>
<p>Of course I want use Python, I know that RapydScript allows to use JavaScript, but I want Python :))</p>
| 1 | 2016-10-02T21:43:48Z | 39,831,709 | <p>As @furas mentioned, there is no <code>turtle</code> module in the base repo. First of all, I think you're misunderstanding what the <code>turtle</code> module is, it's nothing more than an abstraction around another graphics library. Even in Python, it's not the preferred way of handling graphics, it's just a subset of Logo toolkit aimed at making programming easier to kids.</p>
<p>With that said, Transcrypt exists in the exact same JavaScript world as RapydScript, the <code>turtle</code> it uses has nothing to do with Python's <code>turtle</code>, it's a wrapper around SVG. In fact, here it is: <a href="https://github.com/JdeH/Transcrypt/blob/master/transcrypt/modules/turtle/__init__.py" rel="nofollow">https://github.com/JdeH/Transcrypt/blob/master/transcrypt/modules/turtle/<strong>init</strong>.py</a></p>
<p>And looking at that code, I can tell you that you can copy-paste it almost verbatim into RapydScript to "gain" a turtle module there. Everything that code does is supported by RapydScript, even the import mechanism between RS and Transcrypt will work the same.</p>
<p>Moreover, a quick Google search revealed 2 JavaScript implementations of this <code>turtle</code> module (which you can just attach to the same page as RapydScript and use them as if they're Python):<br>
<a href="http://berniepope.id.au/html/js-turtle/turtle.html" rel="nofollow">http://berniepope.id.au/html/js-turtle/turtle.html</a><br>
<a href="https://github.com/davebalmer/turtlewax" rel="nofollow">https://github.com/davebalmer/turtlewax</a></p>
<p>Finally, whether or not you use the <code>turtle</code> module doesn't make your code any more or less Python. You also seem to have a misconception that by using a JavaScript library from RapydScript, you need to write the rest of the code in JavaScript. That is not the case, The RapydScript examples directory already shows <a href="https://github.com/atsepkov/RapydScript/tree/master/examples/d3_treemap" rel="nofollow">D3</a>, <a href="https://github.com/atsepkov/RapydScript/tree/master/examples/paint" rel="nofollow">canvas</a>, and <a href="http://www.glowscript.org/#/user/GlowScriptDemos/folder/Examples/program/RotatingCubes-RapydScript/edit" rel="nofollow">WebGL</a> examples. The reason there is no turtle module is because it's obsolete compared to the graphics libraries that JavaScript (and RapydScript) has access to. You're welcome to do a pull request with a turtle module implementation, however.</p>
| 2 | 2016-10-03T12:30:23Z | [
"python",
"browser",
"turtle-graphics",
"rapydscript"
]
|
getting transaction result from transaction module | 39,822,021 | <p>I am using Sqlalchemy and PostgreSQL. In my models I have a <code>Product</code> and an <code>Image</code>. I want each product to have multiple images. This is the product submission method:</p>
<pre><code>def submit_product(self, **kwargs):
product = Product(
title=kwargs['title'],
sub_category_id=kwargs['sub_category_id'],
year_of_production=kwargs['year_of_production'],
country_of_production=kwargs['country_of_production'],
quantity=kwargs['quantity'],
price=kwargs['price'],
account_id=session.get('account_id', None)
)
DBSession.add(product)
transaction.commit()
for image in kwargs['images']:
image = Image(
product_id= # what should I put here?,
image=image.file.read()
)
DBSession.add(image)
transaction.commit()
</code></pre>
<p>in the last part that Im adding images to db. I need the <code>product_id</code> to set for the image. but I dont find a way to get it. Is there a way to get results from the transaction so I can find out what id the new product is assigned to? <code>DBSession.add()</code> and <code>transaction.commit()</code> both return <code>None</code>.</p>
| 0 | 2016-10-02T21:45:56Z | 39,822,439 | <p>After using:</p>
<pre><code>transaction.commit()
</code></pre>
<p>you can use <code>product.id</code>, because changes have been commited. So product has now its id:</p>
<pre><code>for image in kwargs['images']:
image = Image(
product_id=product.id, # what should I put here?,
image=image.file.read()
)
DBSession.add(image)
</code></pre>
| 1 | 2016-10-02T22:35:50Z | [
"python",
"sqlalchemy"
]
|
getting transaction result from transaction module | 39,822,021 | <p>I am using Sqlalchemy and PostgreSQL. In my models I have a <code>Product</code> and an <code>Image</code>. I want each product to have multiple images. This is the product submission method:</p>
<pre><code>def submit_product(self, **kwargs):
product = Product(
title=kwargs['title'],
sub_category_id=kwargs['sub_category_id'],
year_of_production=kwargs['year_of_production'],
country_of_production=kwargs['country_of_production'],
quantity=kwargs['quantity'],
price=kwargs['price'],
account_id=session.get('account_id', None)
)
DBSession.add(product)
transaction.commit()
for image in kwargs['images']:
image = Image(
product_id= # what should I put here?,
image=image.file.read()
)
DBSession.add(image)
transaction.commit()
</code></pre>
<p>in the last part that Im adding images to db. I need the <code>product_id</code> to set for the image. but I dont find a way to get it. Is there a way to get results from the transaction so I can find out what id the new product is assigned to? <code>DBSession.add()</code> and <code>transaction.commit()</code> both return <code>None</code>.</p>
| 0 | 2016-10-02T21:45:56Z | 39,860,183 | <p>the trick is to <code>DBSession.flush()</code> after adding the image so the adding will be done and <code>product.id</code> will be accessible .</p>
| 1 | 2016-10-04T19:22:43Z | [
"python",
"sqlalchemy"
]
|
flask Sqlalchemy One to Many getting parent attributes | 39,822,087 | <p>Im trying to get the Pet owner or persons name</p>
<pre><code>class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
pets = db.relationship('Pet', backref='owner', lazy='dynamic')
class Pet(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
</code></pre>
<p>I want to query the pets and after i select a pet i want to get pet owner names</p>
<pre><code>pets = Pet.query.all()
for pet in pets:
print pet.owner_id
</code></pre>
<p>will give the owner id but i want to owner name</p>
| 2 | 2016-10-02T21:53:06Z | 39,822,369 | <pre><code>pets = db.session.query(Pet, Person.name).join(Person)
for pet, person_name in pets:
print pet.name, person_name
</code></pre>
<p>Using that type of querying we force SQLAlchemy to use Mapping of <code>pet</code> table to <code>Pet</code> object and get <code>Person</code>'s name as second item in select. Of course you can use something like that:</p>
<pre><code>pets = db.session.query(Pet, Person).join(Person)
</code></pre>
<p>then you'll be able to use it in this way:</p>
<pre><code>for pet, person in pets:
print pet.name, person.name
</code></pre>
<p>so have reference to a person as object of <code>Person</code> class. But first option is more preferable because it's faster, just because of getting person's name only.</p>
| 1 | 2016-10-02T22:27:11Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
]
|
Index out of range using Flask/Python | 39,822,159 | <p>I am working on a web app and running into some issues with the following code. I have a database where I need to update a value. When I try to update the value I am getting an index out of range error, however when I run the code with just python not using the web part it runs and performs as expected.. I cannot figure out what is changing when I try it in part with flask and an HTML form. Here is my code to update the database;</p>
<p>EDIT:: After more testing it seems there is some issue with the form pushing the data I need back to /poplesson. If change these lines;</p>
<pre><code>user_id = request.form['clientid']
pck_id = request.form['packageid']
</code></pre>
<p>to</p>
<pre><code>user_id = 1
pck_id = 1
</code></pre>
<p>it will work as planned, however that is not what I need as I need those ID's to be pulled from the DB.</p>
<pre><code>@app.route("/poplesson", methods=['GET', 'POST'])
def poplesson():
if request.method == 'GET':
return render_template('view_packages.html')
elif request.method == 'POST':
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = request.form['clientid']
pck_id = request.form['packageid']
package = db.execute("SELECT * FROM packages WHERE client_id = ?;", (user_id, ))
result = package.fetchall()
privatelessons = result[0][4] ##Without flask this run, with flask this throws an index error.
pop = privatelessons - 1
db.execute("UPDATE packages SET privatelesson = ? WHERE client_id = ? AND pck_id = ?;", (pop, user_id, pck_id, ))
con.commit()
return render_template('view_packages.html')
</code></pre>
<p>This is the code I am using to display the HTML and get the value from the forms..</p>
<pre><code><table>
{% for col in items %}
<tr>
<td>{{ col['pck_id'] }}</td>
<td>{{ col['client_id'] }}</td>
<td>{{ col['date'] }}</td>
<td>{{ col['price'] }}</td>
<td>{{ col['privatelesson'] }}</td>
<td>{{ col['shortgamelesson'] }}</td>
<td>{{ col['playinglesson'] }}</td>
<td>{{ col['notes'] }}</td>
<td><form class="form-container" action="/deletepackage" method="POST">
<input class="form-field" value="{{ col['pck_id'] }}" name="packageid" /> <br />
<input class="submit-button" type="submit" value="DELETE Package" /> </form>
</td>
<td><form class="form-container" action="/poplesson" method="POST">
<input class="form-field" value="{{ col['client_id'] }}" name="clientid" /> <br />
<input class="form-field" value="{{ col['pck_id'] }}" name="packageid" />
<input class="submit-button" type="submit" value="Subtract Private Lesson" /></form></td>
</tr>
{% endfor %}
</table>
</body>
</code></pre>
<p>if I do just this part in python, it runs as expected and using a DB viewed I can see the DB is updated. Any thoughts?</p>
<pre><code> con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = request.form['clientid']
pck_id = request.form['packageid']
package = db.execute("SELECT * FROM packages WHERE client_id = ?;", (user_id, ))
result = package.fetchall()
privatelessons = result[0][4] ##Without flask this run, with flask this throws an index error.
pop = privatelessons - 1
db.execute("UPDATE packages SET privatelesson = ? WHERE client_id = ? AND pck_id = ?;", (pop, user_id, pck_id, ))
con.commit()
</code></pre>
| 2 | 2016-10-02T22:01:51Z | 39,822,258 | <p>I could think of two possible reasons:</p>
<ol>
<li>Database configuration you are using with/without Flask are different</li>
<li>Check the <code>type</code> and value of your <code>user_id</code> in both the code. It might be different.</li>
</ol>
| 0 | 2016-10-02T22:12:50Z | [
"python",
"flask",
"sqlite3",
"jinja2"
]
|
Flask URL variable type None? | 39,822,188 | <p>I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.</p>
<p>This gives me a malformed URL error:</p>
<pre><code>@app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
</code></pre>
<p>This runs but gives me a var of type none that I can't work with:</p>
<pre><code>@app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
</code></pre>
| 2 | 2016-10-02T22:04:34Z | 39,822,237 | <p>In your second example, instead of <code>num = request.args.get('num')</code> try to simply use <code>num</code>. Since you specified it as an input to your route/function, you should be able to access it directly. </p>
| 1 | 2016-10-02T22:10:02Z | [
"python",
"flask"
]
|
Flask URL variable type None? | 39,822,188 | <p>I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.</p>
<p>This gives me a malformed URL error:</p>
<pre><code>@app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
</code></pre>
<p>This runs but gives me a var of type none that I can't work with:</p>
<pre><code>@app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
</code></pre>
| 2 | 2016-10-02T22:04:34Z | 39,822,292 | <p>Try this:</p>
<pre><code>@app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
print(num)
</code></pre>
| 1 | 2016-10-02T22:16:45Z | [
"python",
"flask"
]
|
Flask URL variable type None? | 39,822,188 | <p>I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.</p>
<p>This gives me a malformed URL error:</p>
<pre><code>@app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
</code></pre>
<p>This runs but gives me a var of type none that I can't work with:</p>
<pre><code>@app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
</code></pre>
| 2 | 2016-10-02T22:04:34Z | 39,822,302 | <p>You are mixing route parameters and request arguments here.</p>
<p>Parameters you specify in the route are route parameters and are a way to declare <a href="http://flask.pocoo.org/docs/0.11/quickstart/#variable-rules" rel="nofollow">variable routes</a>. The values for these parameters are passed as function arguments to the route function. So in your case, for your <code><num></code> url part, the value is passed as the function argument <code>num</code>.</p>
<p>Request arguments are independent of routes and are passed to URLs as GET parameters. You can access them through the <a href="http://flask.pocoo.org/docs/0.11/quickstart/#the-request-object" rel="nofollow">request object</a>. This is what you are doing with <code>request.args.get()</code>.</p>
<p>A full example would look like this:</p>
<pre><code>@app.route('/iLike/<int:num>')
def single2(num):
print(num, request.args.get('num'))
</code></pre>
<p>Opening <code>/iLike/123</code> would now result in <code>123 None</code>. The request argument is empty because you didnât specify one. You can do that by opening <code>/iLike/123?num=456</code>, which would result in <code>123 456</code>.</p>
| 3 | 2016-10-02T22:17:42Z | [
"python",
"flask"
]
|
Flask URL variable type None? | 39,822,188 | <p>I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.</p>
<p>This gives me a malformed URL error:</p>
<pre><code>@app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
</code></pre>
<p>This runs but gives me a var of type none that I can't work with:</p>
<pre><code>@app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
</code></pre>
| 2 | 2016-10-02T22:04:34Z | 39,822,311 | <p>You recieve <code>None</code> here:</p>
<pre><code>num = request.args.get('num')
</code></pre>
<p>because you're not passing <code>num</code> as element of querystring.</p>
<p>When use <code>request.args.get('num')</code>?</p>
<p>If we would have URL like this one:</p>
<pre><code>localhost:8080/iLike?num=2
</code></pre>
<p>But it's not your case. You pass <code>num</code> already to a function as an argument. So in your case just use:</p>
<pre><code>@app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
print(num)
</code></pre>
| 1 | 2016-10-02T22:19:42Z | [
"python",
"flask"
]
|
What effect did DataFrame.loc() cause on the data frame? | 39,822,219 | <p>I used numpy.random.permutation() to generate random order to an original data frame X and want to assign whole X to X_perm by the random order. </p>
<pre><code>X_perm=X
y_perm=y
perm = np.random.permutation(X.shape[0])
for i in range(len(perm)):
X_perm.loc[i]=(X.loc[perm[i]])
y_perm.loc[i]=(y.loc[perm[i]])
</code></pre>
<p>Just found that after running the code, the first record of X given by X[0:1] changed comparing to the case before running.</p>
<p>Strange. I didn't make any operation on X but assign its values to a new data frame. How did it cause the alteration of X value?
Cheers</p>
| 0 | 2016-10-02T22:07:57Z | 39,822,317 | <p>The reason for this unexpected behavior is that X_perm is not an array that is independent of X. X_perm is a reference to X. So modifications to X_perm are also modifications made to X.</p>
<p>To demonstrate this:</p>
<pre><code>import numpy as np
a = np.arange(16)
print a
b = a # as your X_perm = X
print b # same as print a above
b[0] = -999
print a # has been modified
print b # has been modified
a[-1] = -999
print a # has been modified
print b # has been modified
# using copy
a = np.arange(16)
print a
b = a.copy() # b is separate reference to array
print b # same as print a above
b[0] = -999
print a # has NOT been modified
print b # has been modified
a[-1] = -999
print a # has been modified
print b # has NOT been modified
</code></pre>
<p>To do what you want, you need to X_perm to be a copy of X.</p>
<pre><code>X_perm = X.copy()
</code></pre>
<p>See also <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html" rel="nofollow">this relevant numpy doc on copy</a></p>
| 0 | 2016-10-02T22:20:58Z | [
"python",
"numpy"
]
|
Flask Testing - How to retrieve variables that were passed to Jinja? | 39,822,265 | <p>In Flask, how can I test what variables were returned to a Jinja template with <code>render_template</code>?</p>
<pre><code>@app.route('/foo/'):
def foo():
return render_template('foo.html', foo='bar')
</code></pre>
<p>In this example, I want to test that <code>foo</code> is equal to <code>"bar"</code>. </p>
<pre><code>import unittest
from app import app
class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
r = c.get('/foo/')
# Prove that the foo variable is equal to "bar"
</code></pre>
<p>How can I do this?</p>
| 2 | 2016-10-02T22:13:37Z | 39,822,401 | <p>The best way will be to use something like that:</p>
<pre><code>self.assertTrue('Hello bar!' in r.body)
</code></pre>
<p>And in <code>foo.html</code>:</p>
<pre><code><div>Hello {{ foo }}!</div>
</code></pre>
<p>Of course I don't know structure of your html, so this example above is just a prototype.</p>
| 0 | 2016-10-02T22:30:59Z | [
"python",
"flask"
]
|
Flask Testing - How to retrieve variables that were passed to Jinja? | 39,822,265 | <p>In Flask, how can I test what variables were returned to a Jinja template with <code>render_template</code>?</p>
<pre><code>@app.route('/foo/'):
def foo():
return render_template('foo.html', foo='bar')
</code></pre>
<p>In this example, I want to test that <code>foo</code> is equal to <code>"bar"</code>. </p>
<pre><code>import unittest
from app import app
class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
r = c.get('/foo/')
# Prove that the foo variable is equal to "bar"
</code></pre>
<p>How can I do this?</p>
| 2 | 2016-10-02T22:13:37Z | 39,822,423 | <p>This can be done using <a href="http://flask.pocoo.org/docs/0.11/signals/" rel="nofollow">signals</a>. I will reproduce the code snippit here:</p>
<pre>
import unittest
from app import app
from flask import template_rendered
from contextlib import contextmanager
@contextmanager
def captured_templates(app):
recorded = []
def record(sender, template, context, **extra):
recorded.append((template, context))
template_rendered.connect(record, app)
try:
yield recorded
finally:
template_rendered.disconnect(record, app)
class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
with captured_templates(app) as templates:
r = c.get('/foo/')
template, context = templates[0]
self.assertEquals(context['foo'], 'bar')
</pre>
<hr>
<p>Here is another implementation that removes the <code>template</code> part and turns it into an iterator.</p>
<pre>
import unittest
from app import app
from flask import template_rendered
from contextlib import contextmanager
@contextmanager
def get_context_variables(app):
recorded = []
def record(sender, template, context, **extra):
recorded.append(context)
template_rendered.connect(record, app)
try:
yield iter(recorded)
finally:
template_rendered.disconnect(record, app)
class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
with get_context_variables(app) as contexts:
r = c.get('/foo/')
context = next(context)
self.assertEquals(context['foo'], 'bar')
r = c.get('/foo/?foo=bar')
context = next(context)
self.assertEquals(context['foo'], 'foo')
# This will raise a StopIteration exception because I haven't rendered
# and new templates
next(context)
</pre>
| 2 | 2016-10-02T22:33:47Z | [
"python",
"flask"
]
|
Tweepy - How to "tag" tweets with their respective tracking filter | 39,822,272 | <p>I'm having a hard time formulating my question, but basically, imagine you're streaming Twitter with Tweepy and filtering the tweets on 2 keywords like that:</p>
<pre><code>twitterStream = Stream(auth, listener())
twitterStream.filter(track=["keyword1", "keyword2"])
</code></pre>
<p>Basically, I would like to append the keywords on their respective tweets, so, for example, I would get something like this:</p>
<pre><code>some tweet about keyword 1 [keyword1]
another tweet about keyword 1 [keyword1]
some tweet about keyword 2 [keyword2]
etc...
</code></pre>
<p>Is this possible?</p>
<p>Thanks!</p>
| 0 | 2016-10-02T22:14:26Z | 39,822,636 | <p>Tweepy use twitter streaming API, from docs of <a href="https://dev.twitter.com/streaming/overview/request-parameters" rel="nofollow">streaming API</a>, I believe its impossible to get result as you expected. Possible solutions are: </p>
<ol>
<li>If you have very limited keywords to track, then for each of these keywords, make a streaming track request.</li>
<li>If you have lots of keywords to track, and you track all of these keywords in one streaming request, then you can perform keyword search on the returned tweets to determine what keywords this tweets containing. Depending one your applications, the search operation may process on many fields of tweet, e.g., text, hashtag, urls and etc.</li>
</ol>
<p>Hope this would be help for. Thanks.</p>
| 0 | 2016-10-02T23:05:52Z | [
"python",
"twitter",
"tweepy"
]
|
numpy multidimensional (3d) matrix multiplication | 39,822,276 | <p>I get two 3d matrix A (32x3x3) and B(32x3x3), and I want to get matrix C with dimension 32x3x3. The calculation can be done using loop like:</p>
<pre><code>a = numpy.random.rand(32, 3, 3)
b = numpy.random.rand(32, 3, 3)
c = numpy.random.rand(32, 3, 3)
for i in range(32):
c[i] = numpy.dot(a[i], b[i])
</code></pre>
<p>I believe there must be a more efficient one-line solution to this problem. Can anybody help, thanks.</p>
| 3 | 2016-10-02T22:14:53Z | 39,822,646 | <p>You could do this using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>:</p>
<pre><code>In [142]: old = orig(a,b)
In [143]: new = np.einsum('ijk,ikl->ijl', a, b)
In [144]: np.allclose(old, new)
Out[144]: True
</code></pre>
<p>One advantage of using <code>einsum</code> is that you can almost read off what it's doing from the indices: leave the first axis alone (<code>i</code>), and perform a matrix multiplication on the last two <code>(jk,kl->jl)</code>).</p>
| 1 | 2016-10-02T23:06:35Z | [
"python",
"matrix",
"multidimensional-array",
"matrix-multiplication"
]
|
add extra value to kwarg list | 39,822,419 | <p>Suppose there is the following external module and its spelled out like this:</p>
<p><strong>module1.py</strong></p>
<pre><code>X = [1,2,3]
def test_func(keyword_list=X):
return keyword_list
test_func()
</code></pre>
<p>In another file I am trying to add another item to the kwarg <code>X</code> where ill be making my call and that will be here:</p>
<p><strong>my_file.py</strong></p>
<pre><code>from module1 import test_func
test_func()
...
</code></pre>
<p>Is there any way concise way of adding an extra list item to my kwarg in my initial call to <code>test_func</code>. I know technically I could something like the following:</p>
<pre><code>from module1 import test_func, X
test_func(keyword_list=X + [4])
[1,2,3,4]
</code></pre>
<p>Is there anyway to do this without importing <code>X</code> directly from <code>module1.py</code>?</p>
<p><strong>Edit</strong> <code>module1.py</code> is an open source module that I can't directly change.</p>
| 0 | 2016-10-02T22:33:19Z | 39,822,474 | <p>It seems one way to enable the scenario would be to have your test_func api take two lists...</p>
<pre><code>def test_func(user_keywords=None, default_keywords=X):
# merge them
# more stuff...
</code></pre>
<p>I am sure there are ways to reflect over the method and get the default args using the <code>inspect</code> module and methods such as <code>inspect.getargspec</code> but that seems like a hassle that can be avoided by accommodating intended use cases in the method signature in the first place.</p>
| 0 | 2016-10-02T22:41:13Z | [
"python"
]
|
add extra value to kwarg list | 39,822,419 | <p>Suppose there is the following external module and its spelled out like this:</p>
<p><strong>module1.py</strong></p>
<pre><code>X = [1,2,3]
def test_func(keyword_list=X):
return keyword_list
test_func()
</code></pre>
<p>In another file I am trying to add another item to the kwarg <code>X</code> where ill be making my call and that will be here:</p>
<p><strong>my_file.py</strong></p>
<pre><code>from module1 import test_func
test_func()
...
</code></pre>
<p>Is there any way concise way of adding an extra list item to my kwarg in my initial call to <code>test_func</code>. I know technically I could something like the following:</p>
<pre><code>from module1 import test_func, X
test_func(keyword_list=X + [4])
[1,2,3,4]
</code></pre>
<p>Is there anyway to do this without importing <code>X</code> directly from <code>module1.py</code>?</p>
<p><strong>Edit</strong> <code>module1.py</code> is an open source module that I can't directly change.</p>
| 0 | 2016-10-02T22:33:19Z | 39,822,478 | <p>Use another keyword arg:</p>
<pre><code>def test_func(keyword_list=[1,2,3,4], additional_list=[]):
return keyword_list + additional_list
print(test_func())
print(test_func(additional_list=[5]))
</code></pre>
<p>Should produce</p>
<pre><code>[1, 2, 3, 4]
[1, 2, 3, 4, 5]
</code></pre>
<p>Or use a wrapper function:</p>
<pre><code>def wrapper_test_func(additional_list=[]):
return test_func(module1.X + additional_list)
</code></pre>
| 1 | 2016-10-02T22:41:27Z | [
"python"
]
|
Plotting a solid cylinder centered on a plane in Matplotlib | 39,822,480 | <p>I fit a plane to a bunch of points in 3d and initially gave it an arbitrary size using np.meshgrid, but now I'm trying to plot a cylinder centered on that plane and oriented the same way (such that the plane fit would cut the height of the cylinder in half), but with a specified radius and height. The only examples of cylinders plotted in matplotlib I can find are hollow and usually open at the top and bottom. I want the one I plot to be solid so I can clearly see what points it's enclosing.</p>
<p>Here's a minimum working example with a randomly generated plane. Since the plane I'm using is always given by a point and a normal vector, the cylinder should be based off of those things as well (plus a provided radius, and height to extend above and below the plane).</p>
<pre><code>from __future__ import division #Enables new-style division
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
import numpy as np
cen_x = 0
cen_y = 0
cen_z = 0
origin = np.array([cen_x,cen_y,cen_z])
normal = np.array([np.random.uniform(-1,1),np.random.uniform(-1,1),np.random.uniform(0,1)])
a = normal[0]
b = normal[1]
c = normal[2]
#equation for a plane is a*x+b*y+c*z+d=0 where [a,b,c] is the normal
#so calculate d from the normal
d = -origin.dot(normal)
# create x,y meshgrid
xx, yy = np.meshgrid(np.arange(cen_x-1,cen_x+1,0.01),np.arange(cen_y-1,cen_y+1,0.01))
# calculate corresponding z
zz = (-a * xx - b * yy - d) * 1./c
halo_x = [-0.3, -0.9, 0.8, 1.3, -0.1, 0.5]
halo_y = [0.8, 1.1, -0.5, -0.7, -1.2, 0.1]
halo_z = [1.0, -0.4, 0.3, -1.2, 0.9, 1.2]
fig = plt.figure(figsize=(9,9))
plt3d = fig.gca(projection='3d')
plt3d.plot_surface(xx, yy, zz, color='r', alpha=0.4)
plt3d.set_xlim3d(cen_x-3,cen_x+3)
plt3d.set_ylim3d(cen_y-3,cen_y+3)
plt3d.set_zlim3d(cen_z-3,cen_z+3)
plt3d.set_xlabel('X')
plt3d.set_ylabel('Y')
plt3d.set_zlabel('Z')
plt.show()
</code></pre>
| 0 | 2016-10-02T22:41:32Z | 39,823,124 | <p>I have modified a solution to a question <a href="http://stackoverflow.com/questions/38076682/how-to-add-colors-to-each-individual-face-of-a-cylinder-using-matplotlib">How to add colors to each individual face of a cylinder using matplotlib</a>, removing the fancy shading and adding end caps. If you want to show the enclosed points, you can use <code>alpha=0.5</code> or some such to make the cylinder semi-transparent.</p>
<p>The orientation of the cylinder is defined by a unit vector v with length mag, which could be the normal to your surface.</p>
<pre><code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 2 18:33:10 2016
Modified from http://stackoverflow.com/questions/38076682/how-to-add-colors-to-each-individual-face-of-a-cylinder-using-matplotlib
to add "end caps" and to undo fancy coloring.
@author: astrokeat
"""
import numpy as np
from matplotlib import pyplot as plt
from scipy.linalg import norm
#axis and radius
p0 = np.array([1, 3, 2]) #point at one end
p1 = np.array([8, 5, 9]) #point at other end
R = 5
#vector in direction of axis
v = p1 - p0
#find magnitude of vector
mag = norm(v)
#unit vector in direction of axis
v = v / mag
#make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (v == not_v).all():
not_v = np.array([0, 1, 0])
#make vector perpendicular to v
n1 = np.cross(v, not_v)
#normalize n1
n1 /= norm(n1)
#make unit vector perpendicular to v and n1
n2 = np.cross(v, n1)
#surface ranges over t from 0 to length of axis and 0 to 2*pi
t = np.linspace(0, mag, 2)
theta = np.linspace(0, 2 * np.pi, 100)
rsample = np.linspace(0, R, 2)
#use meshgrid to make 2d arrays
t, theta2 = np.meshgrid(t, theta)
rsample,theta = np.meshgrid(rsample, theta)
#generate coordinates for surface
# "Tube"
X, Y, Z = [p0[i] + v[i] * t + R * np.sin(theta2) * n1[i] + R * np.cos(theta2) * n2[i] for i in [0, 1, 2]]
# "Bottom"
X2, Y2, Z2 = [p0[i] + rsample[i] * np.sin(theta) * n1[i] + rsample[i] * np.cos(theta) * n2[i] for i in [0, 1, 2]]
# "Top"
X3, Y3, Z3 = [p0[i] + v[i]*mag + rsample[i] * np.sin(theta) * n1[i] + rsample[i] * np.cos(theta) * n2[i] for i in [0, 1, 2]]
ax=plt.subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, color='blue')
ax.plot_surface(X2, Y2, Z2, color='blue')
ax.plot_surface(X3, Y3, Z3, color='blue')
plt.show()
</code></pre>
<p>The result:</p>
<p><a href="http://i.stack.imgur.com/a8Jum.png" rel="nofollow"><img src="http://i.stack.imgur.com/a8Jum.png" alt="Cylinder with end caps."></a></p>
| 1 | 2016-10-03T00:31:03Z | [
"python",
"matplotlib",
"plot",
"3d",
"plane"
]
|
Using textwrap.dedent() with bytes in Python 3 | 39,822,598 | <p>When I use a triple-quoted multiline string in Python, I tend to use textwrap.dedent to keep the code readable, with good indentation:</p>
<pre><code>some_string = textwrap.dedent("""
First line
Second line
...
""").strip()
</code></pre>
<p>However, in Python 3.x, textwrap.dedent doesn't seem to work with byte strings. I encountered this while writing a unit test for a method that returned a long multiline byte string, for example:</p>
<pre><code># The function to be tested
def some_function():
return b'Lorem ipsum dolor sit amet\n consectetuer adipiscing elit'
# Unit test
import unittest
import textwrap
class SomeTest(unittest.TestCase):
def test_some_function(self):
self.assertEqual(some_function(), textwrap.dedent(b"""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""").strip())
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>In Python 2.7.10 the above code works fine, but in Python 3.4.3 it fails:</p>
<pre class="lang-none prettyprint-override"><code>E
======================================================================
ERROR: test_some_function (__main__.SomeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 16, in test_some_function
""").strip())
File "/usr/lib64/python3.4/textwrap.py", line 416, in dedent
text = _whitespace_only_re.sub('', text)
TypeError: can't use a string pattern on a bytes-like object
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
</code></pre>
<p>So: <strong>Is there an alternative to textwrap.dedent that works with byte strings?</strong></p>
<ul>
<li>I could write such a function myself, but if there is an existing function, I'd prefer to use it.</li>
<li>I could convert to unicode, use textwrap.dedent, and convert back to bytes. But this is only viable if the byte string conforms to some Unicode encoding.</li>
</ul>
| 1 | 2016-10-02T22:59:05Z | 39,824,050 | <p>Answer 1: Triple-quoted multiline strings (and dedent) are a convenience (sometimes), not a necessity. You can instead write a separate bytes literal ending with b'\n' for each line and let the parser join them. Example:</p>
<pre><code>>>> b = (
b'Lorem ipsum dolor sit amet\n' # first line
b'consectetuer adipiscing elit\n' # 2nd line
)
>>> b
b'Lorem ipsum dolor sit amet\nconsectetuer adipiscing elit\n'
</code></pre>
<p>I intentionally added whitespace and comments to the code that are not wanted in the resulting bytes, to should that they are not included. I sometimes do the equivalent of the above with text strings.</p>
<p>Answer 2: Convert textwrap.dedent to process byte (see separate answer)</p>
<p>Answer 3: Omit the <code>b</code> prefix and add <code>.encode()</code> before or after <code>.strip()</code>.</p>
<pre><code>print(textwrap.dedent("""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""").encode())
# prints (same as Answer 2).
b'\nLorem ipsum dolor sit amet\n consectetuer adipiscing elit\n'
</code></pre>
| 0 | 2016-10-03T03:03:23Z | [
"python",
"python-3.x",
"indentation",
"literals",
"python-unicode"
]
|
Using textwrap.dedent() with bytes in Python 3 | 39,822,598 | <p>When I use a triple-quoted multiline string in Python, I tend to use textwrap.dedent to keep the code readable, with good indentation:</p>
<pre><code>some_string = textwrap.dedent("""
First line
Second line
...
""").strip()
</code></pre>
<p>However, in Python 3.x, textwrap.dedent doesn't seem to work with byte strings. I encountered this while writing a unit test for a method that returned a long multiline byte string, for example:</p>
<pre><code># The function to be tested
def some_function():
return b'Lorem ipsum dolor sit amet\n consectetuer adipiscing elit'
# Unit test
import unittest
import textwrap
class SomeTest(unittest.TestCase):
def test_some_function(self):
self.assertEqual(some_function(), textwrap.dedent(b"""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""").strip())
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>In Python 2.7.10 the above code works fine, but in Python 3.4.3 it fails:</p>
<pre class="lang-none prettyprint-override"><code>E
======================================================================
ERROR: test_some_function (__main__.SomeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 16, in test_some_function
""").strip())
File "/usr/lib64/python3.4/textwrap.py", line 416, in dedent
text = _whitespace_only_re.sub('', text)
TypeError: can't use a string pattern on a bytes-like object
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
</code></pre>
<p>So: <strong>Is there an alternative to textwrap.dedent that works with byte strings?</strong></p>
<ul>
<li>I could write such a function myself, but if there is an existing function, I'd prefer to use it.</li>
<li>I could convert to unicode, use textwrap.dedent, and convert back to bytes. But this is only viable if the byte string conforms to some Unicode encoding.</li>
</ul>
| 1 | 2016-10-02T22:59:05Z | 39,841,195 | <p>Answer 2: <code>textwrap</code> is primarily about the <code>Textwrap</code> class and functions. <code>dedent</code> is listed under </p>
<pre><code># -- Loosely related functionality --------------------
</code></pre>
<p>As near as I can tell, the <em>only</em> things that makes it text (unicode <code>str</code>) specific are the re literals. I prefixed all 6 with <code>b</code> and voila! (I did not edit anything else, but the function docstring should be adjusted.)</p>
<pre><code>import re
_whitespace_only_re = re.compile(b'^[ \t]+$', re.MULTILINE)
_leading_whitespace_re = re.compile(b'(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
def dedent_bytes(text):
"""Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, but they
are not equal: the lines " hello" and "\\thello" are
considered to have no common leading whitespace. (This behaviour is
new in Python 2.5; older versions of this module incorrectly
expanded tabs before searching for common leading whitespace.)
"""
# Look for the longest leading string of spaces and tabs common to
# all lines.
margin = None
text = _whitespace_only_re.sub(b'', text)
indents = _leading_whitespace_re.findall(text)
for indent in indents:
if margin is None:
margin = indent
# Current line more deeply indented than previous winner:
# no change (previous winner is still on top).
elif indent.startswith(margin):
pass
# Current line consistent with and no deeper than previous winner:
# it's the new winner.
elif margin.startswith(indent):
margin = indent
# Find the largest common whitespace between current line
# and previous winner.
else:
for i, (x, y) in enumerate(zip(margin, indent)):
if x != y:
margin = margin[:i]
break
else:
margin = margin[:len(indent)]
# sanity check (testing/debugging only)
if 0 and margin:
for line in text.split(b"\n"):
assert not line or line.startswith(margin), \
"line = %r, margin = %r" % (line, margin)
if margin:
text = re.sub(rb'(?m)^' + margin, b'', text)
return text
print(dedent_bytes(b"""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""")
)
# prints
b'\nLorem ipsum dolor sit amet\n consectetuer adipiscing elit\n'
</code></pre>
| 1 | 2016-10-03T22:09:46Z | [
"python",
"python-3.x",
"indentation",
"literals",
"python-unicode"
]
|
Using textwrap.dedent() with bytes in Python 3 | 39,822,598 | <p>When I use a triple-quoted multiline string in Python, I tend to use textwrap.dedent to keep the code readable, with good indentation:</p>
<pre><code>some_string = textwrap.dedent("""
First line
Second line
...
""").strip()
</code></pre>
<p>However, in Python 3.x, textwrap.dedent doesn't seem to work with byte strings. I encountered this while writing a unit test for a method that returned a long multiline byte string, for example:</p>
<pre><code># The function to be tested
def some_function():
return b'Lorem ipsum dolor sit amet\n consectetuer adipiscing elit'
# Unit test
import unittest
import textwrap
class SomeTest(unittest.TestCase):
def test_some_function(self):
self.assertEqual(some_function(), textwrap.dedent(b"""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""").strip())
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>In Python 2.7.10 the above code works fine, but in Python 3.4.3 it fails:</p>
<pre class="lang-none prettyprint-override"><code>E
======================================================================
ERROR: test_some_function (__main__.SomeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 16, in test_some_function
""").strip())
File "/usr/lib64/python3.4/textwrap.py", line 416, in dedent
text = _whitespace_only_re.sub('', text)
TypeError: can't use a string pattern on a bytes-like object
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
</code></pre>
<p>So: <strong>Is there an alternative to textwrap.dedent that works with byte strings?</strong></p>
<ul>
<li>I could write such a function myself, but if there is an existing function, I'd prefer to use it.</li>
<li>I could convert to unicode, use textwrap.dedent, and convert back to bytes. But this is only viable if the byte string conforms to some Unicode encoding.</li>
</ul>
| 1 | 2016-10-02T22:59:05Z | 39,841,424 | <p>It seems like <code>dedent</code> does not support bytestrings, sadly. However, if you want cross-compatible code, I recommend you take advantage of the <a href="http://pythonhosted.org/six/" rel="nofollow"><code>six</code></a> library:</p>
<pre><code>import sys, unittest
from textwrap import dedent
import six
def some_function():
return b'Lorem ipsum dolor sit amet\n consectetuer adipiscing elit'
class SomeTest(unittest.TestCase):
def test_some_function(self):
actual = some_function()
expected = six.b(dedent("""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""")).strip()
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>This is <em>similar</em> to your bullet point suggestion in the question</p>
<blockquote>
<p>I could convert to unicode, use textwrap.dedent, and convert back to bytes. But this is only viable if the byte string conforms to some Unicode encoding.</p>
</blockquote>
<p>But you're misunderstanding something about encodings here - if you can write the string literal in your test like that in the first place, and have the file successfully parsed by python (i.e. the correct coding declaration is on the module), then there is no "convert to unicode" step here. The file gets parsed in the encoding specified (or <code>sys.defaultencoding</code>, if you didn't specify) and then when the string is a python variable it is already decoded. </p>
| 1 | 2016-10-03T22:30:47Z | [
"python",
"python-3.x",
"indentation",
"literals",
"python-unicode"
]
|
Import error: No module named Include in Python Django | 39,822,605 | <p>I am a beginner in Python. The Python version is 2.7. When I run the below command </p>
<pre><code>(test) C:\virtualenvs\test> python manage.py runserver
</code></pre>
<p>under a virtual environment I get an error saying </p>
<pre><code>File "C:\virtualenvs\test\lib\site-packages\django\apps\config.py", line 90, in create
Module = import_module(entry)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module__import__(name)
ImportError: no module named Include
</code></pre>
<p>Any help is highly appreciated.</p>
| 0 | 2016-10-02T23:01:42Z | 39,823,908 | <p>You have not provided any code, if I was to assume, then I would say you haven't imported <code>include</code> in your urls.py:</p>
<pre><code>from django.conf.urls import include
</code></pre>
<p>Add the above in your urls.py and see what happens.</p>
| 0 | 2016-10-03T02:41:33Z | [
"python",
"django"
]
|
Python: how to create a positive test for procedures? | 39,822,639 | <p>I have a class with some <code>@staticmethod</code>'s that are procedures, thus they do not return anything / their return type is <code>None</code>.</p>
<p>If they fail during their execution, they throw an <code>Exception</code>.</p>
<p>I want to <code>unittest</code> this class, but I am struggling with designing positive tests.</p>
<p>For negative tests this task is easy:</p>
<pre><code>assertRaises(ValueError, my_static_method(*args))
assertRaises(MyCustomException, my_static_method(*args))
</code></pre>
<p>...but how do I create positive tests? Should I redesign my procedures to always return <code>True</code> after execution, so that I can use <code>assertTrue</code> on them?</p>
| 2 | 2016-10-02T23:05:59Z | 39,822,709 | <p>If your methods do something, then I'm sure there should be a logic there. Let's consider this dummy example:</p>
<pre><code>cool = None
def my_static_method(something):
try:
cool = int(something)
except ValueError:
# logs here
</code></pre>
<p>for negative test we have:</p>
<pre><code>assertRaises(ValueError, my_static_method(*args))
</code></pre>
<p>and for possitive test we can check cool:</p>
<pre><code>assertIsNotNone(cool)
</code></pre>
<p>So you're checking if invoking <code>my_static_method</code> affects on <code>cool</code>.</p>
| 1 | 2016-10-02T23:17:11Z | [
"python",
"unit-testing",
"static-methods",
"assert",
"procedure"
]
|
Python: how to create a positive test for procedures? | 39,822,639 | <p>I have a class with some <code>@staticmethod</code>'s that are procedures, thus they do not return anything / their return type is <code>None</code>.</p>
<p>If they fail during their execution, they throw an <code>Exception</code>.</p>
<p>I want to <code>unittest</code> this class, but I am struggling with designing positive tests.</p>
<p>For negative tests this task is easy:</p>
<pre><code>assertRaises(ValueError, my_static_method(*args))
assertRaises(MyCustomException, my_static_method(*args))
</code></pre>
<p>...but how do I create positive tests? Should I redesign my procedures to always return <code>True</code> after execution, so that I can use <code>assertTrue</code> on them?</p>
| 2 | 2016-10-02T23:05:59Z | 39,827,425 | <p>Without seeing the actual code it is hard to guess, however I will make some assumptions:</p>
<ol>
<li>The logic in the static methods is deterministic. </li>
<li>After doing some calculation on the input value there is a result
and some operation is done with this result. </li>
<li>python3.4 (mock has evolved and moved over the last few versions)</li>
</ol>
<p>In order to test code one has to check that at least in the end it produces the expected results. If there is no return value then the result is usually stored or send somewhere. In this case we can check that the method that stores or sends the result is called with the expected arguments.</p>
<p>This can be done with the tools available in the <code>mock</code> package that has become part of the <code>unittest</code> package.</p>
<p>e.g. the following static method in <code>my_package/my_module.py</code>:</p>
<pre><code>import uuid
class MyClass:
@staticmethod
def my_procedure(value):
if isinstance(value, str):
prefix = 'string'
else:
prefix = 'other'
with open('/tmp/%s_%s' % (prefix, uuid.uuid4()), 'w') as f:
f.write(value)
</code></pre>
<p>In the unit test I will check the following:</p>
<ol>
<li><code>open</code> has been called.</li>
<li>The expected file name has been calculated.</li>
<li><code>open</code>has been called in <code>write</code> mode.</li>
<li>The <code>write()</code> method of the file handle has been called with the expected argument.</li>
</ol>
<p>Unittest:</p>
<pre><code>import unittest
from unittest.mock import patch
from my_package.my_module import MyClass
class MyClassTest(unittest.TestCase):
@patch('my_package.my_module.open', create=True)
def test_my_procedure(self, open_mock):
write_mock = open_mock.return_value.write
MyClass.my_procedure('test')
self.assertTrue(open_mock.call_count, 1)
file_name, mode = open_mock.call_args[0]
self.assertTrue(file_name.startswith('/tmp/string_'))
self.assertEqual(mode, 'w')
self.assertTrue(write_mock.called_once_with('test'))
</code></pre>
| 1 | 2016-10-03T08:33:17Z | [
"python",
"unit-testing",
"static-methods",
"assert",
"procedure"
]
|
Turtle and draw a tree with Transcrypt | 39,822,733 | <p>today I want draw a tree in browser with Transcrypt.
I have code in Python which is work in Skulpt:</p>
<pre><code>import random
import turtle
def tree(size, myTurtle):
myTurtle.pensize(size / 20)
if size < random.randint(1,2) * 20:
myTurtle.color("green")
else:
myTurtle.color("brown")
if size > 5:
myTurtle.forward(size)
myTurtle.left(25)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.right(50)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.left(25)
myTurtle.penup()
myTurtle.backward(size)
myTurtle.pendown()
window = turtle.Screen()
window.setup(800,600)
window.bgcolor("white")
myTurtle = turtle.Turtle()
myTurtle.color("brown", "blue")
myTurtle.left(90)
myTurtle.speed(0)
myTurtle.penup()
myTurtle.setpos(0, -250)
myTurtle.pendown()
</code></pre>
<p>And I want to run it in browser to get this effect:</p>
<p><a href="http://i.stack.imgur.com/NpcHB.png" rel="nofollow"><img src="http://i.stack.imgur.com/NpcHB.png" alt="image"></a>
âDon't worry about text over the tree, is in polish ;)
I run this in Skulpt, maybe you hear about it, effect you have above.
Now I want to run this in Transcrypt and compare it to Skulpt and Brython.</p>
<p>As you can see here:
<a href="http://www.transcrypt.org/live/turtle_site/turtle_site.html" rel="nofollow">http://www.transcrypt.org/live/turtle_site/turtle_site.html</a></p>
<p>Transcrypt somehow can draw with turtle.</p>
<p>What change in this code, to work with Transcrypt?</p>
<p>Can you help me with this?</p>
| 2 | 2016-10-02T23:20:54Z | 39,823,845 | <p>First: you need some modification in code because some functions in <code>Transcrypt</code> have different names or don't exist. You have to add <code>turtle.done()</code> to dislay result.</p>
<p><strong>turtle_tree.py</strong></p>
<pre><code>import random
import turtle
def tree(size, myTurtle):
myTurtle.pensize(size / 20)
if size < random.randint(1,2) * 20:
myTurtle.color("green")
else:
myTurtle.color("brown")
if size > 5:
myTurtle.forward(size)
myTurtle.left(25)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.right(50)
tree(size - random.randint(10, 20), myTurtle)
myTurtle.left(25)
myTurtle.up() # penup()
myTurtle.back(size) # backward(size)
myTurtle.down() # pendown()
#window = turtle.Screen() # doesn't exists
#window.setup(800,600) # doesn't exists
#window.bgcolor("white") # doesn't exists
myTurtle = turtle.Turtle()
myTurtle.color("brown", "blue")
myTurtle.left(90)
myTurtle.speed(0)
myTurtle.up() # penup()
myTurtle.goto(0, 250) # setpos(0, -250)
myTurtle.down() # pendown()
tree(135, myTurtle)
myTurtle.done() # display
</code></pre>
<p>Install <code>Transcrypt</code> using <code>pip</code></p>
<pre><code>pip install transcrypt
</code></pre>
<p>Compile Python into JavaScript</p>
<pre><code>transcrypt turtle_tree.py
</code></pre>
<p>You get folder <code>__javascript__</code> with file <code>turtle_tree.js</code> (and <code>turtle_tree.min.js</code>, <code>turtle_tree.mod.js</code> but you don't need it now) </p>
<p>You need HTML file which loads <code>turtle_tree.js</code> and has <code><div id="__turtlegraph__"></code> to display result.</p>
<p><strong>turtle_tree.html</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Turtle Tree</title>
<style>
#__turtlegraph__ {
height: 600px;
width: 800px;
}
</style>
</head>
<body>
<div id="__turtlegraph__"></div>
<script src='turtle_tree.js'></script>
</body>
</html>
</code></pre>
<p>Put HTML file in <code>__javascript__</code> folder and open it in browser.</p>
<hr>
<p>Tested on Python 3.5.2 / Linux Mint 17.3 / Firefox 48.0 - it draws in 1 second (or less).</p>
<p><a href="http://i.stack.imgur.com/sh3Fe.png" rel="nofollow"><img src="http://i.stack.imgur.com/sh3Fe.png" alt="enter image description here"></a></p>
| 2 | 2016-10-03T02:30:11Z | [
"python",
"transcrypt"
]
|
Remove last digit from a numeric value in a column if only the value has 4 digits | 39,822,752 | <p>I would like to remove the last digit from a numeric field/value from an entire column only if the value has 4 digits either using SQL or Python.
Example:
Column name is Credit Score
Table name is T1
Example values are 888 and 8880, I would like to remove any values with 0 at the end but only if has 4 digits, as some values are like 740 and 7400.</p>
<p>Thank you,</p>
| 0 | 2016-10-02T23:25:14Z | 39,822,765 | <p>I think you can just <code>update</code> the column dividing the existing value by 10 if it is >= 1000 and ends in a 0.</p>
<pre><code>update tablename
set credit_score = credit_score/10
where credit_score >= 1000 and credit_score%10 = 0
</code></pre>
| 1 | 2016-10-02T23:27:38Z | [
"python",
"sql",
"sql-server",
"azure"
]
|
Remove last digit from a numeric value in a column if only the value has 4 digits | 39,822,752 | <p>I would like to remove the last digit from a numeric field/value from an entire column only if the value has 4 digits either using SQL or Python.
Example:
Column name is Credit Score
Table name is T1
Example values are 888 and 8880, I would like to remove any values with 0 at the end but only if has 4 digits, as some values are like 740 and 7400.</p>
<p>Thank you,</p>
| 0 | 2016-10-02T23:25:14Z | 39,890,739 | <p>I tried to implement your needs on SQL Azure, please try to use the sql below.</p>
<pre><code>update tablename
set credit_score = cast(replace(rtrim(replace(cast(credit_score as varchar), '0', ' ')), ' ', '0') as int)
where credit_score >= 1000
</code></pre>
<p>For example: 7400 => 74, 70400 => 704</p>
| 0 | 2016-10-06T08:05:47Z | [
"python",
"sql",
"sql-server",
"azure"
]
|
Python Nested Loops To Print Rectangle With Asterisks | 39,822,774 | <p>Write nested loops to print a rectangle. Sample output for given program:</p>
<p>3 stars : ***</p>
<p>3 stars : ***</p>
<p>I tried it and ended up with this:</p>
<pre><code>num_rows = 2
num_cols = 3
'''IDK WHAT TO PUT HERE'''
print('*', end=' ')
print('')
</code></pre>
<p>Any help would be appreciated! Thanks!</p>
| -3 | 2016-10-02T23:29:57Z | 39,822,887 | <p>You're trying to learn, I think, so a here is a hint to push you in the right direction.</p>
<p>You need to use a nested <code>for</code> loop. Use the <a href="https://docs.python.org/3/library/functions.html#func-range" rel="nofollow"><code>range()</code></a> builtin to produce an iterable sequence.</p>
<p>The outer for loop should iterate over the number of rows. The inner (nested) for loop should iterate over the columns.</p>
| 0 | 2016-10-02T23:48:45Z | [
"python",
"nested-loops"
]
|
ipithon notebook doesn't work | 39,822,793 | <p>I follow instruction and run ipython.exe notebook:</p>
<pre><code>> [TerminalIPythonApp] WARNING | Subcommand `ipython notebook` is
> deprecated and will be removed in future versions.
> [TerminalIPythonApp] WARNING | You likely want to use `jupyter
> notebook` in the future Traceback (most recent call last): File
> "C:\Miniconda3\Scripts\ipython-script.py", line 5, in <module>
> sys.exit(IPython.start_ipython()) File "C:\Miniconda3\lib\site-packages\IPython\__init__.py", line 119, in
> start_ipython
> return launch_new_instance(argv=argv, **kwargs) File "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 657, in launch_instance
> app.initialize(argv) File "<decorator-gen-110>", line 2, in initialize File
> "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 87, in catch_config_error
> return method(app, *args, **kwargs) File "C:\Miniconda3\lib\site-packages\IPython\terminal\ipapp.py", line 300,
> in initialize
> super(TerminalIPythonApp, self).initialize(argv) File "<decorator-gen-7>", line 2, in initialize File
> "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 87, in catch_config_error
> return method(app, *args, **kwargs) File "C:\Miniconda3\lib\site-packages\IPython\core\application.py", line
> 446, in initialize
> self.parse_command_line(argv) File "C:\Miniconda3\lib\site-packages\IPython\terminal\ipapp.py", line 295,
> in parse_command_line
> return super(TerminalIPythonApp, self).parse_command_line(argv) File "<decorator-gen-4>", line 2, in parse_command_line File
> "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 87, in catch_config_error
> return method(app, *args, **kwargs) File "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 514, in parse_command_line
> return self.initialize_subcommand(subc, subargv) File "C:\Miniconda3\lib\site-packages\IPython\core\application.py", line
> 236, in initialize_subcommand
> return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv) File "<decorator-gen-3>",
> line 2, in initialize_subcommand File
> "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 87, in catch_config_error
> return method(app, *args, **kwargs) File "C:\Miniconda3\lib\site-packages\traitlets\config\application.py",
> line 445, in initialize_subcommand
> subapp = import_item(subapp) File "C:\Miniconda3\lib\site-packages\ipython_genutils\importstring.py",
> line 31, in import_item
> module = __import__(package, fromlist=[obj]) ImportError: No module named 'notebook'
</code></pre>
<p>Now if I run jupyter notebook, I get:</p>
<blockquote>
<p>C:\Miniconda3\Scripts>jupyter notebook Traceback (most recent call
last): File "C:\Miniconda3\Scripts\jupyter-script.py", line 5, in
sys.exit(jupyter_core.command.main()) File "C:\Miniconda3\lib\site-packages\jupyter_core\command.py", line 186,
in main
_execvp(command, sys.argv[1:]) File "C:\Miniconda3\lib\site-packages\jupyter_core\command.py", line 104,
in _execvp
raise OSError('%r not found' % cmd, errno.ENOENT) OSError: [Errno None not found] 2</p>
</blockquote>
<p>I need to save my work as ipython notebook. How can I do it?</p>
| 0 | 2016-10-02T23:33:07Z | 39,823,664 | <p>Like <code>zwol</code> said, your installation might have gotten screwed up. There are two things you can do.</p>
<ol>
<li>Completely remove your miniconda installation and try again.</li>
<li><p>Create a new environment and install ipython/jupyter there. I would try this first. </p>
<p><code>conda create -n myenv python=3<br>
activate myenv<br>
conda install jupyter<br>
jupyter notebook</code> </p></li>
</ol>
| 1 | 2016-10-03T02:03:43Z | [
"python",
"windows",
"jupyter-notebook",
"miniconda"
]
|
How to get a masked rgba array from a ScalarMappable object | 39,822,915 | <p>The docs for <code>to_rgba</code> state:</p>
<blockquote>
<p>Note: this method assumes the input is well-behaved; it does not check
for anomalies such as x being a masked rgba array, or being an integer
type other than uint8, or being a floating point rgba array with
values outside the 0-1 range.</p>
</blockquote>
<p>But that's exactly what I need: a masked rgba array. The following was adapted from <a href="http://stackoverflow.com/questions/15140072/how-to-map-number-to-color-using-matplotlibs-colormap">this post</a> and gives me the correct values, except the values that are <code>nan</code> (that I make zero on the first line) should be black rgba values in <code>spc_map_color</code> </p>
<pre><code>spc_map[np.isnan(spc_map)] = 0
gradient_range = matplotlib.colors.Normalize(-1.0, 1.0)
cmap = matplotlib.cm.ScalarMappable(
gradient_range, self.cm_type)
spc_map_color = cmap.to_rgba(spc_map, bytes=True)
</code></pre>
<p>So as you can see, the colourmap used is variable, but the rgba value that is returned for values outside the mask (that are <code>nan</code>) should be invariant, i.e. always black.</p>
<p>Answers for how to do this for <code>linearsegmentedcolourmap</code> objects exists <a href="http://stackoverflow.com/questions/18718101/applying-different-color-map-to-mask">here</a> and <a href="http://stackoverflow.com/questions/22548813/python-color-map-but-with-all-zero-values-mapped-to-black">here</a>. But this is done if you want to output the image with <code>imshow</code>. I don't want to do that. I want the rgba values in an array.</p>
<p>I've tried <code>cmap.set_bad(color='black')</code> for instance with cmap as my <code>ScalarMappable</code> above before converting to rgba, but <code>ScalarMappable</code> doesn't have a <code>set_bad</code> function.</p>
<p>I missed something obvious?</p>
<p>You can use
<code>spc_map = np.random.randn(256,256)</code> and then do something like set all values below some value to zero to test solutions you may have</p>
| 0 | 2016-10-02T23:52:59Z | 39,829,476 | <p>Black typically corresponds to [0, 0, 0, 1] in an RGBA array. So just set all masked positions to these values ex post.</p>
<pre><code># get mask of masked array
mask = spc_map.mask
# RGBA array should have one more dimension than spc_map with length 4
spc_map_color[mask] = np.array([0, 0, 0, 1])
</code></pre>
| 0 | 2016-10-03T10:28:29Z | [
"python",
"matplotlib"
]
|
Adding horizontal space between data on a Read only script | 39,822,944 | <p>I need my output to look nice, and it looks very sloppy. </p>
<p>--------Current output---------</p>
<pre><code>Below are the players and their scores
John Doe 120
Sally Smooth 115
</code></pre>
<p>----------End current output----------</p>
<p>My desired output follows</p>
<p>-------Desired output-----------------</p>
<pre><code>Below are the players and their scores
John Doe 120
Sally Smooth 115
</code></pre>
<p>--------End desired output-------------</p>
<p>my current code follows;</p>
<pre><code>def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
print("Below are the players and their scores")
print()
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
main()
</code></pre>
| 3 | 2016-10-02T23:56:15Z | 39,822,961 | <p>Try using the tab character to format your spaces better.</p>
<pre><code>print(name + "\t" + score)
</code></pre>
<p>This should give you something closer to your desired output. But you may need to use two if some names are long.</p>
| 1 | 2016-10-03T00:00:37Z | [
"python",
"readfile"
]
|
Adding horizontal space between data on a Read only script | 39,822,944 | <p>I need my output to look nice, and it looks very sloppy. </p>
<p>--------Current output---------</p>
<pre><code>Below are the players and their scores
John Doe 120
Sally Smooth 115
</code></pre>
<p>----------End current output----------</p>
<p>My desired output follows</p>
<p>-------Desired output-----------------</p>
<pre><code>Below are the players and their scores
John Doe 120
Sally Smooth 115
</code></pre>
<p>--------End desired output-------------</p>
<p>my current code follows;</p>
<pre><code>def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
print("Below are the players and their scores")
print()
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
main()
</code></pre>
| 3 | 2016-10-02T23:56:15Z | 39,823,003 | <p>You can add the names and the scores to a list and then print it as a table as </p>
<pre><code>import numpy as np
name_list = ['jane doe' ,'sally smooth']
score = np.array([[102,],[106,]]) #make a numpy array
row_format ="{:>15}" * (len(name_list))
for name, row in zip(name_list, score):
print(row_format.format(name, *row))
</code></pre>
<p>Note: This depends on str.format() </p>
<p>This code will output:</p>
<pre><code> jane doe 102
sally smooth 106
</code></pre>
| 1 | 2016-10-03T00:05:51Z | [
"python",
"readfile"
]
|
List without negative indexing | 39,822,973 | <p>I am coding a simply discrete system in python which is presented bellow:</p>
<pre><code>class System:
def __init__(self, a, b):
self.a = a
self.b = b
self.y = []
def dynamics(self, signal):
for i in range(len(signal)):
try:
self.y.append(signal[i] - self.a*self.y[i-1] - self.b*self.y[i-2])
except:
try:
self.y.append(signal[i] - self.a*self.y[i-1] - self.b*0)
except:
self.y.append(signal[i] - self.a*0 - self.b*0)
</code></pre>
<p>The class System aims to model the system and the method dynamics to compute the dynamic system evolution through discrete time. I thought that would be a good idea to use the try/except structure to deal with the first steps of the system - in our case the first two steps - in each some previous values of y would be not available. Well, this approach would work, if the list object does not accepted negative index, which is not the case. I know that I could solve this problem with other implementation approaches but, I would like to keep with this one. So, this is my question, how could I create a list object and disable negative indexing. I would appreciate some chunks of code.</p>
<p>Thanks</p>
| 0 | 2016-10-03T00:02:49Z | 39,823,085 | <p>Although I pointed out my reluctance in the comments, I'll play your game.</p>
<pre><code>class PositiveList(list):
def __getitem__(self, ind):
if ind < 0:
raise IndexError("Expected a positive index, instead got {}.".format(ind))
return super(PositiveList, self).__getitem__(ind)
x = PositiveList([1, 2, 3])
print x[-1]
#IndexError: Expected a positive index, instead got -1.
</code></pre>
| 1 | 2016-10-03T00:22:26Z | [
"python",
"list",
"wrap"
]
|
List without negative indexing | 39,822,973 | <p>I am coding a simply discrete system in python which is presented bellow:</p>
<pre><code>class System:
def __init__(self, a, b):
self.a = a
self.b = b
self.y = []
def dynamics(self, signal):
for i in range(len(signal)):
try:
self.y.append(signal[i] - self.a*self.y[i-1] - self.b*self.y[i-2])
except:
try:
self.y.append(signal[i] - self.a*self.y[i-1] - self.b*0)
except:
self.y.append(signal[i] - self.a*0 - self.b*0)
</code></pre>
<p>The class System aims to model the system and the method dynamics to compute the dynamic system evolution through discrete time. I thought that would be a good idea to use the try/except structure to deal with the first steps of the system - in our case the first two steps - in each some previous values of y would be not available. Well, this approach would work, if the list object does not accepted negative index, which is not the case. I know that I could solve this problem with other implementation approaches but, I would like to keep with this one. So, this is my question, how could I create a list object and disable negative indexing. I would appreciate some chunks of code.</p>
<p>Thanks</p>
| 0 | 2016-10-03T00:02:49Z | 39,823,116 | <p>This does what you actually want and is much cleaner. Just keep the latest two y-values in extra variables.</p>
<pre><code>def dynamics(self, signal):
y1 = y2 = 0
for sig in signal:
y1, y2 = sig - self.a * y1 - self.b * y2, y1
self.y.append(y1)
</code></pre>
| 1 | 2016-10-03T00:29:08Z | [
"python",
"list",
"wrap"
]
|
How can I replace the vowels of a word with underscores in python? | 39,823,110 | <p>I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore. </p>
<p>So far this is what I have come up with and it just doesn't work</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:28:34Z | 39,823,134 | <p>Make vowels an array with each element it's own letter.</p>
<p>Then do</p>
<pre><code>for letter in word:
if letter in vowels:
letter = "_"
</code></pre>
| 1 | 2016-10-03T00:32:32Z | [
"python"
]
|
How can I replace the vowels of a word with underscores in python? | 39,823,110 | <p>I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore. </p>
<p>So far this is what I have come up with and it just doesn't work</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:28:34Z | 39,823,140 | <p>Lists can be used to easily build words, and with <code>.join()</code> you can combine the list items into a single string.</p>
<pre><code>word = 'pizza'
vowels = "aeiouy"
new_word = []
for letter in word:
if letter in vowels:
new_word.append('_')
else:
new_word.append(letter)
print(''.join(new_word))
</code></pre>
<p>Here's the same thing in a generator expression:</p>
<pre><code>word = 'pizza'
vowels = "aeiouy"
new_word = ''.join(c if c not in vowels else '_' for c in word)
print(new_word)
</code></pre>
| 1 | 2016-10-03T00:33:33Z | [
"python"
]
|
How can I replace the vowels of a word with underscores in python? | 39,823,110 | <p>I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore. </p>
<p>So far this is what I have come up with and it just doesn't work</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:28:34Z | 39,823,148 | <p>You can use <code>string.translate</code> and <code>maketrans</code>.</p>
<pre><code>from string import maketrans
vowels = "aeiouy"
t = "______"
st = "trying this string"
tran = maketrans(vowels, t)
print st.translate(tran)
# Gives tr__ng th_s str_ng
</code></pre>
<p>You may also want to check uppercases.</p>
| 3 | 2016-10-03T00:34:51Z | [
"python"
]
|
How can I replace the vowels of a word with underscores in python? | 39,823,110 | <p>I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore. </p>
<p>So far this is what I have come up with and it just doesn't work</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:28:34Z | 39,823,163 | <p>you can use regex </p>
<pre><code>import re
print(re.sub("[aeiouAEIOU]", "_", "abc")) # prints _bc
</code></pre>
| 1 | 2016-10-03T00:38:33Z | [
"python"
]
|
How can I replace the vowels of a word with underscores in python? | 39,823,110 | <p>I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore. </p>
<p>So far this is what I have come up with and it just doesn't work</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:28:34Z | 39,823,167 | <p>Using a list comprehension and setting <code>vowels</code> as a <code>set</code> object (this is really only valuable for speeding up performance if you have a large list of words over which you're iterating):</p>
<pre><code>>>> vowels = set("aeiouy")
>>> word = 'ampersand'
>>> new_word = "".join([letter if letter not in vowels else "_" for letter in word])
>>> print(new_word)
_mp_rs_nd
</code></pre>
| 0 | 2016-10-03T00:39:30Z | [
"python"
]
|
How can I replace the vowels of a word with underscores in python? | 39,823,110 | <p>I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore. </p>
<p>So far this is what I have come up with and it just doesn't work</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:28:34Z | 39,823,210 | <p>To answer why your approach didn't work.</p>
<pre><code>if letter != vowels:
</code></pre>
<p>Does not do what you are thinking. It actually compares the letter against a full string <code>"aeiouy"</code>. It will always be unequal (e.g. <code>"a" != "aeiouy"</code> is True and so is any other letter).</p>
<p>More likely what you mean was</p>
<pre><code>if letter in vowels:
</code></pre>
<p>Which under the hood will iterate over <code>vowels</code> and compare each character to <code>letter</code>, returning <code>True</code> if any of the letters match.</p>
<p>The second mistake is here</p>
<pre><code>new_word += word
</code></pre>
<p>You are adding the original word to the new word rather than the letter you just checked. So make that</p>
<pre><code>new_word += letter
</code></pre>
<p>The third thing to note is that your logic is the reverse of what you intended. You wanted to replace vowels with <code>_</code> but your if statement allows vowels into the new word and replaces consonants with the underscore. So if you reverse your if and else clauses.</p>
<p>All up you end up with</p>
<pre><code>word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter in vowels:
new_word += '_'
else:
new_word += letter
print(new_word)
</code></pre>
| 0 | 2016-10-03T00:49:52Z | [
"python"
]
|
Python code for all combinations of part of a list? | 39,823,161 | <p>I have some code set up to where 2 consonants are randomly generated and 2 vowels are randomly generated, and each are assigned to their own individual variable. I used print (itertools.permutations(list)) to show all possible combinations of the 4 letters, with list being the variables of each vowel or consonant, but nothing happened. Is there an easier way to do this? Or am I just doing it wrong? </p>
| -1 | 2016-10-03T00:38:20Z | 39,823,175 | <pre><code>In [34]: L = ['a', 'e', 'b', 'c']
In [35]: for p in itertools.permutations(L): print(''.join(p))
aebc
aecb
abec
abce
aceb
acbe
eabc
eacb
ebac
ebca
ecab
ecba
baec
bace
beac
beca
bcae
bcea
caeb
cabe
ceab
ceba
cbae
cbea
</code></pre>
| 2 | 2016-10-03T00:40:44Z | [
"python",
"random",
"permutation",
"itertools"
]
|
Tweepy api binder and python properties | 39,823,262 | <p>I've been digging around the tweepy source code trying to get a feel for how everything is designed. I'm a little confused with the <code>API</code> class and <code>bind_api</code> function. The tweepy source can be found here: <a href="https://github.com/tweepy/tweepy" rel="nofollow">https://github.com/tweepy/tweepy</a></p>
<p>1) Why is almost every api call a property? What is this actually doing and what benefit does it provide?</p>
<p>2) How is <code>bind_api</code> getting the arguments fed into each api call? For example,</p>
<pre><code>@property
def get_status(self):
""" :reference: https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid
:allowed_param:'id'
"""
return bind_api(
api=self,
path='/statuses/show.json',
payload_type='status',
allowed_param=['id']
)
</code></pre>
<p><code>get_status</code> takes no arguments in its definition, but calling api.get_status(id='123') works fine. I'm curious what is happening here. I assume this relates to my first question.</p>
<p>3) Following this same format tweepy is using with <code>bind_api</code>, how can one get the keyword arguments that are fed to an api call? For example if I want to just print "No id supplied" when no <code>id='value'</code> keyword is supplied to <code>get_status</code>, how would I go about that?</p>
<p>Thanks for any help. Hopefully I was clear enough.</p>
| 0 | 2016-10-03T00:58:55Z | 39,864,421 | <p>I was not thinking when I asked this the other day.</p>
<p><code>bind_api</code> is returning a function. This function is then called when that property is called. That is why each api call is a <code>@property</code> which also answers my second question.</p>
| 0 | 2016-10-05T02:13:13Z | [
"python",
"tweepy"
]
|
Python 'if' statement - if in [string] == 'string' -- Not working? | 39,823,275 | <p>I'm trying to find a letter in a giving string. Here's what I got:</p>
<pre><code> if i in steps == 'u':
y -= pixels_per_move
elif i in [steps] == 'r':
x -= pixels_per_move
</code></pre>
<p>steps is a randomly generated string consisting of u, d, r, l.
So it's something like 'uuurlluddd'</p>
<p>So i'm just looking for those letters in 'steps' but with the code above I'm getting the error </p>
<p>TypeError: 'in ' requires string as left operand, not int</p>
<p>Which I don't understand because steps is not an int, and i've tried putting str() around it in multiple places but same error occurs. What am I doing wrong here?</p>
| 0 | 2016-10-03T01:02:07Z | 39,823,287 | <p>What it is saying is that <code>i</code> is an int. You are testing whether <code>i</code> is in <code>steps</code> which is a string. The mostly likely thing I think you are trying to do is get the <code>ith</code> character of the <code>steps</code> in which case you should use <code>if steps[i] == 'u':</code></p>
| 1 | 2016-10-03T01:04:39Z | [
"python",
"if-statement"
]
|
Python 'if' statement - if in [string] == 'string' -- Not working? | 39,823,275 | <p>I'm trying to find a letter in a giving string. Here's what I got:</p>
<pre><code> if i in steps == 'u':
y -= pixels_per_move
elif i in [steps] == 'r':
x -= pixels_per_move
</code></pre>
<p>steps is a randomly generated string consisting of u, d, r, l.
So it's something like 'uuurlluddd'</p>
<p>So i'm just looking for those letters in 'steps' but with the code above I'm getting the error </p>
<p>TypeError: 'in ' requires string as left operand, not int</p>
<p>Which I don't understand because steps is not an int, and i've tried putting str() around it in multiple places but same error occurs. What am I doing wrong here?</p>
| 0 | 2016-10-03T01:02:07Z | 39,823,376 | <p>You confuse the <code>for i in steps</code> with the <code>if</code> statement. Anyway, it should look something like this:</p>
<pre><code>for i in steps:
if i == "u": #here i isn't a int but a string!
y -= pixels_per_move
elif i == "r":
x -= pixels_per_move
</code></pre>
<p>You could add a <code>print</code> statement to print x and y (optional).</p>
| 1 | 2016-10-03T01:21:15Z | [
"python",
"if-statement"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.