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
scrape Url and text from website using lxml python
39,214,339
<p>I don't know much about lxml and xpaths and I want to learn how to scrape data from website. When I run this code I don't get any results and don't know why. Please help me to fix it.</p> <p>code here</p> <pre><code>from lxml import html import requests pageLen=str(100) page = requests.get('http://www.yellowpages....
-1
2016-08-29T20:07:17Z
39,216,900
<p>Thank you @Abd Azrad. Your solution helped me a lot.</p> <p>Can you please further guide me? I am confused how to deal with inconsistent data? Sometimes, there are postal address missing and sometimes location missing. I just want to ignore that data which does not fulfill my requirements.<br> <code> page ...
0
2016-08-29T23:56:09Z
[ "python", "web-scraping", "lxml" ]
PostgreSQL: Unable to drop a specific table named "user"
39,214,369
<p>I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,</p> <pre><code> import psycopg2 conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'") cur = conn.cursor() cur.exec...
2
2016-08-29T20:09:01Z
39,214,396
<p>Quote "user" as below</p> <pre><code>import psycopg2 conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'") cur = conn.cursor() cur.execute('DROP TABLE "user";') conn.commit() conn.close() </code></pre> <p>See <a href="https://www.postgresql.org/docs/9.1/static/sql-...
0
2016-08-29T20:11:28Z
[ "python", "sql", "postgresql", "psycopg2" ]
Running Flask dev server in Python 3.6 raises ImportError for SocketServer and ForkingMixIn
39,214,395
<p>I am trying to run a basic Flask app using Python 3.6. However, I get an <code>ImportError: cannot import name 'ForkingMixIn'</code>. I don't get this error when running with Python 2.7 or 3.5. How can I run Flask with Python 3.6?</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/") def...
2
2016-08-29T20:11:22Z
39,214,538
<p>This is a known issue that was <a href="https://github.com/pallets/werkzeug/pull/999" rel="nofollow">reported to Werkzeug</a> in anticipation of Python 3.6. Until that or another patch is merged and released, Werkzeug's dev server will not run on Python 3.6.</p> <blockquote> <p>Check if OS can fork before import...
0
2016-08-29T20:19:21Z
[ "python", "flask", "werkzeug", "python-3.6" ]
Fetching first record from NDB datastore in GAE
39,214,414
<p>I'm currently writing an application on the Google App Engine for Python. I want to fetch the first record in my datastore, but for some reason this won't work. This is how I'd do it in MySQL:</p> <pre><code>SELECT * FROM MyClass LIMIT 1; </code></pre> <p>However since I'm new to NDB, I can't quite seem to wrap my...
0
2016-08-29T20:12:39Z
39,332,538
<p>It seems like you are trying to retrieve the data immediately after it is written to the Datastore which will not work unless you set the same <code>parent key</code> on each entity as stated in App Engine's <a href="https://cloud.google.com/appengine/docs/python/getting-started/storing-data-datastore" rel="nofollow...
0
2016-09-05T14:16:22Z
[ "python", "google-app-engine" ]
Where to get name of signature algorithm from SSLSocket?
39,214,464
<p>I could not find a suitable way to get the name of the signature algorithm used for a certificate that is received by an SSLSocket. I'm aware you can pull the bytes of the peer's cert with <code>SSLSocket.getpeercert(True)</code> but I don't know what to do with it past that. PyOpenSSL doesn't seem to have an easy i...
0
2016-08-29T20:15:19Z
39,231,835
<p>After the very helpful comment pointing me in the right direction, you can use the <code>cryptography</code> module to load the DER X509 format that the <code>SSLSocket.getpeercert()</code> function outputs. From this <code>Certificate</code> instance you can also access many other fields about the certificate such...
0
2016-08-30T15:39:30Z
[ "python", "ssl", "digital-signature", "x509", "verification" ]
How to rank plot in seaborn boxplot?
39,214,484
<p>Take the following seaborn boxplot for example, from <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html</a></p> <pre><code>import numpy as np import seaborn as sns sns.set(style="tic...
0
2016-08-29T20:16:18Z
39,215,275
<p>You can use the <code>order</code> argument in the <code>sns.boxplot</code> and <code>sns.stripplot</code> functions to order your "boxes". Here is an example of how to do this (since it is not completely clear what you mean by "greatest to lowest", i.e. which variable you want to sort the entries based on, I am ass...
0
2016-08-29T21:10:46Z
[ "python", "pandas", "matplotlib", "seaborn" ]
How to rank plot in seaborn boxplot?
39,214,484
<p>Take the following seaborn boxplot for example, from <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html</a></p> <pre><code>import numpy as np import seaborn as sns sns.set(style="tic...
0
2016-08-29T20:16:18Z
39,215,913
<p>Try this: </p> <pre><code>import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") ranks = planets.groupby("method")["distance"].mean().fillna(0).sort_values()[::-1].index # Plot the orbital period ...
1
2016-08-29T22:06:38Z
[ "python", "pandas", "matplotlib", "seaborn" ]
Understanding asyncio: Asynchronous vs synchronous callbacks
39,214,526
<p>There's one very particular thing about <code>asyncio</code> that I can't seem to understand. And that is the difference between asynchronous and synchronous callbacks. Let me introduce some examples.</p> <p>Asyncio TCP example:</p> <pre><code>class EchoServer(asyncio.Protocol): def connection_made(self, transpor...
3
2016-08-29T20:18:40Z
39,232,069
<p>In <code>aiohttp</code> example you could do asynchronous calls from <code>simple</code> web-handler: access to database, make http requests etc.</p> <p>In <code>Protocol.data_received()</code> you should call only regular synchronous methods.</p> <p><strong>UPD</strong></p> <p><code>Protocol</code> callbacks are...
1
2016-08-30T15:51:48Z
[ "python", "asynchronous", "callback", "python-asyncio" ]
(PY)Object has no attribute error
39,214,577
<pre><code># The imports include turtle graphics and tkinter modules. # The colorchooser and filedialog modules let the user # pick a color and a filename. import turtle import tkinter import tkinter.colorchooser import tkinter.filedialog import xml.dom.minidom # The following classes define the different commands tha...
-3
2016-08-29T20:22:09Z
39,214,695
<p>The problem is that the <code>RawTurtle</code> object, from the turtle module, has no attribute <code>move</code>. You can use the commands <code>forward</code>, <code>backward</code>, <code>left</code>, and <code>right</code> to move your turtle. Before using the above commands, I suggest looking at the <a href="ht...
1
2016-08-29T20:30:10Z
[ "python", "pycharm" ]
(PY)Object has no attribute error
39,214,577
<pre><code># The imports include turtle graphics and tkinter modules. # The colorchooser and filedialog modules let the user # pick a color and a filename. import turtle import tkinter import tkinter.colorchooser import tkinter.filedialog import xml.dom.minidom # The following classes define the different commands tha...
-3
2016-08-29T20:22:09Z
39,214,699
<p>This is fairly straightforward. You initialize <code>theTurtle</code> in the caller to be a <code>turtle.RawTurtle</code>. <code>RawTurtle</code> doesn't have an attribute or method named <code>move</code>, <a href="https://docs.python.org/3/library/turtle.html#turtle-motion" rel="nofollow">it has special purpose me...
1
2016-08-29T20:30:26Z
[ "python", "pycharm" ]
Ternary using pass keyword python
39,214,741
<p>I have a working conditional statement:</p> <pre><code>if True: pass else: continue </code></pre> <p>that I would like to turn it into a ternary expression:</p> <pre><code>pass if True else continue </code></pre> <p>However, Python does not allow this. Can anyone help? </p> <p>Thanks!</p>
1
2016-08-29T20:34:01Z
39,214,775
<p>Ternary expression are used to compute values; neither <code>pass</code> nor <code>continue</code> are values.</p>
1
2016-08-29T20:36:10Z
[ "python", "conditional", "ternary" ]
Ternary using pass keyword python
39,214,741
<p>I have a working conditional statement:</p> <pre><code>if True: pass else: continue </code></pre> <p>that I would like to turn it into a ternary expression:</p> <pre><code>pass if True else continue </code></pre> <p>However, Python does not allow this. Can anyone help? </p> <p>Thanks!</p>
1
2016-08-29T20:34:01Z
39,214,784
<p><code>pass</code> and <code>continue</code> are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.</p> <p>Nevertheless, you can still shorten the condition you brought like this:</p> <pre><code>if False: c...
1
2016-08-29T20:36:42Z
[ "python", "conditional", "ternary" ]
Ternary using pass keyword python
39,214,741
<p>I have a working conditional statement:</p> <pre><code>if True: pass else: continue </code></pre> <p>that I would like to turn it into a ternary expression:</p> <pre><code>pass if True else continue </code></pre> <p>However, Python does not allow this. Can anyone help? </p> <p>Thanks!</p>
1
2016-08-29T20:34:01Z
39,214,823
<p><strong>Point 1</strong>: Are your sure your condition is right? Because <code>if True</code> will always be <code>True</code> and code will never go to <code>else</code> block. </p> <p><strong>Point 2</strong>: <code>pass</code> and <code>continue</code> are not expressions or values, but a action instead You can ...
1
2016-08-29T20:39:37Z
[ "python", "conditional", "ternary" ]
get time difference in seconds for time referring to another timezone
39,214,761
<p>I intend to find the time difference between two time variables in seconds. The issue here is that I am referring to time in a different zone. I have managed to find a solution, but it is a mix of pandas.datetime function and python datetime library. I guess, the objective can be achieved with just pandas/numpy alon...
0
2016-08-29T20:35:08Z
39,214,799
<p>You may want to convert both times to UTC, then find the difference. Programmers usually like to work with UTC until the time reaches the front end.</p>
0
2016-08-29T20:37:59Z
[ "python", "datetime", "pandas", "numpy", "timedelta" ]
PythonQt doesn't print anything
39,214,773
<p>I'm following the examples at <a href="http://pythonqt.sourceforge.net/Examples.html" rel="nofollow">http://pythonqt.sourceforge.net/Examples.html</a>, but PythonQt doesn't print anything on the console. I execute a script that just prints <code>hello</code>, but nothing gets printed.</p> <pre><code>PythonQt::init(...
0
2016-08-29T20:35:57Z
39,214,854
<p>After reading <a href="https://sourceforge.net/p/pythonqt/discussion/631393/thread/33ad915c" rel="nofollow">https://sourceforge.net/p/pythonqt/discussion/631393/thread/33ad915c</a>, it seems that <code>PythonQt::init();</code> does redirect python output to the PythonQt::pythonStdOut signal.</p> <p>This is because ...
1
2016-08-29T20:42:00Z
[ "python", "c++", "qt", "python-embedding", "pythonqt" ]
How to install python "gi" module in virtual environment?
39,214,803
<p>I have looked at <a href="http://stackoverflow.com/questions/12830662/python-package-installed-globally-but-not-in-a-virtualenv-pygtk">this</a>, and tried the following code:</p> <pre><code>ln -s /usr/lib/python2.7/dist-packages/pygtk.pth tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist...
0
2016-08-29T20:38:12Z
39,215,042
<p>You need to install the necessary modules on your virtual environment. </p> <p>After activating it, you have to <code>pip install &lt;library name&gt;</code>. In your case, it should be <code>pip install gi</code></p>
0
2016-08-29T20:54:53Z
[ "python", "virtualenv", "python-gstreamer" ]
zip unknown number of lists with Python for more than one list
39,214,810
<p>I need to do something very similar to what was asked here <a href="http://stackoverflow.com/questions/5938786/how-would-you-zip-an-unknown-number-of-lists-in-python">How would you zip an unknown number of lists in Python?</a>, but in a more general case.</p> <p>I have the following set up:</p> <pre><code>a = [['a...
0
2016-08-29T20:38:41Z
39,214,849
<p><code>itertools.chain</code> to the rescue:</p> <pre><code>import itertools z = list(zip(*itertools.chain(a, b, c))) </code></pre>
5
2016-08-29T20:41:33Z
[ "python", "list", "zip" ]
replacing quotes, commas, apostrophes w/ regex - python/pandas
39,214,938
<p>I have a column with addresses, and sometimes it has these characters I want to remove => <code>'</code> - <code>"</code> - <code>,</code>(apostrophe, double quotes, commas)</p> <p>I would like to replace these characters with space in one shot. I'm using pandas and this is the code I have so far to replace one of...
1
2016-08-29T20:48:14Z
39,215,021
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a>:</p> <pre><code>test['Address 1'] = test['Address 1'].str.replace(r"[\"\',]", '') </code></pre> <p>Sample:</p> <pre><code>import pandas as pd test = pd.DataFrame(...
1
2016-08-29T20:53:18Z
[ "python", "string", "pandas", "replace", "dataframe" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1,...
-1
2016-08-29T20:48:21Z
39,215,060
<p>Best way to achieve this will be to use <a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow"><code>random.shuffle</code></a> (if you want to randomize the original sample list) or <a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow"><code>random.selec...
1
2016-08-29T20:55:38Z
[ "python", "python-2.7" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1,...
-1
2016-08-29T20:48:21Z
39,215,092
<p>You could do this:</p> <pre><code>cool1, cool2, cool3 = random.sample([A1, A2, A3], 3) </code></pre> <blockquote> <p>Also how can I use alphanumerical instead of float only.</p> </blockquote> <p>Have you tried not converting your inputs to float...?</p>
-2
2016-08-29T20:58:03Z
[ "python", "python-2.7" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1,...
-1
2016-08-29T20:48:21Z
39,215,099
<p>Since you are selecting from a list, then you should delete the entry from the list after each check.</p> <ol> <li><p>Create your original list, which will be used as needed.</p></li> <li><p>Create a second list from the first to use as you select.</p></li> <li><p>As you choose each element from the list, remove it...
0
2016-08-29T20:58:43Z
[ "python", "python-2.7" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1,...
-1
2016-08-29T20:48:21Z
39,215,482
<p>write a class to pick a unique element from list<br> 1. permutations finds all unique elements <br> 2. rest can define new data and length of result<br></p> <pre><code>from itertools import permutations class PickOne( object ): def __init__(self,lst,l): self.lst = lst self.visit = set() ...
1
2016-08-29T21:26:50Z
[ "python", "python-2.7" ]
Why does list(next(iter(())) for _ in range(1)) == []?
39,214,961
<p>Why does <code>list(next(iter(())) for _ in range(1))</code> return an empty list rather than raising <code>StopIteration</code>?</p> <pre><code>&gt;&gt;&gt; next(iter(())) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; [next(iter(())) for _ in range(...
17
2016-08-29T20:49:16Z
39,214,998
<p>The <code>StopIteration</code> exception is used to tell the underlying mechanism of the <code>list</code> function when to actually stop iterating on the iterable that has been passed to it. In your case, you're telling Python that the thing that has been passed into <code>list()</code> is a generator. So when it g...
6
2016-08-29T20:51:55Z
[ "python" ]
Why does list(next(iter(())) for _ in range(1)) == []?
39,214,961
<p>Why does <code>list(next(iter(())) for _ in range(1))</code> return an empty list rather than raising <code>StopIteration</code>?</p> <pre><code>&gt;&gt;&gt; next(iter(())) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; [next(iter(())) for _ in range(...
17
2016-08-29T20:49:16Z
39,215,240
<p>assuming all goes well, the generator comprehension <code>x() for _ in range(1)</code> should raise <code>StopIteration</code> when it is finished iterating over <code>range(1)</code> to indicate that there are no more items to pack into the list.</p> <p>However because <code>x()</code> raises <code>StopIteration</...
9
2016-08-29T21:07:37Z
[ "python" ]
Unbalanced worker/machine assignment
39,215,098
<p>I have a problem of assigning 7 possible workers to 3 machines. There is a cost when a worker is assigned to a machine as well as when a worker is idle. It is required that all 3 machines are used. The cost matrices are</p> <pre><code> M1 M2 M3 W1 [72, 74, 74] [64, W2 [48, 50, 50] ...
-3
2016-08-29T20:58:22Z
39,224,750
<p>Found what was wrong with it. I had to many dummy machines allowing workers to be assigned to them rather than to the machines. By changing the dimensions of the matrix to be square (7x7) and changing the cost matrix </p> <pre><code> M1 M2 M3 W1 [72, 74, 74,64,64,64,64] W2 [48, 50, 50,...
0
2016-08-30T10:16:37Z
[ "python", "matrix", "variable-assignment" ]
Trying to run multiple python scripts in Java
39,215,111
<p>I have a python script called generate_graphs.py that generates graphs with python libraries. The graphs are trends we show to customers with our internal data. </p> <p>I'm trying to run the script from Java, but I don't see any evidence of it running. There is no evidence of logs showing it ran, but I'm not sure i...
0
2016-08-29T20:59:30Z
39,230,271
<p>I ended up using <a href="https://commons.apache.org/proper/commons-exec/download_exec.cgi" rel="nofollow">Apache Common's Exec</a> to solve my issue. </p>
0
2016-08-30T14:28:53Z
[ "java", "python", "logging", "command-line", "command" ]
Adding print statements to cython code affects output
39,215,155
<p>I have an application that's written in a combination of Python and Cython. I recently added a new feature and tests to this application. The tests pass on my local machine (a macbook), but when I push to appveyor (a Windows CI service) the tests fail. This in itself is not so strange. When I add print statement...
0
2016-08-29T21:02:13Z
39,215,388
<p>The typical case in my experience is where you've managed to grab a value from unallocated or unaligned storage -- in short, a memory usage error that finesses the compiler's ability to detect such abuse. Normally, you get a garbage value; the print statement forces an evaluation or memory alignment that "fixes" th...
2
2016-08-29T21:18:58Z
[ "python", "windows", "cython", "appveyor" ]
Adding print statements to cython code affects output
39,215,155
<p>I have an application that's written in a combination of Python and Cython. I recently added a new feature and tests to this application. The tests pass on my local machine (a macbook), but when I push to appveyor (a Windows CI service) the tests fail. This in itself is not so strange. When I add print statement...
0
2016-08-29T21:02:13Z
39,215,418
<p>To save some time, you can try to debug deeper using blocking RDP (<a href="https://www.appveyor.com/docs/how-to/rdp-to-build-worker/" rel="nofollow">https://www.appveyor.com/docs/how-to/rdp-to-build-worker/</a>) which you can insert in different stages of Appveyor build. Just please note that Environment variables ...
1
2016-08-29T21:21:29Z
[ "python", "windows", "cython", "appveyor" ]
What is the correct method to spark-submit python applications on aws emr?
39,215,244
<p>I'm connected to the master node of a Spark cluster, running inside of emr, and am trying to submit a python based application:</p> <pre><code>spark-submit --verbose --deploy-mode cluster --master yarn-cluster --num-executors 3 --executor-cores 6 --executor-memory 1g test.py </code></pre> <p>The process produces ...
2
2016-08-29T21:07:52Z
39,239,106
<p>This appears to be a bug with the aws system. Yarn monitors the system and notices that the deployed code is no longer there - which is really a sign that spark is done processing.</p> <p>To verify that this is the problem, double check by reading the logs for your application - ie, run something like this against ...
0
2016-08-31T00:45:22Z
[ "python", "amazon-web-services", "apache-spark", "emr" ]
Python Float to String TypeError
39,215,272
<p>I am writing a temperature converter for fun and everything seems to be working except I am getting a 'TypeError: Can't convert 'float' object to str implicitly' message. From what I can tell I am converting it to a string after the fact, can anyone tell me what I am doing wrong? </p> <p>I looked this this questio...
0
2016-08-29T21:10:28Z
39,215,298
<p>In this calculation:</p> <pre><code>((int(Temp)*9)/5)+32 </code></pre> <p>You are not converting your result to <code>str</code>.</p> <p>Also, you have spelled "Fahrenheit" incorrectly.</p>
1
2016-08-29T21:12:06Z
[ "python", "python-3.x" ]
Python Float to String TypeError
39,215,272
<p>I am writing a temperature converter for fun and everything seems to be working except I am getting a 'TypeError: Can't convert 'float' object to str implicitly' message. From what I can tell I am converting it to a string after the fact, can anyone tell me what I am doing wrong? </p> <p>I looked this this questio...
0
2016-08-29T21:10:28Z
39,215,532
<p>In the line of code:</p> <pre><code>+ 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ## </code></pre> <p>The error is caused by this part of it:</p> <pre><code>Temp+ 273.15 </code></pre> <p><code>Temp</code> is a string. You can't add a string and a number together.</p>
2
2016-08-29T21:30:32Z
[ "python", "python-3.x" ]
Alembic migration for GeoAlchemy2 raises NameError: name 'geoalchemy2' is not defined
39,215,278
<p>I've decided to write a small webapp using Flask, postgresql and leaflet. I wanted to store coordinates (latitude and longitude) using <a href="http://postgis.net/" rel="nofollow">PostGIS</a> extender for postgresql. My flask application uses Flask-SQLAlchemy, blueprint and especially Flask-Migrate for the database ...
0
2016-08-29T21:10:57Z
39,215,327
<p>Alembic does not try to determine and render all imports for custom types in the migration scripts. Edit the generated script to include <code>from geoalchemy2.types import Geometry</code> and change the column def to just use <code>Geometry</code>.</p> <p>You should always review the auto-generated scripts before...
0
2016-08-29T21:14:03Z
[ "python", "postgresql", "flask", "alembic", "geoalchemy2" ]
How to call deepcopy with super in python?
39,215,452
<p>I have 2 classes, let's call them Class1 and Class2(Class1), and Class2 derives from Class1. </p> <p>In Class1, copy.deepcopy works very well and I <strong>don't</strong> want to implement a method <strong>deepcopy</strong> on Class1. </p> <p>Now, I have an instance i2=Class2(someParameters). I want to make a deep...
1
2016-08-29T21:23:55Z
39,215,519
<p>How about instead of inheriting <code>Class1</code>, create a object of <code>Class2 in Class1</code>? Like:</p> <pre><code>class Class2(object): def __init__(self): self.class_1 = Class1() # Then deepcopy copy.deepcopy(class_2.class_1) </code></pre> <p><strong>Note</strong>: It would be great if you ...
0
2016-08-29T21:29:12Z
[ "python", "copy", "super" ]
Order of the link in the page with Scrapy
39,215,467
<p>I have a simple <code>LinkExtractor</code> rule for a given domain. Something like this: <code>Rule(LinkExtractor(allow=('domain\.com/.+/\d+', )), callback='parse_page'),</code></p> <p>What I would like and I can't figure out, it's to know on which position was the link in the page.</p> <p>For example, if a given ...
0
2016-08-29T21:25:05Z
39,215,622
<p>Scrapy uses lxml to for html parsing. <code>LinkExtractor</code> uses <code>root.iter()</code> to iterate through. <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/linkextractors/lxmlhtml.py#L37" rel="nofollow">This line to be more exact.</a></p> <p><a href="http://lxml.de/tutorial.html#tree-iteration" ...
1
2016-08-29T21:39:44Z
[ "python", "scrapy" ]
Conditionally Merging list of lists with rows of a text file
39,215,510
<p>Consider these two data structures:</p> <pre><code>var_a = [['apple','fruit','1'],['banana', 'fruit', '2'],['orange', 'fruit', '3']] </code></pre> <p>text file contents:</p> <pre><code>'1', '20,000', 'USA' '2', '45,000', 'Russia' '3', '56,000', 'China' </code></pre> <p>I want to use a list comprehension that wil...
0
2016-08-29T21:28:32Z
39,215,817
<p>Below is the sample code for list comprehension with the use of <code>itertools</code>:</p> <pre><code>import itertools with open('/tmp/my_text_file.txt') as f: new_list = [list(itertools.chain(item[1][:1], item[0].strip().replace("'", "").split(", "))) for item in zip(f.readlines(), var_a)] # new_list = [['a...
1
2016-08-29T21:57:51Z
[ "python", "json", "list-comprehension" ]
Psycopg2 connection unusable after SELECTs interrupted by OS signal
39,215,527
<h1>Problem</h1> <p>I am working on a long-running python process that performs a lot of database access (mostly reads, occasional writes). Sometimes it may be necessary to terminate the process before it finishes (e.g. by using the <code>kill</code> command) and when this happens I would like to log a value to the da...
0
2016-08-29T21:30:13Z
39,668,740
<p>I filed an <a href="https://github.com/psycopg/psycopg2/issues/471" rel="nofollow">issue</a> for this on the psycopg2 github and received a helpful response from the developer. In summary:</p> <ul> <li>The behavior of an existing connection within a signal handler is OS dependent and there's probably no way to use ...
0
2016-09-23T20:05:26Z
[ "python", "postgresql", "python-2.7", "signals", "psycopg2" ]
Fill in web form using Python
39,215,539
<p>I've been trying to fill in a web form using Selenium in Python. It's a simple enough task, and the code I'm using is this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("https://...") elem = driver.find_element_by_id("receipt_...
2
2016-08-29T21:31:13Z
39,215,568
<p>click the submit button instead of sending a return key</p>
1
2016-08-29T21:33:26Z
[ "python", "selenium-webdriver" ]
What is map_partitions doing?
39,215,617
<p>The dask API says, that map_partition can be used to "apply a Python function on each DataFrame partition." From this description and according to the usual behaviour of "map", I would expect the return value of map_partitions to be (something like) a list whose length equals the number of partitions. Each element o...
3
2016-08-29T21:38:44Z
39,227,474
<p>The <a href="http://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.DataFrame.map_partitions" rel="nofollow">Dask DataFrame.map_partitions</a> function returns a new Dask Dataframe or Series, based on the output type of the mapped function. See the <a href="http://dask.readthedocs.io/en/latest/dataf...
1
2016-08-30T12:26:27Z
[ "python", "pandas", "dask" ]
Flask-SQLAlchemy - Backref isn't working, value is None
39,215,663
<p>I think I have the same issue as <a href="http://stackoverflow.com/questions/28323644/flask-sqlalchemy-backref-not-working">here on SO.</a> Using python 3.5, flask-sqlalchemy, and sqlite. I am trying to establish a one (User) to many (Post) relationship.</p> <pre><code>class User(db_blog.Model): id = db_blog.Co...
0
2016-08-29T21:43:27Z
39,216,243
<p>If you add the newly created <code>post</code> to the <code>posts</code> attribute of the user, it will work:</p> <pre><code>&gt;&gt;&gt; u = User(nickname="John Doe", email="jdoe@email.com") &gt;&gt;&gt; u &lt;User: John Doe&gt; &gt;&gt;&gt; db_blog.session.add(u) &gt;&gt;&gt; p = Post(body="Body of post", title="...
0
2016-08-29T22:39:05Z
[ "python", "sqlite", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Flask-SQLAlchemy - Backref isn't working, value is None
39,215,663
<p>I think I have the same issue as <a href="http://stackoverflow.com/questions/28323644/flask-sqlalchemy-backref-not-working">here on SO.</a> Using python 3.5, flask-sqlalchemy, and sqlite. I am trying to establish a one (User) to many (Post) relationship.</p> <pre><code>class User(db_blog.Model): id = db_blog.Co...
0
2016-08-29T21:43:27Z
39,217,136
<p>You added your own <code>__init__</code> to <code>Post</code>. While it accepts keyword arguments, it does nothing with them. You can either update it to use them</p> <pre><code>def __init__(self, body, title, **kwargs): self.body = body self.title = title for k, v in kwargs: setattr(self, k, v...
0
2016-08-30T00:29:47Z
[ "python", "sqlite", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Can I "touch" a SQLAlchemy record to trigger "onupdate"?
39,215,673
<p>Here's a SQLAlchemy class:</p> <pre><code>class MyGroup(Base): __tablename__ = 'my_group' group_id = Column(Integer, Sequence('my_seq'), primary_key=True) group_name = Column(String(200), nullable=False, index=True) date_created = Column(DateTime, default=func.now()) date_updated = Column(DateTi...
0
2016-08-29T21:44:28Z
39,279,472
<p>I haven't looked at the source but from the <a href="http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.onupdate" rel="nofollow">docs</a> it seems that this is only triggered by issuing a SQL <code>UPDATE</code> command:</p> <blockquote> <p>onupdate – A scalar, Python callab...
0
2016-09-01T19:28:07Z
[ "python", "sqlalchemy", "sql-update" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>resul...
1
2016-08-29T21:46:02Z
39,215,873
<p>Assuming that the "non-increasing" values remain constant in those regions and do not decrease either, you can just group entries that have the same value and then pick those groups that have more than one entry. Finally, extract the beginning and the end index.</p> <pre><code>&gt;&gt;&gt; data = {0: 0, 1: 1, 2: 2,...
2
2016-08-29T22:02:28Z
[ "python" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>resul...
1
2016-08-29T21:46:02Z
39,215,874
<p>If it is the case that (a) your keys are consecutive integers and (b) you want to find those keys whose values are not greater than the value corresponding to preceding integer <em>or</em> not less than the value corresponding to the successive integer, then:</p> <pre><code>&gt;&gt;&gt; [k for k in sorted(data.key...
1
2016-08-29T22:02:36Z
[ "python" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>resul...
1
2016-08-29T21:46:02Z
39,215,937
<p>Here's an alternative way using <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>.</p> <pre><code>from collections import defaultdict ranges = defaultdict(list) data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} ...
0
2016-08-29T22:08:40Z
[ "python" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>resul...
1
2016-08-29T21:46:02Z
39,215,953
<p>What about something like that:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} sd = sorted(data.items()) result = [] for i in range(1, len(sd)): if sd[i][1] == sd[i-1][1]: result.append(i) </code></pre> <p>I think <code>sorted(data.items())</code> is both clea...
0
2016-08-29T22:10:31Z
[ "python" ]
Feature Importance for Random Forest Regressor in Python
39,215,700
<p>I'm trying to find out which features have the most importance for my predictive model.</p> <p>Currently I'm using sklearn's inbuilt attribute as such</p> <pre><code>Model = Model.fit(Train_Features, Labels_Train) print(Model.feature_importances_) </code></pre> <p>It's just that its more of a black box type metho...
0
2016-08-29T21:46:39Z
39,215,847
<p>Feature importance is not a black-box when it comes to decision trees. From the documentation for a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html#sklearn.tree.DecisionTreeRegressor.feature_importances_" rel="nofollow">DecisionTreeRegressor</a>:</p> <blockquote> ...
1
2016-08-29T22:00:36Z
[ "python", "regression", "random-forest", "feature-selection" ]
Efficiency when printing progress updates, print x vs if x%y==0: print x
39,215,750
<p>I am running an algorithm which reads an excel document by rows, and pushes the rows to a SQL Server, using Python. I would like to print some sort of progression through the loop. I can think of two very simple options and I would like to know which is more lightweight and why. Option A:</p> <pre><code>for x in xr...
1
2016-08-29T21:52:02Z
39,219,220
<p>I'm a newbie, so I can't comment. An "answer" might be overkill, but it's all I can do for now. </p> <p>My favorite thing for this is <a href="https://pypi.python.org/pypi/tqdm" rel="nofollow">tqdm</a>. It's minimally invasive, both code-wise and output-wise, and it gets the job done. </p>
3
2016-08-30T05:16:04Z
[ "python", "algorithm", "performance", "python-2.7" ]
Efficiency when printing progress updates, print x vs if x%y==0: print x
39,215,750
<p>I am running an algorithm which reads an excel document by rows, and pushes the rows to a SQL Server, using Python. I would like to print some sort of progression through the loop. I can think of two very simple options and I would like to know which is more lightweight and why. Option A:</p> <pre><code>for x in xr...
1
2016-08-29T21:52:02Z
39,225,991
<p>Using the modulus check (counter % N == 0) is almost free compared print and a great solution if you run a high frequency iteration (log a lot). Specially if you does not need to print for each iteration but want some feedback along the way.</p>
1
2016-08-30T11:14:33Z
[ "python", "algorithm", "performance", "python-2.7" ]
Efficiency when printing progress updates, print x vs if x%y==0: print x
39,215,750
<p>I am running an algorithm which reads an excel document by rows, and pushes the rows to a SQL Server, using Python. I would like to print some sort of progression through the loop. I can think of two very simple options and I would like to know which is more lightweight and why. Option A:</p> <pre><code>for x in xr...
1
2016-08-29T21:52:02Z
39,299,328
<p>I am one of the developers of <a href="https://github.com/tqdm/tqdm" rel="nofollow">tqdm, a Python progress bar</a> that tries to be as efficient as possible while providing as many automated features as possible.</p> <p>The biggest performance sink we had was indeed I/O: printing to the console/file/whatever.</p> ...
1
2016-09-02T19:14:17Z
[ "python", "algorithm", "performance", "python-2.7" ]
Fastest way to calculate "cosine" metrics with scipy
39,215,925
<p>I am given a matrix of ones and zeros. I need to find 20 rows which have the highest cosine metrics towards 1 <code>specific</code> row in matrix: </p> <p>If I have 10 rows, and 5th is called <code>specific</code>, I want to choose the highest value between these:<br> <code>cosine(1row,5row),cosine(2row,5row),...,...
2
2016-08-29T22:07:35Z
39,645,684
<p>The fastest way is to use matrix operations: <code>something like np.multipy(A,B)</code> </p>
0
2016-09-22T17:48:08Z
[ "python", "scipy", "cosine" ]
Python - allowed values of a variable
39,216,012
<p>How can I explicitly define what values can given variable have? Let's say I want value of variable <strong>size</strong> to be either <strong>'small'</strong>, <strong>'medium'</strong>, or <strong>'big'</strong> and nothing else.</p> <p>EDIT: I want to avoid a situation when variable is set to something from beyo...
-3
2016-08-29T22:15:36Z
39,216,069
<p>Simplest way would be to always use dedicated method which would firstly validate input and if it's correct then set variable. Below you may find some example:</p> <pre class="lang-py prettyprint-override"><code>class Test: def __init__(self): self.__variable = None def set_variable(self, value): ...
3
2016-08-29T22:21:32Z
[ "python", "enums" ]
Python - allowed values of a variable
39,216,012
<p>How can I explicitly define what values can given variable have? Let's say I want value of variable <strong>size</strong> to be either <strong>'small'</strong>, <strong>'medium'</strong>, or <strong>'big'</strong> and nothing else.</p> <p>EDIT: I want to avoid a situation when variable is set to something from beyo...
-3
2016-08-29T22:15:36Z
39,216,090
<p>You are describing an <code>enumeration</code>, which is supported in Python by the <code>enum</code> library:</p> <pre><code>from enum import Enum class Size(Enum): small = 'small' medium = 'medium' big = 'big' size = Size('big') print(size) try: size = Size('tiny') except ValueError as e: pr...
2
2016-08-29T22:23:59Z
[ "python", "enums" ]
Python example of how to get formatting information from a cell in Google Sheets API v4?
39,216,029
<p>I've been trying to write my own Google Sheets wrapper, and it's been a frustrating experience so far. The thing I'm stuck on at the moment is how to get a symmetrical in / out format of sheet data.</p> <p>Basically, I want to call values().get(), alter the resulting hash, and send that same hash back up to update...
0
2016-08-29T22:17:16Z
39,500,316
<p>The <code>spreadsheets.values.get</code> endpoint only returns the values. If you want a more complete picture of the spreadsheet (formatting, etc) then you need to use the <code>spreadsheets.get</code> endpoint:</p> <p><a href="https://developers.google.com/sheets/reference/rest/v4/spreadsheets/get" rel="nofollow"...
0
2016-09-14T22:00:57Z
[ "python", "google-api-client", "google-sheets-api" ]
get column names from numpy genfromtxt in python
39,216,092
<p>using numpy genfromtxt in python, i want to be able to get column headers as key for a given data. I tried the following, but not able to get the column names for the corresponding data.</p> <pre><code>column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0)) columnData = np.genfromtxt(pathToFile,dtyp...
1
2016-08-29T22:24:02Z
39,216,177
<p>Using pandas module:</p> <pre><code>In [94]: fn = r'D:\temp\.data\z.csv' </code></pre> <p>read CSV into data frame:</p> <pre><code>In [95]: df = pd.read_csv(fn) In [96]: df Out[96]: header0 header1 header2 0 mydate 3.4 2.0 1 nextdate 4.0 6.0 2 afterthat 7.0 8.0 </code>...
2
2016-08-29T22:32:53Z
[ "python", "numpy", "genfromtxt" ]
get column names from numpy genfromtxt in python
39,216,092
<p>using numpy genfromtxt in python, i want to be able to get column headers as key for a given data. I tried the following, but not able to get the column names for the corresponding data.</p> <pre><code>column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0)) columnData = np.genfromtxt(pathToFile,dtyp...
1
2016-08-29T22:24:02Z
39,216,405
<p>With your sample file and <code>genfromtxt</code> calls I get 2 arrays:</p> <pre><code>In [89]: column Out[89]: array(['header0', 'mydate', 'nextdate', 'afterthat'], dtype='&lt;U9') In [90]: columnData Out[90]: array([['header0', 'header1', 'header2'], ['mydate', '3.4', '2.0'], ['nextdate', '...
1
2016-08-29T22:58:13Z
[ "python", "numpy", "genfromtxt" ]
python tkinter open new window with button click and close first window
39,216,151
<p>I have a login window. I want to close that login window when access is granted to a user, and open a new window. I've searched a lot to find a solution to this simple problem, but didn't understand how to do that. I tried <code>self.destroy()</code> but it close the entire program.</p> <p>here is the code</p> <pr...
0
2016-08-29T22:30:03Z
39,216,646
<p>In my opinion, the best solution is to make each of your sections of the GUI (login page, main page) a subclass of <code>Frame</code> rather than <code>Toplevel</code> or <code>Tk</code>. With that, you can simply destroy the frame representing the login frame, and replace it with the frame representing the main par...
0
2016-08-29T23:26:31Z
[ "python", "python-3.x", "user-interface", "tkinter" ]
How to use the root package in an import?
39,216,182
<p>Taking the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">Ansible</a> project as an example, there is, inside the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">lib/ansible root directory</a>, many other packages, like this</p> <pre><code>ansib...
1
2016-08-29T22:33:19Z
39,216,255
<p>The difference here is that when you install ansible, it puts files into a subdirectory which is accessible from your <code>sys.path</code>. For example, it might go here:</p> <pre><code>/home/leahcim/.local/lib/python2.7/site-packages' </code></pre> <p>That's just a guess at the location. <code>import ansible</...
1
2016-08-29T22:40:50Z
[ "python" ]
How to use the root package in an import?
39,216,182
<p>Taking the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">Ansible</a> project as an example, there is, inside the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">lib/ansible root directory</a>, many other packages, like this</p> <pre><code>ansib...
1
2016-08-29T22:33:19Z
39,216,374
<p>Works for me. Structure:</p> <pre><code>. └── beatles ├── george │   ├── harrison.py │   ├── __init__.py ├── __init__.py ├── john │   ├── __init__.py │   ├── lennon.py ├── paul │   ├── __init__.py ...
1
2016-08-29T22:55:09Z
[ "python" ]
MATCH function in python?
39,216,229
<p>Is there a way to do an Excel match() function in Python, such that:</p> <p>In a graph like this </p> <p><img src="http://i.stack.imgur.com/O3oiF.png" alt="K-Means Elbow Method results">...</p> <p>...wherein I cut-off at y = 90, I would like to print which corresponding x value is the closest.</p> <p>Based on m...
0
2016-08-29T22:37:41Z
39,216,432
<p>You can also beat it to death with this simple-minded function. It finds the first value at least as large as the target value, checks the previous value, and returns the position (1-based, not 0-based) of the closer value.</p> <pre><code>def match (table, target): for over in range(len(table)): if tabl...
0
2016-08-29T23:00:11Z
[ "python", "match", "cluster-analysis", "k-means" ]
MATCH function in python?
39,216,229
<p>Is there a way to do an Excel match() function in Python, such that:</p> <p>In a graph like this </p> <p><img src="http://i.stack.imgur.com/O3oiF.png" alt="K-Means Elbow Method results">...</p> <p>...wherein I cut-off at y = 90, I would like to print which corresponding x value is the closest.</p> <p>Based on m...
0
2016-08-29T22:37:41Z
39,244,621
<p>You are looking for an <em>argmin</em> function.</p> <pre><code>from numpy import * print argmin(abs(data - threshold)) </code></pre> <p>will find the <em>index</em> of the smallest deviation from the threshold. It's much more precise to specify the math relationship (<code>argmin(abs(...))</code>) than to hide t...
0
2016-08-31T08:36:02Z
[ "python", "match", "cluster-analysis", "k-means" ]
Python Threading - Simple but tricky
39,216,238
<p>Could someone please point out, why my code is not printing "hello". I feel that my thread 2 - t2 is not starting. This is just a code snippet, I am trying to work on to implement in my main program. Basically, my idea is the following: </p> <ol> <li>Have a single function - which has two set of codes ---- one code...
1
2016-08-29T22:38:38Z
39,216,360
<p>(Converted from comment because subsequent comment by OP made it clear what they were expecting) The problems come from misuse of <code>Event</code>:</p> <ol> <li><code>if stop_event == True:</code> will always evaluate to <code>False</code> and the <code>if</code> block never executes its contents (<code>stop_even...
0
2016-08-29T22:53:27Z
[ "python", "multithreading" ]
troubles with pandas anaconda package
39,216,240
<p>I got a new mac and just installed anaconda. When I use <code>ipython</code> and <code>spyder</code>, I can <code>import pandas</code> without any problem. However, when I use <code>sublime</code>, I get the error</p> <pre><code>ImportError: No module named pandas </code></pre> <p><code>which python</code> gives <...
1
2016-08-29T22:38:44Z
39,426,440
<p>Just add these two line in your .bash_profile, (if you are on bash) export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 and source it, or restart the terminal. Or if you are using "oh my zsh" shell, then add the lines in .zshrc.</p>
0
2016-09-10T13:16:16Z
[ "python", "pandas", "sublimetext2", "spyder" ]
I'm getting an error list index out of range
39,216,282
<p>I'm reading 'Invent Your own Games with Python' and I'm trying to create a game that's in the book. Even though my code matches the code in the book I'm still getting an error:</p> <pre><code>File "/Users/Rocky/reverso.py", line 251, in &lt;module&gt; resetBoard(mainBoard) File "/Users/Rocky/reverso.py", line...
0
2016-08-29T22:44:49Z
39,216,850
<p>You can initialize your list using this instead:</p> <pre><code>board = [[' ' for _ in range(8)] for _ in range(8)] </code></pre> <p>It should initialize an 8x8 2d list (which will work without errors).</p> <p>This code works:</p> <pre><code>def resetBoard(board): for x in range(8): for y in range(8)...
-1
2016-08-29T23:49:35Z
[ "python" ]
I'm getting an error list index out of range
39,216,282
<p>I'm reading 'Invent Your own Games with Python' and I'm trying to create a game that's in the book. Even though my code matches the code in the book I'm still getting an error:</p> <pre><code>File "/Users/Rocky/reverso.py", line 251, in &lt;module&gt; resetBoard(mainBoard) File "/Users/Rocky/reverso.py", line...
0
2016-08-29T22:44:49Z
39,216,996
<p>Return statement indentation in function <code>getNewBoard()</code> was incorrect.</p>
0
2016-08-30T00:09:17Z
[ "python" ]
Django - Filtering query by difference of two DateTimeFields
39,216,301
<p>I have a model with two DateTimeFields:</p> <pre><code>starttime = models.DateTimeField(db_column='starttime', blank=False, null=False) endtime = models.DateTimeField(db_column='endtime', blank=False, null=False) </code></pre> <p>In my view I would like to filter this by the difference between them. For example if...
0
2016-08-29T22:47:01Z
39,217,786
<p>You can use the F expression as shown below. </p> <pre><code>from django.db.models import F from django.utils import timezone .filter(endtime__gt = models.F('starttime') + timezone.timedelta(0, 45)) </code></pre> <p>It will return only the rows which endtime is greater than starttime + 45 seconds. </p>
2
2016-08-30T02:13:13Z
[ "python", "django" ]
Add letters to string conditionally
39,216,335
<p><strong>Input</strong>: <code>1 10 avenue</code></p> <p><strong>Desired Output</strong>: <code>1 10th avenue</code></p> <p>As you can see above I have given an example of an input, as well as the desired output that I would like. Essentially I need to look for instances where there is a number followed by a certai...
0
2016-08-29T22:49:56Z
39,216,498
<p>Just one way, finding the positions <strong>behind a digit</strong> and <strong>ahead of one of those pattern words</strong> and placing <code>'th'</code> into them:</p> <pre><code>&gt;&gt;&gt; address = '1 10 avenue 3 33 street' &gt;&gt;&gt; patterns = ['avenue', 'street'] &gt;&gt;&gt; &gt;&gt;&gt; import re &gt;...
0
2016-08-29T23:07:01Z
[ "python", "regex" ]
Printing HTML data with Python 3
39,216,368
<p>I am new to Python. I am doing a course in Python 2.7, but at the same time, I want to be able to do everything in Python 3.</p> <p>Code in Python 2.7:</p> <pre><code>import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('www.py4inf.com', 80)) mysock.send('GET http://www.py4inf....
0
2016-08-29T22:54:32Z
39,216,462
<p>It has a <code>b''</code> because what is returned by <code>mysock.recv</code> is of type <code>bytes</code>. You should decode your byte string to a unicode one with <code>decode</code>:</p> <pre><code>print(data.decode('utf-8')) </code></pre> <p>Remember, Python 2 and 3 differ regarding strings as specified in <...
2
2016-08-29T23:03:22Z
[ "python", "python-2.7", "python-3.x" ]
Cannot split a unicode string without converting to ascii - python 2.7
39,216,381
<p>I want to split the string <code>I have £300</code> but it seems that the split function first converts it to a ascii and after. But I can't convert it back to unicode the same as it was before. </p> <p>Is there any other way to split such a unicode string without breaking it as in the snippet bellow.</p> <pre><c...
1
2016-08-29T22:56:07Z
39,216,478
<p>You are looking at a limitation of the way python 2 <em>displays</em> data.</p> <p>Using python 2:</p> <pre><code>&gt;&gt;&gt; mystring = 'I have £300.' &gt;&gt;&gt; mystring.split() ['I', 'have', '\xc2\xa3300.'] </code></pre> <p>But, observe that it will print as you want:</p> <pre><code>&gt;&gt;&gt; print(mys...
3
2016-08-29T23:04:54Z
[ "python", "python-2.7", "unicode", "split", "non-ascii-characters" ]
Cannot split a unicode string without converting to ascii - python 2.7
39,216,381
<p>I want to split the string <code>I have £300</code> but it seems that the split function first converts it to a ascii and after. But I can't convert it back to unicode the same as it was before. </p> <p>Is there any other way to split such a unicode string without breaking it as in the snippet bellow.</p> <pre><c...
1
2016-08-29T22:56:07Z
39,216,633
<p>The problem is not with <code>split()</code>. The real problem is that the handling of unicode in python 2 is confusing.</p> <p>The first line in your code produces a string, i.e. a sequence of bytes, which contains the utf-8 encoding of the symbol <code>£</code>. You can confirm this by displaying the <code>repr<...
1
2016-08-29T23:24:57Z
[ "python", "python-2.7", "unicode", "split", "non-ascii-characters" ]
Spark: Extract zipped keys without computing values
39,216,409
<p>Spark has a <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.zip" rel="nofollow"><code>zip()</code></a> function to combine two RDDs. It also has functions to split them apart again: <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.keys" rel="nofollow"...
0
2016-08-29T22:58:30Z
39,216,798
<p>If you look at the <a href="https://github.com/apache/spark/blob/v2.0.0/core/src/main/scala/org/apache/spark/rdd/PairRDDFunctions.scala#L1249" rel="nofollow">source</a> (at least at 2.0) keys() is simply implemented as </p> <p><code>rdd.map(_._1)</code></p> <p>I.e. returning the first attribute of the tuple, so th...
2
2016-08-29T23:43:16Z
[ "python", "apache-spark", "pyspark" ]
How to extract only the key-value from this list-dict json response?
39,216,533
<p>I would like how can I extract only the keys and values from this json response:</p> <pre><code>[{u'SkuSellersInformation': [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}], u'BestInstallmentNumber': 10, u'RealWeightKg': 1...
0
2016-08-29T23:11:34Z
39,216,809
<p>Well,</p> <p>Your question is not clear, but maybe, this is what you want:</p> <pre><code>for a in data: for key, value in a.items(): if key in ['BestInstallmentNumber', 'RealWeightKg', 'NotifyMe', 'HasServiceAtCartPage', 'RewardValue']: print key, value </code></pre>
-1
2016-08-29T23:44:46Z
[ "python", "json", "list", "dictionary" ]
How to extract only the key-value from this list-dict json response?
39,216,533
<p>I would like how can I extract only the keys and values from this json response:</p> <pre><code>[{u'SkuSellersInformation': [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}], u'BestInstallmentNumber': 10, u'RealWeightKg': 1...
0
2016-08-29T23:11:34Z
39,217,920
<p>Since JSON allow the definition of recursive data structures, the following recursive function will find all the key, value pairs in all the dictionaries encountered in one. Note it may yield the same key multiple times when it occurs in more than one (nested or parallel) dictionary.</p> <pre><code>def get_all(myjs...
1
2016-08-30T02:31:06Z
[ "python", "json", "list", "dictionary" ]
Queue runs successfully! Exits instead of continue, after Break
39,216,593
<p>I am using this script to resolve thousands of domains. It runs successfully, and ends when the queue is empty. I am trying to it to break out of the loop and continue the script by printing.</p> <p>How do I get this code to break out of the loop, ans print, when the queue is empty?</p> <pre><code>q = queue.Queue(...
0
2016-08-29T23:19:18Z
39,216,706
<p>You could simply move the code that does the dns lookup and prints the result into the body of the <code>try/except</code> block:</p> <pre><code>def async_dns(): s = adns.init() while True: try: dname = q.get(False) response = s.synchronous(dname,adns.rr.NS)[0] ...
0
2016-08-29T23:32:47Z
[ "python", "queue" ]
How to overwrite a tensorflow variable after it has been initialized?
39,216,625
<p>Assuming codes like this:</p> <pre><code> sess.run(tf.initialize_all_variables()) assign_op_0 = embedding_list[0].assign(tf.random_normal([35019, 32], stddev = 0.0)) assign_op_1 = embedding_list[1].assign(tf.random_normal([35019, 32], stddev = 0.0)) sess.run(assign_op_0) sess.run(assign_op_1) <...
0
2016-08-29T23:24:07Z
39,229,707
<p>Try as follows:</p> <pre><code>sess.run(tf.initialize_all_variables()) W_0 = tf.Variable(tf.random_normal([35019, 32], stddev = 0.0)) assign_op_0 = W_0.assign(embedding_list[0]) sess.run(assign_op_0) </code></pre>
1
2016-08-30T14:05:01Z
[ "python", "tensorflow" ]
Python KMax Pooling (MXNet)
39,216,640
<p>I'm trying to recreate the char-level CNN in <a href="https://arxiv.org/pdf/1606.01781v1.pdf" rel="nofollow">this paper</a> and am a bit stuck at the final step where I need to create a k-max pooling layer, because I am using MXNet and it does not have this.</p> <blockquote> <p>An important difference is also the...
1
2016-08-29T23:25:43Z
39,317,223
<p><a href="https://github.com/CNevd/DeepLearning-Mxnet/blob/master/DCNN/dcnn_train.py#L15" rel="nofollow">Here</a> you have the code in python with mxnet. </p> <p>It would be great to have it as well in R.</p>
0
2016-09-04T13:06:16Z
[ "python", "neural-network", "deep-learning", "conv-neural-network", "mxnet" ]
How to generate random number between 0 and 1 in genetic algorithm toolbox, Deap
39,216,660
<p>I am using <a href="https://pypi.python.org/pypi/deap" rel="nofollow">genetic algorithm toolbox</a> in Python. The code: </p> <p><code>toolbox.register("attr_bool", random.randint, 0, 1)</code> usually defines random numbers of <code>0</code> and <code>1</code> to be generated. The question is that I am looking for...
0
2016-08-29T23:27:51Z
39,216,858
<p>The error is telling you that it must be able to call the first argument, meaning that it has to be able to act as a function. <code>random.randint</code> is a function, but <code>random.uniform(0, 1)</code> is not. It's a floating-point number. To fix this, you can simply make an anonymous wrapper function with the...
2
2016-08-29T23:50:28Z
[ "python", "random", "genetic-algorithm" ]
When using BING SEARCH API, how do you omit duplicate results?
39,216,665
<p>I built a python 2.7 BING SEARCH API pull, that returns 50 counts per page, and paginates by changing the offset value by a value of 50 each time. My results are written to a JSON file. </p> <p>I am specifying a User-Agent and X-Search-ClientIP in the header of my api call. I am also specifying a responseFilter of ...
-1
2016-08-29T23:28:38Z
39,455,834
<p>Thank you for your inquiry. We noticed you have the following # of paginations:</p> <p>One thing I noticed is that the pagination is set to 10. num_paginations = 10 ## Var used to control max # of paginations.</p> <p>Thanks, Patrick</p>
0
2016-09-12T17:41:29Z
[ "python", "duplicates", "bing-api", "microsoft-cognitive" ]
String variable as literal bytes
39,216,694
<p>I'm reading in a config file. Say I end up with a configuration variable:</p> <pre><code>header = '\x42\x5a\x68' </code></pre> <p>I want to match this against binary files using startswith.</p> <p>Unsurprisingly, I get a <code>"TypeError startswith first arg must be bytes or a tuple of bytes, not str"</code>, if ...
0
2016-08-29T23:32:09Z
39,216,928
<blockquote> <p>How do I use this string? I don't want it encoded.</p> </blockquote> <p>You must. Make a decision, either <code>decode</code> the string you get from the binary file or <code>encode</code> the <code>header</code> name. You can't mix those two types together.</p> <p>See <em><a href="https://docs.pyth...
0
2016-08-29T23:59:49Z
[ "python", "string", "python-3.x" ]
How do I access google cloud storage from local python app?
39,216,702
<p>I am able to access gcs when my app is deployed to gae, but I would like to access gcs from my local machine during development. How would I go about doing this? </p> <p>Here is the traceback i get when i try to open a file on gcs: </p> <pre><code>Traceback (most recent call last): File "/Users/alvinsolidum/Down...
1
2016-08-29T23:32:32Z
39,221,406
<p>Ah, it looks like you're using the appengine-gcs-client for Python. When running on the local development server, the client defaults to using a local, fake version of GCS (see the response header that says "Server: Development/2.0"?). I'm guessing that you're looking for a real GCS object that you haven't uploaded ...
1
2016-08-30T07:31:48Z
[ "python", "google-app-engine", "google-cloud-storage", "google-cloud-platform" ]
Compute Cost of Kmeans
39,216,760
<p>I am using this <a href="https://github.com/yahoo/lopq/blob/master/python/lopq/model.py" rel="nofollow">model</a>, which is not written by me. In order to predict the centroids I had to do this:</p> <pre><code>model = cPickle.load(open("/tmp/model_centroids_128d_pkl.lopq")) codes = d.map(lambda x: (x[0], model.pred...
1
2016-08-29T23:38:35Z
39,217,175
<p>Apparently from the <a href="https://spark.apache.org/docs/latest/mllib-clustering.html" rel="nofollow">documentation</a> I've read, you have to:</p> <ol> <li><p>Create a model maybe by <a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel.l...
1
2016-08-30T00:34:27Z
[ "python", "apache-spark", "machine-learning", "distributed-computing", "k-means" ]
Stacking up multiple shapely polygons to form a heatmap
39,216,767
<p>I have a bunch of Shapely polygons that overlap. Each shape represents one particular observation of the object in the wild. I want to build up some sort of a cumulative observation (heatmap?) by combining the polygons together. Not just the union: I want to combine them in such a way that I can threshold it togethe...
1
2016-08-29T23:39:04Z
39,351,731
<p>one could perhaps proceed by adding one polygon at a time, keep a list of disjoint shapes and remember for each of them how many polygons contributed:</p> <pre><code>import copy from itertools import groupby from random import randint, seed from shapely.geometry import Polygon, box from shapely.ops import cascaded_...
1
2016-09-06T14:38:04Z
[ "python", "matplotlib", "shapely" ]
Problems with multi-layer perceptron in Tensorflow
39,216,771
<p>I created a perceptron (i.e. neural network with fully connected layer(s)) in Tensorflow with one hidden layer (with RELU activation function) and ran it on MNIST data successfully, getting a 90%+ accuracy rate. But when I add a second hidden layer, I get a very low accuracy rate (10%) even after many mini-batches ...
0
2016-08-29T23:40:09Z
39,684,928
<p>Change your learning rate to 0.01 or even smaller value. It helps but in my case accuracy is still worse than with two layers perceptron</p>
0
2016-09-25T08:40:14Z
[ "python", "python-2.7", "neural-network", "tensorflow", "perceptron" ]
Regex matches only one string. Need it to match two
39,216,777
<p>I have the following regex</p> <pre><code>^(.+?)(\s+engine$|\s+ROW_FORMAT) </code></pre> <p>with ignore case enabled.</p> <p>The problem with this is, it matches either "engine" or "row_format" and doesn't match both (as shown in the <a href="https://regex101.com/r/qC3tB7/3" rel="nofollow">last example</a>). What...
0
2016-08-29T23:40:41Z
39,216,917
<p>add the special character <code>+</code>; this <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">causes the resulting RE to match 1 or more repetitions of the preceding RE</a></p> <pre><code>^(.+?)(\s+engine$|\s+ROW_FORMAT)+ </code></pre>
3
2016-08-29T23:58:13Z
[ "python", "regex" ]
Exercism Python Bob
39,216,804
<p>I'm learning Python through Exercism.IO, I'm currently on the <code>Bob</code> problem where the object of the problem is as follows:</p> <blockquote> <p>Bob is a lackadaisical teenager. In conversation, his responses are very limited. Bob answers 'Sure.' if you ask him a question. He answers 'Whoa, chill out...
2
2016-08-29T23:44:19Z
39,217,223
<p>consider using the built-in String method <a href="https://docs.python.org/3/library/stdtypes.html#str.isupper" rel="nofollow"><code>str.isupper()</code></a></p>
3
2016-08-30T00:41:25Z
[ "python" ]
Receive and Parse Emails on AWS SES
39,216,839
<p>I want to setup a Lambda function to parse incoming emails to SES. I followed the documentation and setup the receipt rules. </p> <p>I tested out my script by storing a MIME email in a txt file, parsing the email, and storing required info in a JSON document to be stored in a database. Now, I'm unsure of how to acc...
0
2016-08-29T23:48:28Z
39,217,238
<p>See <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email.html" rel="nofollow">Amazon Simple Email Service document</a></p> <p>Actually, there is a better way; using <a href="http://boto3.readthedocs.io/en/latest/guide/sqs.html#processing-messages" rel="nofollow">boto3</a>, you can send emai...
0
2016-08-30T00:44:11Z
[ "python", "aws-lambda", "amazon-ses" ]
Receive and Parse Emails on AWS SES
39,216,839
<p>I want to setup a Lambda function to parse incoming emails to SES. I followed the documentation and setup the receipt rules. </p> <p>I tested out my script by storing a MIME email in a txt file, parsing the email, and storing required info in a JSON document to be stored in a database. Now, I'm unsure of how to acc...
0
2016-08-29T23:48:28Z
39,332,587
<p>You can set up an Action in your SES Rules Set to automatically PUT your email files into S3. Then you set up an event in S3 (for a specific bucket) to trigger your lambda function. With that, you will be able to retrieve the email with something like this:</p> <pre><code>def lambda_handler(event, context): fo...
0
2016-09-05T14:18:49Z
[ "python", "aws-lambda", "amazon-ses" ]
How to plot PCA `loadings` and `loading.label` like R's `autoplot` w/ `matplotlib` and `sklearn`?
39,216,897
<p>I saw this tutorial in <code>R</code> w/ <code>autoplot</code>. They plotted the loadings and loading labels:</p> <pre><code>autoplot(prcomp(df), data = iris, colour = 'Species', loadings = TRUE, loadings.colour = 'blue', loadings.label = TRUE, loadings.label.size = 3) </code></pre> <p><a href="...
2
2016-08-29T23:55:31Z
39,234,799
<p>I found the answer here by @teddyroland: <a href="https://github.com/teddyroland/python-biplot/blob/master/biplot.py" rel="nofollow">https://github.com/teddyroland/python-biplot/blob/master/biplot.py</a></p>
1
2016-08-30T18:36:20Z
[ "python", "matplotlib", "plot", "ggplot2", "pca" ]
/Library/Python/2.7/site-packages directory empty
39,216,936
<p>When I cd into the /Library/Python/2.7/site-packages directory, there is only a README file. Where are all the third-party modules I installed such as sklearn?</p>
0
2016-08-30T00:01:01Z
39,216,969
<p>Probably you installed the packages for a different version of python, or you installed them locally (in your home dir, not system-wide).</p> <p>Inside a Python shell, type this:</p> <pre><code>import sklearn print (sklearn.__file__) </code></pre> <p>That will tell you where the package is located.</p>
1
2016-08-30T00:05:56Z
[ "python" ]
string to base64 bytes, exactly with the same literal chars
39,216,947
<p>today I got stucked with the following issue. I can explain it better with the inverse purpose: Say we have the following base64-variable,</p> <pre><code>b64_var = b'aGVsbG8gd29ybGQ=' </code></pre> <p>Imagine that what we want it's not to decode it into string object of python, namely,</p> <pre><code>base64.b64de...
0
2016-08-30T00:02:13Z
39,217,360
<p>Is this doing what you want?</p> <pre><code>b64_var = b'aGVsbG8gd29ybGQ=' print(repr(b64_var)) # b'aGVsbG8gd29ybGQ=' print(repr(b64_var)[1:]) # 'aGVsbG8gd29ybGQ=' print('b' + repr(b64_var)[1:]) # b'aGVsbG8gd29ybGQ=' </code></pre>
0
2016-08-30T01:06:48Z
[ "python", "string", "python-3.x", "base64", "literals" ]
string to base64 bytes, exactly with the same literal chars
39,216,947
<p>today I got stucked with the following issue. I can explain it better with the inverse purpose: Say we have the following base64-variable,</p> <pre><code>b64_var = b'aGVsbG8gd29ybGQ=' </code></pre> <p>Imagine that what we want it's not to decode it into string object of python, namely,</p> <pre><code>base64.b64de...
0
2016-08-30T00:02:13Z
39,225,738
<p>Ok, I found the problem, it was easier as I expected.</p> <p>First I am going to try to clarify what actually I wanted to do,</p> <pre><code>str_var = 'aGVsbG8gd29ybGQ=' # str_var: string b64_var = fun_str_2_b64samechars(str_var) # b64_var: bytes (b64) </code></pre> <p>Console,</p> <pre><code>b6...
0
2016-08-30T11:01:55Z
[ "python", "string", "python-3.x", "base64", "literals" ]
Module has not attrbiute many2one - Odoo v9 community
39,217,019
<p>I'm adding a field to a model froma custom module in Odoov9 Community edition.</p> <p>Like this:</p> <pre><code>import logging from openerp import api, fields, models, _ from openerp.exceptions import UserError, ValidationError from openerp.tools.safe_eval import safe_eval as eval class refund(models.Model): """...
1
2016-08-30T00:13:01Z
39,219,459
<p>If you are inheriting from an already defined module, you don't need to define the <code>_name</code> variable, just defining the <code>_inherit</code> variable will work too.</p> <p>You were getting the error "Module has not attrbiute many2one", as you were importing the <code>fields</code> for the new api but def...
2
2016-08-30T05:37:26Z
[ "python", "openerp", "odoo-9" ]
How can I tell in my django view, which of the 2 forms' fields were filled?
39,217,044
<p>I want to display both <code>form1</code> and <code>form2</code> on a web page. If <code>form2</code> is filled (<code>if success == True</code>), I want my view to not execute <code>if form1.is_valid:</code></p> <p>(which gives errors). How can I access the value of <code>success</code> in views.py?</p> <p>for...
0
2016-08-30T00:16:56Z
39,217,094
<p>For your <code>&lt;input /&gt;</code> or <code>&lt;button&gt;&lt;/button&gt;</code> tag, use a <code>name</code> parameter for each form (i.e.):</p> <pre><code>&lt;button type="submit" name="form_1"&gt;Go!&lt;/button&gt; </code></pre> <p>Then, in your view, do something like:</p> <pre><code>if form2.is_valid() an...
0
2016-08-30T00:23:54Z
[ "python", "django", "django-forms", "django-views" ]
How can I tell in my django view, which of the 2 forms' fields were filled?
39,217,044
<p>I want to display both <code>form1</code> and <code>form2</code> on a web page. If <code>form2</code> is filled (<code>if success == True</code>), I want my view to not execute <code>if form1.is_valid:</code></p> <p>(which gives errors). How can I access the value of <code>success</code> in views.py?</p> <p>for...
0
2016-08-30T00:16:56Z
39,222,503
<p>Setting <code>success = False</code> as you've done in the clean method only sets it locally. Store the value on the class (<code>self.success = False</code>) or in the cleaned_data (<code>self.cleaned_data['success'] = False</code>, assuming your form has no field called success).</p> <p>Then, you can access the v...
0
2016-08-30T08:32:52Z
[ "python", "django", "django-forms", "django-views" ]
Finding the length of the longest repeating 1s in a string
39,217,188
<p>I was wondering how one can find the length of the longest repeating 1s in a string of 1s and 0s in python, taking into account the empty string. like<code>'1011110111111'</code> would return <code>6</code> and <code>''</code> would return <code>0</code>.</p> <p>A past post suggested using regex,</p> <p><code>max(...
-1
2016-08-30T00:37:09Z
39,217,253
<p>Just split the string using '0' as separator and find the longest item in the list:</p> <pre><code>s = '1011110111111' result = len(max(s.split('0'))) </code></pre>
6
2016-08-30T00:47:47Z
[ "python" ]
How to colorize Django test results in OSX terminal?
39,217,201
<p>I'd like to colorize the Django test outputs with the nice visual queues of "green=pass, red=failure" font colors in the terminal, similar to what I get with rails/rake (e.g. ....F..FF.... where F is red for failure and the dots are green for passing unit tests). Anyone know how to do this easily? Is there a bash_...
0
2016-08-30T00:38:22Z
39,222,952
<p>Django has it <a href="https://docs.djangoproject.com/en/dev/ref/django-admin/#syntax-coloring" rel="nofollow">built-in</a>.</p> <p>The colors used for syntax highlighting can be customized. Django ships with three color palettes:</p> <ul> <li>dark, suited to terminals that show white text on a black background. T...
0
2016-08-30T08:56:47Z
[ "python", "django", "osx", "terminal" ]
Python telnetlib.expect() dot character '.' not working as expected
39,217,235
<p>I am trying to automate generic telnet connections. I am relying heavily on REGEX to handle different login prompts. Currently, I am using the regex <code>[Ll]ogin</code>, but the prompt causing me problems is the standard Ubuntu prompt:</p> <pre><code>b-davis login: Password: Last login: Mon Aug 29 20:28:24 EDT ...
0
2016-08-30T00:44:00Z
39,217,353
<p>I think the following line:</p> <pre><code>if re.search("[Ll]ogin$",s) is not None: </code></pre> <p>should be replaced with:</p> <pre><code>if re.search("[Ll]ogin", s) is not None: # NOTE: No `$` </code></pre> <p>OR using simple string operations:</p> <pre><code>if 'login' in s.lower(): </code></pre> <p>beca...
0
2016-08-30T01:05:44Z
[ "python", "regex", "telnet", "telnetlib" ]
No conversion for undefined on selection field - Odoo v9 community
39,217,313
<p>I have a selection field on a module for Odoov9 Community</p> <p>But, everytime, I click on it, to select a record it throws me this error:</p> <pre><code>Error: No conversion for undefined http://localhost:8070/web/static/src/js/framework/pyeval.js:732 Traceback: wrap@http://localhost:8070/web/static/src/js/fram...
0
2016-08-30T00:56:55Z
39,336,832
<ol> <li><p>You can't use QWeb for normal view definitions (formular, tree, search, etc.).</p></li> <li><p>You can't use dot-notation on normal view field definitions.</p></li> </ol> <p>So first off create a related <code>Char</code> field on the model your view is for. Then just define a simple field in the view.</p>...
1
2016-09-05T19:47:46Z
[ "javascript", "python", "openerp", "odoo-9" ]
how to split 'number' to separate columns in pandas DataFrame
39,217,347
<p>I have a dataframe;</p> <pre><code>df=pd.DataFrame({'col1':[100000,100001,100002,100003,100004]}) col1 0 100000 1 100001 2 100002 3 100003 4 100004 </code></pre> <p>I wish I could get the result below;</p> <pre><code> col1 col2 col3 0 10 00 00 1 10 00 01 2 ...
1
2016-08-30T01:04:52Z
39,217,425
<pre><code># make string version of original column, call it 'col' df['col'] = df['col1'].astype(str) # make the new columns using string indexing df['col1'] = df['col'].str[0:2] df['col2'] = df['col'].str[2:4] df['col3'] = df['col'].str[4:6] # get rid of the extra variable (if you want) df.drop('col', axis=1, inplac...
1
2016-08-30T01:15:52Z
[ "python", "pandas", "numpy", "dataframe", "split" ]
how to split 'number' to separate columns in pandas DataFrame
39,217,347
<p>I have a dataframe;</p> <pre><code>df=pd.DataFrame({'col1':[100000,100001,100002,100003,100004]}) col1 0 100000 1 100001 2 100002 3 100003 4 100004 </code></pre> <p>I wish I could get the result below;</p> <pre><code> col1 col2 col3 0 10 00 00 1 10 00 01 2 ...
1
2016-08-30T01:04:52Z
39,217,444
<p>One option is to use <code>extractall()</code> method with regex <code>(\d{2})(\d{2})(\d{2})</code> which captures every other two digits as columns. <code>?P&lt;col1&gt;</code> is the name of the captured group which will be converted to the column names:</p> <pre><code>df.col1.astype(str).str.extractall("(?P&lt;c...
2
2016-08-30T01:18:59Z
[ "python", "pandas", "numpy", "dataframe", "split" ]
Secret key is there though it is saying no secret key in django
39,217,362
<p>When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/mana...
0
2016-08-30T01:07:04Z
39,217,496
<p>Then try:</p> <pre><code>python manage.py runserver --settings=kgecweb.settings.development </code></pre> <p>I guess your didn't use the build-in setting.py or you rename it or make a directory to handle different settings.py.</p> <h3>EDIT</h3> <ul> <li><p>Make sure your project in your python path, use this to...
1
2016-08-30T01:25:21Z
[ "python", "django" ]