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 |
|---|---|---|---|---|---|---|---|---|---|
Syntax error while using Foreign Keys in Sqlite 3 in Python. | 38,144,342 | <p>I have a database schema file which I read in my Flask module.</p>
<pre><code>PRAGMA foreign_keys = 1;
drop table if exists user;
create table user(uid integer primary key autoincrement,
username text not null,
password text not null,
email text not null);
drop table if exists asset;
create table asset(aid integ... | 0 | 2016-07-01T11:30:22Z | 38,144,688 | <p>As @soon pointed you have a syntax error on <code>FOREIGN KEY</code> keyword, also you should define column name (owner). </p>
<p><code>drop table if exists asset;
create table asset(aid integer primary key autoincrement,
assetname text not null,
releasedate text,
owner integer,
FOREIGN KEY(owner) REFERENCES user);... | 1 | 2016-07-01T11:48:55Z | [
"python",
"sqlite"
] |
using selenium with python on ubuntu 14.04 | 38,144,403 | <p>I want to automate the navigation of a page, scan its QR code and then interact with it.</p>
<p>I am doing this with selenium and python.</p>
<p>But I don't see any display to scan the QR code,</p>
<p>this is how my code begins:</p>
<pre><code>from pyvirtualdisplay import Display
from selenium import webdriver
f... | 0 | 2016-07-01T11:33:09Z | 38,168,243 | <p>The reason is that you are using a virtual display ( i.e. headless browser ), remove these two lines and you must be able to see the browser.</p>
<pre><code>display = Display(visible=0, size=(800, 600))
display.start()
</code></pre>
<p>Since you don't need the virtual display, remove the first line as well.</p>
| 2 | 2016-07-03T08:45:11Z | [
"python",
"selenium",
"ubuntu-14.04"
] |
python error while inserting node in binary tree | 38,144,439 | <p>I am trying to write a binary tree implementation in python, but am getting an error while adding a child node using recursion. I rarely use python and could not understand where addChild() is given 4 args. As per my understanding, I have given only 3 same as the function prototype. Please ignore other functions imp... | -1 | 2016-07-01T11:35:03Z | 38,144,540 | <p>Your <code>addChild</code> method takes 3 arguments ( including <code>self</code>) but you're passing it 4 arguments(including <code>self</code>).</p>
<p>Change :</p>
<pre><code>def addChild(self, key, value):
</code></pre>
<p>to :</p>
<pre><code>def addChild(self, rightChild, key, value):
</code></pre>
<p>i.e,... | 0 | 2016-07-01T11:40:10Z | [
"python",
"algorithm",
"binary-tree"
] |
Python Inheritance - What am I doing wrong? | 38,144,461 | <p>I am trying to run a example of inheritance and don't know why my output is not correct. Below is the code.</p>
<pre><code>class BankAccount():
def __init__(self):
self.balance=0
def deposit(self,amount):
self.balance += amount
print(self.balance)
def withdraw(self,amount):
... | -1 | 2016-07-01T11:36:15Z | 38,144,555 | <p>Your <code>MinimumBalance(50)</code> instance has a balance of 0. The <code>a</code> object is independent, it is a separate instance, it doesn't matter what balance that entry has. The <code>MinimumBalance()</code> class has all the functionality of <code>Balance</code>, with some tweaks, so you just interact with ... | 3 | 2016-07-01T11:40:52Z | [
"python",
"python-3.x"
] |
Python Inheritance - What am I doing wrong? | 38,144,461 | <p>I am trying to run a example of inheritance and don't know why my output is not correct. Below is the code.</p>
<pre><code>class BankAccount():
def __init__(self):
self.balance=0
def deposit(self,amount):
self.balance += amount
print(self.balance)
def withdraw(self,amount):
... | -1 | 2016-07-01T11:36:15Z | 38,144,559 | <p>Your inheritance construction is right, however you have made two objects. MinimumBalance is now also a BankAccount but with a different withdraw function. You should call it BankAccountWithMinimumBalance instead which is what it is. Then instead of making two objects, you just make a BankAccountWithMinimumBalance a... | 0 | 2016-07-01T11:41:09Z | [
"python",
"python-3.x"
] |
Python - TypeError: 'int' object is not subscriptable | 38,144,503 | <p>I have written some code:</p>
<pre><code>def ICP(x):
numofrepeat=0
warning=0
while numofrepeat<len(str(x)) or (x[numofrepeat]==2) or (x[numofrepeat]==3) or (x[numofrepeat]==5) or (x[numofrepeat]==7):
if (x[numofrepeat]==0):
warning=warning+1
if warning>1:
nu... | 0 | 2016-07-01T11:38:16Z | 38,144,986 | <p>The problem should seem clear enough from the error:</p>
<blockquote>
<p>TypeError: 'int' object is not subscriptable</p>
</blockquote>
<p>Objects of type <code>int</code> are neither iterable nor <em>subscriptable</em>. I really don't know why you want to index <code>x</code> since you're apparently passing an ... | 1 | 2016-07-01T12:04:37Z | [
"python",
"python-3.x"
] |
How to perform stencil computations element-wise on a matrix in Theano? | 38,144,525 | <p>I have the following blurring kernel I need to apply to every pixel in an RGB image </p>
<pre><code>[ 0.0625 0.025 0.375 0.025 0.0625 ]
</code></pre>
<p>So, the pseudo-code looks something like this in Numpy</p>
<pre><code>for i in range(rows):
for j in range(cols):
for k in range(3):
fi... | 2 | 2016-07-01T11:39:41Z | 38,196,969 | <p>You can use <code>Conv2D</code> function for this task. see the reference <a href="http://deeplearning.net/software/theano/library/tensor/nnet/conv.html#theano.tensor.nnet.conv2d" rel="nofollow">here</a> and may be you also can read the example tutorial <a href="http://deeplearning.net/tutorial/lenet.html#the-convol... | 0 | 2016-07-05T06:52:44Z | [
"python",
"image",
"numpy",
"kernel",
"theano"
] |
Plotly moveable/draggable legends, python | 38,144,566 | <p>Is it possible to make the plotly legends draggable? Currently I have my legend positioned outside the graph. I want to move it inside the graph, which is covered in the documentation, but I want to be able to make it draggable. </p>
| 0 | 2016-07-01T11:41:42Z | 39,254,989 | <p>There is no direct way to drag the legend on a Plotly chart as far as I know.</p>
<p>You could find a workround by creating your legend in a HTML canvas and binding the onclick() function for each legend item to the <a href="https://github.com/plotly/postMessage-API" rel="nofollow">Plotly PostMessage API</a> restyl... | 0 | 2016-08-31T16:46:38Z | [
"python",
"plotly"
] |
Django-autocomplete-light returns object names instead of corresponding field values | 38,144,622 | <p>My problem whith django-autocomplete-light (dal 3) is that in the admin, instead of showing the choices corresponding tom my designated field (i.e. <code>birth_nation</code> see <code>forms.py</code> section), I always get a list of the <strong>str</strong> values of my queryset objects (see #models.py section) whic... | 0 | 2016-07-01T11:44:52Z | 39,035,181 | <p>try this:</p>
<pre><code>def __str__(self):
return self.birth_nation
</code></pre>
| 0 | 2016-08-19T09:08:33Z | [
"python",
"django",
"django-autocomplete-light"
] |
Add up the value of data[x] to data[x+1] | 38,144,640 | <p>I have a long list of data which I am working with now,containing a list of 'timestamp' versus 'quantity'. However, the timestamp in the list is not all in order (for example,timestamp[x] can be 140056 while timestamp[x+1] can be 560). I am not going to arrange them, but to add up the value of timestamp[x] to timest... | -2 | 2016-07-01T11:45:54Z | 38,145,132 | <p>The problem is that you're treating <code>t</code> as if it is an <em>index</em> of the list. In your case, <code>t</code> holds the actual values of the list, so constructions like <code>timestamp[t]</code> are not valid. You either want:</p>
<pre><code>for t in range(len(timestamp)):
</code></pre>
<p>Or if you w... | 0 | 2016-07-01T12:11:46Z | [
"python",
"python-3.x"
] |
Add up the value of data[x] to data[x+1] | 38,144,640 | <p>I have a long list of data which I am working with now,containing a list of 'timestamp' versus 'quantity'. However, the timestamp in the list is not all in order (for example,timestamp[x] can be 140056 while timestamp[x+1] can be 560). I am not going to arrange them, but to add up the value of timestamp[x] to timest... | -2 | 2016-07-01T11:45:54Z | 38,145,143 | <p>When you <code>for the in timestamp</code> you are making <code>t</code> take on the value of each item in timestamp. But then you try to use <code>t</code> as an index to make <code>previous</code>. To do this, try:</p>
<pre><code>for i, t, in enumerate(timestamp):
previous = timestamp[i]
current = t
</cod... | 0 | 2016-07-01T12:12:13Z | [
"python",
"python-3.x"
] |
Delay message consumption with SelectConnection | 38,144,789 | <p>I want to write a consumer with a SelectConnection. </p>
<p>We have several devices in our network infrastructure that close connections after a certain time, therefore I want to use the heartbeat functionality. </p>
<p>As far as I know, the IOLoop runs on the main thread, so heartbeat frames can not be processed ... | 1 | 2016-07-01T11:53:41Z | 38,152,860 | <p>I am not an expert on SelectConnection for pika, but you could implement this by setting the <a href="https://www.rabbitmq.com/consumer-prefetch.html" rel="nofollow">Consumer Prefetch (QoS)</a> to the wanted number of processes. </p>
<p>This would basically mean that once a message comes in, you offload it to a pro... | 0 | 2016-07-01T19:37:27Z | [
"python",
"python-2.7",
"rabbitmq",
"pika"
] |
Does Python cache repeatedly accessed files? | 38,144,825 | <p>I was wondering if Python is smart enough enough to cache repeatedly accessed files, e.g. when reading the same CSV with pandas or unpickling the same file multiple times.</p>
<p>Is this even Python's responsibility, or should the operating system take care of it?</p>
| 0 | 2016-07-01T11:56:17Z | 38,145,044 | <p>No, Python is just a language and doesn't really do anything on its own. A particular Python library might implement caching, but the standard functions you use to open and read files don't do so. The higher-level file-loading functions in Pandas and the CSV module don't do any caching either.</p>
<p>The operating ... | 1 | 2016-07-01T12:08:08Z | [
"python",
"pandas"
] |
Should I use python classes for a MySQL database insert program? | 38,144,924 | <p>I have created a database to store NGS sequencing results. It consists of 17 tables to store all of the information. The results are stored in spreadsheets which I parse data from and store in variables using python (2.7), and then use the python package mysqldb to insert data into the database. I mainly use functio... | 0 | 2016-07-01T12:01:51Z | 38,145,529 | <p>17tables it means you may use about 17 classes.
Use a simple script. webpy.db
<a href="https://github.com/webpy/webpy/blob/master/web/db.py" rel="nofollow">https://github.com/webpy/webpy/blob/master/web/db.py</a> just modify few code.
Then you can use webpy api: <a href="http://webpy.org/docs/0.3/api#web.db" rel="n... | 0 | 2016-07-01T12:32:05Z | [
"python",
"database",
"class",
"oop",
"mysql-python"
] |
Database Connection SQL Server / Oracle | 38,145,048 | <p>i have been trying to connect to SQL Server (I have SQL Server 2014 installed on my machine and SQL Native Client 11.0 32bit as driver) using Python and specifically pyodbc but i did not manage to establish any connection.
This is the connection string i am using:</p>
<p>conn = pyodbc.connect('''DRIVER={SQL Server... | 0 | 2016-07-01T12:08:18Z | 38,146,099 | <p>I may be missing something here. Why don't you connect to your Oracle database as a SQL Server linked server (or the other way around) ?</p>
| 0 | 2016-07-01T12:59:36Z | [
"python",
"sql-server",
"database",
"oracle",
"python-3.x"
] |
Catching the Traceback on KeyboardInterrupt() | 38,145,111 | <p>I have a code that I use to stop on Ctrl+C. I would like to do some things juste after i did Ctrl+C. Therefore I write:</p>
<pre><code>try:
work()
except KeyboardInterrupt:
do_other_stuff()
</code></pre>
<p>But I don't see where I did Ctrl+C, as no Traceback prints; I want to see the usual message</p>
<pr... | 0 | 2016-07-01T12:10:44Z | 38,145,201 | <p>You were close:</p>
<pre><code>try:
while True:
x = 1
except KeyboardInterrupt as e:
print 'Here we are, in the error handler!'
raise e
</code></pre>
<p>Just make sure you run <code>do_other_stuff()</code> before you call <code>raise e</code>.</p>
| 0 | 2016-07-01T12:15:44Z | [
"python"
] |
Catching the Traceback on KeyboardInterrupt() | 38,145,111 | <p>I have a code that I use to stop on Ctrl+C. I would like to do some things juste after i did Ctrl+C. Therefore I write:</p>
<pre><code>try:
work()
except KeyboardInterrupt:
do_other_stuff()
</code></pre>
<p>But I don't see where I did Ctrl+C, as no Traceback prints; I want to see the usual message</p>
<pr... | 0 | 2016-07-01T12:10:44Z | 38,145,287 | <p><code>KeyboardInterrupt</code> inherit from <code>BaseException</code>, in <code>BaseException</code> you can get the line of the error using the <code>traceback.format_exc(e)</code>.</p>
| 1 | 2016-07-01T12:19:36Z | [
"python"
] |
Catching the Traceback on KeyboardInterrupt() | 38,145,111 | <p>I have a code that I use to stop on Ctrl+C. I would like to do some things juste after i did Ctrl+C. Therefore I write:</p>
<pre><code>try:
work()
except KeyboardInterrupt:
do_other_stuff()
</code></pre>
<p>But I don't see where I did Ctrl+C, as no Traceback prints; I want to see the usual message</p>
<pr... | 0 | 2016-07-01T12:10:44Z | 38,145,342 | <pre><code>import sys, traceback
def func():
try:
work()
except KeyboardInterrupt:
do_something()
traceback.print_exc(file=sys.stdout)
</code></pre>
<p>if <code>file</code> is omitted then the output goes to <code>stderr</code>.
for more on traceback... <a href="https://docs.python.org... | 3 | 2016-07-01T12:21:09Z | [
"python"
] |
Reshaping R columns with Incremental custom header names | 38,145,252 | <p>I have a dataframe with 3 columns, Min, Max, Average. The dataframe contains 7000 rows.</p>
<pre><code>| Min | Max | Average |
| 1.2 | 1.4 | 1.3 |
| 1.0 | 2.0 | 1.5 |
| 1.2 | 1.4 | 1.6 |
| 1.0 | 7.0 | 1.9 |
</code></pre>
<p>And I want</p>
<pre><code>| Min1 | Max1 | Average1 | Min2 | Max2 | Average... | 2 | 2016-07-01T12:18:25Z | 38,145,395 | <p>In <code>R</code>, we can use <code>data.table</code>. Convert the 'data.frame' to 'data.table' (<code>setDT(df1)</code>), create a grouping variable using 'grp' so that every two rows have a unique index ('grp'), using <code>dcast</code> we convert the 'long' to 'wide' format by using the formula method. The <cod... | 2 | 2016-07-01T12:23:44Z | [
"python",
"statistics"
] |
pandas dataframe to mariadb database with to_sql and sqlalchemy | 38,145,382 | <p>I want to use the pandas function to_sql to write a dataframe into a MariaDB database. My Python code inside PyCharm looks as follows:</p>
<pre><code>import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
myd = pd.read_csv('/[path]/[filename].csv')
engine = create_engine('mysql+mysqlconne... | 0 | 2016-07-01T12:23:13Z | 38,146,021 | <p>Passing sqlalchemy engines is only supported starting from pandas 0.14.0</p>
<p>To use <code>to_sql</code> with older pandas version, you need to pass the raw connection (<code>engine.raw_connection()</code>) and <code>flavor='mysql'</code> to <code>to_sql</code>:</p>
<pre><code>myd.to_sql(name='[tablename]', con=... | 0 | 2016-07-01T12:56:04Z | [
"python",
"pandas",
"sqlalchemy",
"mariadb",
"mysql-connector"
] |
right join with pandas | 38,145,404 | <pre><code>stores = [[232, '2016-02-05 04:30:00', 'Test User', 1],
[332, '2016-02-06 04:30:00', 'Test User', 2],
[432, '2016-02-07 04:30:00', 'Test User', 3],
[532, '2016-02-08 04:30:00', 'Test User', 4],
[632, '2016-02-09 04:30:00', 'Test User', 5]]
visits = pd.DataFrame(data=s... | 0 | 2016-07-01T12:24:08Z | 38,145,636 | <p>You want a left join, not right join. Then it works:</p>
<pre><code> auditor scene product amount
store visit
232 2016-02-05 04:30:00 Test User 1 1551.0 2.0
332 2016-02-06 04:30:00 Test User 2 NaN NaN
432... | 0 | 2016-07-01T12:37:32Z | [
"python",
"pandas",
"dataframe"
] |
How to convert combination of binary and ascii to human readable format in python | 38,145,459 | <p>Below is my code for receiving data over socket.</p>
<pre><code>from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class Chat(LineReceiver):
def lineReceived(self, line):
print(line)
class ChatFactory(Factory):
def _... | 0 | 2016-07-01T12:27:13Z | 38,145,598 | <p>You can use <code>struct.unpack()</code>, but you have to know what you are gonna unpack (int, long, signed, etc.), the endiness if it is encoded on more that 1 bytes, ASCII are 7 bits, encoded on 1 byte.</p>
<p>Read more about struct <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">here</a>.<... | -1 | 2016-07-01T12:35:30Z | [
"python",
"twisted"
] |
How to convert combination of binary and ascii to human readable format in python | 38,145,459 | <p>Below is my code for receiving data over socket.</p>
<pre><code>from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class Chat(LineReceiver):
def lineReceived(self, line):
print(line)
class ChatFactory(Factory):
def _... | 0 | 2016-07-01T12:27:13Z | 38,145,626 | <p>This can be solved just with the binary string:</p>
<pre><code>import struct
header = line[:2]
if header!=b'$$':
raise RuntimeError('Wrong header')
# Assumes you want two have 2 bytes, not one word
L = struct.unpack('BB',line[2:4])
ID = struct.unpack('7B', line[4:11])
location = line[11:]
print 'L={},{}, ID={},... | 1 | 2016-07-01T12:37:00Z | [
"python",
"twisted"
] |
controling the x ticks date values | 38,145,505 | <p>I have the following data sample as x,y pairs and both x and y are Unix time-stamps:</p>
<pre><code>1354648326,1354648326
1354649456,1371775551
1354649664,1429649819
1354649667,1429644021
1354649683,1356976159
1354649767,1441369794
1354649863,1414467362
1354650486,1366297316
1354650757,1456962664
1354650789,1359398... | 9 | 2016-07-01T12:30:31Z | 38,186,557 | <p>Your problem is that your graph only has five ticks, so it can only display five labels. If you want to display all the labels, then you need to make sure that you have the same number of ticks.</p>
<p>I don't have pandas installed, and anyway, don't have the full data so can't re-create the labels. I have simply c... | 3 | 2016-07-04T14:00:33Z | [
"python",
"datetime",
"matplotlib"
] |
controling the x ticks date values | 38,145,505 | <p>I have the following data sample as x,y pairs and both x and y are Unix time-stamps:</p>
<pre><code>1354648326,1354648326
1354649456,1371775551
1354649664,1429649819
1354649667,1429644021
1354649683,1356976159
1354649767,1441369794
1354649863,1414467362
1354650486,1366297316
1354650757,1456962664
1354650789,1359398... | 9 | 2016-07-01T12:30:31Z | 38,194,880 | <p>Limits of your x-axis data is only from <code>2012-12-05 06:12:06</code> to <code>2012-12-05 08:22:19</code>. You have to expand date range.</p>
<p>However you may use this code to set x-axis ticks every 3 month:</p>
<pre><code>import matplotlib.pyplot as plt
from itertools import izip
import datetime
import numpy... | 1 | 2016-07-05T03:41:50Z | [
"python",
"datetime",
"matplotlib"
] |
How to print time in exact UTC format "2015-05-28T22:55:00:000Z" in python27 | 38,145,532 | <p>I need to see output in above-mentioned format. I tried:</p>
<ol>
<li><p><code>datetime.datetime.utcnow().isoformat()[:-4]</code></p></li>
<li><p><code>datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S:%f')[:-4]</code></p></li>
</ol>
<p>it does not include <code>Z</code> at the end.</p>
| 0 | 2016-07-01T12:32:07Z | 38,145,735 | <p>Just add <code>Z</code></p>
<pre><code>datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S:%f')[:-4] + 'Z'
</code></pre>
| 0 | 2016-07-01T12:41:37Z | [
"python",
"python-2.7",
"datetime",
"utc"
] |
Getting text of node and children excluding one | 38,145,614 | <p>What I want to do is taking all text from a node and it's children but excluding one of the child.</p>
<p>So here's the HTML with it:</p>
<pre><code><blocquote>
<div class='quote'>
I don't want to get that.
</div>
Some text I want to <i> get </i>.
<div>
I want to... | 0 | 2016-07-01T12:36:28Z | 38,145,752 | <p>You could exclude that parent with e.g. <code>//blocquote//text()[not(parent::div[@class = 'quote'])]</code>.</p>
| 1 | 2016-07-01T12:42:06Z | [
"python",
"xpath"
] |
Getting text of node and children excluding one | 38,145,614 | <p>What I want to do is taking all text from a node and it's children but excluding one of the child.</p>
<p>So here's the HTML with it:</p>
<pre><code><blocquote>
<div class='quote'>
I don't want to get that.
</div>
Some text I want to <i> get </i>.
<div>
I want to... | 0 | 2016-07-01T12:36:28Z | 38,145,815 | <p>Use descendant-or-self axis:</p>
<pre><code>//blocquote/descendant-or-self::*[not(@class='quote')]/text()
</code></pre>
| 0 | 2016-07-01T12:45:40Z | [
"python",
"xpath"
] |
Complicated data structure union | 38,145,633 | <p>I have two lists of the following form: </p>
<pre><code>lst1 = [{u'Hours': [{u'HourOfDay': 15, u'TotalVisits': 1, u'TotalTimeSpent': 7223.0}, {u'HourOfDay': 11, u'TotalVisits': 1, u'TotalTimeSpent': 4503.0}, {u'HourOfDay': 18, u'TotalVisits': 1, u'TotalTimeSpent': 6273.0}, {u'HourOfDay': 12, u'TotalVisits': 3, u'T... | -1 | 2016-07-01T12:37:29Z | 38,146,656 | <p>I don't have enough rep to comment, so I'll write my concerns here.</p>
<p>First off, I'm guessing that the missing indent level on the second for loop is a typo and that it doesn't appear in your original code.</p>
<p>Secondly, I don't understand the meaning of your else statement.</p>
<p>What you are, essential... | 0 | 2016-07-01T13:25:29Z | [
"python",
"python-2.7"
] |
Filtering similar images in 2 numpy.ndarray in effective way | 38,145,643 | <p>Currently I play with some ML algorithms and I have 2 sets of images (train and validation sets) which I store in in np.ndarray. Images are greyscale, size is 28x28. I have about 200000 of train images and smth like 20000 of validation images. I know that my dataset is not ideal and:
- In each dataset I could have s... | 1 | 2016-07-01T12:37:36Z | 38,154,455 | <p>You can find the sum of the distance in RGB space between the two images by doing something like</p>
<pre><code>(((a - b)**2).sum(axis=2)**0.5).sum()
</code></pre>
<p>However you have to be very careful as you will get a big difference between two images that are actually very similar (i.e. where </p>
<pre><code>... | 1 | 2016-07-01T22:10:56Z | [
"python",
"image",
"numpy",
"machine-learning"
] |
How to concat Pandas dataframe columns | 38,145,645 | <p>How to concat columns of different data types in a Pandas dataframe such that if column <code>number</code> is concatenated with column <code>operator</code>, and I do a <code>groupby('user').sum()</code>, I can have the appropriate aggregation: </p>
<pre><code> number operator user
id
1 ... | 2 | 2016-07-01T12:37:41Z | 38,145,729 | <p>Use <code>loc</code> with boolean mask to make the 'number' values negative:</p>
<pre><code>In [34]:
df.loc[df['operator'] == '-', 'number'] = -df['number']
df
Out[34]:
number operator user
id
1 -193 - A
2 332 + B
3 4434 + A
4 -432 - ... | 2 | 2016-07-01T12:41:22Z | [
"python",
"pandas"
] |
Count time to some event using pandas | 38,145,654 | <p>I have data</p>
<pre><code>date url
2016-07-01 11:43:09 https://www.youtube.com/api/stats/ads?ver=2&ns=1&event=2&device=5&content_v=cmqQy3v8KvM&el=detailpage&ei=bld2V--RJoWHW4OQlbAN&devicever=11.23&format=2_2_1&break_type=1&conn=3&cpn=ifKDc6HI6TsnATCH&lact=8504&m_... | -1 | 2016-07-01T12:38:07Z | 38,145,946 | <p>You can first filter <code>df</code> and then get difference by first and last value selected by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iat.html" rel="nofollow"><code>iat</code></a>:</p>
<pre><code>L = ['AAU2kYTHEDgoKDTG', 'cmqQy3v8KvM']
for id in L:
df1 = df.ix[df.url.str.... | 1 | 2016-07-01T12:52:17Z | [
"python",
"pandas"
] |
appending values to a new dataframe and making one of the datatypes the index | 38,145,788 | <p>I have a new Data-frame <code>df</code>. Which was created using:</p>
<pre><code>df= pd.DataFrame()
</code></pre>
<p>I have a date value called <code>'day'</code> which is in format dd-mm-yyyy and a cost value called <code>'cost</code>'.</p>
<p>Could someone let me know how I can append the date and cost values ... | -1 | 2016-07-01T12:44:12Z | 38,146,747 | <p>Try this:</p>
<pre><code>dfapp = [day,cost]
df.append(dfapp)
</code></pre>
| 0 | 2016-07-01T13:29:33Z | [
"python",
"pandas"
] |
appending values to a new dataframe and making one of the datatypes the index | 38,145,788 | <p>I have a new Data-frame <code>df</code>. Which was created using:</p>
<pre><code>df= pd.DataFrame()
</code></pre>
<p>I have a date value called <code>'day'</code> which is in format dd-mm-yyyy and a cost value called <code>'cost</code>'.</p>
<p>Could someone let me know how I can append the date and cost values ... | -1 | 2016-07-01T12:44:12Z | 38,147,123 | <p>There are a few things here. First, making a column the index goes like this, though you can also do it when you load the dataframe from a file (see below):</p>
<pre><code>df.set_index('date', inplace=True)
</code></pre>
<p>To add new rows, you should write them out to file first. Pandas isn't great at adding ro... | 0 | 2016-07-01T13:47:39Z | [
"python",
"pandas"
] |
Parsing of EOF, Python 3 | 38,145,835 | <p>Sorry for obviously silly question, I am just far not a pro. I was curious how it happens, that for the code in Python 3.5 just below I receive IndexError, </p>
<pre><code>with open('graph.txt') as f:
text = f.read()
for i in range(len(Text)):
if text[i+1] == '>':
*do something*
</code></pre>
<b... | -1 | 2016-07-01T12:46:30Z | 38,145,864 | <p>Because indexes in <code>Text</code> run from <code>0</code> to <code>len(Text)-1</code>. Similarly, the output of <code>range()</code> runs from <code>0</code> to the parameter minus one, here <code>len(Text)-1</code>. Therefore, the very last time through the loop, the <code>if</code> statement indexes <code>Tex... | 2 | 2016-07-01T12:48:23Z | [
"python",
"strip"
] |
Parsing of EOF, Python 3 | 38,145,835 | <p>Sorry for obviously silly question, I am just far not a pro. I was curious how it happens, that for the code in Python 3.5 just below I receive IndexError, </p>
<pre><code>with open('graph.txt') as f:
text = f.read()
for i in range(len(Text)):
if text[i+1] == '>':
*do something*
</code></pre>
<b... | -1 | 2016-07-01T12:46:30Z | 38,145,914 | <p>You could maybe do something along the same lines of this <a href="http://stackoverflow.com/questions/6213063/python-read-next">post</a>. </p>
<p>Also I noticed when you opened the file you did not tell it how to open <code>open('graph.txt', 'r')</code>. Maybe that is part of the issue as well</p>
<p>Also you are ... | 0 | 2016-07-01T12:50:55Z | [
"python",
"strip"
] |
Parsing of EOF, Python 3 | 38,145,835 | <p>Sorry for obviously silly question, I am just far not a pro. I was curious how it happens, that for the code in Python 3.5 just below I receive IndexError, </p>
<pre><code>with open('graph.txt') as f:
text = f.read()
for i in range(len(Text)):
if text[i+1] == '>':
*do something*
</code></pre>
<b... | -1 | 2016-07-01T12:46:30Z | 38,148,672 | <p>Be aware, a more Pythonic way of doing this, that makes it impossible to make these sort of 'off by one' string indexing errors, is:</p>
<pre><code>for char in Text:
if char == '>':
# do something
</code></pre>
<p>If your 'do something' needs access to 'i', the index where 'char' occurs, then this be... | 0 | 2016-07-01T15:06:38Z | [
"python",
"strip"
] |
Regex and beautifulsoup returning "'NoneType' object is not callable" error | 38,145,894 | <p>I am trying to implement the regex query at <a href="http://regexr.com/3dnut" rel="nofollow">http://regexr.com/3dnut</a>.</p>
<p>This is my code so far:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib
r = urllib.urlopen('http://www.indeed.com/resumes?q=banking&l=london&co=GB&start=0').read()... | 0 | 2016-07-01T12:49:58Z | 38,146,414 | <p>There is no <code>search()</code> method in <code>BeautifulSoup</code>. The reason it throws this particular error is that the dot-notation has a special meaning - it is a shortcut to <code>find()</code>. <code>soup.search</code> is basically transformed into <code>soup.find("search")</code> which would try to find ... | 1 | 2016-07-01T13:14:32Z | [
"python",
"regex",
"beautifulsoup"
] |
transform .EDF file on Python in .txt | 38,145,941 | <p>I need to read data from .EDF using Python file and save it in .txt format.
I found a code that allows you to do this, but while it is running, an error occurs. I just started learning Python.
I ask you to help me!
Link to .EDF file conversion code to a .txt I'm trying to use:
<a href="http://csl-sessions.blogspot.r... | 0 | 2016-07-01T12:51:53Z | 38,146,405 | <p>Use <strong><a href="https://github.com/holgern/pyedflib" rel="nofollow">pyedflib</a></strong> - a python library to parse <code>.edf</code> files. (Iv'e ran <a href="https://github.com/holgern/pyedflib/blob/master/demo/readEDFFile.py" rel="nofollow">one of their examples</a> on your file)</p>
<pre><code>from __fut... | 1 | 2016-07-01T13:14:15Z | [
"python"
] |
Incrementing when not in for loop - Python | 38,145,967 | <p><strong>Problem</strong></p>
<p>I'm trying to write a script that records a number of screenshots, but I'm having a problem naming my file. </p>
<hr>
<p><strong>Try</strong></p>
<p>I'm trying to initial my <code>i=0</code> and increment it as I go. </p>
<p>I kept getting 1 on all of them. </p>
<p>My image gett... | 0 | 2016-07-01T12:53:21Z | 38,145,999 | <p>You are not setting back to <code>i</code>. Hence <code>i</code> is always 0.<br>
You need to increment <code>i</code> after saving screenshot.</p>
<pre><code>driver.save_screenshot(today+'/admin/'+str(i+1)+'.png')
i += 1
</code></pre>
<p>Not sure how is your code desgined so I'm giving really basic starting point... | 2 | 2016-07-01T12:55:00Z | [
"python"
] |
Incrementing when not in for loop - Python | 38,145,967 | <p><strong>Problem</strong></p>
<p>I'm trying to write a script that records a number of screenshots, but I'm having a problem naming my file. </p>
<hr>
<p><strong>Try</strong></p>
<p>I'm trying to initial my <code>i=0</code> and increment it as I go. </p>
<p>I kept getting 1 on all of them. </p>
<p>My image gett... | 0 | 2016-07-01T12:53:21Z | 38,146,054 | <p>you need to increment i value for every iteration. like <code>i=i+1</code> </p>
<p>if not i value will be same for every iteration. i.e 1.
thats why every time you are getting 1.png</p>
| 0 | 2016-07-01T12:57:18Z | [
"python"
] |
How to plot age distribution with pandas | 38,146,009 | <p>I have Data Frame, which contains 2 columns: age and gender.</p>
<pre><code>sex,age
1,30
2,29
1,34
1,27
2,28
2,28
1,40
1,30
1,27
2,31
1,37
1,31
2,28
2,30
2,27
2,27
2,29
2,32
1,28
1,27
1,28
1,28
1,29
1,33
1,32
1,30
</code></pre>
<p>How can I plot age distribution for each gender?</p>
| 1 | 2016-07-01T12:55:21Z | 38,147,979 | <p><code>groupby</code> then <code>plot</code> with <code>kind='kde'</code></p>
<pre><code>df1.groupby('sex').age.plot(kind='kde')
</code></pre>
<p><a href="http://i.stack.imgur.com/GBaxm.png" rel="nofollow"><img src="http://i.stack.imgur.com/GBaxm.png" alt="enter image description here"></a></p>
<p>Per @EdChum</p>
... | 2 | 2016-07-01T14:29:55Z | [
"python",
"pandas"
] |
How do I pipe to a file or shell program via Pythons subprocess? | 38,146,282 | <p>I am working with some fairly large gzipped text files that I have to unzip, edit and re-zip. I use Pythons gzip module for unzipping and zipping, but I have found that my current implementation is far from optimal:</p>
<pre><code>input_file = gzip.open(input_file_name, 'rb')
output_file = gzip.open(output_file_na... | 0 | 2016-07-01T13:08:44Z | 38,146,835 | <p>You meant <code>output_file = gzip_process.stdin</code>. After that you can use <code>output_file</code> as you've used <code>gzip.open()</code> object previously (no-seeking).</p>
<p>If the result file is empty then check that you call <code>output_file.close()</code> and <code>gzip_process.wait()</code> at the en... | 0 | 2016-07-01T13:33:57Z | [
"python",
"bash",
"shell",
"subprocess",
"popen"
] |
How do I pipe to a file or shell program via Pythons subprocess? | 38,146,282 | <p>I am working with some fairly large gzipped text files that I have to unzip, edit and re-zip. I use Pythons gzip module for unzipping and zipping, but I have found that my current implementation is far from optimal:</p>
<pre><code>input_file = gzip.open(input_file_name, 'rb')
output_file = gzip.open(output_file_na... | 0 | 2016-07-01T13:08:44Z | 38,162,987 | <p>Here is a working example of how this can be done:</p>
<pre><code>#!/usr/bin/env python
from subprocess import Popen, PIPE
output = ['this', 'is', 'a', 'test']
output_file_name = 'pipe_out_test.txt.gz'
gzip_output_file = open(output_file_name, 'wb', 0)
output_stream = Popen(["gzip"], stdin=PIPE, stdout=gzip_ou... | 0 | 2016-07-02T17:55:27Z | [
"python",
"bash",
"shell",
"subprocess",
"popen"
] |
Create a dictionary from a single line in a file | 38,146,343 | <p>I am currently writing a piece of code that takes a file with a list on one line, and a dictionary on another (See below). Is there a way to take a list or dictionary that was saved into a file in string form, and recreate that list/dict? I've tried other posts, but I don't think I'm searching for the right thing, a... | 0 | 2016-07-01T13:11:25Z | 38,146,383 | <p>To safely evaluate a string containing a Python literal you can use <a href="https://docs.python.org/3.5/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval()</code></a>:</p>
<pre><code>>>> from ast import literal_eval
>>> literal_eval("[1,2,3,4,5,6,7,8]")
[1, 2, 3, 4, 5, 6, 7... | 2 | 2016-07-01T13:13:22Z | [
"python",
"list",
"file",
"dictionary"
] |
Python: Problems appending items to a list over loop iteration | 38,146,353 | <p>I'm new to python so I'm a bit confusing how to deal with that.</p>
<p>I'm trying to append items to a list:</p>
<pre><code>li = []
for path, subdirs, files in os.walk('/data/disk4/a0050969/sftpcollector/Utils/'):
for filename in files:
if filename.endswith(('.log')):
f = os.path.join(path, fil... | 0 | 2016-07-01T13:11:41Z | 38,146,504 | <p>Python is very serious about indentation, hence in the first example of your code, since the </p>
<pre><code>f = os.path.join(path, filename)
li.append(f)
</code></pre>
<p>is in line with the <code>if</code> condition, the block of code run only once and not in the loop. If its in the loop, as shown in yo... | 0 | 2016-07-01T13:18:44Z | [
"python",
"list"
] |
Python: Problems appending items to a list over loop iteration | 38,146,353 | <p>I'm new to python so I'm a bit confusing how to deal with that.</p>
<p>I'm trying to append items to a list:</p>
<pre><code>li = []
for path, subdirs, files in os.walk('/data/disk4/a0050969/sftpcollector/Utils/'):
for filename in files:
if filename.endswith(('.log')):
f = os.path.join(path, fil... | 0 | 2016-07-01T13:11:41Z | 38,146,512 | <p>Maybe it is just a formatting error when you posted the code but the below lines are not indented properly under the if statement. This may be your issue.</p>
<pre><code>f = os.path.join(path, filename)
li.append(f)
</code></pre>
| 0 | 2016-07-01T13:19:00Z | [
"python",
"list"
] |
Python: Problems appending items to a list over loop iteration | 38,146,353 | <p>I'm new to python so I'm a bit confusing how to deal with that.</p>
<p>I'm trying to append items to a list:</p>
<pre><code>li = []
for path, subdirs, files in os.walk('/data/disk4/a0050969/sftpcollector/Utils/'):
for filename in files:
if filename.endswith(('.log')):
f = os.path.join(path, fil... | 0 | 2016-07-01T13:11:41Z | 38,146,542 | <p>The indentation in your first snippet is definitely wrong. After the <code>if</code>, at least on line needs be indented.</p>
<p>Could it be that you are mixing tabs and spaces in your code? This sometimes makes for very hard to detect bugs. I recommend configuring your editor to automatically insert spaces when yo... | 0 | 2016-07-01T13:20:24Z | [
"python",
"list"
] |
Convert unicode to string | 38,146,375 | <p>I'm building a program which takes information from a Json file and then prints some of that data. However some of the data maybe using unicode characters. How can I convert this unicode string to just a plain string ignoring the unicode. </p>
<p>For example I could get a tweet:</p>
<pre><code>@Hellblazer2014 Port... | -1 | 2016-07-01T13:13:03Z | 38,348,214 | <p>You can use:
string.decode('unicode_escape').encode('ascii','ignore')
to ignore the Unicode character in the string.</p>
| 0 | 2016-07-13T09:51:20Z | [
"python",
"json",
"unicode",
"python-2.x"
] |
Why not works in a | 38,146,433 | <p>I am going to use the . </p>
<p>Here is my code:</p>
<pre><code>FirstList = ["1", "2", "3", "4"]
SecondList = ["a", "b", "c", "d", "e", "f"]
ThirdList = ["A" , "B" , "C"]
pass
</code></pre>
| 0 | 2016-07-01T13:15:23Z | 38,153,547 | <p>If I understand what you want, you just want the cartestian product of your lists. You can use <code>itertools</code> for this instead of a nested forloop like you have, no need to re-invent the wheel since itertools already has this built-in and it's by far cleaner.</p>
<p>Here you go: (Not tested)</p>
<pre><code... | 3 | 2016-07-01T20:35:47Z | [
"python",
"tkinter"
] |
Where does "ainv" come from? | 38,146,448 | <p>Python's <code>random</code> module has the following method in it:</p>
<pre><code>def gammavariate(self, alpha, beta):
"""Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha ... | 1 | 2016-07-01T13:16:05Z | 38,149,192 | <p>Not sure why the IDE thinks it's a typo, but don't you just need to declare the <code>ainv</code> variable? </p>
<pre><code>double ainv = Math.sqrt(2.0 * alpha - 1.0) ;
</code></pre>
<p>As for it's purpose, it looks to be just an intermediate calculation that's used in two other places.</p>
| 0 | 2016-07-01T15:35:38Z | [
"python",
"python-3.x",
"variables",
"random",
"naming-conventions"
] |
Regular expression to separate out the last occurring number using Python | 38,146,531 | <p>I have a regular expression which separates out the number from the given string.</p>
<pre><code>username = "testuser1"
xp = r'^\D+'
ma = re.match(xp, username)
user_prefix = ma.group(0)
print user_prefix
</code></pre>
<p>output is</p>
<pre><code>testuser
</code></pre>
<p>But if the username is something like be... | 9 | 2016-07-01T13:19:52Z | 38,146,627 | <p>I suggest starting from the end, deleting each char and stopping at the first non-number.</p>
| -2 | 2016-07-01T13:24:09Z | [
"python",
"regex",
"python-2.7"
] |
Regular expression to separate out the last occurring number using Python | 38,146,531 | <p>I have a regular expression which separates out the number from the given string.</p>
<pre><code>username = "testuser1"
xp = r'^\D+'
ma = re.match(xp, username)
user_prefix = ma.group(0)
print user_prefix
</code></pre>
<p>output is</p>
<pre><code>testuser
</code></pre>
<p>But if the username is something like be... | 9 | 2016-07-01T13:19:52Z | 38,146,670 | <p>You can use <code>re.sub</code> and look behind syntax:</p>
<pre><code>re.sub(r'(?<=\D)\d+$', '', username)
</code></pre>
<p>A shorter version:</p>
<pre><code>re.sub(r'\d+$', '', username)
</code></pre>
<p>The <code>sub</code> function is more suited for this case.</p>
<p>Test cases:</p>
<pre><code>re.sub(r... | 6 | 2016-07-01T13:25:55Z | [
"python",
"regex",
"python-2.7"
] |
Regular expression to separate out the last occurring number using Python | 38,146,531 | <p>I have a regular expression which separates out the number from the given string.</p>
<pre><code>username = "testuser1"
xp = r'^\D+'
ma = re.match(xp, username)
user_prefix = ma.group(0)
print user_prefix
</code></pre>
<p>output is</p>
<pre><code>testuser
</code></pre>
<p>But if the username is something like be... | 9 | 2016-07-01T13:19:52Z | 38,146,749 | <p>Here! </p>
<pre><code>regex_ = '\w+-?(?:\d+)?'
</code></pre>
| 1 | 2016-07-01T13:29:40Z | [
"python",
"regex",
"python-2.7"
] |
Regular expression to separate out the last occurring number using Python | 38,146,531 | <p>I have a regular expression which separates out the number from the given string.</p>
<pre><code>username = "testuser1"
xp = r'^\D+'
ma = re.match(xp, username)
user_prefix = ma.group(0)
print user_prefix
</code></pre>
<p>output is</p>
<pre><code>testuser
</code></pre>
<p>But if the username is something like be... | 9 | 2016-07-01T13:19:52Z | 38,146,910 | <p>A solution using re.match:</p>
<pre><code>import re
username = "testuser1"
xp = r'^(.+?)\d+$'
ma = re.match(xp, username)
user_prefix = ma.groups()[0]
user_prefix
# 'testuser'
# you can also capture the last number
xp = r'^(.+?)(\d+)$'
ma = re.match(xp, username)
user_prefix, user_number = ma.groups()
user_prefix,... | 5 | 2016-07-01T13:38:02Z | [
"python",
"regex",
"python-2.7"
] |
Regular expression to separate out the last occurring number using Python | 38,146,531 | <p>I have a regular expression which separates out the number from the given string.</p>
<pre><code>username = "testuser1"
xp = r'^\D+'
ma = re.match(xp, username)
user_prefix = ma.group(0)
print user_prefix
</code></pre>
<p>output is</p>
<pre><code>testuser
</code></pre>
<p>But if the username is something like be... | 9 | 2016-07-01T13:19:52Z | 38,147,526 | <p>Less engine involving regex (considering <code>-</code> as the only token)</p>
<pre><code>^([^\s-]+-|\D+)
</code></pre>
| 1 | 2016-07-01T14:06:58Z | [
"python",
"regex",
"python-2.7"
] |
python read date and time from csv | 38,146,590 | <p>my data looks like that:</p>
<pre><code>GIdx,Date,num,Time
1,11/28/2012,20,10:05:50
1,11/28/2012,20,10:05:50
2,11/28/2012,20,10:09:24
2,11/28/2012,20,10:09:24
2,11/28/2012,20,10:09:25
2,11/28/2012,20,10:09:25
2,11/28/2012,20,10:09:26
3,11/28/2012,20,10:09:34
3,11/28/2012,20,10:09:34
</code></pre>
<p>i try to read ... | 0 | 2016-07-01T13:22:49Z | 38,147,392 | <p>You can add to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> parameter <code>parse_dates</code> with columns where are <code>dates</code> and <code>times</code>:</p>
<pre><code>import pandas as pd
import io
temp=u"""GIdx,Date,num,Time
... | 0 | 2016-07-01T14:01:07Z | [
"python",
"datetime",
"pandas",
"series"
] |
Where can i cache pandas dataframe in tornado requesthandler | 38,146,607 | <p>I want to cache a pandas dataframe into tornado requesthandler. So i don't want to repeat the pd.read_csv() for every hit to that particular url.</p>
| 0 | 2016-07-01T13:23:27Z | 38,153,190 | <p>Since a new <code>RequestHandler</code> is instantiated on each invocation, any data that is supposed to persist between calls needs to be stored somewhere, and CSV is as good a form as any. Alternatively, you can use any of a number of Python <a href="https://www.fullstackpython.com/caching.html" rel="nofollow">cac... | 1 | 2016-07-01T20:04:56Z | [
"python",
"caching",
"tornado",
"requesthandler"
] |
Where can i cache pandas dataframe in tornado requesthandler | 38,146,607 | <p>I want to cache a pandas dataframe into tornado requesthandler. So i don't want to repeat the pd.read_csv() for every hit to that particular url.</p>
| 0 | 2016-07-01T13:23:27Z | 38,439,059 | <p>Depends on how and where you want to be able to access this cache in the future, and how you want to handle invalidation. If the CSV files don't change then this could be as simple as @functools.lru_cache or a global dict. If you need one cache shared across multiple processes then you could use something like memca... | 0 | 2016-07-18T14:18:08Z | [
"python",
"caching",
"tornado",
"requesthandler"
] |
sslobj.do_handshake failure and "error: [Errno 0] Error" | 38,146,613 | <p>I have a Django App running on Ubuntu 14.04</p>
<p>When I use the requests module or the smtp module and try to establish encrypted connections I often (not always, mostly every other time) get this error:</p>
<p>error: [Errno 0] Error</p>
<p>the long error (here from sending email):</p>
<pre><code>mod_wsgi (pid... | 1 | 2016-07-01T13:23:40Z | 38,224,367 | <p>After a long research I found out its a bug in cryptography module.</p>
<p>See:
<a href="https://github.com/pyca/cryptography/issues/2299" rel="nofollow">https://github.com/pyca/cryptography/issues/2299</a></p>
<p>workaround:
place
WSGIApplicationGroup %{GLOBAL} </p>
<p>in apache virtualhost configuration
e.g.</... | 1 | 2016-07-06T12:45:18Z | [
"python",
"django",
"smtp",
"ubuntu-14.04",
"pyopenssl"
] |
Recieving Blank SMS SIM800 using AT Commands and Python on Raspberry Pi 2 | 38,146,737 | <p>I created this python script on rpi2, the message goes through, but it is a blank message. Is it a encoding issue? </p>
<pre><code>import serial
import time
from sys import version_info
from curses import ascii
phone = serial.Serial("/dev/ttyAMA0", 115200, timeout=0.5)
def send_text(number,message):
phone.w... | 1 | 2016-07-01T13:29:01Z | 38,150,794 | <p>There was an issue with the <strong>text mode</strong> parameters. The AT command below fixed it - </p>
<pre><code>AT+CSMP=17,167,0,0
--info about it
AT+CSMP=<fo>,<vp>,<pid>,<dcs>
<fo>=17 Sets reply pat, user data header, status report request, validity period format, reject duplicate... | 1 | 2016-07-01T17:14:43Z | [
"python",
"raspberry-pi",
"gsm",
"at-command"
] |
TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly | 38,146,756 | <p>I would like to save a pandas.DataFrame object into a .csv file (using DataFrame.to_csv()). To make it simple, here is the situation; my project 'Algos' contains the folder 'Plip' with a .txt file called 'plop.txt':</p>
<pre><code>1,2
3,4
5,6
</code></pre>
<p>My script is here:</p>
<pre><code>import numpy as n... | 0 | 2016-07-01T13:29:57Z | 38,147,379 | <p>Seems like you reassigned <code>fichier</code> to a file object on L7, use a new variable instead!</p>
| 0 | 2016-07-01T14:00:41Z | [
"python",
"string",
"python-3.x",
"folder"
] |
JSON formatting by appending dict values to list | 38,146,777 | <p>I have a JSON object which is like this:</p>
<pre><code>{ "produktNr:"1234",
"artNr_01":"12",
"artNr_02":"23",
"artNr_03":"",
"artNr_04":"14",
"name_01":"abc",
"name_02":"der",
"test":"junk"
}
</code></pre>
<p>I would like to convert this into a dictionary like this:</p>
<pre><code>{ "produktNr:"123... | 0 | 2016-07-01T13:31:12Z | 38,147,294 | <p>You can recreate a new dictionary that will group values of keys with <code>'_'</code> in the keys in a list while the other keys and values are kept intact. This should do:</p>
<pre><code>d = { "produktNr":"1234", "artNr_01":"12", "artNr_02":"23","artNr_03":"","artNr_04":"14","name_01":"abc","name_02":"der","test"... | 0 | 2016-07-01T13:56:54Z | [
"python",
"json",
"dictionary"
] |
JSON formatting by appending dict values to list | 38,146,777 | <p>I have a JSON object which is like this:</p>
<pre><code>{ "produktNr:"1234",
"artNr_01":"12",
"artNr_02":"23",
"artNr_03":"",
"artNr_04":"14",
"name_01":"abc",
"name_02":"der",
"test":"junk"
}
</code></pre>
<p>I would like to convert this into a dictionary like this:</p>
<pre><code>{ "produktNr:"123... | 0 | 2016-07-01T13:31:12Z | 38,147,885 | <p>A slight modification of your code:</p>
<pre><code>tempDict = {}
for key,value in fmData.iteritems():
seqval_in_key = "no"
for seqval in seq:
if seqval in key:
seqval_in_key = "yes"
for seqval in seq:
if seqval in key:
if seqval in tempDict:
tempDi... | 0 | 2016-07-01T14:24:58Z | [
"python",
"json",
"dictionary"
] |
JSON formatting by appending dict values to list | 38,146,777 | <p>I have a JSON object which is like this:</p>
<pre><code>{ "produktNr:"1234",
"artNr_01":"12",
"artNr_02":"23",
"artNr_03":"",
"artNr_04":"14",
"name_01":"abc",
"name_02":"der",
"test":"junk"
}
</code></pre>
<p>I would like to convert this into a dictionary like this:</p>
<pre><code>{ "produktNr:"123... | 0 | 2016-07-01T13:31:12Z | 38,148,728 | <p>You may use <code>OrderedDict</code> from the <code>collections</code> package:</p>
<pre><code>from collections import OrderedDict
import re
input_dict = { "produktNr":"1234",
"artNr_01":"12",
"artNr_02":"23",
"artNr_03":"",
"artNr_04":"14",
... | 1 | 2016-07-01T15:09:58Z | [
"python",
"json",
"dictionary"
] |
Arbitrary colorbar | 38,146,801 | <p>I have data that is in the range -70,0 that I display using imshow() and would like to use a non-linear colorbar to represent the data as I have paterns both in the -70,-60 range and -70,0 range.
I would like the easiest way to rescale/renormalize using an arbitrary function (see example) the colorbar so that all pa... | 1 | 2016-07-01T13:32:14Z | 38,148,334 | <p>This is what I managed to do:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import PowerNorm
sample_data=(np.ones((20,20))*np.linspace(0,1,20)**3)*70-70
plt.figure()
im = plt.imshow(sample_data+70, norm=PowerNorm(gamma=0.5))
cbar = plt.colorbar(orientation='horizontal')
cb... | 1 | 2016-07-01T14:48:29Z | [
"python",
"matplotlib",
"colorbar"
] |
Estimation of fundamental matrix or essential matrix from feature matching | 38,146,821 | <p>I am estimating the fundamental matrix and the essential matrix by using the inbuilt functions in opencv.I provide input points to the function by using ORB and brute force matcher.These are the problems that i am facing:</p>
<p>1.The essential matrix that i compute from in built function does not match with the on... | 1 | 2016-07-01T13:33:07Z | 38,615,979 | <ol>
<li>Both F and E are defined up to a scale factor. It may help to normalize the matrices, e. g. by dividing by the last element.</li>
<li>RANSAC is a randomized algorithm, so you will get a different result every time. You can test how much it varies by triangulating the points, or by computing the reprojection er... | 0 | 2016-07-27T14:33:01Z | [
"python",
"opencv",
"matrix",
"computer-vision"
] |
Parsing a wiki-styled web page, XPath error | 38,146,858 | <p>I am new to XPath, and I totally fail to parse a simple wiki-styled web page with lxml.</p>
<p>I have a following expression:</p>
<pre><code>"".join(tree.xpath('//*[@id="mw-content-text"]/div[1]/p//text()'))
</code></pre>
<p>It works fine, but I need to exclude children whose class is "reference" and get a lxml.e... | 1 | 2016-07-01T13:35:05Z | 38,174,356 | <p>Probably, the error occured because of <code>.text()</code> instead of <code>/text()</code>.</p>
<p>If you want include also text of <code>p</code> elements then you have to use the <code>descendant-or-self</code> <a href="http://www.w3schools.com/xsl/xpath_axes.asp" rel="nofollow">XPath axis</a>:</p>
<pre><code>/... | 1 | 2016-07-03T21:07:35Z | [
"python",
"xml",
"xpath",
"lxml",
"wiki"
] |
Inverse filtering using Python | 38,146,985 | <p>Given an impulse response <code>h</code> and output <code>y</code> (both one-dimensional arrays), I'm trying to find a way to compute the inverse filter <code>x</code> such that <code>h * x = y</code>, where <code>*</code> denotes the convolution product.</p>
<p>For example, suppose that the impulse response <code>... | 4 | 2016-07-01T13:40:58Z | 38,149,245 | <p>This is called deconvolution: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.deconvolve.html" rel="nofollow">scipy.signal.deconvolve</a> will do this for you. Example where you know the original input signal <code>x</code>:</p>
<pre><code>import numpy as np
import scipy.signal as signal
... | 4 | 2016-07-01T15:37:59Z | [
"python",
"numpy",
"scipy",
"signal-processing",
"sympy"
] |
Action with pandas SettingWithCopyWarning | 38,147,027 | <p>I try to <code>delete</code> some column and convert some value in column with</p>
<pre><code>df2.drop(df2.columns[[0, 1, 3]], axis=1, inplace=True)
df2['date'] = df2['date'].map(lambda x: str(x)[1:])
df2['date'] = df2['date'].str.replace(':', ' ', 1)
df2['date'] = pd.to_datetime(df2['date'])
</code></pre>
<p>and ... | 2 | 2016-07-01T13:43:01Z | 38,147,527 | <p>Your <code>df2</code> is a slice of another dataframe. You need to explicitly copy it with <code>df2 = df2.copy()</code> just prior to your attempt to <code>drop</code></p>
<p>Consider the following dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(20).reshape(4, 5), ... | 6 | 2016-07-01T14:07:02Z | [
"python",
"pandas",
"dataframe"
] |
How to send hard-coded events to piwik via python script | 38,147,064 | <p>I am working on using piwik as a tracker for vm usage. Thr plan is that every time a VM starts or shuts down, a custom request will be send to a piwik server and report a UUID and a few other variables.
I downloaded the <a href="https://github.com/piwik/piwik-python-api" rel="nofollow">https://github.com/piwik/piwik... | 0 | 2016-07-01T13:44:42Z | 38,190,505 | <p>This piwik library is intended for a python web server such as Django. Unless you're planning on running a web server in your VMs, it will be of no use. That said, running a web server to send tracks to piwik seems to be overdoing it.</p>
<p>Piwik is simply calling a URL when it sends data to the server. It doesn't... | 1 | 2016-07-04T18:30:40Z | [
"python",
"piwik"
] |
web2py date & time picker issue | 38,147,120 | <p>I am trying to get the AJAX / JQUERY UI element in Web2Py for the date time picker to work for my forms from within a smart grid table. It doesn't seem to function as expected in the documentation. I just get a text entry field that doesn't display the picker at all and I can't figure out why.
The code I have crea... | 0 | 2016-07-01T13:47:28Z | 38,250,666 | <p>I upgraded to the latest build 2.14.6 and it solved the problem. I did the upgrade because the CAS functionality was also broken in the version I was using. Hope this helps others out too.</p>
| 1 | 2016-07-07T16:23:35Z | [
"python",
"date",
"time",
"web2py"
] |
How to access the cURL executable with Python subprocess module | 38,147,124 | <p>I am trying to access the <code>curl</code> executable on my computer using a <code>subprocess</code> call, but when I do so, I get the following error:</p>
<p><code>WindowsError: [Error 2] The system cannot find the file specified</code></p>
<p>my code looks as follows</p>
<p><code>path = 'C:\\Users\\Username\\A... | 0 | 2016-07-01T13:47:49Z | 38,149,152 | <p>Take a step back and do some sanity checks. Here are some steps to try.</p>
<ul>
<li>Copy the path in your script, and paste it into the file explorer (remove the escape characters) and verify that the path is indeed correct.</li>
<li><p>Verify that you have proper permissions to the path<br>
<s>* Copy the executab... | 2 | 2016-07-01T15:33:39Z | [
"python",
"windows",
"curl"
] |
How to obtain correct error from SWIG with incorrect overloading of C++ virtual function in Python | 38,147,212 | <p>I am wrapping the following C++ code:</p>
<pre><code>// content of cpp.h
class A
{
public:
virtual int fnA() = 0;
virtual ~A() { }
};
class B
{
public:
int fnB(A &a)
{
return a.fnA();
}
};
</code></pre>
<p>by SWIG using the SWIG wrapper:</p>
<pre><code>// content of swigmodule.i
%module(direct... | 1 | 2016-07-01T13:52:55Z | 38,192,264 | <p>You can get some distance towards improving the error like you want using <code>%typemap(directorout)</code>, for example:</p>
<pre><code>// content of swigmodule.i
%module(directors="1") swigmodule
%feature("director");
%feature("director:except") {
if ($error != NULL) {
fprintf(stderr, "throw\n");
... | 1 | 2016-07-04T21:10:52Z | [
"python",
"c++",
"swig"
] |
How to obtain correct error from SWIG with incorrect overloading of C++ virtual function in Python | 38,147,212 | <p>I am wrapping the following C++ code:</p>
<pre><code>// content of cpp.h
class A
{
public:
virtual int fnA() = 0;
virtual ~A() { }
};
class B
{
public:
int fnB(A &a)
{
return a.fnA();
}
};
</code></pre>
<p>by SWIG using the SWIG wrapper:</p>
<pre><code>// content of swigmodule.i
%module(direct... | 1 | 2016-07-01T13:52:55Z | 38,265,700 | <p>A way to fix this for all return types is by hacking the SWIG generated wrapper file. I have done this by:</p>
<pre><code>cp swigmodule_wrap.cxx x
cp myRaise.h swigmodule_wrap.cxx
sed 's/Swig::DirectorTypeMismatchException::raise(/myRaise(__PRETTY_FUNCTION__,swig_get_self(),/' < x >> swigmodule_wrap.cxx
</... | 0 | 2016-07-08T11:38:39Z | [
"python",
"c++",
"swig"
] |
How to access parameters passed in the __init__ in property attribute? | 38,147,218 | <pre><code>class Data(object):
def __init__(self, info_dict):
self.name = info_dict["name"]
self.address = info_dict["address"]
self._url = None
@property
def url(self):
if 'my_url' in info_dict:
self._url = info_dict['my_url']
elif 'this_url' in info_dict:
self._url = info_dict['this... | 0 | 2016-07-01T13:53:09Z | 38,147,315 | <p>When I have two possible dictionary keys that might store a value I want, I always use a <code>try</code> <code>except</code> block.</p>
<pre><code>try:
self._url = info_dict['my_url']
except KeyError:
self._url = info_dict['this_url']
</code></pre>
| 0 | 2016-07-01T13:57:46Z | [
"python"
] |
How to access parameters passed in the __init__ in property attribute? | 38,147,218 | <pre><code>class Data(object):
def __init__(self, info_dict):
self.name = info_dict["name"]
self.address = info_dict["address"]
self._url = None
@property
def url(self):
if 'my_url' in info_dict:
self._url = info_dict['my_url']
elif 'this_url' in info_dict:
self._url = info_dict['this... | 0 | 2016-07-01T13:53:09Z | 38,147,387 | <p>In the context of <code>__init__</code>, <code>info_dict</code> is a local variable. Once <code>__init__</code> is done, the variable goes away. </p>
<p>The simplest solution is to simply not use the property.
Just move the logic into <code>__init__</code> and move on to more interesting problems.</p>
| 3 | 2016-07-01T14:01:05Z | [
"python"
] |
Can I DeserializeWithLengthPrefix a c# class into a Python class? | 38,147,223 | <p>I have a lot of data Serialized with ProtoBuf in c#.</p>
<p>A colleague would like read these files with Python.</p>
<p>Can this be achieved as Python classes not same as c#.</p>
<p>Here is the c# class:</p>
<pre><code> [ProtoContract]
public class TickRecord
{
[ProtoMember(1, DataFormat = Data... | 1 | 2016-07-01T13:53:19Z | 38,147,333 | <p>That looks like <code>protobuf-net</code>; fortunately, the library includes a tool to spit out the .proto schema for what it thinks of your model:</p>
<pre><code>var schema = Serializer.GetProto<TickRecord>();
</code></pre>
<p>which comes out as:</p>
<pre><code>message TickRecord {
required bcl.DateTime... | 0 | 2016-07-01T13:58:40Z | [
"c#",
"python",
"protocol-buffers"
] |
How to work with surrogate pairs in Python? | 38,147,259 | <p>This is a follow-up to <a href="http://stackoverflow.com/questions/38106422/converting-to-emoji">Converting to Emoji</a>. In that question, the OP had a <code>json.dumps()</code>-encoded file with an emoji represented as a surrogate pair - <code>\ud83d\ude4f</code>. S/he was having problems reading the file and tran... | 5 | 2016-07-01T13:55:31Z | 38,147,966 | <p>You've mixed a literal string <code>\ud83d</code> in a json file on disk (six characters: <code>\ u d 8 3 d</code>) and a <em>single</em> character <code>u'\ud83d'</code> (specified using a string literal in Python source code) in memory. It is the difference between <code>len(r'\ud83d') == 6</code> and <code>len('\... | 10 | 2016-07-01T14:28:45Z | [
"python",
"python-3.x",
"unicode",
"surrogate-pairs"
] |
How do I make my program move files without the .py file being in the source location | 38,147,329 | <p>I wrote this program to move videos from my download folder to different destination folders.</p>
<pre><code>import os
import shutil
import sys
folder = []
highlight = ['highlights','goals','skills']
comedy_word = ['comedy', 'acapella','seyilaw','basketmouth','basket mouth','bovi','gordons','buchi','rhythm unplugge... | 1 | 2016-07-01T13:58:34Z | 38,147,489 | <p>You call <code>shutil.move</code> specifying the reference point incorrectly. In your loop that gathers the files, you should use <code>os.path.join('C:\\Users\\Afro\\Downloads\\Video', i)</code> and put that in your list instead. Otherwise it's all relative paths, hence the <code>FileNotFound</code> error. </p>
<p... | 3 | 2016-07-01T14:05:12Z | [
"python",
"file",
"python-3.x"
] |
How to remove square bracket from pandas dataframe | 38,147,447 | <p>I came up with values in square bracket(more like a <code>list</code>) after applying <code>str.findall()</code> to column of a pandas dataframe. How can I remove the square bracket ?</p>
<pre><code>print df
id value
1 [63]
2 [65]
3 [64]
4 [53] ... | 4 | 2016-07-01T14:03:28Z | 38,147,471 | <p>If values in column <code>value</code> have type <code>list</code>, use:</p>
<pre><code>df['value'] = df['value'].str[0]
</code></pre>
<p>Or:</p>
<pre><code>df['value'] = df['value'].str.get(0)
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/text.html#splitting-and-replacing-strings" rel="n... | 5 | 2016-07-01T14:04:40Z | [
"python",
"string",
"pandas",
"dataframe"
] |
Going through a list and checking in Python | 38,147,573 | <p>I'm currently looking for an algorithm to be able to go through a list such as the following one: <code>[1,1,1,1,2,3,4,5,5,5,3,2]</code>
I want, in this example, to be able to select the first "1" as there's a duplicate next to it, and keep going through the list until finding the next number having a duplicate next... | 0 | 2016-07-01T14:09:49Z | 38,147,664 | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to find groups of repeating numbers, then find the difference between the first two of those:</p>
<pre><code>>>> import itertools
>>> lst = [1,1,1,1,2,3,4,5,5,... | 0 | 2016-07-01T14:14:04Z | [
"python",
"list",
"condition"
] |
Going through a list and checking in Python | 38,147,573 | <p>I'm currently looking for an algorithm to be able to go through a list such as the following one: <code>[1,1,1,1,2,3,4,5,5,5,3,2]</code>
I want, in this example, to be able to select the first "1" as there's a duplicate next to it, and keep going through the list until finding the next number having a duplicate next... | 0 | 2016-07-01T14:09:49Z | 38,147,772 | <p>You can use <code>enumerate</code> with a starting index of <code>1</code>. Duplicates are detected if the current value is equal to the value at the previous index:</p>
<pre><code>l = [1,1,1,1,2,3,4,5,5,5,3,2]
r = [v for i, v in enumerate(l, 1) if i < len(l) and v == l[i]]
result = r[-1] - r[0]
# 4
</code></pr... | 1 | 2016-07-01T14:19:32Z | [
"python",
"list",
"condition"
] |
Going through a list and checking in Python | 38,147,573 | <p>I'm currently looking for an algorithm to be able to go through a list such as the following one: <code>[1,1,1,1,2,3,4,5,5,5,3,2]</code>
I want, in this example, to be able to select the first "1" as there's a duplicate next to it, and keep going through the list until finding the next number having a duplicate next... | 0 | 2016-07-01T14:09:49Z | 38,147,807 | <p>Solution:</p>
<pre><code>def subDupeLimits( aList ):
dupList = []
prevX = None
for x in aList:
if x == prevX:
dupList.append(x) # track duplicates
prevX = x # update previous x
# return last duplicate minus first
return dupList[-1] - dupList[0]
# call it
y = subDupe... | 1 | 2016-07-01T14:21:36Z | [
"python",
"list",
"condition"
] |
Python 2 IndexError: list index out of range | 38,147,595 | <p>I'm trying to solve Project Euler Problem 15.</p>
<p>I've put some arrays in mainarray.</p>
<p>I get an IndexError: list index out of range on line 33 and don't know why. Can someone help me?</p>
<p>Thanks.</p>
<p>Here is my Code:</p>
<pre><code>def make_file(num_matrix):
file = open("euler15.csv", "w")
... | 0 | 2016-07-01T14:10:58Z | 38,148,235 | <p>To check, when error occures, you can add this code before <code>akt_feld</code> assignment:</p>
<pre><code>try:
_ = mainarray[summand_1][summand_2]
except IndexError:
print("something wrong with this indexes", summand_1, summand_2)
</code></pre>
<p>Or just call <code>mainarray[1][1]</code>. </p>
<pre><co... | 0 | 2016-07-01T14:43:27Z | [
"python"
] |
Python - Algorithm to generate all possible arrays of ones and zeros of a given length | 38,147,636 | <p>My goal is to come up with an array of all possible bit combinations of length n. For example, if n = 3, the target answer set should look like</p>
<pre><code>000,
001,
010,
100,
011,
101,
110,
111
</code></pre>
<p>I've found the <a href="http://stackoverflow.com/questions/4633584/algorithm-to-generate-all-possibl... | 2 | 2016-07-01T14:12:40Z | 38,147,703 | <pre><code>>>> import itertools
>>> result = ["".join(item) for item in itertools.product("01", repeat=3)]
>>> print result
['000', '001', '010', '011', '100', '101', '110', '111']
</code></pre>
| 4 | 2016-07-01T14:15:55Z | [
"python",
"c++",
"algorithm"
] |
Python - Algorithm to generate all possible arrays of ones and zeros of a given length | 38,147,636 | <p>My goal is to come up with an array of all possible bit combinations of length n. For example, if n = 3, the target answer set should look like</p>
<pre><code>000,
001,
010,
100,
011,
101,
110,
111
</code></pre>
<p>I've found the <a href="http://stackoverflow.com/questions/4633584/algorithm-to-generate-all-possibl... | 2 | 2016-07-01T14:12:40Z | 38,147,940 | <p>Without itertools: print the numbers from <code>0</code> to <code>2 ** n</code> in base 2 and pad them with zeros:</p>
<pre><code>for i in range(2 ** n):
print('{0:b}'.format(i).rjust(n, '0'))
</code></pre>
<p>Note that this leads to a much simpler solution in any language. All you need is a function to conver... | 2 | 2016-07-01T14:27:39Z | [
"python",
"c++",
"algorithm"
] |
Python - Algorithm to generate all possible arrays of ones and zeros of a given length | 38,147,636 | <p>My goal is to come up with an array of all possible bit combinations of length n. For example, if n = 3, the target answer set should look like</p>
<pre><code>000,
001,
010,
100,
011,
101,
110,
111
</code></pre>
<p>I've found the <a href="http://stackoverflow.com/questions/4633584/algorithm-to-generate-all-possibl... | 2 | 2016-07-01T14:12:40Z | 38,148,061 | <pre><code>import itertools
#Possible characters
n = [0, 1]
#Asking required length
l = int(input("length: "))
#Putting all possibilities in list
r = list(itertools.product(n, repeat=l))
print(r)
</code></pre>
<p>Python always has a few handy libraries or functions to make complex things easy, and to make long takin... | 1 | 2016-07-01T14:34:35Z | [
"python",
"c++",
"algorithm"
] |
Python Multiprocessing speed issue | 38,147,699 | <p>I have a nested <code>for</code> loop of the form</p>
<pre><code>while x<lat2[0]:
while y>lat3[1]:
if (is_inside_nepal([x,y])):
print("inside")
else:
print("not")
y = y - (1/150.0)
y = lat2[1]
x = x + (1/150.0)
#here lat2[0] represents a large number... | 0 | 2016-07-01T14:15:39Z | 38,148,224 | <p>You seem to be using a thread Queue (from Queue import Queue). This does not work as expected as Process uses fork() and it clones the entire Queue into each worker Process</p>
<p>Use:</p>
<p><code>from multiprocessing import Queue</code></p>
| 0 | 2016-07-01T14:42:42Z | [
"python",
"multithreading",
"performance",
"python-multiprocessing",
"cpu-speed"
] |
python variable m.start() from re.finditer does not get overwritten | 38,147,773 | <p>I am currently writing a small python program for manipulating text files. (I am a newb programmer)</p>
<p>First, I am using re.finditer to find a specific string in lines1. Then I write this into a file and close it.
Next I want to grab the first line and search for this in another text file. The first time using ... | 0 | 2016-07-01T14:19:34Z | 38,147,927 | <p>You've not declared\initialized <code>line</code> that you're using here :</p>
<pre><code>re.finditer(line,lines2)
</code></pre>
<p>So, change :</p>
<pre><code>linecache.getline('out.txt', n)
</code></pre>
<p>to </p>
<pre><code>line = linecache.getline('out.txt', n)
</code></pre>
| 0 | 2016-07-01T14:26:54Z | [
"python"
] |
Dask: very low CPU usage and multiple threads? is this expected? | 38,147,839 | <p>I am using <code>dask</code> as in <a href="http://stackoverflow.com/questions/37979167/how-to-parallelize-many-fuzzy-string-comparisons-using-apply-in-pandas">how to parallelize many (fuzzy) string comparisons using apply in Pandas?</a></p>
<p>Basically I do some computations (without writing anything to disk) tha... | 3 | 2016-07-01T14:22:44Z | 38,154,513 | <blockquote>
<p>Of course, I understand the specifics depends on what exactly I am doing, but maybe the patterns above can already tell that something is horribly wrong?</p>
</blockquote>
<p>This is pretty spot on. Identifying performance issues is tricky, especially when parallel computing comes into play. Here a... | 1 | 2016-07-01T22:18:44Z | [
"python",
"multithreading",
"pandas",
"dask",
"fuzzywuzzy"
] |
Where is the syntax error in my cmd Python? | 38,147,890 | <p>Since several hours i had some errors in my command:</p>
<pre><code> message = "test."+hostname+"."+service+" "current_state_id "%d\n" % int(time.time())
</code></pre>
<p>The error is: </p>
<blockquote>
<p>SyntaxError: invalid syntax</p>
</blockquote>
<p>The result will be
message = test.myhost.myservice 2 146... | -1 | 2016-07-01T14:25:14Z | 38,147,945 | <p>You have at least two; there is nothing between <code>current_state_id</code> and either the space before it or the string after it.</p>
<p>You appear to know about string substitution, as you are using it in that code; you should use it throughout, rather than using a combination of concatenation and substitution.... | 0 | 2016-07-01T14:27:48Z | [
"python"
] |
Where is the syntax error in my cmd Python? | 38,147,890 | <p>Since several hours i had some errors in my command:</p>
<pre><code> message = "test."+hostname+"."+service+" "current_state_id "%d\n" % int(time.time())
</code></pre>
<p>The error is: </p>
<blockquote>
<p>SyntaxError: invalid syntax</p>
</blockquote>
<p>The result will be
message = test.myhost.myservice 2 146... | -1 | 2016-07-01T14:25:14Z | 38,148,959 | <p>There are 2 mistakes:</p>
<p>1)You need a '+' between '" "' and 'current_state_id'. </p>
<p>2)You need a '+' between 'current_state_id' and '"%d\n"'.</p>
<p>This is the correct version:</p>
<blockquote>
<p>message = "test."+hostname+"."+service+" "+current_state_id+"%d\n" % int(time.time())</p>
</blockquote>
| 0 | 2016-07-01T15:22:48Z | [
"python"
] |
Python/Django - list index out of range for function | 38,147,898 | <p>I have a function that gets a users history and puts it in a breadcrumb, and im trying to make that breadcrumb look better by having a display. so my function should be able to return a nice readable url instead of /service/site/7 it will give "Site UK" or "Showroom - Italy" as the breadcrumb.</p>
<p>however as soo... | 3 | 2016-07-01T14:25:33Z | 38,148,661 | <p>you should use </p>
<pre><code>try:
...
expect IndexError:
# Handle exception
</code></pre>
<p>when <code>list_path</code> have nothing</p>
| -3 | 2016-07-01T15:05:51Z | [
"python",
"django"
] |
Python/Django - list index out of range for function | 38,147,898 | <p>I have a function that gets a users history and puts it in a breadcrumb, and im trying to make that breadcrumb look better by having a display. so my function should be able to return a nice readable url instead of /service/site/7 it will give "Site UK" or "Showroom - Italy" as the breadcrumb.</p>
<p>however as soo... | 3 | 2016-07-01T14:25:33Z | 38,148,817 | <pre><code>if list_path[0]:
if list_path[0] != "admin":
del list_path[0] # Here you delete the first element of the list.
# Thus `list_path` now equals `['showrooms']`.
# and `list_path[1]` doesn't exist anymore.
</code></pre>
| 0 | 2016-07-01T15:15:11Z | [
"python",
"django"
] |
Python/Django - list index out of range for function | 38,147,898 | <p>I have a function that gets a users history and puts it in a breadcrumb, and im trying to make that breadcrumb look better by having a display. so my function should be able to return a nice readable url instead of /service/site/7 it will give "Site UK" or "Showroom - Italy" as the breadcrumb.</p>
<p>however as soo... | 3 | 2016-07-01T14:25:33Z | 38,149,264 | <p>It seems, not always your urls are as you expect, which involve sometimes not having more than one item in your <code>list_path</code> and that could happen due to paths like <code>/majorsite</code> or <code>/admin</code>, etc... So It could be more accurate doing the replacement following a more safe solution: </p>... | 0 | 2016-07-01T15:39:06Z | [
"python",
"django"
] |
Mixing datetime.strptime() arguments | 38,147,923 | <p>It is quite a common mistake to mix up the <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime"><code>datetime.strptime()</code></a> format string and date string arguments using:</p>
<pre><code>datetime.strptime("%B %d, %Y", "January 8, 2014")
</code></pre>
<p>instead of the other ... | 8 | 2016-07-01T14:26:51Z | 38,215,307 | <p>I claim that this cannot be checked statically <em>in the general case</em>.</p>
<p>Consider the following snippet:</p>
<pre><code>d = datetime.strptime(read_date_from_network(), read_format_from_file())
</code></pre>
<p>This code may be completely valid, where both <code>read_date_from_network</code> and <code>r... | 17 | 2016-07-06T01:51:30Z | [
"python",
"datetime",
"pycharm",
"pylint",
"static-code-analysis"
] |
How to change a 'LinearSegmentedColormap' to a different distribution of color? | 38,147,997 | <p>I am trying to make a color map that 'favors' lower values, i.e. it takes longer to get out of the darker color to get to the light color. At the moment I am using this as the colormap:</p>
<pre><code>cmap = clr.LinearSegmentedColormap.from_list('custom blue', ['#ffff00','#002266'], N=256)
</code></pre>
<p>I am pl... | 2 | 2016-07-01T14:30:59Z | 38,158,047 | <p>When making colormaps with <code>LinearSegmentedColormap.from_list</code>, you can supply a list of tuples of the form (value, color) (as opposed to simply a list of colors) where the values correspond to the relative positions of colors. The values must range from <code>0</code> to <code>1</code> so you will have t... | 1 | 2016-07-02T08:18:17Z | [
"python",
"matplotlib"
] |
modifying sparse matrix using advanced indexing in python | 38,148,024 | <p>I'm trying to use advanced indexing to modify a big sparse matrix. Say you have the following code:</p>
<pre><code>import numpy as np
import scipy.sparse as sp
A = sp.lil_matrix((10, 10))
a = np.array([[1,2],[3,4]])
idx = [1,4]
A[idx, idx] += a
</code></pre>
<p>Why this code doesn't work? It gives me the error</... | 2 | 2016-07-01T14:32:27Z | 38,148,487 | <p>For <code>idx = [1,4]</code>, <code>A[idx, idx]</code> returns a sparse matrix of shape <code>(1,2)</code> with the elements <code>A[1,1]</code> and <code>A[4,4]</code>. However, <code>a</code> has shape <code>(2,2)</code>. Therefore, there is a mismatch in shape. If you want to assign <code>A[1,1]</code>, <code>A[1... | 2 | 2016-07-01T14:56:52Z | [
"python",
"numpy",
"scipy",
"matrix-indexing"
] |
Why is non-greedy Python Regex not non-greedy enough? | 38,148,043 | <p>I've implemented non-greedy regex on a group of string URLs, where I'm trying to clean them up so that they end after the .com (.co.uk etc). Some of them continued with <code>'</code> or <code>"</code> or <code><</code> after the desired cutoff, and so I used <code>x = re.findall('([A-Za-z0-9]+@\S+.co\S*?)[\'"&l... | 0 | 2016-07-01T14:33:28Z | 38,148,209 | <p>Try this one :</p>
<p>([A-Za-z0-9]+@\S+?.co([^\'\"<]*))</p>
| 0 | 2016-07-01T14:42:16Z | [
"python",
"regex",
"non-greedy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.