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 |
|---|---|---|---|---|---|---|---|---|---|
Python script to catch failed commands or warnings messages | 37,887,337 | <p>I have a little script that telnets into a network switch and executes commands. It works fine but I need it stop and show an error message if any of the commands fail or network give a waning or something. </p>
<p>Here is the code:</p>
<pre><code>import sys
import telnetlib
HOST = "10.10.10.1"
user = "Test"
p... | 0 | 2016-06-17T17:41:16Z | 37,887,699 | <p>You can use <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow">Try/Except</a> statements.</p>
<p>They're related to the <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">Errors and Exceptions</a> part of the Python docs.</p>
<p><strong>Example:</strong... | 0 | 2016-06-17T18:03:19Z | [
"python",
"networking",
"cisco"
] |
Python script to catch failed commands or warnings messages | 37,887,337 | <p>I have a little script that telnets into a network switch and executes commands. It works fine but I need it stop and show an error message if any of the commands fail or network give a waning or something. </p>
<p>Here is the code:</p>
<pre><code>import sys
import telnetlib
HOST = "10.10.10.1"
user = "Test"
p... | 0 | 2016-06-17T17:41:16Z | 37,887,915 | <p>you can extract the message based on key word appeared in failed command, then raise the exception.<br>
for example:</p>
<pre><code>try:
if '%Warning' == message[:8]:
raise Exception('Test')
except Exception:
print message
</code></pre>
| 0 | 2016-06-17T18:16:47Z | [
"python",
"networking",
"cisco"
] |
Python Flask how not to include one specific element in a query sqlalchemy | 37,887,439 | <p>I want to find all books with the same category as a given book. Right now, my query includes the specific book as well, but I only want <em>other</em> books. How do I exclude the specific book from the query?</p>
<pre><code>@app.route('/book/<id>')
def book(id):
return render_template(
'book.ht... | 0 | 2016-06-17T17:47:50Z | 37,887,573 | <p>Add a filter to your query to exclude that id.</p>
<pre><code>@app.route('/book/<id>')
def book(id):
book = Book.query.get_or_404(id)
related = Book.query.filter(Book.id != id, Book.category == book.category)
return render_template('book.html', book=book, related=related)
</code></pre>
<p><code>f... | 1 | 2016-06-17T17:56:11Z | [
"python",
"flask",
"sqlalchemy"
] |
Python sqlite3 delete not doing anything | 37,887,513 | <p>I am a noob about sqlite (but somewhat experienced as Pythonista), but I am deeply confused why this (Python 2.7, DBPATH is the path to the database)...</p>
<pre><code>import sqlite3
connection = sqlite3.connect(DBPATH)
cursor = connection.cursor()
query = "SELECT * from jobs"
cursor.execute(query)
print(cursor.fe... | 0 | 2016-06-17T17:52:14Z | 37,887,658 | <p>You have to <code>commit()</code> after every <strong>CUD</strong> operation you do in your database.</p>
<blockquote>
<p>If you <strong>C</strong>reate, <strong>U</strong>pdate or <strong>D</strong>elete, then <code>commit()</code>.</p>
</blockquote>
| 2 | 2016-06-17T18:00:48Z | [
"python",
"python-2.7",
"sqlite3",
"sql-delete"
] |
Python sqlite3 delete not doing anything | 37,887,513 | <p>I am a noob about sqlite (but somewhat experienced as Pythonista), but I am deeply confused why this (Python 2.7, DBPATH is the path to the database)...</p>
<pre><code>import sqlite3
connection = sqlite3.connect(DBPATH)
cursor = connection.cursor()
query = "SELECT * from jobs"
cursor.execute(query)
print(cursor.fe... | 0 | 2016-06-17T17:52:14Z | 37,887,781 | <p>From the manual: </p>
<p>commit()</p>
<p>This method commits the current transaction. If you donât call this
method, anything you did since the last call to commit() is not visible from
other database connections. If you wonder why you donât see the data youâve
written to the database, please check you... | 3 | 2016-06-17T18:07:55Z | [
"python",
"python-2.7",
"sqlite3",
"sql-delete"
] |
How do you add pandas series filling each series' missing values separately | 37,887,560 | <p>If I have two series:</p>
<pre><code>import pandas as pd
import numpy as np
s1 = pd.Series([1, np.nan, 2, np.nan])
s2 = pd.Series([1, 2, np.nan, np.nan])
</code></pre>
<p>I want to fill <code>s1</code>'s missing values with <code>0</code> and <code>s2</code>'s missing values with <code>1</code>. But I want to pr... | 0 | 2016-06-17T17:55:33Z | 37,887,722 | <p>I would just override your result if both are missing:</p>
<pre><code>In [22]: s1.fillna(0).add(s2.fillna(1)).where(~s1.isnull() | ~s2.isnull(), np.nan)
Out[22]:
0 2
1 2
2 3
3 NaN
dtype: float64
</code></pre>
| 2 | 2016-06-17T18:04:20Z | [
"python",
"pandas"
] |
How do you add pandas series filling each series' missing values separately | 37,887,560 | <p>If I have two series:</p>
<pre><code>import pandas as pd
import numpy as np
s1 = pd.Series([1, np.nan, 2, np.nan])
s2 = pd.Series([1, 2, np.nan, np.nan])
</code></pre>
<p>I want to fill <code>s1</code>'s missing values with <code>0</code> and <code>s2</code>'s missing values with <code>1</code>. But I want to pr... | 0 | 2016-06-17T17:55:33Z | 37,887,858 | <p>I guess you could:</p>
<pre><code>df = pd.concat([s1, s2], axis=1)
df[~df.isnull().all(axis=1)].fillna({c: c for c in df.columns}).append(df[df.isnull().all(axis=1)]).sum(axis=1)
</code></pre>
<p>to get:</p>
<pre><code>0 2.0
1 2.0
2 3.0
3 NaN
</code></pre>
| 1 | 2016-06-17T18:12:55Z | [
"python",
"pandas"
] |
I tried to build a simple messenger but the message pops up only when the other user presses Return. How to modify that? | 37,887,582 | <p>I built a simple messenger using socket and Tkinter modules. But there seems to be one problem. The message from the other user displays only when the first one presses the Return key to send his message. I tried enough to fix this but I can't.</p>
<p>Here are my codes (Sorry for too much code, but had to include a... | 0 | 2016-06-17T17:56:50Z | 37,887,655 | <p>You put the recv function in sendText</p>
<p>The UI and the network should be in 2 differents thread. I recommend you experience a bit more network programming to understand the need for a dedicated network thread.</p>
<p>Try to read about event queue also.</p>
| 0 | 2016-06-17T18:00:30Z | [
"python",
"networking",
"tkinter"
] |
Error when __setattr__ for List | 37,887,650 | <p>I am implementing all of the predefined function for a class, and I am stuck when i implement my<code>__setattr__()</code> for updating a list </p>
<pre><code>class testop:
def __init__(self):
self.li=[x*2 for x in list(range(5))]
def __getitem__(self,index):
return self.li[index]
def __... | 1 | 2016-06-17T18:00:17Z | 37,887,827 | <p>The issue is that when <code>__init__</code> is called, <code>li</code> doesn't exist yet.</p>
<p>Basically, what's happening is that as part of <code>__init__</code> you call <code>__setattr__</code> to set <code>li</code>. But, <code>li</code> doesn't exist yet, so you get a keyerror.</p>
<p>What you need to do ... | 3 | 2016-06-17T18:11:30Z | [
"python"
] |
Error when __setattr__ for List | 37,887,650 | <p>I am implementing all of the predefined function for a class, and I am stuck when i implement my<code>__setattr__()</code> for updating a list </p>
<pre><code>class testop:
def __init__(self):
self.li=[x*2 for x in list(range(5))]
def __getitem__(self,index):
return self.li[index]
def __... | 1 | 2016-06-17T18:00:17Z | 37,887,838 | <p>The problem there is, that the <code>__init__</code> function does <code>self.li = something</code> which calls <code>__setattr__</code>. and since there is no <code>li</code> defined at the time, it fails, so in the <code>__init__</code> function you should also assign using <code>__dict__</code>, like this:</p>
<... | 1 | 2016-06-17T18:11:58Z | [
"python"
] |
Django: Difference between BASE_DIR and PROJECT_ROOT? | 37,887,690 | <p>From settings.py:</p>
<pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
</code></pre>
<p>What's the difference between these two?</p>
| 1 | 2016-06-17T18:02:49Z | 37,887,792 | <p>They're almost the same thing. <code>BASE_DIR</code> is where your <code>manage.py</code> lies, and <code>PROJECT_ROOT</code> is <code>BASE_DIR</code> + <em>your_project_name</em> (where <code>settings.py</code> is).</p>
| 2 | 2016-06-17T18:08:56Z | [
"python",
"django"
] |
Error using python to import data in hive | 37,887,736 | <p>I am learning using python to import data into Hive on hadoop, here is the python code:</p>
<pre><code>import sys
import datetime
for line in sys.stdin:
line = line.strip()
userid, movieid, rating, unixtime = line.split('\t')
weekday = datetime.datetime.fromtimestamp(float(unixtime)).isoweekday()
p... | 0 | 2016-06-17T18:05:37Z | 37,888,296 | <p>I just noticed this in the traceback:</p>
<p><strong>while processing row</strong><code>{"userid":222,"movieid":298,"rating":4,"unixtime":"877563253"}</code></p>
<p><strong>"unixtime"</strong> is a string and according to your table it should be <code>weekday INT</code>.</p>
| 0 | 2016-06-17T18:41:32Z | [
"python",
"hadoop"
] |
Python MongoDB query requests segment data into chunks | 37,887,777 | <p>I am writing a python script that does these steps below.</p>
<p>Query a MongoDB database
Parse and aggregate results
Upload data to a ServiceNow table via a REST API</p>
<p>The script works, however, the data set is too large, and the REST transaction times out after 60 seconds (the connection is closed by the Se... | 0 | 2016-06-17T18:07:37Z | 37,935,205 | <p><code>j = dumps({"records":computers})</code> will return a list, so you can easily point to a single data entry by calling <code>j[x]</code>, or iterating through a for loop. Each of these entries should be acceptable to ServiceNow.</p>
<pre><code># Set proper headers (these are always the same, so this
# can be a... | 1 | 2016-06-21T03:45:50Z | [
"python",
"mongodb",
"rest",
"servicenow",
"chunked"
] |
pandas DataFrame add fill_value NotImplementedError | 37,887,796 | <p>I have:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((1, 2, np.nan), (5, 5)))
s = pd.Series(range(5))
</code></pre>
<p>I want to add <code>s</code> to <code>df</code> and broadcast across rows. Usually I'd:</p>
<pre><code>df.add(s)
</code></pr... | 2 | 2016-06-17T18:09:12Z | 37,887,912 | <p>The stack trace indicates that this parameter was never implemented:</p>
<pre><code>.../pandas/core/frame.py in _combine_match_columns(self, other, func, level, fill_value)
3470 if fill_value is not None:
3471 raise NotImplementedError("fill_value %r not supported" %
-> 3472 ... | 1 | 2016-06-17T18:16:35Z | [
"python",
"pandas"
] |
pandas DataFrame add fill_value NotImplementedError | 37,887,796 | <p>I have:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((1, 2, np.nan), (5, 5)))
s = pd.Series(range(5))
</code></pre>
<p>I want to add <code>s</code> to <code>df</code> and broadcast across rows. Usually I'd:</p>
<pre><code>df.add(s)
</code></pr... | 2 | 2016-06-17T18:09:12Z | 37,887,918 | <p>I get the same error with <code>0</code> and other numbers. You could alternatively use <code>df.fillna(0)</code>:</p>
<pre><code>df.fillna(0).add(s)
print df
>>>
0 1 2 3 4
0 1.0 1.0 2.0 3.0 4.0
1 2.0 3.0 2.0 4.0 4.0
2 1.0 1.0 3.0 4.0 4.0
3 1.0 1.0 2.0 4.0 6.0
4 1.0 3... | 1 | 2016-06-17T18:16:51Z | [
"python",
"pandas"
] |
pandas DataFrame add fill_value NotImplementedError | 37,887,796 | <p>I have:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice((1, 2, np.nan), (5, 5)))
s = pd.Series(range(5))
</code></pre>
<p>I want to add <code>s</code> to <code>df</code> and broadcast across rows. Usually I'd:</p>
<pre><code>df.add(s)
</code></pr... | 2 | 2016-06-17T18:09:12Z | 37,887,931 | <p>Just use <code>.fillna(0)</code> on the <code>df</code>:</p>
<pre><code>df.fillna(0).add(s)
</code></pre>
| 1 | 2016-06-17T18:17:40Z | [
"python",
"pandas"
] |
iteritems only giving one key | 37,887,897 | <p>So I have this function:</p>
<pre><code>cached_list = []
def build_dependency_list(list, tree, cache=True):
global cached_list
if not tree:
return
if cache:
cached_list = list
pp = pprint.PrettyPrinter(indent=4)
pprint.pprint(tree)
for key, value in tree.iteritems():
... | 0 | 2016-06-17T18:15:52Z | 37,887,959 | <p>You <em>return</em> from the function during the first iteration:</p>
<pre><code>for key, value in tree.iteritems():
pprint.pprint(key)
if key not in list:
list.append(key)
return build_dependency_list(list, value, cache)
# ^^ part of the loop
</code></pre>
<p>So only the first key-value pa... | 2 | 2016-06-17T18:19:09Z | [
"python",
"loops"
] |
How to identify non-printable KeyPress events in Tkinter | 37,887,962 | <p>I'm making an app in Tkinter using multiple Text widgets, and I'm working on undo/redo functionality, which is triggered by a KeyPress event. (I'm not using the text widget's built-in undo stack because I have non-tkinter objects which can also be undone/redone and I want to keep everything in one stack)</p>
<p>Bef... | 5 | 2016-06-17T18:19:17Z | 37,895,305 | <p><strong>Question 1 and 2 :</strong></p>
<p>I believe your method works, but it seems simpler to just use the <code>str.isprintable</code> method, it returns a boolean indicating whether or not the argument string isprintable:</p>
<pre><code>>>> "aéûβÃ\\".isprintable() #Works with various accents, spec... | 3 | 2016-06-18T09:15:23Z | [
"python",
"tkinter",
"tk"
] |
Raspberry PI MailCheck Error | 37,887,971 | <p>I need some help because I can't execute my <strong>Python</strong> script.
Please tell me where my mistakes are. Additional information: I wrote this programme on a Raspberry Pi.</p>
<pre><code>import imapclient
import time
import RPi.GPIO as GPIO
HOSTNAME = 'imap.gmail.com'
USERNAME = ',misterx@gmail.com'
PASSWO... | 0 | 2016-06-17T18:19:45Z | 37,888,023 | <p>You are using <code>imapclient</code> wrong.</p>
<p>Your import statement should be </p>
<p><code>from imapclient import IMAPClient</code>, and</p>
<p><code>mail = imapclient(HOSTNAME, use_uid=True, ssl=True)</code> </p>
<p>should be changed to </p>
<p><code>mail = IMAPClient(HOSTNAME, use_uid=True, ssl=Tru... | 0 | 2016-06-17T18:23:48Z | [
"python",
"email",
"raspberry-pi"
] |
Pipeline programming in parallel | 37,887,993 | <p>I've got a linux VM which is updated with new data files every 4 hours.
The files are organized in directories by numbered 01 to 10.</p>
<p>I've got an executable (convert.exe) that converts the files uploaded to a different file type.</p>
<p>I'd like to develop a pipeline to process the files (convert.exe) then r... | 2 | 2016-06-17T18:21:25Z | 37,888,279 | <p>You would likely need to use the <code>os</code>, <code>threading</code> or <code>multiprocessing</code>, and <code>subprocess</code> modules.</p>
<p>The first thing you need to do is get a list of files to process. You can use the <code>os</code> library for that. <code>os.listdir</code> will give you the conten... | 0 | 2016-06-17T18:40:37Z | [
"python",
"linux",
"snakemake"
] |
Pipeline programming in parallel | 37,887,993 | <p>I've got a linux VM which is updated with new data files every 4 hours.
The files are organized in directories by numbered 01 to 10.</p>
<p>I've got an executable (convert.exe) that converts the files uploaded to a different file type.</p>
<p>I'd like to develop a pipeline to process the files (convert.exe) then r... | 2 | 2016-06-17T18:21:25Z | 37,902,668 | <pre><code>doit() {
d="$1"
for f in $(find $d -type f -mtime -1); do
#determine appropriate folder for file to move to
newdirname=$(basename $d)
newfilename=$(basename $f)
mono convert.exe $f -o /mnt/convertedfiles/$newdirname/$newfilename
done
}
export -f doit
find /mnt/data01/dpad -mindepth 1 -... | 0 | 2016-06-18T23:55:07Z | [
"python",
"linux",
"snakemake"
] |
How can i pass the ip address to a nmap scanner? | 37,888,005 | <p>I have a code which basically returns 3 things <code>ip, instance_tag_name, availability_zone</code> as follows :</p>
<pre><code>def call_me ():
ACCESS_KEY= "XXXXXXXXXXXX"
SECRET_KEY= "XXXXXXXXXXXXXXXXXXX"
regions = ['us-west-2','eu-central-1','ap-southeast-1']
combined_shit = []
for region in regions:
... | -1 | 2016-06-17T18:22:01Z | 37,888,086 | <p>you can unpack the data.</p>
<pre><code>data = [[('52.1.113.171', ' Exclusive LB', ''), ('52.26.2.83', 'pdx-cloud-1-LB', 'us-west-2'), ('51.25.14.146', 'SDlusive LB', '')]]
for line in data:
... ips = [ ip for ip,_,_ in line]
... print ips
</code></pre>
<p>output</p>
<pre><code>['52.1.113.171', '52.26.2.... | 1 | 2016-06-17T18:28:12Z | [
"python"
] |
How can i pass the ip address to a nmap scanner? | 37,888,005 | <p>I have a code which basically returns 3 things <code>ip, instance_tag_name, availability_zone</code> as follows :</p>
<pre><code>def call_me ():
ACCESS_KEY= "XXXXXXXXXXXX"
SECRET_KEY= "XXXXXXXXXXXXXXXXXXX"
regions = ['us-west-2','eu-central-1','ap-southeast-1']
combined_shit = []
for region in regions:
... | -1 | 2016-06-17T18:22:01Z | 37,888,192 | <p>I think your NMAP <code>run</code> requires a comma separated list of IPs. Here's how to do it.</p>
<pre><code>r = s.run(net_range)
</code></pre>
<p><code>net_range</code> is a list of <code>tuple</code>s which have IPs at index 0. We get the list of IPs and join it to create a comma separated string of IPs. </... | 2 | 2016-06-17T18:34:49Z | [
"python"
] |
How can i pass the ip address to a nmap scanner? | 37,888,005 | <p>I have a code which basically returns 3 things <code>ip, instance_tag_name, availability_zone</code> as follows :</p>
<pre><code>def call_me ():
ACCESS_KEY= "XXXXXXXXXXXX"
SECRET_KEY= "XXXXXXXXXXXXXXXXXXX"
regions = ['us-west-2','eu-central-1','ap-southeast-1']
combined_shit = []
for region in regions:
... | -1 | 2016-06-17T18:22:01Z | 37,889,351 | <blockquote>
<p>targets (string or list) â hosts to be scanned. Could be a string of hosts separated with a coma or a python list of hosts/ip.</p>
</blockquote>
<p><a href="http://libnmap.readthedocs.io/en/latest/process.html#libnmap.process.NmapProcess" rel="nofollow">NmapProcess</a></p>
<p>In <code>call_me</cod... | 0 | 2016-06-17T19:49:22Z | [
"python"
] |
Compiling Python code into an exe file calling just the required DLLs | 37,888,102 | <p>There seems to be little information out there on this subject - I have tried <code>py2exe</code> to no avail (errors out w/ Python 3.5), as well as <code>pyinstaller.</code> The latter seems to include EVERY extension module installed on the system unless they are specifically excluded during build time, which end... | 1 | 2016-06-17T18:29:21Z | 37,889,243 | <p>If you can take the dependency, you can use <a href="http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/index.html" rel="nofollow"><code>boost::python</code></a> to help.</p>
<p>There's a full working exemplar app below, which only links <code>boost_python</code> and <code>python2.7</code> shared libraries. ... | 0 | 2016-06-17T19:42:35Z | [
"python",
"c++",
"numpy",
"exe",
"cython"
] |
pandas series bfill first half, ffill second half | 37,888,116 | <p>Suppose I had:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.choice((0, 1, 2, 3, 4, np.nan),
(50,), p=(.1, .1, .1, .1, .1, .5)))
</code></pre>
<p>I want to back fill in missing values for the first half of the series and forwa... | 1 | 2016-06-17T18:30:03Z | 37,888,320 | <p>I just operate on the two halves independently here:</p>
<pre><code>In [71]: s.ix[:len(s)/2].bfill().append(s.ix[1+len(s)/2:].ffill())
Out[71]:
0 4
1 4
2 4
3 4
4 4
5 0
6 1
7 1
8 1
9 1
10 1
11 1
12 1
13 1
14 1
15 1
16 1
17 1
18 4
1... | 1 | 2016-06-17T18:43:13Z | [
"python",
"pandas"
] |
Django search posts query filter month | 37,888,204 | <p>I am learning django and I am currently working on a blog project. I have a basic search function which filters the posts accordingly.
It works fine by searching for content in my title and content filters of the posts. I am trying to add a new filter so that I can type in the month for example "March" and then it ... | 1 | 2016-06-17T18:35:35Z | 37,888,237 | <p>I found a solution. I realized that if I search for "07" instead of July it filters out the posts accordingly, so currently that is solving my problem since the blog will only be used by my at the moment. It can obviously be converted to the month word with some python.</p>
<p>This is because you enter the DateFiel... | 0 | 2016-06-17T18:37:56Z | [
"python",
"django"
] |
How to combine two rows in Python list | 37,888,218 | <p>Suppose I have a 2D list,</p>
<pre><code>a= [['a','b','c',1],
['a','b','d',2],
['a','e','d',3],
['a','e','c',4]]
</code></pre>
<p>I want to obtain a list such that if the first two elements in rows are identical, sum the fourth element, drop the third element and combine these rows together, like the f... | -1 | 2016-06-17T18:36:34Z | 37,888,287 | <p>If your list is already sorted, then you can use <code>itertools.groupby</code>. Once you group by the first two elements, you can use a generator expression to sum the 4th element and create your new lists.</p>
<pre><code>>>> from itertools import groupby
>>> a= [['a','b','c',1],
['a','b'... | 2 | 2016-06-17T18:41:00Z | [
"python",
"list"
] |
How to combine two rows in Python list | 37,888,218 | <p>Suppose I have a 2D list,</p>
<pre><code>a= [['a','b','c',1],
['a','b','d',2],
['a','e','d',3],
['a','e','c',4]]
</code></pre>
<p>I want to obtain a list such that if the first two elements in rows are identical, sum the fourth element, drop the third element and combine these rows together, like the f... | -1 | 2016-06-17T18:36:34Z | 37,888,415 | <p>Using <code>pandas</code>'s <code>groupby</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(a)
df.groupby([0, 1]).sum().reset_index().values.tolist()
</code></pre>
<p>Output:</p>
<pre><code>df.groupby([0, 1]).sum().reset_index().values.tolist()
Out[19]: [['a', 'b', 3L], ['a', 'e', 7L]]
</code></pre>
| 1 | 2016-06-17T18:48:05Z | [
"python",
"list"
] |
How to combine two rows in Python list | 37,888,218 | <p>Suppose I have a 2D list,</p>
<pre><code>a= [['a','b','c',1],
['a','b','d',2],
['a','e','d',3],
['a','e','c',4]]
</code></pre>
<p>I want to obtain a list such that if the first two elements in rows are identical, sum the fourth element, drop the third element and combine these rows together, like the f... | -1 | 2016-06-17T18:36:34Z | 37,888,500 | <p>You can use pandas groupby methods to achieve that goal.</p>
<pre><code>import pandas as pd
a= [['a','b','c',1],
['a','b','d',2],
['a','e','d',3],
['a','e','c',4]]
df = pd.DataFrame(a)
df_sum = df.groupby([0,1])[3].sum().reset_index()
array_return = df_sum.values
list_return = array_return.tolist()
p... | 0 | 2016-06-17T18:53:03Z | [
"python",
"list"
] |
How to combine two rows in Python list | 37,888,218 | <p>Suppose I have a 2D list,</p>
<pre><code>a= [['a','b','c',1],
['a','b','d',2],
['a','e','d',3],
['a','e','c',4]]
</code></pre>
<p>I want to obtain a list such that if the first two elements in rows are identical, sum the fourth element, drop the third element and combine these rows together, like the f... | -1 | 2016-06-17T18:36:34Z | 37,888,768 | <p>If you're interested. Here is an implementation using raw python. I've only tested it on the dataset you provided.</p>
<pre><code>a= [['a','b','c',1],
['a','b','d',2],
['a','e','d',3],
['a','e','c',4]]
b_dict = {}
for row in a:
key = (row[0], row[1])
b_dict[key] = b_dict[key] + row[3] if key in b_dict else... | 0 | 2016-06-17T19:09:36Z | [
"python",
"list"
] |
Artificially creating memory usage in Python | 37,888,265 | <p>I'm trying to create a pure memory intensive script in Python for testing purposes but every script that I try also increases my cpu. I've read <a href="http://stackoverflow.com/questions/30509322/how-to-implement-a-memory-intensive-python-script-for-test">this post</a> and I also tried, among others:</p>
<pre><cod... | 1 | 2016-06-17T18:39:40Z | 37,888,795 | <p>You have a couple of misconceptions that I'll try to address.</p>
<ul>
<li>You have to use CPU to use memory. There's no other way.</li>
<li>Your copy of a list is only assigning a pointer. You're not moving memory.</li>
</ul>
<p>If you want to increase memory utilization, you need to keep adding data to your li... | 1 | 2016-06-17T19:11:18Z | [
"python",
"performance",
"testing",
"memory"
] |
accessing CSV file in d3.js with no header row | 37,888,290 | <p>I have a CSV file with data as such:</p>
<pre><code>,tests,Mary,Joe,Frank
0,Test1,92,15,72
1,Test2,74,25,70
2,Test3,30,65,50
3,Test4,82,80,48
</code></pre>
<p>this data has been taken from a space delimited text file, converted into a dataframe in <code>pandas</code>, and then converted into a csv file for use i... | -1 | 2016-06-17T18:41:12Z | 37,890,261 | <p>First off, your CSV will not work as you haven't got a name for the first element in the header.</p>
<p>If you did, and you read the first element of the dataset you will get something like :</p>
<pre><code>randomname(this i made up) : 0
tests : Test1
mary : 92
joe : 15
frank : 72
</code></pre>
<p>So to get it in... | 0 | 2016-06-17T20:56:32Z | [
"javascript",
"python",
"csv",
"d3.js"
] |
displaying x-axis labels properly in matplotlib plots | 37,888,300 | <p>I'm trying to plot electricity usage against time. I'm using this script:</p>
<pre><code>from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
timelist = []
valuelist = []
# Logic that populates timelist and valuelist
timeaxis = np.array(timelist)
valueaxis = np.array(valuelist)
plt.p... | 1 | 2016-06-17T18:41:38Z | 37,888,683 | <p>You could use <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.autofmt_xdate" rel="nofollow">gcf().autofmt_xdate</a> to format the x-axis nicely. And for the date string format, you could use <code>matplotlib.dates.DateFormatter</code>. It will be something like below:</p>
<p><a href="htt... | 1 | 2016-06-17T19:03:29Z | [
"python",
"matplotlib"
] |
Scrapy crawler does not follow links even when I collect and parse them | 37,888,374 | <p>I've been stuck on this problem for hours. I couldn't follow the links on this site using the Rule syntax so I manually found all the links I needed to make a request. Even though I tested that the extracted links are valid urls, my crawler does not crawl additional pages. I've been stuck on this for hours. I also d... | 0 | 2016-06-17T18:45:32Z | 37,889,053 | <p>I finally got it working!</p>
<p>According to the <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.allowed_domains" rel="nofollow">scrapy documentation</a> if OffsiteMiddleware is enabled then domains not in the <code>allowed_domains</code> list will not be read for a request. I kn... | 1 | 2016-06-17T19:29:19Z | [
"python",
"scrapy",
"web-crawler"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,437 | <p>In python, the phrase <code>x=4</code> will assign the value of <code>4</code> to <code>x</code>. However, the phrase <code>x+=4</code> will increment <code>4</code> to the current value of <code>x</code>. For example:</p>
<pre><code>x = 3
print x #will print 3
x += 2
print x #will print 5
</code></pre>
| 4 | 2016-06-17T18:49:09Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,465 | <p><code>foo = bar</code> sets <code>foo</code> to the same value as <code>bar</code>- if <code>foo</code> is 5 and <code>bar</code> is 3, <code>foo</code> is now 3.</p>
<p><code>foo += bar</code> is shorthand for <code>foo = foo + bar</code>. So if <code>foo</code> is 5, and <code>bar</code> is 3, foo is now 8</p>
<... | 0 | 2016-06-17T18:51:17Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,475 | <p>Similar to many other languages, <code>+=</code> is a "shortcut".</p>
<pre><code>x = y
</code></pre>
<p>Assigns a reference to the object on the right-hand-side to the name on the left.</p>
<pre><code>x += y
</code></pre>
<p>Conceptually adds the object or the right-hand-size to the object referred to on the lef... | 4 | 2016-06-17T18:51:54Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,479 | <p>= is used to assign a value to a variable. e.g.: c=1+c (which assigns the value of c+1 to c, so it increments c by 1 )</p>
<p>+= is used to increment a variable by a specific value. e.g.: c+=1 (which </p>
| 0 | 2016-06-17T18:52:04Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,504 | <p><code>x = 4</code> initiates the variable <code>x</code> to equal 4</p>
<p><code>x += 4</code> is actually <code>x = x + 4</code>. If you try to do <code>x += 4</code> without initializing x you will get a name error</p>
<pre><code>y = 5 # 5
y += 2 # 7
x += 4
Traceback (most recent call last):
File "<stdin... | 0 | 2016-06-17T18:53:05Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,507 | <p><code>x = 2</code> assigns a value <code>2</code> to the variable <code>x</code>. <code>x += 2</code> is the same as <code>x = x + 2</code>. In other words <code>+=</code> adds a value to a already existing value. Example:</p>
<pre><code>>>> x += 2
Traceback (most recent call last):
File "<stdin>",... | 0 | 2016-06-17T18:53:10Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,509 | <p>In python</p>
<p><code>c = a + b</code> assigns value of a + b into c</p>
<p><code>c = 1 + 3 #returns 4</code></p>
<p><code>c += a</code> is equivalent to c = c + a</p>
<p><code>c = 1</code>
<code>a = 2</code></p>
<p><code>c += 1 #returns 3</code></p>
<p>Check out: <a href="http://www.tutorialspoint.com/python... | 0 | 2016-06-17T18:53:14Z | [
"python"
] |
Difference between "=" and "+=" on python? | 37,888,384 | <p>What is the Difference between "=" and "+=" on python? (Without speech marks)
I've been experimenting, and I haven't found the difference...
I'm not fluent in python, however - I am on "A Day at the Supermarket" on Codeacademy.
Thanks for all your answers!</p>
| 0 | 2016-06-17T18:45:45Z | 37,888,546 | <p><strong>Quick Notes:</strong></p>
<p><code>a=b</code> : assign the value <code>b</code> to the variable <code>a</code></p>
<p><code>a+=b</code> : sum <code>b</code> to the current value of <code>a</code></p>
<p><code>a+=b</code> is a short notation for <code>a = a + b</code></p>
<p>You can do <code>a-=b</code>, ... | 0 | 2016-06-17T18:55:20Z | [
"python"
] |
Calling property object from within class? | 37,888,419 | <p>I am trying to call a property from within its class and get the value. I understand that properties are <code>A.foo.__get__(a)</code>, but since the properties are within the instance of the class I am not sure what my <code>a</code> would be. Currently, my attempts return the object and location. This makes sense,... | 0 | 2016-06-17T18:48:19Z | 37,888,651 | <p>I think this is what you want. You shouldn't have to deal with the <code>__get__</code> nonsense. That's the whole point of creating a descriptor on a class; python handles it automagically.</p>
<pre><code>def make_burger_dict(self, key):
val = getattr(self, key)
return {1: val, 2: val}
</code></pre>
| 3 | 2016-06-17T19:02:02Z | [
"python",
"python-2.7",
"class",
"properties"
] |
Python sort a json based on a key inside an array of dictionary | 37,888,436 | <p>I have a structure like this:</p>
<pre><code>[{
"name": "apple",
"price": "5.0",
"record": [
{
"id": "008",
"time": 1465689600
}
]
},{
"name": "banana",
"price": "9.0",
"record": [
{
"id": "002",
"time": 1465682600
... | 0 | 2016-06-17T18:48:59Z | 37,888,505 | <p>Apparently, your structure is a string. You need to convert it to a python object using <a href="https://docs.python.org/3/library/json.html#json.loads" rel="nofollow"><code>json.loads</code></a></p>
<pre><code>import json
d = "[{'record': [{'id': '008', 'time': 1465689600}], 'price': '5.0', 'name': 'apple'}, {'re... | 0 | 2016-06-17T18:53:07Z | [
"python",
"json"
] |
Python sort a json based on a key inside an array of dictionary | 37,888,436 | <p>I have a structure like this:</p>
<pre><code>[{
"name": "apple",
"price": "5.0",
"record": [
{
"id": "008",
"time": 1465689600
}
]
},{
"name": "banana",
"price": "9.0",
"record": [
{
"id": "002",
"time": 1465682600
... | 0 | 2016-06-17T18:48:59Z | 37,888,518 | <p>Since this is a json, I would just decode it using <a href="https://docs.python.org/3.4/library/json.html#json.loads" rel="nofollow"><code>json.loads</code></a>:</p>
<pre><code>import json
lines = '''
[{
"name": "apple",
"price": "5.0",
"record": [
{
"id": "008",
"time":... | 0 | 2016-06-17T18:53:42Z | [
"python",
"json"
] |
Python 3.5, ctypes: TypeError: bytes or integer address expected instead of str instance | 37,888,565 | <p>I'm having an issue with ctypes. I think my type conversion is correct and the error isn't making sense to me.
Error on line " arg - ct.c_char_p(logfilepath) "
TypeError: bytes or integer address expected instead of str instance</p>
<p>I tried in both python 3.5 and 3.4.</p>
<p>function i'm calling:</p>
<pre><co... | 1 | 2016-06-17T18:56:55Z | 37,888,716 | <p><code>c_char_p</code> takes <code>bytes</code> object so you have to convert your <code>string</code> to <code>bytes</code> first:</p>
<pre><code>ct.c_char_p(logfilepath.encode('utf-8'))
</code></pre>
<p>Another solution is using the <code>c_wchar_p</code> type which takes a <code>string</code>.</p>
| 2 | 2016-06-17T19:06:14Z | [
"python",
"ctypes"
] |
PyInstaller + UI Files - FileNotFoundError: [Errno 2] No such file or directory: | 37,888,581 | <p>I'm trying to export my .py script to .exe using PyInstaller, which has dependencies on .ui files which were created using Qt Designer.</p>
<p><em>I can confirm that my .py script works just fine when running it through PyCharm - I'm able to see the GUI I've created with the .ui files.</em></p>
<p>However, when I ... | 1 | 2016-06-17T18:57:32Z | 37,920,111 | <p>After scratching my head all weekend and looking further on SO, I managed to compile the standalone .exe as expected using the UI files.</p>
<p>Firstly, I defined the following function using this answer</p>
<p><a href="http://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile">Bundli... | 0 | 2016-06-20T10:25:26Z | [
"python",
"pyqt4",
"pyinstaller",
"qt-designer"
] |
Using external data files in f2py | 37,888,586 | <p>I have some old fortran code that I am wrapping and importing to python using <code>f2py</code>. The fortran code relies on a data file that resides in the same directory. If I start python in that directory, everything works fine.</p>
<p>However, if I import this module from somewhere else, it looks for the files ... | 0 | 2016-06-17T18:57:51Z | 37,889,028 | <p>I don't know a lot about <code>f2py</code> but it looks like there is a command line version and a module version.</p>
<p>To use the commmand line option, I see two options:</p>
<ol>
<li>Modify the fortran to find the path</li>
<li>Wrap the command line with a wrapper</li>
</ol>
<p>For a wrapper, you could use a ... | 0 | 2016-06-17T19:27:02Z | [
"python",
"f2py"
] |
python comparing boolean and int using isinstance | 37,888,620 | <p>Can someone give me an explanation why <code>isinstance()</code> returns True in the following case? I expected False, when writing the code.</p>
<pre><code>print isinstance(True, (float, int))
True
</code></pre>
<p>My guess would be that its python's internal subclassing, as zero and one - wheter float or int - b... | 1 | 2016-06-17T18:59:41Z | 37,888,668 | <p>For historic reasons, <code>bool</code> is a subclass of <code>int</code>, so <code>True</code> is an instance of <code>int</code>.</p>
<p>The correct way to "solve" this depends on exactly what you consider the problem to be.</p>
<ul>
<li>If you want <code>True</code> to stop being an <code>int</code>, well, too ... | 4 | 2016-06-17T19:02:49Z | [
"python",
"int",
"boolean",
"comparison",
"isinstance"
] |
Jenkins finishing with Finished: SUCCESS even though Python exiting with sys.exit(-1) | 37,888,625 | <p>Python code:</p>
<pre><code>print "Initiating myPy..."
...
try:
opts, args = getopt.getopt(sys.argv[1:], "d:", ["dolphins="])
except getopt.GetoptError:
print '\tUsage: python myPy.py -d <foo>'
sys.exit(-1)
</code></pre>
<p>Server response:</p>
<blockquote>
<p>Initiating myPy...</p>
<pre><... | 1 | 2016-06-17T19:00:03Z | 37,889,011 | <ol>
<li>It seems like you are running the python script from a bash script, what flags jenkins use when it runs the bash script? <code>/bin/sh sh133331232.sh -xe</code>? the -e flag denotes exit on fail, is it there?</li>
<li>Try adding <code>exit $?</code> after the python script runs. </li>
</ol>
| 3 | 2016-06-17T19:26:02Z | [
"python",
"jenkins"
] |
Filter out all rows preceding a string match | 37,888,675 | <p>I'm attempting to get <code>DataFrame</code> to <em>discard all rows that precedes</em> the place where there is a string match in one of the columns.</p>
<p>In other words: The row with the string match, and all rows after it, should be kept. (Column headers should also be kept).</p>
<pre><code>import pandas as p... | 2 | 2016-06-17T19:03:10Z | 37,888,796 | <p>If you want to just select starting with the first match, you could just pick the first matching <code>index</code> and <code>slice</code> accordingly - the below does not depend on the index value in case the <code>index</code> is non-unique:</p>
<pre><code>df.iloc[df['strings'].tolist().index(test_string):]
</cod... | 3 | 2016-06-17T19:11:27Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Filter out all rows preceding a string match | 37,888,675 | <p>I'm attempting to get <code>DataFrame</code> to <em>discard all rows that precedes</em> the place where there is a string match in one of the columns.</p>
<p>In other words: The row with the string match, and all rows after it, should be kept. (Column headers should also be kept).</p>
<pre><code>import pandas as p... | 2 | 2016-06-17T19:03:10Z | 37,888,821 | <p>You could use <code>cumsum().astype(bool)</code> to create a boolean selection mask:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col' : ['AA', 'AB', 'BA', 'BB', 'XX', 'AA', 'AB', 'XX', 'BA', 'BB']},
index=[1,2]*5)
mask = df['col'].str.contains(r'XX').cumsum().astype(bool)
print(df.loc[... | 2 | 2016-06-17T19:12:38Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Filter out all rows preceding a string match | 37,888,675 | <p>I'm attempting to get <code>DataFrame</code> to <em>discard all rows that precedes</em> the place where there is a string match in one of the columns.</p>
<p>In other words: The row with the string match, and all rows after it, should be kept. (Column headers should also be kept).</p>
<pre><code>import pandas as p... | 2 | 2016-06-17T19:03:10Z | 37,888,910 | <p>EDIT: Disregard, I misread and thought you were trying to discard every row preceding ones with matches. Anyways, if that is what you want, this is your code</p>
<pre><code>import pandas as pd
df = pd.read_csv(file_path)
test_string = "myUniqueMatch"
mask = df["Column"].str.contains(test_string).shift(-1).fillna(... | 1 | 2016-06-17T19:18:20Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Python 3.51 Requests causes Proxy Error | 37,888,774 | <p>I'm trying to consume the Informatica Cloud REST API using Python (3.51) Requests (requests package version is 2.10.0):</p>
<pre><code>import requests
username='myuser'
password='mypassword'
genheaders = {
'Content-Type': 'application/json',
}
data = '{"@type":"login","username":"' + username + '","password"... | 0 | 2016-06-17T19:09:53Z | 38,129,524 | <p>Maybe try the following:</p>
<pre><code>import requests
proxies = {
'http': 'http://10.123.123.10:8080',
'https': '10.123.123.10:8080',
}
response = requests.post('https://app.informaticaondemand.com/ma/api/v2/user/login', headers=genheaders, data=data, proxies=proxies)
</code></pre>
<p>Link to requests prox... | 1 | 2016-06-30T17:14:50Z | [
"python",
"proxy",
"python-requests"
] |
Merging CSV Rows with Common Data and Updating Count | 37,888,850 | <p>I have a CSV with data like the following: </p>
<p><strong>document_id | body_mention | count</strong> </p>
<p>doc_01 | Bob | 5 </p>
<p>doc_03 | Sam | 1</p>
<p>doc_04 | Bob | 1</p>
<p>Where <code>body_mention</code> are names parsed out from text and <code>count</code> is how many times that nam... | 0 | 2016-06-17T19:14:40Z | 37,889,257 | <p>It's a little awkward but you can use two defaultdicts, one to keep track of all the docs for each person and the other to keep a sum of all the values of the docs</p>
<pre><code>import csv
import collections
name_sum = collections.defaultdict(int)
docs_for_name = collections.defaultdict(list)
with open("csv1.csv... | 0 | 2016-06-17T19:43:39Z | [
"python",
"csv",
"pandas",
"join"
] |
Merging CSV Rows with Common Data and Updating Count | 37,888,850 | <p>I have a CSV with data like the following: </p>
<p><strong>document_id | body_mention | count</strong> </p>
<p>doc_01 | Bob | 5 </p>
<p>doc_03 | Sam | 1</p>
<p>doc_04 | Bob | 1</p>
<p>Where <code>body_mention</code> are names parsed out from text and <code>count</code> is how many times that nam... | 0 | 2016-06-17T19:14:40Z | 37,889,402 | <p>You could read your <code>csv</code> from <code>pandas</code>, using <code>import pandas as pd; pd.read_csv()</code>. Then you data can be stored inside a <code>Dataframe</code>, like below:</p>
<pre><code>df
Out[86]:
document_id body_mention count
0 doc_01 Bob 5
1 doc_03 Sam ... | 0 | 2016-06-17T19:53:00Z | [
"python",
"csv",
"pandas",
"join"
] |
Merging CSV Rows with Common Data and Updating Count | 37,888,850 | <p>I have a CSV with data like the following: </p>
<p><strong>document_id | body_mention | count</strong> </p>
<p>doc_01 | Bob | 5 </p>
<p>doc_03 | Sam | 1</p>
<p>doc_04 | Bob | 1</p>
<p>Where <code>body_mention</code> are names parsed out from text and <code>count</code> is how many times that nam... | 0 | 2016-06-17T19:14:40Z | 37,892,092 | <p>Try this: </p>
<pre><code>df.groupby("body_mention")['document_id'].apply(lambda x: ','.join(x))
# body_mention
# Bob doc_01,doc_04
# Sam doc_03
# Name: document_id, dtype: object
df.groupby("body_mention")['count'].sum()
#body_mention
# Bob 6
# Sam 1
# Name: count, dtype: int64
</code></pre>
... | 0 | 2016-06-18T00:25:39Z | [
"python",
"csv",
"pandas",
"join"
] |
Equivalent of python's textwrap dedent in bash | 37,888,872 | <p>I have a variable containing a multi-line string in bash:</p>
<pre><code>mystring="foo
bar
stack
overflow"
</code></pre>
<p>Obviously this gives a ton of indentation when I <code>echo "$mystring"</code>. In python I would simply import textwrap and use dedent on the string, which brin... | 0 | 2016-06-17T19:16:02Z | 37,888,919 | <p>You can use sed to remove leading spaces from each line:</p>
<pre><code>$ sed 's/^[[:space:]]*//' <<< "$mystring"
foo
bar
stack
overflow
</code></pre>
<p>Alternative you can <a href="https://unix.stackexchange.com/questions/18886/why-is-while-ifs-read-used-so-often-instead-of-ifs-while-read">(ab)use the f... | 1 | 2016-06-17T19:19:31Z | [
"python",
"string",
"bash",
"format"
] |
Equivalent of python's textwrap dedent in bash | 37,888,872 | <p>I have a variable containing a multi-line string in bash:</p>
<pre><code>mystring="foo
bar
stack
overflow"
</code></pre>
<p>Obviously this gives a ton of indentation when I <code>echo "$mystring"</code>. In python I would simply import textwrap and use dedent on the string, which brin... | 0 | 2016-06-17T19:16:02Z | 37,897,495 | <p>Instead of indenting the string, suppress the initial newline that causes the need for indentation.</p>
<pre><code>mystring="\
foo
bar
stack
overflow"
</code></pre>
| -1 | 2016-06-18T13:26:23Z | [
"python",
"string",
"bash",
"format"
] |
Equivalent of python's textwrap dedent in bash | 37,888,872 | <p>I have a variable containing a multi-line string in bash:</p>
<pre><code>mystring="foo
bar
stack
overflow"
</code></pre>
<p>Obviously this gives a ton of indentation when I <code>echo "$mystring"</code>. In python I would simply import textwrap and use dedent on the string, which brin... | 0 | 2016-06-17T19:16:02Z | 38,535,244 | <p>The âhere documentâ feature allows a multi-line string to be defined as input to a command:</p>
<pre class="lang-bash prettyprint-override"><code>$ cat <<_EOT_
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Morbi quis rutrum nisi, nec dignissim libero.
_EOT_
</code></pre>
<pre c... | 0 | 2016-07-22T21:07:31Z | [
"python",
"string",
"bash",
"format"
] |
How to split a datafile into multiple parts along with comments in each splitted files? | 37,888,923 | <p>I have a datafile like this:</p>
<pre><code># coating file for detector A/R
# column 1 is the angle of incidence (degrees)
# column 2 is the wavelength (microns)
# column 3 is the transmission probability
# column 4 is the reflection probability
14.2000 0.531000 0.0618000 0.938200
14.2000 ... | 0 | 2016-06-17T19:19:44Z | 37,889,864 | <p>This ought to do it</p>
<pre><code># Store comments in this to use for all files
comments = []
# Create a new sub list for each of the 20 files
data = []
for _ in range(20):
data.append([])
# Track line number
index = 0
# open input file
with open('input.txt', 'r') as fi:
# fetch all lines at once so I c... | 1 | 2016-06-17T20:25:33Z | [
"python",
"file-io"
] |
How to split a datafile into multiple parts along with comments in each splitted files? | 37,888,923 | <p>I have a datafile like this:</p>
<pre><code># coating file for detector A/R
# column 1 is the angle of incidence (degrees)
# column 2 is the wavelength (microns)
# column 3 is the transmission probability
# column 4 is the reflection probability
14.2000 0.531000 0.0618000 0.938200
14.2000 ... | 0 | 2016-06-17T19:19:44Z | 37,890,252 | <p><strong>UPDATE:</strong> optimized code</p>
<pre><code>fn = r'D:\download\input.txt'
with open(fn, 'r') as f:
data = f.readlines()
comments_lines = 0
for line in data:
if line.strip().startswith('#'):
comments_lines += 1
else:
break
nfiles = 20
chunk_size = (len(data)-comments_lines)/... | 1 | 2016-06-17T20:55:41Z | [
"python",
"file-io"
] |
SQLite3 + Python sqlite3.OperationalError: table A has no column named message B | 37,889,004 | <p>I don't understand, what wrong with my code?
I create 2 tables 'users' and 'messages', but when I try to insert data in to messages table, raise this strange error - </p>
<pre><code>sqlite3.OperationalError: table messages has no column named message
</code></pre>
<p>Here is my code</p>
<pre><code>conn = sqlite3.... | 0 | 2016-06-17T19:25:19Z | 37,896,744 | <p>Your are using <code>create table if not exists</code>, which will keep any old version of the table.</p>
<p>To ensure that the table has the desired schema, use a plain <code>create table</code>.
Any old table can be deleted with <code>drop table if exists</code>.</p>
| 0 | 2016-06-18T12:06:40Z | [
"python",
"sqlite3"
] |
python program sign in not working | 37,889,006 | <pre><code>list_names = ("A"+"B"+"C")
username = input("enter your username: ")
if username == (list_names):
password = input("enter your password "+username+": ")
elif username !=(list_names):
print("that is not a valid username")
if password == ("password"):
print("allowing access...")
time.sleep(3)
e... | -5 | 2016-06-17T19:25:35Z | 37,889,049 | <p><code>password</code> is defined as a local variable. That means if can only be referenced in the first if block. You need to put the password check inside the user check like so:</p>
<pre><code>list_names = ("A"+"B"+"C")
username = input("enter your username: ")
if username == (list_names):
password = input("e... | 0 | 2016-06-17T19:29:04Z | [
"python"
] |
python program sign in not working | 37,889,006 | <pre><code>list_names = ("A"+"B"+"C")
username = input("enter your username: ")
if username == (list_names):
password = input("enter your password "+username+": ")
elif username !=(list_names):
print("that is not a valid username")
if password == ("password"):
print("allowing access...")
time.sleep(3)
e... | -5 | 2016-06-17T19:25:35Z | 37,889,220 | <p>You're defining <code>password</code> inside of an <code>if</code>-block, so if the <code>if</code>-block does not execute, <code>password</code> will remain undefined. Also, your syntax for the <code>list_names</code> is incorrect. Update </p>
<pre><code>list_names = ("A"+"B"+"C")
</code></pre>
<p>to</p>
<pre><c... | 0 | 2016-06-17T19:40:57Z | [
"python"
] |
Secure way to call the API from Javascript? | 37,889,074 | <p>I'm using flask to build my API. I've a tornado server in front of flask which takes care of requests. I'm using HTTP basic auth in Flask like this:</p>
<pre><code>auth = HTTPBasicAuth()
@auth.get_password
def get_password(username):
if username == 'uname':
return 'password'
return None
</code></pr... | 0 | 2016-06-17T19:30:21Z | 37,889,407 | <p>You cant avoid sending your password this way and it's fine. You just need to take reasonable precautions about how those credentials are handled. Make sure you are not saving the password in cookies / localStorage.</p>
<p>Make sure the <code>uname</code> and <code>password</code> variables are not hard-coded into ... | 1 | 2016-06-17T19:53:20Z | [
"javascript",
"python",
"ajax"
] |
TensorFlow: 'ValueError: No gradients provided for any variable' | 37,889,125 | <p>I'm implementing DeepMind's DQN algorithm in tensorflow and running into this error on my the line where I call <code>optimizer.minimize(self.loss)</code>: </p>
<p><code>ValueError: No gradients provided for any variable...</code></p>
<p>From reading other posts about this error I've gathered that it means that th... | 0 | 2016-06-17T19:33:44Z | 37,973,784 | <p>I figured out that the issue was that, in my <code>qloss()</code> function I was pulling values out of the tensors, doing operations on them and returning the values. While the values did depend on the tensors, they were't incapsulated in tensors themselves, so TensorFlow couldn't tell that they depended on the tens... | 0 | 2016-06-22T16:36:05Z | [
"python",
"tensorflow",
"deep-learning"
] |
How to wait for a POST request (requests.post) completion in Python? | 37,889,171 | <p>I'm using the requests library in Python to do a POST call.
My POST call takes about 5 minutes to be completed. It will create a file in a S3 bucket.
After that, I want to download this file. However, I need to create an extra logic to wait for my POST to finish before executing the next line on my code to download ... | 0 | 2016-06-17T19:37:39Z | 37,889,208 | <p>It should already wait until it's finished.</p>
<p>Python, unlike Node.js, will block requests by default. You'd have to explicitly run it in another thread if you wanted to run it async. If it takes your POST request 5 minutes to fetch, then the download line won't run until the 5 minutes are up and the POST reque... | 0 | 2016-06-17T19:40:19Z | [
"python",
"python-requests"
] |
How to wait for a POST request (requests.post) completion in Python? | 37,889,171 | <p>I'm using the requests library in Python to do a POST call.
My POST call takes about 5 minutes to be completed. It will create a file in a S3 bucket.
After that, I want to download this file. However, I need to create an extra logic to wait for my POST to finish before executing the next line on my code to download ... | 0 | 2016-06-17T19:37:39Z | 37,889,566 | <p>The question says the POST request takes 5 minutes to return, but maybe that's not quite right? Maybe the POST request returns promptly, but the server continues to grind 5 minutes creating the file for the S3 bucket? In that case, the need for a delay makes sense. The fact that a separate download is needed at a... | 0 | 2016-06-17T20:03:45Z | [
"python",
"python-requests"
] |
Pre-calculating the values of a dictionary with tuple as its value | 37,889,262 | <p>I have the following code example where I am creating a dictionary <code>result</code> for each <code>id</code> with a tuple of 2 numbers for its value.</p>
<pre><code># populate the ids list (contents of the current directory which is for a speicif id name)
ids_list = [filename for filename in glob('*' + .txt)
de... | -3 | 2016-06-17T19:44:11Z | 37,889,579 | <p>Part of the problem is you've organized your code badly. You're creating your dictionary too early.</p>
<p>Consider if you reorganized it something like this:</p>
<pre><code>def count_stuff(id, filename):
return (some_numerical_calc(filename), size_of_file(filename))
for id in ids_list:
nums = 0
size... | 2 | 2016-06-17T20:04:33Z | [
"python",
"python-3.x",
"dictionary",
"tuples"
] |
Pre-calculating the values of a dictionary with tuple as its value | 37,889,262 | <p>I have the following code example where I am creating a dictionary <code>result</code> for each <code>id</code> with a tuple of 2 numbers for its value.</p>
<pre><code># populate the ids list (contents of the current directory which is for a speicif id name)
ids_list = [filename for filename in glob('*' + .txt)
de... | -3 | 2016-06-17T19:44:11Z | 37,889,600 | <p>To create a tuple that contains sums, you can do something like this*:</p>
<pre><code>result[id] = (sum(some_numerical_calc(filename) for filename in files_list),
sum(size_of_file(filename) for filename in files_list))
</code></pre>
<p>But just as a heads up, using your current code, this would store... | 1 | 2016-06-17T20:05:46Z | [
"python",
"python-3.x",
"dictionary",
"tuples"
] |
Pre-calculating the values of a dictionary with tuple as its value | 37,889,262 | <p>I have the following code example where I am creating a dictionary <code>result</code> for each <code>id</code> with a tuple of 2 numbers for its value.</p>
<pre><code># populate the ids list (contents of the current directory which is for a speicif id name)
ids_list = [filename for filename in glob('*' + .txt)
de... | -3 | 2016-06-17T19:44:11Z | 37,889,642 | <p>You could try mixing map and sum:</p>
<pre><code>resultDict = {}
for id in ids_list:
resultDict[id] = (sum(map(some_numerical_calc(files_list[id]))), sum(map(size_of_file(files_list[id]))))
</code></pre>
<p>Edit:</p>
<p>A more detailed example given your particular situation. Some parts will be described in ... | 1 | 2016-06-17T20:09:28Z | [
"python",
"python-3.x",
"dictionary",
"tuples"
] |
Pre-calculating the values of a dictionary with tuple as its value | 37,889,262 | <p>I have the following code example where I am creating a dictionary <code>result</code> for each <code>id</code> with a tuple of 2 numbers for its value.</p>
<pre><code># populate the ids list (contents of the current directory which is for a speicif id name)
ids_list = [filename for filename in glob('*' + .txt)
de... | -3 | 2016-06-17T19:44:11Z | 37,889,646 | <p>There are a few things strange about your code, for one, you are creating a new dictionary every time you call count_stuff, but never doing anything with it or return it. From the question it seems like you want everything added to one dictionary.</p>
<p>Something like this might work better:</p>
<pre><code>def so... | 1 | 2016-06-17T20:09:38Z | [
"python",
"python-3.x",
"dictionary",
"tuples"
] |
SQLAlchemy Efficient Subquery for Latest Value | 37,889,286 | <p>The current value of an Entity's <code>status</code> attribute can queried as the latest entry in a <em>EntityHistory</em> table for that entity, i.e.</p>
<pre><code>Entities (id) <- EntityHistory (timestamp, entity_id, value)
</code></pre>
<p>How do I write an efficient SQLALchemy expression that eagerly loads... | 0 | 2016-06-17T19:45:33Z | 37,901,823 | <p>I think you could use a <a href="http://docs.sqlalchemy.org/en/latest/orm/mapped_sql_expr.html#using-column-property" rel="nofollow"><code>column_property</code></a> to load the latest value as an attribute of an <code>Entities</code> instance along other column-mapped attributes:</p>
<pre><code>from sqlalchemy imp... | 0 | 2016-06-18T21:31:47Z | [
"python",
"sqlalchemy",
"subquery",
"select-n-plus-1"
] |
How to handle the KeyError in Python? | 37,889,335 | <p>I am trying to do some data analysis in Python, whereby I am trying to use some Twitter data to find the number of tweets of different countries. This is the code I am using :</p>
<pre><code>import json
import pandas as pd
import matplotlib.pyplot as plt
tweets_data=[]
with open('/home/surya/tweet.txt','r') as f:
... | 1 | 2016-06-17T19:48:40Z | 37,889,857 | <pre><code>import json
import pandas as pd
import matplotlib.pyplot as plt
with open("testfile.txt", "r") as f:
tweet_data = [json.loads(line) for line in f]
tweet_table= pd.DataFrame()
tweet_table['country'] = [tweet['place']['country'] for tweet in tweet_data if tweet['place']]
tweets_by_country = tweet_tabl... | 1 | 2016-06-17T20:24:56Z | [
"python",
"twitter"
] |
Appending to a Pandas Dataframe From a pd.read_sql Output | 37,889,360 | <p>I'm coming from R but need to do this in Python for various reasons.
This very well could be a basic PEBKAC issue with my Python more than anything with Pandas, PyODBC or anything else. </p>
<p>Please bear with me.</p>
<p>My current Python 3 code:</p>
<pre><code>import pandas as pd
import pyodbc
cnxn = pyodbc.co... | 3 | 2016-06-17T19:50:02Z | 37,889,429 | <p>you may try to do it this way:</p>
<pre><code>df = pd.concat([pd.read_sql(querystring, cnxn, params = [i] for i in orders], ignore_index=True)
</code></pre>
<p>so you don't need an extra loop ...</p>
<p>alternatively if your <code>orders</code> list is relatively small, you can select all your rows "in one shot":... | 1 | 2016-06-17T19:54:45Z | [
"python",
"pandas",
"dataframe",
"pyodbc"
] |
Appending to a Pandas Dataframe From a pd.read_sql Output | 37,889,360 | <p>I'm coming from R but need to do this in Python for various reasons.
This very well could be a basic PEBKAC issue with my Python more than anything with Pandas, PyODBC or anything else. </p>
<p>Please bear with me.</p>
<p>My current Python 3 code:</p>
<pre><code>import pandas as pd
import pyodbc
cnxn = pyodbc.co... | 3 | 2016-06-17T19:50:02Z | 37,889,438 | <p>Need to assign the result:</p>
<pre><code>df = df.append(pd.read_sql(querystring, cnxn, params = [i]))
</code></pre>
| 1 | 2016-06-17T19:55:16Z | [
"python",
"pandas",
"dataframe",
"pyodbc"
] |
Appending to a Pandas Dataframe From a pd.read_sql Output | 37,889,360 | <p>I'm coming from R but need to do this in Python for various reasons.
This very well could be a basic PEBKAC issue with my Python more than anything with Pandas, PyODBC or anything else. </p>
<p>Please bear with me.</p>
<p>My current Python 3 code:</p>
<pre><code>import pandas as pd
import pyodbc
cnxn = pyodbc.co... | 3 | 2016-06-17T19:50:02Z | 37,889,450 | <p>How about</p>
<p><code>for i in orders:
df = df.append(pd.read_sql(querystring, cnxn, params = [i]))</code></p>
| 0 | 2016-06-17T19:55:47Z | [
"python",
"pandas",
"dataframe",
"pyodbc"
] |
Creating shapes using For Loop Coding in Python | 37,889,366 | <p>Hey guys I am having a difficult time writing a code to create a triangle of asterisks and having a reflection of the triangle appear on the same line. The end product is two triangles that have a giant V shape of empty space in the middle. So far I have created the left side triangle but I do not know how to reflec... | 0 | 2016-06-17T19:50:39Z | 37,890,039 | <p>One solution doesn't even use nested for loops</p>
<pre><code>for A in range(1,10):
print(A*"*" + (18-(2*A))*" " + A*"*")
</code></pre>
<p>or</p>
<pre><code>for A in range(1,N):
print(A * "*" + (((N-1)*2)*A)*" " + A * "*")
</code></pre>
| 0 | 2016-06-17T20:38:06Z | [
"python",
"for-loop",
"range",
"shapes"
] |
Python, Regex: Is it possible to have 2 ending anchors? | 37,889,435 | <p>I am using this regex: </p>
<pre><code>(r'(?<=DESCR:).*?(?=")')
</code></pre>
<p>to retrieve data from logs formatted like this</p>
<pre><code> DESCR: "Cisco ASR1004 Chassis"
</code></pre>
<p>or </p>
<pre><code>NAME: "CISCO2951/K9", DESCR: "CISCO2951/K9 chassis, Hw Serial#: FTX1619AK8E, Hw Revision: 1.1"
</c... | 1 | 2016-06-17T19:55:08Z | 37,889,776 | <p>Let me aswer the question in the title, mainly:</p>
<blockquote>
<p>Is it possible to have 2 ending anchors?</p>
</blockquote>
<p>If by anchors, you understand some context that is just checked but not consumed, yes, you may use an alternation in the <em>lookahead</em>. </p>
<p>If you want to match <code>a</cod... | 1 | 2016-06-17T20:19:07Z | [
"python",
"regex"
] |
How to make Python change xlsx files when Excel app is opened? | 37,889,467 | <p>Sorry if I ask a question that may have been asked before but I could not really find the answer in Google and Stack Overflow forums.</p>
<p>Question is connected with <code>openpyxl</code> usage as it is the most convenient library which works with <code>xlsx</code> files. </p>
<pre><code> import openpyxl
... | 1 | 2016-06-17T19:56:48Z | 37,890,323 | <p>OpenPyXL operates directly on files; it has nothing to do with the Excel program, and has no control over the Excel program. As such, if the file it is trying to modify is locked by Excel, there is nothing OpenPyXL can do about that.</p>
<p>This question is tagged with <a href="/questions/tagged/excel-vba" class="p... | 2 | 2016-06-17T21:02:01Z | [
"python",
"excel",
"python-2.7",
"excel-vba",
"openpyxl"
] |
Python requests and instagram | 37,889,539 | <p>I am playing around with the instagram api and requests, trying to get past the OAuth. I use <code>r = requests.get(...)</code> and follow the instagram doc. However, the output from requests is never what I expect. I am having 2 issues that are somewhat similar.</p>
<p>1) If I send the wrong parameters I expect to... | 0 | 2016-06-17T20:02:02Z | 37,890,615 | <p>It tells you in the <a href="https://www.instagram.com/developer/authentication/" rel="nofollow">documentation</a> exactly what happen, <em>At this point, we present the user with a login screen and then a confirmation screen where to grant your app access to her Instagram data</em>, if you run the snippet below you... | 1 | 2016-06-17T21:28:04Z | [
"python",
"python-requests",
"instagram"
] |
Stripe, PayPal, integration with django-rest-framework | 37,889,607 | <p>I'm pretty new on rest-framework ground so please bare with me. I want to integrate Stripe, PayPal or Braintree into django project, and I want to use 'django-rest-framework`, now I'm confused about one thing and that is - Should I "touch" my database?</p>
<p>What I mean, I want only to charge once to my customers,... | 1 | 2016-06-17T20:06:10Z | 37,890,296 | <p>(Disclaimer: I'm a Stripe employee, so I'll only talk about Stripe here.)</p>
<p>Stripe makes it easy to be PCI compliant. With a proper integration, you will never have access to your customers' payment information.</p>
<p>A typical payment flow with Stripe can be divided in two steps:</p>
<ol>
<li><p>Collect th... | 1 | 2016-06-17T20:59:34Z | [
"python",
"django",
"rest",
"paypal",
"stripe-payments"
] |
zmq python publish c++ subscribe | 37,889,628 | <p>I have a ZeroMQ publisher in <code>c++</code> (using <strong><code>zhelpers.hpp</code></strong>) and ZeroMQ subscriber in python3 (using <strong><code>pyzmq</code></strong>).</p>
<p>Trouble is, no message is recived in subscriber. I suppose, there is a problem with ZeroMQ filter. I can't figure out, how to properly... | 0 | 2016-06-17T20:08:19Z | 37,890,671 | <p>From the <a href="http://api.zeromq.org/2-1:zmq-setsockopt" rel="nofollow">docs</a>:
<code>setsockopt</code>'s last argument is the length of the option value. In your case the length of the string you are passing as a filter value.</p>
<p>As you put in <code>8</code> as the length c++ will read 8 characters but yo... | 0 | 2016-06-17T21:33:12Z | [
"python",
"c++",
"python-3.x",
"zeromq",
"publish-subscribe"
] |
zmq python publish c++ subscribe | 37,889,628 | <p>I have a ZeroMQ publisher in <code>c++</code> (using <strong><code>zhelpers.hpp</code></strong>) and ZeroMQ subscriber in python3 (using <strong><code>pyzmq</code></strong>).</p>
<p>Trouble is, no message is recived in subscriber. I suppose, there is a problem with ZeroMQ filter. I can't figure out, how to properly... | 0 | 2016-06-17T20:08:19Z | 37,897,949 | <p>I ended up swiching to C using zhelpers.h. I had to update libzmq-dev to version > 3.2. I used example on zguide: <a href="http://zguide.zeromq.org/c:psenvsub" rel="nofollow">zmq subscriber in c</a> </p>
| 0 | 2016-06-18T14:16:53Z | [
"python",
"c++",
"python-3.x",
"zeromq",
"publish-subscribe"
] |
How can I force Python code to read input files again without rebooting my computer | 37,889,723 | <p>I am scanning through a large number of files looking for some markers. I am starting to be really confident that once I have run through the code one time Python is not rereading the actual files from disk. I find this behavior strange because I was told that one reason I needed to structure my file access in th... | 1 | 2016-06-17T20:15:21Z | 37,889,928 | <p>This is caused by caching in Windows. It is not related to Python.</p>
<p>In order to stop Windows from caching your reads:</p>
<ol>
<li><p>Disable paging file in Windows and fill the RAM up to 90%</p></li>
<li><p>Use some tool to disable file caching in Windows <a href="https://technet.microsoft.com/en-us/sysinte... | 5 | 2016-06-17T20:31:22Z | [
"python",
"python-2.7",
"file",
"garbage-collection"
] |
How can I force Python code to read input files again without rebooting my computer | 37,889,723 | <p>I am scanning through a large number of files looking for some markers. I am starting to be really confident that once I have run through the code one time Python is not rereading the actual files from disk. I find this behavior strange because I was told that one reason I needed to structure my file access in th... | 1 | 2016-06-17T20:15:21Z | 37,890,934 | <p>I fail to see why this is a problem. I'm not 100% certain of how Windows handles file cache invalidation, but unless the "Last modified time" changes, you and I and Windows would assume that the file still holds the same content. If the file holds the same content, I don't see why reading from cache can be a problem... | 0 | 2016-06-17T21:56:04Z | [
"python",
"python-2.7",
"file",
"garbage-collection"
] |
How to write an output file of multiple time called functions? | 37,889,752 | <p>I tried to write a output file from the values return from consecutively called functions but I couldnt make it instead I am getting error like below:</p>
<pre><code> MA.write(l)
TypeError: expected a character buffer object
</code></pre>
<p>MY script:</p>
<pre><code>def do():
print "Hello"
if __name__ == ... | 0 | 2016-06-17T20:17:44Z | 37,890,034 | <p>Try something like this:</p>
<pre><code>def do():
return "Hello"
if __name__ == "__main__":
MA=open("hi.txt","w") # Prepare hi.txt
l=map(lambda x: do(), range(10)) # Adds Hello to the list 10 times
MA.write('\n'.join(l)) # Combines them together with a newline between each entry
MA.close() # Fi... | 1 | 2016-06-17T20:37:52Z | [
"python",
"function",
"file-handling"
] |
How to write an output file of multiple time called functions? | 37,889,752 | <p>I tried to write a output file from the values return from consecutively called functions but I couldnt make it instead I am getting error like below:</p>
<pre><code> MA.write(l)
TypeError: expected a character buffer object
</code></pre>
<p>MY script:</p>
<pre><code>def do():
print "Hello"
if __name__ == ... | 0 | 2016-06-17T20:17:44Z | 37,890,132 | <p>I think this is your intent:</p>
<pre><code>def do():
return "Hello"
if __name__ == "__main__":
with open("hi.txt", "w") as adele:
hellos = map(lambda x: do(), range(10))
for hello in hellos:
adele.write(hello)
</code></pre>
<ul>
<li><code>do()</code> needs to return a value to... | 2 | 2016-06-17T20:44:22Z | [
"python",
"function",
"file-handling"
] |
A class within a class, should this be fixed or is it intentional? | 37,889,766 | <p>Today I was experimenting and / or messing around with Python 3.5.</p>
<p>I happened to <em>"accidentally"</em> write this:</p>
<pre><code>class Apple(object):
class green(object):
def eat():
print("You just ate a green apple...")
class red(object):
def eat():
print... | 1 | 2016-06-17T20:18:32Z | 37,889,816 | <p>Classes within classes work just fine in python -- However, python's primary mechanism for handling namespaces is <em>modules</em> and <em>packages</em>, not classes. I've not found a whole lot of use for classes within classes (though there probably are <em>some</em> valid use-cases).</p>
<p>To set up something l... | 5 | 2016-06-17T20:21:35Z | [
"python",
"class",
"python-3.x",
"inner-classes",
"python-3.5"
] |
Pandas Apply Syntax | 37,889,824 | <p>I can't figure out how to apply a simple function to every row of a column in a Panda data frame.</p>
<p>Example:</p>
<pre><code>def delLastThree(x):
x = x.strip()
x = x[:-3]
return x
arr = ['test123','test234','test453']
arrDF = pandas.DataFrame(arr)
arrDF.columns = ['colOne']
arrDF['colOne'].apply(d... | 0 | 2016-06-17T20:22:12Z | 37,889,839 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> function for series (single column):</p>
<pre><code>In [15]: arrDF['colOne'].map(delLastThree)
Out[15]:
0 test
1 test
2 test
Name: colOne, dtype: object
</code></pre>
<p>or if you want to ch... | 1 | 2016-06-17T20:23:30Z | [
"python",
"pandas"
] |
Pandas Apply Syntax | 37,889,824 | <p>I can't figure out how to apply a simple function to every row of a column in a Panda data frame.</p>
<p>Example:</p>
<pre><code>def delLastThree(x):
x = x.strip()
x = x[:-3]
return x
arr = ['test123','test234','test453']
arrDF = pandas.DataFrame(arr)
arrDF.columns = ['colOne']
arrDF['colOne'].apply(d... | 0 | 2016-06-17T20:22:12Z | 37,889,854 | <p>You are creating a <code>pd.Series</code> when selecting using single brackets with <code>df['colOne']</code>.</p>
<p>Either use <code>.apply(func, axis=1)</code> on a <code>DataFrame</code>, ie either when selecting with <code>[['colOne']]</code>, or without selecting any columns. However, if you use <code>.apply(... | 2 | 2016-06-17T20:24:48Z | [
"python",
"pandas"
] |
Find rank and percentage rank in list | 37,889,843 | <p>I have some very large lists that I am working with (>1M rows), and I am trying to find a fast (the fastest?) way of, given a float, ranking that float compared to the list of floats, and finding it's percentage rank compared to the range of the list. Here is my attempt, but it's extremely slow:</p>
<pre><code>X =[... | 1 | 2016-06-17T20:23:55Z | 37,889,981 | <p>Sorting the array seems to be rather slow. If you don't need the array to be sorted in the end, then numpy's boolean operations are quicker.</p>
<pre><code>arr = np.array(X)
bool_array = arr < val # Returns boolean array
RANK = np.sum(bool_array)
PCT_RANK = RANK/len(X)
</code></pre>
<p>Or, better yet, use a li... | 3 | 2016-06-17T20:34:59Z | [
"python",
"performance",
"numpy",
"pandas",
"rank"
] |
Find rank and percentage rank in list | 37,889,843 | <p>I have some very large lists that I am working with (>1M rows), and I am trying to find a fast (the fastest?) way of, given a float, ranking that float compared to the list of floats, and finding it's percentage rank compared to the range of the list. Here is my attempt, but it's extremely slow:</p>
<pre><code>X =[... | 1 | 2016-06-17T20:23:55Z | 37,890,189 | <p>The two slow parts of your code are:</p>
<ul>
<li><p><code>st = np.sort(arr)</code>. Sorting the list takes on average O(n log n) time, where n is the size of the list.</p></li>
<li><p><code>RANK = float([i for i, k in enumerate(st) if k == val][0]) + 1</code>. Iterating through the list takes O(n) time.</p></li>
<... | 1 | 2016-06-17T20:49:34Z | [
"python",
"performance",
"numpy",
"pandas",
"rank"
] |
method vs __init__ in a python class | 37,889,903 | <p>My understanding of these methods are:</p>
<ul>
<li><code>__init__()</code> is like constructor.</li>
<li><code>run()</code> is called when a thread for this class starts.</li>
</ul>
<p>But why do we need a run method? Could we have instantiated an object of the class and all initializations stay in <code>__init__... | 0 | 2016-06-17T20:29:10Z | 37,889,956 | <p>I think the Python threading module provides a good example. What if you had a derived thread class that always ran the same function, but perhaps you want to give it different inputs. You might want to instantiate a lot of objects of the class but with differing inputs -- and you don't want it to start running ye... | 1 | 2016-06-17T20:32:58Z | [
"python",
"class",
"subprocess"
] |
method vs __init__ in a python class | 37,889,903 | <p>My understanding of these methods are:</p>
<ul>
<li><code>__init__()</code> is like constructor.</li>
<li><code>run()</code> is called when a thread for this class starts.</li>
</ul>
<p>But why do we need a run method? Could we have instantiated an object of the class and all initializations stay in <code>__init__... | 0 | 2016-06-17T20:29:10Z | 37,889,987 | <p><code>__init__</code> runs once (when the object is constructed), while <code>run</code> (in the example you gave) runs in the background (another process) as long as the object exists.<br/></p>
<p>The only difference between <code>__init__</code> and <code>run</code> are that the first runs in the main thread, whi... | 1 | 2016-06-17T20:35:27Z | [
"python",
"class",
"subprocess"
] |
method vs __init__ in a python class | 37,889,903 | <p>My understanding of these methods are:</p>
<ul>
<li><code>__init__()</code> is like constructor.</li>
<li><code>run()</code> is called when a thread for this class starts.</li>
</ul>
<p>But why do we need a run method? Could we have instantiated an object of the class and all initializations stay in <code>__init__... | 0 | 2016-06-17T20:29:10Z | 37,889,988 | <p>You are correct about <code>__init__()</code> being a constructor. In this example, the goal is to run a function, the <code>run()</code> function, in a thread. The example provides a clean way of doing this. You cannot run the code inside the <code>run()</code> function inside the <code>__init__()</code>, as this w... | 0 | 2016-06-17T20:35:31Z | [
"python",
"class",
"subprocess"
] |
Moving app to docker from host increases HTTP lag by 5 seconds | 37,889,960 | <p>I have an app that I noticed was performing badly when making outgoing HTTP requests (an extra lag of 5 seconds). Through a lot of trials / tests, I realized that moving the app outside of docker into the host machine eliminated the weird HTTP lag. </p>
<p>I'm using alpine linux for the docker image, and ubuntu is ... | 1 | 2016-06-17T20:33:09Z | 39,415,759 | <p>I don't know whether you still require this information or not. We've seen something similar, which was resolved by upgrading Docker.</p>
<p>Not knowing the cause of the issue caused me to do a little digging, and I found this:</p>
<p><a href="https://github.com/docker/docker/issues/20661" rel="nofollow">https://g... | 2 | 2016-09-09T16:14:49Z | [
"python",
"networking",
"docker",
"urllib3",
"alpine"
] |
How to trap an exception that occurs in code underlying Python for-loop? | 37,890,123 | <p>I STILL DO NOT HAVE A SOLUTION.</p>
<p>I am writing a mail processing program. I have a big INBOX file downloaded (by Thunderbird) that has my gmail.</p>
<p>It runs on some mailboxes, but not the INBOX from gmail. It goes for a long while, but then I get a <code>UnicodeDecodeError</code> exception with a message... | 0 | 2016-06-17T20:43:48Z | 37,890,328 | <p>The internal mechanics of a <code>for</code> loop is something like this:</p>
<pre><code>#for message in mbox:
# do_stuff()
it = iter(mbox)
try:
while True:
message = next(it)
do_stuff()
except StopIteration:
pass
</code></pre>
<p>so you could handle the iterator manually or use a gener... | 1 | 2016-06-17T21:02:30Z | [
"python",
"exception",
"for-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.