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
Speed up a list operation using threads in python
39,807,058
<p>I have a huge list of proxies (70k) and I have this script:</p> <pre><code>entries = open("proxy.txt").readlines() proxiesp = [x.strip().split(":") for x in entries] proxies = [] for x in proxiesp: x = tuple(x) proxies.append(x) set(proxies) </code></pre> <p>And the operation of set(proxies) so the du...
-1
2016-10-01T13:13:32Z
39,807,263
<p>No, threading won't speed this up, for three reasons:</p> <ol> <li><p>The Python GIL prevents Python code from being executed in parallel; threads executing Python code can only be run concurrently. For the same amount of CPU work, the same amount of time or more is required.</p></li> <li><p>To be able to add to th...
3
2016-10-01T13:34:05Z
[ "python", "multithreading", "list", "python-3.x", "set" ]
Python Selenium CHROMEDRIVER
39,807,281
<p>So I'm currently using chromedriver for selenium with Python, responses are quite slow, so I'm trying to reduce how much chromedriver loads..</p> <p>is there anyway I can remove the address bar, tool bar and most of the gui from chrome its self using chrome arguments?</p>
0
2016-10-01T13:35:22Z
39,807,531
<p>I don't think hiding the address bar and other GUI elements will have any effect. I would like to suggest using PhantomJS, a headless browser without a GUI at all. This will certainly speed up your tests.</p>
1
2016-10-01T14:02:00Z
[ "python", "selenium", "selenium-chromedriver" ]
Why tf.Variable is iterable but can't be iterated
39,807,356
<p>Why this is true:</p> <pre><code>from collections import Iterable import tensorflow as tf v = tf.Variable(1.0) print(isinstance(v, Iterable)) True </code></pre> <p>while this</p> <pre><code>iter(v) </code></pre> <p>gives</p> <pre><code>TypeError: 'Variable' object is not iterable. </code></pre>
0
2016-10-01T13:44:12Z
39,808,194
<p>I found below method in Tensorflow's Variable class: </p> <pre><code>def __iter__(self): """Dummy method to prevent iteration. Do not call. NOTE(mrry): If we register __getitem__ as an overloaded operator, Python will valiantly attempt to iterate over the variable's Tensor from 0 to infinity. Decla...
2
2016-10-01T15:12:57Z
[ "python", "python-2.7", "tensorflow", "iterable" ]
Search for the latest rows in terms of timestamp
39,807,389
<p>I am looking for how to search for the latest rows in hbase table that is loaded by Nutch 2.3. </p> <p>I use happybase and thrift, the only example I have found is in this link <a href="https://happybase.readthedocs.io/en/happybase-0.4/tutorial.html#using-table-namespaces" rel="nofollow">https://happybase.readthedo...
2
2016-10-01T13:47:32Z
39,807,432
<p>I dont know python so Im explaining this in hbase shell.. More or less you should be able to do this in python.</p> <h3>Python way : <a href="http://stackoverflow.com/questions/12458595/convert-timestamp-since-epoch-to-datetime-datetime">Convert timestamp since epoch to datetime.datetime</a></h3> <blockquote> <h...
1
2016-10-01T13:52:31Z
[ "python", "hadoop", "hbase", "nutch", "happybase" ]
Python Threads, why threads in two dimensions aren't work?
39,807,458
<p>I have this script:</p> <pre><code>import threading import time import sys def threadWait(d1, d2): global number time.sleep(1) # My actions number = number+1 # Count of complete actions +1 sys.stdout.write("\033[K") # Clean line to the end. sys.stdout.write(str(number)+" (Thread "+str(d1)+", "+...
0
2016-10-01T13:55:17Z
39,807,747
<p>What do you mean here:</p> <pre><code>for item in dimension1: for items in dimension2: </code></pre> <p>Do you mean:</p> <pre><code>for item in dimension1: for items in item: </code></pre> <p>I suppose you don't want to run threads in [dimension2] every cycle</p>
2
2016-10-01T14:25:55Z
[ "python", "multithreading" ]
Python Threads, why threads in two dimensions aren't work?
39,807,458
<p>I have this script:</p> <pre><code>import threading import time import sys def threadWait(d1, d2): global number time.sleep(1) # My actions number = number+1 # Count of complete actions +1 sys.stdout.write("\033[K") # Clean line to the end. sys.stdout.write(str(number)+" (Thread "+str(d1)+", "+...
0
2016-10-01T13:55:17Z
39,807,760
<p>Your nested loop iterates over something else than you think:</p> <pre><code>for item in dimension1: for items in dimension2: # But I can't do more than 100 Threads at once. </code></pre> <p>Ask yourself a question where is <code>dimension2</code> defined?<br> If you find it hard to figure out, here's ...
2
2016-10-01T14:26:51Z
[ "python", "multithreading" ]
python: check if substring is in tuple of strings
39,807,545
<p>Which is the most elegant way to check if there is an occurrence of several substrings in a tuple of strings?</p> <pre><code>tuple = ('first-second', 'second-third', 'third-first') substr1 = 'first' substr2 = 'second' substr3 = 'third' #if substr1 in tuple and substr2 in tuple and substr3 in tuple: # should r...
2
2016-10-01T14:02:54Z
39,807,561
<pre><code>any(substr in str_ for str_ in tuple_) </code></pre> <p>You can start with that and look at <code>all()</code> as well.</p>
3
2016-10-01T14:04:46Z
[ "python", "substring", "tuples" ]
python: check if substring is in tuple of strings
39,807,545
<p>Which is the most elegant way to check if there is an occurrence of several substrings in a tuple of strings?</p> <pre><code>tuple = ('first-second', 'second-third', 'third-first') substr1 = 'first' substr2 = 'second' substr3 = 'third' #if substr1 in tuple and substr2 in tuple and substr3 in tuple: # should r...
2
2016-10-01T14:02:54Z
39,807,576
<p>You need to iterate over the tuple for each of the substrings, so using <code>any</code> and <code>all</code>:</p> <pre><code>all(any(substr in s for s in data) for substr in ['first', 'second', 'third']) </code></pre>
2
2016-10-01T14:07:06Z
[ "python", "substring", "tuples" ]
How to create Python dictionary with multiple 'lists' for each key by reading from .txt file?
39,807,586
<p>I have a large text file that looks like:</p> <pre><code>1 27 21 22 1 151 24 26 1 48 24 31 2 14 6 8 2 98 13 16 . . . </code></pre> <p>that I want to create a dictionary with. The first number of each list should be the key in the dictionary and should be in this format:</p> <pre><code>{1: [(27...
3
2016-10-01T14:08:22Z
39,807,630
<pre><code>result = {} with open(filetxt, 'r') as f: for line in f: # split the read line based on whitespace idx, c1, c2, c3 = line.split() # setdefault will set default value, if the key doesn't exist and # return the value corresponding to the key. In this case, it returns a list...
4
2016-10-01T14:12:31Z
[ "python", "dictionary" ]
How to create Python dictionary with multiple 'lists' for each key by reading from .txt file?
39,807,586
<p>I have a large text file that looks like:</p> <pre><code>1 27 21 22 1 151 24 26 1 48 24 31 2 14 6 8 2 98 13 16 . . . </code></pre> <p>that I want to create a dictionary with. The first number of each list should be the key in the dictionary and should be in this format:</p> <pre><code>{1: [(27...
3
2016-10-01T14:08:22Z
39,808,018
<p>You are converting your values back to comma separated strings, which you can't use in <code>for first, second, third in data</code> - so just leave them as a list <code>splitLine[1:]</code> (or convert to <code>tuple</code>).<br> You don't need your initializing <code>for</code> loop with a <code>defaultdict</code>...
3
2016-10-01T14:54:32Z
[ "python", "dictionary" ]
How to link inputs to new questions in Python (troubleshooting program)?
39,807,601
<p>I was programming a troubleshooter on python and I have been finding it really hard to link inputs to new questions:</p> <pre><code> Question 1 print("Has your car got a flat tyre? 1. Yes 2. No") choice=input("1/2") if choice == "1": goto (Question 2) #How do I link this input elif choice == "...
0
2016-10-01T14:10:19Z
39,807,763
<p>Python does not support labels and goto. What you should be doing is something like the code below.</p> <pre><code>QUESTION_1 = "Has your car got a flat tyre? 1. Yes 2. No" QUESTION_2 = "Have you taken your car to the petrol station? 1. Yes 2. No" QUESTION_3 = "Has your car recently had an MOT? 1. Yes 2. No" QUESTI...
0
2016-10-01T14:27:37Z
[ "python", "design" ]
Extract Python dictionary from string
39,807,724
<p>I have a string with valid python dictionary inside</p> <pre><code>data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc." </code></pre> <p>I need to extract that dict. I tried with regex but for some reason <code>re.search(r"\{(.*?)\}", data)</code> did not work. Is there any better ...
0
2016-10-01T14:22:55Z
39,807,873
<p>From @AChampion's suggestion.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; import ast &gt;&gt;&gt; x = ast.literal_eval(re.search('({.+})', data).group(0)) &gt;&gt;&gt; x {'Bar': 'value', 'Foo': '1002803'} </code></pre> <p>so the pattern you're looking for is <code>re.search('({.+})', data)</code></p> <p>Yo...
0
2016-10-01T14:40:15Z
[ "python", "regex", "django", "dictionary", "django-views" ]
Extract Python dictionary from string
39,807,724
<p>I have a string with valid python dictionary inside</p> <pre><code>data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc." </code></pre> <p>I need to extract that dict. I tried with regex but for some reason <code>re.search(r"\{(.*?)\}", data)</code> did not work. Is there any better ...
0
2016-10-01T14:22:55Z
39,807,934
<p>Your solution works!</p> <pre><code>In [1]: import re In [2]: data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc." In [3]: a = eval(re.search(r"\{(.*?)\}", data).group(0)) In [4]: a Out[4]: {'Bar': 'value', 'Foo': u'1002803'} </code></pre>
0
2016-10-01T14:46:11Z
[ "python", "regex", "django", "dictionary", "django-views" ]
argmin in dataset containing NaN python
39,807,845
<pre><code> SGSIN VNVUT CNSHK HKHKG JPOSA To MYPKL 1 4 8 9 13 SGSIN NaN 3 7 8 12 VNVUT NaN NaN 3 4 8 CNSHK 1 NaN NaN 1 5 HKHKG NaN NaN NaN NaN 3 </code></pre> <p>Let say we have the above dataset using...
2
2016-10-01T14:37:04Z
39,807,996
<p>You can use numpy's <code>argwhere</code></p> <pre><code>import numpy as np np.argwhere(df['SGSIN'].eq(df['SGSIN'].min())) array([[0], [3]]) </code></pre>
1
2016-10-01T14:52:13Z
[ "python", "pandas", "machine-learning" ]
Startswith with a range of number instead an unit
39,807,907
<pre><code>ip = a list of ips ipf = list(filter(lambda x: x if not x.startswith(str(range(257,311))) else None, ip)) </code></pre> <p>Is is possible to do something like this? I tested it and it doesn't work. I'd like to delete all ips from "ip" list that start with 256. 257. 258. ecc... to 310.</p>
-2
2016-10-01T14:43:45Z
39,807,937
<p>No, <code>str.startswith()</code> doesn't take a range.</p> <p>You'd have to parse out the first part and test it as an integer; filtering is also easier done with a list comprehension:</p> <pre><code>[ip for ip in ip_addresses if 257 &lt;= int(ip.partition('.')[0]) &lt;= 310] </code></pre> <p>The alternative wou...
3
2016-10-01T14:46:21Z
[ "python", "list", "python-3.x", "range", "startswith" ]
Arrow keys no longer work in Python shell after upgrading Mac OS to Sierra
39,807,946
<p>I'm using zsh, iTerm2 (3.0.9), and pyenv (1.0.2) with pyenv global set to 3.5.2.</p> <p>In the Python shell, the up and down arrow keys used to work, to access the previous commands in the history. But now after upgrading to OSX 10.12, instead it shows control characters. For example up arrow displays:</p> <pre><c...
-1
2016-10-01T14:46:59Z
39,834,510
<p>I'm seeing the same thing and the only "fix" I was able to come up with was to not run the <code>pyenv init -</code> command in my .zshrc file. That however will inhibit the functioning of virtual environments.. and so it's not a fix but a workaround to get the python shell history to work again.</p> <p>I'm continu...
0
2016-10-03T14:53:49Z
[ "python", "osx", "zsh", "iterm2", "pyenv" ]
Arrow keys no longer work in Python shell after upgrading Mac OS to Sierra
39,807,946
<p>I'm using zsh, iTerm2 (3.0.9), and pyenv (1.0.2) with pyenv global set to 3.5.2.</p> <p>In the Python shell, the up and down arrow keys used to work, to access the previous commands in the history. But now after upgrading to OSX 10.12, instead it shows control characters. For example up arrow displays:</p> <pre><c...
-1
2016-10-01T14:46:59Z
39,906,060
<p>I had the exact same issue and this command worked for me easy_install -a readline</p> <p>Full credit here: <a href="http://stackoverflow.com/questions/7375545/ipython-complaining-about-readline">ipython complaining about readline</a></p>
1
2016-10-06T21:44:27Z
[ "python", "osx", "zsh", "iterm2", "pyenv" ]
Deleting a list after creating an iterator object from it
39,807,948
<p>I am trying to understand the concept of iterators in python and tried this in Python 3.5.2.</p> <pre><code>x = list(range(1000)) # size of x is 9112 bytes y = iter(x) # size of y is 56 bytes del x x = list(y) # size of x is again 9112 bytes </code></pre> <p>How does the iterator store...
3
2016-10-01T14:47:12Z
39,808,173
<p>Because iterators have enough details stored in them to enable them generate the next element of a sequence without having that "next element" in memory.</p> <p>To understand what is going on let's create our own fake iterator</p> <pre><code>class Fakeiterator: def __init__(self, range_list): self.curr...
2
2016-10-01T15:10:44Z
[ "python", "iterator", "iterable" ]
Deleting a list after creating an iterator object from it
39,807,948
<p>I am trying to understand the concept of iterators in python and tried this in Python 3.5.2.</p> <pre><code>x = list(range(1000)) # size of x is 9112 bytes y = iter(x) # size of y is 56 bytes del x x = list(y) # size of x is again 9112 bytes </code></pre> <p>How does the iterator store...
3
2016-10-01T14:47:12Z
39,808,275
<p>According to what I know, del x does not del the value in the memory since your y is still referring it. It is kind of pointer. x and y is referring to the same memory. </p> <p>when you do del x, python will dereference the x and do garbage collection.</p> <p>while by doing x=list(y), you are pointing the memory t...
1
2016-10-01T15:21:03Z
[ "python", "iterator", "iterable" ]
read Chinese character from excel file python3
39,807,951
<p>I have an Excel file that contains two columns, first one in Chinese and the second is just a link. I tried two methods I found here. but it didn't work and I can't print the value in the console, I changed my encoding variable in settings (pycharm) to U8, still doesn't work. I used Pandas &amp; xlrd libs, both didn...
0
2016-10-01T14:47:27Z
39,813,259
<p>It's not about encoding, you are not access the right rows.</p> <p>On the line 24<br> <code>for row in range(1, number_of_rows):</code></p> <p>why are you want to start with 1 instead of 0.<br> try<code>for row in range(number_of_rows):</code></p>
1
2016-10-02T02:20:52Z
[ "python", "excel" ]
read Chinese character from excel file python3
39,807,951
<p>I have an Excel file that contains two columns, first one in Chinese and the second is just a link. I tried two methods I found here. but it didn't work and I can't print the value in the console, I changed my encoding variable in settings (pycharm) to U8, still doesn't work. I used Pandas &amp; xlrd libs, both didn...
0
2016-10-01T14:47:27Z
39,815,822
<p>Well the problem I had wasn't in reading the Chinese characters actually! my problem we're in printing in console. I thought that the print encoder works fine and I just didn't read it the characters, but this code works fine : </p> <pre><code>from xlrd import open_workbook wb = open_workbook('test.xls') messages ...
0
2016-10-02T09:59:23Z
[ "python", "excel" ]
Python Pandas: Read specific columns from cdv, then reorder
39,807,953
<p>I have a csv which I need to manipulated and write back. I only want specific columns (with header) and re-order them.</p> <p>I use:</p> <pre><code>fields = ['Ticket Number', 'Created', 'Closed', 'CustomerID', 'Customer Realname'] df = pd.read_csv('args.inname', sep=',', skipinitialspace=True, usecols=fields, ...
2
2016-10-01T14:47:50Z
39,808,165
<p>Try this:</p> <pre><code># specify your columns in the order you want to have it in the ouptut file fields = ['Ticket Number', 'Created', 'Closed', 'CustomerID', 'Customer Realname'] df = pd.read_csv('args.inname', sep=',', skipinitialspace=True, usecols=fields)[fields] df = df.rename(columns={'Ticket Number': 'C...
2
2016-10-01T15:10:13Z
[ "python", "pandas" ]
python write file dealing with encode
39,807,985
<p>I'm confused. I need HELP!!! I'm dealing with a file contains Chinese characters,for instance, let's call it <code>a.TEST</code>, and here is what's inside.</p> <pre><code>你好 中国 Hello China 1 2 3 </code></pre> <p>You don't need to understand what the chinese means.(Actually it's 'hello China')</p> <pre><c...
1
2016-10-01T14:51:16Z
39,808,682
<p>In the beginning, there was just english characters, and people was not satisfied.</p> <p>Then they want to display every character in the world.But there is problem. One byte can only represent 255 characters. There just simply not enough place to hold them. </p> <p>Then people decide to use two byte to represent...
1
2016-10-01T16:01:22Z
[ "python", "unicode", "encoding", "utf-8", "character-encoding" ]
python write file dealing with encode
39,807,985
<p>I'm confused. I need HELP!!! I'm dealing with a file contains Chinese characters,for instance, let's call it <code>a.TEST</code>, and here is what's inside.</p> <pre><code>你好 中国 Hello China 1 2 3 </code></pre> <p>You don't need to understand what the chinese means.(Actually it's 'hello China')</p> <pre><c...
1
2016-10-01T14:51:16Z
39,808,990
<h2>What is Encoding</h2> <p>A file consists of bytes. You can represent each byte with a number between 0 and 255 (or 0x00 and 0xFF in hexadecimal).</p> <p>Text is also written as bytes. There is an agreement on the way text is written. That is an encoding. The most basic encoding is ASCII and other encodings are us...
3
2016-10-01T16:34:19Z
[ "python", "unicode", "encoding", "utf-8", "character-encoding" ]
How to access some widget attribute from another widget in Kivy?
39,807,997
<p>Ok let's say I want that label in some widget to use text from label inside another widget:</p> <pre><code>&lt;SubWidget@RelativeLayout&gt;: Label: text: str(root.parent.ids.first.text) &lt;RootWidget&gt;: Label: id: first center_x: 100 text: "text" SubWidget: i...
0
2016-10-01T14:52:14Z
39,808,691
<ol> <li><p>The object property <code>l</code> probably gets populated <strong>after</strong> the first event loop iteration, while you are trying to access it within the first. You could delay it till the second iteration to make it work.</p></li> <li><p>The most powerful approach is to bind those properties from insi...
2
2016-10-01T16:02:21Z
[ "python", "kivy", "kivy-language" ]
Click button (python), having problems with both mechanize and selenium
39,808,006
<p>I'm trying to click the "Coevolution Scores (TXT)" button that pops up after clicking the "Export..." button, however, using a python script <a href="http://polyview.cchmc.org/cgi-bin/coevolve.cgi?JOB=c8a266e0d7ba7cc" rel="nofollow">here</a>, I could not do it either with mechanize nor selenium, using different sele...
-1
2016-10-01T14:53:42Z
39,808,443
<p>The code you are trying to select is inside an <code>&lt;iframe&gt;</code> element. This means that you have to switch frame first before selecting anything that is inside it. This will work:</p> <pre><code>from selenium import webdriver import time from selenium.webdriver.common.by import By url="http://polyview.c...
1
2016-10-01T15:37:28Z
[ "python", "selenium", "mechanize" ]
Is this type of attribute value/function checking, a code smell in Python?
39,808,072
<p><em>note</em>: This is <a href="http://codereview.stackexchange.com/questions/142983/is-this-type-of-attribute-value-function-checking-a-code-smell-in-python">crossposted</a> on CodeReview, as per recommendation</p> <p><strong>Premise</strong>: I have a class hierarchy (Python), where <code>tidy</code> is one of th...
2
2016-10-01T15:00:10Z
39,809,685
<p>I think using the return value from the <code>tidy</code> method is a good way to pass information between your nodes. You're going to call <code>tidy</code> on each of your children anyway, so getting a return value that tells you what to do with that child makes the whole code simpler.</p> <p>You can avoid repeat...
1
2016-10-01T17:45:53Z
[ "python", "typechecking", "duck-typing" ]
make bouncing turtle with python
39,808,240
<p>i am a beginner with python I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering</p> <pre><code>import turtle turtle.shape("circle") xdir = 1 x = 1 y = 1 ydir = 1 while True: x = x + 3 * xdir y = y + 3 * ydir turtle.goto(x , y) if x &gt;= turtle.wi...
2
2016-10-01T15:17:26Z
39,808,329
<p>You need <code>window_width()/2</code> and <code>window_height()/2</code> to keep inside window.</p> <p>ie.</p> <pre><code>if x &gt;= turtle.window_width()/2: xdir = -1 if x &lt;= -turtle.window_width()/2: xdir = 1 if y &gt;= turtle.window_height()/2: ydir = -1 if y &lt;= -turtle.window_height()/2: ...
1
2016-10-01T15:27:08Z
[ "python", "turtle-graphics" ]
make bouncing turtle with python
39,808,240
<p>i am a beginner with python I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering</p> <pre><code>import turtle turtle.shape("circle") xdir = 1 x = 1 y = 1 ydir = 1 while True: x = x + 3 * xdir y = y + 3 * ydir turtle.goto(x , y) if x &gt;= turtle.wi...
2
2016-10-01T15:17:26Z
39,808,515
<p>You should put turtle.penup() Before the while loop to make your code better and a little bit faster. It is almost a bug! </p>
1
2016-10-01T15:44:44Z
[ "python", "turtle-graphics" ]
make bouncing turtle with python
39,808,240
<p>i am a beginner with python I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering</p> <pre><code>import turtle turtle.shape("circle") xdir = 1 x = 1 y = 1 ydir = 1 while True: x = x + 3 * xdir y = y + 3 * ydir turtle.goto(x , y) if x &gt;= turtle.wi...
2
2016-10-01T15:17:26Z
39,809,154
<p>Although your approach to the problem works (my rework):</p> <pre><code>import turtle turtle.shape("circle") turtle.penup() x, y = 0, 0 xdir, ydir = 3, 3 xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2 while True: x = x + xdir y = y + ydir if not -xlimit &lt; x &lt; xlimit: ...
1
2016-10-01T16:48:53Z
[ "python", "turtle-graphics" ]
assign value of variables from Matlab matrix
39,808,429
<p>Coming from a numpy background I had to use Matlab for a new project started a few days ago.</p> <p>Switching to Matlab was really straight forward since the syntax is somehow comparable to numpy's syntax. However, there is one thing I was not able to 'convert' in a satisfying way.</p> <p>In numpy I am able to as...
2
2016-10-01T15:35:47Z
39,808,466
<p>The only way to really do this in MATLAB is to use a <a href="https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html" rel="nofollow">comma-separated list</a> to "distribute" the contents of a cell array to multiple variables. The down-side is that it requires that you first convert your row (a ...
2
2016-10-01T15:40:02Z
[ "python", "arrays", "matlab", "numpy", "matrix" ]
Create local files from a Django web
39,808,462
<p>I have written a Django web run under Linux server, the web is used to read a</p> <p>file path and generate some folders and files on the local machine which browse</p> <p>the web, not sure how to do that, currently it can only generate the files on </p> <p>the server runs the web locally.</p> <p>Does it need to...
-1
2016-10-01T15:39:29Z
39,808,505
<p>Django runs on server and every web server has no access to local (user) computer - it can't create folder on local computer (and it can't steal your files). It can only generate file and user can download it.</p>
1
2016-10-01T15:44:25Z
[ "python", "django" ]
Importing module from string in the Python C API
39,808,521
<p>Importing Python modules from files is relatively easy with the Python C API with <code>pyImport_Import()</code> however I would need to use functions stored in strings. Is there a way to import python modules from strings (to clarify: there is no file; the code is in a string) or will I have to save the strings as ...
0
2016-10-01T15:45:06Z
39,808,548
<p><s>If my understanding is correct, you could use <a href="https://docs.python.org/3/c-api/import.html#c.PyImport_ImportModule" rel="nofollow"><code>PyImport_ImportModule</code></a> which takes a <code>const char* name</code> to specify the module to be imported.</s></p> <p>Since my understanding was incorrect:</p> ...
1
2016-10-01T15:47:53Z
[ "python", "c", "python-c-api", "cross-language" ]
"Redeclared s defined above without usage"
39,808,529
<pre><code>for i in range(10): s = 5 for j in range(10): s = min(s) </code></pre> <p>The above code gives the title of this question as warning in IntelliJ for the second line.</p> <p>I'm pretty sure that the warning happens because in the CFG there are possibly two consecutive writes (without read in...
0
2016-10-01T15:46:17Z
39,808,579
<p>Your hypothesis is nearly correct. The name <code>s</code> was bounded to an integer whose value was never used nor changed in the enclosing loop and yet it is rebounded to another value (<em>although that will raise an error</em>) in the nested loop. Note that the first assignment does not change with any iteration...
0
2016-10-01T15:50:23Z
[ "python", "intellij-idea" ]
implement mat2gray in Opencv with Python
39,808,545
<p>I have the same problem with him: <a href="http://http://stackoverflow.com/questions/27483013/scaling-a-matrix-in-opencv" rel="nofollow">Scaling a matrix in OpenCV</a></p> <p>I got the same problem with him, I have a colored picture, I used matlab to read the picture: <code>Input = imread('input1.jpg');</code>, and...
0
2016-10-01T15:47:51Z
39,808,617
<p>Your input matrix is an integer datatype and your output matrix is defined to be <code>np.uint8</code> (an integer type). By default, <code>cv2.normalize</code> is going to return a result that is the same datatype as the inputs. You'll want to use floating point datatypes if you want output values between <code>0....
2
2016-10-01T15:54:46Z
[ "python", "matlab", "opencv" ]
Find all common N-sized tuples in list of tuples
39,808,550
<p>I have to create an an application that does the following (I have to parse the data only once and store them in a database):</p> <p>I am given K tuples (with K over 1000000) and each tuple is in the form of</p> <pre><code>(UUID, (tuple of N integers)) </code></pre> <p>Lets assume that N equals 20 for every k-tup...
2
2016-10-01T15:48:06Z
39,811,749
<p>It appears that you could put the tuples into the rows of a matrix and make a map from row numbers to UUIDs. Then it's feasible to store all of the tuples in a numpy array since the elements of the tuples are small. numpy has code capable of computing the intersections between rows of such an array. This code genera...
3
2016-10-01T21:45:08Z
[ "python", "algorithm", "sqlite", "numpy" ]
Find all common N-sized tuples in list of tuples
39,808,550
<p>I have to create an an application that does the following (I have to parse the data only once and store them in a database):</p> <p>I am given K tuples (with K over 1000000) and each tuple is in the form of</p> <pre><code>(UUID, (tuple of N integers)) </code></pre> <p>Lets assume that N equals 20 for every k-tup...
2
2016-10-01T15:48:06Z
39,813,183
<p>Bill, I think this creates a more random mix. Your combinations version steps systematically through the choices. With small K the intersection size is close to <code>tupleSize</code>.</p> <pre><code>choices = np.arange(minInt, maxInt) for i in range(K): rows[i,:] = np.random.choice(choices, tupleSize, replac...
2
2016-10-02T02:02:59Z
[ "python", "algorithm", "sqlite", "numpy" ]
Find all common N-sized tuples in list of tuples
39,808,550
<p>I have to create an an application that does the following (I have to parse the data only once and store them in a database):</p> <p>I am given K tuples (with K over 1000000) and each tuple is in the form of</p> <pre><code>(UUID, (tuple of N integers)) </code></pre> <p>Lets assume that N equals 20 for every k-tup...
2
2016-10-01T15:48:06Z
39,813,697
<p>There doesn't appear to be much hope for this: forgetting the <code>combinations()</code> part, you need to check the intersection of every pair of <code>K</code> tuples. There are <code>choose(K, 2) = K*(K-1)/2</code> pairs, so with a million tuples there are nearly 500 billion pairs.</p> <p>One low-level trick ...
2
2016-10-02T03:54:16Z
[ "python", "algorithm", "sqlite", "numpy" ]
I would like to remove the first n colors from a colormap without losing the original number of colours
39,808,565
<pre><code>from matplotlib import cm import seaborn as sns import matplotlib.pyplot as plt </code></pre> <p>Here is the original colormap</p> <pre><code>cmap = [cm.inferno(x)[:3] for x in range(0,256)] sns.palplot(cmap) </code></pre> <p><a href="http://i.stack.imgur.com/VewIo.png" rel="nofollow"><img src="http://i.s...
2
2016-10-01T15:49:41Z
39,808,980
<p>I believe that by "same resolution" you mean that you want 256 colors in the palette. I would actually think of this as having a different resolution from the original palette in sense that the values are closer together in the color space. In any case, I think you can get what you want by doing:</p> <pre><code>imp...
1
2016-10-01T16:33:19Z
[ "python", "matplotlib", "seaborn", "colormap" ]
Python, Requests, Threading, How fast do python requests close its sockets?
39,808,573
<p>I'm trying to make actions with Python requests. Here is my code:</p> <pre><code>import threading import resource import time import sys #maximum Open File Limit for thread limiter. maxOpenFileLimit = resource.getrlimit(resource.RLIMIT_NOFILE)[0] # For example, it shows 50. # Will use one session for every Thread...
2
2016-10-01T15:50:08Z
39,808,815
<p>Your limiter is a tight loop that takes up most of your processing time. Use a thread pool to limit the number of workers instead.</p> <pre><code>import multiprocessing.pool # Will use one session for every Thread. requestSessions = requests.Session() # Making requests Pool bigger to prevent [Errno -3] when socket...
1
2016-10-01T16:15:50Z
[ "python", "multithreading", "sockets", "python-requests" ]
Python | How to parse JSON from results from AWS response?
39,808,593
<p>I was trying to get the value of <code>VersionLabel</code> which is <code>php-v1</code> but my code doesn't work properly and I don't know what I'm doing wrong.</p> <p>Could you please let me know what's wrong and how can I parse the <code>php-v1</code>?</p> <p>This is my error message.</p> <p><code>TypeError: th...
2
2016-10-01T15:52:03Z
39,808,919
<p>As per the boto3 docs [<a href="http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html?highlight=describe_instances_health#ElasticBeanstalk.Client.describe_instances_health]" rel="nofollow">http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html?highlight=describe_insta...
3
2016-10-01T16:26:49Z
[ "python", "json", "amazon-web-services", "boto" ]
How to save a scraped list in a CSV file?
39,808,841
<p>I wrote this code below, which scrapes from the OED.com website words by subject and date and prints them out in a list.</p> <pre><code>import requests import re import urllib2 import os import csv year_search = 1550 subject_search = ['Law'] path = '/Applications/Python 3.5/Economic' opener = urllib2.build_opener...
0
2016-10-01T16:18:36Z
39,809,237
<p>I suggest using the csv.writer method. Here's the sample code:</p> <p>`</p> <pre><code>with open('/Applications/Python 3.5/Economic/OED_table.csv', 'w') as csv_file: csv_writer = csv.writer(csv_file) year = ["1550"] new_word = ["apple", "banana"] complete_row = year + new_word csv_writer.write...
1
2016-10-01T16:57:54Z
[ "python", "csv", "web-scraping" ]
How to save a scraped list in a CSV file?
39,808,841
<p>I wrote this code below, which scrapes from the OED.com website words by subject and date and prints them out in a list.</p> <pre><code>import requests import re import urllib2 import os import csv year_search = 1550 subject_search = ['Law'] path = '/Applications/Python 3.5/Economic' opener = urllib2.build_opener...
0
2016-10-01T16:18:36Z
39,809,264
<p>After the line where you define <code>new_word</code> you can do the following:</p> <pre><code>year_info = [str(year_search)] + new_word print '|'.join(year_info) </code></pre> <p>This will output exactly</p> <p>1550|word1|word2|etc.|</p>
0
2016-10-01T17:00:32Z
[ "python", "csv", "web-scraping" ]
My knapsack code is giving wrong output?
39,808,872
<p>I was trying to write a simple 0-1 knapsack problem but am encountering some error. Help would be appreciated.</p> <pre><code>T = int(input().strip()) def knapsack(n,k,ar): if n==0 or k==0: return 0 elif ar[n-1]&gt;k: return knapsack(n-1,k,ar) else: return max(knapsack(n-1,k,ar),...
1
2016-10-01T16:21:38Z
39,809,381
<p>Your algorithm is fine but your input to the function is wrong. </p> <p>In the first input, the line <code>n,k = int(a[0]),int(a[2])</code> is taking <code>3</code> and <code>1</code> as an input instead of <code>3</code> and <code>12</code>.<br> I guess you should use <code>list(map(int, input().split()))</code> ...
2
2016-10-01T17:12:13Z
[ "python", "algorithm", "python-3.x", "knapsack-problem" ]
Detect If Item is the Last in a List
39,808,908
<p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p> <pre><code>a = ['hello', 9, 3.14, 9] for item in a: print(item, end='') if item != a[-1]: print(', ') </code></pre> <p>And I would like this output:</p> <pre><code>hel...
0
2016-10-01T16:25:36Z
39,808,935
<p>Rather than try and detect if you are at the last item, print the comma and newline <em>when printing the next</em> (which only requires detecting if you are at the first):</p> <pre><code>a = ['hello', 9, 3.14, 9] for i, item in enumerate(a): if i: # print a separator if this isn't the first element pr...
7
2016-10-01T16:29:04Z
[ "python", "list", "python-3.x" ]
Detect If Item is the Last in a List
39,808,908
<p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p> <pre><code>a = ['hello', 9, 3.14, 9] for item in a: print(item, end='') if item != a[-1]: print(', ') </code></pre> <p>And I would like this output:</p> <pre><code>hel...
0
2016-10-01T16:25:36Z
39,808,992
<p>If you really just want to join your elements into a comma+newline-separated string then it's easier to use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join</code></a> method:</p> <pre><code>elements = ['hello', 9, 3.14, 9] s = ',\n'.join(str(el) for el in elements) #...
3
2016-10-01T16:34:20Z
[ "python", "list", "python-3.x" ]
Detect If Item is the Last in a List
39,808,908
<p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p> <pre><code>a = ['hello', 9, 3.14, 9] for item in a: print(item, end='') if item != a[-1]: print(', ') </code></pre> <p>And I would like this output:</p> <pre><code>hel...
0
2016-10-01T16:25:36Z
39,809,104
<p>If you are just looking to see if the item is last in the (or any item in any list) you could try using a function to check if an item is last in a list.</p> <pre><code>a = ['hello', 9, 3.14, 9] def is_last(alist,choice): if choice == alist[-1]: print("Item is last in list!") return ...
0
2016-10-01T16:44:56Z
[ "python", "list", "python-3.x" ]
Detect If Item is the Last in a List
39,808,908
<p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p> <pre><code>a = ['hello', 9, 3.14, 9] for item in a: print(item, end='') if item != a[-1]: print(', ') </code></pre> <p>And I would like this output:</p> <pre><code>hel...
0
2016-10-01T16:25:36Z
39,809,115
<p>You are not getting the expected output because in your code you say, "Hey python, print a comma if current element is not equal to last element."</p> <p>Second element 9 is equal to last element, hence the comma is not printed.</p> <p>The right way to check for the last element is to check the index of element :<...
1
2016-10-01T16:45:38Z
[ "python", "list", "python-3.x" ]
Using webbrowser module to use Google Maps
39,808,974
<p>i'm just new to python and i want to ask a simple question.<br> what's the difference between using this code:</p> <pre><code> import webbrowser, pyperclip, sys chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe %s" def location_finder(): output = input('Type the place you ...
-1
2016-10-01T16:33:00Z
39,809,131
<p>The diffrent is:</p> <ol> <li>With the first one, using target browser is <code>chrome.exe</code> and the second is using the default browser.</li> <li>The first code using import from built in function <code>input</code> and the second code <code>sys.argv</code>is automatically a list of strings representing the a...
0
2016-10-01T16:46:28Z
[ "python", "module", "sys", "pyperclip" ]
Python multithreading freeze(?) randomly
39,809,155
<p>I'm writing a script that's supposed to get some pictures from a very large amount or websites. First time using multithreading, think it is required here so get an okay runtime. So the Problem: The script runs, but after a seemingly random amount of passed websites it just doesn't continue any more. It doesn't tota...
1
2016-10-01T16:48:57Z
39,925,073
<p>My bad guys, the problem was actually in the getPicture function. Thanks for the answers anyways!</p>
0
2016-10-07T20:11:42Z
[ "python", "multithreading", "freeze" ]
Set background and separate foreground color for cell in openpyxl
39,809,156
<p>I am using <strong>openpyxl 2.3.5</strong>.</p> <p>I am writing an Excel sheet from Python and need to set a cell's background color to black and its foreground color (font color?) to white.</p> <p>I know how to set the background color to white (leaving the foreground/font color):</p> <pre><code>from openpyxl im...
0
2016-10-01T16:49:02Z
39,815,571
<p>While styles have changed a lot since version 1.x, fills haven't changed that much.</p> <p>In this case you need to set the foreground to black (<code>000000</code>) and the background doesn't matter because the "pattern" is solid.</p>
2
2016-10-02T09:21:08Z
[ "python", "openpyxl" ]
kivy python passing parameters to fuction with button click
39,809,206
<p>I am having trouble passing parameters to function when calling it with button press. One could do it like this in kivy language:</p> <pre><code>Button: on_press: root.my_function('btn1') </code></pre> <p>but I would like to do it in python, as I would like to create a larger number of buttons with a loop. Cur...
0
2016-10-01T16:53:59Z
39,809,268
<pre><code>Button(on_press=self.my_function) </code></pre> <p>This is <em>passing</em> the function as an argument.</p> <pre><code>Button(on_press=self.my_function('btn1')) </code></pre> <p>This is <em>calling</em> the function and passing the <em>returned value</em> as the argument to <code>on_press</code>. Since t...
0
2016-10-01T17:01:25Z
[ "python", "function", "button", "kivy" ]
Basic Python: Passing a string as an input to a function
39,809,255
<p>I am just starting off with python. I have 4 variables F_1, F_2, F_3 and F_4. Each containing a matrix in them. I want to count the non-zero values in each of them. So i wrote a loop.</p> <pre><code>f_1 = thresh1[1:mr, 1:mc] f_2 = thresh1[1:mr, (mc+1):width] f_3 = thresh1[(mr+1):height, 1:mc] f_4 = thresh1[(mr+1):...
-1
2016-10-01T16:59:56Z
39,809,501
<p>You have a problem in that you're trying to use strings to reference variable names. This is considerably difficult to do; you're better off using lists to contain your images. That is, instead of trying to reference <code>f_1</code>, <code>f_2</code>, etc, create a single list called <code>f</code> that contains ...
1
2016-10-01T17:24:14Z
[ "python", "string", "for-loop" ]
Basic Python: Passing a string as an input to a function
39,809,255
<p>I am just starting off with python. I have 4 variables F_1, F_2, F_3 and F_4. Each containing a matrix in them. I want to count the non-zero values in each of them. So i wrote a loop.</p> <pre><code>f_1 = thresh1[1:mr, 1:mc] f_2 = thresh1[1:mr, (mc+1):width] f_3 = thresh1[(mr+1):height, 1:mc] f_4 = thresh1[(mr+1):...
-1
2016-10-01T16:59:56Z
39,811,400
<pre><code>f_1_nz = f_1[f_1 != 0].size # etc. r_1 = f_1_nz / b_1_nz # etc. </code></pre> <p>Ideally you'd put f_1 etc. into a list and iterate over it, instead of defining new names for each, see the answer by @apnorton.</p> <p>So, in the end:</p> <pre><code>for ff, bb in zip(f,b): f_nz = ff[ff != 0].size b...
1
2016-10-01T20:57:29Z
[ "python", "string", "for-loop" ]
make a button for animation in matplotlib
39,809,329
<p>I just made a simple gui using Qt Designer, the gui has 4 buttons and a widget. The widget will show the animation and the buttons are for pause animation,resume, clean the canvas and start animation. I made this code:</p> <pre><code>import sys from PyQt4 import QtGui, uic import numpy as np import matplotlib.pyplo...
0
2016-10-01T17:07:02Z
39,812,186
<p>Try to provide minimal <em>working</em> examples. Without animacion.ui we cannot run you code.</p> <p>Refering to the second code: The problem here seems to be that inside <code>borr()</code> you clear the figure (<code>plt.clf()</code>). If the figure is cleared, where should the animation be drawn to? </p>
0
2016-10-01T22:50:41Z
[ "python", "qt", "animation", "button", "matplotlib" ]
make a button for animation in matplotlib
39,809,329
<p>I just made a simple gui using Qt Designer, the gui has 4 buttons and a widget. The widget will show the animation and the buttons are for pause animation,resume, clean the canvas and start animation. I made this code:</p> <pre><code>import sys from PyQt4 import QtGui, uic import numpy as np import matplotlib.pyplo...
0
2016-10-01T17:07:02Z
39,812,475
<p>I solved the problem making a function with the animation </p> <pre><code>import sys from PyQt4 import QtGui, uic import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas def start(): def datos...
0
2016-10-01T23:34:38Z
[ "python", "qt", "animation", "button", "matplotlib" ]
Merge elements in tuples?
39,809,452
<p>Here I have a dataset:</p> <pre><code>rd=''' 1:A,B,C;D,E 2:F,G 3:H,J,K ''' </code></pre> <p>Desired result:</p> <pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')] </code></pre> <p>My code:</p> <pre><code>def rd_edges(f): allEdges =[] for line in f.split(): ...
2
2016-10-01T17:19:17Z
39,809,593
<p>The "Roughly equivalent to" code from the docs of the itertools function you have been wisely advised to use shows a correct version that is actually written in Python:</p> <p><a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">https://docs.python.org/3/library/itertools...
0
2016-10-01T17:35:52Z
[ "python", "tuples" ]
Merge elements in tuples?
39,809,452
<p>Here I have a dataset:</p> <pre><code>rd=''' 1:A,B,C;D,E 2:F,G 3:H,J,K ''' </code></pre> <p>Desired result:</p> <pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')] </code></pre> <p>My code:</p> <pre><code>def rd_edges(f): allEdges =[] for line in f.split(): ...
2
2016-10-01T17:19:17Z
39,809,669
<pre><code>def find_edges(f): out = [] for line in f.split(): line = line.split(':')[1] disjoint = line.split(';') for d in disjoint: s = d.split(',') for i, node in enumerate(s)): for downnode in s[i+1:]: out.append((node, downnode)) return out </...
0
2016-10-01T17:44:10Z
[ "python", "tuples" ]
Merge elements in tuples?
39,809,452
<p>Here I have a dataset:</p> <pre><code>rd=''' 1:A,B,C;D,E 2:F,G 3:H,J,K ''' </code></pre> <p>Desired result:</p> <pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')] </code></pre> <p>My code:</p> <pre><code>def rd_edges(f): allEdges =[] for line in f.split(): ...
2
2016-10-01T17:19:17Z
39,809,674
<p>Here is how you could do it without import of itertools:</p> <pre><code>def rd_edges(f): allEdges =[] for line in f.split(): edges = line.split(":")[1].split(';') for edge in edges: nodes = edge.split(',') for i, a in enumerate(nodes): for b in nodes[i...
2
2016-10-01T17:44:21Z
[ "python", "tuples" ]
Merge elements in tuples?
39,809,452
<p>Here I have a dataset:</p> <pre><code>rd=''' 1:A,B,C;D,E 2:F,G 3:H,J,K ''' </code></pre> <p>Desired result:</p> <pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')] </code></pre> <p>My code:</p> <pre><code>def rd_edges(f): allEdges =[] for line in f.split(): ...
2
2016-10-01T17:19:17Z
39,809,695
<p>Below is the simplified solution to achieve it using <a href="https://docs.python.org/2/library/re.html#re.compile" rel="nofollow"><code>re.compile()</code></a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> functions. In...
1
2016-10-01T17:47:14Z
[ "python", "tuples" ]
python webscraping and write data into csv
39,809,465
<p>I'm trying to save all the data(i.e all pages) in single csv file but this code only save the final page data.Eg Here url[] contains 2 urls. the final csv only contains the 2nd url data. I'm clearly doing something wrong in the loop.but i dont know what. And also this page contains 100 data points. But this code on...
2
2016-10-01T17:20:59Z
39,809,569
<p>the gen_list is being initialized again inside your loop that runs over the urls.</p> <pre><code>gen_list=[] </code></pre> <p>Move this line outside the for loop.</p> <pre><code>... url = ["http://sfbay.craigslist.org/search/sfc/npo","http://sfbay.craigslist.org/search/sfc/npo?s=100"] gen_list=[] for ur in url: ....
3
2016-10-01T17:33:31Z
[ "python", "python-2.7", "csv", "web-scraping", "beautifulsoup" ]
Running a command on a remote server to find the uptime in seconds
39,809,487
<p>Here's what I have so far:</p> <pre><code>#!/usr/bin/python import sys import os import subprocess from subprocess import check_output import time import sh from sh import sshpass import re import time, datetime check_time = 0 with open("log.txt", "a") as f: while 1: #out = check_output(["sshpass", "-...
2
2016-10-01T17:23:19Z
39,810,037
<p>Someone on IRC suggested I use <code>command_string = "cat /proc/cpu/"</code> and</p> <pre><code>result = uptime("-p", "pass", "ssh", "theo@localhost", command_string) </code></pre> <p>Which works!</p>
1
2016-10-01T18:21:26Z
[ "python", "linux", "python-3.x" ]
Running a command on a remote server to find the uptime in seconds
39,809,487
<p>Here's what I have so far:</p> <pre><code>#!/usr/bin/python import sys import os import subprocess from subprocess import check_output import time import sh from sh import sshpass import re import time, datetime check_time = 0 with open("log.txt", "a") as f: while 1: #out = check_output(["sshpass", "-...
2
2016-10-01T17:23:19Z
39,810,123
<p>Based on the output, you need to modify your uptime line to look something like this:</p> <pre><code> result = uptime("-p", "pass", "ssh", "theo@localhost", "cat", "/proc/uptime") </code></pre> <p>It looks like "cat /proc/uptime" is interpreted as one argument by ssh in your original cod...
2
2016-10-01T18:29:24Z
[ "python", "linux", "python-3.x" ]
How to use standard Linux tools to fix a deadlocked script?
39,809,554
<p>I have a script in Python3 and if I use <code>subprocess.Popen.wait()</code> I have problem — my script iterates some Linux command many times and it looks to me like my app is not responding. When I use <code>subprocess.Popen.communicate()</code> my application correctly completes its work in a second. <strong>Wh...
-1
2016-10-01T17:31:11Z
39,810,762
<p>Your script is sending output to its <code>stdout</code> or <code>stderr</code> pipes. The operating system will buffer some data then block the process forever when the pipe fills. Suppose I have a long winded command like</p> <p>longwinded.py:</p> <pre><code>for i in range(100000): print('a'*1000) </code></p...
0
2016-10-01T19:41:15Z
[ "python", "linux", "subprocess", "buffer", "buffer-overflow" ]
How do I make a function iterate over a list twice, picking up where it left off?
39,809,649
<p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at...
2
2016-10-01T17:41:35Z
39,809,971
<p>Here is sample code for how to achieve this with generators and yield keyword -</p> <pre><code>def splitter(long_mess) : split_mess = "" for index in xrange(len(long_mess)) : if index&gt;0 and index%5==0 : yield split_mess split_mess = ...
1
2016-10-01T18:14:40Z
[ "python" ]
How do I make a function iterate over a list twice, picking up where it left off?
39,809,649
<p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at...
2
2016-10-01T17:41:35Z
39,810,035
<p>Here is a sample code which makes a list of lists which contains info about 5 stops. Then, you can call <code>send_message</code> in a loop</p> <pre><code>def split_into_pairs_of_5(info) outer = [] inner = [] for x in range(len(info["results"])): if x % 5 == 0 and inner: outer.append...
0
2016-10-01T18:20:59Z
[ "python" ]
How do I make a function iterate over a list twice, picking up where it left off?
39,809,649
<p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at...
2
2016-10-01T17:41:35Z
39,810,148
<p>You can do it easily by writing a <a href="https://docs.python.org/2/glossary.html#term-generator" rel="nofollow">generator function</a> like <code>chunks()</code> in the code below:</p> <pre><code>info = {'results': [ {'route': 1, 'destination': 'DestA', 'duetime': '10'}, {'route': 2, 'dest...
5
2016-10-01T18:31:51Z
[ "python" ]
How do I make a function iterate over a list twice, picking up where it left off?
39,809,649
<p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at...
2
2016-10-01T17:41:35Z
39,810,465
<p>My approach uses <code>itertools.groupby()</code> to group the records in chunk of 5 (or any positive number). In your post, you are not showing the name in which <code>send_message</code> calls, so I just name it myself: <code>get_info</code>:</p> <pre><code>import itertools def show_rec(rec): output = 'Route...
0
2016-10-01T19:07:10Z
[ "python" ]
How do I make a function iterate over a list twice, picking up where it left off?
39,809,649
<p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at...
2
2016-10-01T17:41:35Z
39,810,877
<p>You can use a generator function with <code>range</code> (or <code>xrange</code> in Python 2.7), like this:</p> <pre><code>info = {'results': [ {'route': 1, 'destination': 'DestA', 'duetime': '1'}, {'route': 2, 'destination': 'DestB', 'duetime': '2'}, {'route': 3, 'destination': 'DestC', 'duetime': '3'}...
0
2016-10-01T19:54:22Z
[ "python" ]
selecting rows in a tuplelist in pandas
39,809,650
<p>I have a list of tuples as below in python:</p> <pre><code> Index Value 0 (1,2,3) 1 (2,5,4) 2 (3,3,3) </code></pre> <p>How can I select rows from this in which the second value is less than or equal 2?</p> <p><strong><em>EDIT:</em></strong></p> <p>Basically, the da...
2
2016-10-01T17:41:37Z
39,809,700
<p>You could slice the <code>tuple</code> by using <code>apply</code>:</p> <pre><code>df[df['Value'].apply(lambda x: x[1] &lt;= 2)] </code></pre> <p><a href="http://i.stack.imgur.com/MZBwY.png" rel="nofollow"><img src="http://i.stack.imgur.com/MZBwY.png" alt="Image"></a></p> <hr> <p>Seems, it was a list of tuples a...
2
2016-10-01T17:47:45Z
[ "python", "pandas", "tuples" ]
selecting rows in a tuplelist in pandas
39,809,650
<p>I have a list of tuples as below in python:</p> <pre><code> Index Value 0 (1,2,3) 1 (2,5,4) 2 (3,3,3) </code></pre> <p>How can I select rows from this in which the second value is less than or equal 2?</p> <p><strong><em>EDIT:</em></strong></p> <p>Basically, the da...
2
2016-10-01T17:41:37Z
39,809,734
<pre><code>df[df["Value"].str[1] &lt;= 2] </code></pre> <p>You can read this for more details - <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str</a></p>
1
2016-10-01T17:51:27Z
[ "python", "pandas", "tuples" ]
selecting rows in a tuplelist in pandas
39,809,650
<p>I have a list of tuples as below in python:</p> <pre><code> Index Value 0 (1,2,3) 1 (2,5,4) 2 (3,3,3) </code></pre> <p>How can I select rows from this in which the second value is less than or equal 2?</p> <p><strong><em>EDIT:</em></strong></p> <p>Basically, the da...
2
2016-10-01T17:41:37Z
39,812,611
<p>just to put this out there. you should read <a href="http://stackoverflow.com/help/mcve">mcve</a>. your question was/is confusing because it looks as though you've got 2 good answers and your not satisfied. then you edited your question to be clearer, but just barely.</p> <p>ok, now that i've got my editorial ou...
0
2016-10-01T23:58:32Z
[ "python", "pandas", "tuples" ]
Python pandas resampling instantaneous hourly data to daily timestep including 00:00 of next day
39,809,703
<p>Let's say I have a series of instantaneous temperature measurements (i.e. they capture the temperature at an exact moment in time).</p> <pre><code>index = pd.date_range('1/1/2000', periods=9, freq='T') series = pd.Series(range(9), index=index) series Out[130]: 2000-01-01 00:00:00 0 2000-01-01 06:00:00 1 200...
2
2016-10-01T17:48:02Z
39,812,467
<p><strong><em>setup</em></strong> </p> <pre><code>index = pd.date_range('1/1/2000', periods=9, freq='6H') series = pd.Series(range(9), index=index) series 2000-01-01 00:00:00 0 2000-01-01 06:00:00 1 2000-01-01 12:00:00 2 2000-01-01 18:00:00 3 2000-01-02 00:00:00 4 2000-01-02 06:00:00 5 2000-01-02...
1
2016-10-01T23:33:23Z
[ "python", "pandas" ]
pycrypto: unable to decrypt file
39,809,743
<p>I am using PKCS1_OAEP crypto algorithm to encrypt a file. The file is encrypted successfully but unable to decrypt file, getting the error "Ciphertext with incorrect length."</p> <p>Encryption Algorithm is here: </p> <pre><code>#!/usr/bin/python from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA...
2
2016-10-01T17:52:31Z
39,811,745
<p>You encrypt with a <strong>2048 bit RSA key</strong>, which gives encrypted blocks of <strong>2048 bites (256 bytes)</strong>. Your decrypt implementation assumes the encrypted blocks are <strong>128 bytes</strong> where they are actually <strong>256 bytes</strong>, and thus you get the 'incorrect length' error. Not...
0
2016-10-01T21:44:43Z
[ "python", "encryption", "cryptography", "public-key-encryption", "pycrypto" ]
Django: add filtering sidebar to a change list admin view
39,809,945
<p>I have a back-end module showing a quite long items listing that looks like this:</p> <pre><code>ID Label Type 1 Label 1 Type A 2 Label 2 Type B 3 Label 3 Type A 4 Label 4 Type D 5 Label 5 ...
0
2016-10-01T18:12:06Z
39,810,459
<p>You can use <code>class based generic views</code></p> <pre><code>from django.views import generic class MyListView(generic.ListView): model = MyModel template_name = 'my_list.html' def get_queryset(self): queryset = super(MyListView, self).get_queryset() # get query value of query par...
1
2016-10-01T19:06:56Z
[ "python", "django" ]
See if user in ManyToManyField
39,809,984
<p>I am trying to see if the current user is in the <code>collaborators</code> m2m field, but keep getting an error saying: </p> <p><code>Cannot query "John Doe": Must be "Company" instance.</code></p> <p>Could someone help me out with the conditional statement please?</p> <p><strong>models.py:</strong></p> <pre><c...
0
2016-10-01T18:15:55Z
39,810,355
<p>Full docs is <a href="https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/" rel="nofollow">here</a></p> <p>You can use</p> <pre><code>if company.user == user or company.collaborators.filter(collaborators=user): </code></pre> <p>or </p> <pre><code>if company.user == user or company.collaborator...
0
2016-10-01T18:54:35Z
[ "python", "django", "django-models", "django-views", "many-to-many" ]
Python - How to plot 'boundary edge' onto a 2D plot
39,809,997
<p>The program <strong>pastebinned</strong> below generates a plot that looks like: <a href="http://i.stack.imgur.com/6pTzP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/6pTzP.jpg" alt="Original plot"></a> <strong>Pastebin</strong>: <a href="http://pastebin.com/wNgAG6K9" rel="nofollow">http://pastebin.com/wNgA...
0
2016-10-01T18:17:07Z
39,810,573
<p>Without seeing your data, I would suggest first trying to work with matplotlib's internal algorithm to plot the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.contour" rel="nofollow"><code>contour</code></a> line corresponding to the zero level. This is simple, but it might happen that the inte...
0
2016-10-01T19:16:50Z
[ "python", "matplotlib", "plot" ]
explicitly setting style sheet in python pyqt4?
39,810,010
<p>In pyqt standard way for setting style sheet is like this <br><br> <code>MainWindow.setStyleSheet(_fromUtf8("/*\n" "gridline-color: rgb(85, 170, 255);\n" "QToolTip\n" "{\n" " border: 1px solid #76797C;\n" " background-color: rgb(90, 102, 117);;\n" " color: white;\n" " padding: 5px;\n" " opacity: 200;\...
0
2016-10-01T18:18:16Z
39,838,248
<p>There are currently only two main ways to set a stylesheet. The first is to use the <code>setStyleSheet</code> method:</p> <pre><code>widget.setStyleSheet(""" QToolTip { border: 1px solid #76797C; background-color: rgb(90, 102, 117); color: white; padding: 5px; opacity: 2...
2
2016-10-03T18:37:28Z
[ "python", "pyqt", "pyqt4", "qss" ]
Comparing hundreds of JPEG images taken from multiple angles
39,810,168
<p>I am comparing X-ray images to find a specific difference between these images. All images are in jpeg format. Sometimes there are six, or eight different camera angles from which these images are taken. From each angle there are ~ 100 images. I am trying to compare a couple of hundred images to identify a specific ...
2
2016-10-01T18:33:37Z
39,810,608
<p>I don't know Sci-kit, but I'm sure <a href="http://docs.opencv.org/2.4/index.html" rel="nofollow">OpenCV</a> can do the job!</p> <ul> <li><a href="https://en.wikipedia.org/wiki/OpenCV" rel="nofollow">https://en.wikipedia.org/wiki/OpenCV</a></li> <li><a href="http://docs.opencv.org/2.4/modules/stitching/doc/exposure...
2
2016-10-01T19:21:52Z
[ "python", "jpeg" ]
Threading queue hangs in Python
39,810,172
<p>I am trying to make a parser multi-threaded via a Queue. It seems to work, but my Queue is hanging. I'd appreciate if someone could tell me how to fix this, since I have rarely written multi-threaded code.</p> <p>This code reads from the Q:</p> <pre><code>from silk import * import json import datetime import panda...
2
2016-10-01T18:34:16Z
39,810,328
<p>The <a href="https://docs.python.org/3.6/library/queue.html#queue.Queue.empty" rel="nofollow">Queue.empty doc</a> says:</p> <blockquote> <p>...if empty() returns False it doesn’t guarantee that a subsequent call to get() will not block.</p> </blockquote> <p>As a minimum you should use <code>get_nowait</code> o...
2
2016-10-01T18:52:09Z
[ "python", "multithreading", "queue", "hang" ]
no "\n" but new line being made?
39,810,199
<p>There is no <code>\n</code> in my code but when I print out all my variables, it creates a newline meaning my last variable is printed on another line.</p> <p>my code :</p> <pre><code>with open("read_it.txt", "r") as text_file: for items in text_file: line = items.split(",") if GTIN in items: ...
0
2016-10-01T18:37:51Z
39,810,319
<p>When you call readline on a file object (which you're doing implicitly in your for loop), it leaves the trailing '\n' and/or '\r' characters. In this case, your indprice variable still contains that trailing '\n'.</p> <p>Try:</p> <pre><code>line = items.strip('\r\n').split(',') </code></pre> <p>Or, if it's a sma...
2
2016-10-01T18:51:22Z
[ "python", "python-3.x" ]
Django log requests with status 200 to syslog
39,810,236
<p>I am writing a Django Application and using basic URL Routing to views. I am trying to implement logging to syslog. I want to log all incoming requests to syslog. My <code>LOGGING</code> dict looks like this:</p> <pre><code>LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { ...
2
2016-10-01T18:41:34Z
39,811,554
<p>The logging requests from django to syslog depends on several things:</p> <ul> <li>Syslog configuration. I assume that your syslog configuration is correct and syslog does not drop debug messages from local7.</li> <li>If you run your application with 'runserver', django uses built-in lightweight http server. This s...
1
2016-10-01T21:17:35Z
[ "python", "django", "logging" ]
Sending content directly to scrapy pipeline
39,810,251
<p>I'm working with scrapy. In my current project I am capturing the text from pdf files. I want to send this to a pipeline for parsing. Right now I have:</p> <pre><code>def get_pdf_text(self, response): in_memory_pdf = BytesIO(bytes(response.body)) in_memory_pdf.seek(0) doc = slate.PDF(in_memory_pdf) ...
1
2016-10-01T18:43:30Z
39,810,891
<p>According to <a href="https://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.parse" rel="nofollow">Scrapy documentation</a>, a spider callback has to either return a <code>Request</code> instance(s), dictionary(ies) or <code>Item</code> instance(s):</p> <blockquote> <p>This method, as well as ...
1
2016-10-01T19:56:01Z
[ "python", "scrapy" ]
Using the click package: Making an option be a choice of `int`
39,810,313
<p>I'm trying to make a <code>click.option</code> be a choice between the numbers <code>0</code>, <code>1</code> and <code>2</code>. I tried this: </p> <pre><code>@click.Option('--verbosity', default=1, type=click.Choice([0, 1, 2])) def f(): # ... pass </code></pre> <p>But I get the exception <code>TypeError:...
2
2016-10-01T18:50:41Z
39,810,394
<p>You can use <code>IntRange(min=0, max=2)</code>:</p> <blockquote> <p><code>class click.IntRange(min=None, max=None, clamp=False)</code> </p> <p>A parameter that works similar to click.INT but restricts the value to fit into a range. The default behavior is to fail if the value falls outside the range,...
2
2016-10-01T19:00:08Z
[ "python", "click" ]
Shut down server in TensorFlow
39,810,356
<p>When we want to use distributed TensorFlow, we will create a parameter server using</p> <pre><code>tf.train.Server.join() </code></pre> <p>However, I can't find any way to shut down the server except killing the processing. The TensorFlow documentation for join() is</p> <pre><code>Blocks until the server has shut...
0
2016-10-01T18:54:36Z
39,812,053
<p>There's currently no clean way to shut down a TensorFlow gRPC server. It <em>is</em> possible to <a href="http://stackoverflow.com/a/35708349/3574081">shut down a gRPC server</a>, but doing it safely requires additional memory management for all of the in-flight request and response buffers, which would require a lo...
0
2016-10-01T22:30:13Z
[ "python", "machine-learning", "tensorflow", "deep-learning", "grpc" ]
python 'string index out of range' error
39,810,553
<p>I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems. my code is:</p> <pre><code>a = input('word -&gt;') b = [] count = 0 while count &lt; 5...
0
2016-10-01T19:14:55Z
39,810,584
<p>The problem is that your "count" will increase each loop until it reaches 5. If the string in the input is shorter than 5, you will get index error.</p>
0
2016-10-01T19:18:33Z
[ "python", "indexing", "syntax", "range" ]
python 'string index out of range' error
39,810,553
<p>I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems. my code is:</p> <pre><code>a = input('word -&gt;') b = [] count = 0 while count &lt; 5...
0
2016-10-01T19:14:55Z
39,810,611
<p>Because when you give input smaller than 5 a[count] is out of index. So try this one:</p> <pre><code>a = input('word -&gt;') b = [] count = 0 while count &lt; len(a): b.append(a[count]) count +=1 print(b) </code></pre>
1
2016-10-01T19:22:14Z
[ "python", "indexing", "syntax", "range" ]
python 'string index out of range' error
39,810,553
<p>I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems. my code is:</p> <pre><code>a = input('word -&gt;') b = [] count = 0 while count &lt; 5...
0
2016-10-01T19:14:55Z
39,810,645
<p>I'm not sure what you are trying to achieve here, but look at this:</p> <pre><code>word = input('word -&gt; ') b1 = [] # Iterate over letters in a word: for letter in word: b1.append(letter) print(b1) b2 = [] # Use `enumerate` if you need to have an index: for i, letter in enumerate(word): # `i` here is yo...
2
2016-10-01T19:26:50Z
[ "python", "indexing", "syntax", "range" ]
Executeable Tkinter plus selenium
39,810,918
<p>WEll , i am getting hard to make this works, i have tried Cx_freeze</p> <p>but its showing this:</p> <p><a href="http://i.stack.imgur.com/8zXWE.png" rel="nofollow"><img src="http://i.stack.imgur.com/8zXWE.png" alt="With Cx_freeze"></a></p> <p>This is the Setup:</p> <pre><code>import sys from cx_Freeze import set...
0
2016-10-01T19:58:35Z
39,823,365
<p>Well after Saurabh Gaur told me if i was initialising the web driver, have re-thinking about it again and search for it , well you have to make executeable-path for you webdriver for example:</p> <pre><code>phantomdriver = r"C:\Users\Bar\PycharmProjects\Yad2FinalFix\phantomjs.exe" driver = webdriver.PhantomJS(execu...
0
2016-10-03T01:19:06Z
[ "python", "selenium", "executable", "pyinstaller", "cx-freeze" ]
behavior of machine epsilon in simple arithmetic
39,811,087
<p>*using python x2</p> <p>my homework asks me to set: eps = 2.**-52 the output of eps then becomes: 2.2204e-16</p> <p>(1. + eps - 1. = 2.2204e-16) # expected</p> <p>(1. + eps/2. - 1. = 0.0) # what?</p> <p>My homework simply asks me what happened in the second equation. I've experimented with different si...
-3
2016-10-01T20:20:14Z
39,811,170
<p><code>(1 + eps/2.0) - 1 = 0.0</code> because <code>eps/2.0</code> is too small to be properly represented alongside 1 (it as called <em>absorption</em> or <em>cancellation</em>)</p> <p>On a typical machine running Python, there are 53 bits of precision available for a Python float. If you try to go further, Python ...
0
2016-10-01T20:30:25Z
[ "python", "python-2.7", "floating-point" ]
issues importing a script
39,811,120
<p>Hello i have been working on this simple script and i have run into some rather annoying problems that i can not fix myself with the def. and import function it just won't work. here is the main script </p> <pre><code>import time # This part import the time module import script2 # This part imports the...
-1
2016-10-01T20:24:40Z
39,811,224
<p>This is an error:</p> <pre><code>def main(): #... q1 = input("Would you like to some maths today? ") if q1 == "yes": # ... </code></pre> <p>Firstly, the <code>q1</code> in <code>main()</code> and the <code>q1</code> outside are not the same variable.</p> <p>Secondly, <code>if q1 == "yes":</code> is e...
0
2016-10-01T20:37:29Z
[ "python", "function", "python-import" ]
issues importing a script
39,811,120
<p>Hello i have been working on this simple script and i have run into some rather annoying problems that i can not fix myself with the def. and import function it just won't work. here is the main script </p> <pre><code>import time # This part import the time module import script2 # This part imports the...
-1
2016-10-01T20:24:40Z
39,811,267
<p>Firstly your indentation doesn't seems to be right. As zvone stated. Secondly you should use script2.test() instead of script2 test(). A functional code is</p> <pre><code>import time # This part import the time module import script2 # This part imports the second script def main(): print("This pro...
0
2016-10-01T20:41:42Z
[ "python", "function", "python-import" ]
How to add url file to zip
39,811,192
<p>I have a zip file with the following structure:</p> <pre><code>my_zip.zip |-file1.txt |-folder1/ |-file2.txt </code></pre> <p>I want to add <code>some_file</code> <strong>from url</strong> to the <code>folder1</code>. I know that I can do something like:</p> <pre><code>&gt;&gt;&gt; import zipfile &gt;&gt;&gt;...
0
2016-10-01T20:33:42Z
39,811,408
<p>Use <a href="https://docs.python.org/3.7/library/zipfile.html#zipfile.ZipFile.writestr" rel="nofollow"><code>ZipFile.writestr(<em>arcname</em>, <em>data</em>)</code></a>.</p> <p>To write to a folder in the zipfile, you just write the foldername as if you were writing to a folder in a folder (So <code>folder1/some_f...
1
2016-10-01T20:58:06Z
[ "python", "python-3.x", "url", "zip" ]
KNeighborsClassifier .predict() function doesn't work
39,811,270
<p>i am working with KNeighborsClassifier algorithm from scikit-learn library in Python. I followed basic instructions e.g. split my data and labels into training and test data, then trained my model on a training data. Now I am trying to predict accuracy of testing data but get an error. Here is my code:</p> <pre><c...
1
2016-10-01T20:42:00Z
39,811,525
<p>Did you tried to solve your issue via the following question ?</p> <blockquote> <p><a href="http://stackoverflow.com/questions/30813044/sklearn-found-arrays-with-inconsistent-numbers-of-samples-when-calling-linearre">sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()</a...
1
2016-10-01T21:13:34Z
[ "python", "pandas", "machine-learning" ]
KNeighborsClassifier .predict() function doesn't work
39,811,270
<p>i am working with KNeighborsClassifier algorithm from scikit-learn library in Python. I followed basic instructions e.g. split my data and labels into training and test data, then trained my model on a training data. Now I am trying to predict accuracy of testing data but get an error. Here is my code:</p> <pre><c...
1
2016-10-01T20:42:00Z
39,812,834
<p>You should calculate the <code>accuracy_score</code> with <code>label_test</code>, not <code>label_train</code>. You want to compare the actual labels of the test set, <code>label_test</code>, to the predictions from your model, <code>predictions</code>, for the test set.</p>
1
2016-10-02T00:44:02Z
[ "python", "pandas", "machine-learning" ]
Python alphabet shifting string
39,811,337
<p>i have tried but can't seem to find my mistake in my code. My code is suppose to switch all the alphabetic characters (like a/aa/A/AA) and do nothing with the rest but when i run the code it doesn't give an error yet do what i want.</p> <p>Could anyone tell me what i have done wrong or have forgotten?</p> <pre><co...
0
2016-10-01T20:48:41Z
39,811,383
<p>I suppose you want to shift the letters so if the input letter is 'a' and shift is 3, then the output should be 'd'.</p> <p>In that case replace</p> <pre><code>if letter == ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', '...
0
2016-10-01T20:54:53Z
[ "python", "algorithm" ]
Python alphabet shifting string
39,811,337
<p>i have tried but can't seem to find my mistake in my code. My code is suppose to switch all the alphabetic characters (like a/aa/A/AA) and do nothing with the rest but when i run the code it doesn't give an error yet do what i want.</p> <p>Could anyone tell me what i have done wrong or have forgotten?</p> <pre><co...
0
2016-10-01T20:48:41Z
39,811,389
<p>You compare letter with list, but i think you want to check for contain letter in list, so you should just replace <code>==</code> to <code>in</code></p>
0
2016-10-01T20:55:50Z
[ "python", "algorithm" ]
Python alphabet shifting string
39,811,337
<p>i have tried but can't seem to find my mistake in my code. My code is suppose to switch all the alphabetic characters (like a/aa/A/AA) and do nothing with the rest but when i run the code it doesn't give an error yet do what i want.</p> <p>Could anyone tell me what i have done wrong or have forgotten?</p> <pre><co...
0
2016-10-01T20:48:41Z
39,811,481
<p>From the looks of it, I'd say you're more after something like this:</p> <pre><code>import string text = input("type something&gt; ") shift = int(input("enter number of shifts&gt; ")) for letter in text: index = ord(letter) - ord('a') + shift print(string.ascii_letters[index % len(string.ascii_letters)]) </...
0
2016-10-01T21:06:38Z
[ "python", "algorithm" ]
Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other
39,811,423
<p>So I have this homework assignment and seem to be stuck on this question.</p> <p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt;threePairs([5, 6, 3, 2, 1, 4]) ...
0
2016-10-01T20:59:26Z
39,811,465
<p>You could <code>zip</code> the a sliced list with itself one position ahead, with steps equal to <code>2</code> to get adjacent elements. Then feed that to <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all</code></a> with the condition you need:</p> <pre><code>def threePairs(l)...
2
2016-10-01T21:04:31Z
[ "python", "list", "python-3.x", "pair" ]
Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other
39,811,423
<p>So I have this homework assignment and seem to be stuck on this question.</p> <p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt;threePairs([5, 6, 3, 2, 1, 4]) ...
0
2016-10-01T20:59:26Z
39,811,471
<p>How about making a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter()</code></a> and check how many "pairs" you've got:</p> <pre><code>In [1]: from collections import Counter In [2]: def has_pairs(l, n): return sum(value / 2 for value in Coun...
2
2016-10-01T21:05:05Z
[ "python", "list", "python-3.x", "pair" ]