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 |
|---|---|---|---|---|---|---|---|---|---|
accessing the tokenized words in python | 38,910,318 | <p>Suppose we have values in query column of a panda data frame which are tokenized using the split() function like </p>
<pre><code>query[4] = "['rain', 'shower', 'head']".
</code></pre>
<p>Now I want to perform some operations on individual words. So, I converted it into list and iterated through it using for loop l... | 2 | 2016-08-12T05:06:14Z | 38,910,410 | <p>You need to convert to string to actual list:</p>
<pre><code>data = eval(query[4])
</code></pre>
<p>Then loop through the data:</p>
<pre><code>for word in data: word = func(word)
</code></pre>
| 0 | 2016-08-12T05:17:04Z | [
"python",
"pandas"
] |
accessing the tokenized words in python | 38,910,318 | <p>Suppose we have values in query column of a panda data frame which are tokenized using the split() function like </p>
<pre><code>query[4] = "['rain', 'shower', 'head']".
</code></pre>
<p>Now I want to perform some operations on individual words. So, I converted it into list and iterated through it using for loop l... | 2 | 2016-08-12T05:06:14Z | 38,910,415 | <p>If need works with <code>pandas DataFrame</code>, you need first convert <code>string</code> values to <code>list</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable... | 1 | 2016-08-12T05:17:28Z | [
"python",
"pandas"
] |
How to stop parse in Scrapy SitemapSpider | 38,910,328 | <p>My requirement is to get all the url present in sitemap.xml, scrapy sitemapspider class does the task but it also try to parse the pages which makes the crawling slow as it try to download the entire page. </p>
<p>Is their a way to get just the url's without going into each one of them.</p>
| 0 | 2016-08-12T05:07:54Z | 38,913,600 | <p>You can extract urls from sitemap by using <code>scrapy.utils.sitemap.Sitemap</code> object, which does everything for you.</p>
<pre><code>import scrapy
from scrapy.utils.sitemap import Sitemap
class SitemapJustUrlsSpider(scrapy.Spider):
name = "sitemap_spider"
start_urls = (
'http://www.example.c... | 0 | 2016-08-12T08:41:08Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler",
"sitemap"
] |
How do I validate against multiple xsd schemas using lxml? | 38,910,347 | <p>I'm writing a unit test that validates sitemap xml I generate by fetching its xsd schema and validating using python's lxml library:</p>
<p>Here's some metadata on my root element:</p>
<pre><code>xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xsi:... | 1 | 2016-08-12T05:10:20Z | 38,910,984 | <p>You could try to define a wrapper schema <em>wrapper-schema.xsd</em> that imports all the schemas needed, and use this schema with lxml instead of each one of the others.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import
nam... | 1 | 2016-08-12T06:03:48Z | [
"python",
"xml",
"xsd",
"lxml"
] |
How to exclude string of patten in regex search | 38,910,388 | <p>How to use regex to search word in the html string, but ignore the word in html tags. For example <code><a href="foo">foo</a></code>, the first <code>foo</code> in should be ignored, the second <code>foo</code> is the pattern to search.</p>
| 1 | 2016-08-12T05:14:41Z | 38,910,675 | <p>An example using <code>BeautifulSoup</code> <strong>combined with regex</strong> instead:</p>
<pre><code>from bs4 import BeautifulSoup
import re
string = '''
<a class='fooo123'>foo on its own</a>
<a class='123foo'>only foo</a>
'''
soup = BeautifulSoup(string, "lxml")
foo_links = soup.find_... | 1 | 2016-08-12T05:38:17Z | [
"python",
"regex"
] |
How to exclude string of patten in regex search | 38,910,388 | <p>How to use regex to search word in the html string, but ignore the word in html tags. For example <code><a href="foo">foo</a></code>, the first <code>foo</code> in should be ignored, the second <code>foo</code> is the pattern to search.</p>
| 1 | 2016-08-12T05:14:41Z | 38,911,680 | <p>This program should be able to find all the contents between tags.</p>
<pre><code>import re
str = '''<h3>
<a href="//stackexchange.com/users/838793061/?accounts">yourcommunities</a>
</h3>
<a href="#" id="edit-pinned-sites">edit</a>
<a href="#"... | 1 | 2016-08-12T06:54:01Z | [
"python",
"regex"
] |
How to exclude string of patten in regex search | 38,910,388 | <p>How to use regex to search word in the html string, but ignore the word in html tags. For example <code><a href="foo">foo</a></code>, the first <code>foo</code> in should be ignored, the second <code>foo</code> is the pattern to search.</p>
| 1 | 2016-08-12T05:14:41Z | 39,059,500 | <p>What if the content contains spaces? </p>
<p>I propose the next regex that also removes the spaces from the answer:</p>
<pre><code>#### With spaces:
line = '<a href="foo"> foo </a>'
re.findall(r'>\s*(\w*)\s*<',line)
### ['foo']
#### No spaces:
line = '<a href="foo">foo</a>'... | 0 | 2016-08-20T23:10:16Z | [
"python",
"regex"
] |
How to replace a word in Python without replacing other forms of the word? | 38,910,496 | <p>I am supposed to change a specific word in a string without changing the other forms of it. </p>
<p>For example, if the sentence is
âThe letters in your letter are great"</p>
<p>and I'm supposed to replace "letter" with "book",</p>
<p>The output should be
"The letters in your book are great"
instead of
"The b... | -2 | 2016-08-12T05:23:07Z | 38,910,534 | <p>No of ways</p>
<p>One is (which you used):-</p>
<pre><code>âThe letters in your letter are great".replace(" letter ", " book ")
</code></pre>
<p>Other is regx</p>
| 0 | 2016-08-12T05:25:55Z | [
"python"
] |
How to replace a word in Python without replacing other forms of the word? | 38,910,496 | <p>I am supposed to change a specific word in a string without changing the other forms of it. </p>
<p>For example, if the sentence is
âThe letters in your letter are great"</p>
<p>and I'm supposed to replace "letter" with "book",</p>
<p>The output should be
"The letters in your book are great"
instead of
"The b... | -2 | 2016-08-12T05:23:07Z | 38,910,922 | <p>You may split the string into words, replace the required word and then join the final words to a string:</p>
<pre><code>def replace_word(text, findWord, replaceWord):
return ' '.join(replaceWord if word == findWord else word for word in text.split(' '))
</code></pre>
<p>Then:</p>
<pre><code>replace_word("Thi... | 0 | 2016-08-12T05:58:55Z | [
"python"
] |
How to do a partial check with string or array in Python? | 38,910,538 | <p>How to do a partial check with string or array in Python?</p>
<p>I have a string like this</p>
<p>"doamins" and it should partially match with "domainsid"</p>
<p>I tried with few examples I will explain what I need</p>
<p>eg 1: - > This is not fine as I need "domain" which should be a partial match</p>
<pre><co... | 0 | 2016-08-12T05:26:07Z | 38,911,634 | <p>First a <em>helper</em> function adapted from the <a href="https://docs.python.org/dev/library/itertools.html#itertools-recipes" rel="nofollow">itertools pairwise recipe</a> to produce substrings.</p>
<pre><code>import itertools
def n_wise(iterable, n = 2):
'''n = 2 -> (s0,s1), (s1,s2), (s2, s3), ...
n ... | 1 | 2016-08-12T06:50:20Z | [
"python",
"match",
"partial"
] |
Append dataframe in for loop | 38,910,642 | <p>If I have a pd dataframe with three columns: <code>id</code>, <code>start_time</code>, <code>end_time</code>, and I would like to transform it into a pd.df with two columns: <code>id</code>, <code>time</code></p>
<p>e.g. from <code>[001, 1, 3][002, 3, 4]</code> to <code>[001, 1][001, 2][001, 3][002, 3][002, 4]</cod... | 2 | 2016-08-12T05:34:47Z | 38,910,730 | <p>If <code>start_time</code> and <code>end_time</code> is <code>timedelta</code> use:</p>
<pre><code>df = pd.DataFrame([['001', 1, 3],['002', 3, 4]],
columns=['id','start_time','end_time'])
print (df)
id start_time end_time
0 001 1 3
1 002 3 4
#stack col... | 1 | 2016-08-12T05:42:52Z | [
"python",
"datetime",
"pandas",
"dataframe",
"resampling"
] |
Append dataframe in for loop | 38,910,642 | <p>If I have a pd dataframe with three columns: <code>id</code>, <code>start_time</code>, <code>end_time</code>, and I would like to transform it into a pd.df with two columns: <code>id</code>, <code>time</code></p>
<p>e.g. from <code>[001, 1, 3][002, 3, 4]</code> to <code>[001, 1][001, 2][001, 3][002, 3][002, 4]</cod... | 2 | 2016-08-12T05:34:47Z | 38,912,669 | <p>Here is my take on your question:</p>
<pre><code>df.set_index('id', inplace=True)
reshaped = df.apply(lambda x: pd.Series(range(x['start time'], x['end time']+1)), axis=1).\
stack().reset_index().drop('level_1', axis=1)
reshaped.columns = ['id', 'time']
reshaped
</code></pre>
<hr>
<h1>Test</h1>
<p>Input:</p... | 0 | 2016-08-12T07:49:15Z | [
"python",
"datetime",
"pandas",
"dataframe",
"resampling"
] |
Running Python script through subprocess fails | 38,910,649 | <p>I am trying to run util.py from script <code>file1.py</code> using <code>subprocess</code>. Both of them are in same directory. When I run them from current directory it works fine, but if I run <code>file1.py</code> from different directory it fails.</p>
<p>file1.py:</p>
<pre><code>#!/usr/bin/env python
import su... | 0 | 2016-08-12T05:35:16Z | 38,912,355 | <p>Executing <code>./util.py</code> in a terminal means <em>"Look in the current working directory for a file named util.py and run it</em>." The working directory is the directory from where you run the command. This means that your python script cannot see util.py if you run it from a different directory.</p>
<p>If ... | 0 | 2016-08-12T07:31:23Z | [
"python",
"subprocess"
] |
Running Python script through subprocess fails | 38,910,649 | <p>I am trying to run util.py from script <code>file1.py</code> using <code>subprocess</code>. Both of them are in same directory. When I run them from current directory it works fine, but if I run <code>file1.py</code> from different directory it fails.</p>
<p>file1.py:</p>
<pre><code>#!/usr/bin/env python
import su... | 0 | 2016-08-12T05:35:16Z | 38,913,003 | <p>You can use <code>execfile()</code> instead of <code>subprocess.Popen()</code>:</p>
<p>file1.py:</p>
<pre><code>execfile("util.py")
print "done"
</code></pre>
<p>or if you want to process both of them,you can use <code>threading</code> module which is already in python's standard library:</p>
<pre><code>from thr... | 0 | 2016-08-12T08:08:03Z | [
"python",
"subprocess"
] |
pynetdicom qyuery/retrive using study date and time | 38,910,755 | <p>I'm trying the query/retrieve example (qrscu.py) from <a href="https://pythonhosted.org/pynetdicom/usecases.html" rel="nofollow">pynetdicom</a> but
it is working good with the patient name when we search.
But I need to search the study on the basis of studyDate and studyTime.</p>
<p>Note: here some <a href="http://... | 0 | 2016-08-12T05:45:08Z | 38,911,187 | <p>I am not very familiar with python nor with the particular DICOM toolkit you are using. I dare to answer because the exception appears to be pretty clear - the toolkit does not seem to support the Study Root Query Information model. </p>
<p>DICOM queries come in four flavours which are called information models:</p... | 1 | 2016-08-12T06:20:36Z | [
"python",
"python-2.7",
"dicom",
"dcm4che"
] |
perl /pyhton/bash script to get values from files and group them | 38,910,958 | <p>I have a requirement to process values from different files. I have 5 dirs input,success,manual,retry,current. Each dir has multiple <code>*.txt</code> files. Each <code>.txt</code> file has <code>hostname=<hostname></code>. I would want to know for each hostname how many files are in input,success,retry,curre... | -3 | 2016-08-12T06:01:38Z | 38,911,939 | <p>I recommend that you either write a proper bash script or, better yet, step up to a full-on scripting language. </p>
<p>Here's an algorithm that will work:</p>
<ol>
<li>for each directory in your list:
<ol>
<li>get a list of <code>*.txt</code> files</li>
<li>open each file</li>
<li>read each line of the file loo... | 1 | 2016-08-12T07:09:02Z | [
"python",
"bash",
"perl"
] |
Python return code for os.system() and subprocess.call() command | 38,911,016 | <p>I am running python on windows server.</p>
<p>I want the return code for os.system , so that i can check whether robocopy was successful or not. </p>
<pre><code>a=os.system('robocopy \\\\aucb-net-01\\d$ \\\\nasc01\\rem\\aucb-net-01 /E /MIR')
</code></pre>
<p>will <code>"a"</code> have any value ? can i print it ?... | 0 | 2016-08-12T06:06:56Z | 38,911,511 | <p>using os.system</p>
<pre><code>import os
cmd = os.system('robocopy \\\\aucb-net-01\\d$ \\\\nasc01\\rem\\aucb-net-01 /E /MIR')
exit_code = os.WEXITSTATUS(cmd)
</code></pre>
<p>using subprocess</p>
<pre><code>import subprocess
exit_code = subprocess.call('robocopy \\\\aucb-net-01\\d$ \\\\nasc01\\rem\\aucb-net-01 /E... | 0 | 2016-08-12T06:41:32Z | [
"python",
"windows",
"robocopy"
] |
python equivalent of functools 'partial' for a class / constructor | 38,911,146 | <p>I want to create a class that behaves like collections.defaultdict, without having the usage code specify the factory. EG:
instead of </p>
<pre><code>class Config(collections.defaultdict):
pass
</code></pre>
<p>this:</p>
<pre><code>Config = functools.partial(collections.defaultdict, list)
</code></pre>
<p>Th... | 0 | 2016-08-12T06:18:02Z | 38,911,383 | <p>I don't think there's a standard method to do it, but if you need it often, you can just put together your own small function:</p>
<pre><code>import functools
import collections
def partialclass(cls, *args, **kwds):
class NewCls(cls):
__init__ = functools.partialmethod(cls.__init__, *args, **kwds)
... | 1 | 2016-08-12T06:33:05Z | [
"python",
"partial",
"functools"
] |
python equivalent of functools 'partial' for a class / constructor | 38,911,146 | <p>I want to create a class that behaves like collections.defaultdict, without having the usage code specify the factory. EG:
instead of </p>
<pre><code>class Config(collections.defaultdict):
pass
</code></pre>
<p>this:</p>
<pre><code>Config = functools.partial(collections.defaultdict, list)
</code></pre>
<p>Th... | 0 | 2016-08-12T06:18:02Z | 38,911,395 | <p>If you actually need working explicit type checks via <code>isinstance</code>, you can simply create a not too trivial subclass:</p>
<pre><code>class Config(collections.defaultdict):
def __init__(self): # no arguments here
# call the defaultdict init with the list factory
super(Config, self).__... | 1 | 2016-08-12T06:33:45Z | [
"python",
"partial",
"functools"
] |
Django REST Framework Token Registration | 38,911,202 | <p>I'm trying to create a user registration with Django-Rest-Framework. But when I go to my url I get this message:</p>
<pre><code>{ "detail": "Authentication credentials were not provided." }
</code></pre>
<p><a href="http://imgur.com/lr7PnwA" rel="nofollow">Here's a screen capture.</a></p>
<p>Is it asking for a to... | 0 | 2016-08-12T06:22:02Z | 38,911,485 | <p>Try to adding <code>permission_classes</code> decorator along <code>IsNotAuthenticated</code> to your view</p>
<pre><code>from authentication.permissions import IsNotAuthenticated
@api_view(['POST'])
@permission_classes((IsNotAuthenticated,))
def create_auth(request):
serialized = CustomUserSerializer(data=re... | 1 | 2016-08-12T06:39:32Z | [
"python",
"django",
"django-rest-framework"
] |
ImportError: No module named bottle -- WSGI + python + apache | 38,911,268 | <p>I'm trying to run a bottle app on my apache Amazon EC2 server through WSGI, and I keep getting this error:</p>
<pre><code>[Fri Aug 12 06:15:13 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/app.wsgi", line 5, in <module>
[Fri Aug 12 06:15:13 2016] [error] [client 72.219.147.5] import bott... | 0 | 2016-08-12T06:26:20Z | 38,925,531 | <p>Try uninstalling bottle from your directory and then open cmd and run it as administrater and type pip install bottle and see for yourself...</p>
<pre><code> Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>pip install bottle
Collecting bottle
U... | 0 | 2016-08-12T19:51:20Z | [
"python",
"apache",
"amazon-web-services",
"amazon-ec2",
"bottle"
] |
Python DataFrame: Why does my values change to NaN if I change the indices? | 38,911,269 | <p>I want to change my indices. My dataFrame is as follows:</p>
<pre><code>partA = pd.DataFrame({'u1': 2, 'u2': 3, 'u3':4, 'u4':29, 'u5':4, 'u6':1, 'u7':323, 'u8':9, 'u9':7, 'u10':5}, index = [20])
</code></pre>
<p>which gives a dataframe of size (1,10) with all cells filled.</p>
<p>However, when I create a new data... | 2 | 2016-08-12T06:26:25Z | 38,911,288 | <p>You need <code>values</code> for converting <code>partA</code> to <code>numpy array</code>:</p>
<pre><code>partA = pd.DataFrame({'u1': 2, 'u2': 3, 'u3':4, 'u4':29, 'u5':4, 'u6':1,
'u7':323, 'u8':9, 'u9':7, 'u10':5}, index = [20])
print (partA)
u1 u10 u2 u3 u4 u5 u6 u7 u8 u9
20 ... | 1 | 2016-08-12T06:27:53Z | [
"python",
"pandas",
"dataframe",
"multiple-columns",
null
] |
How to upload an image or any other file to online server like www.pythonanywhere.com or any other server in django ? via python scripts | 38,911,623 | <h1>Models.py</h1>
<pre><code>from django.db import models
class Stock(models.Model):
ticker = models.CharField(max_length=10)
open = models.FloatField()
close = models.FloatField()
volume = models.IntegerField()
image = models.ImageField(upload_to=r'geeky.pythonanywhere.com/files', max_length=25... | -3 | 2016-08-12T06:49:44Z | 38,955,333 | <p>PythonAnywhere dev here, try using the full absolute path in the <code>upload_to</code> argument:</p>
<pre><code>image = models.ImageField(
upload_to='/home/geeky/mysite/files',
max_length=254,
default='/home/geeky/mysite/files/default.png'
)
</code></pre>
<p>Also for the "default" argument (you might ... | 2 | 2016-08-15T12:43:39Z | [
"python",
"django",
"image",
"upload",
"backend"
] |
Dynamically update python plot for realtime visualization | 38,911,667 | <p>I am a graduate student with only limited knowledge of the Python programming language. I am currently working on creating a streaming visualization of EEG data. I am able to generate the individual topographical figures using matplotlib, but cannot find a way of dynamically updating a single plot in the output at s... | 0 | 2016-08-12T06:52:47Z | 38,912,419 | <p>If you want to make an animation with Python, then there are plenty of ways. For example:
<a href="https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/" rel="nofollow">https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/</a></p>
<p><a href="http://matplotlib.org/examples/anim... | 0 | 2016-08-12T07:34:55Z | [
"python",
"matplotlib",
"visualization"
] |
Restore deleted files using Dropbox API | 38,912,264 | <p>I was searching for a way to use Dropbox API to restore my files and Google brought me here.</p>
<p><strong>First of all, a bit about my situation:</strong></p>
<p>My computer got a virus that rename all of my files (idk if its recognized as rename or delete on Dropbox) and they are all synced to Dropbox. I want t... | 0 | 2016-08-12T07:26:44Z | 39,171,863 | <p>I've been scratching my head over this exact problem this afternoon, to try and restore the state of a friend's Dropbox which got hit by the same ransomware. I don't know whether you're still in need of a solution, but in a nutshell, here's the state of play.</p>
<p>In Dropbox API V2, every file has a unique ID. ... | 2 | 2016-08-26T17:36:20Z | [
"python",
"dropbox",
"dropbox-api"
] |
Restore deleted files using Dropbox API | 38,912,264 | <p>I was searching for a way to use Dropbox API to restore my files and Google brought me here.</p>
<p><strong>First of all, a bit about my situation:</strong></p>
<p>My computer got a virus that rename all of my files (idk if its recognized as rename or delete on Dropbox) and they are all synced to Dropbox. I want t... | 0 | 2016-08-12T07:26:44Z | 39,271,805 | <p>Thanks James Scholes, Exactly what I was looking for.
Solution works very well with the files, but this does not work for folders, Since there is no versions/revisions for a folder. In this case any other way that I can undelete the folder??.</p>
<p>Thanks,</p>
| 0 | 2016-09-01T12:38:13Z | [
"python",
"dropbox",
"dropbox-api"
] |
Restore deleted files using Dropbox API | 38,912,264 | <p>I was searching for a way to use Dropbox API to restore my files and Google brought me here.</p>
<p><strong>First of all, a bit about my situation:</strong></p>
<p>My computer got a virus that rename all of my files (idk if its recognized as rename or delete on Dropbox) and they are all synced to Dropbox. I want t... | 0 | 2016-08-12T07:26:44Z | 39,652,592 | <p>Sample code in Java:</p>
<pre><code> public static void main(String[] args) throws IOException, DbxException {
String userLocale = Locale.getDefault().toString();
DbxRequestConfig requestConfig = new DbxRequestConfig("examples-authorize", userLocale);
DbxClientV2 client = new DbxClientV2(requestCon... | 0 | 2016-09-23T04:22:05Z | [
"python",
"dropbox",
"dropbox-api"
] |
Identify Thread in Python | 38,912,407 | <p>I've a python Socket server running and also socket clients.</p>
<p>Now, for example say there are 3 clients connected to same server. Please find below the code of the server.</p>
<pre><code>#!/usr/bin/python # This is server.py file
import socket # Import socket module
import threading
... | 0 | 2016-08-12T07:34:25Z | 38,921,159 | <p>You can use Queues and multiple threads per connection to solve this problem.</p>
<p>Basic outline:</p>
<ol>
<li><p>Each client connection spawns two threads - one to monitor client input and another which monitors a Queue. Items placed on the queue will be sent to the client. Each client connection will have its ... | 1 | 2016-08-12T15:08:04Z | [
"python",
"multithreading",
"sockets",
"server",
"client-server"
] |
How to fill the form if query returns None | 38,912,480 | <p>I use sqlalchemy to query ip in my database,when result returns ,everything is ok,how can i remain blank in my form when no result returns.</p>
<p>error</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'Ip'
</code></pre>
<p>code</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login... | 0 | 2016-08-12T07:38:48Z | 38,912,840 | <p>You can use a simple if condition for this..</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login_required
def post():
caseid=Masterlist.query.filter_by(Ip=request.args.get('Ip')).first()
if caseid:
form = RepairForm(request.form)
print request.form
if request.form.ge... | 0 | 2016-08-12T07:59:28Z | [
"python",
"forms",
"flask",
"sqlalchemy"
] |
How to fill the form if query returns None | 38,912,480 | <p>I use sqlalchemy to query ip in my database,when result returns ,everything is ok,how can i remain blank in my form when no result returns.</p>
<p>error</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'Ip'
</code></pre>
<p>code</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login... | 0 | 2016-08-12T07:38:48Z | 38,913,541 | <p>Solution here lol</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login_required
def post():
# Ip=Ip
# Ip=Ip
# print Ip
# Ip=request.args['Ip']
# Ip=request.args.get('Ip')
caseid=Masterlist.query.filter_by(Ip=request.args.get('Ip')).first()
form = RepairForm(request.form)
if cas... | 0 | 2016-08-12T08:38:09Z | [
"python",
"forms",
"flask",
"sqlalchemy"
] |
send_keys does not working in django testing | 38,912,562 | <p>I want functional testing</p>
<p>functional test process is</p>
<ol>
<li>Create_user</li>
<li>log in the website using created user</li>
<li>click a button named <code>booksale</code></li>
</ol>
<p><strong>In <code>myproject/functional_test/test_booksale.py</code></strong></p>
<pre><code>from selenium import web... | 2 | 2016-08-12T07:42:53Z | 38,913,048 | <p>If <code>book_sale</code> element is button, you should try using <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.click" rel="nofollow"><code>.click()</code></a> instead of <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webele... | 1 | 2016-08-12T08:09:52Z | [
"python",
"django",
"selenium",
"testing"
] |
Python decimal precision and rounding | 38,912,563 | <p>I want to limit the precision of my float and use it as an exact value for next operations, but I'm doing something wrong with decimal module.</p>
<pre><code>from decimal import *
factor = 350/float(255)
# Settings
getcontext().prec = 1
getcontext().rounding = ROUND_UP
print Decimal(factor)
</code></pre>
<p>Pyt... | 0 | 2016-08-12T07:42:56Z | 38,913,962 | <p>From Python Documentation: (<a href="https://docs.python.org/2/library/decimal.html" rel="nofollow">https://docs.python.org/2/library/decimal.html</a>)</p>
<p>The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play <strong>during arith... | 0 | 2016-08-12T08:58:16Z | [
"python",
"decimal",
"rounding"
] |
How to get an object bounding box given pixel label in python? | 38,912,569 | <p>Say I have a scene parsing map for an image, each pixel in this scene parsing map indicates which object this pixel belongs to. Now I want to get bounding box of each object, how can I implement this in python?
For a detail example, say I have a scene parsing map like this: </p>
<pre><code>0 0 0 0 0 0 0
0 1 1 0 0 0... | 0 | 2016-08-12T07:43:25Z | 38,912,884 | <p>using numpy:</p>
<pre><code>import numpy as np
ind = np.nonzero(arr.any(axis=0))[0] # indices of non empty columns
width = ind[-1] - ind[0] + 1
ind = np.nonzero(arr.any(axis=1))[0] # indices of non empty rows
height = ind[-1] - ind[0] + 1
</code></pre>
<p>a bit more explanation:</p>
<p><code>arr.any(axis=0)</co... | 1 | 2016-08-12T08:01:29Z | [
"python",
"image-processing"
] |
How to get an object bounding box given pixel label in python? | 38,912,569 | <p>Say I have a scene parsing map for an image, each pixel in this scene parsing map indicates which object this pixel belongs to. Now I want to get bounding box of each object, how can I implement this in python?
For a detail example, say I have a scene parsing map like this: </p>
<pre><code>0 0 0 0 0 0 0
0 1 1 0 0 0... | 0 | 2016-08-12T07:43:25Z | 38,914,055 | <p>If you are processing images, you can use scipy's ndimage library.</p>
<p>If there is only one object in the image, you can get the measurements with scipy.ndimage.measurements.find_objects (<a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.measurements.find_objects.html" rel="nofoll... | 1 | 2016-08-12T09:03:18Z | [
"python",
"image-processing"
] |
"Undecorate" Turtle Window | 38,912,653 | <p>For a scientific experiment I wrote a <code>turtle.py</code>, which opens a 800x480 window and draws a slowly growing black dot. The <code>turtle.py</code> is started with <code>C:\Users\kaza>python C:\Users\kaza\Desktop\Python_scripts\turtle.py "black" 900 40 1 20 20 10 0 0 30 10</code> in the cmd. <code>black</... | 1 | 2016-08-12T07:48:22Z | 38,972,802 | <p>The standard module <code>turtle</code> uses Tk (through the <code>Tkinter</code> module in Python) for its windows. When you want to undecorate Tk windows, you could use the <code>overrideredirect</code> method of the <code>Toplevel</code> class. This was suggested in <a href="/questions/37197213/launch-tkinter-wit... | 1 | 2016-08-16T10:43:45Z | [
"python",
"turtle-graphics"
] |
Celery - Given a task_id, execute the task | 38,912,661 | <p>I'm creating a celery task in a situation where task producers are more than consumers(workers). Now since my queues are getting filled up and the workers consume in FCFS manner, can I get to execute a specific task(given a task_id) instantly?</p>
<p>for eg:-</p>
<p>My tasks are filled in the following fashion. <c... | 3 | 2016-08-12T07:48:51Z | 38,913,906 | <blockquote>
<p>how can I execute a task given an id ?</p>
</blockquote>
<p>the short answer is you can't. Celery workers pull tasks off the broker backend as they become available.</p>
<p><strong>Why not?</strong></p>
<p>Note that's not a limitation of Celery as such, rather it is a characteristic of message queu... | 0 | 2016-08-12T08:56:04Z | [
"python",
"celery"
] |
Ubuntu run python script on system startup that is using Firefox | 38,912,819 | <p>I wrote python script that uses <code>subprocess.pOpen()</code> module to run and manipulate with 2 GUI programs: Firefox and VLC player. I am using Ubuntu 14.04 LTS operating system in Desktop mode.</p>
<p>My problem is when I try to run that python script when system starts, script is running but Firefox or VLC d... | 0 | 2016-08-12T07:58:08Z | 38,916,866 | <p>Found solution to my problem. When you are running commands with <code>pOpen</code> in python like this:</p>
<pre><code>FNULL = open(os.devnull, 'w')
_FIREFOX_START = ["sudo", "firefox", "test.com/index.html"]
subprocess.Popen(self._FIREFOX_START, stdout=self.FNULL, stderr=subprocess.STDOUT)
</code></pre>
<p>it wo... | 0 | 2016-08-12T11:26:30Z | [
"python",
"linux",
"shell",
"ubuntu",
"firefox"
] |
python webframework django noreversematch | 38,912,896 | <p><a href="http://i.stack.imgur.com/6ybxC.png" rel="nofollow">here is screenshot error</a>
i dont understand why i am getting error after clicking add photo button in details page but if i type url it works fine but after submitting i want to return to the details page but it gives me this error
my views.py</p>
<pre>... | 0 | 2016-08-12T08:02:06Z | 38,913,460 | <p>The problem is that you are not passing the <code>pk</code> in the template. From the screenshot, if you look at the highlight line in the template it is clear that your URL is missing the keyword argument that is needed...</p>
<p>The same is also mentioned in the first line of the error page (with keyword args {})... | 1 | 2016-08-12T08:33:32Z | [
"python",
"django"
] |
For each loop with JSON object python | 38,913,040 | <p>Alright, so I'm struggling a little bit with trying to parse my JSON object.
My aim is to grab the certain JSON key and return it's value. </p>
<p><strong>JSON File</strong></p>
<pre><code>{
"files": {
"resources": [
{
"name": "filename",
"hash": "0x001"
},
{
"name":... | -1 | 2016-08-12T08:09:24Z | 38,913,098 | <p>By using <code>name, hash</code> as the <code>for</code> loop target, you are <em>unpacking</em> the dictionary:</p>
<pre><code>>>> d = {"name": "filename", "hash": "0x001"}
>>> name, hash = d
>>> name
'name'
>>> hash
'hash'
</code></pre>
<p>This happens because iteration over ... | 3 | 2016-08-12T08:13:24Z | [
"python",
"json"
] |
For each loop with JSON object python | 38,913,040 | <p>Alright, so I'm struggling a little bit with trying to parse my JSON object.
My aim is to grab the certain JSON key and return it's value. </p>
<p><strong>JSON File</strong></p>
<pre><code>{
"files": {
"resources": [
{
"name": "filename",
"hash": "0x001"
},
{
"name":... | -1 | 2016-08-12T08:09:24Z | 38,913,178 | <p>The problem seems to be you have a list of dictionaries, first get each element of the list, and then ask the element (which is the dictionary) for the values for keys name and hash</p>
<p>EDIT: this is tested and works</p>
<pre><code>mydict = {"files": { "resources": [{ "name": "filename", "hash": "0x001"},{ "... | -2 | 2016-08-12T08:17:37Z | [
"python",
"json"
] |
For each loop with JSON object python | 38,913,040 | <p>Alright, so I'm struggling a little bit with trying to parse my JSON object.
My aim is to grab the certain JSON key and return it's value. </p>
<p><strong>JSON File</strong></p>
<pre><code>{
"files": {
"resources": [
{
"name": "filename",
"hash": "0x001"
},
{
"name":... | -1 | 2016-08-12T08:09:24Z | 38,913,223 | <p>So what you intend to do is :</p>
<pre><code>for dic in x["files"]["resources"]:
print dic['name'],dic['hash']
</code></pre>
<p>You need to iterate on those dictionaries in that array resources.</p>
| 0 | 2016-08-12T08:20:21Z | [
"python",
"json"
] |
For each loop with JSON object python | 38,913,040 | <p>Alright, so I'm struggling a little bit with trying to parse my JSON object.
My aim is to grab the certain JSON key and return it's value. </p>
<p><strong>JSON File</strong></p>
<pre><code>{
"files": {
"resources": [
{
"name": "filename",
"hash": "0x001"
},
{
"name":... | -1 | 2016-08-12T08:09:24Z | 38,913,248 | <p>If in case you have multiple files and multiple resources inside it. This generalized solution works.</p>
<pre><code>for keys in patcher:
for indices in patcher[keys].keys():
print(patcher[keys][indices])
</code></pre>
<p>Checked output from myside</p>
<pre><code>for keys in patcher:
... for... | -2 | 2016-08-12T08:23:07Z | [
"python",
"json"
] |
Make the median line of matplotlib boxplot invisible | 38,913,144 | <p>By default, the median line of a matplotlib boxplot is red. How can I make it invisible, or how can I get rid of it?</p>
| 0 | 2016-08-12T08:15:40Z | 38,913,737 | <p>This example uses a custom setting of <code>medianprops</code>: <a href="http://matplotlib.org/examples/statistics/boxplot_demo.html" rel="nofollow">http://matplotlib.org/examples/statistics/boxplot_demo.html</a>. Try using <code>linewidth=0</code> or <code>linestyle=None</code>.</p>
<p>How to set the linestyle is ... | 1 | 2016-08-12T08:47:32Z | [
"python",
"matplotlib",
"boxplot"
] |
How to convert text from TextArea to file? | 38,913,164 | <p>I have a <code>form</code> where <code>User</code> can fill either text to translate or attach a file. If the text to translate has been filled, I want to create a txt file from it so it seems like <code>User</code> uploaded a <code>txt</code> file. </p>
<pre><code> if job_creation_form.is_valid():
c... | 0 | 2016-08-12T08:16:28Z | 38,913,285 | <p>use a <a href="https://docs.python.org/2/library/tempfile.html" rel="nofollow">tempfile</a> maybe?</p>
<pre><code>import tempfile
tmp = tempfile.TemporaryFile()
tmp.write("Hello World!\n")
Job.objects.create(file=File(tmp),...)
</code></pre>
<p>Hope this helps</p>
| 1 | 2016-08-12T08:25:21Z | [
"python",
"django",
"django-models",
"django-forms",
"django-uploads"
] |
How come these strings are not equal? | 38,913,204 | <p>I have been trying out (for my own personal use) some peoples' solutions to timed keyboard inputs and the only one that has worked was one by Alex Martelli/martineau <a href="http://stackoverflow.com/questions/2933399/how-to-set-time-limit-on-input">here.</a> I used their second block of code (starting with import m... | 1 | 2016-08-12T08:19:27Z | 38,913,310 | <p>You probably have some unseen bytes after the string. Try to <code>print([c for c in textVar])</code> and if it shows characters lie <code>'\r'</code> and <code>\n</code> try <code>str(textVar).strip() == "test"</code> or remove those chars manually.</p>
| 0 | 2016-08-12T08:26:37Z | [
"python",
"python-2.7",
"input"
] |
How come these strings are not equal? | 38,913,204 | <p>I have been trying out (for my own personal use) some peoples' solutions to timed keyboard inputs and the only one that has worked was one by Alex Martelli/martineau <a href="http://stackoverflow.com/questions/2933399/how-to-set-time-limit-on-input">here.</a> I used their second block of code (starting with import m... | 1 | 2016-08-12T08:19:27Z | 38,913,316 | <p>You won't be able to see why the strings are different just by printing. String values can contain bytes that are not (easily) visible on a console when printed.</p>
<p>Use the <a href="https://docs.python.org/2/library/functions.html#repr" rel="nofollow"><code>repr()</code> function</a> to produce a <em>debugging-... | 2 | 2016-08-12T08:26:58Z | [
"python",
"python-2.7",
"input"
] |
How come these strings are not equal? | 38,913,204 | <p>I have been trying out (for my own personal use) some peoples' solutions to timed keyboard inputs and the only one that has worked was one by Alex Martelli/martineau <a href="http://stackoverflow.com/questions/2933399/how-to-set-time-limit-on-input">here.</a> I used their second block of code (starting with import m... | 1 | 2016-08-12T08:19:27Z | 38,913,339 | <p>If you consider this fragment of code:</p>
<pre><code>result = []
while True:
if msvcrt.kbhit():
result.append(msvcrt.getche())
if result[-1] == '\r': # or \n, whatever Win returns;-)
return ''.join(result)
</code></pre>
<p>You can see that when building the input string, the fina... | 1 | 2016-08-12T08:27:42Z | [
"python",
"python-2.7",
"input"
] |
Python script to launch and configure several programms | 38,913,256 | <p>I've got an application which I want to debug locally. To do so, I have to run <code>Consul</code> first (it's a <code>jar</code>), then I have to call 2 two <code>REST API</code> methods so I call two <code>POST</code>s. Then I launch <code>elasticmq-server</code> and call <code>8</code> <code>GET</code>s.</p>
<p>... | 0 | 2016-08-12T08:23:22Z | 38,913,621 | <p>The <code>subprocess</code> module has specific support for handling new window creation on Windows with <a href="https://docs.python.org/2/library/subprocess.html#subprocess.STARTUPINFO" rel="nofollow">startupinfo</a>.
On *nix and Linux you want to actually spawn a new terminal emulator so you would call something ... | 0 | 2016-08-12T08:42:11Z | [
"java",
"python",
"scripting",
"subprocess",
"python-requests"
] |
Python script to launch and configure several programms | 38,913,256 | <p>I've got an application which I want to debug locally. To do so, I have to run <code>Consul</code> first (it's a <code>jar</code>), then I have to call 2 two <code>REST API</code> methods so I call two <code>POST</code>s. Then I launch <code>elasticmq-server</code> and call <code>8</code> <code>GET</code>s.</p>
<p>... | 0 | 2016-08-12T08:23:22Z | 38,983,520 | <p>I know for a fact, that you cannot port the said <code>call</code> method between Windows and Linux. You have to search for another solution.</p>
| 1 | 2016-08-16T20:04:11Z | [
"java",
"python",
"scripting",
"subprocess",
"python-requests"
] |
Adding delimiters to a text file using python | 38,913,301 | <p>I have recently started my job as an ETL Developer and as a part of my exercise, I am extracting data from a text file containing raw data. My raw data looks like this as shown in the image.
<a href="http://i.stack.imgur.com/YE76K.png" rel="nofollow">My Raw Data</a></p>
<p>Now I want to add delimiters to my data fi... | 0 | 2016-08-12T08:25:55Z | 38,913,469 | <p>So when you write to file you need to encode it before writing. If you google that you will find ton of results.</p>
<p>Here is how it can be done :</p>
<pre><code>output.write(new_line.encode('utf-8'))# or ascii
</code></pre>
<p>You can also ask to ignore which can't be converted but that wil cause loss of chara... | 0 | 2016-08-12T08:33:57Z | [
"python",
"etl"
] |
Adding delimiters to a text file using python | 38,913,301 | <p>I have recently started my job as an ETL Developer and as a part of my exercise, I am extracting data from a text file containing raw data. My raw data looks like this as shown in the image.
<a href="http://i.stack.imgur.com/YE76K.png" rel="nofollow">My Raw Data</a></p>
<p>Now I want to add delimiters to my data fi... | 0 | 2016-08-12T08:25:55Z | 38,913,826 | <p>When you open a file in python 3 in "text" mode then reading and writing convert the bytes in the file to python (unicode) strings. The default encoding is platform dependent, but is usually UTF-8. </p>
<p>If you file uses latin-1 encoding, you should open with</p>
<pre><code>with open('locations.txt', 'r', encod... | 1 | 2016-08-12T08:51:49Z | [
"python",
"etl"
] |
convert Series to DataFrame | 38,913,355 | <p>I created a dataframe 'x' </p>
<p>I wanted to create another dataframe y which consists of values of feature 'wheat_type' from dataframe x</p>
<p>so i executed the code</p>
<pre><code>y=X.loc[:, 'wheat_type']
</code></pre>
<p>when I ran the following command</p>
<pre><code>y['wheat_type'] = y.wheat_type("catego... | 1 | 2016-08-12T08:28:31Z | 38,913,459 | <p>There's a special method for that - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_frame.html" rel="nofollow"><code>pd.Series.to_frame</code></a></p>
<pre><code>In [2]: df = pd.DataFrame({'a': range(4)})
In [3]: df.a
Out[3]:
0 0
1 1
2 2
3 3
Name: a, dtype: int64
In [4... | 1 | 2016-08-12T08:33:29Z | [
"python",
"pandas",
"dataframe",
"series",
"categorical-data"
] |
convert Series to DataFrame | 38,913,355 | <p>I created a dataframe 'x' </p>
<p>I wanted to create another dataframe y which consists of values of feature 'wheat_type' from dataframe x</p>
<p>so i executed the code</p>
<pre><code>y=X.loc[:, 'wheat_type']
</code></pre>
<p>when I ran the following command</p>
<pre><code>y['wheat_type'] = y.wheat_type("catego... | 1 | 2016-08-12T08:28:31Z | 38,913,886 | <p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_frame.html" rel="nofollow"><code>to_frame</code></a>:</p>
<pre><code>X = pd.DataFram... | 1 | 2016-08-12T08:55:05Z | [
"python",
"pandas",
"dataframe",
"series",
"categorical-data"
] |
How do I install a python package to /usr/local/bin? | 38,913,502 | <p>I am trying to install a python package on my ubuntu.I am trying to install it through a setup script which i had written.The setup.py script looks like this:</p>
<pre><code> from setuptools import setup
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
n... | 0 | 2016-08-12T08:36:01Z | 38,914,415 | <p>Try install your packages with pip using this </p>
<pre><code>pip install --install-option="--prefix=$PREFIX_PATH" package_name
</code></pre>
<p>as described here <a href="http://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip">Install a Python package into a diffe... | 0 | 2016-08-12T09:23:12Z | [
"python",
"ubuntu",
"installation"
] |
How do I install a python package to /usr/local/bin? | 38,913,502 | <p>I am trying to install a python package on my ubuntu.I am trying to install it through a setup script which i had written.The setup.py script looks like this:</p>
<pre><code> from setuptools import setup
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
n... | 0 | 2016-08-12T08:36:01Z | 38,915,028 | <p>Currently, you're using a <code>scripts</code> tag to install your python code. This will put your code in <code>/usr/local/bin</code>, which is not in <code>PYTHONPATH</code>.</p>
<p>According to <a href="https://docs.python.org/2/distutils/setupscript.html" rel="nofollow">the documentation</a>, you use <code>scri... | 0 | 2016-08-12T09:52:48Z | [
"python",
"ubuntu",
"installation"
] |
How to open downgrade a file in python using an NFS mount | 38,913,588 | <p>I am running some experiments against NFS and would like to open-downgrade a file in my NFS mount but I do not which python command should I use for that.</p>
| -1 | 2016-08-12T08:40:33Z | 38,962,289 | <p>If an open-owner has opened the same file multiple times with different access and deny values, closing one of the opens will result in invocation of open_downgrade on NFS server.</p>
<pre><code>fd1 = open("/home/ubuntu/v4/foo", 'r')
fd2 = open("/home/ubuntu/v4/foo", 'w')
fd1.close()
</code></pre>
| 0 | 2016-08-15T20:08:05Z | [
"python",
"nfs",
"nfsclient"
] |
what is logical AND doing here ,is it catching error | 38,913,594 | <p>If I run <code>script.py</code> without passing argument it shows </p>
<pre><code>error: list index out of bounds
</code></pre>
<p><strong>script.py</strong>:</p>
<pre><code>from sys import *
if argv[1]=="what":
print "done"
else:
pass
</code></pre>
<p>If I run <code>script1.py</code> without passing errors ... | -1 | 2016-08-12T08:40:49Z | 38,913,655 | <p>The and ensures that you have at least 2 arguments to the script as well as a second argument with value "what". If you don't pass in that argument, this evaluates to false by short-circuiting (since <code>len(argv)</code> is only 1), so there is no error.</p>
| 0 | 2016-08-12T08:43:30Z | [
"python",
"subprocess"
] |
what is logical AND doing here ,is it catching error | 38,913,594 | <p>If I run <code>script.py</code> without passing argument it shows </p>
<pre><code>error: list index out of bounds
</code></pre>
<p><strong>script.py</strong>:</p>
<pre><code>from sys import *
if argv[1]=="what":
print "done"
else:
pass
</code></pre>
<p>If I run <code>script1.py</code> without passing errors ... | -1 | 2016-08-12T08:40:49Z | 38,913,760 | <pre><code>if len(argv)==2 and argv[1]=="what"
</code></pre>
<p>"Logical and" evaluate the left statement, then the right statement.</p>
<p>If the left statement return "false" then the right statement will not be evaluated.</p>
| 0 | 2016-08-12T08:48:31Z | [
"python",
"subprocess"
] |
Python: String [ [k1:v1, k2:v2], [k3:v3] ] to Object | 38,913,684 | <p>I'm stuck with an application that outputs the following</p>
<pre><code>[[_type:logs, _id:AVY0ofxOHiyEPsw_vkZS, _index:firewall-all-2016.07.29, _score:13.445344], [_type:logs, _id:AVY1EI1z79siNC3TEi7P, _index:firewall-all-2016.07.29, _score:13.445344]]
</code></pre>
<p>I would like to parse this text into an itera... | 2 | 2016-08-12T08:44:41Z | 38,913,985 | <p>How about this:</p>
<pre><code>import re
data = "[[_type:logs, _id:AVY0ofxOHiyEPsw_vkZS, _index:firewall-all-2016.07.29, _score:13.445344], [_type:logs, _id:AVY1EI1z79siNC3TEi7P, _index:firewall-all-2016.07.29, _score:13.445344]]"
parsed_1 = re.findall("\[(.*?)\]", data[1:-1])
parsed_list = []
for line in parsed... | 1 | 2016-08-12T08:59:23Z | [
"python",
"converter"
] |
OpenCV3 Python, svm.train() TypeError | 38,913,720 | <p>When I use Opencv3 with Python2, my code is to do something with SVM.</p>
<p>But an Error is shown:</p>
<blockquote>
<p>svm.train(trainData,responses,params = svm_params) TypeError: only
length-1 arrays can be converted to Python scalars</p>
</blockquote>
| 1 | 2016-08-12T08:46:27Z | 38,936,903 | <p>This error occurred because the function was expecting a single array object and <code>trainData</code> variable contained multiple array objects. There are several ways to solve this, one of them is, say if your input object is:</p>
<pre><code># Used for creating training samples for a logic gate (eg: xor) NN
trai... | 0 | 2016-08-13T20:51:35Z | [
"python",
"svm",
"opencv3.0"
] |
Django FormView Response | 38,913,762 | <p>Hy! I created a new Django project to upload a photo using a FormView. The photo gets processed and a download link is provided. The problem is the response: I want the html page to stay the same, only the download link should be added.</p>
<pre><code>class ColorImageView(FormView):
template_name = 'images.html'
... | 0 | 2016-08-12T08:48:33Z | 38,913,956 | <p>Just edit <code>images.html</code> with something like:</p>
<pre><code>{% if download_link %}
<a href="{{ download_link }}">Download</a>
{% endif %}
</code></pre>
<p>And pass the URL in the view:</p>
<pre><code>def form_valid(self):
download_link = ''
return self.render_to_response(self.get_... | 0 | 2016-08-12T08:57:55Z | [
"python",
"django",
"httpresponse",
"formview"
] |
Python: How to calculate combinations of parts of a given number, giving the number, list lenght, first and last number | 38,913,852 | <p>I'm very stuck on this ( probably because I'm new to computer programming ).
I have the following code, from the question: [<a href="http://stackoverflow.com/questions/37616841/python-find-all-possible-combinations-of-parts-of-a-given-number/37617708?noredirect=1#comment62719215_37617708]">Python: Find all possible ... | 0 | 2016-08-12T08:53:04Z | 38,916,373 | <p>Since you know the first number, you just need to solve if for the last one. </p>
<p>In your example, that would give something like:</p>
<pre><code>for res in sum_to_n(n=8-4, last=1, size=3-1):
print([4] + res)
</code></pre>
| 1 | 2016-08-12T11:00:11Z | [
"python",
"math",
"combinatorics"
] |
How can I capture the group catch by starts in python? | 38,913,868 | <p>I'm using python2.7 and I want to capture all module names by import "os", "ma"
so i use regular expresson from the <code>re</code> module to do this. I created a test string:</p>
<pre><code>testString = "import os, math, string"
</code></pre>
<p>Here I'm using regular expression:</p>
<pre><code>import re
pattern... | 1 | 2016-08-12T08:53:55Z | 38,913,953 | <p>You have a typo: use <code>\w+</code> instead of <code>\w</code>:</p>
<pre><code>pattern = re.compile(r"^import\s+(\w+,\s*)*(\w+)")
</code></pre>
<p>But the main problem is: <code>re</code> module doesn't support repeated captures (<code>regex</code> supports it)</p>
<pre><code>>>> m = regex.match("^impo... | 0 | 2016-08-12T08:57:54Z | [
"python",
"regex"
] |
How can I capture the group catch by starts in python? | 38,913,868 | <p>I'm using python2.7 and I want to capture all module names by import "os", "ma"
so i use regular expresson from the <code>re</code> module to do this. I created a test string:</p>
<pre><code>testString = "import os, math, string"
</code></pre>
<p>Here I'm using regular expression:</p>
<pre><code>import re
pattern... | 1 | 2016-08-12T08:53:55Z | 38,917,478 | <p>The <code>import os, math, string</code> string seems to start with <code>import</code>, so, all you need is to check whether the string starts with <code>import</code>, and then remove it and split with <code>,</code>:</p>
<pre><code>testString = "import os, math, string"
if testString.startswith("import "):
p... | 1 | 2016-08-12T12:01:36Z | [
"python",
"regex"
] |
How can I capture the group catch by starts in python? | 38,913,868 | <p>I'm using python2.7 and I want to capture all module names by import "os", "ma"
so i use regular expresson from the <code>re</code> module to do this. I created a test string:</p>
<pre><code>testString = "import os, math, string"
</code></pre>
<p>Here I'm using regular expression:</p>
<pre><code>import re
pattern... | 1 | 2016-08-12T08:53:55Z | 38,921,616 | <pre><code>testString = "import os, math, string"
re.findall(r"\b(\w+)(?:,|$)", testString)
</code></pre>
<p>The output is:</p>
<pre><code>['os', 'math', 'string']
</code></pre>
| 1 | 2016-08-12T15:32:50Z | [
"python",
"regex"
] |
How can I capture the group catch by starts in python? | 38,913,868 | <p>I'm using python2.7 and I want to capture all module names by import "os", "ma"
so i use regular expresson from the <code>re</code> module to do this. I created a test string:</p>
<pre><code>testString = "import os, math, string"
</code></pre>
<p>Here I'm using regular expression:</p>
<pre><code>import re
pattern... | 1 | 2016-08-12T08:53:55Z | 38,951,485 | <p><a href="http://stackoverflow.com/questions/38913868/how-can-i-capture-the-group-catch-by-starts-in-python/38921616#38921616">jcxu's answer</a> is pretty nice, here is another one.</p>
<pre><code>testString = "import os, math, string"
re.search(r"(?!import)\s(\w.+)", testString).group(1).split(', ')
</code></pre>
... | 0 | 2016-08-15T08:09:48Z | [
"python",
"regex"
] |
Why is data hiding a key part of OOP and not Imperative or Functional programming? | 38,913,937 | <p>Is it used in other programming paradigms as well? What would be a good example of when and when not to use it?</p>
| -2 | 2016-08-12T08:57:20Z | 38,914,130 | <p>Oh, this is a very broad topic and it differs very much from the language/environment in wich you are working.</p>
<p>For example python doesn't really spend much thought about encapsulation: <a href="http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private">Why are Python's... | 1 | 2016-08-12T09:07:35Z | [
"python",
"oop",
"data-hiding"
] |
Make the size of a heatmap bigger with seaborn | 38,913,965 | <p>I create a heatmap with seaborn </p>
<pre><code>df1.index = pd.to_datetime(df1.index)
df1 = df1.set_index('TIMESTAMP')
df1 = df1.resample('30min').mean()
ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)
</code></pre>
<p>But the probleme is when there is lot of data in the dataframe the heatmap will ... | -1 | 2016-08-12T08:58:22Z | 38,914,112 | <p>You could alter the <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure" rel="nofollow"><code>figsize</code></a> by passing a <code>tuple</code> showing the <code>width, height</code> parameters you would like to keep. </p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots(f... | 1 | 2016-08-12T09:06:40Z | [
"python",
"heatmap",
"seaborn"
] |
Make the size of a heatmap bigger with seaborn | 38,913,965 | <p>I create a heatmap with seaborn </p>
<pre><code>df1.index = pd.to_datetime(df1.index)
df1 = df1.set_index('TIMESTAMP')
df1 = df1.resample('30min').mean()
ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)
</code></pre>
<p>But the probleme is when there is lot of data in the dataframe the heatmap will ... | -1 | 2016-08-12T08:58:22Z | 38,914,119 | <blockquote>
<p><strong>fmt</strong> : string, optional String formatting code to use when adding
annotations</p>
</blockquote>
<p>Origin: <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html" rel="nofollow">Seaborn docs</a></p>
<p>Add fmt parameter with d to show it as integer</... | 1 | 2016-08-12T09:06:50Z | [
"python",
"heatmap",
"seaborn"
] |
Yatzy, how do I refer to my Player-attributes? | 38,914,031 | <p>I have a huge problem right now, I cannot refer to my Player-attributes, my code is looking like this currently:</p>
<pre><code>from terminaltables import AsciiTable
class Player:
def __init__(self,name):
self.name=name
self.ones=0
self.twos=0
self.threes=0
self.fours=0
... | 1 | 2016-08-12T09:02:20Z | 38,914,094 | <p><code>spelarlista.append("name")</code> means that the first item in your list is a string. Then later you try to access <code>spelarlista[0].ones</code>.</p>
<p>As the error message says, string objects do not have an attribute <code>ones</code>.</p>
| 3 | 2016-08-12T09:05:42Z | [
"python"
] |
OpenSSL error - RestClient Gem - Python WSGI | 38,914,068 | <h2>Issue :</h2>
<p>I'm struggling on a SSL issue. I'm trying to connect to a Web server for a Python application but each time I execute a request, I have this error : </p>
<pre><code>RestClient::SSLCertificateNotVerified: SSL_connect returned=1 errno=0 state=error: certificate verify failed:
</code></pre>
<h2>Deta... | 0 | 2016-08-12T09:04:08Z | 39,039,535 | <p>It turns out the gevent.pywsgi server did not handle the SSL certificate correctly.
I installed Nginx and did a reverse proxy on the localhost Python gevent.pywsgi server and did the SSL handling on the Nginx part and it worked instantly.</p>
<p>For information, my nginx conf :</p>
<pre><code>server{
liste... | 0 | 2016-08-19T12:51:52Z | [
"python",
"ruby",
"ssl",
"wsgi",
"rest-client"
] |
Run a part of code every 5 min independently of the other commands | 38,914,104 | <p>I want to open, stay open for 6 seconds and close one relay every 5 minutes while the rest code running normally. </p>
<p>For example:</p>
<pre><code>GPIO.output(18, 1)
sleep(6)
GPIO.output(18, 0)
sleep(300)
</code></pre>
<p>But without the rest program stacks in this delay. My Python code is:</p>
<pre><code>im... | 3 | 2016-08-12T09:06:25Z | 38,914,193 | <p>You can put the logic for this in different thread. Will stop freezing your program and won't affect it's workflow. </p>
| 0 | 2016-08-12T09:10:59Z | [
"python",
"raspberry-pi3"
] |
Run a part of code every 5 min independently of the other commands | 38,914,104 | <p>I want to open, stay open for 6 seconds and close one relay every 5 minutes while the rest code running normally. </p>
<p>For example:</p>
<pre><code>GPIO.output(18, 1)
sleep(6)
GPIO.output(18, 0)
sleep(300)
</code></pre>
<p>But without the rest program stacks in this delay. My Python code is:</p>
<pre><code>im... | 3 | 2016-08-12T09:06:25Z | 38,914,479 | <p>Threads offer a convenient way to do this. I normally create a <code>threading.Thread</code> subclass, whose <code>run</code> method is the code to be run in a separate thread. So you would want something like:</p>
<pre><code>class BackgroundRunner(threading.thread):
def run(self):
while True:
... | 4 | 2016-08-12T09:25:38Z | [
"python",
"raspberry-pi3"
] |
Run a part of code every 5 min independently of the other commands | 38,914,104 | <p>I want to open, stay open for 6 seconds and close one relay every 5 minutes while the rest code running normally. </p>
<p>For example:</p>
<pre><code>GPIO.output(18, 1)
sleep(6)
GPIO.output(18, 0)
sleep(300)
</code></pre>
<p>But without the rest program stacks in this delay. My Python code is:</p>
<pre><code>im... | 3 | 2016-08-12T09:06:25Z | 38,914,735 | <p>Apart from the suggested threading methods, you can also use an interrupt using the python signal module. Interrupts are cheaper than threads, which may be more appropriate on your chosen platform.</p>
<p>You can find more examples here: <a href="https://docs.python.org/2/library/signal.html" rel="nofollow">https:/... | 3 | 2016-08-12T09:38:11Z | [
"python",
"raspberry-pi3"
] |
python 3.4, setting up QWidgets.QMessageBox | 38,914,151 | <p>an update to my code, based on the reply of Israel Unterman:</p>
<p>The Error-Class is now</p>
<pre><code>from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow
class Error(QtWidgets.QMainWindow):
reply = False
last_reply_id = None
last_id = 0
def __init__(self, error_code_string, pa... | 0 | 2016-08-12T09:08:54Z | 38,915,140 | <p>You didn't create an object of the message box. To create an object use:</p>
<pre><code>msg_box = QMessageBox()
</code></pre>
<p>But you don'y need to go through all this, since <code>QMessageBox</code> has static functions for showing messages, which you can call directly on the <code>QMessageBox</code> class. Fo... | 0 | 2016-08-12T09:57:53Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5",
"qmessagebox"
] |
find most occurring word in text file using dictionary | 38,914,461 | <p>My question is similar to <a href="http://stackoverflow.com/questions/21297740/how-to-find-set-of-most-frequently-occurring-word-pairs-in-a-file-using-python">this</a> but slightly different. I am trying to read through a file, looking for lines containing emails starting with 'From' and then creating a dictionary t... | 1 | 2016-08-12T09:24:51Z | 38,914,661 | <p>Your loop over <code>matches</code> and over <code>found</code> do not have the right indentation. First you iterate over all lines in file and add all lines which start with "From " to matches. <strong>Afterwards</strong> you have to iterate over those matches. Similarily, for matched line you add all email address... | 0 | 2016-08-12T09:34:29Z | [
"python",
"dictionary"
] |
find most occurring word in text file using dictionary | 38,914,461 | <p>My question is similar to <a href="http://stackoverflow.com/questions/21297740/how-to-find-set-of-most-frequently-occurring-word-pairs-in-a-file-using-python">this</a> but slightly different. I am trying to read through a file, looking for lines containing emails starting with 'From' and then creating a dictionary t... | 1 | 2016-08-12T09:24:51Z | 38,915,114 | <p>You have a couple of issues. </p>
<p>The first one is the <code>for email in matches</code> loop is being called for each line in the text file.</p>
<pre><code>for lines in handle :
# look for specific characters in document text
if not lines.startswith("From ") : continue
# increment the count variabl... | 1 | 2016-08-12T09:57:00Z | [
"python",
"dictionary"
] |
find most occurring word in text file using dictionary | 38,914,461 | <p>My question is similar to <a href="http://stackoverflow.com/questions/21297740/how-to-find-set-of-most-frequently-occurring-word-pairs-in-a-file-using-python">this</a> but slightly different. I am trying to read through a file, looking for lines containing emails starting with 'From' and then creating a dictionary t... | 1 | 2016-08-12T09:24:51Z | 38,915,251 | <ol>
<li><code>lines.split()</code> will not change lines, as in <code>i.split()</code>, use print to verify this temp values.</li>
<li><p>check whether the <code>for</code> loops do as you want.</p>
<pre><code>import re
import collections
addy = []
with open("mbox-short.txt") as handle:
for lines in handle :
... | 1 | 2016-08-12T10:03:05Z | [
"python",
"dictionary"
] |
find most occurring word in text file using dictionary | 38,914,461 | <p>My question is similar to <a href="http://stackoverflow.com/questions/21297740/how-to-find-set-of-most-frequently-occurring-word-pairs-in-a-file-using-python">this</a> but slightly different. I am trying to read through a file, looking for lines containing emails starting with 'From' and then creating a dictionary t... | 1 | 2016-08-12T09:24:51Z | 38,916,541 | <p>Came up with an answer almost similar to that of <a href="http://stackoverflow.com/users/1663352/noelkd">@Noelkd</a>, after further reflection on my code:</p>
<pre><code>import re
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
email_matches = []
found_emails = []... | 0 | 2016-08-12T11:09:22Z | [
"python",
"dictionary"
] |
Prevent executing infinite js loop in Selenium/Phantomjs | 38,914,502 | <p>If a webapp have JS code such as the following:</p>
<pre><code>for(i=0; i > -1; i++){var a=1}; // Infinite loop
</code></pre>
<p>and I use Selenium/Phantomjs to browse it, it will be stuck forever.</p>
<p>How can I solve this problem? Does phantomjs have an option to set a timeout for script execution?</p>
| 0 | 2016-08-12T09:26:21Z | 38,914,771 | <p>Use resourceTimeout</p>
<pre><code>var page = require('webpage').create();
page.settings.resourceTimeout = 5000; // 5 seconds
</code></pre>
<p>Origin: <a href="http://stackoverflow.com/questions/16854788/phantomjs-webpage-timeout">phantomJS webpage timeout</a></p>
| -1 | 2016-08-12T09:40:34Z | [
"javascript",
"python",
"selenium",
"phantomjs"
] |
Why getting null written inside the logger while using it inside python script? | 38,914,874 | <p>I am using logger in my python script as :</p>
<pre><code>import logger
logging.basicConfig(filename='sample.log',level=logging.DEBUG)
logging.info("helllo")
</code></pre>
<p>Now there are many functions inside the python script and every time i have to use a logger i need to mention following line :</p>
<pre><co... | 1 | 2016-08-12T09:45:23Z | 38,914,979 | <p>You don't need to call <code>logging.basicConfig()</code> each time, no. You only need to call it <em>once</em>. The <code>logging.basicConfig()</code> function always returns <code>None</code>, so you can't use it to access a <code>Logger.info()</code> method anyway.</p>
<p>You can always access the root logger (i... | 1 | 2016-08-12T09:50:14Z | [
"python",
"logging"
] |
Using SSH in Raspberry Pi to get Input? | 38,914,946 | <p>I need to run Python scripts from SSH on my Raspberry Pi, while still being able to get input from a user on the Raspberry Pi via a USB keyboard emulator (<em>card reader</em>). I would normally be able to use <code>raw_input</code> for this, but if I run the Python script through SSH, it does not create a window an... | 0 | 2016-08-12T09:48:36Z | 38,916,439 | <p>I've solved it the best I can, with help from @Gaurav Dave</p>
<p>I now have a script which creates a new terminal window upon launch, using <code>Popen</code> from <code>sys</code>. The script looks like this...</p>
<pre><code>from sys import executable
from subprocess import Popen, CREATE_NEW_CONSOLE
Popen([exe... | 1 | 2016-08-12T11:03:54Z | [
"python",
"linux",
"python-2.7",
"ssh",
"raspberry-pi"
] |
Django: how to model a rectangle? | 38,915,041 | <p>I am trying to draw a rectangle using Django for backend and React for frontend. Some third party is going to hit my API with 4 coordinate points (x,y) in JSON format and then I draw the line via React. Should I keep a single model named Rectangle with 8 fields {(x1,y1),(x2,y2),(x3,y3),(x4,y4)} or should I keep 2 mo... | 1 | 2016-08-12T09:53:27Z | 38,915,985 | <p>I would definitely recommend using one simple model. If you are not building a new rectangle engine or something sophisticated, it will be enough.</p>
<p>As @BasicWolf already said in comment, you can even think of putting the points in just one field as JSON, or more simpler, comma separated (provided you never ne... | 0 | 2016-08-12T10:40:09Z | [
"python",
"django",
"django-models",
"django-rest-framework"
] |
Python3 subprocess executes command in old shell - sftp problems | 38,915,165 | <p>I am trying to create some kind of ping of a sftp server and report when the connection fails with python3.</p>
<p>The command that I am trying to execute is this one :</p>
<pre><code>sftp -P port user@host <<< exit > /dev/null 2>&1
</code></pre>
<p>It works when I execute it locally with all m... | 0 | 2016-08-12T09:59:14Z | 38,916,051 | <p>/bin/sh was actually redirected to /bin/dash. I changed it to /bin/bash and now it works.</p>
| 0 | 2016-08-12T10:43:31Z | [
"python",
"linux",
"shell"
] |
Python conversion from JSON to JSONL | 38,915,183 | <p>I wish to manipulate a standard JSON object to an object where each line must contain a separate, self-contained valid JSON object. See <a href="http://jsonlines.org/" rel="nofollow">JSON Lines</a></p>
<pre><code>JSON_file =
[{u'index': 1,
u'no': 'A',
u'met': u'1043205'},
{u'index': 2,
u'no': 'B',
u'met':... | 0 | 2016-08-12T10:00:04Z | 38,915,250 | <p>Your input appears to be a sequence of <strong>Python objects</strong>; it certainly is not valid a JSON document.</p>
<p>If you have a list of Python dictionaries, then all you have to do is dump each entry into a file separately, followed by a newline:</p>
<pre><code>import json
with open('output.jsonl', 'w') a... | 1 | 2016-08-12T10:03:03Z | [
"python",
"json"
] |
Pandas: use groupby to count difference between dates | 38,915,186 | <p>I have df:</p>
<pre><code>i,Unnamed,ID,url,used_at,active_seconds,domain,subdomain,search_engine,search_term,diff_time,period
0,322015,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/antoninaribina,2015-12-31 09:16:05,35,vk.com,vk.com,None,None,,1
1,838267,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed,2015-12-31 09:16:38,54... | 1 | 2016-08-12T10:00:10Z | 38,915,411 | <p>I think you need <code>groupby</code> with difference with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.last.html" rel="nofol... | 1 | 2016-08-12T10:11:26Z | [
"python",
"pandas",
"dataframe",
"group-by",
"timedelta"
] |
Pandas: use groupby to count difference between dates | 38,915,186 | <p>I have df:</p>
<pre><code>i,Unnamed,ID,url,used_at,active_seconds,domain,subdomain,search_engine,search_term,diff_time,period
0,322015,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/antoninaribina,2015-12-31 09:16:05,35,vk.com,vk.com,None,None,,1
1,838267,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed,2015-12-31 09:16:38,54... | 1 | 2016-08-12T10:00:10Z | 38,915,746 | <p>there is a oneline.</p>
<pre><code>df.groupby('ID').agg(['first','last']).apply( lambda r: r['used_at','last'] - r['used_at','first'], axis=1)
</code></pre>
<p>first group by column <code>ID</code>, then for each group take first and last element and calculate the difference <code>last - first</code>.</p>
| 1 | 2016-08-12T10:28:18Z | [
"python",
"pandas",
"dataframe",
"group-by",
"timedelta"
] |
meTypeset installation and python module installation, converting word docs to XML | 38,915,187 | <p>hope everyone doing good..today am come up with an different question..i need to convert word docs to XML am using meTypeset..<a href="https://github.com/MartinPaulEve/meTypeset..because" rel="nofollow">https://github.com/MartinPaulEve/meTypeset..because</a> i need to validate high end journal docs..it needs python... | 0 | 2016-08-12T10:00:11Z | 39,032,728 | <p>and i have found the solution for this ..we have to install lxml module for this through python web link </p>
| 0 | 2016-08-19T06:48:43Z | [
"python",
"xml",
"xml-parsing"
] |
PyQt5 signal communication error | 38,915,213 | <p>I need your help with the following problem that I've encountered.
I have two Python files, Main.py and Module.py, which need to communicate using PyQt5 signals. Here's the code:</p>
<p><strong>Main.py</strong></p>
<pre><code>from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from ... | 1 | 2016-08-12T10:01:24Z | 38,915,311 | <p>You need to connect the signal from an instance of the <code>moduleWindow</code> class, and not from the class itself: </p>
<pre><code>from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from MyGUI import main_window_GUI
from Modules import Module
class MainWindow(QMainWindow, main... | 0 | 2016-08-12T10:06:03Z | [
"python",
"python-3.x",
"signals-slots",
"pyqt5",
"qmdiarea"
] |
Fails to read the value of formular after using xlsxwriter to close and then usinging xlrd to read the excel file | 38,915,228 | <p>At fisrt, I use xlsxwriter to write a simple formula in one cell and close the *.xlsx file. Then I try to read the value of the cell but only read '0' from the cell using xlrd at the same program.</p>
<p>If I read some fixed values (like string or constant number) in a cell, it works well.
If I create a formula ce... | 1 | 2016-08-12T10:02:05Z | 38,922,683 | <p>XlsxWriter doesn't write the value of a formula to Excel. See the <a href="http://xlsxwriter.readthedocs.io/working_with_formulas.html#formula-result" rel="nofollow">Formula Result</a> section of the docs.</p>
| 0 | 2016-08-12T16:31:14Z | [
"python",
"excel",
"xlrd",
"xlsxwriter"
] |
Pandas - Using 'ffill' on values other than Na | 38,915,330 | <p>Is there a way to use <code>ffill</code> method on values that are not <code>NaN</code>?</p>
<p>I have <code>NaN</code> in my dataframe, but I have added these <code>NaN</code> using </p>
<pre><code>addNan = sample['colA'].replace(['A'], 'NaN')
</code></pre>
<p>So this is what my DataFrame, <code>df</code> looks ... | 2 | 2016-08-12T10:07:00Z | 38,915,495 | <p>I think you need first replace <code>NaN</code> to <code>np.nan</code>, because <code>NaN</code> is only text:</p>
<pre><code>import pandas as pd
import numpy as np
print (sample)
ColA ColB ColC ColD
0 B A A C
1 A B A A
2 C D D A
3 A A A B
sample['ColA'] = sample[... | 1 | 2016-08-12T10:16:19Z | [
"python",
"pandas",
"dataframe",
null,
"pandasql"
] |
Python MYSQL 'ascii' codec can't encode characters in position 10-25: ordinal not in range(128) | 38,915,458 | <p>I'm trying to parse a Russian web-site (in Cyrillic) and insert data to a mySQL DB. The parsing is fine, but I can't save the data in the DB because of the Cyrillic letters. Python give me this error: </p>
<pre><code>Traceback (most recent call last):
File "/Users/kr/PycharmProjects/education_py/vape_map.py", lin... | -2 | 2016-08-12T10:14:30Z | 38,936,625 | <p><code>%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0</code> is the encoding for <code>ÐоÑква</code>, so that looks OK. But you also need to establish that utf8 will be used in the connection to MySQL. And specify that the target column is <code>CHARACTER SET utf8</code>.</p>
<p><a href="http://stackoverflow.com/quest... | 1 | 2016-08-13T20:16:50Z | [
"python",
"mysql",
"encoding",
"utf-8",
"ascii"
] |
Repeating captures in Python strange result | 38,915,491 | <p>I would like to repeat for natural numbers to occur and catch all of them.</p>
<pre><code>import re
r = "the ((sixty|six)[ -]+)+items"
s = "the sixty six items"
re.findall(r, s)
# [('six ', 'six')]
</code></pre>
<p>It matches 'six' 2 times, while it can be observed that it could have never matched on "six six"; in... | 3 | 2016-08-12T10:16:04Z | 38,915,543 | <p>If you use <code>(group)+</code> then only last matched text will be captured in the group.</p>
<p>You should use <code>findall</code> with slightly different regex.</p>
<pre><code>s = 'the sixty six items'
>>> if re.match(r'the (?:(?:sixty|six)[ -]+)+items', s):
... re.findall(r"\b(sixty|six)[ -]+(?... | 2 | 2016-08-12T10:18:04Z | [
"python",
"regex"
] |
Repeating captures in Python strange result | 38,915,491 | <p>I would like to repeat for natural numbers to occur and catch all of them.</p>
<pre><code>import re
r = "the ((sixty|six)[ -]+)+items"
s = "the sixty six items"
re.findall(r, s)
# [('six ', 'six')]
</code></pre>
<p>It matches 'six' 2 times, while it can be observed that it could have never matched on "six six"; in... | 3 | 2016-08-12T10:16:04Z | 38,915,772 | <p>Try regex</p>
<pre><code>re.findall('(six\w*)', s)
</code></pre>
| 0 | 2016-08-12T10:29:54Z | [
"python",
"regex"
] |
Repeating captures in Python strange result | 38,915,491 | <p>I would like to repeat for natural numbers to occur and catch all of them.</p>
<pre><code>import re
r = "the ((sixty|six)[ -]+)+items"
s = "the sixty six items"
re.findall(r, s)
# [('six ', 'six')]
</code></pre>
<p>It matches 'six' 2 times, while it can be observed that it could have never matched on "six six"; in... | 3 | 2016-08-12T10:16:04Z | 38,915,780 | <p>Use <code>\b</code> assertion: Hope this helps.</p>
<pre><code>>>> s = "the sixty six items"
>>> print(re.findall(r'(?is)(\bsixty\b|\bsix\b)',s))
['sixty', 'six']
</code></pre>
<p><code>\b</code> assertion will avoid false hit, for example : If you add sixteen and do not wish to match</p>
<p>Wit... | 1 | 2016-08-12T10:30:12Z | [
"python",
"regex"
] |
Repeating captures in Python strange result | 38,915,491 | <p>I would like to repeat for natural numbers to occur and catch all of them.</p>
<pre><code>import re
r = "the ((sixty|six)[ -]+)+items"
s = "the sixty six items"
re.findall(r, s)
# [('six ', 'six')]
</code></pre>
<p>It matches 'six' 2 times, while it can be observed that it could have never matched on "six six"; in... | 3 | 2016-08-12T10:16:04Z | 38,916,044 | <p><code>re.search</code> just finds the first thing that matches the pattern, it doesn't look for further matches once it's found one. You are getting <code>('six ', 'six')</code> because you have one capture group nested inside another; the <code>'six '</code> matches the outer group, and the <code>'six'</code> (with... | 3 | 2016-08-12T10:43:11Z | [
"python",
"regex"
] |
How to properly construct query with in_ operator | 38,915,733 | <p>I have an SQL update query with IN statement which is executed via SQLAlchemy. Unfortunately current implementation uses string interpolation, which I'd like to replace with more secure option.</p>
<pre class="lang-py prettyprint-override"><code>session.execute('''
UPDATE servers SET
cpu_cores=s... | 0 | 2016-08-12T10:27:28Z | 38,925,780 | <p>If all you want to do is to make it more secure, you can still interpolate in the param placeholders:</p>
<pre><code>session.execute("""UPDATE ... WHERE server.provider_id IN (%s)""" % ",".join("?" * len(provider_ids)), provider_ids)
</code></pre>
<p>The <code>?</code> is the placeholder, and varies depending on t... | 1 | 2016-08-12T20:11:09Z | [
"python",
"sqlalchemy"
] |
reading corresponding columns using python | 38,915,758 | <p>I have the output in the format :</p>
<pre><code>Neighbor InQ OutQ Up/Down State
10.230.3.2 0 0 33w5d 1177
10.230.4.2 0 0 33w4d 1175
125.62.173.253 0 0 8w3d 2637
125.62.173.254 0 0 1w3d 2657
</code></pre>
<p>I want to read the Neighbor(e.g ... | 0 | 2016-08-12T10:29:24Z | 38,915,991 | <p>Not 100% sure what you are asking for and what format you have this data in but this will print the column <code>Neighbour</code> if <code>State</code> >=0. You can move this into a list or tuple or dictionary based on your requirements.</p>
<p>EDIT:Assuming the file only has one space per entry and you have format... | 0 | 2016-08-12T10:40:30Z | [
"python"
] |
reading corresponding columns using python | 38,915,758 | <p>I have the output in the format :</p>
<pre><code>Neighbor InQ OutQ Up/Down State
10.230.3.2 0 0 33w5d 1177
10.230.4.2 0 0 33w4d 1175
125.62.173.253 0 0 8w3d 2637
125.62.173.254 0 0 1w3d 2657
</code></pre>
<p>I want to read the Neighbor(e.g ... | 0 | 2016-08-12T10:29:24Z | 38,916,031 | <p>You can use pandas.</p>
<pre><code>>>> import pandas as pd
>>> data_set = [('10.230.3.2', 0, 0, '33w5d', 1177), ('10.230.4.2', 0, 0, '33w5d', 1175), ('125.62.173.253', 0, 0, '8w3d', 2637), ('125.62.173.254', 0, 0, '1w3d', 2657), ('127.0.0.1', 0, 0, '1w0d', -1)]
>>> df = pd.DataFrame(data ... | 0 | 2016-08-12T10:42:30Z | [
"python"
] |
reading corresponding columns using python | 38,915,758 | <p>I have the output in the format :</p>
<pre><code>Neighbor InQ OutQ Up/Down State
10.230.3.2 0 0 33w5d 1177
10.230.4.2 0 0 33w4d 1175
125.62.173.253 0 0 8w3d 2637
125.62.173.254 0 0 1w3d 2657
</code></pre>
<p>I want to read the Neighbor(e.g ... | 0 | 2016-08-12T10:29:24Z | 38,916,612 | <p>Though I think Nehal's answer using pandas is very ideal for this scenario.</p>
<p>You may try this way as well and tweek according to your requirement-</p>
<pre><code>>>> for i in range(1, len(t)):
... temp = t[i].split()
... if int(temp[4]) >= 0:
... print temp[0]
...
10.230.3.2
10.23... | 0 | 2016-08-12T11:14:00Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.