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 |
|---|---|---|---|---|---|---|---|---|---|
pandas: how to get the percentage for each row | 39,243,649 | <p>When I use pandas <code>value_count</code> method, I get the data below:</p>
<pre><code>new_df['mark'].value_counts()
1 1349110
2 1606640
3 175629
4 790062
5 330978
</code></pre>
<p>How can I get the percentage for each row like this?</p>
<pre><code>1 1349110 31.7%
2 1606640 37.8%
3 175629 4.1%
... | 1 | 2016-08-31T07:46:36Z | 39,243,707 | <p>I think you need:</p>
<pre><code>#if output is Series, convert it to DataFrame
df = df.rename('a').to_frame()
df['per'] = (df.a * 100 / df.a.sum()).round(1).astype(str) + '%'
print (df)
a per
1 1349110 31.7%
2 1606640 37.8%
3 175629 4.1%
4 790062 18.6%
5 330978 7.8%
</code></pre>
<p><s... | 3 | 2016-08-31T07:49:40Z | [
"python",
"pandas",
"sum",
"percentage",
"series"
] |
pandas: how to get the percentage for each row | 39,243,649 | <p>When I use pandas <code>value_count</code> method, I get the data below:</p>
<pre><code>new_df['mark'].value_counts()
1 1349110
2 1606640
3 175629
4 790062
5 330978
</code></pre>
<p>How can I get the percentage for each row like this?</p>
<pre><code>1 1349110 31.7%
2 1606640 37.8%
3 175629 4.1%
... | 1 | 2016-08-31T07:46:36Z | 39,243,763 | <pre><code>np.random.seed([3,1415])
s = pd.Series(np.random.choice(list('ABCDEFGHIJ'), 1000, p=np.arange(1, 11) / 55.))
s.value_counts()
I 176
J 167
H 136
F 128
G 111
E 85
D 83
C 52
B 38
A 24
dtype: int64
</code></pre>
<hr>
<p>As percent</p>
<pre><code>s.value_counts(normalize=Tr... | 5 | 2016-08-31T07:52:33Z | [
"python",
"pandas",
"sum",
"percentage",
"series"
] |
Python performance on reading files with extremely long lines | 39,243,710 | <p>I've got a file with around 6MB of data. All of the data are written in a single line. Why is the following command taking more than 15 minutes to finish? Is it normal?</p>
<pre><code>infile = open('file.txt')
outfile = open('out.txt', 'w')
for line in infile.readlines():
outfile.write(line);
</code></pre>
<p>... | 1 | 2016-08-31T07:49:47Z | 39,244,001 | <p>Try the following code snippet. The <code>readlines()</code> loads all data on memory, which seems to cause a long time.</p>
<pre><code>infile = open('file.txt', 'r')
outfile = open('out.txt', 'w')
for line in infile:
outfile.write(line)
</code></pre>
<p>With my python 3.5 (64bit) on Windows 10 OS, the followi... | 1 | 2016-08-31T08:05:28Z | [
"python",
"performance",
"file"
] |
Python performance on reading files with extremely long lines | 39,243,710 | <p>I've got a file with around 6MB of data. All of the data are written in a single line. Why is the following command taking more than 15 minutes to finish? Is it normal?</p>
<pre><code>infile = open('file.txt')
outfile = open('out.txt', 'w')
for line in infile.readlines():
outfile.write(line);
</code></pre>
<p>... | 1 | 2016-08-31T07:49:47Z | 39,244,160 | <p>try reading file in chunks</p>
<pre><code>infile = open('file.txt')
outfile = open('out.txt', 'w')
while True:
text = infile.read(100): # or any other size
if not text:
break
outfile.write(line);
</code></pre>
| 0 | 2016-08-31T08:14:04Z | [
"python",
"performance",
"file"
] |
Python 3 + Selenium: Clicked the element but nothing happen | 39,243,905 | <p>The element was clicked and I didn't get any error but the popup ("add featured photos" popup in Facebook) is still there. It is not closed. </p>
<p>This is html code:</p>
<pre><code><div class="_5lnf uiOverlayFooter _5a8u">
<table class="uiGrid _51mz uiOverlayFooterGrid" cellspacing="0" cellpadding="0... | 2 | 2016-08-31T07:59:57Z | 39,244,260 | <p>Try this</p>
<pre><code>driver.find_element_by_xpath("//button[text() = 'Save']").click()
</code></pre>
| 1 | 2016-08-31T08:18:35Z | [
"javascript",
"python",
"facebook",
"selenium",
"xpath"
] |
Python 3 + Selenium: Clicked the element but nothing happen | 39,243,905 | <p>The element was clicked and I didn't get any error but the popup ("add featured photos" popup in Facebook) is still there. It is not closed. </p>
<p>This is html code:</p>
<pre><code><div class="_5lnf uiOverlayFooter _5a8u">
<table class="uiGrid _51mz uiOverlayFooterGrid" cellspacing="0" cellpadding="0... | 2 | 2016-08-31T07:59:57Z | 39,244,514 | <p>You can scroll to the button before clicking to it</p>
<pre><code>from selenium.webdriver.common.action_chains import ActionChains
button = driver.find_element_by_xpath(".//button[@class='_42ft _4jy0 layerConfirm uiOverlayButton _4jy3 _4jy1 selected _51sy']")
ActionChains(driver).move_to_element(button).perform()
... | 2 | 2016-08-31T08:30:49Z | [
"javascript",
"python",
"facebook",
"selenium",
"xpath"
] |
"CSRF token missing" with PUT/DELETE meethod rest-framework | 39,243,912 | <p>I'm using using django rest framework browsable api with ModelViewSet to do CRUD actions and want to use permissions.IsAuthenticatedOrReadOnly, but when I'm logged and try to DELETE or PUT I get
<code>"detail": "CSRF Failed: CSRF token missing or incorrect."</code></p>
<p>My view looks like this</p>
<pre><code>cla... | 0 | 2016-08-31T08:00:27Z | 39,250,180 | <p>You can remove CSRF check on individual urls. Try this on your urls.py:</p>
<pre><code>url(r'^/my_url_to_view/', csrf_exempt(views.my_view_function), name='my_name'),
</code></pre>
| 0 | 2016-08-31T12:51:28Z | [
"python",
"django",
"rest"
] |
"CSRF token missing" with PUT/DELETE meethod rest-framework | 39,243,912 | <p>I'm using using django rest framework browsable api with ModelViewSet to do CRUD actions and want to use permissions.IsAuthenticatedOrReadOnly, but when I'm logged and try to DELETE or PUT I get
<code>"detail": "CSRF Failed: CSRF token missing or incorrect."</code></p>
<p>My view looks like this</p>
<pre><code>cla... | 0 | 2016-08-31T08:00:27Z | 39,251,175 | <p>You might have used SessionAuthentication and session auth checks for the csrf_token always and you can avoid the checks by exempting but Lets not do that. </p>
<p>I think you can keep both Authentication classes. or just TokenAuthentication. ie,</p>
<pre><code>'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_fram... | 0 | 2016-08-31T13:35:55Z | [
"python",
"django",
"rest"
] |
"CSRF token missing" with PUT/DELETE meethod rest-framework | 39,243,912 | <p>I'm using using django rest framework browsable api with ModelViewSet to do CRUD actions and want to use permissions.IsAuthenticatedOrReadOnly, but when I'm logged and try to DELETE or PUT I get
<code>"detail": "CSRF Failed: CSRF token missing or incorrect."</code></p>
<p>My view looks like this</p>
<pre><code>cla... | 0 | 2016-08-31T08:00:27Z | 39,251,374 | <p>In your REST_FRAMEWORK settings you haven't mentioned the Authentication scheme so DRF uses the default authentication scheme which is SessionAuthentication. This scheme makes it mandatory for you to put csrf token with your requests. You can overcome this by:</p>
<ol>
<li>To make this setting for the whole project... | 0 | 2016-08-31T13:44:01Z | [
"python",
"django",
"rest"
] |
Inclusion templatetag with counter | 39,243,933 | <h1>What I want</h1>
<p>Inclusion Templatetag which returns number of uses and don't break when using template inheritance. I tried to storage counter in context, but it does not work as I intended.</p>
<p>base.html</p>
<pre><code>{% block body %}
{% my_tag %}<br>
{% my_tag %}<br>
{% endblock %}
</co... | 0 | 2016-08-31T08:01:29Z | 39,245,635 | <p>I suggest putting your counter in <code>request</code>. Something like this.</p>
<pre><code># This code wasn't checked
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
counter = getattr(context['request'], 'tag_counter', 0)
request.tag_counter = counter + 1
context['r... | 0 | 2016-08-31T09:23:05Z | [
"python",
"django",
"python-2.7",
"django-templates",
"django-views"
] |
update dataframe with series | 39,243,961 | <p>having a dataframe, I want to update subset of columns with a series of same length as number of columns being updated: </p>
<pre><code>>>> df = pd.DataFrame(np.random.randint(0,5,(6, 2)), columns=['col1','col2'])
>>> df
col1 col2
0 1 0
1 2 4
2 4 4
3 4 0
4 ... | 4 | 2016-08-31T08:03:21Z | 39,244,289 | <p>When assigning with a pandas object, pandas treats the assignment more "rigorously". A pandas to pandas assignment must pass stricter protocols. Only when you turn it to a list (or equivalently <code>pd.Series([0, 1]).values</code>) did pandas give in and allow you to assign in the way you'd imagine it should work... | 3 | 2016-08-31T08:19:36Z | [
"python",
"pandas",
"dataframe"
] |
More effective way of passing several arguments to script? | 39,244,007 | <p>My command line script takes several arguments including strings, ints, floats and lists, and it is becoming a bit tricky to do the call with all arguments:</p>
<pre><code>python myscript.py arg1 arg2 arg3 ... argN
</code></pre>
<p>To avoid having to write all arguments in the command line I have created a text fi... | 0 | 2016-08-31T08:05:41Z | 39,244,085 | <p>You can use <code>argpase</code> module. Refer to the following links :)</p>
<p><a href="https://pymotw.com/2/argparse" rel="nofollow">https://pymotw.com/2/argparse</a></p>
<p><a href="http://stackoverflow.com/questions/7427101/dead-simple-argparse-example-wanted-1-argument-3-results">Dead simple argparse example ... | 1 | 2016-08-31T08:09:43Z | [
"python",
"arguments",
"parameter-passing"
] |
More effective way of passing several arguments to script? | 39,244,007 | <p>My command line script takes several arguments including strings, ints, floats and lists, and it is becoming a bit tricky to do the call with all arguments:</p>
<pre><code>python myscript.py arg1 arg2 arg3 ... argN
</code></pre>
<p>To avoid having to write all arguments in the command line I have created a text fi... | 0 | 2016-08-31T08:05:41Z | 39,244,280 | <p>For me I think python getopt is the way to go.</p>
<pre><code>#!/usr/bin/python
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfi... | 1 | 2016-08-31T08:19:14Z | [
"python",
"arguments",
"parameter-passing"
] |
Python:Sorting 2d arrays generated in a loop causing errors | 39,244,063 | <p>This program randomly generates weights for several artificial neural networks using a loop, calculates the output of the network and appends that to the end of each array, then appends the cost to the end of each array. When run without sorting the arrays this program does all calculations correctly, but when I try... | 2 | 2016-08-31T08:08:17Z | 39,244,131 | <p>Your current approach sorts the list but does not <code>return</code> the result nor update the network. Note that <code>sorted</code> <em>returns</em> a sorted list. </p>
<p>You want an <em>in-place</em> sort:</p>
<pre><code>def sort():
network.sort(key=lambda x: x[-1]) # or x[8]
# ... | 0 | 2016-08-31T08:12:23Z | [
"python",
"neural-network"
] |
Google App Engine, start / stop continuously script on button click | 39,244,091 | <p>I am looking for guidance in how to achieve start / stop functionality of a function, which makes a <code>restAPI</code> to retrieve data in JSON format continuously, by clicking a button on a rendered html page through <code>webapp2</code> and hosted on GAE?</p>
<p>The current behaviour is once the http request is... | 1 | 2016-08-31T08:10:13Z | 39,252,758 | <p>The start/stop functionality is simple - just make the button control something like an <code>operation_is_stopped</code> flag persisted across requests (in the datastore, for example).</p>
<p>In case you didn't realize it yet your difficulty really comes from achieving the <strong>continuous</strong> operation tha... | 0 | 2016-08-31T14:46:10Z | [
"python",
"google-app-engine"
] |
Django CMS absolute url for Elasticsearch | 39,244,232 | <p>i write a command for django app like this :</p>
<pre><code>for p in Article.public.all():
data += '{"index": {"_id": "%s", "_type": "article"}}\n' % p.pk
data += json.dumps({
"title": p.title,
"category": p.category.category,
"content_type": p.content_type,
"duration": p.get... | 2 | 2016-08-31T08:17:30Z | 39,407,839 | <p>You will need to ensure that Django itself, not just CMS, knows the app's namespace, <code>tv_article_hook</code>.</p>
<p>I suspect that is registered with CMS, but not a namespace which Django knows about. Now depending on what version of Django you're using there's a couple of ways to define the namespace for Dja... | 0 | 2016-09-09T09:06:43Z | [
"python",
"django",
"elasticsearch",
"django-cms"
] |
How to manually invoke wxPython event | 39,244,310 | <p>I have a <code>textCTRL</code> (Wxpython) with event binding to it:</p>
<pre><code>self.x= wx.TextCtrl(self, -1, "")
self.x.Bind(wx.EVT_KILL_FOCUS, self.OnLeavex)
</code></pre>
<p>I want to manually trigger this event as I wish.
I read this topic: <a href="http://stackoverflow.com/questions/747781/wxpython-calling... | 1 | 2016-08-31T08:20:32Z | 39,255,739 | <p>The things like <code>wx.EVT_KILL_FOCUS</code> are not the event object needed here. Those are instances of <code>wx.PyEventBinder</code> which, as the name suggests, are used to bind events to handlers. The event object needed for the <code>PostEvent</code> or <code>ProcessEvent</code> functions will be the same ... | 0 | 2016-08-31T17:34:18Z | [
"python",
"wxpython"
] |
python repeat list elements in an iterator | 39,244,320 | <p>Is there any way to create an iterator to repeat elements in a list certain times? For example, a list is given:</p>
<pre><code>color = ['r', 'g', 'b']
</code></pre>
<p>Is there a way to create a iterator in form of <code>itertools.repeatlist(color, 7)</code> that can produce the following list?</p>
<pre><code>co... | 0 | 2016-08-31T08:21:01Z | 39,244,356 | <p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle"><code>itertools.cycle()</code></a> together with <a href="https://docs.python.org/2/library/itertools.html#itertools.islice"><code>itertools.islice()</code></a> to build your <code>repeatlist()</code> function:</p>
<pre><code>fro... | 8 | 2016-08-31T08:22:54Z | [
"python",
"itertools"
] |
python repeat list elements in an iterator | 39,244,320 | <p>Is there any way to create an iterator to repeat elements in a list certain times? For example, a list is given:</p>
<pre><code>color = ['r', 'g', 'b']
</code></pre>
<p>Is there a way to create a iterator in form of <code>itertools.repeatlist(color, 7)</code> that can produce the following list?</p>
<pre><code>co... | 0 | 2016-08-31T08:21:01Z | 39,244,434 | <p>Try:</p>
<pre><code>def repeat_list(l, n):
for i in range(n): yield l[i%len(l)]
</code></pre>
| -1 | 2016-08-31T08:26:17Z | [
"python",
"itertools"
] |
Python - Sending Arabic E-Mails using smtplib | 39,244,358 | <p>I'm trying to send and email including Arabic and Persian characters, using smtplib. The Following is my Function:</p>
<pre><code>def send_email (admin, pwd, user, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(admin, pwd)
server.sendmail(admi... | 0 | 2016-08-31T08:22:55Z | 39,245,577 | <p>try .encode('UTF-8')
hope it'll help</p>
| 1 | 2016-08-31T09:20:54Z | [
"python",
"email",
"smtplib"
] |
Python - Sending Arabic E-Mails using smtplib | 39,244,358 | <p>I'm trying to send and email including Arabic and Persian characters, using smtplib. The Following is my Function:</p>
<pre><code>def send_email (admin, pwd, user, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(admin, pwd)
server.sendmail(admi... | 0 | 2016-08-31T08:22:55Z | 39,246,290 | <p>The following code should solve your problem:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
import email.mime.text
def send_email (admin, pwd, user, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login... | 0 | 2016-08-31T09:50:46Z | [
"python",
"email",
"smtplib"
] |
Python regular expression(.map file parsing) | 39,244,364 | <p>I want to make a program that parses a .map file and I can't figure out what regular expression should I use to identify the name of a section.
<br><code>.text 00040000 00000d7e</code><br>
I want to get <code>.text</code> string from this line. There is no other(whitespace character) before it. W... | 1 | 2016-08-31T08:23:08Z | 39,244,452 | <p>Simply use <code>split</code>:</p>
<pre><code>yourString.split(' ')[0]
</code></pre>
<p>It will print:</p>
<pre><code>.text
</code></pre>
| 1 | 2016-08-31T08:27:11Z | [
"python",
"expression"
] |
Pyplot move origin with axis | 39,244,380 | <p>I have some code for a plot I want to create:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# data
X = np.linspace(-1, 3, num=50, endpoint=True)
b = 2.0
Y = X + b
# plot stuff
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1)
ax.set_title('linear neuron')
# move axes
ax.spines['le... | 0 | 2016-08-31T08:23:50Z | 39,245,835 | <p>You've done a lot of manual tweaking of where each thing goes, so the solution is not very portable. But here it is: remove the <code>ax.spines['bottom'].set_position</code> and <code>ax.xaxis.set_label_coords</code> calls from your original code, and add this instead:</p>
<pre><code>ax.set_ylim(-1, 6)
ax.spines['b... | 1 | 2016-08-31T09:32:03Z | [
"python",
"matplotlib",
"axis-labels"
] |
how to get the data from the table with python selenium if the class and xpath are always changing? | 39,244,407 | <pre><code><table border="0" cellpadding="0" cellspacing="0" class="A490847cc28c94895bcf96e98abdb2b32209xB">
<tbody>
<tr>
<td style="vertical-align:top">
<table border="0" cellpadding="0" cellspacing="0" class="A490... | -1 | 2016-08-31T08:25:09Z | 39,244,776 | <p>You might be able to use this xpath, not sure if it's 100% correct:</p>
<pre><code>//div[text() = 'CSFf']/ancestor::tr/td[not(descendant::div[text() = 'CSFf'])]/div
</code></pre>
<p>To make it variable:</p>
<pre><code>public String getXpathForTableThing(String searchString) {
return "//div[text() = '"+search... | 0 | 2016-08-31T08:42:53Z | [
"python",
"regex",
"selenium-webdriver",
"beautifulsoup"
] |
how to get the data from the table with python selenium if the class and xpath are always changing? | 39,244,407 | <pre><code><table border="0" cellpadding="0" cellspacing="0" class="A490847cc28c94895bcf96e98abdb2b32209xB">
<tbody>
<tr>
<td style="vertical-align:top">
<table border="0" cellpadding="0" cellspacing="0" class="A490... | -1 | 2016-08-31T08:25:09Z | 39,250,488 | <p>The parent of table id has kind of unique in which every time the number changes but the ReportCell is appended to it so using that we can find its children like this</p>
<pre><code>//*[contains(@id,'oReportCell')]/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[3]/td[1]
</code></pre>
| 1 | 2016-08-31T13:05:00Z | [
"python",
"regex",
"selenium-webdriver",
"beautifulsoup"
] |
How to resolve complex struct from a JPEG file using Python? | 39,244,494 | <p>The tail of the JPEG file contains a complex structure, such as following:</p>
<pre><code>FFD8...........................
...............................
............FFD9 1C01 0000 ....
...............................
struct definations in C file are:
typedef struct
{
short wYear;
short wM... | 0 | 2016-08-31T08:29:32Z | 39,245,686 | <p>You need to know the offset at which this struct is positioned in the file.
Assuming it is at the end of the file:</p>
<pre><code>data = open("filename.jpg", "rb").read()
offset = len(data) - sizeof(IMAGE_CAPTURE_INFO)
myStructure = IMAGE_CAPTURE_INFO.from_buffer(data, offset)
</code></pre>
| 0 | 2016-08-31T09:25:24Z | [
"python",
"struct",
"ctype"
] |
Select several directories with tkinter | 39,244,546 | <p>I have to perform an operation on several directories.</p>
<p>TKinter offers a dialog for opening one file (askopenfilename), and several files (askopenfilenames), but is lacking a dialog for several directories. </p>
<p>What is the quickest way to get to a feasible solution for "askdirectories"?</p>
| -1 | 2016-08-31T08:32:16Z | 39,245,736 | <p>You should be able to use <code>tkFileDialog.askdirectory</code>. Take a look at the docs <a href="http://tkinter.unpythonic.net/wiki/tkFileDialog" rel="nofollow">here</a> :)</p>
<p><strong>EDIT</strong></p>
<p>Perhaps something like this?</p>
<pre><code>from Tkinter import *
import tkFileDialog
root = Tk()
root... | 0 | 2016-08-31T09:27:15Z | [
"python",
"tkinter"
] |
Select several directories with tkinter | 39,244,546 | <p>I have to perform an operation on several directories.</p>
<p>TKinter offers a dialog for opening one file (askopenfilename), and several files (askopenfilenames), but is lacking a dialog for several directories. </p>
<p>What is the quickest way to get to a feasible solution for "askdirectories"?</p>
| -1 | 2016-08-31T08:32:16Z | 39,246,781 | <p>The only way for doing this in pure tkinter (except building the directory selector widget by hand) is requesting user for each dir in separate dialog. You could save previously used location, so user won't need to navigate there each time, by using code of below:</p>
<pre><code>from tkinter import filedialog
dirse... | 1 | 2016-08-31T10:13:49Z | [
"python",
"tkinter"
] |
Finding out running anaconda environment (not active on new processes or default) from within python | 39,244,579 | <p>What would be the best way to find the current anaconda environment from within python. </p>
<p>The problem is that it is not the default environment: for example calling </p>
<pre><code>import subprocess
subprocess.call(['conda','info'])
</code></pre>
<p>gives me the wrong result (because it creates a new proces... | 0 | 2016-08-31T08:33:44Z | 39,298,093 | <pre><code>import sys
print sys.version
</code></pre>
<p>Returns: (Something like)</p>
<pre><code>2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)]
</code></pre>
| 0 | 2016-09-02T17:43:53Z | [
"python",
"anaconda"
] |
Serializing image stream using protobuf | 39,244,589 | <p>I have two programs in Ubuntu: a C++ program (TORCS game) and a python program. The C++ program always generates images. I want to transfer these real-time images into python(maybe the numpy.ndarray format). So I think that maybe using Google protobuf to serialize the image to string and send string to python client... | 2 | 2016-08-31T08:34:10Z | 39,248,610 | <p>If I had to do this, I would use one of:</p>
<pre><code>message image {
int width = 1;
int height = 2;
bytes image_data = 3;
}
message image {
int width = 1;
int height = 2;
bytes red_data = 3;
bytes green_data = 4;
bytes blue_data = 5;
}
</code></pre>
<p>Or possibly use an interme... | 1 | 2016-08-31T11:37:52Z | [
"python",
"c++",
"protocol-buffers"
] |
Compute the shortest path with exactly `n` nodes between two points on a meshgrid | 39,244,636 | <p>I have defined the following 3D surface on a grid:</p>
<pre><code>%pylab inline
def muller_potential(x, y, use_numpy=False):
"""Muller potential
Parameters
----------
x : {float, np.ndarray, or theano symbolic variable}
X coordinate. If you supply an array, x and y need to be the same shape,
... | 4 | 2016-08-31T08:37:00Z | 39,269,175 | <p>As I want to obtain a reasonable path that sample basins in the potential, I wrote the functions below. For completeness I remember the <code>dijkstra</code> function I wrote:</p>
<pre><code>%pylab
def dijkstra(V, start):
mask = V.mask
visit_mask = mask.copy() # mask visited cells
m = numpy.ones_like(V)... | 1 | 2016-09-01T10:32:29Z | [
"python",
"numpy",
"shortest-path"
] |
How to run a luigi task with spark-submit and pyspark | 39,244,648 | <p>I have a <strong>luigi</strong> python task which includes some pyspark libs. Now I would like to submit this task on mesos with spark-submit. What should I do to run it? Below is my code skeleton:</p>
<pre><code>from pyspark.sql import functions as F
from pyspark import SparkContext
class myClass(SparkSubmitTask)... | 0 | 2016-08-31T08:37:30Z | 39,296,694 | <p>Luigi has some template Tasks. One of them called PySparkTask.
You can inherit from this class and override the properties:</p>
<p><a href="https://github.com/spotify/luigi/blob/master/luigi/contrib/spark.py" rel="nofollow">https://github.com/spotify/luigi/blob/master/luigi/contrib/spark.py</a>.</p>
<p>I haven't t... | 0 | 2016-09-02T16:08:07Z | [
"python",
"apache-spark",
"pyspark",
"luigi"
] |
Geometric rounding with numpy/quantize? | 39,244,873 | <p>I've got a pandas series of data which is a curve.</p>
<p>I want to round it in such a way as to make it 'stepped'. Furthermore, I want the steps to be roughly within 10% of the present value. (Another way of putting this is I want the steps to increase in increments of 10%, i.e. geometrically).</p>
<p>I've writte... | 1 | 2016-08-31T08:47:24Z | 39,246,183 | <p>OK, I think the solution should be something like:</p>
<pre><code>np.exp(np.around(np.log(np.abs(j)), decimals=1)) * np.sign(j)
</code></pre>
<p>Map to logarithmic space, do the rounding, transform back.</p>
| 1 | 2016-08-31T09:46:20Z | [
"python",
"pandas",
"numpy"
] |
Double IIF Statement in Python | 39,244,955 | <p>I have an SQL code that has a double IIF statement in it, that is, the if true part is another IIF statement and I m trying to recreate this in python using <code>np.where</code></p>
<p>the SQL code is:</p>
<pre><code>IIF ([STATE] Is Null, IIF ([COUNTRY] Is Null,'No Country',[COUNTRY]), [STATE])
</code></pre>
<p>... | 1 | 2016-08-31T08:51:20Z | 39,244,989 | <p>I think you need:</p>
<pre><code>DF['NewCol'] = np.where(DF['STATE'].isnull(),
np.where(DF['COUNTRY'].isnull(),'No Country', DF['COUNTRY']),DF['STATE'])
</code></pre>
<p>Sample:</p>
<pre><code>DF = pd.DataFrame({'STATE':[np.nan,'a','b',np.nan],
'COUNTRY':[np.nan,'c',np.nan, 'd']}... | 1 | 2016-08-31T08:52:57Z | [
"python",
"sql",
"pandas",
"if-statement",
null
] |
Django: Random ManyToMany relation is added on User connect | 39,244,969 | <p>Strangest bug I ever encountered</p>
<p>User model is the regular one from <code>conrtib.auth.User</code></p>
<p>Let's say I have the following model:</p>
<pre><code>class Region(model.Model):
name = models.CharField(max_length=256)
rakazim = models.ManyToManyField(settings.AUTH_USER_MODEL)
goal = mod... | 0 | 2016-08-31T08:52:01Z | 39,251,022 | <p>The issue turned out to be:
I seeded the staging server with data from prod for "region" the <code>dumpdata</code> command dumps the <code>region</code> with foreign keys for <code>rakazim</code> . But since the users where actually missing (I didn't copy the users from my prod environment) Instead of shouting at me... | 0 | 2016-08-31T13:30:01Z | [
"python",
"django"
] |
Can't create a virtual environment in the Google Drive folder | 39,244,999 | <p>I'm using Google Drive to keep a copy of my code projects in case my computer dies (I'm also using GitHub, but not on some private projects).</p>
<p>However, when I try to create a virtual environment using <code>virtualenv</code>, I get the following error:</p>
<pre><code>PS C:\users\fchatter\google drive> vir... | 0 | 2016-08-31T08:53:27Z | 39,245,144 | <p>Don't set up a virtual env in a cloud synced folder, nor should you run a python script from such a folder. It's a bad idea. They are not meant for version control. Write access (modifying files) to the folder is limited because in your case Google drive will periodically sync the folder which will prevent exclusive... | 2 | 2016-08-31T08:59:59Z | [
"python",
"powershell",
"virtualenv",
"drive"
] |
Python: Generic/Templated getters | 39,245,032 | <p>I have a code that simply fetches a user/s from a database</p>
<pre><code>class users:
def __init__(self):
self.engine = create_engine("mysql+pymysql://root:password@127.0.0.1/my_database")
self.connection = self.engine.connect()
self.meta = MetaData(bind=self.connection)
self.us... | 1 | 2016-08-31T08:54:57Z | 39,245,566 | <p>But you did all the hard work.. It's just a matter of combining the functions you created, initializing the input variables and throwing some <code>if</code> statements in the mix.</p>
<pre><code>def get_user(self, user_id=0, username='', role='', company=''):
if user_id:
stmt = self.users.select().wher... | 0 | 2016-08-31T09:19:53Z | [
"python",
"python-3.x",
"sqlalchemy",
"metaprogramming"
] |
Python: Generic/Templated getters | 39,245,032 | <p>I have a code that simply fetches a user/s from a database</p>
<pre><code>class users:
def __init__(self):
self.engine = create_engine("mysql+pymysql://root:password@127.0.0.1/my_database")
self.connection = self.engine.connect()
self.meta = MetaData(bind=self.connection)
self.us... | 1 | 2016-08-31T08:54:57Z | 39,245,616 | <p>Try something like:</p>
<pre><code>def get_user(self, **kwargs):
if 'user_id' in kwargs:
(...)
elif 'username' in kwargs:
(...)
elif all(a in ['role','company'] for a in kwargs):
(...)
else:
(...)
</code></pre>
| 0 | 2016-08-31T09:22:29Z | [
"python",
"python-3.x",
"sqlalchemy",
"metaprogramming"
] |
Python: Generic/Templated getters | 39,245,032 | <p>I have a code that simply fetches a user/s from a database</p>
<pre><code>class users:
def __init__(self):
self.engine = create_engine("mysql+pymysql://root:password@127.0.0.1/my_database")
self.connection = self.engine.connect()
self.meta = MetaData(bind=self.connection)
self.us... | 1 | 2016-08-31T08:54:57Z | 39,262,531 | <p>Fully generalized, so any combination of legal field names is accepted as long as a field of that name exists in the table. The magic is in <code>getattr</code>, which allows us to look up the field we're interested in dynamically (and raises <code>AttributeError</code> if called with a non-existent field name):</p>... | 1 | 2016-09-01T04:02:50Z | [
"python",
"python-3.x",
"sqlalchemy",
"metaprogramming"
] |
Pass commands from one docker container to another | 39,245,139 | <p>I have a helper container and an app container. </p>
<p>The helper container handles mounting of code via git to a shared mount with the app container. </p>
<p>I need for the helper container to check for a <code>package.json</code> or <code>requirements.txt</code> in the cloned code and if one exists to run <code... | 0 | 2016-08-31T08:59:47Z | 39,245,305 | <p>Well there is no "container to container" internal communication layer like "ssh". In this regard, the containers are as standalone as 2 different VMs ( beside the network part in general ).</p>
<p>You might go the usual way, install opensshd-server on the "receiving" server, configure it key-based only. You do not... | 1 | 2016-08-31T09:08:12Z | [
"python",
"node.js",
"linux",
"git",
"docker"
] |
Pass commands from one docker container to another | 39,245,139 | <p>I have a helper container and an app container. </p>
<p>The helper container handles mounting of code via git to a shared mount with the app container. </p>
<p>I need for the helper container to check for a <code>package.json</code> or <code>requirements.txt</code> in the cloned code and if one exists to run <code... | 0 | 2016-08-31T08:59:47Z | 39,367,150 | <p>Found that better way I was looking for :-) .</p>
<p>Using supervisord and running the xml rpc server enables me to run something like:</p>
<p><code>supervisorctl -s http://127.0.0.1:9002 -utheuser -pthepassword start uwsgi</code>
<code>supervisorctl -s http://127.0.0.1:9002 -utheuser -pthepassword start uwsgi</co... | 0 | 2016-09-07T10:16:17Z | [
"python",
"node.js",
"linux",
"git",
"docker"
] |
Plotting Lists in Matplotlib | 39,245,167 | <p>I have to lists of that kind (series and pred_upd):</p>
<p><a href="http://i.stack.imgur.com/o5sES.png" rel="nofollow"><img src="http://i.stack.imgur.com/o5sES.png" alt="enter image description here"></a></p>
<p>I try to put them together on a plot doing that:</p>
<pre><code>az = series.plot(figsize=(12,8), label... | 0 | 2016-08-31T09:01:36Z | 39,246,462 | <p>If you are using <a href="http://matplotlib.org/users/pyplot_tutorial.html" rel="nofollow"><code>matplotlib</code></a>, I think you are using it incorrectly. I cannot really infer what <code>type</code> are the variables <code>series</code> and <code>pred_upd</code> are, but I am assuming they are of type <code>list... | 1 | 2016-08-31T09:58:38Z | [
"python",
"list",
"matplotlib",
"plot"
] |
VariableDoesNotExist while rendering: Failed lookup for key [object] | 39,245,224 | <p>I am using django-haystack and elasticsearch on my Ubuntu server and finding that certain search queries just raise an error page, and I have no idea why this is happening..
Any help appreciated! :)</p>
<p>model.py : </p>
<pre><code>class EnActress(models.Model):
name = models.CharField(max_length=100, null=Tr... | 0 | 2016-08-31T09:04:37Z | 39,247,979 | <pre><code>Failed lookup for key [actress_image] in 'EnMovielist object'
</code></pre>
<p>This means you are looking up the <code>actress_image</code> value of an <code>EnMovielist</code> object.</p>
<p>What you are presumably trying to do requires <code>result.object</code> to be an instance of <code>EnActress</code... | 0 | 2016-08-31T11:08:46Z | [
"python",
"django",
"elasticsearch"
] |
geodjango check PointField in PolygonField | 39,245,233 | <p>I have two django models:</p>
<pre><code>class Region(models.Model):
geometry = models.PolygonField()
class Position(models.Model):
coordinates = models.PointField()
</code></pre>
<p>I am trying to check if a Position is geographically contained inside a Region:</p>
<pre><code>def check(region, positio... | 1 | 2016-08-31T09:05:00Z | 39,245,996 | <p>Your mistake is logical, I guess.Point's latitude and longitude should be swapped.
I mean </p>
<pre><code>{"coordinates": [11.1245718, 46.2071762], "type": "Point"}
</code></pre>
<p>Instead of</p>
<pre><code>{"coordinates": [46.2071762, 11.1245718], "type": "Point"}
</code></pre>
| 2 | 2016-08-31T09:39:05Z | [
"python",
"django",
"postgis",
"geodjango"
] |
Create a new list from two dictionaries | 39,245,557 | <p>This is a question about Python. I have the following list of dictionaries:</p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{... | 3 | 2016-08-31T09:19:18Z | 39,245,694 | <p>You can use a <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow">dictionary view</a>:</p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": ... | 2 | 2016-08-31T09:25:34Z | [
"python",
"dictionary"
] |
Create a new list from two dictionaries | 39,245,557 | <p>This is a question about Python. I have the following list of dictionaries:</p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{... | 3 | 2016-08-31T09:19:18Z | 39,245,730 | <p>You would need to check the <em>length</em> of the intersection, just checking <code>if dct.viewitems() & dictA.viewitems()</code> would evaluate to True for any intersection :</p>
<pre><code>[dct for dct in listA if len(dct.viewitems() & dictA.viewitems()) == len(dictA)]
</code></pre>
<p>Or just check for... | 3 | 2016-08-31T09:27:02Z | [
"python",
"dictionary"
] |
Create a new list from two dictionaries | 39,245,557 | <p>This is a question about Python. I have the following list of dictionaries:</p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{... | 3 | 2016-08-31T09:19:18Z | 39,245,841 | <p>For python 2.7 : </p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{"t": 5, "tid": 6, "gtm": 3, "c1": 4, "c2"... | 1 | 2016-08-31T09:32:12Z | [
"python",
"dictionary"
] |
Create a new list from two dictionaries | 39,245,557 | <p>This is a question about Python. I have the following list of dictionaries:</p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{... | 3 | 2016-08-31T09:19:18Z | 39,246,091 | <p>Try this,<code>all</code> will check the existence of <code>dictA</code> in <code>listA</code>.</p>
<pre><code>[i for i in listA if all(j in i.items() for j in dictA.items())]
</code></pre>
<p><strong>Result</strong> </p>
<pre><code>[{'c1': 4, 'gtm': 3, 'id': '111', 't': 1, 'tid': 2},
{'c1': 4, 'c2': 5, 'gtm': 3... | 1 | 2016-08-31T09:42:32Z | [
"python",
"dictionary"
] |
Using Python to plot graphs from the mySQL database | 39,245,981 | <p>I am new to python and mySQL. Initially, I want to generate few graphs using the data which I have in mySQL database. At the end I want to generate a pdf report containing that graph. Any help/advice it will be great if you guys can point me in the right direction. Thanks very much. </p>
| 0 | 2016-08-31T09:38:10Z | 39,246,971 | <p>I am generating graphs from a database with >10 million entries. The aggregating is mostly done by the database itself. Some operations take a lot of time, but it's ok. </p>
<p>The connection to the database is easy with sqlalchemy and mysqlconnector. There are many others connectors for mysql. </p>
<p>Here a litt... | 0 | 2016-08-31T10:21:52Z | [
"python",
"mysql",
"anaconda",
"spyder"
] |
Pandas Dataframe Line Plot: Show Random Markers | 39,246,115 | <p>I often have dataframes with many obervations and want to have a quick glance at the data using a line plot.</p>
<p>The problem is that the colors of the colormap are either repeated over X observations or hard to distinguish e.g. in case of sequential colormaps.</p>
<p>So my idea was to add random markers to the ... | 1 | 2016-08-31T09:43:29Z | 39,247,062 | <p>First we need to choose random marker. It could be done via <code>matplotlib.markers.MarkerStyle.markers</code> dictionary which contains all available markers. Also markers means 'nothing', starting with 'tick' and 'caret' should be dropped Some more <a href="http://matplotlib.org/api/markers_api.html" rel="nofollo... | 1 | 2016-08-31T10:25:59Z | [
"python",
"pandas",
"matplotlib"
] |
Python Text Cleaning Remove spaces between non alpha numeric characters | 39,246,146 | <p>I have a text-file with alphanumeric and non-alphanumeric characters in the text.</p>
<p>I want to remove any spaces that are between two non-alphanumeric characters.</p>
<p>How can I achieve this efficiently?</p>
<p>Any method/popular libraries is fine.</p>
| -3 | 2016-08-31T09:44:28Z | 39,248,038 | <p>Here's a possible solution to your question:</p>
<pre><code>import re
file = """
7 u p, S a k s F i f t h A v e, A u d i A 4, C a n o n A 7 5
"""
print re.sub(r"([A-Za-z0-9])\ *([A-Za-z0-9])\ *", r"\1\2", file)
</code></pre>
<p>I think <a href="https://docs.python.org/2/library/re.html#r... | 0 | 2016-08-31T11:11:02Z | [
"python",
"parsing",
"text"
] |
Pandas: Fill new column by condition row-wise | 39,246,197 | <pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame([np.random.rand(100),100*[0.1],100*[0.3]]).T
df.columns = ["value","lower","upper"]
df.head()
</code></pre>
<p><a href="http://i.stack.imgur.com/1J2Gm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/1J2Gm.jpg" alt="enter image description her... | 0 | 2016-08-31T09:46:58Z | 39,246,495 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> for this purpose.</p>
<pre><code>df['new_col'] = df['value'].between(df['lower'], df['upper'])
</code></pre>
| 3 | 2016-08-31T10:00:03Z | [
"python",
"pandas"
] |
Check two list of dicts and filter one list to remove dicts that appear in other list | 39,246,218 | <p>I have two lists:</p>
<pre><code>a = [{'val': 'abc', 'locval': {'China':24},'key3': 'meh'},{'val': 'men', 'locval': {'China':24},'key3': 'bla'},{'val': 'men', 'locval': {'India':56},'key3': 'cheh'}]
b = [{'val': 'abc', 'locval': {'China':24},'key3': 'cheh'}, {'val': 'def', 'locval': {'India':56},'key3': 'men'}]
</c... | 0 | 2016-08-31T09:47:56Z | 39,246,411 | <p>You can make a <em>set</em> of all the pairs of interesting <em>key/value</em> pairings from the <em>b</em> list of dicts then only keep dicts from <em>a</em> that do not have the same <em>key/value</em> pairings:</p>
<pre><code>a = [{'val': 'abc', 'locval': {'China':24},'key3': 'meh'},{'val': 'men', 'locval': {'C... | 1 | 2016-08-31T09:56:31Z | [
"python",
"list",
"dictionary",
"unique"
] |
TCP threaded python | 39,246,259 | <p>I'm learning some Networking through Python and came up with this idea of TCPServer Multithread so i can have multiple clients connected. The problem is that i can only connect one client.</p>
<pre><code>import socket
import os
import threading
from time import sleep
from threading import Thread
s = socket.socket(... | 1 | 2016-08-31T09:49:38Z | 39,247,892 | <p>You need to create a new thread each time you get a new connection</p>
<pre><code>import socket
import thread
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Ready...')
s.bind((host, port))
print('Bind Ready...')
print('Listening...')
s.listen(1)
def handle_cl... | 1 | 2016-08-31T11:04:09Z | [
"python",
"multithreading",
"sockets",
"networking",
"tcp"
] |
TCP threaded python | 39,246,259 | <p>I'm learning some Networking through Python and came up with this idea of TCPServer Multithread so i can have multiple clients connected. The problem is that i can only connect one client.</p>
<pre><code>import socket
import os
import threading
from time import sleep
from threading import Thread
s = socket.socket(... | 1 | 2016-08-31T09:49:38Z | 39,253,545 | <p>Ok, here's the code solved, i should have said i was working on Python3 version. Reading the docs i found out, here's the code and below the docs.</p>
<pre><code>import socket
import os
import threading
from time import sleep
from threading import Thread
import _thread
s = socket.socket(socket.AF_INET, socket.SOCK... | 0 | 2016-08-31T15:26:20Z | [
"python",
"multithreading",
"sockets",
"networking",
"tcp"
] |
Get printer status with SNMP using Pysnmp | 39,246,288 | <p>I try to get status from my printer using SNMP protocol
The problem is, I've never used the SNMP and I have trouble understanding how can I get my status like ( PAPER OUT, RIBBON OUT etc... ).</p>
<p>I configured my printer to enable the SNMP protocol using the community name "public"<br>
I presume SNMP messages ar... | 0 | 2016-08-31T09:50:35Z | 39,246,630 | <p>You need your printer specific MIB file in common case. E.g., printer in my office seems to be not support both oids by your link. Also you can use <code>snmpwalk</code> to get available oids and values on your printer and if you somehow understand which values you need, you can use it for specific instance of your ... | 0 | 2016-08-31T10:05:57Z | [
"python",
"snmp",
"zebra"
] |
Cannot import logging.py after I renamed one of my source files logging.py in my Eclipse project | 39,246,374 | <p>I thought, I broke Eclipse by renaming one of my source file logging.py, I quickly changed the name to something else but Eclipse cannot find the original python standard file ... I reinstalled my Anaconda install but it did not correct the problem ... and I later discovered it was likely a Python problem (see Edit ... | 0 | 2016-08-31T09:55:00Z | 39,249,890 | <p>First, define modules path, where built-in module logging is placed:</p>
<pre><code>user@host:$ python
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['/usr/lib/python2.7', ... ... | 1 | 2016-08-31T12:37:42Z | [
"python",
"eclipse",
"rename",
"pyinstaller",
"pyc"
] |
Cannot import logging.py after I renamed one of my source files logging.py in my Eclipse project | 39,246,374 | <p>I thought, I broke Eclipse by renaming one of my source file logging.py, I quickly changed the name to something else but Eclipse cannot find the original python standard file ... I reinstalled my Anaconda install but it did not correct the problem ... and I later discovered it was likely a Python problem (see Edit ... | 0 | 2016-08-31T09:55:00Z | 39,253,125 | <p>Sorry, I solved it myself.
I thought Eclipse delete the .pyc files when I told it to clean the project, but it is not how it works apparently, So after 2 reinstalls of anaconda and configuration tweaks for this project (I have others ...), I finally remembered to check that ... the .pyc for the file was still there ... | 0 | 2016-08-31T15:04:12Z | [
"python",
"eclipse",
"rename",
"pyinstaller",
"pyc"
] |
Regular expressions issue with python due to values with brackets | 39,246,378 | <p>I have a very large string (300 MB+), and it has some garbage data in it that I need to clean up. I am using Python 2.7 32-bit.</p>
<p>I didn't want to use the string operation <code>replace</code> because the file the user uses is only going to grow over time, so I am trying to use <code>re.sub</code> to replace ... | 0 | 2016-08-31T09:55:08Z | 39,246,463 | <p>You need to pass the pattern as a raw string:</p>
<pre><code>re.sub(r'\[lineender\]\b', os.linesep, text_value)
</code></pre>
<p>alternatively, you'll have to use <code>\\</code> (double backslashes):</p>
<pre><code>re.sub('\\[lineender\\]\\b', os.linesep, text_value)
</code></pre>
| 1 | 2016-08-31T09:58:38Z | [
"python",
"regex",
"python-2.7"
] |
Regular expressions issue with python due to values with brackets | 39,246,378 | <p>I have a very large string (300 MB+), and it has some garbage data in it that I need to clean up. I am using Python 2.7 32-bit.</p>
<p>I didn't want to use the string operation <code>replace</code> because the file the user uses is only going to grow over time, so I am trying to use <code>re.sub</code> to replace ... | 0 | 2016-08-31T09:55:08Z | 39,246,511 | <p>Note that <code>\b</code> in a non-raw string literal is a backspace. If you use a word boundary <code>r'\b'</code>, it will require a word char (a letter, digit or an underscore) after <code>]</code>. In your case, I'd remove <code>\b</code> altogether:</p>
<pre><code>re.sub(r'\[lineender]', os.linesep, text_value... | 2 | 2016-08-31T10:00:28Z | [
"python",
"regex",
"python-2.7"
] |
Estimate power spectral density of time series DF using scipy.welch | 39,246,401 | <p>I have a pandas DF with datetime index with spacing = 200ms and corresponding values for each index as shown</p>
<pre><code>print(filtered)
2016-07-14 16:31:19.000 -0.010054
2016-07-14 16:31:19.200 -0.011849
2016-07-14 16:31:19.400 -0.009564
2016-07-14 16:31:19.600 -0.001077
[20038 rows x 1 columns]
</code></pre>... | 2 | 2016-08-31T02:27:44Z | 39,256,494 | <pre><code>f,pxx =welch(filtered.values.flatten(),5)
</code></pre>
<p>works fine on my side, make sure you have no missing values in your DF and your dtypes are correct (values are floats) first. </p>
<p>this should work </p>
<pre><code>filtered = filtered.astype(float)
filtered = filtered.dropna()
f,pxx ... | 0 | 2016-08-31T18:21:39Z | [
"python",
"scipy",
"pandas"
] |
'unicode' object has no attribute 'utcoffset' | 39,246,594 | <p>In my admin, I am getting errors for only one class, 'unicode' object has no attribute 'utcoffset'. I have looked at a few other similar questions and have been unable to solve it. Any ideas on how to fix it? The traceback is below the class.</p>
<pre><code>class PartRequest(models.Model):
pub_date = models.Dat... | 0 | 2016-08-31T10:04:34Z | 39,246,873 | <p>The default value for your <code>pub_date</code> field is a string. It should be an instance of <code>datetime.date</code>.</p>
| 0 | 2016-08-31T10:17:30Z | [
"python",
"sql",
"django",
"unicode"
] |
Boolean filter using a timestamp value on a dataframe in Python | 39,246,615 | <p>I have a dataframe created from a <code>.csv</code> document. Since one of the columns has dates, I have used pandas <code>read_csv</code> with <code>parse_dates</code>:</p>
<pre><code>df = pd.read_csv('CSVdata.csv', encoding = "ISO-8859-1", parse_dates=['Dates_column'])
</code></pre>
<p>The dates range from 2012 ... | 0 | 2016-08-31T10:05:25Z | 39,246,702 | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow"><code>dt</code> accessor</a>:</p>
<pre><code>df = df[df.Dates_column.dt.year == 2014]
</code></pre>
| 1 | 2016-08-31T10:09:46Z | [
"python",
"pandas",
"dataframe",
"timestamp"
] |
Calculate percentiles/quantiles for a timeseries with resample or groupby - pandas | 39,246,664 | <p>I have a time series of hourly values and I am trying to derive some basic statistics on a weekly/monthly basis.</p>
<p>If we use the following abstract dataframe, were each column is time-series:</p>
<pre><code>rng = pd.date_range('1/1/2016', periods=2400, freq='H')
df = pd.DataFrame(np.random.randn(len(rng), 4),... | 1 | 2016-08-31T10:07:50Z | 39,246,854 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.apply.html" rel="nofollow"><code>Resampler.apply</code></a>, because <code>Resampler.quantile</code> is <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#resampling" rel="nofollow">not imp... | 2 | 2016-08-31T10:16:39Z | [
"python",
"pandas",
"group-by",
"resampling",
"quantile"
] |
Normalising pandas data frame using StandardScaler() excluding a particular column | 39,246,676 | <p>So I have a data frame which I formed by merging training (labeled) and test (unlabelled) data frames. And to un-append the test data frame I have kept a column which has a identifier if the row belonged to training or test.
Now I have to normalize all the values in all the columns except for this one column "Sl No.... | 1 | 2016-08-31T10:08:46Z | 39,247,955 | <p>try this it may work use <code>numpy</code> as <code>np</code>:</p>
<pre><code>data_norm = data_x_filled.copy() #Has training + test data frames combined to form single data frame
normalizer = StandardScaler()
data_array = normalizer.fit_transform(data_norm.ix[:,data_norm.columns!='SI No'])
data_norm = pd.DataFrame... | 2 | 2016-08-31T11:07:16Z | [
"python",
"pandas",
"scikit-learn",
"normalization"
] |
Converting a numpy array into a c++ native vector | 39,246,725 | <p>I currently have a python C extension which takes a PyObject list and I can parse is using 'PySequence_Fast'.</p>
<p>Is there an equivalent command which would allow my to parse a one dimensional numpy array?</p>
<p>Cheers,
Jack</p>
| 0 | 2016-08-31T10:10:55Z | 39,250,655 | <p>The function <code>PyArray_FROM_OTF</code> converts to a numpy array (unless the argument is already a numpy array when it just returns it with an incremented refcount). See <a href="http://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html#converting-an-arbitrary-sequence-object" rel="nofollow">http://docs.sci... | 1 | 2016-08-31T13:14:08Z | [
"python",
"numpy",
"python-c-api"
] |
AWS lambda to send email with attachements through SES> ParamValidationError: Parameter validation failed | 39,246,789 | <p>I am using AWS lambda to send email with attachments through Amazon SES. The attachment files stored in S3 bucket. Has anyone had any experience using lambda and sending emails via ses, through a lambda function? </p>
<p>here is my code:</p>
<pre><code>import boto3
from email.mime.text import MIMEText
from email.m... | 1 | 2016-08-31T10:14:26Z | 39,769,066 | <p>To fix the issue you should use:</p>
<pre><code>ses.send_raw_email(RawMessage={
'Data': msg.as_string(),
},
Source=msg['From'],
Destinations=to_emails
)
</code></pre>
<p>As described in <a href="http://boto3.readth... | 0 | 2016-09-29T11:30:09Z | [
"python",
"amazon-web-services",
"amazon-ses",
"amazon-lambda"
] |
How can I make a package from my PyCharm project available to other PyCharm projects on my computer? | 39,246,827 | <p>I am not sure if this is a Python or a PyCharm question. I think that it is quite simple, but I could not find a solution anywhere.</p>
<p>I have started to write a collection of modules with utility stuff. Now I want to import one of my packages in several of my other projects. What do I have to do to be able to s... | 1 | 2016-08-31T10:15:33Z | 39,246,879 | <p>It's not pyCharm issue. You have to give python information of the place your module live, to do that update <code>PYTHONPATH</code>, if you're using bash (OS X,GNU/Linux distro), add this to your <code>~/.bashrc</code> or <code>~/.bash_profile</code></p>
<pre><code>export PYTHONPATH="${PYTHONPATH}:/path/to/my_modu... | 3 | 2016-08-31T10:17:48Z | [
"python",
"pycharm"
] |
List to nested dictionary | 39,246,906 | <p>I have list of levels like </p>
<pre><code>levels = [["A", "B", "C", "D"], ["A", "B"], ["A", "B", "X"]]
</code></pre>
<p>In response nested dictionary should appear like</p>
<pre><code> {
"name": "A",
"parent": -1,
"children": [
{
"name": "B",
"parent": "A",
... | 2 | 2016-08-31T10:18:59Z | 39,277,084 | <pre><code>import csv
import json
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def... | 1 | 2016-09-01T16:57:18Z | [
"python",
"tree",
"hierarchy"
] |
"The system cannot find the file specified" error in Spyder | 39,246,978 | <p>I am using python to solve Captcha level 1 on <a href="http://hackthis.co.uk" rel="nofollow">http://hackthis.co.uk</a></p>
<p>here is the code</p>
<pre><code>from PIL import Image
import pytesseract
import requests
from StringIO import StringIO
url = "https://www.hackthis.co.uk/levels/captcha/1"
login = "https://w... | 0 | 2016-08-31T10:22:13Z | 39,249,311 | <p>Well the problem was, tesserect wasn't installed!
i downloaded this Tesserect OCR executables from <a href="https://github.com/tesseract-ocr/tesseract/wiki/Downloads" rel="nofollow">the download page</a></p>
<p>then added the downloaded directory to <code>PATH</code> variable
Installed VC2015 x86 redist (required)
... | 0 | 2016-08-31T12:11:51Z | [
"python",
"spyder"
] |
module.__init__() takes at most 2 arguments error in Python | 39,246,994 | <p>I have 3 files, factory_imagenet.py, imdb.py and imagenet.py</p>
<p><strong>factory_imagenet.py has:</strong></p>
<pre><code>import datasets.imagenet
</code></pre>
<p>It also has a function call as </p>
<pre><code>datasets.imagenet.imagenet(split,devkit_path))
...
</code></pre>
<p><strong>imdb.py has:</st... | -1 | 2016-08-31T10:22:41Z | 39,247,043 | <p>When you call <code>datasets.imdb.__init__(self, image_set)</code><br>
Your <code>imdb.__init__</code> method gets 3 arguments. Two you send and third is implicit <code>self</code></p>
| 0 | 2016-08-31T10:25:11Z | [
"python",
"inheritance"
] |
module.__init__() takes at most 2 arguments error in Python | 39,246,994 | <p>I have 3 files, factory_imagenet.py, imdb.py and imagenet.py</p>
<p><strong>factory_imagenet.py has:</strong></p>
<pre><code>import datasets.imagenet
</code></pre>
<p>It also has a function call as </p>
<pre><code>datasets.imagenet.imagenet(split,devkit_path))
...
</code></pre>
<p><strong>imdb.py has:</st... | -1 | 2016-08-31T10:22:41Z | 39,247,101 | <blockquote>
<pre><code>module.__init__() takes at most 2 arguments (3 given)
</code></pre>
</blockquote>
<p>This means that you are trying to inherit from a module, not from a class. In fact, <code>datasets.imdb</code> is a module; <code>datasets.imdb.imdb</code> is your class.</p>
<p>You need to change your code so... | 3 | 2016-08-31T10:27:51Z | [
"python",
"inheritance"
] |
Internal Reference - Auto Increment field | 39,247,220 | <p><a href="http://i.stack.imgur.com/PuAv9.png" rel="nofollow">enter image description here</a></p>
<p>Hello to all,</p>
<p>I need to know how to change the type of the field 'ref' (Internal Reference) from char to Auto Sequence. You can see on the picture the field. Everytime i create a new Contact, internal referen... | 0 | 2016-08-31T10:33:25Z | 39,250,532 | <p>Crreate a sequence and write it value to <code>ref</code> </p>
<p><em>XML code</em>: </p>
<pre><code> <record id="Your_sequence_type_id" model="ir.sequence.type">
<field name="name">Reference</field>
<field name="code">Your_code</field>
</record>
&l... | 0 | 2016-08-31T13:07:47Z | [
"python",
"xml",
"auto-increment",
"odoo-9"
] |
Python pandas: dataframe grouped by a column(such as, name), and get the value of some columns in each group | 39,247,335 | <p>There is dataframe called as df as following:</p>
<pre><code> name id age text
a 1 1 very good, and I like him
b 2 2 I play basketball with his brother
c 3 3 I hope to get a offer
d 4 4 everything goes well, I think
a 1 1 ... | 1 | 2016-08-31T10:38:49Z | 39,247,555 | <p>I'll elaborate a bit more than in the comment. The problem is that extract_text is only able to handle individual strings. However when you groupby and then apply, you're sending a list with all the strings in the group.</p>
<p>There are two solutions, the first is the one I indicated (sending individual strings):<... | 1 | 2016-08-31T10:48:58Z | [
"python",
"string",
"pandas",
"dataframe",
"group-by"
] |
Python pandas: dataframe grouped by a column(such as, name), and get the value of some columns in each group | 39,247,335 | <p>There is dataframe called as df as following:</p>
<pre><code> name id age text
a 1 1 very good, and I like him
b 2 2 I play basketball with his brother
c 3 3 I hope to get a offer
d 4 4 everything goes well, I think
a 1 1 ... | 1 | 2016-08-31T10:38:49Z | 39,248,400 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.find.html" rel="nofollow"><code>str.find</code></a>:</p>
<pre><code>print (df.groupby('age')['text'].apply(lambda x: x.str.find('I').tolist()))
age
1 [15, 0, 0]
2 [0, 26, 30]
3 [0, 0, 0]
4 [22, 6, 22]... | 1 | 2016-08-31T11:27:54Z | [
"python",
"string",
"pandas",
"dataframe",
"group-by"
] |
PyQt GUI size on high resolution screens | 39,247,342 | <p>I posted a <a href="http://stackoverflow.com/questions/38546580/tkinter-gui-size-on-high-resolution-screens/38546859#38546859">question</a> a while ago asking about Tkinter backends and subsequently forgot about it but I've since realised that I'm using the pyqt backend. Is there a fix for that? </p>
<p>Original Qu... | 0 | 2016-08-31T10:39:09Z | 39,247,516 | <p>While I do not have much experience with PyQt, upon googling I found <a href="http://stackoverflow.com/questions/14726296/how-to-make-pyqt-window-state-to-maximised-in-pyqt">this</a> SO question about setting the window state of a PyQT window to maximised. The accepted answer says to use <code>self.showMaximized()</... | 0 | 2016-08-31T10:46:48Z | [
"python",
"qt",
"user-interface",
"matplotlib",
"pyqt"
] |
How to check if, elif, else conditions at the same time in django template | 39,247,352 | <p>I have 3 category in category field. I want to check it in django template and assign appropirte urls for 3 distinct category.</p>
<p>I tried:</p>
<pre><code>{% for entry in entries %}
{% if entry.category == 1 %}
<a href="{% url 'member:person-list' %}"><li>{{ entry.category }}</li&... | -6 | 2016-08-31T10:39:31Z | 39,247,780 | <p>This is my working answers:</p>
<pre><code> {% for entry in entries %}
{% if entry.category == 'General Member' %}
<a href="{% url 'member:person-list' %}"><li>{{ entry.category }}</li></a>
{% elif entry.category == 'Executive Committee Member' %}
<a href="{%... | -1 | 2016-08-31T10:59:58Z | [
"python",
"django"
] |
How to check if, elif, else conditions at the same time in django template | 39,247,352 | <p>I have 3 category in category field. I want to check it in django template and assign appropirte urls for 3 distinct category.</p>
<p>I tried:</p>
<pre><code>{% for entry in entries %}
{% if entry.category == 1 %}
<a href="{% url 'member:person-list' %}"><li>{{ entry.category }}</li&... | -6 | 2016-08-31T10:39:31Z | 39,268,453 | <p>From what I understand, you want to associate each entry to a url depending on the category it belongs among the 3 categories. you can have this refactored in your <code>Entry</code> model in order to minimize logic in templates like:</p>
<pre><code>class Entry(models.Model):
category = ...
def get_entry_u... | 1 | 2016-09-01T10:00:10Z | [
"python",
"django"
] |
How do I parse the data structure sent by DynamoDB to Lambda using python? | 39,247,445 | <p>I am trying to link DynamoDB with Amazon Lambda such that when an item is inserted in DynamoDB, it will be sent to my lambda function which will parse the data structure and perfomr operations on the data. However, the data posted looks like this :</p>
<pre><code>{
"Records": [
{
"eventID": ... | 0 | 2016-08-31T10:43:09Z | 39,247,787 | <p><code>print string['Records'][0]['eventID']</code> to print the eventID</p>
<p>There are many data structures involved here. The outer one being a python dictionary whose objects you can receive using keys.
In our case you have only one mapping in your dictionary so, assuming that the whole data structure you have ... | 1 | 2016-08-31T11:00:08Z | [
"python",
"amazon-web-services",
"amazon-dynamodb",
"aws-lambda"
] |
score_cbow_pair in word2vec (gensim) | 39,247,496 | <p>I wanted to output the log-probability during learning of the word and doc vectors in gensim. I have taken a look at the implementation of the score function in the "slow plain numpy" version.</p>
<pre class="lang-py prettyprint-override"><code>def score_cbow_pair(model, word, word2_indices, l1):
l2a = model.sy... | 0 | 2016-08-31T10:45:53Z | 39,357,806 | <p>I've overlooked that the logarithm of the sigmoid function can be rewritten: <code>log(1.0/(1.0+exp(-sgn*dot(l1, l2a.T)))) = log(1)-log(1.0+exp(-sgn*dot(l1, l2a.T))) = -log(1.0+exp(-sgn*dot(l1, l2a.T)))</code></p>
<p>So the code does compute the log-likelihood.</p>
| 0 | 2016-09-06T21:03:22Z | [
"python",
"numpy",
"probability",
"gensim",
"word2vec"
] |
How to organize data of several datasets into the same dataframe using pandas in Python? | 39,247,527 | <p>I am having trouble in keeping some data organized as I want in a data frame using pandas in Python.</p>
<p>I would like to have a single data frame where the data would be organized in three columns (e.g. <code>Time</code>, <code>V</code> and <code>I</code>).</p>
<p>However, I would like to have the data of diffe... | 1 | 2016-08-31T10:47:14Z | 39,247,584 | <p>Yes, <code>MultiIndex</code> is one possible solution:</p>
<pre><code>np.random.seed(1)
df1 = pd.DataFrame({'Time': np.arange(0,10,0.5),
'V': np.random.rand(20),
'I': np.random.rand(20)})
np.random.seed(2)
df2 = pd.DataFrame({'Time': np.arange(0,10,0.5),
... | 1 | 2016-08-31T10:50:01Z | [
"python",
"pandas",
"indexing",
"dataframe",
"multi-index"
] |
AttributeError when trying to set a window type hint with GTK using Python | 39,247,538 | <p>I'm still really new to python, so this will probably be a dumb question.</p>
<p>I'm trying to learn how to make a GUI using pygtk (Mostly because I use linux and I'd like to have GTK theming support in my programs). I've started with the most simple window possible, and I've found that since I'm using a tiling win... | 1 | 2016-08-31T10:48:09Z | 39,248,628 | <p>You need to import <code>Gdk</code>, then use <code>Gdk.WindowTypeHint.UTILITY</code>, not <code>Gtk.gdk.WINDOW_TYPE_HINT_UTILITY</code>:</p>
<pre class="lang-py prettyprint-override"><code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
win = Gtk.Window()
win.connect("delete-event", ... | 1 | 2016-08-31T11:38:37Z | [
"python",
"user-interface",
"gtk"
] |
Create dataframe column with elif of different types in pandas | 39,247,591 | <p>This is an extension of <a href="http://stackoverflow.com/questions/18194404/create-column-with-elif-in-pandas">question</a>.</p>
<p>I'd like to do some if/elif/else logic to create a dataframe column, pseudocode example:</p>
<pre><code>if Col1 = 'A' and Col2 = 1 then Col3 = 'A1'
else if Col1 = 'A' and Col2 = 0 th... | 1 | 2016-08-31T10:50:09Z | 39,247,683 | <p>I think you can use:</p>
<pre><code>df['Col3'] = 'XX'
df.loc[(df.Col1 == 'A') & (df.Col2 == 1), 'Col3'] = 'A1'
df.loc[(df.Col1 == 'A') & (df.Col2 == 0), 'Col3'] = 'A0'
</code></pre>
<p>With double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>num... | 2 | 2016-08-31T10:55:53Z | [
"python",
"pandas",
"indexing",
"condition",
"multiple-columns"
] |
'PyQt4 module not found' - Cannot use PyQt to open a GUI | 39,247,929 | <p>I am very new to using PyQt4. So far, i have used QtDesigner to create the GUI windows i shall be using for my program. </p>
<p>However, when i run the first bit of python coding to get the user interface to appear, i get an error i cannot find a solution to.</p>
<p>Here's the code:</p>
<pre><code>import sys, os
... | 1 | 2016-08-31T11:05:45Z | 39,263,674 | <p>I also work in windows and python 3,just run the execute file to install pyqt:</p>
<p><a href="https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.6/" rel="nofollow">https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.6/</a></p>
<p>it works well in my environment</p>
| 0 | 2016-09-01T05:57:20Z | [
"python",
"python-3.x",
"pyqt",
"pyqt4"
] |
Import packages from current project directory in VScode | 39,248,054 | <p>When I build or debug a particular file in my Python project (which imports a user defined package) I get an import error. How can I solve this problem?</p>
<p>test.py</p>
<pre><code>def sum(a,b):
return a+b
</code></pre>
<p>test2.py</p>
<pre><code>from test import sum
sum(3,4)
</code></pre>
<p>The above co... | 0 | 2016-08-31T11:11:47Z | 39,249,192 | <p>About the <code>heap</code> file, make sure that you are running on the project root folder.</p>
<p>If these <code>test.py</code> files are running on the same folder, try to add a <code>__init__.py</code> empty file on this folder. </p>
<blockquote>
<p>The <code>__init__.py</code> files are required to make Pyt... | 0 | 2016-08-31T12:05:30Z | [
"python",
"vscode"
] |
Extract part of file and print using python | 39,248,101 | <p>I want to extract part of the file content . Which starts with ("head"
and ends with ("arraydat"</p>
<p>content of file:</p>
<pre><code>(record
( "head"
(record
( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
... | 1 | 2016-08-31T11:13:43Z | 39,248,349 | <pre><code>data = []
read = False
for line in open('test.dat'):
if line.strip() == '( "head"':
read = True
continue
elif line.strip() == '( "arraydat"':
read = False
if read:
data.append(line.rstrip())
print('\n'.join(data))
</code></pre>
| 1 | 2016-08-31T11:25:09Z | [
"python"
] |
Extract part of file and print using python | 39,248,101 | <p>I want to extract part of the file content . Which starts with ("head"
and ends with ("arraydat"</p>
<p>content of file:</p>
<pre><code>(record
( "head"
(record
( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
... | 1 | 2016-08-31T11:13:43Z | 39,248,713 | <p>Please check the below code:</p>
<pre><code>import re
import csv
data_list= []
record_data = False
comm_line = False
#Open file read data.
#Save one set of data between 'head' and 'arraydat' in single dict
#Append that dict to data list
with open('sample.txt','r') as new_file:
for line in new_file:
... | 0 | 2016-08-31T11:42:29Z | [
"python"
] |
Extract part of file and print using python | 39,248,101 | <p>I want to extract part of the file content . Which starts with ("head"
and ends with ("arraydat"</p>
<p>content of file:</p>
<pre><code>(record
( "head"
(record
( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
... | 1 | 2016-08-31T11:13:43Z | 39,248,823 | <pre><code>try:
with open('sample.txt', 'r') as fileObject:
fileData = fileObject.read().split("\n")
fileDataClean = [data.strip() for data in fileData]
startIndex, stopIndex = fileDataClean.index('( "head"'), fileDataClean.index('( "arraydat"')
resultData = "\n"join(fileData[startIndex:stopIn... | 0 | 2016-08-31T11:48:04Z | [
"python"
] |
Factor an integer to something as close to a square as possible | 39,248,245 | <p>I have a function that reads a file byte by byte and converts it to a floating point array. It also returns the number of elements in said array.
Now I want to reshape the array into a 2D array with the shape being as close to a square as possible.</p>
<p>As an example let's look at the number 800:</p>
<p><code>sq... | 1 | 2016-08-31T11:20:43Z | 39,248,503 | <pre><code>def factor_int(n):
nsqrt = math.ceil(math.sqrt(n))
solution = False
val = nsqrt
while not solution:
val2 = int(n/val)
if val2 * val == float(n):
solution = True
else:
val-=1
return val, val2, n
</code></pre>
<p>try it with:</p>
<pre><code>for ... | 1 | 2016-08-31T11:33:26Z | [
"python",
"algorithm",
"cython",
"factoring"
] |
Factor an integer to something as close to a square as possible | 39,248,245 | <p>I have a function that reads a file byte by byte and converts it to a floating point array. It also returns the number of elements in said array.
Now I want to reshape the array into a 2D array with the shape being as close to a square as possible.</p>
<p>As an example let's look at the number 800:</p>
<p><code>sq... | 1 | 2016-08-31T11:20:43Z | 39,248,799 | <p>Interesting question, here's a possible solution to your problem:</p>
<pre><code>import math
def min_dist(a, b):
dist = []
for Pa in a:
for Pb in b:
d = math.sqrt(
math.pow(Pa[0] - Pb[0], 2) + math.pow(Pa[1] - Pb[1], 2))
dist.append([d, Pa])
return sort... | 1 | 2016-08-31T11:47:03Z | [
"python",
"algorithm",
"cython",
"factoring"
] |
Factor an integer to something as close to a square as possible | 39,248,245 | <p>I have a function that reads a file byte by byte and converts it to a floating point array. It also returns the number of elements in said array.
Now I want to reshape the array into a 2D array with the shape being as close to a square as possible.</p>
<p>As an example let's look at the number 800:</p>
<p><code>sq... | 1 | 2016-08-31T11:20:43Z | 39,527,893 | <p>I think the modulus operator is a good fit for this problem:</p>
<pre><code>import math
def factint(n):
pos_n = abs(n)
max_candidate = int(math.sqrt(pos_n))
for candidate in xrange(max_candidate, 0, -1):
if pos_n % candidate == 0:
break
return candidate, n / candidate
</code></... | 0 | 2016-09-16T09:22:02Z | [
"python",
"algorithm",
"cython",
"factoring"
] |
Bypassing intrusive cookie statement with requests library | 39,248,266 | <p>I'm trying to crawl a website using the <code>requests</code> library. However, the particular website I am trying to access (<a href="http://www.vi.nl/matchcenter/vandaag.shtml" rel="nofollow">http://www.vi.nl/matchcenter/vandaag.shtml</a>) has a very intrusive cookie statement.</p>
<p>I am trying to access the we... | 0 | 2016-08-31T11:21:41Z | 39,248,347 | <p>I have found <a href="http://stackoverflow.com/questions/7164679/how-to-send-cookies-in-a-post-request-with-the-python-requests-library">this</a> SO question which asks how to send cookies in a post using requests. The accepted answer states that the latest build of Requests will build CookieJars for you from simple... | -1 | 2016-08-31T11:25:04Z | [
"python",
"cookies",
"beautifulsoup",
"python-requests"
] |
Bypassing intrusive cookie statement with requests library | 39,248,266 | <p>I'm trying to crawl a website using the <code>requests</code> library. However, the particular website I am trying to access (<a href="http://www.vi.nl/matchcenter/vandaag.shtml" rel="nofollow">http://www.vi.nl/matchcenter/vandaag.shtml</a>) has a very intrusive cookie statement.</p>
<p>I am trying to access the we... | 0 | 2016-08-31T11:21:41Z | 39,248,697 | <p>Try setting:</p>
<pre><code>cookies = dict(BCPermissionLevel='PERSONAL')
html = requests.get(website, headers={"User-Agent": "Mozilla/5.0"}, cookies=cookies)
</code></pre>
<p>This will bypass the cookie consent page and will land you staight to the page.</p>
<p><strong>Note</strong>: You could find the above by a... | -1 | 2016-08-31T11:41:36Z | [
"python",
"cookies",
"beautifulsoup",
"python-requests"
] |
Python: Tornado and persistent database connection | 39,248,278 | <p>I am reading <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.initialize" rel="nofollow">tornado documentation</a>. I would like to have persistent connection(connection is up during application lifetime) to DB and return data from DB asynchronously. Where is the best place of doing t... | 0 | 2016-08-31T11:22:19Z | 39,248,853 | <p>The simplest thing is just to make the database connection object a module-level global variable. See this example <a href="http://motor.readthedocs.io/en/stable/tutorial-tornado.html#tornado-application-startup-sequence" rel="nofollow">from the Motor documentation</a>:</p>
<pre><code>db = motor.motor_tornado.Motor... | 1 | 2016-08-31T11:48:58Z | [
"python",
"database",
"asynchronous",
"tornado"
] |
Reshape dataframe to have the same index as another dataframe | 39,248,331 | <p>I have two dataframes:</p>
<pre><code>dayData
power_comparison final_average_delta_power calculated_power
1 0.0 0.0 0
2 0.0 0.0 0
3 0.0 0.0 ... | 1 | 2016-08-31T11:24:14Z | 39,248,442 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> if <code>index</code> has no duplicates:</p>
<pre><code>historicPower = historicPower.reindex(dayData.index)
print (historicPower)
power
1 0.0
2 0.0
3 ... | 2 | 2016-08-31T11:30:34Z | [
"python",
"pandas",
"indexing",
"dataframe",
"reindex"
] |
handle http post request with json by python script on iis | 39,248,376 | <p>i have trouble handling http post request with JSON as body of the request.
i am running IIS with python as server script.</p>
<p>this is the code that makes request: </p>
<pre><code>var http = new XMLHttpRequest();
var url = "http://myurl.ext/py/script.py";
http.onreadystatechange = function() {
if(http.readyS... | 0 | 2016-08-31T11:26:50Z | 39,250,912 | <p>The <a href="https://docs.python.org/3/library/cgi.html#module-cgi" rel="nofollow"><code>cgi</code></a> module is designed primarily with form processing from a POST request, or query string parsing from a GET request, in mind. As such it does not really provide much that might help you process a JSON request.</p>
... | 0 | 2016-08-31T13:25:07Z | [
"python",
"json",
"iis",
"post",
"request"
] |
handle http post request with json by python script on iis | 39,248,376 | <p>i have trouble handling http post request with JSON as body of the request.
i am running IIS with python as server script.</p>
<p>this is the code that makes request: </p>
<pre><code>var http = new XMLHttpRequest();
var url = "http://myurl.ext/py/script.py";
http.onreadystatechange = function() {
if(http.readyS... | 0 | 2016-08-31T11:26:50Z | 39,286,864 | <p>to make it work you have to explicitly tell how much to read.
<br/></p>
<pre><code>data = "";
if int(os.environ.get('CONTENT_LENGTH', 0)) != 0:
for i in range(int(os.environ.get('CONTENT_LENGTH', 0))):
data += sys.stdin.read(1)
print(data)
</code></pre>
<p>this what worked for me</p>
| 0 | 2016-09-02T07:38:36Z | [
"python",
"json",
"iis",
"post",
"request"
] |
unable to plot two columns from DataFrame after using pandas.read_csv | 39,248,380 | <p>I'm trying to plot two columns that have been read in using pandas.read_csv, the code:-</p>
<pre><code>from pandas import read_csv
from matplotlib import pyplot
data = read_csv('Stats.csv', sep=',')
#data = data.astype(float)
data.plot(x = 1, y = 2)
pyplot.show()
</code></pre>
<p>the csv file snippet:-</p>
<pre... | 2 | 2016-08-31T11:27:01Z | 39,249,150 | <p>Your input csv is without headers which doesn't help clarity (see Murali's comment). But I think the problem stems from the nature of column that contains a4,a2.</p>
<p>This column can be used for the x axis but not for y axis (non-numeric data on an x axis appears to be just read in order). Hence the count offset.... | 0 | 2016-08-31T12:03:31Z | [
"python",
"csv",
"pandas"
] |
Difference between Queue and Sets Python | 39,248,452 | <p>In case there is multi-threads and one function which adds a value to a list and another function which takes that value. What would the difference be with:</p>
<pre><code>import queue
scrape = queue.Queue()
def scrape():
scrape.put('example')
def send():
example = scrape.get()
print (example)
scrape =... | 1 | 2016-08-31T11:30:55Z | 39,248,636 | <p><code>Queues</code> maintain ordering of possibly non-unique elements. <code>Sets</code>, on the other hand, do not maintain ordering and may not contain duplicates.</p>
<p>In your case you may need to keep a record of each thing scraped and/or the relative order in which it was scraped. In that case, use <code>que... | 4 | 2016-08-31T11:38:56Z | [
"python",
"multithreading",
"set",
"queue"
] |
Keyboardinterupt does not work after a cplex model is solved | 39,248,477 | <p>I know there is a bug with Keyboardinterupts in python with multiprocessor tasks, but I also know there are some workarounds. Here I can't figure out a solution because the threads are handled inside the cplex package, which I can not (and do not want to) change.</p>
<p>Here is a minimal example:</p>
<pre><code>de... | 1 | 2016-08-31T11:32:27Z | 39,261,525 | <p>I think you may have found a bug in the CPLEX Python API. I'm not sure yet, but I think the default signal handler is not being restored correctly there (i.e., it's corrupted once you're done with CPLEX).</p>
<p>This is a (ugly?) workaround for your specific question:</p>
<pre><code>import signal
def test_interu... | 0 | 2016-09-01T01:48:22Z | [
"python",
"multithreading",
"cplex",
"keyboardinterrupt"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.