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 |
|---|---|---|---|---|---|---|---|---|---|
Beginner in Python, can't get this for loop to stop | 39,369,347 | <pre><code>Bit_128 = 0
Bit_64 = 0
Bit_32 = 0
Bit_64 = 0
Bit_32 = 0
Bit_16 = 0
Bit_8 = 0
Bit_4 = 0
Bit_2 = 0
Bit_1 = 0
Number = int(input("Enter number to be converted: "))
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
if place_value == 128:
Bit_128 = 1
elif place_value == 64:
... | 0 | 2016-09-07T11:58:39Z | 39,369,722 | <p>Just using "break" statement , to break the current loop when the condition is satisfied.</p>
| 0 | 2016-09-07T12:15:38Z | [
"python",
"for-loop"
] |
ModelForm won't validate because missing value, but model field has null=True | 39,369,364 | <p>I have a problem where my <code>ModelForm</code> is trying to assign <code>''</code> to a field (it saves fine if I actually provide the primary key of the <code>Product</code>, but it's not a compulsory field, and won't save if the field is left blank). I take it that the ORM it's trying to set that field to <code>... | 0 | 2016-09-07T11:59:20Z | 39,369,599 | <p>Try adding <code>blank=True</code> too.</p>
<p><code>null=True</code> means that this field is allowed to be NULL in database.</p>
<p><code>blank=True</code> means it can be submitted without a value in forms. Otherwise it must have value.</p>
| 4 | 2016-09-07T12:09:48Z | [
"python",
"django"
] |
python ldap3 bulk delete users and groups | 39,369,546 | <p>Is there any way to delete from AD pack of objects with python ldap3?
Something like </p>
<pre><code>conn.delete("(CN='auto*'),CN=Users,DC=mycompany,DC=com")
</code></pre>
<p>doesn't find any</p>
<p>TIA!</p>
| 0 | 2016-09-07T12:07:23Z | 39,398,772 | <p>You can't. The LDAP protocol doesn't allow such an operation. You must use a conn.delete() for each user to delete.</p>
| 0 | 2016-09-08T19:27:53Z | [
"python",
"active-directory",
"ldap3"
] |
Matplotlib global legend for lots of subplots | 39,369,557 | <p>i have some problem figuring out how to force matplotlib to add a legend where i want. </p>
<p>The figures i currently have look like this:
<a href="http://i.stack.imgur.com/wZOKM.png" rel="nofollow"><img src="http://i.stack.imgur.com/wZOKM.png" alt="enter image description here"></a></p>
<p><a href="http://i.stac... | 0 | 2016-09-07T12:07:52Z | 39,372,106 | <p>Try using a <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend" rel="nofollow">figure legend</a> which will let you create a legend for <a href="http://matplotlib.org/examples/pylab_examples/figlegend_demo.html" rel="nofollow">any of the lines plotted in</a> your figure and position it re... | 0 | 2016-09-07T14:05:47Z | [
"python",
"python-3.x",
"matplotlib"
] |
Python calculate minimum distances between multiple coordinates | 39,369,559 | <p>I have files in two type:
A: contains 1206 lines of coordinates (xyz) - a protein chain
B: contains 114 lines of coordinates (xyz) - a bunch of molecule</p>
<p>I would like to do the followings:
For each line of A calculate distance from each line of B. So I get 114 distance value for each line of A. But I don't n... | 0 | 2016-09-07T12:08:12Z | 39,370,044 | <p>Your code is pretty confusing and I can see a few mistakes.</p>
<p>You're using <code>minimum</code> outside of the <code>for</code> loop, so only its last value is written.</p>
<p>Also, the way you computes <code>minimum</code> is wierd. <code>szamok</code> is not used, nor is <code>x</code> (since you use anothe... | 1 | 2016-09-07T12:31:33Z | [
"python",
"coordinates",
"distance",
"bioinformatics"
] |
Can I store a file (HDF5 file) in another file with serialization? | 39,369,671 | <p>I have a HDF5 file and a list of objects that I need to store for saving functionality. For simplicity I want to create only one save file. Can I store H5 file, in my save file that I create with serialization (pickle) without opening H5 file. </p>
| 0 | 2016-09-07T12:13:11Z | 39,386,944 | <p>You can put several files in one by using <a href="https://docs.python.org/3/library/zipfile.html" rel="nofollow">zipfile</a> or <a href="https://docs.python.org/3/library/tarfile.html" rel="nofollow">tarfile</a></p>
<ul>
<li>for zipfile you would <code>write</code> the database files and <code>writestr</code> your... | 1 | 2016-09-08T09:11:31Z | [
"python",
"serialization",
"pickle",
"hdf5"
] |
best way to get an integer from string without using regex | 39,369,711 | <p>I would like to get some integers from a string (the 3rd one). Preferable without using regex. </p>
<p>I saw a lot of stuff.</p>
<p>my string:</p>
<pre><code>xp = '93% (9774/10500)'
</code></pre>
<p>So i would like the code to return a list with integers from a string. So the desired output would be: <code>[93, ... | 0 | 2016-09-07T12:15:13Z | 39,369,887 | <p>Using regex (sorry!) to split the string by a non-digit, then filter on digits (can have empty fields) and convert to int.</p>
<pre><code>import re
xp = '93% (9774/10500)'
print([int(x) for x in filter(str.isdigit,re.split("\D+",xp))])
</code></pre>
<p>result:</p>
<pre><code>[93, 9774, 10500]
</code></pre>
| 1 | 2016-09-07T12:23:21Z | [
"python",
"string",
"int"
] |
best way to get an integer from string without using regex | 39,369,711 | <p>I would like to get some integers from a string (the 3rd one). Preferable without using regex. </p>
<p>I saw a lot of stuff.</p>
<p>my string:</p>
<pre><code>xp = '93% (9774/10500)'
</code></pre>
<p>So i would like the code to return a list with integers from a string. So the desired output would be: <code>[93, ... | 0 | 2016-09-07T12:15:13Z | 39,369,911 | <p>Since the problem is that you have to split on different chars, you can first replace everything that's not a digit by a space then split, a one-liner would be :</p>
<pre><code> xp = '93% (9774/10500)'
''.join([ x if x.isdigit() else ' ' for x in xp ]).split() # ['93', '9774', '10500']
</code></pre>
| 7 | 2016-09-07T12:24:33Z | [
"python",
"string",
"int"
] |
best way to get an integer from string without using regex | 39,369,711 | <p>I would like to get some integers from a string (the 3rd one). Preferable without using regex. </p>
<p>I saw a lot of stuff.</p>
<p>my string:</p>
<pre><code>xp = '93% (9774/10500)'
</code></pre>
<p>So i would like the code to return a list with integers from a string. So the desired output would be: <code>[93, ... | 0 | 2016-09-07T12:15:13Z | 39,369,962 | <p>Since the <em>format is fixed</em>, you can use consecutive <code>split()</code>.
It's not very pretty, or general, but sometimes the direct and "stupid" solution is not so bad:</p>
<pre><code>a, b = xp.split("%")
x = int(a)
y = int(b.split("/")[0].strip()[1:])
z = int(b.split("/")[1].strip()[:-1])
print(x, y, z) #... | -1 | 2016-09-07T12:27:16Z | [
"python",
"string",
"int"
] |
best way to get an integer from string without using regex | 39,369,711 | <p>I would like to get some integers from a string (the 3rd one). Preferable without using regex. </p>
<p>I saw a lot of stuff.</p>
<p>my string:</p>
<pre><code>xp = '93% (9774/10500)'
</code></pre>
<p>So i would like the code to return a list with integers from a string. So the desired output would be: <code>[93, ... | 0 | 2016-09-07T12:15:13Z | 39,371,143 | <p>Since this is Py2, using <code>str</code>, it looks like you don't need to consider the full Unicode range; since you're doing this more than once, you can slightly improve on <a href="http://stackoverflow.com/a/39369911/364696">polku's answer</a> using <code>str.translate</code>:</p>
<pre><code># Create a translat... | 0 | 2016-09-07T13:24:14Z | [
"python",
"string",
"int"
] |
Functions get called more and more times with reopening plugin | 39,369,712 | <p>I have a QGIS plugin written in Python 2.7.3 with PyQt 4.9.1, Qt 4.8.1. When I run this plugin every function works just fine. But when I close the window and reopen it again, every function happens twice. Then I close/open again and it goes 3 times, etc., etc.</p>
<p>Where should I look for an error here? My <code... | 0 | 2016-09-07T12:15:15Z | 39,397,887 | <p>Every time you call <code>connect</code>, it adds another connection - even if it's to the same slot. So you need to move the connections out of the <code>run()</code> method and put them in the setup method for the dialog, so that they are only made once.</p>
| 0 | 2016-09-08T18:29:35Z | [
"python",
"qt",
"pyqt",
"qgis"
] |
How to find the directory of the .app that a python script is running from | 39,369,746 | <p>I recently made a python script that goes through files in whatever directory it is placed in and renames them based on certain criteria. The script works perfectly, and I compiled the script into an OS X .app using py2app. This worked fine as well. However now when I run the script, it searches through the files in... | 0 | 2016-09-07T12:16:46Z | 39,369,800 | <p>Try to use:</p>
<pre><code>import os
print(os.getcwd())
</code></pre>
<p>From docs:</p>
<blockquote>
<p><strong>getcwd()</strong></p>
<p>Return a unicode string representing the current working directory.</p>
</blockquote>
| 0 | 2016-09-07T12:19:18Z | [
"python",
"osx",
"python-3.x",
"py2app"
] |
How to find the directory of the .app that a python script is running from | 39,369,746 | <p>I recently made a python script that goes through files in whatever directory it is placed in and renames them based on certain criteria. The script works perfectly, and I compiled the script into an OS X .app using py2app. This worked fine as well. However now when I run the script, it searches through the files in... | 0 | 2016-09-07T12:16:46Z | 39,370,161 | <p>To find the location of the <code>.app</code> directory that wraps the application, the most direct way is to modify the path that you find with your current code. After computing <code>src</code> as you did, just trim it like this and use <code>app</code> as the path:</p>
<pre><code>import re
...
app, rest = re.sp... | 0 | 2016-09-07T12:36:35Z | [
"python",
"osx",
"python-3.x",
"py2app"
] |
Simplest way to plot 3d sphere by python? | 39,369,766 | <p>This is the simplest as I know:</p>
<pre><code>from visual import *
ball1=sphere(pos=vector(x,y,z),radius=radius,color=color)
</code></pre>
<p>Which alternatives can you suggest?</p>
| 0 | 2016-09-07T12:17:55Z | 39,370,789 | <p>See <a href="http://docs.enthought.com/mayavi/mayavi/index.html" rel="nofollow">Mayavi</a> library for 3D visualization and some examples to draw a sphere. It should work with Python 2.7. </p>
<p>Enjoy!</p>
| 1 | 2016-09-07T13:08:05Z | [
"python",
"python-2.7",
"3d",
"render"
] |
python & pandas - How to calculate frequency under conditions in columns in DataFrame? | 39,369,820 | <p>I have a series of data in a DataFrame called <code>frames</code>:</p>
<pre><code> NoUsager Sens IdVehiculeUtilise NoConducteur NoAdresse Fait NoDemande Periods
0 000001 + 287Véh 000087 000079 1 42196000013 Matin
1 000001 - 287Véh 000087 000079 1 42196... | 1 | 2016-09-07T12:20:34Z | 39,369,923 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by columns which will be <code>indexes</code> (<code>NoUsager</code>,<code>Sens</code>,<code>Periods</code>) in output df. Then need add column (<code>NoAdresse</code... | 1 | 2016-09-07T12:25:30Z | [
"python",
"pandas",
"dataframe"
] |
SQLAlchemy Python 3 Ubuntu 16.04 | 39,369,897 | <p>I can't seem to install the newest version of SQLAlchemy in my Python 3. Similar questions asked on stackoverflow are all pre-2016 and talk about older distributions of Ubuntu, hence again this question.</p>
<h2>System</h2>
<ul>
<li>Ubuntu 16.04</li>
<li>Python 2.7.12 (default if I call python in terminal)</li>
<l... | 0 | 2016-09-07T12:23:50Z | 39,369,932 | <p><code>pip</code> is only for installing Python 2 packages. To install a PyPI package for Python 3, you need to use <code>pip3</code>:</p>
<pre><code>pip3 install SQLAlchemy
</code></pre>
| 1 | 2016-09-07T12:25:58Z | [
"python",
"python-3.x",
"ubuntu",
"sqlalchemy"
] |
SQLAlchemy Python 3 Ubuntu 16.04 | 39,369,897 | <p>I can't seem to install the newest version of SQLAlchemy in my Python 3. Similar questions asked on stackoverflow are all pre-2016 and talk about older distributions of Ubuntu, hence again this question.</p>
<h2>System</h2>
<ul>
<li>Ubuntu 16.04</li>
<li>Python 2.7.12 (default if I call python in terminal)</li>
<l... | 0 | 2016-09-07T12:23:50Z | 39,369,935 | <p>Use virtualenv:</p>
<pre><code>pyvenv env
source env/bin/activate
pip install sqlalchemy
</code></pre>
<p>Command <code>pyvenv</code> creates virtualenv based on python 3.x.</p>
| 0 | 2016-09-07T12:26:04Z | [
"python",
"python-3.x",
"ubuntu",
"sqlalchemy"
] |
How to create an Azure API App using the .YAML file and Pithon code? | 39,369,919 | <p>One of my clients wants to host his API's in Azure, his APIs are developed in Python. I tried creating Azure API app in dot net and I am getting the successful result but I don't have any knowledge of Python, can anyone help me finding out how can I host these python API's in Azure?</p>
<p>The source file has a .YA... | 0 | 2016-09-07T12:25:18Z | 39,760,398 | <p>You can confirm to your customer, whether the Python APIs are in a complete Python web application.</p>
<p>There are several most popular python web frameworks your customer may use to build the APIs server, Flask, Django and Bottle. You can find the document about how to deploy these application to Azure Web Apps ... | 0 | 2016-09-29T02:27:02Z | [
"python",
"azure",
"yaml",
"azure-api-apps"
] |
Subprocess.Popen stdin in new console | 39,370,127 | <p>I want to execute a python subprocess in a new console. Once started, I want the user to be able to answer questions asked by this new process on stdin.</p>
<p>I tried the following code:</p>
<pre><code>p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, creati... | 1 | 2016-09-07T12:35:14Z | 39,371,602 | <p>As i'm not really interested in the stdout/stderr redirection, i tried this way: </p>
<p><code>subprocess.Popen(cmd, cwd=cwd, creationflags=subprocess.CREATE_NEW_CONSOLE)</code></p>
<p>It works fine now. I guess that it's not compatible to redirect standard input/outputs and to create a new console.</p>
| 1 | 2016-09-07T13:44:27Z | [
"python",
"subprocess",
"stdin"
] |
Py3.4 IMAPLib Login... 'str' does not support the buffer interface | 39,370,328 | <p>Using imaplib, I'm trying to connect to a mailserver.
When I include the password as just a normal string: 'password'
It connects fine. But I'm trying to slightly obfuscate my password, so I previously had run it through b64encode, and then used b64decode in the login:</p>
<pre><code>#Works:
mail.login('myloginnam... | 0 | 2016-09-07T12:45:22Z | 39,370,420 | <p>You are passing in a <code>bytes</code> object for the password, not a <code>str</code> value, because that's what <code>base64.b64decode()</code> returns.</p>
<p>You'd have to <em>decode</em> that value to a string:</p>
<pre><code> base64.b64decode('Ja3rHsnakhdgkhervc').decode('ascii')
</code></pre>
<p>The excep... | 0 | 2016-09-07T12:50:00Z | [
"python",
"python-3.x",
"base64",
"imaplib"
] |
Sending email with python | 39,370,412 | <p>I have the following code </p>
<pre><code>import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: We are blending baby !
This is a test e-mail message.
"""
try:
smtpObj = s... | -1 | 2016-09-07T12:49:39Z | 39,370,597 | <p>If the indentation of your code is as pasted, please indent your code correctly and check if it works:</p>
<pre><code>def email_sender():
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Person <[email protected]>
To: To Person <[email protected]... | 0 | 2016-09-07T12:58:23Z | [
"python",
"email"
] |
Understanding fragments of a Python/PuLP code | 39,370,442 | <p>I have to adopt an existing script where they used the PuLP package. I need to know how the result of the following line looks like:</p>
<pre><code>unit = ["one", "two", "three"]
time = range(10)
status=LpVariable.dicts("status",[(f,g) for f in unit for g in time],0,1,LpBinary)
</code></pre>
<p>How does the keys/... | 4 | 2016-09-07T12:51:14Z | 39,370,893 | <pre><code>from pulp import *
unit = ["one", "two"]
time = range(2)
status=LpVariable.dicts("status",[(f,g) for f in unit for g in time],0,1,LpBinary)
</code></pre>
<p>Leads to </p>
<pre><code>>>> status
{('two', 1): status_('two',_1),
('two', 2): status_('two',_2),
('one', 2): status_('one',_2),
('one'... | 1 | 2016-09-07T13:12:51Z | [
"python",
"pulp"
] |
Recalling data from a text document on python 3 | 39,370,474 | <p>I have made this script which will save players names followed by their scores. </p>
<p>I am looking to recall this data back into python so it can be sorted into a table in a UI.</p>
<p>Im sure its a simple solution but i can only find how to save to a text document.</p>
<pre><code> players=int(input("How man... | 0 | 2016-09-07T12:52:31Z | 39,370,846 | <p>There are multiple ways to do
1. you will reopen the your playerscores.txt file read the data from it store it in buffer sort it and write it again .
2. while tacking input store it in buffer sort them and then write on txt file. </p>
<pre><code>players=int(input("How many payers are there? "))
with open('playersc... | 0 | 2016-09-07T13:10:55Z | [
"python",
"python-3.x",
"serialization"
] |
Flask does not take WTForms input | 39,370,510 | <p>I'm tring to create an app with flask with WTForms.</p>
<p>In the controller.py i have:</p>
<pre><code>@mod_private.route('/portfolio/', methods=['GET', 'POST'])
@login_required
def portfolio():
print "in portfolio" # I read this
form = CreateCoinsForm(request.form)
if request.method == 'POST' and form.v... | 0 | 2016-09-07T12:53:53Z | 39,370,659 | <p>Your problem suggests that you are using the built-in CSRF protection on your form, and your form actually isn't validating because you haven't included the CSRF token. </p>
<p>Try adjusting your template like so:</p>
<pre><code><form method="post" action="/private/portfolio/" accept-charset="UTF-8" role="form"... | 2 | 2016-09-07T13:01:25Z | [
"python",
"flask",
"wtforms"
] |
Override get_instance import-export django | 39,370,528 | <p>I have a basic problem in Django/ Python. But I don't know the right answer.</p>
<p>I have to override "get_instance" in django-import-export.instance_loaders</p>
<p>Actually i change the code directly in this function. I know this is not very clever. But I don#t understand where I should override this function.</... | 0 | 2016-09-07T12:54:35Z | 39,371,045 | <p>Basically, you need to define custom <code>InstanceLoader</code> class in your resource inner <code>Meta</code> class:</p>
<pre><code>class BookResource(resources.ModelResource):
class Meta:
model = Book
fields = ('id', 'name', 'price',)
instance_loader_class = MyCustomInstanceLoaderCla... | 0 | 2016-09-07T13:19:57Z | [
"python",
"django"
] |
sample time series datasets R and python | 39,370,593 | <p>Since I am very lazy I don't want to spend time downloading datasets, loading them and perform pre-processing to test some sample functions on different timeseries. What are some sample timeseries datasets available with R and python? (which can be imported easily). For eg: there is the iris dataset (which can be ea... | 2 | 2016-09-07T12:58:01Z | 39,371,193 | <p>The python scikit package has access to the iris and other datasets:</p>
<p><a href="http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html</a>
<a href="http://scikit-learn.org/stable/modules/classes.h... | 1 | 2016-09-07T13:26:38Z | [
"python",
"time-series"
] |
sample time series datasets R and python | 39,370,593 | <p>Since I am very lazy I don't want to spend time downloading datasets, loading them and perform pre-processing to test some sample functions on different timeseries. What are some sample timeseries datasets available with R and python? (which can be imported easily). For eg: there is the iris dataset (which can be ea... | 2 | 2016-09-07T12:58:01Z | 39,371,361 | <p>In <code>R</code>, per @Kabulan0lak's comment, you can choose from different "preloaded" datasets. One way to see what you currently have available in your system is to type:</p>
<pre><code>data()
</code></pre>
<p>Since you're looking for time series data, I would suggest the <code>EuStockMarkets</code> dataset. Y... | 2 | 2016-09-07T13:34:13Z | [
"python",
"time-series"
] |
python decorate function call | 39,370,642 | <p>I recently learned about decorators and wondered if it's possible to use them not in a function definition but in a function call, as some kind of general wrapper.</p>
<p>The reason for that is, that I want to call functions from a module through a user-defined interface that does repeatable things to a function an... | -1 | 2016-09-07T13:00:46Z | 39,370,818 | <p>You could do something like that:</p>
<pre><code>def a(num):
return num * 1
def double(f):
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
return wrapped
print(double(a)(2))
</code></pre>
<p>It's because we can decorate functions and run functions using a decorator function explicit a... | 1 | 2016-09-07T13:09:27Z | [
"python",
"wrapper",
"decorator"
] |
python decorate function call | 39,370,642 | <p>I recently learned about decorators and wondered if it's possible to use them not in a function definition but in a function call, as some kind of general wrapper.</p>
<p>The reason for that is, that I want to call functions from a module through a user-defined interface that does repeatable things to a function an... | -1 | 2016-09-07T13:00:46Z | 39,371,706 | <p>There is a very good detailed section on decorators in Marty Alchin's book <strong>Pro Python</strong> from Apress.</p>
<p>While the new style @decorator syntax is only available to be used at function definition, you can use the older syntax, which does the same thing this way:</p>
<pre><code>from module import m... | 1 | 2016-09-07T13:48:27Z | [
"python",
"wrapper",
"decorator"
] |
Setting up Python's ArgumentParser with two mutually excluding flags where one flag has optional additional flags | 39,370,691 | <p>I would like to define the following using Python's ArgumentParser:</p>
<pre><code>--mutually_exclusive_flag_A stringParameter
--mutually_exclusive_flag_B stringParameter
--optional_b_flag_one
--optional_b_flag_two
</code></pre>
<p>One can use either mutually_exclusive_flag_A or mutually_exclusive_flag_B,... | 0 | 2016-09-07T13:02:54Z | 39,375,840 | <p><code>argparse</code> can't handle that complex of a test. Mutually exclusive groups can't be nested, and they don't handle other kinds of logic (only <code>xor</code>, not <code>and</code> and <code>or</code>). I've explored such an expansion in a Python bug/issue, but it's not a trivial addition.</p>
<p>The bes... | 0 | 2016-09-07T17:18:32Z | [
"python",
"python-3.x",
"argparse"
] |
Error in pip install matplotlib in Mac | 39,370,731 | <p>When I do </p>
<pre><code>pip install matplotlib --upgrade --user
</code></pre>
<p>I dont get any error but my program fails saying</p>
<pre><code>Traceback (most recent call last):
File "forest.py", line 22, in <module>
matplotlib.style.use('ggplot')
AttributeError: 'module' object has no attribute '... | 2 | 2016-09-07T13:04:58Z | 39,371,141 | <p>It seems like your first error is because you are searching for style in matplotlib and not matplotlib.pyplot. Normally, it should work anyway but try this.</p>
<p>Try changing this: </p>
<pre><code>matplotlib.style.use('ggplot')
</code></pre>
<p>By adding this in the beginning of your code:</p>
<pre><code>impor... | 0 | 2016-09-07T13:24:12Z | [
"python",
"osx",
"matplotlib"
] |
flask socket-io, sometimes client calls freeze the server | 39,370,848 | <p>I occasionally have a problem with flask socket-io freezing, and I have no clue how to fix it.</p>
<p>My client connects to my socket-io server and performs some chat sessions. It works nicely. But for some reason, sometimes from the client side, there is some call that blocks the whole server (The server is stuck ... | 0 | 2016-09-07T13:11:00Z | 39,394,019 | <p>According to your comment above, you are using the Flask development web server, without the help of an asynchronous framework such as eventlet or gevent. Besides this option being highly inefficient, you should know that this web server is not battle tested, it is meant for short lived tests during development. I'm... | 0 | 2016-09-08T14:48:43Z | [
"python",
"freeze",
"flask-socketio"
] |
extract hour from timestamp with python | 39,370,879 | <p>I have a dataframe df_energy2</p>
<pre><code>df_energy2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29974 entries, 0 to 29973
Data columns (total 4 columns):
TIMESTAMP 29974 non-null datetime64[ns]
P_ACT_KW 29974 non-null int64
PERIODE_TARIF 29974 non-null object
P_SOUSCR ... | 3 | 2016-09-07T13:12:21Z | 39,370,905 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html" rel="nofollow"><code>dt.hour</code></a>:</p>
<pre><code>print (df.TIMESTAMP.dt.hour)
0 0
1 0
Name: TIMESTAMP, dtype: int64
df['hours'] = df.TIMESTAMP.dt.hour
print (df)
TIMESTAMP P_ACT_KW ... | 2 | 2016-09-07T13:13:19Z | [
"python",
"datetime",
"pandas",
"extract",
"hour"
] |
extract hour from timestamp with python | 39,370,879 | <p>I have a dataframe df_energy2</p>
<pre><code>df_energy2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29974 entries, 0 to 29973
Data columns (total 4 columns):
TIMESTAMP 29974 non-null datetime64[ns]
P_ACT_KW 29974 non-null int64
PERIODE_TARIF 29974 non-null object
P_SOUSCR ... | 3 | 2016-09-07T13:12:21Z | 39,371,167 | <p>Given your data:</p>
<blockquote>
<pre><code>df_energy2.head()
TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR
2016-01-01 00:00:00 116 HC 250
2016-01-01 00:10:00 121 HC 250
</code></pre>
</blockquote>
<p>You have timestamp as the index. For extracting hours from timestamp where you have it as the index of the datafram... | 0 | 2016-09-07T13:25:35Z | [
"python",
"datetime",
"pandas",
"extract",
"hour"
] |
Static class property pointing to special instance of the same class in Python | 39,370,891 | <p>Coming from cpp/c#, how does one refer to the same class in the class body in Python:</p>
<pre><code>class Foo(object):
ANSWER = Foo(42)
FAIL = Foo(-1)
def __init__(self, value):
self._v = value
</code></pre>
<p>When I try to use this code, I get "name 'Foo' is not defined" exception in a line... | 0 | 2016-09-07T13:12:44Z | 39,371,121 | <p>The name <code>Foo</code> is not set until the full class body has been executed. The only way you can do what you want is to add attributes to the class <em>after</em> the <code>class</code> statement has completed:</p>
<pre><code>class Foo(object):
def __init__(self, value):
self._v = value
Foo.A... | 1 | 2016-09-07T13:23:15Z | [
"python",
"class"
] |
Python PYQT Tabs outside app window [why] | 39,370,970 | <p>Tabs added before app.exec_() is called look and act as any other tabs u met, though if adding another after the app.exec_() call makes the new tab 'detach' from the main app window. Pic below :)</p>
<p>Why? How can I make it move inside the window?</p>
<pre><code>import threading
import time
import sys
from PyQt... | 0 | 2016-09-07T13:16:35Z | 39,373,790 | <p>It works with QTimer or signals:</p>
<pre><code>import sys
import time
from PyQt5.QtCore import QObject
from PyQt5.QtCore import QThread
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets im... | 0 | 2016-09-07T15:20:51Z | [
"python",
"python-3.x",
"user-interface",
"pyqt",
"pyqt5"
] |
How to insert strings and slashes in a path? | 39,370,988 | <p>I'm trying to extract tar.gz files which are situated in diffent files named srm01, srm02 and srm03.
The file's name must be in input (a string) to run my code.
I'm trying to do something like this :</p>
<pre><code>import tarfile
import glob
thirdBloc = 'srm01' #Then, that must be 'srm02', or 'srm03'
for f in glob... | 0 | 2016-09-07T13:17:04Z | 39,371,267 | <p>In order to join paths you have to use <a href="https://docs.python.org/2/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join</code></a> as follow:</p>
<pre><code>import os
import tarfile
import glob
thirdBloc = 'srm01' #Then, that must be 'srm02', or 'srm03'
for f in glob.glob(os.path.join('C://... | 2 | 2016-09-07T13:30:30Z | [
"python",
"python-2.7",
"filepath",
"glob",
"tarfile"
] |
How to insert strings and slashes in a path? | 39,370,988 | <p>I'm trying to extract tar.gz files which are situated in diffent files named srm01, srm02 and srm03.
The file's name must be in input (a string) to run my code.
I'm trying to do something like this :</p>
<pre><code>import tarfile
import glob
thirdBloc = 'srm01' #Then, that must be 'srm02', or 'srm03'
for f in glob... | 0 | 2016-09-07T13:17:04Z | 39,371,314 | <p>os.path.join will create the correct paths for your filesystem</p>
<pre><code>f = os.path.join('C://Users//asediri//Downloads/srm/', thirdBloc, '*.tar.gz')
</code></pre>
| 0 | 2016-09-07T13:32:26Z | [
"python",
"python-2.7",
"filepath",
"glob",
"tarfile"
] |
How to insert strings and slashes in a path? | 39,370,988 | <p>I'm trying to extract tar.gz files which are situated in diffent files named srm01, srm02 and srm03.
The file's name must be in input (a string) to run my code.
I'm trying to do something like this :</p>
<pre><code>import tarfile
import glob
thirdBloc = 'srm01' #Then, that must be 'srm02', or 'srm03'
for f in glob... | 0 | 2016-09-07T13:17:04Z | 39,371,336 | <p><code>C://Users//asediri//Downloads/srm/srm01\20160707000001-server.log.1.tar.gz</code></p>
<p>Never use \ with python for filepaths, \201 is \x81 character. It results to this:</p>
<p><code>C://Users//asediri//Downloads/srm/srm01ü60707000001-server.log.1.tar.gz</code></p>
<p>this is why os.path.exists does not ... | 0 | 2016-09-07T13:33:19Z | [
"python",
"python-2.7",
"filepath",
"glob",
"tarfile"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,371,182 | <p><strong>Approach #1</strong></p>
<p>You can simulate that iterator dependency criteria for a vectorized solution using a <code>triangular matrix</code>. This is based on <a href="http://stackoverflow.com/a/36045511/3293881"><code>this post</code></a> that dealt with multiplication involving <code>iterator dependenc... | 0 | 2016-09-07T13:26:14Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,371,197 | <p>Python itself is a highly-dynamic, slow, language. The idea in numpy is to use <a href="https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/ch04.html" rel="nofollow">vectorization</a>, and avoid explicit loops. In this case, you can use <a href="http://docs.scipy.org/doc/numpy/reference/gene... | 1 | 2016-09-07T13:26:49Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,371,224 | <blockquote>
<p>I wonder why whatever I tried Python is 100x or more slower than an equivalent C code.</p>
</blockquote>
<p>Because Python programs are usually 100x slower than C programs.</p>
<p>You can either implement critical code paths in C and provide Python-C bindings, or change the algorithm. You can write ... | 0 | 2016-09-07T13:28:03Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,371,652 | <p>This solution using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package has complexity n Log n, and is fully vectorized; so not terribly different from C performance, in all likelihood.</p>
<pre><code>import numpy_indexed as npi
dpl = np.flatnonzero(npi.mu... | 0 | 2016-09-07T13:46:13Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,371,741 | <p>The obvious question is why you want to do this in this way. NumPy arrays are intended to be opaque data structures â by this I mean NumPy arrays are intended to be created inside the NumPy system and then operations sent in to the NumPy subsystem to deliver a result. i.e. NumPy should be a black box into which yo... | 0 | 2016-09-07T13:49:30Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,372,054 | <p>As an alternative to Ami Tavory's answer, you can use a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow">Counter</a> from the collections package to detect duplicates. On my computer it seems to be even faster. See the function below which can also find different duplic... | 0 | 2016-09-07T14:03:34Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,373,909 | <p>This runs in 8 ms compared to 18 s for your code and doesn't use any strange libraries. It's similar to the approach by @vs0, but I like <code>defaultdict</code> more. It should be approximately O(N).</p>
<pre><code>from collections import defaultdict
dupl = []
counter = 0
indexes = defaultdict(list)
for i, e in e... | 0 | 2016-09-07T15:26:21Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
efficient loop over numpy array | 39,371,021 | <p>Versions of this question have already been asked but I have not found a satisfactory answer.</p>
<p><strong>Problem</strong>: given a large numpy vector, find indices of the vector elements which are duplicated (a variation of that could be comparison with tolerance). </p>
<p>So the problem is ~O(N^2) and memory ... | 3 | 2016-09-07T13:19:02Z | 39,468,387 | <p>Since the answers have stopped coming and none was totally satisfactory, for the record I post my own solution.</p>
<p>It is my understanding that it's the assignment which makes Python slow in this case, not the nested loops as I thought initially. Using a library or compiled code eliminates the need for assignmen... | 0 | 2016-09-13T11:00:08Z | [
"python",
"arrays",
"loops",
"numpy",
"optimization"
] |
Read a complete data file and round numbers to 2 decimal places and save it with the same format | 39,371,050 | <p>I am trying to learn python and I have the intention to make the a very big data file smaller and later do some statistical Analysis with R. I need to read the data file (see below):</p>
<pre><code>SCALAR
ND 3
ST 0
TS 10.00
0.0000
0.0000
0.0000
SCALAR
ND 3
ST 0
TS 3600.47
255.1744
255.0201
255.2... | 0 | 2016-09-07T13:20:16Z | 39,371,222 | <p>Try <code>"%.2f" % float(columns[1])</code> to round to two decimal places. Note that it gives you a string, not a float. I don't understand the rest of what you're asking.</p>
<p><code>>>> "%.2f" % 255.5984</code><br>
<code>'255.60'</code> </p>
| 1 | 2016-09-07T13:27:52Z | [
"python",
"statistics",
"string-formatting",
"data-type-conversion"
] |
Read a complete data file and round numbers to 2 decimal places and save it with the same format | 39,371,050 | <p>I am trying to learn python and I have the intention to make the a very big data file smaller and later do some statistical Analysis with R. I need to read the data file (see below):</p>
<pre><code>SCALAR
ND 3
ST 0
TS 10.00
0.0000
0.0000
0.0000
SCALAR
ND 3
ST 0
TS 3600.47
255.1744
255.0201
255.2... | 0 | 2016-09-07T13:20:16Z | 39,371,612 | <p>The code doesn't execute correctly (where is selecting maximum num or saving to output or ...),
please put the fixed one,
but if you have only trouble in float function you can choose %.2f or round(num,2)</p>
| 1 | 2016-09-07T13:44:51Z | [
"python",
"statistics",
"string-formatting",
"data-type-conversion"
] |
Read a complete data file and round numbers to 2 decimal places and save it with the same format | 39,371,050 | <p>I am trying to learn python and I have the intention to make the a very big data file smaller and later do some statistical Analysis with R. I need to read the data file (see below):</p>
<pre><code>SCALAR
ND 3
ST 0
TS 10.00
0.0000
0.0000
0.0000
SCALAR
ND 3
ST 0
TS 3600.47
255.1744
255.0201
255.2... | 0 | 2016-09-07T13:20:16Z | 39,371,684 | <p>Here is how to convert some float to a string with 2 decimals with the <code>format</code> syntax (the new python2/3 formating syntax):</p>
<pre><code>"{:.2f}".format(some_float)
</code></pre>
<p>Regarding the rest of your question: your code does not seems to correctly deal with the format of your text file. You ... | 1 | 2016-09-07T13:47:20Z | [
"python",
"statistics",
"string-formatting",
"data-type-conversion"
] |
Read a complete data file and round numbers to 2 decimal places and save it with the same format | 39,371,050 | <p>I am trying to learn python and I have the intention to make the a very big data file smaller and later do some statistical Analysis with R. I need to read the data file (see below):</p>
<pre><code>SCALAR
ND 3
ST 0
TS 10.00
0.0000
0.0000
0.0000
SCALAR
ND 3
ST 0
TS 3600.47
255.1744
255.0201
255.2... | 0 | 2016-09-07T13:20:16Z | 39,372,143 | <p>The first part can be done easily if it can be assumed that the floats that require rounding occur only on lines by themselves. That excludes lines that are prefixed with alpha chars, e.g. <code>TS 3600.47</code>.</p>
<pre><code>from __future__ import print_function
with open('data.txt') as f, open('output.tx... | 1 | 2016-09-07T14:07:29Z | [
"python",
"statistics",
"string-formatting",
"data-type-conversion"
] |
How to convert 007898989 to 7898989 in Python | 39,371,186 | <p>I am trying to convert <code>007898989</code> to <code>7898989</code> in Python using the following code:</p>
<pre><code>long(007898989)
</code></pre>
<p>However this leads to the following error:</p>
<pre><code>>>> long(007898989)
File "<stdin>", line 1
long(007898989)
^
Syn... | -3 | 2016-09-07T13:26:27Z | 39,371,307 | <p>Indeed, doing this:</p>
<pre><code>a = 007898989
</code></pre>
<p>will raise the error <code>SyntaxError: invalid token</code>, the easiest way to convert to long would be:</p>
<p><strong>On Python 2</strong></p>
<pre><code>a = long("007898989")
print a
</code></pre>
<p>Trying this cast on python 3 would give <... | 4 | 2016-09-07T13:32:14Z | [
"python"
] |
How to convert 007898989 to 7898989 in Python | 39,371,186 | <p>I am trying to convert <code>007898989</code> to <code>7898989</code> in Python using the following code:</p>
<pre><code>long(007898989)
</code></pre>
<p>However this leads to the following error:</p>
<pre><code>>>> long(007898989)
File "<stdin>", line 1
long(007898989)
^
Syn... | -3 | 2016-09-07T13:26:27Z | 39,371,418 | <p><code>007898989</code> is not a valid number in Python since numbers starting with a <code>0</code> are supposed to be octal numbers and cannot contain 8 or 9. For example <code>077</code> octal is the same as <code>63</code> decimal. In Python 2, you can write this code:</p>
<pre><code>>>> 077
63
</code><... | 0 | 2016-09-07T13:36:15Z | [
"python"
] |
Tkinter Dynamic Widget editing | 39,371,187 | <p>Here is my code:</p>
<pre><code>class render_window:
def __init__(self, height, width, window_title):
self.root_window = Tk()
w = width
h = height
ws = self.root_window.winfo_screenwidth() # width of the screen
hs = self.root_window.winfo_screenheight() # height of the sc... | 0 | 2016-09-07T13:26:28Z | 39,371,701 | <p>If I understand you correctly... could you not just asign each progressbar to a variable? Ie.</p>
<pre><code>pb1 = options_window.progress_bar
pb1.start()
pb1.conig('etc, etc')
</code></pre>
<p>Sorry if i have misunderstood your problem!</p>
<p>PS - Cool idea!</p>
| 2 | 2016-09-07T13:48:11Z | [
"python",
"class",
"python-3.x",
"user-interface",
"tkinter"
] |
Finding the right parameters for neural network for pong-game | 39,371,211 | <p>I have some trouble with my implementation of a deep neural network to the game Pong because my network is always diverging, regardless which parameters I change.
I took a Pong-Game and implemented a theano/lasagne based deep-q learning algorithm which is based on the famous nature paper by Googles Deepmind. </p>
<... | 3 | 2016-09-07T13:27:20Z | 39,386,000 | <p>Repeating my suggestion from comments as an answer now to make it easier to see for anyone else ending up on this page later (was posted as comment first since I was not 100% sure it'd be the solution):</p>
<p>Reducing the magnitude of the rewards to lie in (or at least close to) the [0.0, 1.0] or [-1.0, 1.0] inter... | 2 | 2016-09-08T08:23:58Z | [
"python",
"machine-learning",
"artificial-intelligence",
"deep-learning",
"theano"
] |
Python webbrowser - Check if browser is available (nothing happens when opening webpage over an SSH connection) | 39,371,219 | <p>Is there a way to detect whether there is a browser available on the system on which the script is run? Nothing happens when running the following code on a server:</p>
<pre><code>try:
webbrowser.open("file://" + os.path.realpath(path))
except webbrowser.Error:
print "Something went wrong when opening webbr... | 0 | 2016-09-07T13:27:44Z | 39,371,956 | <p>Checkout the <a href="https://docs.python.org/2/library/webbrowser.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>webbrowser.<strong>get</strong>([name])</p>
<p>Return a controller object for the browser type name. If name is empty, return a controller for a default browser appropriate to the ca... | 1 | 2016-09-07T13:58:39Z | [
"python",
"python-webbrowser"
] |
Traversing multiple dataframes simultaneously | 39,371,228 | <p>I have three dataframes of three users with same column names like time, compass data,accelerometer data, gyroscope data and camera panning information. I want to traverse all the dataframes simultaneously to check for a particular time which user has performed camera panning and return the user(like in which data f... | 0 | 2016-09-07T13:28:19Z | 39,373,533 | <p>I'm going to make the assumption that you want to traverse simultaneously in time. In any case, you want your three dataframes to have an index in the dimension you want to traverse. </p>
<p>I'll generate 3 dataframes with rows representing random seconds in a 9 second period. </p>
<p>Then, I'll align these wit... | 1 | 2016-09-07T15:09:59Z | [
"python",
"pandas",
"dataframe"
] |
Python Pandas group by function | 39,371,325 | <p>I have this table </p>
<pre><code> uname sid usage
0 Ahmad a 5
1 Ahmad a 7
2 Ahmad a 10
3 Ahmad b 2
4 Mohamad c 6
5 Mohamad c 7
6 Mohamad c 9
</code></pre>
<p>I want to group by uname and side, and have usage column = <code>group.max</code> - <code>group.min</code>. But if... | 2 | 2016-09-07T13:32:48Z | 39,371,445 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow"><code>apply</code></a> difference <a href="http:... | 1 | 2016-09-07T13:37:03Z | [
"python",
"pandas",
"group-by",
"max",
"min"
] |
Python Pandas group by function | 39,371,325 | <p>I have this table </p>
<pre><code> uname sid usage
0 Ahmad a 5
1 Ahmad a 7
2 Ahmad a 10
3 Ahmad b 2
4 Mohamad c 6
5 Mohamad c 7
6 Mohamad c 9
</code></pre>
<p>I want to group by uname and side, and have usage column = <code>group.max</code> - <code>group.min</code>. But if... | 2 | 2016-09-07T13:32:48Z | 39,372,250 | <p>First, use <code>agg</code> to grab <code>min</code>, <code>max</code>, and <code>size</code> of each group.<br>
Then multiply <code>min</code> by <code>size > 1</code>. When it is, it will equal <code>min</code>, else <code>0</code>. Then subtract that from <code>max</code>.</p>
<pre><code>d1 = df.groupby(['u... | 1 | 2016-09-07T14:12:19Z | [
"python",
"pandas",
"group-by",
"max",
"min"
] |
How can i override print function in Python 2.2.1 (WebLogic version) | 39,371,341 | <p>How to override print function in Python 2.2 in order to being able to redirect output to custom logger.</p>
| 0 | 2016-09-07T13:33:33Z | 39,371,767 | <p>I don't have a version of 2.2 to check (why are you using such an old version?), but I suspect the following is valid for all 2.x.</p>
<hr>
<p>The <code>print</code> statement recognizes a first argument beginning with <code>>></code> to indicate which file to write to.</p>
<p>The following are identical:</... | 1 | 2016-09-07T13:50:29Z | [
"python",
"wlst"
] |
Python IF conditions | 39,371,393 | <p>I'm new to django python so the if makes me feel confused. Please help me!</p>
<p>Im trying to make a IF condition for Facebook chat bot API. The whole function is when a user sends something in the Facebook chat, my bot will remove all punctuations, lower case the text and split it based on space.
After that he w... | 0 | 2016-09-07T13:35:33Z | 39,371,495 | <pre><code>if 'No':
</code></pre>
<p>is always true, you probably want to be checking if something == 'No'?</p>
| 5 | 2016-09-07T13:39:20Z | [
"python",
"django",
"if-statement"
] |
Python IF conditions | 39,371,393 | <p>I'm new to django python so the if makes me feel confused. Please help me!</p>
<p>Im trying to make a IF condition for Facebook chat bot API. The whole function is when a user sends something in the Facebook chat, my bot will remove all punctuations, lower case the text and split it based on space.
After that he w... | 0 | 2016-09-07T13:35:33Z | 39,371,615 | <p>I think this code have a problem</p>
<pre><code> if 'No':
joke_text = "Then not"
send_message(fbid, joke_text)
</code></pre>
<p>What is 'No"? You have to compare something with "No".
And also this <code>if</code> condition is on wrong indentation level. </p>
| 0 | 2016-09-07T13:44:54Z | [
"python",
"django",
"if-statement"
] |
Python IF conditions | 39,371,393 | <p>I'm new to django python so the if makes me feel confused. Please help me!</p>
<p>Im trying to make a IF condition for Facebook chat bot API. The whole function is when a user sends something in the Facebook chat, my bot will remove all punctuations, lower case the text and split it based on space.
After that he w... | 0 | 2016-09-07T13:35:33Z | 39,386,029 | <p>'No' is a string.</p>
<pre><code>if 'No'
</code></pre>
<p>always return True.</p>
| 0 | 2016-09-08T08:25:16Z | [
"python",
"django",
"if-statement"
] |
matplotlib very slow in plotting | 39,371,429 | <p>I have multiple functions in which I input an array or dict as well as a path as an argument, and the function will save a figure to the path of a particular path.</p>
<p>Trying to keep example as minimal as possible, but here are two functions:</p>
<pre><code>def valueChartPatterns(dict,path):
seen_values = C... | 1 | 2016-09-07T13:36:38Z | 39,376,368 | <p>This is the test that I mentioned in the comments above, resulting in:</p>
<pre><code>Elapsed pre-processing = 13.79 s
Elapsed plotting = 0.17 s
Pre-processing / plotting = 83.3654562565
</code></pre>
<p>Test script:</p>
<pre><code>import matplotlib.pylab as plt
from collections import Counter
from operator impor... | 1 | 2016-09-07T17:52:28Z | [
"python",
"matplotlib",
"plot",
"figure",
"figures"
] |
Subnetwork analysis on proteomics data | 39,371,435 | <p>Background: I have proteomics data from seven samples (pvalue/ log-score of fold change), I want to analyze the data by network (interactome) analyses. </p>
<p>Question: I like to create an interactome of all the proteins from the data, and map the proteins to this network that have significant pvalue (compare to c... | 0 | 2016-09-07T13:36:50Z | 39,376,855 | <p>For creating network graphs to represent your protein-protein interactions, I would recommend taking a look at the <a href="https://networkx.github.io" rel="nofollow">networkx</a> library. You can use it to pass in some nodes (proteins of interest) and edges (interactions) and generate a graph. I believe that it can... | 0 | 2016-09-07T18:28:27Z | [
"python",
"validation",
"network-programming"
] |
BeautifulSoup: get some tag from the page | 39,371,488 | <p>I have html-code</p>
<pre><code><div class="b-media-cont b-media-cont_relative" data-triggers-container="true"><span class="label">ÐвигаÑелÑ:</span> бензин, 1.6 л<br/>
<div class="b-triggers b-triggers_theme_dashed-buttons b-triggers_size_s b-triggers_text-notif"><di... | 0 | 2016-09-07T13:39:09Z | 39,371,561 | <blockquote>
<p>AttributeError: 'ResultSet' object has no attribute 'next_subling'</p>
</blockquote>
<p>This is because <code>find_all()</code> returns multiple results - a list of matching tags. And, this problem is actually <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#miscellaneous" rel="nofollo... | 1 | 2016-09-07T13:42:44Z | [
"python",
"html",
"beautifulsoup"
] |
BeautifulSoup: get some tag from the page | 39,371,488 | <p>I have html-code</p>
<pre><code><div class="b-media-cont b-media-cont_relative" data-triggers-container="true"><span class="label">ÐвигаÑелÑ:</span> бензин, 1.6 л<br/>
<div class="b-triggers b-triggers_theme_dashed-buttons b-triggers_size_s b-triggers_text-notif"><di... | 0 | 2016-09-07T13:39:09Z | 39,371,662 | <p>Try this code:</p>
<pre><code>b = None
spans = soup.find_all("span", {"class":"label"})
for span in spans:
b = span.find("b")
if b is not None:
break
</code></pre>
<p>Then you can get access to text of "b" using:</p>
<pre><code>b.text
</code></pre>
| 0 | 2016-09-07T13:46:23Z | [
"python",
"html",
"beautifulsoup"
] |
BeautifulSoup: get some tag from the page | 39,371,488 | <p>I have html-code</p>
<pre><code><div class="b-media-cont b-media-cont_relative" data-triggers-container="true"><span class="label">ÐвигаÑелÑ:</span> бензин, 1.6 л<br/>
<div class="b-triggers b-triggers_theme_dashed-buttons b-triggers_size_s b-triggers_text-notif"><di... | 0 | 2016-09-07T13:39:09Z | 39,375,978 | <p>the following should work for you</p>
<pre><code>spanTag = soup.find_all("span", string="ÐÑобег:")
print spanTag[0].find_next_sibling("b")
print spanTag[0].find_next_sibling("b").string
</code></pre>
<p>result output:</p>
<pre><code><b>ÐовÑй авÑÐ¾Ð¼Ð¾Ð±Ð¸Ð»Ñ Ð¾Ñ Ð¾ÑиÑиалÑного ди... | 0 | 2016-09-07T17:26:57Z | [
"python",
"html",
"beautifulsoup"
] |
python thrift error ```TSocket read 0 bytes``` | 39,371,489 | <p>My python version:2.7.8 <br/>
thrift version:0.9.2 <br/>
python-thrift version:0.9.2 <br/>
OS: centOS 6.8 <br/>
My test.thrift file:</p>
<pre><code>const string HELLO_IN_KOREAN = "an-nyoung-ha-se-yo"
const string HELLO_IN_FRENCH = "bonjour!"
const string HELLO_IN_JAPANESE = "konichiwa!"
service HelloWorld {
void... | 2 | 2016-09-07T13:39:09Z | 39,382,757 | <p>My OS environment problems.<br/>
I change port <code>30303</code> to <code>9999</code>, it run successfully.</p>
| 1 | 2016-09-08T04:44:46Z | [
"python",
"thrift"
] |
Image loses quality with cv2.warpPerspective | 39,371,507 | <p>I am working with OpenCV 3.1 and with Python. </p>
<p>My problem comes when I try to deskew (fix the tilt of) an image with text. I am using <code>cv2.warpPerspective</code> to make it possible, but the image loses a lot of quality. You can see here the original part of the image:</p>
<p><a href="http://i.stack.im... | 1 | 2016-09-07T13:39:51Z | 39,372,458 | <p>The problem is related to the interpolation required by the warping. If you don't want things to appear smoother, you should switch from default interpolation method, which is <code>INTER_LINEAR</code> to another one, such as <code>INTER_NEAREST</code>. It would help you with the sharpness of the edges.</p>
<p>Try ... | 2 | 2016-09-07T14:20:53Z | [
"python",
"image",
"opencv",
"image-rotation",
"opencv3.1"
] |
Invalid Syntax on MUD Game | 39,371,588 | <p>pretty much spent a whole entire term getting this python code typed up and ready to go although im hitting some speedbumps and it is causing me to panic as the assignment is due tomorrow. Im not too sure how to fix it so if anyone can please fix this, I would be so happy! </p>
<p>Im quite new to this website so he... | -7 | 2016-09-07T13:43:55Z | 39,372,288 | <p>Your Error is invalid Syntax, which comes from not correctly opening and closing.
Looking trough the code I see huge varation in formating style starting at <code>rooms = {</code>compared to the rest of the code.</p>
<p>I've put some quotes inbetween the part I suspect to be wrong and it runs directly. line 161 - 2... | -1 | 2016-09-07T14:14:11Z | [
"python",
"python-3.x"
] |
Is it possible to skip breakpoints in pdb / ipdb? | 39,371,646 | <p>Is there a way to tell pdb or ipdb to skip all future break-points and just finish execution as if they weren't there?</p>
| 2 | 2016-09-07T13:46:05Z | 39,371,787 | <p>Maybe you can try with clear.</p>
<p>From help:
<code>
'(Pdb) help clear
cl(ear) filename:lineno
cl(ear) [bpnumber [bpnumber...]]
With a space separated list of breakpoint numbers, clear
those breakpoints. Without argument, clear all breaks (but
first ask confirmation). With a filename:lineno argument,
clear all ... | 0 | 2016-09-07T13:51:25Z | [
"python",
"pdb",
"ipdb"
] |
Is it possible to skip breakpoints in pdb / ipdb? | 39,371,646 | <p>Is there a way to tell pdb or ipdb to skip all future break-points and just finish execution as if they weren't there?</p>
| 2 | 2016-09-07T13:46:05Z | 39,399,896 | <p>If you want to keep your breakpoints rather than clearing them, but also want them not to be reached, you can use <code>pdb</code>'s <code>disable</code> command. I don't see a convenient way to disable all breakpoints in a concise way, but you can list their numbers in the <code>disable</code> command. You can also... | 0 | 2016-09-08T20:42:57Z | [
"python",
"pdb",
"ipdb"
] |
Implement rms without numpy | 39,371,727 | <p>I have to implement a function to calculate rms without using numpy, using data that is in txt. I have the following:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import math
def main():
# Cargando los datos
avrgPress = []
press = []
with open("C:\Users\SAULO\Downloads\prvsp... | -2 | 2016-09-07T13:49:05Z | 39,408,864 | <p>Is this what you want, <code>rms( avrgPress )</code> ?</p>
<pre><code>from __future__ import division # necessary
import math
def rms( alist ):
""" rms( [1, 2, 3] ) = sqrt( average( 1**2 + 2**2 + 3**2 )) = 2.16 """
sum_squares = sum([ x**2 for x in alist ])
return math.sqrt( sum_squares / len(alist) )... | 1 | 2016-09-09T09:57:58Z | [
"python",
"matplotlib"
] |
How to install psycopg2 for use in HDInsight PySpark Jupyter notebook | 39,371,732 | <p>I need to "import psycopg2" as part of my PySpark script.</p>
<p>Per the <a href="https://notebooks.azure.com/faq#upload_data" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>!pip install
psycopg2</p>
</blockquote>
<p>but that results in a syntax error (as any ! command does).</p>
<p>I was able to inst... | 1 | 2016-09-07T13:49:15Z | 39,376,908 | <p>Did you make a typo? Your text was 'pyscopg2' not 'psycopg2'</p>
<pre><code>!pip install psycopg2
</code></pre>
<p>For Python 3.5 and Python 2.7 is installed already on Azure Notebooks.</p>
| 0 | 2016-09-07T18:32:23Z | [
"python",
"azure",
"psycopg2",
"jupyter",
"hdinsight"
] |
How to change the distance between y axis points in matplotlib? | 39,371,742 | <p>Sorry if this is a really stupid question, I have done a lot of searching but cant find the answer. I am using matplotlib to generate plots for some data but need to space out the distance between the points on the y axis. </p>
<p>So this is how I have it currently <a href="http://i.stack.imgur.com/pWWin.png" rel="... | 1 | 2016-09-07T13:49:29Z | 39,372,303 | <p>You need a call to:</p>
<pre><code>plt.yscale("log")
</code></pre>
| 1 | 2016-09-07T14:14:49Z | [
"python",
"matplotlib",
"plot"
] |
Complex aggregation methods as single param in query string | 39,371,747 | <p>Iâm trying to design a flexible API with django REST. What I meant by this is to have basically any field filterable through a query string and in addition to that have a param in the query string that can denote some complex method to perform. Ok, here are the details:</p>
<p><strong>views.py</strong></p>
<pre>... | 0 | 2016-09-07T13:49:46Z | 39,372,985 | <p>Definitely would be good to see your MyModelList class but anyway my example as per <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/base/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/class-based-views/base/</a></p>
<pre><code>from django.http import HttpResponse
from django.views... | 1 | 2016-09-07T14:44:23Z | [
"python",
"django",
"django-rest-framework"
] |
Timeit timing a python function | 39,371,781 | <p>I am trying to time the below function, however it shows me the error, can't import name val_in_range, what's the error, is there any other method to do it better? </p>
<pre><code>import timeit
x = 10000000
def val_in_range(x, val):
return val in range(x)
print (val_in_range(x,x/2))
timeit.timeit( 'val_in_r... | 0 | 2016-09-07T13:51:01Z | 39,372,180 | <p>replace
<code>timeit.timeit( 'val_in_range(x,x/2)', 'from __main__ import val_in_range, x', number=10)</code></p>
<p>with <code>timeit.timeit(lambda:val_in_range(x,x/2), number=10)</code></p>
<p>you can print the value directly using the <code>print</code> statement.</p>
| 2 | 2016-09-07T14:09:01Z | [
"python",
"python-3.x"
] |
Combine list of numpy arrays and reshape | 39,372,037 | <p>I'm hoping anybody could help me with the following.
I have 2 lists of arrays, which should be linked to each-other. Each list stands for a certain object. <code>arr1</code> and <code>arr2</code> are the attributes of that object.
For example:</p>
<pre><code>import numpy as np
arr1 = [np.array([1, 2, 3]), np.arra... | 2 | 2016-09-07T14:02:33Z | 39,372,393 | <p>Here's an almost* vectorized approach -</p>
<pre><code>lens = np.array([len(i) for i in arr1])
N = len(arr1)
row_idx = np.repeat(np.arange(N),lens)
col_idx = np.concatenate(arr1)
M = col_idx.max()+1
out = np.zeros((N,M),dtype=int)
out[row_idx,col_idx] = np.concatenate(arr2)
</code></pre>
<p>*: Almost because of ... | 3 | 2016-09-07T14:17:55Z | [
"python",
"arrays",
"numpy"
] |
Combine list of numpy arrays and reshape | 39,372,037 | <p>I'm hoping anybody could help me with the following.
I have 2 lists of arrays, which should be linked to each-other. Each list stands for a certain object. <code>arr1</code> and <code>arr2</code> are the attributes of that object.
For example:</p>
<pre><code>import numpy as np
arr1 = [np.array([1, 2, 3]), np.arra... | 2 | 2016-09-07T14:02:33Z | 39,372,445 | <p>Here is a solution with for-loops. Showing each step in detail.</p>
<pre><code>import numpy as np
arr1 = [np.array([1, 2, 3]), np.array([1, 2]), np.array([2, 3])]
arr2 = [np.array([20, 50, 30]), np.array([50, 50]), np.array([75, 25])]
maxi = []
for i in range(len(arr1)):
maxi.append(np.max(arr1[i]))
maxi = np... | 1 | 2016-09-07T14:20:19Z | [
"python",
"arrays",
"numpy"
] |
Combine list of numpy arrays and reshape | 39,372,037 | <p>I'm hoping anybody could help me with the following.
I have 2 lists of arrays, which should be linked to each-other. Each list stands for a certain object. <code>arr1</code> and <code>arr2</code> are the attributes of that object.
For example:</p>
<pre><code>import numpy as np
arr1 = [np.array([1, 2, 3]), np.arra... | 2 | 2016-09-07T14:02:33Z | 39,376,078 | <p>This is a straight forward approach, with only one level of iteration:</p>
<pre><code>In [261]: res=np.zeros((3,4),int)
In [262]: for i,(idx,vals) in enumerate(zip(arr1, arr2)):
...: res[i,idx]=vals
...:
In [263]: res
Out[263]:
array([[ 0, 20, 50, 30],
[ 0, 50, 50, 0],
[ 0, 0, 75... | 0 | 2016-09-07T17:33:14Z | [
"python",
"arrays",
"numpy"
] |
Wait for a clicked() event in while loop in Qt | 39,372,071 | <p>How can I wait, at each iteration, within a for loop, that the user press a given QPushButton? </p>
<pre><code>for i in range(10):
while (the button has not been pressed):
#do nothing
#do something
</code></pre>
<p>The main problem is that I cannot catch the clicked() event in the w... | 0 | 2016-09-07T14:04:19Z | 39,377,065 | <p>So, I share the slight skepticism as to whether you should want to be doing what you described. Also, I share that it would be better if you show a bit more code to describe the context. </p>
<p>Having said this, the code below is a stab at what you seem to be describing. Note that this is by no means meant to be p... | 2 | 2016-09-07T18:42:11Z | [
"python",
"qt"
] |
Anaconda plugin not working on Sublime Text 3 | 39,372,150 | <p>I am using a Sublime Text 3 portable app and I simply dragged all of the Anaconda files into the <code>packages</code> directory, i.e. <code>\Sublime Text Build 3114 x64\Data\Packages\anaconda-1.3.4</code>.</p>
<p>However, I keep getting an error in the console that says <code>ImportError: No module named 'anaconda... | 0 | 2016-09-07T14:07:48Z | 39,795,023 | <p>Fixed by using PackageControl to reinstall Anaconda.</p>
| 0 | 2016-09-30T15:27:26Z | [
"python",
"sublimetext3",
"sublime-anaconda"
] |
Python error in Console but not in File: unexpected character after line continuation character | 39,372,362 | <p>I've got a Python script which has a class defined with this method:</p>
<pre><code>@staticmethod
def _sanitized_test_name(orig_name):
return re.sub(r'[`ââ\"]*', '', re.sub(r'[\r\n\/\:\?\<\>\|\*\%]*', '', orig_name.encode('utf-8')))
</code></pre>
<p>I'm able to run the script from the command prompt ... | 1 | 2016-09-07T14:16:54Z | 39,372,363 | <p>Focusing on just the expression causing the error <code>r'[`ââ"]*'</code>...</p>
<pre><code>>>> r'[`ââ"]*'
File "<stdin>", line 1
r'[``'"]*'
^
SyntaxError: EOL while scanning string literal
>>> ur'[`ââ"]*' # with the unicode modifier
File "<stdin>", li... | 1 | 2016-09-07T14:16:54Z | [
"python",
"console"
] |
Python - Removing vertical bar lines from histogram | 39,372,470 | <p>I'm wanting to remove the vertical bar outlines from my histogram plot, but preserving the "etching" of the histogram, if that makes since.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
bins = 35
fig = plt.figure(figsize=(7,6))
ax = fig.add_subplot(111)
ax.hist(subVel_Hydro1, bins=bins, fac... | 3 | 2016-09-07T14:21:19Z | 39,372,725 | <p>In <code>pyplot.hist()</code> you could set the value of <code>histtype = 'step'</code>. Example code:</p>
<pre><code>import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(0,1,size=1000)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(x, bins=50, histtype = 'step',... | 5 | 2016-09-07T14:32:00Z | [
"python",
"matplotlib",
"histogram"
] |
when i made a 3 handshake with ubuntu in VMware return package R | 39,372,630 | <pre><code>#!/usr/bin/python
from scapy.all import *
def findWeb():
a = sr1(IP(dst="8.8.8.8")/UDP()/DNS(qd=DNSQR(qname="www.google.com")),verbose=0)
return a[DNSRR].rdata
def sendPacket(dst,src):
ip = IP(dst = dst)
SYN = TCP(sport=1500, dport=80, flags='S')
SYNACK = sr1(ip/SYN)
my_ack = SYNAC... | 0 | 2016-09-07T14:27:51Z | 39,412,283 | <p>Few things I notice wrong.
1. You have your sequence number set statically (seq=11) which is wrong. Sequence numbers are always randomly generated and they must be used as per RFC793. So the sequence should be = SYNACK[TCP].ack</p>
<ol start="2">
<li><p>You set your source port as 1500 during SYN packet, but then ... | 0 | 2016-09-09T13:05:13Z | [
"python",
"http",
"package",
"virtual-machine",
"scapy"
] |
"shade is required for this module" even though shade is installed | 39,372,696 | <p>Im trying to deploy an ansible playbook to spin up some new openstack instances and keep getting the errorr</p>
<pre><code>"shade is required for this module"
</code></pre>
<p>Shade is definitely installed as are all its dependancies. </p>
<p>I've tried adding </p>
<pre><code>localhost ansible_python_interpreter... | 0 | 2016-09-07T14:30:53Z | 39,374,456 | <p>On my hosts file I have the following: </p>
<pre><code>[local]
127.0.0.1 ansible_connection=local ansible_python_interpreter="/usr/bin/python"
</code></pre>
<p>So far I haven't been using venv and my playbooks work fine.
By adding the ansible_connection= local, it should tell your playbook to be executed on the An... | 0 | 2016-09-07T15:54:24Z | [
"python",
"ansible",
"openstack"
] |
Matplotlib bar chart customisation for multiple values | 39,372,762 | <p>I have a list of tuples with the countries and the number of times they occur. I have 175 countries all with long names.</p>
<p>When I chart them, I get:</p>
<p><a href="http://i.stack.imgur.com/dYNTx.png" rel="nofollow"><img src="http://i.stack.imgur.com/dYNTx.png" alt="enter image description here"></a></p>
<p>... | 1 | 2016-09-07T14:33:56Z | 39,375,146 | <p>The problem was in the alignment of the autolabels:</p>
<pre><code>def autolabel(rects,labels):
# attach some text labels
for i,(rect,label) in enumerate(zip(rects,labels)):
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width()/2., 1.05*height,
label,
ha='ce... | 1 | 2016-09-07T16:29:42Z | [
"python",
"matplotlib",
"plot",
"charts",
"figure"
] |
How can I print the entire converted sentence on a single line? | 39,372,778 | <p>I am trying to expand on Codeacademy's Pig Latin converter to practice basic programming concepts. </p>
<p>I believe I have the logic nearly right (I'm sure it's not as concise as it could be!) and now I am trying to output the converted Pig Latin sentence entered by the user on a single line.</p>
<p>If I print fr... | 1 | 2016-09-07T14:34:35Z | 39,373,079 | <p>Try:</p>
<pre><code>pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
final_sentence = ""
print "You entered \"%s\"." % original
split_list = original.s... | 0 | 2016-09-07T14:48:31Z | [
"python",
"join",
"printing"
] |
How can I print the entire converted sentence on a single line? | 39,372,778 | <p>I am trying to expand on Codeacademy's Pig Latin converter to practice basic programming concepts. </p>
<p>I believe I have the logic nearly right (I'm sure it's not as concise as it could be!) and now I am trying to output the converted Pig Latin sentence entered by the user on a single line.</p>
<p>If I print fr... | 1 | 2016-09-07T14:34:35Z | 39,373,084 | <p>I'm not sure of the program logic but a quick solution would be appending all the final_sentence in a list, and after the for print the list with a Join.</p>
<pre><code>pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
to_print = []
while True:
if len(original) >... | 0 | 2016-09-07T14:48:45Z | [
"python",
"join",
"printing"
] |
How can I print the entire converted sentence on a single line? | 39,372,778 | <p>I am trying to expand on Codeacademy's Pig Latin converter to practice basic programming concepts. </p>
<p>I believe I have the logic nearly right (I'm sure it's not as concise as it could be!) and now I am trying to output the converted Pig Latin sentence entered by the user on a single line.</p>
<p>If I print fr... | 1 | 2016-09-07T14:34:35Z | 39,373,100 | <p>Your issue is here:</p>
<pre><code>for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = "".join(new_sentence)
print final_sentence
</code></pre>
<p>You are joining a single word to itself. You will want to save all the words from inside the loop, then print them o... | 0 | 2016-09-07T14:49:23Z | [
"python",
"join",
"printing"
] |
Word count: 'Column' object is not callable | 39,372,801 | <pre><code>from pyspark.sql.functions import split, explode
sheshakespeareDF = sqlContext.read.text(fileName).select(removePunctuation(col('value')))
shakespeareDF.show(15, truncate=False)
</code></pre>
<p>The dataframe looks like this:</p>
<p><a href="http://i.stack.imgur.com/3pAy9.png" rel="nofollow"><img src="ht... | 0 | 2016-09-07T14:35:27Z | 39,373,074 | <p>Just use select:</p>
<pre><code>shakespeareDF = sc.parallelize([
("from fairest creatures we desire increase", ),
("that thereby beautys rose might never die", ),
]).toDF(["sentence"])
(shakespeareDF
.select(explode(split("sentence", " ")).alias("word"))
.show(4))
## +---------+
## | word|
## ... | 1 | 2016-09-07T14:48:13Z | [
"python",
"apache-spark",
"pyspark"
] |
Word count: 'Column' object is not callable | 39,372,801 | <pre><code>from pyspark.sql.functions import split, explode
sheshakespeareDF = sqlContext.read.text(fileName).select(removePunctuation(col('value')))
shakespeareDF.show(15, truncate=False)
</code></pre>
<p>The dataframe looks like this:</p>
<p><a href="http://i.stack.imgur.com/3pAy9.png" rel="nofollow"><img src="ht... | 0 | 2016-09-07T14:35:27Z | 39,376,823 | <p>Note that split() returns an array of Strings, u can't use them directly to create Data Frame (it is 'ss' in your case)</p>
<p>So you explode() them into a column & give an alias to it.
Select would take your processed column & creates new dataframe.</p>
<pre><code>newDF = (shakespeareDF
.select... | -1 | 2016-09-07T18:25:39Z | [
"python",
"apache-spark",
"pyspark"
] |
python sqlite3 UPDATE set from variables | 39,372,932 | <p>I made next Query to update a row in my DB.</p>
<pre><code>def saveData(title, LL, LR, RL, RR, distanceBack):
c.execute("UPDATE settings SET (?,?,?,?,?,?) WHERE name=?",(title, LL, LR, RL, RR, distanceBack, title))
conn.commit()
</code></pre>
<p>I always get next error: sqlite3.OperationalError: near "(": ... | 0 | 2016-09-07T14:41:56Z | 39,373,240 | <p>You could use this SQL syntax:</p>
<pre><code>UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
</code></pre>
<p>for example, if you have a table called Category and you want to edit the category name you can use:</p>
<pre><code>c.execute("UPDATE CATEGORY SET NAME=?... | 1 | 2016-09-07T14:56:08Z | [
"python",
"sqlite3",
"sql-update"
] |
python sqlite3 UPDATE set from variables | 39,372,932 | <p>I made next Query to update a row in my DB.</p>
<pre><code>def saveData(title, LL, LR, RL, RR, distanceBack):
c.execute("UPDATE settings SET (?,?,?,?,?,?) WHERE name=?",(title, LL, LR, RL, RR, distanceBack, title))
conn.commit()
</code></pre>
<p>I always get next error: sqlite3.OperationalError: near "(": ... | 0 | 2016-09-07T14:41:56Z | 39,373,331 | <p>As far as I know the
UPDATE query must look like <code>UPDATE table SET (key=value, key2=value2, ...) WHERE <condition></code></p>
<p>Try to modify query to something like</p>
<pre><code>c.execute("UPDATE settings SET (title=?,LL=?,LR=?,RL=?,RR=?,distanceBack=?) WHERE name=?",(title, LL, LR, RL, RR, dis... | -1 | 2016-09-07T15:00:12Z | [
"python",
"sqlite3",
"sql-update"
] |
How to modifying the behaviour of the Python logging facility? | 39,373,005 | <p>I would like to change the way in which messages with DEBUG and INFO level are displayed when using Python's native logging facility. By "change", I do not mean altering the format but adding an extra logical level. For example:</p>
<pre><code># This is a global variable that is set at the time of initializing the ... | 1 | 2016-09-07T14:45:06Z | 39,373,339 | <p>If all you want is custom debug levels then it's supported <em>out of the box</em>.
You set custom debug level (<code>required_verbosity_level</code> in your example) on logger using <a href="https://docs.python.org/2/library/logging.html#logging.Logger.setLevel" rel="nofollow">setLevel()</a> and then you use <a hre... | 1 | 2016-09-07T15:00:27Z | [
"python",
"logging"
] |
Module Import Error for Pypi module | 39,373,117 | <p>I am trying to import a pypi module (thinkx 1.1.2) into spyder. It is installed on anaconda and showing up on conda list. I my python path folders is my anaconda folder. When I attempt to import thinkx into spyder I get :
import thinkx
Traceback (most recent call last):</p>
<p>File "", line 1, in
impo... | 0 | 2016-09-07T14:50:19Z | 39,373,225 | <p>According to <a href="https://github.com/AllenDowney/ThinkX" rel="nofollow">module README</a>, <code>thinkx</code> does not expose package named <code>thinkx</code>.</p>
<blockquote>
<p>It provides the following modules:</p>
<ul>
<li><code>thinkbayes</code>: Code for Think Bayes.</li>
<li><code>thinkstat... | 0 | 2016-09-07T14:55:08Z | [
"python",
"spyder"
] |
Rolling sum in subgroups of a dataframe (pandas) | 39,373,196 | <p>I have <code>sessions</code> dataframe that contains <code>E-mail</code> and <code>Sessions</code> (int) columns. </p>
<p>I need to calculate rolling sum of sessions <em>per email</em> (i.e. not globally).</p>
<p>Now, the following works, but it's painfully slow:</p>
<pre><code>emails = set(list(sessions['E-mail'... | 2 | 2016-09-07T14:53:41Z | 39,373,401 | <p>Say you start with</p>
<pre><code>In [58]: df = pd.DataFrame({'E-Mail': ['foo'] * 3 + ['bar'] * 3 + ['foo'] * 3, 'Session': range(9)})
In [59]: df
Out[59]:
E-Mail Session
0 foo 0
1 foo 1
2 foo 2
3 bar 3
4 bar 4
5 bar 5
6 foo 6
7 foo ... | 2 | 2016-09-07T15:03:05Z | [
"python",
"performance",
"pandas"
] |
Rolling sum in subgroups of a dataframe (pandas) | 39,373,196 | <p>I have <code>sessions</code> dataframe that contains <code>E-mail</code> and <code>Sessions</code> (int) columns. </p>
<p>I need to calculate rolling sum of sessions <em>per email</em> (i.e. not globally).</p>
<p>Now, the following works, but it's painfully slow:</p>
<pre><code>emails = set(list(sessions['E-mail'... | 2 | 2016-09-07T14:53:41Z | 39,373,818 | <pre><code>np.random.seed([3,1415])
df = pd.DataFrame({'E-Mail': np.random.choice(list('AB'), 20),
'Session': np.random.randint(1, 10, 20)})
df.groupby('E-Mail').Session.rolling(3).sum()
E-Mail
A 0 NaN
2 NaN
4 11.0
5 7.0
7 10.0
... | 2 | 2016-09-07T15:22:33Z | [
"python",
"performance",
"pandas"
] |
print([[i+j for i in "abc"] for j in "def"]) | 39,373,220 | <p>I'm new to Python.</p>
<p>I stumped upon with one of this comprehension</p>
<pre><code>print([[i+j for i in "abc"] for j in "def"])
</code></pre>
<p>Could you please help me convert the comprehension in for loop?</p>
<p>I'm not getting the desired result by for loop:</p>
<pre><code>list = []
list2 = []
for j i... | -2 | 2016-09-07T14:54:52Z | 39,373,348 | <p>For loop for this comprehension will look like this</p>
<pre><code>result = []
for j in "def":
r = []
for i in "abc":
r.append(i+j)
result.append(r)
</code></pre>
| 1 | 2016-09-07T15:00:51Z | [
"python",
"list-comprehension"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.