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 |
|---|---|---|---|---|---|---|---|---|---|
Extract all single {key:value} pairs from dictionary | 38,957,159 | <p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p>
<p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p>
<p>My dict looks something like this:</p>
<pre><code>&... | 0 | 2016-08-15T14:34:25Z | 38,957,250 | <p>Iterate through values in dictionary and count:</p>
<pre><code>count = 0
for value in dic.values():
if len(value) == 1:
count += 1
print count
</code></pre>
| 0 | 2016-08-15T14:39:43Z | [
"python",
"dictionary"
] |
Extract all single {key:value} pairs from dictionary | 38,957,159 | <p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p>
<p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p>
<p>My dict looks something like this:</p>
<pre><code>&... | 0 | 2016-08-15T14:34:25Z | 38,957,257 | <p>You could just filter your dictionary out like this:</p>
<pre><code>data = {
'key1': ['value11', 'value12'],
'key2': ['value21'],
'key3': ['value31', 'value32']
}
result = filter(lambda (k, v): len(v) == 1, data.iteritems())
print result, "=>", len(result)
</code></pre>
| 0 | 2016-08-15T14:39:58Z | [
"python",
"dictionary"
] |
Extract all single {key:value} pairs from dictionary | 38,957,159 | <p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p>
<p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p>
<p>My dict looks something like this:</p>
<pre><code>&... | 0 | 2016-08-15T14:34:25Z | 38,957,260 | <p>You can use <a href="http://stackoverflow.com/questions/38957159/extract-all-single-keyvalue-pairs-from-dictionary/38957260#comment65268425_38957159">@MosesKoledoye's</a> solution for the short (and probably a tiny bit faster) solution, or this naive version:</p>
<pre><code>print(len([value for value in d.values()
... | 1 | 2016-08-15T14:40:12Z | [
"python",
"dictionary"
] |
Extract all single {key:value} pairs from dictionary | 38,957,159 | <p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p>
<p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p>
<p>My dict looks something like this:</p>
<pre><code>&... | 0 | 2016-08-15T14:34:25Z | 38,957,270 | <p>With <code>d</code> being the dictionary:</p>
<pre><code>sum(len(v) == 1 for v in d.values())
</code></pre>
<p>Or:</p>
<pre><code>map(len, d.values()).count(1)
</code></pre>
<p>(The latter requires <code>list</code> around the <code>map</code> if you're using Python 3.)</p>
| 2 | 2016-08-15T14:40:53Z | [
"python",
"dictionary"
] |
How to predict new values using statsmodels.formula.api (python) | 38,957,178 | <p>I trained the logistic model using the following, from breast cancer data and ONLY using one feature 'mean_area'</p>
<pre><code>from statsmodels.formula.api import logit
logistic_model = logit('target ~ mean_area',breast)
result = logistic_model.fit()
</code></pre>
<p>There is a built in predict method in the trai... | 0 | 2016-08-15T14:35:27Z | 38,958,427 | <p>You can provide new values to the <code>.predict()</code> model as illustrated in output #11 in this <a href="http://statsmodels.sourceforge.net/devel/examples/notebooks/generated/discrete_choice.html" rel="nofollow">notebook</a> from the docs for a single observation. You can provide multiple observations as <code>... | 0 | 2016-08-15T15:49:57Z | [
"python",
"machine-learning",
"scikit-learn",
"logistic-regression",
"statsmodels"
] |
How to iterate over/manipulate a list of class objects in python (Node Crawl in a decentralized network simulation) | 38,957,286 | <p>Can anyone help me with the an iteration over a list of class objects?</p>
<p>I want to setup a simulation of nodes interacting with each other in a decentralized network. Each node is created as an object in the class Node.
Every node gets his name and a list of max three other nodes (also objects in sam class) h... | 1 | 2016-08-15T14:41:20Z | 38,957,974 | <p>Okay so thanks to wwii I found the answer</p>
<pre><code> for i in self.l1:
self.l2.extend(i.l1)
for i in self.l2:
self.l3.extend(i.l1)
</code></pre>
<p>nodes appearing double in the list can be eliminated with:</p>
<pre><code>from collections import OrderedDict as odict
self.l2... | 1 | 2016-08-15T15:19:31Z | [
"python",
"list",
"class",
"loops",
"object"
] |
select certain files from directory | 38,957,382 | <p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p>
<pre><code>blablabla_350.dat
blablabla_351.dat
blablabla_352.dat
blablabla_353.dat
...
blablabla_100.dat
blablabla_101.dat
blablabla_102.dat
</code></pre>
<p>The ones ending from 350... | 0 | 2016-08-15T14:46:39Z | 38,957,527 | <p>You can use <code>glob.glob</code> to get the list of all <code>*.dat</code> files then filter that list using a list comprehension with a conditional. In my solution I use a regular expression to extract the number from the filename as text. I then convert it to an integer and check if that integer lies between <co... | 2 | 2016-08-15T14:55:03Z | [
"python",
"glob"
] |
select certain files from directory | 38,957,382 | <p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p>
<pre><code>blablabla_350.dat
blablabla_351.dat
blablabla_352.dat
blablabla_353.dat
...
blablabla_100.dat
blablabla_101.dat
blablabla_102.dat
</code></pre>
<p>The ones ending from 350... | 0 | 2016-08-15T14:46:39Z | 38,957,579 | <p>You can use <code>glob.glob('*.dat')</code> to get a list of all of the files and then slice that list according to your criteria. The slice will begin at the index of the first reference name, and be as large as the number of references.</p>
<p>Extract that slice to get your references. Delete that slice to get yo... | 2 | 2016-08-15T14:57:49Z | [
"python",
"glob"
] |
select certain files from directory | 38,957,382 | <p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p>
<pre><code>blablabla_350.dat
blablabla_351.dat
blablabla_352.dat
blablabla_353.dat
...
blablabla_100.dat
blablabla_101.dat
blablabla_102.dat
</code></pre>
<p>The ones ending from 350... | 0 | 2016-08-15T14:46:39Z | 38,957,581 | <p>try something like</p>
<pre><code>import glob
samples = []
references = []
ref = raw_input("Enter first reference name: ")
num_refs = int(raw_input("How many references are? "))
for number in num_refs:
refferences.append(ref+number)
for filename in sorted(glob.glob('*.dat')):
if filename not in refferen... | -1 | 2016-08-15T14:58:00Z | [
"python",
"glob"
] |
select certain files from directory | 38,957,382 | <p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p>
<pre><code>blablabla_350.dat
blablabla_351.dat
blablabla_352.dat
blablabla_353.dat
...
blablabla_100.dat
blablabla_101.dat
blablabla_102.dat
</code></pre>
<p>The ones ending from 350... | 0 | 2016-08-15T14:46:39Z | 38,957,642 | <p>You can also do it without <code>glob</code> by using the <code>os</code> package:</p>
<pre><code>import os, re
files = os.listdir(r'C:\path\to\files')
samples, references = [], []
for file in files:
if re.search(r'blablabla_1\d{2}', file):
references.append(file)
elif re.serach(r'blablabla_3\d{2}'... | 0 | 2016-08-15T15:01:31Z | [
"python",
"glob"
] |
Hi, I just installed requests with pip but I can't import it | 38,957,513 | <p>For example my Code is: </p>
<pre><code>import requests
r = requests.get('https://www.python.org')
r.status_code
</code></pre>
<p>And the Result is: </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Till\workspace\firstproject\Learning_python\Web_crawler.py", line 6, in <module>
... | -2 | 2016-08-15T14:53:48Z | 38,957,543 | <p>Requests requires Python 3.3 or newer. It doesn't work on Python 3.2 as that version doesn't support the required <code>u'...'</code> compatibility syntax for string literals.</p>
<p>From the <a href="http://docs.python-requests.org/en/master/#supported-features" rel="nofollow"><code>requests</code> documentation</... | 8 | 2016-08-15T14:56:01Z | [
"python",
"python-requests"
] |
Hi, I just installed requests with pip but I can't import it | 38,957,513 | <p>For example my Code is: </p>
<pre><code>import requests
r = requests.get('https://www.python.org')
r.status_code
</code></pre>
<p>And the Result is: </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Till\workspace\firstproject\Learning_python\Web_crawler.py", line 6, in <module>
... | -2 | 2016-08-15T14:53:48Z | 38,957,635 | <p>Well, as issue is that Requests require Python-3.3 or higher so you will need to upgrade your Python. I noticed you are on windows so follow this link to download the installer for latest stable Python-3.5.2 (<a href="https://www.python.org/ftp/python/3.5.2/python-3.5.2-webinstall.exe" rel="nofollow">https://www.pyt... | 0 | 2016-08-15T15:01:00Z | [
"python",
"python-requests"
] |
memory efficient way to write an uncompressed file from a gzip file | 38,957,623 | <p>using Python 3.5</p>
<p>I am uncompressing a gzip file, writing to another file. After looking into an out of memory problem, I find an example in the docs for the gzip module:</p>
<pre><code>import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
with gzip.open('/home/joe/file.txt.gz', 'wb')... | 1 | 2016-08-15T15:00:12Z | 38,957,865 | <p>Here is the <code>shutil.copyfileObj</code> method.</p>
<pre><code>def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
</code></pre>
<p>It read... | 2 | 2016-08-15T15:13:02Z | [
"python",
"python-3.x",
"gzip",
"generator",
"shutil"
] |
memory efficient way to write an uncompressed file from a gzip file | 38,957,623 | <p>using Python 3.5</p>
<p>I am uncompressing a gzip file, writing to another file. After looking into an out of memory problem, I find an example in the docs for the gzip module:</p>
<pre><code>import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
with gzip.open('/home/joe/file.txt.gz', 'wb')... | 1 | 2016-08-15T15:00:12Z | 38,963,601 | <p>Instead of the memory hungry (and naive)</p>
<pre><code>import gzip
with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout:
wout.write(zin.read())
</code></pre>
<p>Based on the earlier answers I tested this:</p>
<pre><code>import gzip
block_size = 64*1024
with gzip.open(zipped_file, 'rb'... | 0 | 2016-08-15T21:50:44Z | [
"python",
"python-3.x",
"gzip",
"generator",
"shutil"
] |
Compute first order derivative with MongoDB aggregation framework | 38,957,649 | <p>Is it possible to calculate a first order derivative using the aggregate framework?</p>
<p>For example, I have the data : </p>
<pre><code>{time_series : [10,20,40,70,110]}
</code></pre>
<p>I'm trying to obtain an output like: </p>
<pre><code>{derivative : [10,20,30,40]}
</code></pre>
| 13 | 2016-08-15T15:02:00Z | 39,154,290 | <p>it's a bit dirty, but perhaps something like this?</p>
<pre><code>use test_db
db['data'].remove({})
db['data'].insert({id: 1, time_series: [10,20,40,70,110]})
var mapF = function() {
emit(this.id, this.time_series);
emit(this.id, this.time_series);
};
var reduceF = function(key, values){
var n = value... | 4 | 2016-08-25T20:33:03Z | [
"python",
"mongodb",
"mapreduce",
"pymongo",
"aggregation-framework"
] |
Compute first order derivative with MongoDB aggregation framework | 38,957,649 | <p>Is it possible to calculate a first order derivative using the aggregate framework?</p>
<p>For example, I have the data : </p>
<pre><code>{time_series : [10,20,40,70,110]}
</code></pre>
<p>I'm trying to obtain an output like: </p>
<pre><code>{derivative : [10,20,30,40]}
</code></pre>
| 13 | 2016-08-15T15:02:00Z | 39,185,810 | <p>We can do this using the aggregation framework in MongoDB 3.2 or newer because what we really need is a way to keep tracking of the index of the <em>current</em> and <em>previous</em> element in our array and fortunately starting from MongoDB 3.2 we can use the <a href="https://docs.mongodb.com/manual/reference/oper... | 5 | 2016-08-27T21:14:36Z | [
"python",
"mongodb",
"mapreduce",
"pymongo",
"aggregation-framework"
] |
Read uncompressed image from byte array | 38,957,724 | <p>I created a uncompressed dicom video from an ultrasound device. Now I want to read it frame by frame in a python application and for now save the file. Later I want to add some image processing. So far I've tried to extract the bytes belonging to the first frame.</p>
<pre><code>import dicom
import array
from PIL im... | 1 | 2016-08-15T15:06:05Z | 39,032,594 | <p>Thanks to the comments I figured out how to solve it. The Image was in 'RGB' and the shape of the array was (3L, 800L, 376L). Instead of converting it to a byte array I can take the <code>pixel_array</code> as numpy array and reshape it to (800L, 376L, 3L). </p>
<pre><code>import dicom
from PIL import Image
filena... | 0 | 2016-08-19T06:39:34Z | [
"python",
"image",
"dicom"
] |
Project Euler 22 Python | 300k from right result | 38,957,774 | <p>I'm working on Problem 22 from Project Euler.</p>
<p><em>Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical ... | 1 | 2016-08-15T15:08:06Z | 38,957,902 | <p>I believe you have an off-by-one error. Remember that array indexes start at zero, but ordinal numbers (like first, second, 938th) start at one.</p>
<p>Try this:</p>
<pre><code>namescoresum += lettersum * (indexofname+1)
</code></pre>
<p>To determine for sure if you have an off-by-one error, add this to your <cod... | 0 | 2016-08-15T15:15:01Z | [
"python",
"list"
] |
Project Euler 22 Python | 300k from right result | 38,957,774 | <p>I'm working on Problem 22 from Project Euler.</p>
<p><em>Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical ... | 1 | 2016-08-15T15:08:06Z | 38,985,628 | <p>Also, to complete this question a little bit... in case you wanted to solve the problem with a single comprehension list (assuming you already have your data ready to go), here's some tips:</p>
<ul>
<li>ord, ASCII, sum, enumerate</li>
</ul>
<p>There you go :-)</p>
| 0 | 2016-08-16T22:47:53Z | [
"python",
"list"
] |
In Python, use a method both as instance and class method | 38,957,820 | <p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p>
<pre><code>class RandomPlayer(ComputerPlayer):
def __init__(self, mark):
super(RandomPlayer, self).__init__(mark=mark)
def g... | 0 | 2016-08-15T15:10:36Z | 38,957,917 | <p>It sounds like you're looking for a <a href="https://docs.python.org/3.5/library/functions.html#staticmethod" rel="nofollow"><code>staticmethod</code></a>, which has access to neither <code>cls</code> nor <code>self</code> but can be accessed via either:</p>
<pre><code>>>> class Foo:
... @staticmethod
... | 2 | 2016-08-15T15:16:11Z | [
"python"
] |
In Python, use a method both as instance and class method | 38,957,820 | <p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p>
<pre><code>class RandomPlayer(ComputerPlayer):
def __init__(self, mark):
super(RandomPlayer, self).__init__(mark=mark)
def g... | 0 | 2016-08-15T15:10:36Z | 38,958,345 | <p>A random move is a specific type of move; put a method which generates one in <code>ComputerPlayer</code>; then both <code>RandomPlayer</code> and <code>THandPlayer</code> can call it as necessary.</p>
<pre><code>class ComputerPlayer(...):
@staticmethod
def choose_random_move(moves):
if moves:
... | 1 | 2016-08-15T15:45:10Z | [
"python"
] |
In Python, use a method both as instance and class method | 38,957,820 | <p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p>
<pre><code>class RandomPlayer(ComputerPlayer):
def __init__(self, mark):
super(RandomPlayer, self).__init__(mark=mark)
def g... | 0 | 2016-08-15T15:10:36Z | 38,958,680 | <p>For the sake of completeness, here is my implementation of the solution suggested by <a href="http://stackoverflow.com/users/476/deceze">deceze</a>, in which I also followed <a href="http://stackoverflow.com/users/1126841/chepner">chepner</a>'s suggestion to refactor the two Boolean statements:</p>
<pre><code>class... | 0 | 2016-08-15T16:06:44Z | [
"python"
] |
In Python, use a method both as instance and class method | 38,957,820 | <p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p>
<pre><code>class RandomPlayer(ComputerPlayer):
def __init__(self, mark):
super(RandomPlayer, self).__init__(mark=mark)
def g... | 0 | 2016-08-15T15:10:36Z | 38,958,735 | <p>(This is an alternative to my other answer, using a different abstraction.)</p>
<p>A random move isn't something associated with a player as much as it is something associated with a board; it's like <code>board.available_moves</code>, but returns a single move instead of all moves.</p>
<pre><code> class Board(...... | 1 | 2016-08-15T16:09:33Z | [
"python"
] |
Python 2.7 - prime number generator, can't figure out what is wrong with my program | 38,957,908 | <p>noob programmer here. I am trying to build a small program in 2.7 which generates a prime number, asks the user to continue or not, and then continues generating primes until the user tells it to stop. Unfortunately my program isn't outputting anything at all, and I can't figure out why.</p>
<p>Here is my code:</p>... | 0 | 2016-08-15T15:15:26Z | 38,958,001 | <p><code>n</code> should be incremented unconditionally. If it isn't the program gets stuck in an infinite loop the first time it encounters a non-prime.</p>
<pre><code>def primegen():
n = 1
while True:
if isprime(n):
print n
cont = raw_input("continue? Enter Y/N")
i... | 1 | 2016-08-15T15:21:39Z | [
"python",
"python-2.7",
"primes"
] |
Python 2.7 - prime number generator, can't figure out what is wrong with my program | 38,957,908 | <p>noob programmer here. I am trying to build a small program in 2.7 which generates a prime number, asks the user to continue or not, and then continues generating primes until the user tells it to stop. Unfortunately my program isn't outputting anything at all, and I can't figure out why.</p>
<p>Here is my code:</p>... | 0 | 2016-08-15T15:15:26Z | 38,958,593 | <p>Your code is a bit chaotic, I would rewrite it like this:</p>
<pre><code>def isPrime(num):
if num % 2 == 0:
return True
return False
n=1
while True:
if isPrime(n):
print n
cont = raw_input("Do you want to continue? (1,0) ")
if not bool(int(cont)):
break
n... | 0 | 2016-08-15T16:01:04Z | [
"python",
"python-2.7",
"primes"
] |
How to keep track of players' rankings? | 38,957,961 | <p>I have a <code>Player</code> class with a <code>score</code> attribute:</p>
<pre><code>class Player(game_engine.Player):
def __init__(self, id):
super().__init__(id)
self.score = 0
</code></pre>
<p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell... | 15 | 2016-08-15T15:18:40Z | 39,000,851 | <p>The problem you have is that you want real-time updates against a database, which requires a db query each time. If you instead maintain a list of scores in memory, and update it at a more reasonable frequency (say once an hour, or even once a minute, if your players are really concerned with their rank), then the p... | 4 | 2016-08-17T15:35:23Z | [
"python",
"algorithm",
"python-3.x",
"ranking",
"rank"
] |
How to keep track of players' rankings? | 38,957,961 | <p>I have a <code>Player</code> class with a <code>score</code> attribute:</p>
<pre><code>class Player(game_engine.Player):
def __init__(self, id):
super().__init__(id)
self.score = 0
</code></pre>
<p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell... | 15 | 2016-08-15T15:18:40Z | 39,002,736 | <p>That kind of information can be pulled using SQLAlchemy's sort_by function. If you perform a Query like:</p>
<pre><code>leaderboard = session.query(Player).order_by(Player.score).all()
</code></pre>
<p>You will have the list of Players sorted by their score. Keep in mind that every time you do this you do an I/O w... | 0 | 2016-08-17T17:18:25Z | [
"python",
"algorithm",
"python-3.x",
"ranking",
"rank"
] |
How to keep track of players' rankings? | 38,957,961 | <p>I have a <code>Player</code> class with a <code>score</code> attribute:</p>
<pre><code>class Player(game_engine.Player):
def __init__(self, id):
super().__init__(id)
self.score = 0
</code></pre>
<p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell... | 15 | 2016-08-15T15:18:40Z | 39,043,000 | <p>Redis sorted sets help with this exact situation (the documentation uses leader boards as the example usage) <a href="http://redis.io/topics/data-types-intro#redis-sorted-sets">http://redis.io/topics/data-types-intro#redis-sorted-sets</a></p>
<ul>
<li>The key commands you care about are ZADD (update player rank) an... | 6 | 2016-08-19T15:40:22Z | [
"python",
"algorithm",
"python-3.x",
"ranking",
"rank"
] |
Can't access the variable inside the generated code from pyqt5 | 38,957,964 | <p>this is my first post and I would like to thanks the amazing community of Stack Overflow for helping me during all this years! </p>
<p>However, after extensive research, i couldn't find a solution to my problem. I have the file generated by QtCreator which contain a progressbar.
In my code, I have 2 class, and 1 is... | 0 | 2016-08-15T15:18:52Z | 38,958,044 | <p><code>MainWindow</code> is a class, not an object. What you should do instead is something like:</p>
<pre><code>class B(Thread):
def __init__(self, target):
self.__target = target
def run(self):
self.__target.setprogressBar(48)
MAINWIN = MainWindow()
bi = B(MAINWIN)
bi.start()
MAINWIN.sh... | 0 | 2016-08-15T15:23:33Z | [
"python",
"multithreading",
"pyqt5"
] |
The requested address is not valid in its context error | 38,958,233 | <p>I was following a tutorial called "Black Hat Python" and got a "the requested address is not valid in its context" error. I'm Python IDE version: 2.7.12
This is my code:</p>
<pre><code>import socket
import threading
bind_ip = "184.168.237.1"
bind_port = 21
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM... | 0 | 2016-08-15T15:36:35Z | 38,958,939 | <p>You are trying to bind to an IP address that is not actually assigned to your network interface:</p>
<pre><code>bind_ip = "184.168.237.1"
</code></pre>
<p>See the <a href="https://msdn.microsoft.com/en-gb/library/windows/desktop/ms740668(v=vs.85).aspx" rel="nofollow"><em>Windows Sockets Error Codes</em> documentat... | 1 | 2016-08-15T16:22:18Z | [
"python",
"python-2.7",
"server"
] |
Learning Python - syntax error preventing me from proceeding in tutorial | 38,958,343 | <p>As the title suggests I'm doing a tutorial. I have however come across this error:</p>
<pre><code>>>> from words import (fetch_words, print_words)
>>> print_words(fetch_words())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\jjosey\Documents\p... | 0 | 2016-08-15T15:45:08Z | 38,958,402 | <p>Try putting a <code>return</code> statement at the end of <code>fetch_words</code>. Without it, <code>words = fetch_words()</code> will cause <code>words</code> to be <code>None</code>.</p>
<pre><code>def fetch_words():
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
fo... | 4 | 2016-08-15T15:48:36Z | [
"python",
"syntax"
] |
Learning Python - syntax error preventing me from proceeding in tutorial | 38,958,343 | <p>As the title suggests I'm doing a tutorial. I have however come across this error:</p>
<pre><code>>>> from words import (fetch_words, print_words)
>>> print_words(fetch_words())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\jjosey\Documents\p... | 0 | 2016-08-15T15:45:08Z | 38,958,417 | <pre><code>def fetch_words():
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)
</code></pre>
<p>This function has a bug... i... | 0 | 2016-08-15T15:49:24Z | [
"python",
"syntax"
] |
Get counts of specific values within a nested Python dictionary | 38,958,380 | <p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p>
<pre><code>item_dict = {
64762.0: {
'In Sheet': 'No',
'Paid': Y,
'Region': "AMER'",
'Matrix Position': 'Check'
},
130301.0: {
'Paid': N,
... | 1 | 2016-08-15T15:47:18Z | 38,958,710 | <pre><code>AmerCalculate={}
Regions = ["AMER", "EMEA", "JP"]
Positions = ["Calculate", "Check"]
for row in item_dict():
for region in regions:
for pos in Positions:
if (item_dict[row]['Region']==region) and (item_dict[row][MatrixPosition] == pos:
AmerCalculate(str(region)+ ' and ' +str(pos) ... | 0 | 2016-08-15T16:08:32Z | [
"python",
"dictionary",
"nested"
] |
Get counts of specific values within a nested Python dictionary | 38,958,380 | <p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p>
<pre><code>item_dict = {
64762.0: {
'In Sheet': 'No',
'Paid': Y,
'Region': "AMER'",
'Matrix Position': 'Check'
},
130301.0: {
'Paid': N,
... | 1 | 2016-08-15T15:47:18Z | 38,958,810 | <p>Use another dictionary to couple that data set together, from there you can generate the output you're looking for:</p>
<pre><code>def dict_counter(dict_arg):
d = {'AMER':[],'EMEA':[],'JP':[]} # Regions as keys.
for int_key in dict_arg:
sub_dict = dict_arg[int_key]
for key, value in sub_di... | 1 | 2016-08-15T16:14:09Z | [
"python",
"dictionary",
"nested"
] |
Get counts of specific values within a nested Python dictionary | 38,958,380 | <p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p>
<pre><code>item_dict = {
64762.0: {
'In Sheet': 'No',
'Paid': Y,
'Region': "AMER'",
'Matrix Position': 'Check'
},
130301.0: {
'Paid': N,
... | 1 | 2016-08-15T15:47:18Z | 38,958,867 | <p>To get all combinations, you can use <code>itertools.product</code>. Then you can store the result in a dictionary:</p>
<pre><code>result = {}
for r, p in itertools.product(regions, positions):
result[(r,p)] = len( [None for item in item_dict.values() if item['Region'] == r and item['Matrix Position'] == p] )
... | 0 | 2016-08-15T16:17:31Z | [
"python",
"dictionary",
"nested"
] |
Get counts of specific values within a nested Python dictionary | 38,958,380 | <p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p>
<pre><code>item_dict = {
64762.0: {
'In Sheet': 'No',
'Paid': Y,
'Region': "AMER'",
'Matrix Position': 'Check'
},
130301.0: {
'Paid': N,
... | 1 | 2016-08-15T15:47:18Z | 38,959,121 | <p>Is it critical for you to use pure <code>Python</code>? I guess, if you wanted just to do this once, you could do this without care of performance or beauty, either you want to know something new.</p>
<p>What's about <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> library which can solve this problem ... | 0 | 2016-08-15T16:34:17Z | [
"python",
"dictionary",
"nested"
] |
requests.get returns <!doctype> instead <Response> | 38,958,492 | <p>I have an issue with requests.get().
If I paste the URL manually into the code as here:</p>
<pre><code>r = requests.get('https://berlin.kauperts.de/Strassen/Igelsteig-12557-Berlin.html')
print(r)
</code></pre>
<p>I get: <code><Response [200]></code>. Which works quite fine.
Instead if I try to ask for the re... | 0 | 2016-08-15T15:54:27Z | 38,958,539 | <p>If you want to see the <a href="http://docs.python-requests.org/en/master/api/#requests.Response" rel="nofollow"><code>Response</code></a> <em>string representation</em>, you should not be iterating over it, just print:</p>
<pre><code>url = urlparse.urljoin('https://berlin.kauperts.de/Strassen/', z)
response = requ... | 1 | 2016-08-15T15:57:38Z | [
"python",
"parsing",
"url",
"request",
"python-requests"
] |
Comparing content in two csv files | 38,958,591 | <p>So I have two csv files. <code>Book1.csv</code> has more data than <code>similarities.csv</code> so I want to pull out the rows in <code>Book1.csv</code> that <strong>do not</strong> occur in <code>similarities.csv</code> Here's what I have so far </p>
<pre><code> with open('Book1.csv', 'rb') as csvMasterForDi... | 1 | 2016-08-15T16:00:57Z | 38,958,706 | <p>A <code>csv.reader</code> object is an <em>iterator</em>, which means you can only iterate through it <strong>once</strong>. You should be using lists/sets for containment checking, e.g.:</p>
<pre><code>slave_rows = set(slaveReaderDiff)
for row in masterReaderDiff:
if row not in slave_rows:
testNotInCo... | 1 | 2016-08-15T16:08:16Z | [
"python",
"csv"
] |
Comparing content in two csv files | 38,958,591 | <p>So I have two csv files. <code>Book1.csv</code> has more data than <code>similarities.csv</code> so I want to pull out the rows in <code>Book1.csv</code> that <strong>do not</strong> occur in <code>similarities.csv</code> Here's what I have so far </p>
<pre><code> with open('Book1.csv', 'rb') as csvMasterForDi... | 1 | 2016-08-15T16:00:57Z | 38,958,803 | <p>After converting it into <code>sets</code>, you can do a lot of <code>set</code> related & helpful operation without writing much of a code.</p>
<pre><code>slave_rows = set(slaveReaderDiff)
master_rows = set(masterReaderDiff)
master_minus_slave_rows = master_rows - slave_rows
common_rows = master_rows & sl... | 0 | 2016-08-15T16:13:55Z | [
"python",
"csv"
] |
Pandas: create json file from dataframe | 38,958,639 | <p>I have dataframe</p>
<pre><code>ID, visiting
111, 03.2015
111, 07.2015
111, 05.2016
222, 12.2013
222, 04.2016
333, 02.2014
333, 06.2015,
333, 11.2015
</code></pre>
<p>I need to get file like this(I need to specify all month since december 2013 to june 2016)</p>
<pre><code>{
"111": {
"2013-12": 0,
"2014-01": 0,... | -1 | 2016-08-15T16:03:45Z | 38,958,959 | <p>It would by more efficent using <code>groupby</code>s, but this gets the job done:</p>
<pre><code>txt = """ID, visiting
111, 03.2015
111, 07.2015
111, 05.2016
222, 12.2013
222, 04.2016
333, 02.2014
333, 06.2015
333, 11.2015"""
split = [line.split(', ') for line in txt.split('\n')]
df = pd.DataFrame(split[1:], col... | 0 | 2016-08-15T16:23:44Z | [
"python",
"json",
"pandas"
] |
Using python multiprocess outside the main script | 38,958,640 | <p>According to the <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing-programming" rel="nofollow">docs</a> of python's multiprocess the spawning of process needs to be inside of the <code>if __name__ == '__main__':</code> clause to prevent spawning infinite processes.</p>
<p>My question, ... | 0 | 2016-08-15T16:03:46Z | 38,959,596 | <p>Multiprocessing doesn't have to run within the <code>__main__</code> block, <code>__main__</code> block is only used if the file is ran via <code>python filename.py</code>.</p>
<p>So if you did:</p>
<p><code>m1.py</code>:</p>
<pre><code>from multiprocessing import Pool
def f(x):
return x^2
def f2():
... | 0 | 2016-08-15T17:05:34Z | [
"python",
"python-3.x",
"python-multithreading",
"python-multiprocessing"
] |
How to make a plot of data from several sheets in same excel file by using Python pandas | 38,958,654 | <p>I have 4 sheets, they have same numbers of columns and same numbers of data.</p>
<p>But I want to make a plot of pressure as y while date as X. So there will be four lines in one graph. I can make them separately but not all together. The date is all same in the four sheets but for each date, each sheet may have di... | 0 | 2016-08-15T16:04:36Z | 38,959,228 | <p>I'm assuming you are trying to merge and plot all the data coming from the four sheets. In this case, you could load data from each sheet into a pandas df and merge them together. This is made easier given that your sheets have the same amount of data.
You can use pandas directly:</p>
<pre><code>import pandas as p... | 0 | 2016-08-15T16:41:22Z | [
"python",
"excel",
"pandas"
] |
How to make a plot of data from several sheets in same excel file by using Python pandas | 38,958,654 | <p>I have 4 sheets, they have same numbers of columns and same numbers of data.</p>
<p>But I want to make a plot of pressure as y while date as X. So there will be four lines in one graph. I can make them separately but not all together. The date is all same in the four sheets but for each date, each sheet may have di... | 0 | 2016-08-15T16:04:36Z | 38,965,617 | <p>I don't have your excel file so you'll need to test it yourself.</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#sheetname=None will load all sheets in to a dict of dataframes
dict_of_df = pd.read_excel('mslp0.0001.xlsx', sheetname=None, index_col=None, na_values=['NA'])
ax ... | 0 | 2016-08-16T02:06:28Z | [
"python",
"excel",
"pandas"
] |
BeautifulSoup confused | 38,958,697 | <p>I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements:</p>
<pre><code><li class="spacer">
<span>Location:</span>
<br>Some Sample Stre... | 0 | 2016-08-15T16:07:41Z | 38,958,944 | <p>Try this out:</p>
<pre><code>locations = info.find_all('span',Class_="spacer")
for location in locations:
print (location.text)
</code></pre>
| 0 | 2016-08-15T16:22:47Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
BeautifulSoup confused | 38,958,697 | <p>I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements:</p>
<pre><code><li class="spacer">
<span>Location:</span>
<br>Some Sample Stre... | 0 | 2016-08-15T16:07:41Z | 38,977,308 | <p>You can use the <a href="https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#nextSibling%20and%20previousSibling" rel="nofollow">nextSibling</a> to navigate to the next elements inside the <code>li</code> and after the <code>span</code></p>
<p>Example:</p>
<pre><code>from bs4 import BeautifulSoup ... | 0 | 2016-08-16T14:15:39Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Python script doesn't delete file from archive -- printed command via terminal works fine | 38,958,760 | <p>I'm creating an archive in Python using this code:</p>
<pre><code>#Creates archive using string like [proxy_16-08-15_08.57.07.tar]
proxyArchiveLabel = 'proxy_%s' % EXECUTION_START_TIME + '.tar'
log.info('Packaging %s ...' % proxyArchiveLabel)
#Removes .tar from label during creation
shutil.make_archive(proxyArchiv... | 0 | 2016-08-15T16:11:21Z | 38,958,998 | <p>You may have to use the <code>--wildcards</code> option in the tar command, which enables pattern matching. This may well be what you are seeing in your log, be it somewhat cryptically.</p>
<p>Edit:
In answer to your question Why? I suspect that the shell is performing the wildcard expansion whilst the command prof... | 2 | 2016-08-15T16:26:36Z | [
"python",
"python-2.7",
"command",
"archive"
] |
browser automation with PhantomJS and Firefox, support of the different browsers | 38,958,761 | <p>Why the code works with webdriver.Firefox but do not work with webdriver.PhantomJS ?</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.PhantomJS() # why not?
# driver.set_window_size(1400, 1050)
# driver = webdriver.Firefox() # Firefox 45, works corre... | 1 | 2016-08-15T16:11:21Z | 38,959,160 | <p>You should try using <code>.click()</code> for click purpose instead of <code>send_keys(Keys.RETURN)</code> as below :</p>
<pre><code>driver.find_element_by_id('search-submit').click()
</code></pre>
| 0 | 2016-08-15T16:36:40Z | [
"python",
"selenium",
"selenium-webdriver",
"phantomjs",
"browser-automation"
] |
Not getting ord() of hexadecimal values when reading from file | 38,958,786 | <p>Suppose <code>a = '\x00\x01\x02'</code></p>
<p>Now when I use <code>ord()</code> by looping through <code>a</code>, I get the output I want.</p>
<p><strong>Program:</strong></p>
<pre><code>for i in a:
ord(i)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>0
1
2
</code></pre>
<p>But now when I do t... | -2 | 2016-08-15T16:12:47Z | 38,958,861 | <p>The problem is that you're iterating over the file line by line, but the string character by character.</p>
<p>The easiest way is to either use a second nested loop, or <code>map</code>.</p>
<pre><code>with open('abc.txt') as input_file:
for line in input_file:
for character in line:
prin... | 2 | 2016-08-15T16:17:14Z | [
"python",
"python-2.7"
] |
Add data to Django database through views or JSON dictionary | 38,958,844 | <p>I have been searching through various opensource forums for a definitive answer on how to do this. I am open to any number of methods, but I am a little green at Django and Python for that matter so please bare with me. </p>
<p>The simplest of my tables is as follows:</p>
<pre><code>class Player(models.Model):
n... | 0 | 2016-08-15T16:15:59Z | 38,958,907 | <p>I can suggest two options:</p>
<ol>
<li>Through the view. Eventually you create a <code>FormView</code> with a form to upload a file or just a textbox and handle the json on backend.</li>
<li>You may create a manage.py command that receives path to a file as a parameter.</li>
</ol>
<p>In both cases handling of you... | 0 | 2016-08-15T16:20:16Z | [
"python",
"json",
"django",
"models"
] |
Appengine throwing BadRequestError: The property.name is the empty string | 38,958,864 | <p>I have an application that has worked successfully in the past. Today however, it's started throwing an error when I try write to datastore. For example, I'm creating a new entity of this model</p>
<pre><code> class EventInstallment(ndb.Model):
somekey = ndb.KeyProperty()
somename = ndb.StringPro... | 0 | 2016-08-15T16:17:18Z | 38,960,654 | <p>Shouldn't <code>notes = ndb.StringProperty("")</code> be: <code>notes = ndb.StringProperty(default = "")</code> ?</p>
| 1 | 2016-08-15T18:19:00Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] |
only 404s returned when using ngrok for kik | 38,958,913 | <p>I'm trying to develop a kik bot. I used ngrok to tunnel my localhost to a ngrok server. However, whenever I run my python program and start the ngrok server and message the bot on my phone, all it returns are 404 errors. Here is my python code </p>
<pre><code>from flask import Flask, request, Response
import os
fr... | 0 | 2016-08-15T16:20:38Z | 39,002,146 | <p>I figured it out. I changed the route in the code from "/incoming" to "/". That allowed for the right response. </p>
| 0 | 2016-08-17T16:45:05Z | [
"python",
"flask",
"http-status-code-404",
"bots",
"ngrok"
] |
How to plot a "grouped scatterplot" with non-categorical data? | 38,958,925 | <p>I am a bit confused how to use <code>seaborn.stripplot()</code> to plot multiple columns of data points when these data do not have "categorical" labels. </p>
<p>For example, users can plot "grouped" scatterplots as follows, with the <code>tips</code> dataset:</p>
<pre><code>import numpy as np
import pandas as pd
... | 0 | 2016-08-15T16:21:25Z | 38,959,936 | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> the dataframe and name the parameters accordingly to apply to the <code>stripplot</code> as follows:</p>
<pre><code>df_strip = pd.melt(df, var_name='total_bill', value_name='price')
sns.stri... | 3 | 2016-08-15T17:31:15Z | [
"python",
"pandas",
"matplotlib",
"plot",
"seaborn"
] |
Python descending list | 38,958,929 | <p>I want to make a functions which return false if the list input in the function is not in descending order ,</p>
<p>now for descending([19,17,18,7]) it returns true </p>
<p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p>
<pre><code>def des(l):
for i in rang... | 0 | 2016-08-15T16:21:34Z | 38,959,030 | <p>Try this out:</p>
<pre><code>def des(l):
for x in l:
try:
if x < l[l.index(x)+1 ]-1:
return True
except:
pass
return False
</code></pre>
| 0 | 2016-08-15T16:28:42Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python descending list | 38,958,929 | <p>I want to make a functions which return false if the list input in the function is not in descending order ,</p>
<p>now for descending([19,17,18,7]) it returns true </p>
<p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p>
<pre><code>def des(l):
for i in rang... | 0 | 2016-08-15T16:21:34Z | 38,959,034 | <p>It can be written in a more declarative way:</p>
<pre><code>def is_descending(array):
return array == sorted(array, reverse=True)
</code></pre>
<p>Or, for python3:</p>
<pre><code>def is_descending(array):
return array == list(sorted(array, reverse=True))
</code></pre>
| 3 | 2016-08-15T16:28:51Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python descending list | 38,958,929 | <p>I want to make a functions which return false if the list input in the function is not in descending order ,</p>
<p>now for descending([19,17,18,7]) it returns true </p>
<p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p>
<pre><code>def des(l):
for i in rang... | 0 | 2016-08-15T16:21:34Z | 38,959,036 | <p>Your code doesn't work because you are returning <code>True</code>/<code>False</code> after one check. You should return <code>True</code> only after you check the entire list. Following is one way of doing it:</p>
<pre><code>def des(l):
for i in range(1,len(l)):
if (l[i] > l[i-1]):
retur... | 2 | 2016-08-15T16:28:56Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python descending list | 38,958,929 | <p>I want to make a functions which return false if the list input in the function is not in descending order ,</p>
<p>now for descending([19,17,18,7]) it returns true </p>
<p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p>
<pre><code>def des(l):
for i in rang... | 0 | 2016-08-15T16:21:34Z | 38,959,057 | <p>Here is another way to write your function:</p>
<pre><code>def des(l):
return all(i>j for i,j in zip(l,l[1:]))
</code></pre>
| 1 | 2016-08-15T16:30:32Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python descending list | 38,958,929 | <p>I want to make a functions which return false if the list input in the function is not in descending order ,</p>
<p>now for descending([19,17,18,7]) it returns true </p>
<p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p>
<pre><code>def des(l):
for i in rang... | 0 | 2016-08-15T16:21:34Z | 38,959,066 | <p>The problem is that you only ever make one check, and always <em>immediately</em> return <code>True</code> or <code>False</code>.</p>
<p>Instead, you shouldn't be returning `True until you have checked the whole list:</p>
<pre><code>def des(l):
for i in range(len(l)):
if (l[i]<l[i+1]):
r... | 1 | 2016-08-15T16:31:04Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python descending list | 38,958,929 | <p>I want to make a functions which return false if the list input in the function is not in descending order ,</p>
<p>now for descending([19,17,18,7]) it returns true </p>
<p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p>
<pre><code>def des(l):
for i in rang... | 0 | 2016-08-15T16:21:34Z | 38,959,087 | <pre><code>def des(l):
for i in range(len(l)):
if (l[i]<l[i+1]):
return [False,i]
return True
</code></pre>
<p>You return True if its not false, You must only return true when the entire for loop has run through. Therefore it must be outside the for loop. If once the loop has run throug... | 0 | 2016-08-15T16:32:05Z | [
"python",
"python-2.7",
"python-3.x"
] |
adding values of dictionaries in python | 38,959,089 | <p>I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:</p>
<pre><code>{'match1': {'player1': 57, 'player2': 38},
'match2': {'player3': 9, 'player1': 42},
'match3': {'player2': 41, 'player4': 63, 'player3': 91}}... | -5 | 2016-08-15T16:32:21Z | 38,959,194 | <pre><code>def score(match):
players = {}
for key in match:
for player in match[key]:
if player not in players:
players[player] =match[key][player]
else:
players[player]+=match[key][player]
return players
</code></pre>
<p>Quick overview, if th... | 0 | 2016-08-15T16:39:31Z | [
"python",
"python-2.7",
"python-3.x",
"dictionary"
] |
adding values of dictionaries in python | 38,959,089 | <p>I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:</p>
<pre><code>{'match1': {'player1': 57, 'player2': 38},
'match2': {'player3': 9, 'player1': 42},
'match3': {'player2': 41, 'player4': 63, 'player3': 91}}... | -5 | 2016-08-15T16:32:21Z | 38,959,235 | <p>Iterate over the nested <code>dictionary</code> and add up scores to a dictionary of player totals.</p>
<pre><code>def find_totals(d):
total = {}
for match, results in d.items():
for player, score in results.items():
total[player] = total.get(player, 0) + score
return total
</code></... | 2 | 2016-08-15T16:41:52Z | [
"python",
"python-2.7",
"python-3.x",
"dictionary"
] |
adding values of dictionaries in python | 38,959,089 | <p>I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:</p>
<pre><code>{'match1': {'player1': 57, 'player2': 38},
'match2': {'player3': 9, 'player1': 42},
'match3': {'player2': 41, 'player4': 63, 'player3': 91}}... | -5 | 2016-08-15T16:32:21Z | 38,959,903 | <p>Here is the solution for your problem,</p>
<pre><code>d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}}
players = {}
for key, val in enumerate(d):
#print val
for ele,value in enumerate(d[val]):
#print value
... | 0 | 2016-08-15T17:29:18Z | [
"python",
"python-2.7",
"python-3.x",
"dictionary"
] |
How to deploy Django project without fabric | 38,959,099 | <p>This might be a dumb question, maybe not. I'm currently done with the development of a Django project and would like to deploy it. Since Python 3 is not supported by Fabric. I need to install and configure things by myself I guess.</p>
<p>So the question I have is what software should I use in the virtualenv of my ... | 0 | 2016-08-15T16:32:53Z | 38,959,291 | <ol>
<li><p>All of these are system-wide software and not merely python packages. </p></li>
<li><p>Fabric doesn't work in your server, what it does is only to read the <code>fabfile.py</code>, connect to your server and take actions according to file. So you can install Fabric to your python2.7 site-packages, and still... | 0 | 2016-08-15T16:45:33Z | [
"python",
"django",
"python-3.x",
"nginx"
] |
How to deploy Django project without fabric | 38,959,099 | <p>This might be a dumb question, maybe not. I'm currently done with the development of a Django project and would like to deploy it. Since Python 3 is not supported by Fabric. I need to install and configure things by myself I guess.</p>
<p>So the question I have is what software should I use in the virtualenv of my ... | 0 | 2016-08-15T16:32:53Z | 38,961,278 | <p>I'm using <a href="https://www.ansible.com/" rel="nofollow">Ansible</a> to do my deploys. With Ansible I can provision all my server and do deploys easily. I recommend.</p>
| 0 | 2016-08-15T18:59:39Z | [
"python",
"django",
"python-3.x",
"nginx"
] |
How to deploy Django project without fabric | 38,959,099 | <p>This might be a dumb question, maybe not. I'm currently done with the development of a Django project and would like to deploy it. Since Python 3 is not supported by Fabric. I need to install and configure things by myself I guess.</p>
<p>So the question I have is what software should I use in the virtualenv of my ... | 0 | 2016-08-15T16:32:53Z | 38,961,929 | <p>I have not tried memcached, but I can tell about the rest. </p>
<p>First, you install nginx and supervisord outside of virtualenv.</p>
<p>Second, in virtualenv using pip you install gunicorn. </p>
<p>Finally, you have got folder (e.g. /var/www/youproject/), and inside that folder you have virtualenv (/var/www/you... | 2 | 2016-08-15T19:44:10Z | [
"python",
"django",
"python-3.x",
"nginx"
] |
Multiply sequence by non-int of type 'str' | 38,959,103 | <p>Hey guys im new here and im just starting out.
I tried to make a BMI calculator by simply getting input and doing calculations but it doesn't work for some reason.
This is the program:</p>
<pre><code>print "how old are you?",
age = raw_input()
print "how tall are you?",
height = raw_input()
print "how much do you w... | -1 | 2016-08-15T16:33:13Z | 38,962,061 | <p>Your user input values are strings. You are trying to perform mathematical operations on them. You need to convert them to numbers first.</p>
<p>Here is a question that will set you on the path to converting the strings to integers: <a href="http://stackoverflow.com/questions/642154/how-to-convert-strings-into-int... | 0 | 2016-08-15T19:52:10Z | [
"python",
"string"
] |
Multiply sequence by non-int of type 'str' | 38,959,103 | <p>Hey guys im new here and im just starting out.
I tried to make a BMI calculator by simply getting input and doing calculations but it doesn't work for some reason.
This is the program:</p>
<pre><code>print "how old are you?",
age = raw_input()
print "how tall are you?",
height = raw_input()
print "how much do you w... | -1 | 2016-08-15T16:33:13Z | 38,988,169 | <p>With your help, this is the working code:</p>
<p>print "how old are you?",</p>
<p>age = int(raw_input())</p>
<p>print "how tall are you?",</p>
<p>height = float(raw_input())</p>
<p>print "how much do you weigh?",</p>
<p>weight = float(raw_input())</p>
<p>print "So, you're %r years old, %r meters tall and %r K... | 0 | 2016-08-17T04:33:51Z | [
"python",
"string"
] |
Accessing mangled member of another instance | 38,959,180 | <p>I use this logic to maintain a directed tree of <code>Object</code> instances :</p>
<pre><code>class Object:
def __init__(self, *parents: 'Object'):
self.__parents = list(parents)
@property
def __ascendants(self):
for parent in self.__parents:
yield from parent.__ascendants
... | 1 | 2016-08-15T16:38:33Z | 38,961,467 | <p>Why are you making the <code>ascendants</code> method a mangled property? If you really want to use such a complicated inheritance and keep multiple <code>parents</code> attribute for each of superclasses, mangling <code>parents</code> will work. However, it seems like there is no use in mangling <code>ascendants</c... | 1 | 2016-08-15T19:12:09Z | [
"python",
"oop",
"code-analysis",
"pylint",
"private-members"
] |
Accessing mangled member of another instance | 38,959,180 | <p>I use this logic to maintain a directed tree of <code>Object</code> instances :</p>
<pre><code>class Object:
def __init__(self, *parents: 'Object'):
self.__parents = list(parents)
@property
def __ascendants(self):
for parent in self.__parents:
yield from parent.__ascendants
... | 1 | 2016-08-15T16:38:33Z | 39,068,082 | <blockquote>
<p>I'm looking for a way to make PyLint accept accessing mangled attributes of a client subclass</p>
</blockquote>
<p>There are ways to fool pylint.</p>
<p>One way is to disguise <code>parent</code> as <code>self</code>:</p>
<pre><code>@property
def __ascendants(self):
for parent in self.__parents... | 1 | 2016-08-21T19:29:06Z | [
"python",
"oop",
"code-analysis",
"pylint",
"private-members"
] |
"with", context manager, python: What's going on in simple terms? | 38,959,182 | <p>Novice Python coder here coming from a Java background. I'm still puzzled by this:</p>
<pre><code>with open(...) as f:
do_something(f)
</code></pre>
<p>even after Googling and reading some of the answers here (I just couldn't get my head around them).</p>
<p>My understanding is that there is this thing called... | -1 | 2016-08-15T16:38:38Z | 38,959,232 | <p>File objects <em>are themselves context managers</em>, in that they have <a href="https://docs.python.org/2/library/stdtypes.html#contextmanager.__enter__" rel="nofollow"><code>__enter__</code></a> and <a href="https://docs.python.org/2/library/stdtypes.html#contextmanager.__exit__" rel="nofollow"><code>__exit__</co... | 3 | 2016-08-15T16:41:47Z | [
"python",
"with-statement"
] |
"with", context manager, python: What's going on in simple terms? | 38,959,182 | <p>Novice Python coder here coming from a Java background. I'm still puzzled by this:</p>
<pre><code>with open(...) as f:
do_something(f)
</code></pre>
<p>even after Googling and reading some of the answers here (I just couldn't get my head around them).</p>
<p>My understanding is that there is this thing called... | -1 | 2016-08-15T16:38:38Z | 38,959,274 | <p>Context managers are fairly simple beasts ... They're simply classes that define <a href="https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers" rel="nofollow">two separate methods</a> (<a href="https://docs.python.org/3/reference/datamodel.html#object.__enter__" rel="nofollow"><code>__e... | 0 | 2016-08-15T16:44:25Z | [
"python",
"with-statement"
] |
"with", context manager, python: What's going on in simple terms? | 38,959,182 | <p>Novice Python coder here coming from a Java background. I'm still puzzled by this:</p>
<pre><code>with open(...) as f:
do_something(f)
</code></pre>
<p>even after Googling and reading some of the answers here (I just couldn't get my head around them).</p>
<p>My understanding is that there is this thing called... | -1 | 2016-08-15T16:38:38Z | 38,959,585 | <p>This is the most basic context manager you could create:</p>
<pre><code>class UselessContextManager(object):
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
with UselessContextManager() as nothing:
print(nothing is None)
</code></pre>
<p>If you want to get a... | 0 | 2016-08-15T17:04:59Z | [
"python",
"with-statement"
] |
openpyxl - get input from QLineEdit and save in excel | 38,959,214 | <p>I want to use openpyxl to get the user input from a QLineEdit and save it to an Excel file. The script below works well when no QLineEdit is envolved but is not working under openpyxl. The error message I get is: cannot convert QlineEdit to Excel. </p>
<pre><code>self.le.setText(str(text))
text = self.le.text()
wb ... | 0 | 2016-08-15T16:40:37Z | 38,959,397 | <p>Its possible that with more code I could provide a more certain answer, but QT has several problems with typing in python. More specifically it returns 'Qtypes' for a lot of common python types that need to be manually converted before they can be serialized. Try this:</p>
<pre><code>self.le.setText(str(text))
text... | 1 | 2016-08-15T16:52:29Z | [
"python",
"openpyxl"
] |
Python and Listbox (GUI) | 38,959,246 | <p>I have constructed a listbox using tkinter
Now I want the user to click on an item in the listbox that creates a variable with the selection. </p>
<pre><code>listbox.bind('<ButtonRelease-1>', get_list)
def get_list(event):
index = listbox.curselection()[0]
seltext = listbox.get(index)
print(selte... | 1 | 2016-08-15T16:42:48Z | 38,959,824 | <p>This is an issue with how you are structuring your code more than anything. Event handlers are not built to return values. Use a global variable or class property to retrieve and store the value. A global variable can be set like so:</p>
<pre><code>from Tkinter import *
def get_list(event):
global seltext
... | 1 | 2016-08-15T17:23:14Z | [
"python",
"user-interface",
"tkinter"
] |
Manipulating web pages with python | 38,959,269 | <p>My aim is to be able to automatically manipulate a web page with a script. Filling in information and selecting the correct drop down box. With minimal user input. </p>
<p>So my example here I'm using the national rail website. </p>
<pre><code>import win32com.client
from time import sleep
ie = win32com.client.Dis... | 1 | 2016-08-15T16:43:55Z | 38,959,434 | <p>While I'm sure every Python user can appreciate you trying to do this in the most difficult way possible, why not make things easier for yourself and use the library <a href="http://selenium-python.readthedocs.io/getting-started.html" rel="nofollow">Selenium?</a></p>
<p>Here's your code & what you're trying to ... | 1 | 2016-08-15T16:54:58Z | [
"python",
"python-3.x",
"win32com"
] |
Python Socket Server Can Only Handle 1 Client at a time | 38,959,333 | <p>I am trying to make a server-client program using threads to handle each client, but the server will only accept one client at a time. If the first client disconnects, then the second client is accepted. Furthermore, each client can only send data once, then the program fails to send any more.</p>
<p>Prior to posti... | 0 | 2016-08-15T16:47:52Z | 38,959,657 | <p>Thanks to user Rawing. His/Her solution was: Thread(target=clienââthandler(c)) -> Thread(target=clienââthandler, args=(c,))
This allowed for more than one thread, and I was able to solve the only one message problem by putting the client send block in a while loop.</p>
| 0 | 2016-08-15T17:10:44Z | [
"python",
"multithreading",
"sockets"
] |
Convert XML to CSV with python | 38,959,337 | <p>I have the following XML files that need to be converted to CSV for Magento import. Under
<code><values> <Value AttributeID="attributes"></Value></code> there are a few hundred possibilities that are different for each product. </p>
<p>I've tried using <code>xml2csv</code> and <code>xmlutils.xml2... | 0 | 2016-08-15T16:48:23Z | 38,959,631 | <p>I'm not familiar with "Magento", but this program converts your XML file to a CSV file. The resulting CSV file has one column for <code>Name</code> and one column for each <code>Value</code>.</p>
<pre><code>from xml.etree import ElementTree as ET
import csv
tree = ET.parse('x.xml')
root = tree.getroot()
columns =... | 0 | 2016-08-15T17:08:39Z | [
"python",
"xml",
"csv",
"magento"
] |
Efficently multiply a matrix with itself after offsetting it by one in numpy | 38,959,365 | <p>I am trying to write a function that takes a matrix A, then offsets it by one, and does element wise matrix multiplication on the shared area. Perhaps an example will help. Suppose I have the matrix:</p>
<pre><code>A = np.array([[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>What i'd like returned is:
(1*2) + (4*5... | 0 | 2016-08-15T16:50:05Z | 38,961,194 | <p>In this 3 column case, you are just multiplying the 1st 2 columns, and taking the sum:</p>
<pre><code>A[:,:2].prod(1).sum()
Out[36]: 78
</code></pre>
<p>Same as <code>(A[:,0]*A[:,1]).sum()</code></p>
<p>Now just how does that generalize to more columns?</p>
<p>In your original loop, you can cut out the row iter... | 0 | 2016-08-15T18:54:50Z | [
"python",
"numpy"
] |
Python Regexp for extracting tags and words | 38,959,382 | <p>I have the following string:</p>
<pre><code>str1 = "I/TAG1 like/TAG2 red/TAG3 apples/TAG3 ./TAG4"
</code></pre>
<p>And I have two lists in python</p>
<pre><code>tokens = []
tags = []
</code></pre>
<p>My desired output would be:</p>
<pre><code>tokens = ['I', 'like', 'red', 'apples', '.']
tags = ['TAG1', 'TAG2', ... | 2 | 2016-08-15T16:51:16Z | 38,959,428 | <p>You can use:</p>
<pre><code>>>> re.findall(r'([\w.]+)/([\w.]+)', str1)
[('I', 'TAG1'), ('like', 'TAG2'), ('red', 'TAG3'), ('apples', 'TAG3'), ('.', 'TAG4')]
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>>>> tags=[]
>>> vals=[]
>>> for m in re.findall(r'([\w.]+)/([\w.]... | 4 | 2016-08-15T16:54:39Z | [
"python",
"regex",
"python-2.7",
"tokenize"
] |
Python Regexp for extracting tags and words | 38,959,382 | <p>I have the following string:</p>
<pre><code>str1 = "I/TAG1 like/TAG2 red/TAG3 apples/TAG3 ./TAG4"
</code></pre>
<p>And I have two lists in python</p>
<pre><code>tokens = []
tags = []
</code></pre>
<p>My desired output would be:</p>
<pre><code>tokens = ['I', 'like', 'red', 'apples', '.']
tags = ['TAG1', 'TAG2', ... | 2 | 2016-08-15T16:51:16Z | 38,959,488 | <p>You can use a combination of <code>str.split()</code> by space and by slash. Then calling <code>zip()</code> to pipe the output into two separate lists:</p>
<pre><code>>>> tokens, tags = zip(*[item.split("/") for item in str1.split()])
>>> tokens
('I', 'like', 'red', 'apples', '.')
>>> ta... | 2 | 2016-08-15T16:58:13Z | [
"python",
"regex",
"python-2.7",
"tokenize"
] |
How to call the functions present in one .py file from other .py file? | 38,959,396 | <p>I have two files and I'd like to import a class from the other file.</p>
<p>File <code>one.py</code>:</p>
<pre><code>class One:
def printNumber( self, a ):
print (a)
</code></pre>
<p>and file <code>two.py</code>:</p>
<pre><code>#import One # gives error no module named One
#import one # gives error ... | -3 | 2016-08-15T16:52:18Z | 38,959,562 | <p><strong>Keep the files in the same directory</strong> then use something like the below format.</p>
<pre><code>from one import One
one = One()
class Two:
a = 5
one.printNumber(a)
</code></pre>
<p>Edit: When working in Pycharm you need to mark your sources root to import your own files.</p>
<p><a href="h... | 0 | 2016-08-15T17:03:26Z | [
"python",
"python-3.x",
"import"
] |
Pygame screen is read-only | 38,959,441 | <p>I'm working on a pygame program, and want to display some text on the screen.</p>
<p>I define my screen here:</p>
<pre><code>screenDi = pygame.display.Info()
height = screenDi.current_h
width = screenDi.current_w
size = width, height
screen = pygame.display.set_mode(size)
</code></pre>
<p>and define my text funct... | 0 | 2016-08-15T16:55:22Z | 38,959,491 | <p>blit() is a function, but you're trying to assign it:</p>
<pre><code>screen.blit = (text,[x,y])
</code></pre>
<p>Try it without the = :</p>
<pre><code>screen.blit(text,[x,y])
</code></pre>
| 1 | 2016-08-15T16:58:19Z | [
"python",
"pygame",
"blit"
] |
Draw Line chart with openpyxl - Axis/drawing issue | 38,959,471 | <p>I'm having problems getting the LineChart() feature of Openpyxl to draw the chart in the way that I'd like it. </p>
<p>I've been using the documentation on <a href="http://openpyxl.readthedocs.io/en/default/charts/line.html" rel="nofollow">the official page</a>, but I get <a href="http://i.stack.imgur.com/8ig1c.jpg... | -1 | 2016-08-15T16:57:20Z | 39,069,632 | <p>This was solved by writing the new data to a new sheet after reading it. </p>
<p>The way it was originally meant that it wasn't using the correct axis orientation, so the revised code below appends the content of the masterList to a new sheet of the workbook, in data columns (as opposed to rows), as is shown in the... | 0 | 2016-08-21T23:13:40Z | [
"python",
"excel",
"graph",
"openpyxl"
] |
How to iterate a large table in Django without running out of memory? | 38,959,478 | <p>I have a Django model whose table has millions of records in it. I'm trying to do some emergency maintenance on all of the records in the table at a shell but I'm unable to do a <code>MyModel.objects.all()</code> without completely exhausting memory on my system.</p>
<p>Even a <code>pass</code> causes the OOM kill... | 0 | 2016-08-15T16:57:41Z | 38,959,523 | <p>You might not be able to fit all of the full records in memory, but there's a good chance you can fit all of the primary keys in memory. So you can iterate the list of all primary keys and do a <code>.get()</code> on each one and operate on the records individually:</p>
<pre><code>for pk in MyModel.objects.values_... | 0 | 2016-08-15T17:00:21Z | [
"python",
"django"
] |
How to iterate a large table in Django without running out of memory? | 38,959,478 | <p>I have a Django model whose table has millions of records in it. I'm trying to do some emergency maintenance on all of the records in the table at a shell but I'm unable to do a <code>MyModel.objects.all()</code> without completely exhausting memory on my system.</p>
<p>Even a <code>pass</code> causes the OOM kill... | 0 | 2016-08-15T16:57:41Z | 38,959,569 | <p>The first thing to try is using the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#iterator" rel="nofollow"><code>iterator()</code></a> method on the queryset before iterating over it:</p>
<pre><code>for ii in MyModel.objects.all().iterator():
</code></pre>
| 3 | 2016-08-15T17:04:02Z | [
"python",
"django"
] |
How to iterate a large table in Django without running out of memory? | 38,959,478 | <p>I have a Django model whose table has millions of records in it. I'm trying to do some emergency maintenance on all of the records in the table at a shell but I'm unable to do a <code>MyModel.objects.all()</code> without completely exhausting memory on my system.</p>
<p>Even a <code>pass</code> causes the OOM kill... | 0 | 2016-08-15T16:57:41Z | 38,959,702 | <p>If you are using python3.X you can try some async tasks.</p>
<p>It may be useful to create a schedule fetch.</p>
<p>Something like this:</p>
<pre><code>async def _fetch_all(self):
if self._result_cache is None:
self._result_cache = await list(self.iterator()) # <<<< this guy!
if s... | 0 | 2016-08-15T17:13:40Z | [
"python",
"django"
] |
Python regex - find patterns in a file and put them in a list | 38,959,481 | <p>I am trying to use regex to find all the matched patterns in a BibTex file. The file looks like this:</p>
<pre><code>bib_file = """
@article{Fu_2007_ssr,
doi = {10.1016/j.surfrep.2007.07.001}
}
@article{Shibuya_2007_apl,
doi = {10.1063/1.2816907}
}
"""
</code></pre>
<p>My goal is to find all the matched patterns... | 1 | 2016-08-15T16:57:48Z | 38,959,605 | <p>You can match all these articles with</p>
<pre><code>r"(@article.*?\n[ \t]*}[ \t]*)(?:\n|$)"
</code></pre>
<p>(to be used with <code>re.DOTALL</code> modifier for the <code>.</code> to match any char incl. a newline). See the <a href="https://regex101.com/r/pO5hP6/2" rel="nofollow">regex demo</a></p>
<p><strong>P... | 1 | 2016-08-15T17:06:20Z | [
"python",
"regex"
] |
Python regex - find patterns in a file and put them in a list | 38,959,481 | <p>I am trying to use regex to find all the matched patterns in a BibTex file. The file looks like this:</p>
<pre><code>bib_file = """
@article{Fu_2007_ssr,
doi = {10.1016/j.surfrep.2007.07.001}
}
@article{Shibuya_2007_apl,
doi = {10.1063/1.2816907}
}
"""
</code></pre>
<p>My goal is to find all the matched patterns... | 1 | 2016-08-15T16:57:48Z | 38,959,776 | <p>Alternatively, you could use <a href="https://bibtexparser.readthedocs.io/en/v0.6.2/" rel="nofollow"><code>bibtexparser</code></a> which saves you all the trouble:</p>
<pre><code>>>> import bibtexparser
>>> bib_file = """
... @article{Fu_2007_ssr,
... doi = {10.1016/j.surfrep.2007.07.001}
... }
..... | 1 | 2016-08-15T17:18:37Z | [
"python",
"regex"
] |
maximal subset of integers that are not evenly divisible by k | 38,959,567 | <p>This is a practice problem I am solving:</p>
<p>Given a set S of distinct integers, print the size of a maximal subset S' of S where the sum of any 2 numbers in S' are not evenly divisible by k.</p>
<p>My approach was to limit the problem to the subset <code>S[0...i]</code> where 0 < i <= n-1 and determine ... | -1 | 2016-08-15T17:03:51Z | 38,960,396 | <p>Your lack of comments and explanatory names makes your code very hard to follow, so I do not understand it. (Your example using a list when you talk of sets, and the use of both <code>s</code> and <code>S</code> for your "set", do not help.) However, the basic idea of your algorithm is flawed: this problem for a giv... | 2 | 2016-08-15T18:01:16Z | [
"python",
"algorithm"
] |
Re-defining already assigned python class | 38,959,609 | <p>I am new to Python and I inherited someone's code that had the following code structure. Why do I get an object not callable and how can I redefine this method again even after re-assigning l.bar. Another question would therefore be what's the difference between l.bar and l.bar()?</p>
<pre><code>>>> class ... | -2 | 2016-08-15T17:06:33Z | 38,959,712 | <p>As others have pointed out, it's generally not good practice to have nested classes. But, here's a breakdown of what's happening:</p>
<pre><code>class foo(object):
def __init__(self):
self.name = "Food"
class bar(object):
def __init__(self):
self.name = "Is"
class tea(o... | 2 | 2016-08-15T17:14:12Z | [
"python",
"oop",
"inner-classes"
] |
Re-defining already assigned python class | 38,959,609 | <p>I am new to Python and I inherited someone's code that had the following code structure. Why do I get an object not callable and how can I redefine this method again even after re-assigning l.bar. Another question would therefore be what's the difference between l.bar and l.bar()?</p>
<pre><code>>>> class ... | -2 | 2016-08-15T17:06:33Z | 38,959,726 | <blockquote>
<p>Why do i get an object not callable</p>
</blockquote>
<p>You assigned <code>l.bar</code> to be an instance of the class <code>foo.bar</code> (specifically, you assigned <code>m</code> to it). Instances of that class aren't callable, therefore <code>l.bar</code> isn't callable.</p>
<blockquote>
<p>... | 1 | 2016-08-15T17:14:59Z | [
"python",
"oop",
"inner-classes"
] |
Re-defining already assigned python class | 38,959,609 | <p>I am new to Python and I inherited someone's code that had the following code structure. Why do I get an object not callable and how can I redefine this method again even after re-assigning l.bar. Another question would therefore be what's the difference between l.bar and l.bar()?</p>
<pre><code>>>> class ... | -2 | 2016-08-15T17:06:33Z | 38,959,743 | <p>It is not clear which of the following problems you are experiencing:</p>
<h1>1. indentation issue</h1>
<p>When copy-pasting from source to terminal, indentation sometimes gets messed up. in ipython you can use <code>%paste</code> to safely paste code.</p>
<p>The correctly indented class declarations are:</p>
<p... | 0 | 2016-08-15T17:16:18Z | [
"python",
"oop",
"inner-classes"
] |
Loop between 2 csv files stops at first mach | 38,959,621 | <p>I have 2 <code>csv</code> files: the source file has only one column with IDs (one ID per line). The 2nd <code>csv</code> file has the IDs plus extra info. I would like to check each ID from <code>file1</code> against all the records in <code>file2</code> and if there is a match, to print out the row that matched (f... | 1 | 2016-08-15T17:08:00Z | 38,959,790 | <p>You're specifically referring to line[0]. That's why it's only giving you the first match. Your loop is going X amount of times (x being how many lines are in the csv), but still checking to see if line[0] is in <code>mine</code>every loop iteration.</p>
<p>Try this:</p>
<pre><code>import csv
source = csv.reader(o... | 1 | 2016-08-15T17:19:48Z | [
"python",
"python-3.x",
"csv",
"for-loop"
] |
Loop between 2 csv files stops at first mach | 38,959,621 | <p>I have 2 <code>csv</code> files: the source file has only one column with IDs (one ID per line). The 2nd <code>csv</code> file has the IDs plus extra info. I would like to check each ID from <code>file1</code> against all the records in <code>file2</code> and if there is a match, to print out the row that matched (f... | 1 | 2016-08-15T17:08:00Z | 38,960,086 | <p>Well after you iterate through the second <code>.csv</code> in your inner loop you reach the end and no new lines can be read again.</p>
<p>You should be using something like this where the second file is going to <code>seek(0)</code> to go back to the beginning after the inner loop breaks. Also, it is advisable to... | 1 | 2016-08-15T17:41:27Z | [
"python",
"python-3.x",
"csv",
"for-loop"
] |
Reading C structures in Python with ctypes | 38,959,713 | <p>I'm using ctypes to call foreign functions in Python3.</p>
<p>The C function is supposed to return the pointer to the structure:</p>
<pre><code>struct sLinkedList {
void* data;
struct sLinkedList* next;
};
typedef struct sLinkedList* LinkedList;
</code></pre>
<p>And the function as it is defined in C is... | 4 | 2016-08-15T17:14:12Z | 38,960,415 | <p>Well, looks like i've solved it by myself:</p>
<pre><code>IedConnection_getServerDirectory.restype = c_int
</code></pre>
<p>is incorrect and shall was changed to:</p>
<pre><code>IedConnection_getServerDirectory.restype = c_void_p
</code></pre>
<p><strong>And it started working fine already.</strong></p>
<p>But ... | 2 | 2016-08-15T18:01:53Z | [
"python",
"c",
"ctypes"
] |
tensorflow.merge_all_summaries() hangs | 38,959,733 | <p>I've been having a problem where if I run <code>sess.run(tf.merge_all_summaries())</code> during training, the program will hang. This was also brought up in <a href="https://github.com/tensorflow/tensorflow/issues/3704" rel="nofollow">a github issue</a>, although I'm not sure that my problem is the same.</p>
<p>F... | 1 | 2016-08-15T17:15:42Z | 38,961,775 | <p>Your <code>summary_op</code> likely triggers a Queue dequeue which will hang when the queue is empty.</p>
<p>One work-around is to restructure your code using variables so that summaries don't trigger queue dequeue, like here --
<a href="http://stackoverflow.com/questions/36783560/tensorflow-reading-images-in-queue... | 1 | 2016-08-15T19:33:00Z | [
"python",
"tensorflow"
] |
testing client- server on the same computer | 38,959,744 | <p>I am trying to test socket communication on my laptop using python. However, I'm not sure why the connection is not being established? I keep getting error that the target machine is actively refusing connection. I am trying to use the same computer to run both the client and the server portion. The server is runnin... | 0 | 2016-08-15T17:16:19Z | 38,960,563 | <p>Your code won't work with python 2.* , because of the differences in <code>input()</code>, <code>raw_input()</code>, <code>bytes</code>, etc. in python 3.* vs python 2.* . You'd have to minimally make the following changes to get it working with python 2.*. Otherwise, use python 3 to run your code: </p>
<p>Server p... | 0 | 2016-08-15T18:12:38Z | [
"python",
"sockets",
"tcp",
"client",
"communication"
] |
UPDATED: Parsing JSON object in python when object contains an array and another associated object at the same level | 38,959,786 | <p>I'm having trouble with a JSON object being passed to me by one of our products API's. I'm using Python 2.7 to create a function to let our customer service team see details about jobs that are posted on our website. The JSON package returns an array of objects that each contain an array and an object. I need to rea... | -1 | 2016-08-15T17:19:33Z | 38,959,921 | <p>That content doesn't seem to be a valid json, which means you won't be able to parse it with the typical well-known <code>json.loads</code> function.</p>
<p>Also, you won't be able to use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow">ast.literal_eval</a> cos it's not a valid p... | 1 | 2016-08-15T17:30:20Z | [
"python",
"asp.net",
"arrays",
"json"
] |
Mapping set on new index is ignored | 38,959,794 | <p>Hi ! </p>
<p>I just started to learn ElasticSearch, and my first steps wasn't too bad. I put some data into with the help of the ES library available on Python with the following piece of code:</p>
<pre><code>from elasticsearch import Elasticsearch
jsondata(json.dumps("{
"low": "5.9400",
"high": "5.9600",... | 0 | 2016-08-15T17:20:14Z | 38,960,400 | <p>There it is !</p>
<p>Ok, I've tried to do the following:</p>
<pre><code>$curl -XDELETE http://localhost:9200/index_test/
{"acknowledged":true}
$curl -XPUT 'http://localhost:9200/index_test/' -d conf/ESConf/ElasticSearchMapping.conf
{"acknowledged":true}
$curl -XGET 'http://localhost:9200/index_test/'
{"index_tes... | 0 | 2016-08-15T18:01:24Z | [
"python",
"elasticsearch"
] |
How can I continually send data without shutdown socket connection in python | 38,959,847 | <p>I wrote a python client to communicate with server side. Each time when I finished sanding out data, I have to call <code>sock.shutdown(socket.SHUT_WR)</code>, otherwise the server would not do any response. But after calling <code>sock.shutdown(socket.SHUT_WR)</code>, I have to reconnect the connection as <code>soc... | 1 | 2016-08-15T17:24:51Z | 38,960,222 | <p>You didn't show any server side code but I suspect it simply reads bytes until it gets none anymore. </p>
<p>You can't do this as you found out, because then the only way to tell the server the message is complete is by killing the connection.</p>
<p>Instead you'll have to add some form of framing in your protocol... | 2 | 2016-08-15T17:49:33Z | [
"python",
"sockets"
] |
Add new data to a text file without overwriting it in python | 38,959,849 | <p>Right, I'm running a while loop that does some calculations, and, at the end, exports the data to a .txt file. The problem is, rather than appending the data to the end of the file, it seems to overwrite it and create a brand new file instead. How would I make it append to the old file?</p>
<p>Here's my code:</p>
... | 0 | 2016-08-15T17:24:53Z | 38,959,878 | <p>You should use <code>open("Monarchs Output.txt", "a")</code> instead of <code>open("Monarchs Output.txt", "w")</code><br>
link: <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files</a></p>
| 1 | 2016-08-15T17:26:37Z | [
"python",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.