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 like like :</p> <pre><code>l=list(query[4]) for word in l : word=func(word) </code></pre> <p>But it is storing each alphabets on the list like - <code>['[', "'", 'r', 'a', 'i', 'n', "'", ','</code> and so on.</p> <p>I have even tried to use join function i.e. - <code>''.join(word)</code> and <code>''.join(l)</code></p> <p>But still nothing is working for me. Can you suggest something here. Any help will be appreciated. </p>
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 like like :</p> <pre><code>l=list(query[4]) for word in l : word=func(word) </code></pre> <p>But it is storing each alphabets on the list like - <code>['[', "'", 'r', 'a', 'i', 'n', "'", ','</code> and so on.</p> <p>I have even tried to use join function i.e. - <code>''.join(word)</code> and <code>''.join(l)</code></p> <p>But still nothing is working for me. Can you suggest something here. Any help will be appreciated. </p>
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/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a>:</p> <pre><code>df = pd.DataFrame({'a':["[rain, shower, head]", "[rain1, shower1, head1]"]}) print (df) a 0 [rain, shower, head] 1 [rain1, shower1, head1] print (type(df.a.ix[0])) &lt;class 'str'&gt; df['a'] = df.a.str.strip('[]').str.split(',') print (df) a 0 [rain, shower, head] 1 [rain1, shower1, head1] print (type(df.a.ix[0])) &lt;class 'list'&gt; </code></pre> <p>Then you can apply custom function:</p> <pre><code>def func(x): return x + 'aaa' def f(L): return [func(word) for word in L] print (df.a.apply(f)) 0 [rainaaa, showeraaa, headaaa] 1 [rain1aaa, shower1aaa, head1aaa] Name: a, dtype: object </code></pre> <hr> <pre><code>def f(L): return [word + 'aaa' for word in L] print (df.a.apply(f)) 0 [rainaaa, showeraaa, headaaa] 1 [rain1aaa, shower1aaa, head1aaa] Name: a, dtype: object </code></pre>
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.com/sitemap.xml', ) def parse(self, response): s = Sitemap(response.body) for sitelink in s: url = sitelink['loc'] yield {'url': url} </code></pre> <p>Then to save the urls just: <code>scrapy crawl sitemap_spider -o urls.json</code></p>
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:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd" </code></pre> <p>And this test code:</p> <pre><code>_xsd_validators = {} def get_xsd_validator(url): if url not in _xsd_validators: _xsd_validators[url] = etree.XMLSchema(etree.parse(StringIO(requests.get(url).content))) return _xsd_validators[url] # this util function is later on in a TestCase def validate_xml(self, content): content.seek(0) doc = etree.parse(content) schema_loc = doc.getroot().attrib.get('{http://www.w3.org/2001/XMLSchema-instance}schemaLocation').split(' ') # lxml doesn't like multiple namespaces for i, loc in enumerate(schema_loc): if i % 2 == 1: get_xsd_validator(schema_loc[i]).assertValid(doc) return doc </code></pre> <p>Example XML that fails validation:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd" &gt; &lt;url&gt; &lt;loc&gt;https://www.example.com/press&lt;/loc&gt; &lt;lastmod&gt;2016-08-11&lt;/lastmod&gt; &lt;changefreq&gt;weekly&lt;/changefreq&gt; &lt;/url&gt; &lt;url&gt; &lt;loc&gt;https://www.example.com/about-faq&lt;/loc&gt; &lt;lastmod&gt;2016-08-11&lt;/lastmod&gt; &lt;changefreq&gt;weekly&lt;/changefreq&gt; &lt;/url&gt; &lt;/urlset&gt; </code></pre> <p>When I just had a regular sitemap everything worked great, but when I added in image sitemap markup <code>assertValid</code> started failing with:</p> <pre><code>E DocumentInvalid: Element '{http://www.google.com/schemas/sitemap-image/1.1}image': No matching global element declaration available, but demanded by the strict wildcard., line 12 </code></pre> <p>Or:</p> <pre><code>E DocumentInvalid: Element '{http://www.sitemaps.org/schemas/sitemap/0.9}urlset': No matching global declaration available for the validation root., line 6 </code></pre>
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>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:import namespace="http://www.sitemaps.org/schemas/sitemap/0.9" schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"/&gt; &lt;xs:import namespace="http://www.google.com/schemas/sitemap-image/1.1" schemaLocation="http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd"/&gt; &lt;/xs:schema&gt; </code></pre> <p>I don't have python, but this validates successfully in oXygen:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="wrapper-schema.xsd" &gt; &lt;image:image&gt; &lt;image:loc&gt;http://www.example.com/image&lt;/image:loc&gt; &lt;/image:image&gt; &lt;url&gt; &lt;loc&gt;https://www.example.com/press&lt;/loc&gt; &lt;lastmod&gt;2016-08-11&lt;/lastmod&gt; &lt;changefreq&gt;weekly&lt;/changefreq&gt; &lt;/url&gt; &lt;url&gt; &lt;loc&gt;https://www.example.com/about-faq&lt;/loc&gt; &lt;lastmod&gt;2016-08-11&lt;/lastmod&gt; &lt;changefreq&gt;weekly&lt;/changefreq&gt; &lt;/url&gt; &lt;/urlset&gt; </code></pre>
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>&lt;a href="foo"&gt;foo&lt;/a&gt;</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 = ''' &lt;a class='fooo123'&gt;foo on its own&lt;/a&gt; &lt;a class='123foo'&gt;only foo&lt;/a&gt; ''' soup = BeautifulSoup(string, "lxml") foo_links = soup.find_all(text=re.compile("^foo")) print(foo_links) # ['foo on its own'] </code></pre> <hr> <p>To <strong><em>wrap</em></strong> the found links with e.g. <code>mark</code>, you can do the following:</p> <pre><code>from bs4 import BeautifulSoup import re string = ''' &lt;a class='fooo123'&gt;foo on its own&lt;/a&gt; &lt;a class='123foo'&gt;only foo&lt;/a&gt; ''' soup = BeautifulSoup(string, "lxml") foo_links = soup.findAll('a', text=re.compile("^foo")) for a in foo_links: mark = soup.new_tag('mark') a.wrap(mark) print(soup.prettify()) </code></pre> <p>As well as the mandatory <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags"><strong>Tony the Pony</strong></a> link...</p>
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>&lt;a href="foo"&gt;foo&lt;/a&gt;</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 = '''&lt;h3&gt; &lt;a href="//stackexchange.com/users/838793061/?accounts"&gt;yourcommunities&lt;/a&gt; &lt;/h3&gt; &lt;a href="#" id="edit-pinned-sites"&gt;edit&lt;/a&gt; &lt;a href="#" id="cancel-pinned-sites"style="display:none;"&gt;cancel&lt;/a&gt;''' pattern = re.compile(r'&gt;([^&lt;&gt;]+)&lt;') all = re.findall(pattern, str) for i in all: print(i) </code></pre>
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>&lt;a href="foo"&gt;foo&lt;/a&gt;</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 = '&lt;a href="foo"&gt; foo &lt;/a&gt;' re.findall(r'&gt;\s*(\w*)\s*&lt;',line) ### ['foo'] #### No spaces: line = '&lt;a href="foo"&gt;foo&lt;/a&gt;' re.findall(r'&gt;\s*(\w*)\s*&lt;',line) ### ['foo'] </code></pre>
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 books in your book are great".</p> <p>Can anyone please help me?</p> <p>Sorry I'm new to coding and I'm really struggling.</p> <p>Thank you so much!</p> <p>(BTW this is just an example... and the code is supposed to work with any sentence with the specific word and other forms of the word, but all I need to change is the original not anything else.</p> <p>Also the sentence is supposed to be an input so it's uncertain... But the word to be replaced is certain.) </p>
-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 books in your book are great".</p> <p>Can anyone please help me?</p> <p>Sorry I'm new to coding and I'm really struggling.</p> <p>Thank you so much!</p> <p>(BTW this is just an example... and the code is supposed to work with any sentence with the specific word and other forms of the word, but all I need to change is the original not anything else.</p> <p>Also the sentence is supposed to be an input so it's uncertain... But the word to be replaced is certain.) </p>
-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("This letters in your letter are great", "letter", "book") </code></pre>
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><code>"domains" in "domainid" False </code></pre> <p>eg 2: - > This works as expected (but there is problem at example at eg 3)</p> <pre><code>"domains" in "domainsid" True </code></pre> <p>eg 3: - > This is not fine as "d" shud not match (but instead "domain shud be matched")</p> <pre><code>&gt;&gt;&gt; "d" in "domainsid" True &gt;&gt;&gt; "d" in "domainid" True </code></pre>
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 -&gt; (s0,s1), (s1,s2), (s2, s3), ... n = 3 -&gt; (s0,s1, s2), (s1,s2, s3), (s2, s3, s4), ...''' a = itertools.tee(iterable, n) for x, thing in enumerate(a[1:]): for _ in range(x+1): next(thing, None) return zip(*a) </code></pre> <p>Then a function the iterates over substrings, longest first, and tests for membership.</p> <pre><code>def foo(s1, s2): '''Finds the longest matching substring ''' # the longest matching substring can only be as long as the shortest string #which string is shortest? shortest, longest = sorted([s1, s2], key = len) #iterate over substrings, longest substrings first for n in range(len(shortest)+1, 2, -1): for sub in n_wise(shortest, n): sub = ''.join(sub) if sub in longest: #return the first one found, it should be the longest return sub s = "fdomainster" t = "exdomainid" print(foo(s,t)) </code></pre>
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]</code></p> <p>Currently, I am using a for loop and append the dataframe in each iteration, but it's very slow. Is there any other method I can use to save time?</p>
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 columns df1 = pd.melt(df, id_vars='id', value_name='time').drop('variable', axis=1) #convert int to timedelta df1['time'] = pd.to_timedelta(df1.time, unit='s') df1.set_index('time', inplace=True) print (df1) id time 00:00:01 001 00:00:03 002 00:00:03 001 00:00:04 002 #groupby by id and resample by one second print (df1.groupby('id') .resample('1S') .ffill() .reset_index(drop=True, level=0) .reset_index()) time id 0 00:00:01 001 1 00:00:02 001 2 00:00:03 001 3 00:00:03 002 4 00:00:04 002 </code></pre> <p>If <code>start_time</code> and <code>end_time</code> is <code>datetime</code> use:</p> <pre><code>df = pd.DataFrame([['001', '2016-01-01', '2016-01-03'], ['002', '2016-01-03', '2016-01-04']], columns=['id','start_time','end_time']) print (df) id start_time end_time 0 001 2016-01-01 2016-01-03 1 002 2016-01-03 2016-01-04 df1 = pd.melt(df, id_vars='id', value_name='time').drop('variable', axis=1) #convert to datetime df1['time'] = pd.to_datetime(df1.time) df1.set_index('time', inplace=True) print (df1) id time 2016-01-01 001 2016-01-03 002 2016-01-03 001 2016-01-04 002 #groupby by id and resample by one day print (df1.groupby('id') .resample('1D') .ffill() .reset_index(drop=True, level=0) .reset_index()) time id 0 2016-01-01 001 1 2016-01-02 001 2 2016-01-03 001 3 2016-01-03 002 4 2016-01-04 002 </code></pre>
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]</code></p> <p>Currently, I am using a for loop and append the dataframe in each iteration, but it's very slow. Is there any other method I can use to save time?</p>
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> <pre><code>import pandas as pd from io import StringIO data = StringIO("""id,start time,end time 001, 1, 3 002, 3, 4""") df = pd.read_csv(data, dtype={'id':'object'}) df.set_index('id', inplace=True) print("In\n", df) 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'] print("Out\n", reshaped) </code></pre> <p>Output:</p> <pre><code>In start time end time id 001 1 3 002 3 4 Out id time 0 001 1 1 001 2 2 001 3 3 002 3 4 002 4 </code></pre>
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 subprocess out=subprocess.Popen(["./util.py"],shell=True) print "done" </code></pre> <p>util.py:</p> <pre><code>#!/usr/bin/env python def display(): print "displaying" display() </code></pre> <p>error:</p> <pre><code>/bin/sh: ./util.py: No such file or directory done </code></pre>
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 you are sure that file1.py and util.py always lie in the same directory, you could use <code>__file__</code> and <code>os.path.dirname</code> to prefix it with the directory of file1.py:</p> <p>file1.py:</p> <pre><code>#!/usr/bin/env python import os import subprocess current_dir = os.path.dirname(__file__) filename = os.path.join(current_dir, "util.py") out = subprocess.Popen([filename], shell=True) print("done") </code></pre>
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 subprocess out=subprocess.Popen(["./util.py"],shell=True) print "done" </code></pre> <p>util.py:</p> <pre><code>#!/usr/bin/env python def display(): print "displaying" display() </code></pre> <p>error:</p> <pre><code>/bin/sh: ./util.py: No such file or directory done </code></pre>
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 threading import Thread Thread(target=lambda:execfile("util.py")).start() print "done" </code></pre>
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://www.dicomlibrary.com/dicom/sop/" rel="nofollow">SOP's for DICOM</a>, are available. So I try to use <strong>StudyRootFindSOPClass</strong></p> <p>I tried to use the :</p> <pre><code>print "DICOM FindSCU ... ", d = Dataset() d.StudyDate = args.searchstring d.QueryRetrieveLevel = "STUDY" d.StudyID = "*" study = [x[1] for x in assoc.StudyRootFindSOPClass.SCU(d, 1)][:-1] print 'done with status "%s"' % st print "\n\n\n Cont...", study </code></pre> <p>But it gives the error </p> <pre><code>Request association Association response received DICOM Echo ... done with status "Success " DICOM FindSCU ... Traceback (most recent call last): File "studyqrscu.py", line 104, in &lt;module&gt; study = [x[1] for x in assoc.StudyRootFindSOPClass.SCU(d, 1)][:-1] File "/usr/local/lib/python2.7/dist-packages/pynetdicom-0.8.1-py2.7.egg/netdicom/applicationentity.py", line 90, in __getattr__ raise Exception("SOP Class %s not supported as SCU" % attr) Exception: SOP Class StudyRootFindSOPClass not supported as SCU </code></pre> <p>Please help me to fetch the study using the study date and time.</p>
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> <ul> <li>Modality Worklist (that's a different story)</li> <li>Patient Root</li> <li>Study Root</li> <li>Patient Study Only (not very popular in commercial products, has been retired)</li> </ul> <p>Source: <a href="http://dicom.nema.org/dicom/2013/output/chtml/part04/sect_C.3.html" rel="nofollow">DICOM PS3.4</a></p> <p>As the name tells, Patient- and Study Root differ in terms of what is the root element from which you start to search down the hierarchy (Patient -> Study -> Series -> Image) in subsequent queries. Patient Root starts on the patient level, so you first search for criteria on the patient level and have patient level results. With the patient ID obtained from the results you go down to the study level to query for studies of the particular patient.</p> <p>Study Root treats the patient level attributes as secondary study attributes, i.e. you are asking for studies and you receive the attributes of the patient each study belongs to for each study (meaning that you may receive the same patient twice for different studies which makes the difference to Patient Root).</p> <p>I agree that a study root is what you want to have for your use case, but unfortunately the toolkit you are using apparently only supports Patient Root. According to the error message it's a problem on the client (SCU) side, so dcm4chee is not to blame.</p> <p>How to solve this?</p> <p>You might find a different toolkit supporting StudyRoot. Actually to me the absence of Study Root support puts the fitness for practical usage in question to me.</p> <p>You might want to go the dirty way and try to form a <strong>non DICOM conformant</strong> query in Patient Root looking like this:</p> <pre><code> - Q/R-Level = "STUDY" - Patient-ID = "*" or empty - Study Date = &lt;your date range&gt; </code></pre> <p>There is a fair chance that this is going to work, however, keep in mind, it is not DICOM conformant, so it depends on the SCP implementation and may vary between different products.</p> <p>For the sake of completeness: You may put a query on patient level and for each patient received put a subsequent query on study level giving the patient-ID and your study date range as matching criteria. Not worth mentioning that this is going to fail for performance issues but it would be the DICOM conformance way to solve the issue.</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=&lt;hostname&gt;</code>. I would want to know for each hostname how many files are in input,success,retry,current and manual dir.</p> <p>For eg.</p> <pre><code>input -&gt; A.txt (HOSTNAME=host1) -&gt; B.txt (HOSTNAME=host2) -&gt; C.txt (HOSTNAME=host3) -&gt; D.txt (HOSTNAME=host1) success -&gt; P.txt (HOSTNAME=host1) -&gt; Q.txt (HOSTNAME=host2) -&gt; R.txt (HOSTNAME=host1) OUTPUT Host | Input | Success | Current | Retry | Manual host1 | 2 | 2 | 0 | 0 | 0 host2 | 1 | 1 | 0 | 0 | 0 host3 | 1 |0 | 0 | 0 | 0 </code></pre> <p>Would like to know if there are any libraries in perl, python or bash to do this.</p>
-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 looking for a match <ol> <li>On matched files, increment a two-level hash/dict/object/map/associative array (or whatever your language of choice calls them) keyed by host and directory. Record the hostname found in a list.</li> </ol></li> </ol></li> <li>remove duplicates from the list of hostnames</li> <li>sort the list of hostnames</li> <li>Use the list of hostnames, the list of directories and the hash of host counts to print a table.</li> </ol> <p>Here's <a href="http://perldoc.perl.org/perlfunc.html#Perl-Functions-by-Category" rel="nofollow">a link to Perl's built in functions organized by category</a>. The stuff on working with regular expressions, files and directories is particularly relevant.</p>
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 ? like this print <code>("a",a)</code></p> <p>and then I can decide whether the robocopy was successful or not. </p> <p>Also how can I run above robocopy with subprocess.call() command? And also get the return code. </p> <p>thanks everyone for reading my post. </p>
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 /MIR', shell=True) </code></pre>
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>This almost works, but </p> <pre><code>isinstance(Config(), Config) </code></pre> <p>fails. I am betting this clue means there are more devious problems deeper in also. So is there a way to actually achieve this?</p> <p>I also tried:</p> <pre><code>class Config(Object): __init__ = functools.partial(collections.defaultdict, list) </code></pre>
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) return NewCls if __name__ == '__main__': Config = partialclass(collections.defaultdict, list) assert isinstance(Config(), Config) </code></pre>
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>This almost works, but </p> <pre><code>isinstance(Config(), Config) </code></pre> <p>fails. I am betting this clue means there are more devious problems deeper in also. So is there a way to actually achieve this?</p> <p>I also tried:</p> <pre><code>class Config(Object): __init__ = functools.partial(collections.defaultdict, list) </code></pre>
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).__init__(list) </code></pre> <p>You'll have no-argument construction with the list factory and</p> <pre><code>isinstance(Config(), Config) </code></pre> <p>will work as well.</p>
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 token? I'm trying to register the user so it shouldn't have/need one at this point right?</p> <p>Mind you, I'm just using my browser and just going to </p> <blockquote> <p>127.0.0.1:8000/register</p> </blockquote> <p>I'm not playing around with angular and requesting api's, I just went to /register in my browser to see what I would get. I was expecting to see a form or something. Is it working properly and I just accessed it the wrong way?</p> <p>Here's my models.py</p> <pre><code>@receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True, db_index=True) password1 = models.CharField(max_length=50) username = models.CharField('username', max_length=50, unique=True, db_index=True) image = models.FileField(upload_to='photos', null=True, blank=True) joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) friends = [] USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = CustomUserManager() def __unicode__(self): return self.username class Meta: unique_together = (('username', 'password1'),) </code></pre> <p>my views.py</p> <pre><code>@api_view(['POST']) def create_auth(request): serialized = CustomUserSerializer(data=request.DATA) if serialized.is_valid(): CustomUser.objects.create_user( serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password1'] ) return Response(serialized.data, status=HTTP_201_CREATED) else: return Response(serialized._errors, status=HTTP_400_BAD_REQUEST) </code></pre> <p>urls.py</p> <pre><code>router = DefaultRouter() router.register(r'friends', FriendViewSet) router.register(r'posts', PostViewSet, 'Post') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^users/$', UserView.as_view()), url(r'^add_friend/$', add_friend), url(r'^register', create_auth), # This is the url I'm trying to access. url(r'^api-token-auth/$', ObtainAuthToken.as_view()), url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^logout/$', Logout.as_view()), ] </code></pre> <p><strong>EDIT 1</strong> settings.py</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } </code></pre>
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=request.DATA) if serialized.is_valid(): CustomUser.objects.create_user( serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password1'] ) return Response(serialized.data, status=HTTP_201_CREATED) else: return Response(serialized._errors, status=HTTP_400_BAD_REQUEST) </code></pre> <p>My recomendation: Work with Based-Class Views</p>
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 &lt;module&gt; [Fri Aug 12 06:15:13 2016] [error] [client 72.219.147.5] import bottle [Fri Aug 12 06:15:13 2016] [error] [client 72.219.147.5] ImportError: No module named bottle </code></pre> <p>When I installed mod_wsgi, this was used: </p> <pre><code>mod_wsgi-python26-3.2-6.11.amzn1.x86_64 </code></pre> <p>Here is my app.wsgi file</p> <pre><code>import os, sys sys.path.insert(0, "/var/www/html/lumos") import bottle import app application = bottle.default_app() </code></pre> <p>Here is my httpd.conf:</p> <pre><code>WSGISocketPrefix /var/run/wsgi &lt;VirtualHost *&gt; ServerName lumos.website.me DocumentRoot /var/www/html/lumos WSGIDaemonProcess lumos threads=5 WSGIScriptAlias / /var/www/html/lumos/app.wsgi &lt;Directory "/var/www/html/lumos"&gt; WSGIProcessGroup lumos WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>Here is the version of WSGI (from my error log):</p> <pre><code>[Fri Aug 12 06:15:11 2016] [notice] Apache/2.2.31 (Unix) DAV/2 PHP/5.3.29 mod_wsgi/3.2 Python/2.6.9 configured -- resuming normal operations </code></pre> <p>But if I run <code>python -V</code>, I get <code>Python 2.7.10</code>. </p> <p>Also I know bottle is installed correctly because when I do the following, there's no error:</p> <pre><code>$ python &gt;&gt;&gt;import bottle #no import error &gt;&gt;&gt; </code></pre> <p><strong>UPDATE:</strong></p> <p>I tried doing a "hello world" test to see if wsgi was working:</p> <pre><code>def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] </code></pre> <p>It worked, so the problem is not WSGI.</p> <p>This is what is inside my app.py file:</p> <pre><code>from bottle import route, run, template, static_file, request import main template = """&lt;html&gt; &lt;head&gt;&lt;title&gt;Home&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Upload a file&lt;/h1&gt; &lt;form action="/upload" method="post" enctype="multipart/form-data"&gt; Category: &lt;input type="text" name="category" /&gt; Select a file: &lt;input type="file" name="upload1" /&gt; Select a file: &lt;input type="file" name="upload2" /&gt; &lt;input type="submit" value="Start upload" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;""" @route('/') def index(): return template </code></pre> <p>If I execute <code>python app.py</code>, there are no errors. It's just when I refresh lumos.website.me that there is the 500 error.</p> <p>Any help is appreciated.</p>
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&gt;pip install bottle Collecting bottle Using cached bottle-0.12.9.tar.gz Building wheels for collected packages: bottle Running setup.py bdist_wheel for bottle ... done Stored in directory: C:\Users\hkpra\AppData\Local\pip\Cache\wheels\6e\87\89\f7ddd6721f4a208d44f2dac02f281b2403a314dd735d2b0e61 Successfully built bottle Installing collected packages: bottle Successfully installed bottle-0.12.9 </code></pre>
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 dataframe of this one (necessary in my original code which contain different data) and I change the index for this dataFrame, the values of my cells are all equal to <code>NaN</code>. </p> <p>I know that I could use <code>reset_index</code> to change the index, but I would like to be able to do it all in one line. </p> <p>What I did now is the following (resulting in NaNs)</p> <pre><code>partB = pd.DataFrame(partA, columns = ['A', 'B', 'C', 'D','E', 'F', 'G', 'H', 'I','J']) </code></pre>
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 2 5 3 4 29 4 1 323 9 7 partB = pd.DataFrame(partA.values,columns = ['A', 'B', 'C', 'D','E', 'F', 'G', 'H', 'I','J']) print (partB) A B C D E F G H I J 0 2 5 3 4 29 4 1 323 9 7 </code></pre> <p>If need index from <code>partA</code>:</p> <pre><code>partB = pd.DataFrame(partA.values, columns = ['A', 'B', 'C', 'D','E', 'F', 'G', 'H', 'I','J'], index = partA.index) print (partB) A B C D E F G H I J 20 2 5 3 4 29 4 1 323 9 7 </code></pre> <p>You get <code>NaN</code> because not align column names, so if changed last name (<code>u7</code>), you get value:</p> <pre><code>partB = pd.DataFrame(partA, columns = ['A', 'B', 'C', 'D','E', 'F', 'G', 'H', 'I','u7'], index = partA.index) print (partB) A B C D E F G H I u7 20 NaN NaN NaN NaN NaN NaN NaN NaN NaN 323 </code></pre>
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=254,default="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRvj-aG0r4GBOQbne5fKQxoPdozZr81YZjrgM1etERa4RHWkvBOsw") def __str__(self): return self.ticker </code></pre> <p>here geeky is my username and pythonanywhere is the website on which i have my server account for running python script!</p>
-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 need to download that default image from wherever it is now, and upload it to PythonAnywhere)...</p>
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 specific intervals.</p> <p>Is there some way of taking a list of Figure objects and dynamically displaying each one in turn after some interval in python 2.7? Perhaps using a Graphics object similar to the ones found in Java's Swing? Or would it be better simply to save my plots as images and use JavaScript to display them as desired?</p> <p>Thank you in advance for any help or suggestions you may offer.</p>
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/animation/double_pendulum_animated.html" rel="nofollow">http://matplotlib.org/examples/animation/double_pendulum_animated.html</a></p> <p><a href="http://matplotlib.org/examples/animation/dynamic_image2.html" rel="nofollow">http://matplotlib.org/examples/animation/dynamic_image2.html</a></p>
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 to download all my original files using Dropbox API.</p> <p>As i can see on web interface, I can download them individually but I got like thousand files so I couldn't do it.</p> <p><strong>My problem:</strong></p> <p>I used Python API wrapper to work with Dropbox API. I first fetched all of my files and tried to get all of their revisions but the original files are not included in revision list.</p> <p>Then I tried to list all of my files including deleted files and I can see my original files listed. I tried to download them using download endpoint but it returned <code>File not found</code> error. Has anyone bumped into something similar? How can I solve this issue?</p> <p><strong>My code snippet:</strong></p> <pre><code>dbx = dropbox.Dropbox('token is intentionally hidden') print dbx.users_get_current_account() for entry in dbx.files_list_folder('', recursive = False, include_deleted = True).entries: if (isinstance(entry, dropbox.files.FileMetadata) or isinstance(entry, dropbox.files.DeletedMetadata)): if not entry.name.endswith('cerber2'): print "name: ", entry.name, "| path: ", entry.path_lower print repr(entry) try: meta, resp = dbx.files_download(entry.path_lower) except dropbox.exceptions.ApiError as e: print e.user_message_text print "-" * 80 </code></pre>
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. This is persisted across deletes, renames, moves, etc. This will be key to fixing this problem, as Dropbox tracks file history by file path, so as soon as the ransomware renamed your files, the option of simply rolling back your files programmatically was lost. To make things even more difficult, fetch a directory listing with <code>include_deleted</code> set to True and you'll notice that Dropbox don't include file IDs in the metadata for deletions. If they did, this would be a breeze.</p> <p>So, here's what to do instead:</p> <ol> <li>Fetch a list of files, as normal.</li> <li><p>Split that list of files into two lists, existing files and those that have been deleted:</p> <p>deleted = list(filter(lambda file: isinstance(file, dropbox.files.DeletedMetadata), files.entries))</p></li> </ol> <p>(where <code>files</code> is an instance of <code>dropbox.files.ListFolderResult</code>)</p> <ol start="3"> <li>Here's where things get a bit hairy when it comes to API calls. For each of the deleted files, you need to fetch a list of revisions, using <code>dropbox.Dropbox.files_list_revisions</code>. Take the first revision, which will be the newest, and store its ID alongside the file path. This is how we get an ID for a deleted file.</li> <li>Now that we (hopefully) have an ID for each deleted file in your folder/Dropbox, all that's left to do is to match up those IDs with the IDs of the existing encrypted .cerber2 files. Once you've done that, you'll have a mapping between the encrypted .cerber2 file and the original, decrypted file stored in your Dropbox history. Simply restore the old file and delete the files created by the virus.</li> </ol> <p>I've purposefully left the actual implementation in code up to you, but I hope this helps.</p>
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 to download all my original files using Dropbox API.</p> <p>As i can see on web interface, I can download them individually but I got like thousand files so I couldn't do it.</p> <p><strong>My problem:</strong></p> <p>I used Python API wrapper to work with Dropbox API. I first fetched all of my files and tried to get all of their revisions but the original files are not included in revision list.</p> <p>Then I tried to list all of my files including deleted files and I can see my original files listed. I tried to download them using download endpoint but it returned <code>File not found</code> error. Has anyone bumped into something similar? How can I solve this issue?</p> <p><strong>My code snippet:</strong></p> <pre><code>dbx = dropbox.Dropbox('token is intentionally hidden') print dbx.users_get_current_account() for entry in dbx.files_list_folder('', recursive = False, include_deleted = True).entries: if (isinstance(entry, dropbox.files.FileMetadata) or isinstance(entry, dropbox.files.DeletedMetadata)): if not entry.name.endswith('cerber2'): print "name: ", entry.name, "| path: ", entry.path_lower print repr(entry) try: meta, resp = dbx.files_download(entry.path_lower) except dropbox.exceptions.ApiError as e: print e.user_message_text print "-" * 80 </code></pre>
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 to download all my original files using Dropbox API.</p> <p>As i can see on web interface, I can download them individually but I got like thousand files so I couldn't do it.</p> <p><strong>My problem:</strong></p> <p>I used Python API wrapper to work with Dropbox API. I first fetched all of my files and tried to get all of their revisions but the original files are not included in revision list.</p> <p>Then I tried to list all of my files including deleted files and I can see my original files listed. I tried to download them using download endpoint but it returned <code>File not found</code> error. Has anyone bumped into something similar? How can I solve this issue?</p> <p><strong>My code snippet:</strong></p> <pre><code>dbx = dropbox.Dropbox('token is intentionally hidden') print dbx.users_get_current_account() for entry in dbx.files_list_folder('', recursive = False, include_deleted = True).entries: if (isinstance(entry, dropbox.files.FileMetadata) or isinstance(entry, dropbox.files.DeletedMetadata)): if not entry.name.endswith('cerber2'): print "name: ", entry.name, "| path: ", entry.path_lower print repr(entry) try: meta, resp = dbx.files_download(entry.path_lower) except dropbox.exceptions.ApiError as e: print e.user_message_text print "-" * 80 </code></pre>
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(requestConfig, AUTH_TOKEN); FullAccount account = client.users().getCurrentAccount(); Set&lt;String&gt; folderNames; SearchResult result = client.files().searchBuilder("/Pankaj", "*.cerber3").withMaxResults(1000L).withMode(SearchMode.FILENAME).start(); folderNames = new HashSet&lt;&gt;(result.getMatches().size()); for (SearchMatch match : result.getMatches()){ FileMetadata fileMetadata = (FileMetadata) match.getMetadata(); String path = fileMetadata.getPathLower(); folderNames.add(path.substring(0, path.lastIndexOf("/"))); } for(String path : folderNames){ processDirectory(path, client); } } static void processDirectory(String dirName, DbxClientV2 client) throws DbxException { ListFolderResult result = client.files().listFolderBuilder(dirName).withIncludeDeleted(true).start(); while (true) { for (Metadata metadata : result.getEntries()) { if(metadata instanceof DeletedMetadata){ String filePath = metadata.getPathLower(); if(filePath.endsWith(".doc") || filePath.endsWith(".docx") || filePath.endsWith(".pdf")){ List&lt;FileMetadata&gt; revisions = client.files().listRevisions(filePath).getEntries(); if(revisions.size()&gt;0) { FileMetadata revision = revisions.get(0); System.out.println("Deleted File: " + filePath + ", " + revision.getClientModified() + ", Id:" + revision.getId()); revision.getRev(); client.files().restore(filePath, revision.getRev()); } } } } if (!result.getHasMore()) { break; } result = client.files().listFolderContinue(result.getCursor()); } } </code></pre>
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 serversocket = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 1234 # Reserve a port for your service. serversocket.bind((host, port)) # Bind to the port serversocket.listen(5) print("Bound the port ",port,"on Machine : ",host,", and ready to accept connections.\n") def clientThread(connection): while True: data=connection.recv(1024) if not data: break connection.send("Thanks") connection.close() def sendMessage(connection, message): connection.send(message) while 1: connection, address = serversocket.accept() start_new_thread(clientthread, (connection,)) serversocket.close(); </code></pre> <p>Now, I need to call sendMessage for a particular client, say out of clients A,B and C, send it to B. In this case, how do I identify the thread and call that function?</p>
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 own output queue.</p></li> <li><p>You'll also need a global dictionary to map a client name to their output queue.</p></li> <li><p>To send a message to a particular client, find the client's output queue and add the message to it.</p></li> <li><p>You'll also need a way to shutdown the output thread for a client. A common approach is to use a <em>sentinel</em> value (like <code>None</code>) on the queue to inform the output thread to exit its processing loop. When the client's input thread detects EOF it can place the sentinel value on the client's output queue and eventually the output thread will shut itself down.</p></li> </ol>
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_required def post(): caseid=Masterlist.query.filter_by(Ip=request.args.get('Ip')).first() form = RepairForm(request.form) print request.form if request.form.get("submit"): repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data, ManagerIp=form.managerip.data,Comp=form.comp.data,Discription=form.discription.data, Model=form.model.data,Location=form.location.data,Box=form.box.data, Important=form.important.data,Faultype=form.faultype.data,Source=form.source.data, Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data, Status=form.status.data,auth_id=current_user._get_current_object().id, Owner=current_user._get_current_object().username,) db.session.add(repair) db.session.commit() flash('报修成功') return redirect(url_for('.index')) form.ip.data=caseid.Ip form.hostname.data=caseid.Hostname form.managerip.data=caseid.Managerip form.comp.data=caseid.Comp form.model.data=caseid.Model form.location.data=caseid.Location form.box.data=caseid.Box form.classify.data=caseid.Classify form.series.data=caseid.Series form.discription.data=caseid.Discription return render_template('post.html',form=form) </code></pre>
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.get("submit"): repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data, ManagerIp=form.managerip.data,Comp=form.comp.data,Discription=form.discription.data, Model=form.model.data,Location=form.location.data,Box=form.box.data, Important=form.important.data,Faultype=form.faultype.data,Source=form.source.data, Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data, Status=form.status.data,auth_id=current_user._get_current_object().id, Owner=current_user._get_current_object().username,) db.session.add(repair) db.session.commit() flash('报修成功') return redirect(url_for('.index')) form.ip.data=caseid.Ip form.hostname.data=caseid.Hostname form.managerip.data=caseid.Managerip form.comp.data=caseid.Comp form.model.data=caseid.Model form.location.data=caseid.Location form.box.data=caseid.Box form.classify.data=caseid.Classify form.series.data=caseid.Series form.discription.data=caseid.Discription return render_template('post.html',form=form) else: pass </code></pre>
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_required def post(): caseid=Masterlist.query.filter_by(Ip=request.args.get('Ip')).first() form = RepairForm(request.form) print request.form if request.form.get("submit"): repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data, ManagerIp=form.managerip.data,Comp=form.comp.data,Discription=form.discription.data, Model=form.model.data,Location=form.location.data,Box=form.box.data, Important=form.important.data,Faultype=form.faultype.data,Source=form.source.data, Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data, Status=form.status.data,auth_id=current_user._get_current_object().id, Owner=current_user._get_current_object().username,) db.session.add(repair) db.session.commit() flash('报修成功') return redirect(url_for('.index')) form.ip.data=caseid.Ip form.hostname.data=caseid.Hostname form.managerip.data=caseid.Managerip form.comp.data=caseid.Comp form.model.data=caseid.Model form.location.data=caseid.Location form.box.data=caseid.Box form.classify.data=caseid.Classify form.series.data=caseid.Series form.discription.data=caseid.Discription return render_template('post.html',form=form) </code></pre>
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 caseid: print request.form # print request.form # if form.validate_on_submit(): # if request.method == "POST": # if request.form["submit"] == "submitpost": # if request.form.get("submit", "submit"): if request.form.get("submit"): repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data, ManagerIp=form.managerip.data,Comp=form.comp.data,Discription=form.discription.data, Model=form.model.data,Location=form.location.data,Box=form.box.data, Important=form.important.data,Faultype=form.faultype.data,Source=form.source.data, Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data, Status=form.status.data,auth_id=current_user._get_current_object().id, Owner=current_user._get_current_object().username,) db.session.add(repair) db.session.commit() flash('报修成功') return redirect(url_for('.index')) form.ip.data=caseid.Ip form.hostname.data=caseid.Hostname form.managerip.data=caseid.Managerip form.comp.data=caseid.Comp form.model.data=caseid.Model form.location.data=caseid.Location form.box.data=caseid.Box form.classify.data=caseid.Classify form.series.data=caseid.Series form.discription.data=caseid.Discription return render_template('post.html',form=form) else: if request.form.get("submit"): repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data, ManagerIp=form.managerip.data,Comp=form.comp.data,Discription=form.discription.data, Model=form.model.data,Location=form.location.data,Box=form.box.data, Important=form.important.data,Faultype=form.faultype.data,Source=form.source.data, Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data, Status=form.status.data,auth_id=current_user._get_current_object().id, Owner=current_user._get_current_object().username,) db.session.add(repair) db.session.commit() flash('报修成功') return redirect(url_for('.index')) return render_template('postmanual.html') </code></pre>
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 webdriver from selenium.webdriver.common.keys import Keys from django.test import LiveServerTestCase from users.models import User class OurClientLogInTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() ## create 1 user id User.objects.create_user(username='MyTestID', password='123', nickname='NICKNAMETEST', phone='01011111111') def tearDown(self): self.browser.quit() def test_our_client_can_log_in_this_website(self): # url connect self.browser.get(self.live_server_url) # web page header title has 'Korea book' self.assertIn('Korea book', self.browser.title) # click log_in button in main page log_in = self.browser.find_element_by_id('log_in') log_in.send_keys(Keys.ENTER) self.assertIn('로그인', self.browser.title) # insert username, password # click enter username_box = self.browser.find_element_by_name('username') password_box = self.browser.find_element_by_name('password') username_box.send_keys('MyTestID') password_box.send_keys('123') self.browser.find_element_by_id('button').click() ##redirect main page self.assertIn('Korea book', self.browser.title) ## click a button named book_sale book_sale = self.browser.find_element_by_id('book_sale') book_sale.send_keys(Keys.ENTER) from IPython import embed; embed() </code></pre> <p>I command <code>python manage.py functional_test</code></p> <p>it show me error </p> <pre><code>raceback (most recent call last): File "/Users/hanminsoo/.pyenv/versions/3.5.1/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/test/testcases.py", line 1198, in __call__ return super(FSFilesHandler, self).__call__(environ, start_response) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 177, in __call__ response = self.get_response(request) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/test/testcases.py", line 1181, in get_response return self.serve(request) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/test/testcases.py", line 1193, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/views/static.py", line 54, in serve fullpath = os.path.join(document_root, newpath) File "/Users/hanminsoo/.pyenv/versions/3.5.1/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/Users/hanminsoo/.pyenv/versions/3.5.1/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'NoneType' </code></pre> <p>when I remove the code</p> <pre><code>book_sale.send_keys(Keys.ENTER) </code></pre> <p>the test passed very clearly</p> <p>I can't not understand why book_sale button doesn't send ENTER KEY..</p> <p>please some body help me</p>
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.webelement.WebElement.send_keys" rel="nofollow"><code>send_keys()</code></a> as :-</p> <pre><code>book_sale.click() </code></pre>
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>Python output: 1.372549019607843145962533526471816003322601318359375</p> <p>Expected and wanted result: 1.4</p>
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 arithmetic operations</strong>.</p> <pre><code>getcontext().prec = 6 Decimal('3.0') Decimal('3.0') Decimal('3.1415926535') Decimal('3.1415926535') Decimal('3.1415926535') + Decimal('2.7182818285') Decimal('5.85987') getcontext().rounding = ROUND_UP Decimal('3.1415926535') + Decimal('2.7182818285') Decimal('5.85988') </code></pre> <p>so you need to use decimal in operation, not when printing result.</p>
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 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>So the bounding box is:</p> <pre><code>0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>Actually, in my task, just know the width and height of this object is enough.</p> <p>A basic idea is to search four edges in the scene parsing map, from top, bottom, left and right direction. But there might be a lot of small objects in the image, this way is not time efficient.</p> <p>A second way is to calculate the coordinates of all non-zero elements and find the max/min x/y. Then calculate weight and height using these x and y.</p> <p>Is there any other more efficient way to do this? Thx.</p>
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)</code> gives a boolean array telling you if the columns are empty (<code>False</code>) or not (<code>True</code>). <code>np.nonzero(arr.any(axis=0))[0]</code> then extract the non zero (i.e. <code>True</code>) indices from that array. <code>ind[0]</code> is the first element of that array, hence the left most column non empty column and <code>ind[-1]</code> is the last element, hence the right most non empty column. The difference then gives the width, give or take 1 depending on whether you include the borders or not. Similar stuff for the height but on the other axis.</p>
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 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>So the bounding box is:</p> <pre><code>0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>Actually, in my task, just know the width and height of this object is enough.</p> <p>A basic idea is to search four edges in the scene parsing map, from top, bottom, left and right direction. But there might be a lot of small objects in the image, this way is not time efficient.</p> <p>A second way is to calculate the coordinates of all non-zero elements and find the max/min x/y. Then calculate weight and height using these x and y.</p> <p>Is there any other more efficient way to do this? Thx.</p>
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="nofollow">http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.measurements.find_objects.html</a>):</p> <pre><code>import numpy as np from scipy import ndimage a = np.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) # Find the location of all objects objs = ndimage.find_objects(a) # Get the height and width height = int(objs[0][0].stop - objs[0][0].start) width = int(objs[0][1].stop - objs[0][1].start) </code></pre> <p>If there are many objects in the image, you first have to label each object and then get the measurements:</p> <pre><code>import numpy as np from scipy import ndimage a = np.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0]]) # Second object here # Label objects labeled_image, num_features = ndimage.label(a) # Find the location of all objects objs = ndimage.find_objects(labeled_image) # Get the height and width measurements = [] for ob in objs: measurements.append((int(ob[0].stop - ob[0].start), int(ob[1].stop - ob[1].start))) </code></pre> <p>If you check ndimage.measurements, you can get more measurements: center of mass, area...</p>
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&gt;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</code> and the numbers after the command are parameters of the dot, which regulate parameters of the dot like growing speed, maxsize etc.</p> <p>If I execute the cmd the window opens and the <code>turtle.py</code> starts to draw. the size of the screen is 800x480, so the window covers the full screen. The only thing that bothers me is the menu bar. By clicking on it and choosing "undecorate" I can make it disappear but I was not able to find a way starting the window undecorated. The <code>turtle.py</code> should start simultaneously on 12 raspberrys and it is impossible to run to each raspberry and undecorate the window.</p> <p>I already tried to modify the <code>rc.xml</code> of openbox but nothing changed. Is there maybe a command for the cmd, which starts the <code>turtle.py</code> automatically in an undecorated window?</p>
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-with-undecorated-window">an answer to a similar question</a>. From <a href="//infohost.nmt.edu/tcc/help/pubs/tkinter/web/toplevel.html" rel="nofollow">the documentation of <code>Tkinter</code></a>:</p> <blockquote> <p>If called with a <code>True</code> argument, this method sets the override redirect flag, which removes all window manager decorations from the window, so that it cannot be moved, resized, iconified, or closed. If called with a <code>False</code> argument, window manager decorations are restored and the override redirect flag is cleared. If called with no argument, it returns the current state of the override redirect flag.</p> <p>Be sure to call the <code>.update_idletasks()</code> method (see Section 26, “Universal widget methods”) before setting this flag. If you call it before entering the main loop, your window will be disabled before it ever appears.</p> <p>This method may not work on some Unix and MacOS platforms. </p> </blockquote> <p>Note that the window is <a href="/questions/22421888/tkinter-windows-without-title-bar-but-resizable">still resizable</a>, but just not through the platform's window manager.</p> <p>The quick and dirty way to access this method would be to say</p> <pre><code>turtle.Screen().get‌​canvas()._root().over‌​rideredirect(True) </code></pre> <p><strong>after</strong> the window has been created (to avoid the need for the aforementioned <code>.update_idletasks()</code> workaround).</p> <p>Normally, the <code>_</code> at the beginning of a name indicates that the member should not be touched. However, according to <a href="//docs.python.org/2/library/tkinter.html#the-window-manager" rel="nofollow">the documentation of <code>Tkinter</code></a>, this is the way to get to the root window:</p> <blockquote> <p>To get at the toplevel window that contains a given widget, you can often just refer to the widget’s master. Of course if the widget has been packed inside of a frame, the master won’t represent a toplevel window. To get at the toplevel window that contains an arbitrary widget, you can call the <code>_root()</code> method. This method begins with an underscore to denote the fact that this function is part of the implementation, and not an interface to Tk functionality.</p> </blockquote>
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. <code>[1,2,3,4,5,6,7,8,9,0]</code>. Now the tasks are fetched from the zeroth index. Now a situation arise where I want to execute task 8 above all. How can I do this?</p> <p>The worker need not execute that task(because there can be situation where a worker is already occupied). It can be run directly from the application. And when the task is completed (either from the worker or directly from the application), it should get deleted from the queue.</p> <p>I know how to forcefully revoke a task(given a task_id) but how can I execute a task given an id ?</p>
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 queuing systems(MQS) in general. The point of MQS is to desynchronize an application's component so that the producer can go on to do other work while workers execute the tasks asynchronously. In other words, once a task has been sent off it cannot be modified (but it can be removed as long as it has not been started yet).</p> <p><strong>What options are there?</strong></p> <p>Celery offers you several options to deal with lower v.s. higher priority or short- and long-running tasks, <em>at task submission time</em>:</p> <ol> <li><p><a href="http://docs.celeryproject.org/en/latest/userguide/routing.html" rel="nofollow">Routing</a> - tasks can be routed to different workers. So if your tasks [0 .. 9] are all long-running, except for task 8, you could route task 8 to a worker, or a set of workers, that deal with short-running tasks. </p></li> <li><p><a href="http://docs.celeryproject.org/en/latest/userguide/calling.html#eta-and-countdown" rel="nofollow">Timed execution</a> - specify a countdown or estimated time of arrival (eta) for each task. That's a good option if you know that some tasks can be delayed for later execution i.e. when the system will be less busy. This leaves workers ready for those tasks that need to be executed immediately. </p></li> <li><p><a href="http://docs.celeryproject.org/en/latest/userguide/calling.html#expiration" rel="nofollow">Task expiry</a> - specify an expire countdown or time with a callback. This way the task will be revoked if it didn't execute within the time alloted to it and the callback can start an alternative course of action. </p></li> <li><p><a href="http://docs.celeryproject.org/en/latest/reference/celery.result.html#celery.result.AsyncResult.status" rel="nofollow">Check on task results periodically</a>, revoke a task if it didn't start executing within some time. Note this is different from task expiry where the revoking only happens once a worker has fetched the task from the queue - if the queue is full the revoking may happen too late for your use case. Checking results periodically means you have another component in your system that does this and determines an alternate course of action.</p></li> </ol>
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 don't start.</p> <p>So far, I tried to make shell script to run my python script and then with <code>crontab</code> with <code>@reboot /home/user/startup.sh</code> to execute my python script. I set all permissions for every script that is using. I gave my user root permisions so everything is OK with that.</p> <p>I also tried to run my script putting command <code>"sudo python /path/to/my/script.py"</code> in <code>/etc/rc.local</code> file but that also is not helping.</p> <p>I googled and found out people using <code>.desktop</code> files that they put in <code>~/.config/autostart/</code> directory but that also failed. Example of what I wrote:</p> <pre><code>[Desktop Entry] Type=Application Exec="sudo python /home/user/path_to_my_script/my_script.py" X-GNOME-Autostart-enabled=true Name=screensplayer Comment=screensplayer </code></pre> <p>And I saved this as <code>program.desktop</code> in <code>~/.config/autostart/</code> directory but it does not work. I am sure there is a way to fix this but don't know how. Any help will be appreciated!</p>
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 won't run apps because of "<code>sudo</code>" word, when I removed it, it worked.</p> <p>Also run gnome-session-properties in terminal and add new startup application, be aware that you have to execute python script without sudo, like this:</p> <pre><code>python /home/user/path_to_script/script.py </code></pre> <p>Also, I granted my user root privileges so kepp that in mind.</p>
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><code>from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Category, Photo class IndexView(generic.ListView): template_name='gallery/index.html' context_object_name='cat' def get_queryset(self): return Category.objects.all() class DetailView(generic.DetailView): model=Category template_name='gallery/detail.html' context_object_name='cater' class CategoryCreate(CreateView): model=Category fields=['Category_title','artist','Category_logo'] </code></pre> <p>my urls.py</p> <pre><code>from django.conf.urls import url from . import views app_name='gallery' urlpatterns=[ url(r'^$',views.IndexView.as_view(),name='index'), url(r'^(?P&lt;pk&gt;[0-9]+)/$',views.DetailView.as_view(),name='detail'), #adding photo to category url(r'(?P&lt;pk&gt;[0-9]+)/add/$',views.PhotoCreate.as_view(),name='add- photo'), url(r'category/add/$',views.CategoryCreate.as_view(),name='add-category'), url(r'category/(?P&lt;pk&gt;[0- 9 ]+)/$',views.CategoryUpdate.as_view(),name='update-category'), </code></pre> <p>]</p> <p>my models.py</p> <pre><code>from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Category(models.Model): Category_title=models.CharField(max_length=200) artist=models.CharField(max_length=200) Category_logo=models.FileField() # returns to details page after submitting category form def get_absolute_url(self): return reverse('gallery:detail',kwargs={'pk':self.pk}) def __str__(self): return self.Category_title + '-' +self.artist class Photo(models.Model): cat=models.ForeignKey(Category,on_delete=models.CASCADE) file_type=models.FileField() photo_title=models.CharField(max_length=100) # returns to details page after submitting photo form def get_absolute_url(self): return reverse('gallery:add-photo',kwargs={'pk':self.pk}) def __str__(self): return self.photo_title </code></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 {})</p> <p>Just mention it after the url name and it should work</p> <pre><code>{% url 'gallery:add-photo' photo.pk %} </code></pre> <p>or you could also do </p> <pre><code>{{ photo.get_absolute_url }} </code></pre>
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": "filename2", "hash": "0x002" } ] } } </code></pre> <p>I've developed a function which allows me to parse the JSON code above</p> <p><strong>Function</strong></p> <pre><code>def parsePatcher(): url = '{0}/{1}'.format(downloadServer, patcherName) patch = urllib2.urlopen(url) data = json.loads(patch.read()) patch.close() return data </code></pre> <p>Okay so now I would like to do a foreach statement which prints out each name and hash inside the <code>"resources": []</code> object.</p> <p><strong>Foreach statement</strong></p> <pre><code>for name, hash in patcher["files"]["resources"]: print name print hash </code></pre> <p>But it only prints out "name" and "hash" not "filename" and "0x001"</p> <p>Am I doing something incorrect here?</p>
-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>&gt;&gt;&gt; d = {"name": "filename", "hash": "0x001"} &gt;&gt;&gt; name, hash = d &gt;&gt;&gt; name 'name' &gt;&gt;&gt; hash 'hash' </code></pre> <p>This happens because iteration over a dictionary only produces the keys:</p> <pre><code>&gt;&gt;&gt; list(d) ['name', 'hash'] </code></pre> <p>and unpacking uses iteration to produce the values to be assigned to the target names.</p> <p>That that worked at all is subject to random events even, on Python 3.3 and newer with hash randomisation enabled by default, the order of those two keys could equally be reversed.</p> <p>Just use <em>one</em> name to assign the dictionary to, and use subscription on that dictionary:</p> <pre><code>for resource in patcher["files"]["resources"]: print resource['name'] print resource['hash'] </code></pre>
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": "filename2", "hash": "0x002" } ] } } </code></pre> <p>I've developed a function which allows me to parse the JSON code above</p> <p><strong>Function</strong></p> <pre><code>def parsePatcher(): url = '{0}/{1}'.format(downloadServer, patcherName) patch = urllib2.urlopen(url) data = json.loads(patch.read()) patch.close() return data </code></pre> <p>Okay so now I would like to do a foreach statement which prints out each name and hash inside the <code>"resources": []</code> object.</p> <p><strong>Foreach statement</strong></p> <pre><code>for name, hash in patcher["files"]["resources"]: print name print hash </code></pre> <p>But it only prints out "name" and "hash" not "filename" and "0x001"</p> <p>Am I doing something incorrect here?</p>
-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"},{ "name": "filename2", "hash": "0x002"}]} } for element in mydict["files"]["resources"]: for d in element: print d, element[d] </code></pre>
-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": "filename2", "hash": "0x002" } ] } } </code></pre> <p>I've developed a function which allows me to parse the JSON code above</p> <p><strong>Function</strong></p> <pre><code>def parsePatcher(): url = '{0}/{1}'.format(downloadServer, patcherName) patch = urllib2.urlopen(url) data = json.loads(patch.read()) patch.close() return data </code></pre> <p>Okay so now I would like to do a foreach statement which prints out each name and hash inside the <code>"resources": []</code> object.</p> <p><strong>Foreach statement</strong></p> <pre><code>for name, hash in patcher["files"]["resources"]: print name print hash </code></pre> <p>But it only prints out "name" and "hash" not "filename" and "0x001"</p> <p>Am I doing something incorrect here?</p>
-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": "filename2", "hash": "0x002" } ] } } </code></pre> <p>I've developed a function which allows me to parse the JSON code above</p> <p><strong>Function</strong></p> <pre><code>def parsePatcher(): url = '{0}/{1}'.format(downloadServer, patcherName) patch = urllib2.urlopen(url) data = json.loads(patch.read()) patch.close() return data </code></pre> <p>Okay so now I would like to do a foreach statement which prints out each name and hash inside the <code>"resources": []</code> object.</p> <p><strong>Foreach statement</strong></p> <pre><code>for name, hash in patcher["files"]["resources"]: print name print hash </code></pre> <p>But it only prints out "name" and "hash" not "filename" and "0x001"</p> <p>Am I doing something incorrect here?</p>
-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 indices in patcher[keys].keys(): ... print(patcher[keys][indices]) ... [{'hash': '0x001', 'name': 'filename'}, {'hash': '0x002', 'name': 'filename2'}] </code></pre>
-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 described here: <a href="http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_linestyle" rel="nofollow">http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_linestyle</a></p> <p>This thread treats a similar topic: <a href="http://stackoverflow.com/questions/32502153/pandas-boxplot-median-color-settings-issues">pandas - boxplot median color settings issues</a></p>
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(): cleaned_data_job_creation_form = job_creation_form.cleaned_data try: with transaction.atomic(): text = cleaned_data_job_creation_form.get('text_to_translate') if text: cleaned_data_job_creation_form['file']=create_txt_file(text) Job.objects.create( customer=request.user, text_to_translate=cleaned_data_job_creation_form['text_to_translate'], file=cleaned_data_job_creation_form['file'].... ) except Exception as e: RaiseHttp404(request, 'Something went wrong :(') return HttpResponseRedirect(reverse('review_orders')) </code></pre> <p>I though about creating a <code>txt</code> file like:</p> <pre><code>with open('name.txt','a') as f: ... </code></pre> <p>But there can be many problems - the directory where the file is saved, the name of the file which uploading handles automatically etc.</p> <p>Do you know a better way? </p> <p>In short:</p> <p>If the text to translate has been filled, fake it so it looks like <code>txt</code> file has been uploaded.</p>
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 msvcrt) and it worked great for pretty much everything but comparisons. I replaced the return of None with an empty string if no input is entered in time and I used some test lines as shown below: </p> <pre><code>import msvcrt import time def raw_input_with_timeout(prompt, timeout): print prompt, finishat = time.time() + timeout result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': # or \n, whatever Win returns;-) return ''.join(result) time.sleep(0.1) # just to yield to other processes/threads else: if time.time() &gt; finishat: return "" textVar = raw_input_with_timeout("Enter here: \n", 5) print str(textVar) # to make sure the string is being stored print type(str(textVar)) # to make sure it is of type string and can be compared print str(str(textVar) == "test") time.sleep(10) # so I can see the output </code></pre> <p>After I compile that with pyinstaller, run it, and type test into the window, I get this output: </p> <pre><code>Enter here: test test &lt;type 'str'&gt; False </code></pre> <p>I originally thought the comparison was returning False because the function appends characters to an array and that may have had something to do with it not doing a proper comparison with a string, but after looking further into the way Python works (namely, SilentGhost's response <a href="http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce">here</a>), I really have no idea why the comparison will not return True. Any response is appreciated. Thank you!</p>
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 msvcrt) and it worked great for pretty much everything but comparisons. I replaced the return of None with an empty string if no input is entered in time and I used some test lines as shown below: </p> <pre><code>import msvcrt import time def raw_input_with_timeout(prompt, timeout): print prompt, finishat = time.time() + timeout result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': # or \n, whatever Win returns;-) return ''.join(result) time.sleep(0.1) # just to yield to other processes/threads else: if time.time() &gt; finishat: return "" textVar = raw_input_with_timeout("Enter here: \n", 5) print str(textVar) # to make sure the string is being stored print type(str(textVar)) # to make sure it is of type string and can be compared print str(str(textVar) == "test") time.sleep(10) # so I can see the output </code></pre> <p>After I compile that with pyinstaller, run it, and type test into the window, I get this output: </p> <pre><code>Enter here: test test &lt;type 'str'&gt; False </code></pre> <p>I originally thought the comparison was returning False because the function appends characters to an array and that may have had something to do with it not doing a proper comparison with a string, but after looking further into the way Python works (namely, SilentGhost's response <a href="http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce">here</a>), I really have no idea why the comparison will not return True. Any response is appreciated. Thank you!</p>
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-friendly representation</em> instead. This representation will format the string as a Python string literal, using only printable ASCII characters and escape sequences:</p> <pre><code>&gt;&gt;&gt; foo = 'test\t\n' &gt;&gt;&gt; print foo test &gt;&gt;&gt; foo == 'test' False &gt;&gt;&gt; print repr(foo) 'test\t\n' </code></pre> <p>In your case, you are <strong>including</strong> the <code>\r</code> carriage return character in your return value:</p> <pre><code>if result[-1] == '\r': return ''.join(result) </code></pre> <p>That last <code>\r</code> is still there, so you get, at the very least, the value <code>'test\r'</code>, but <code>\r</code> won't show up when printing:</p> <pre><code>&gt;&gt;&gt; print 'test\r' test &gt;&gt;&gt; print repr('test\r') 'test\r' </code></pre> <p>You could just <em>exclude</em> that last character when joining, by slicing the string:</p> <pre><code>return ''.join(result[:-1]) </code></pre> <p>or you could use <code>str.strip()</code> to remove all whitespace characters from both the start and end of the string (including that <code>\r</code> character):</p> <pre><code>return ''.join(result).strip() </code></pre> <p>Note that there is no point in using <code>str()</code> calls here. You return a <code>str</code> object, so <code>str(textVar)</code> is redundant. Moreover, <code>print</code> will call <code>str()</code> on anything not a string object yet.</p>
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 msvcrt) and it worked great for pretty much everything but comparisons. I replaced the return of None with an empty string if no input is entered in time and I used some test lines as shown below: </p> <pre><code>import msvcrt import time def raw_input_with_timeout(prompt, timeout): print prompt, finishat = time.time() + timeout result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': # or \n, whatever Win returns;-) return ''.join(result) time.sleep(0.1) # just to yield to other processes/threads else: if time.time() &gt; finishat: return "" textVar = raw_input_with_timeout("Enter here: \n", 5) print str(textVar) # to make sure the string is being stored print type(str(textVar)) # to make sure it is of type string and can be compared print str(str(textVar) == "test") time.sleep(10) # so I can see the output </code></pre> <p>After I compile that with pyinstaller, run it, and type test into the window, I get this output: </p> <pre><code>Enter here: test test &lt;type 'str'&gt; False </code></pre> <p>I originally thought the comparison was returning False because the function appends characters to an array and that may have had something to do with it not doing a proper comparison with a string, but after looking further into the way Python works (namely, SilentGhost's response <a href="http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce">here</a>), I really have no idea why the comparison will not return True. Any response is appreciated. Thank you!</p>
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 final character that the user enters must be <code>\r</code>, which is an unprintable character corresponding to the carriage return. Therefore, the returned input string looks like:</p> <pre><code>test\r </code></pre> <p>I think you need to rework to the code to discard the final unprintable character from the input.</p>
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>At the moment I have launching <code>jar</code>s in a <code>bat</code> file, but it makes it useless for <code>UNIX</code>. I tried the following:</p> <p><code>subprocess.call(['java', '-jar', 'elasticmq-server-0.8.12.jar'], shell=True)</code></p> <p>but it doesn't work as I want. I expect <code>jar</code>s to launch in separate consoles after double-clicking on script.py. Is it possible? Below I attach the <code>Minimal Complete Verifiable Example</code>:</p> <p><strong>My code</strong></p> <pre><code>import subprocess import time, sys import requests subprocess.call(['java', '-jar', 'elasticmq-server-0.8.12.jar'], shell=True) #call("my.bat") - it works on Windows, but not on Linux time.sleep(5) #elastic must complete launch - it usually takes 1024 milsec, so I w8 5 just in case. requests.get('http://localhost:8888/?Action=CreateQueue&amp;QueueName=top-secret') requests.get('http://localhost:8888/?Action=CreateQueue&amp;QueueName=top-secret2') requests.get('http://localhost:8888/?Action=CreateQueue&amp;QueueName=top-secret3') requests.post('http://127.0.0.1:7777/some/catalogs/register', data = {"JSON WITH DATA FOR CONSUL") </code></pre> <p><strong>Expected behavior</strong></p> <ol> <li>Launch script with a double click.</li> <li>Launch consul in new console,</li> <li>Launch elastic in new console,</li> <li>Wait 2-5 seconds - it already works.</li> <li>Call requests - it already works.</li> </ol>
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 like: <code>x-terminal-emulator -e 'bash -c "sleep 20"'</code> .... but this likely would not work on Mac... And you need to effectively test which OS you are on.</p>
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>At the moment I have launching <code>jar</code>s in a <code>bat</code> file, but it makes it useless for <code>UNIX</code>. I tried the following:</p> <p><code>subprocess.call(['java', '-jar', 'elasticmq-server-0.8.12.jar'], shell=True)</code></p> <p>but it doesn't work as I want. I expect <code>jar</code>s to launch in separate consoles after double-clicking on script.py. Is it possible? Below I attach the <code>Minimal Complete Verifiable Example</code>:</p> <p><strong>My code</strong></p> <pre><code>import subprocess import time, sys import requests subprocess.call(['java', '-jar', 'elasticmq-server-0.8.12.jar'], shell=True) #call("my.bat") - it works on Windows, but not on Linux time.sleep(5) #elastic must complete launch - it usually takes 1024 milsec, so I w8 5 just in case. requests.get('http://localhost:8888/?Action=CreateQueue&amp;QueueName=top-secret') requests.get('http://localhost:8888/?Action=CreateQueue&amp;QueueName=top-secret2') requests.get('http://localhost:8888/?Action=CreateQueue&amp;QueueName=top-secret3') requests.post('http://127.0.0.1:7777/some/catalogs/register', data = {"JSON WITH DATA FOR CONSUL") </code></pre> <p><strong>Expected behavior</strong></p> <ol> <li>Launch script with a double click.</li> <li>Launch consul in new console,</li> <li>Launch elastic in new console,</li> <li>Wait 2-5 seconds - it already works.</li> <li>Call requests - it already works.</li> </ol>
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 file. Basically after every line, I want to add a comma (<code>,</code>). My code in Python looks like this.</p> <pre><code>with open ('new_locations.txt', 'w') as output: with open('locations.txt', 'r') as input: for line in input: new_line = line+',' output.write(new_line) </code></pre> <p>where <code>new_locations.txt</code> is the output text file, <code>locations.txt</code> is the raw data. </p> <p>However, it throws me error all the time. </p> <blockquote> <p>UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 3724: character maps to </p> </blockquote> <p>Where exactly am I going wrong?</p> <blockquote> <p>Note: The characters in raw data are not all ASCII characters. Some are Latin characters as well. </p> </blockquote>
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 charachter and may not be the desired output, here is how that will be done :</p> <pre><code>output.write(new_line.encode('ascii','ignore'))# or 'utf-8' </code></pre>
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 file. Basically after every line, I want to add a comma (<code>,</code>). My code in Python looks like this.</p> <pre><code>with open ('new_locations.txt', 'w') as output: with open('locations.txt', 'r') as input: for line in input: new_line = line+',' output.write(new_line) </code></pre> <p>where <code>new_locations.txt</code> is the output text file, <code>locations.txt</code> is the raw data. </p> <p>However, it throws me error all the time. </p> <blockquote> <p>UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 3724: character maps to </p> </blockquote> <p>Where exactly am I going wrong?</p> <blockquote> <p>Note: The characters in raw data are not all ASCII characters. Some are Latin characters as well. </p> </blockquote>
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', encoding='latin_1') as input </code></pre> <p>You should probably also do this with the output if you want the output also to be in latin-1.</p> <p>In the longer term, you should probably consider converting all your data to a unicode format in the data files.</p>
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("category").cat.codes </code></pre> <p>I got following error</p> <blockquote> <p>'Series' object has no attribute 'wheat_type'</p> </blockquote> <p>on executing type(X),I got</p> <pre><code> &lt;class 'pandas.core.frame.DataFrame'&gt; </code></pre> <p>and on executing type(y),I got</p> <pre><code> &lt;class 'pandas.core.series.Series'&gt; </code></pre> <p>Is there possible way to covert y into a dataframe.If not,please tell me how to create required dataframe y from x</p>
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]: df.a.to_frame() Out[4]: a 0 0 1 1 2 2 3 3 </code></pre>
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("category").cat.codes </code></pre> <p>I got following error</p> <blockquote> <p>'Series' object has no attribute 'wheat_type'</p> </blockquote> <p>on executing type(X),I got</p> <pre><code> &lt;class 'pandas.core.frame.DataFrame'&gt; </code></pre> <p>and on executing type(y),I got</p> <pre><code> &lt;class 'pandas.core.series.Series'&gt; </code></pre> <p>Is there possible way to covert y into a dataframe.If not,please tell me how to create required dataframe y from x</p>
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.DataFrame({'wheat_type':[5,7,3]}) print (X) wheat_type 0 5 1 7 2 3 #create DataFrame by subset y=X[['wheat_type']] #cast to category and get codes y['wheat_type'] = y.wheat_type.astype("category").cat.codes print (y) wheat_type 0 1 1 2 2 0 </code></pre> <p>If there are multiple columns, better is use <code>to_frame</code> as pointed <a href="http://stackoverflow.com/a/38913459/2901002"><code>Ami</code></a>:</p> <pre><code>X = pd.DataFrame({'wheat_type':[5,7,3], 'z':[4,7,9]}) print (X) wheat_type z 0 5 4 1 7 7 2 3 9 y = X['wheat_type'].to_frame() #cast to category and get codes y['wheat_type'] = y.wheat_type.astype("category").cat.codes print (y) wheat_type 0 1 1 2 2 0 </code></pre> <hr> <p>Another solution for creating new DataFrame is by subset and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow"><code>copy</code></a>:</p> <pre><code>y = X[['wheat_type']].copy() </code></pre>
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( name = 'pyduino', description = 'PyDuino project aims to make python interactive with hardware particularly arduino.', url = '###', keywords = 'python arduino', author = '###', author_email = '###', version = '0.0.0', license = 'GNU', packages = ['pyduino'], install_requires = ['pyserial'], classifiers = [ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], scripts=['pyduino/pyduino.py'], ) </code></pre> <p>Package installs in /usr/local/bin directory.But when I am importing the modules outside the /usr/local/bin,import error occurs.I tried changing path to /usr/local/bin and it works perfectly and import error doesn't occur.How can I install the package so that I can import the modules in any directory? Thanks in advance...</p>
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 different directory using pip?</a> and i'll suggest to read what are 1. pip 2. virtualenv </p> <p>Good luck :)</p> <p>EDIT: i found the package is installed with pip like:</p> <pre><code>pip install --install-option="--prefix=/usr/local/bin" pyduino_mk </code></pre>
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( name = 'pyduino', description = 'PyDuino project aims to make python interactive with hardware particularly arduino.', url = '###', keywords = 'python arduino', author = '###', author_email = '###', version = '0.0.0', license = 'GNU', packages = ['pyduino'], install_requires = ['pyserial'], classifiers = [ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], scripts=['pyduino/pyduino.py'], ) </code></pre> <p>Package installs in /usr/local/bin directory.But when I am importing the modules outside the /usr/local/bin,import error occurs.I tried changing path to /usr/local/bin and it works perfectly and import error doesn't occur.How can I install the package so that I can import the modules in any directory? Thanks in advance...</p>
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>scripts</code> when you want to install executable scripts (stuff you want to call from command line). Otherwise, you need to use <code>packages</code>.</p> <p>My approach would be like this:</p> <ul> <li>install the <code>pyduino/pyduino.py</code> in the library with something like <code>packages=['pyduino']</code></li> <li>create a wrapper (shell or python) capable of calling your installed script and install that via <code>scripts=[...]</code></li> </ul> <p>Using the <code>packages</code> tag for your module will install it in <code>/usr/local/lib/python...</code>, which is in <code>PYTHONPATH</code>. This will allow you to import your script with something like <code>import pyduino.pyduino.*</code>.</p> <p>For the wrapper script part:</p> <p>A best practice is to isolate the code to be executed if the script is triggered from command line in something like:</p> <pre><code>def main(): # insert your code here pass if __name__ == '__main__': main() </code></pre> <ul> <li>Assuming there is a <code>def main()</code> as above</li> <li>create a directory <code>scripts</code> in your tree (at the same level with <code>setup.py</code>)</li> <li>create a file <code>scripts/pyduino</code></li> <li><p>in <code>scripts/pyduino</code>:</p> <pre><code>#!/usr/bin/env python from pydiuno.pyduino import main if __name__ == '__main__': main() </code></pre></li> <li>add a `scripts = ['scripts/pyduino'] to your setup.py code</li> </ul>
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 it doesn't show error</p> <p><strong>script1.py</strong>:</p> <pre><code>from sys import * if len(argv)==2 and argv[1]=="what": print "done" else: pass </code></pre> <p>What is logical <code>AND</code> doing?</p>
-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 it doesn't show error</p> <p><strong>script1.py</strong>:</p> <pre><code>from sys import * if len(argv)==2 and argv[1]=="what": print "done" else: pass </code></pre> <p>What is logical <code>AND</code> doing?</p>
-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 iterable object. But the standards approach using <code>ast.literal_eval</code> doesn't like the input.</p> <p>Is there something else I can try before I start looking into str replace etc...</p> <p>Thank you</p>
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: parsed_dict = {} for record in line.split(","): k, v = record.split(":") parsed_dict[k] = v parsed_list.append(parsed_dict) print(parsed_list) </code></pre> <p>The output is list of dictionaries, you can itarate over it in many ways.</p>
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 trainData = np.random.randint(2,size=2) # array([ ..some values.. ]) </code></pre> <p>then add [np.newaxis] to it</p> <pre><code>np.random.randint(2,size=2)[np.newaxis] # array([[ ..some values.. ]]) </code></pre> <p>See: <a href="http://stackoverflow.com/questions/28385666/numpy-use-reshape-or-newaxis-to-add-dimensions">numpy newaxis</a>, <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">numpy broadcasting</a></p>
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' form_class = ColorImageForm def form_valid(self, form): download_link = .... return HttpResponse(...?...) </code></pre> <p><a href="http://i.stack.imgur.com/gF8D2.png" rel="nofollow">Screenshot</a></p>
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 %} &lt;a href="{{ download_link }}"&gt;Download&lt;/a&gt; {% 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_context_data(download_link=download_link)) </code></pre>
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 combinations of parts of a given number</a></p> <pre><code>def sum_to_n(n, size, limit=None): """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = n start = (n + size - 1) // size stop = min(limit, n - size + 1) + 1 for i in range(start, stop): for tail in sum_to_n(n - i, size - 1, i): yield [i] + tail for partition in sum_to_n(8, 3): print (partition) [6, 1, 1] [5, 2, 1] [4, 3, 1] [4, 2, 2] [3, 3, 2] </code></pre> <p>Is it very useful but I'm trying to modify it in order to set some options. Suppose I want to have only the results in wich the first number of the list is 4 and the last of the list is 1. At the moment I use this solution:</p> <pre><code>def sum_to_n(n,first, last, size, limit=None): if size == 1: yield [n] return if limit is None: limit = n start = (n + size - 1) // size stop = min(limit, n - size + 1) + 1 for i in range(start, stop): if i &lt;=first: for tail in sum_to_n(n - i,first,last, size - 1, i): ll=len(tail) if tail[ll-1]==last: yield [i] + tail for i in sum_to_n(8,4,1,3): if i[0]==4 and i[size-1]==1: print(i) if i[0]&gt;4: break [4,3,1] </code></pre> <p>But with larger integers the program is doing a lot of unwanted work. For example, the <code>for i in range(start, stop):</code> computes all the possible first numbers of the list and not only the "first" parameter nedded and the function does not work without it. Someone can suggest a better and faster solution to call the function giving the parameters needed in order to have only the requested computations ?</p>
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 = re.compile(r"^import\s+(\w,\s*)*(\w+)") pattern.findall(testString) </code></pre> <p>This gives me <code>[('math,','string')]</code>, but no <code>os</code>, so I tried to use the search method.</p> <pre><code>p.search(a).groups() </code></pre> <p>This gives me the same result as with findall.</p> <pre><code>p.search(a).group(0) </code></pre> <p>Gives me <code>'import os, math, string'</code></p> <p>How can i get the module name 'os' by regular expression?</p>
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>&gt;&gt;&gt; m = regex.match("^import\s+(\w+,\s*)*(\w+)", testString) &gt;&gt;&gt; m.captures(1) ['os, ', 'math, '] </code></pre> <p>If you want to use <code>regex</code>, you should install it first. It is not a part of standard library.</p> <p>But it would be better to use <code>findall</code> in this case, like @akash_karothiya suggests.</p>
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 = re.compile(r"^import\s+(\w,\s*)*(\w+)") pattern.findall(testString) </code></pre> <p>This gives me <code>[('math,','string')]</code>, but no <code>os</code>, so I tried to use the search method.</p> <pre><code>p.search(a).groups() </code></pre> <p>This gives me the same result as with findall.</p> <pre><code>p.search(a).group(0) </code></pre> <p>Gives me <code>'import os, math, string'</code></p> <p>How can i get the module name 'os' by regular expression?</p>
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 "): print(testString[7:].split(', ')) # = &gt; ['os', 'math', 'string'] </code></pre> <p>See the <a href="https://ideone.com/Gr9ixe" rel="nofollow">Python demo</a></p> <p>If the spaces are used inconsistently between the commas and packages, use</p> <pre><code>[x.strip() for x in testString[7:].split(',')] </code></pre> <p>See <a href="https://ideone.com/N4gRVI" rel="nofollow">another Python demo</a></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 = re.compile(r"^import\s+(\w,\s*)*(\w+)") pattern.findall(testString) </code></pre> <p>This gives me <code>[('math,','string')]</code>, but no <code>os</code>, so I tried to use the search method.</p> <pre><code>p.search(a).groups() </code></pre> <p>This gives me the same result as with findall.</p> <pre><code>p.search(a).group(0) </code></pre> <p>Gives me <code>'import os, math, string'</code></p> <p>How can i get the module name 'os' by regular expression?</p>
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 = re.compile(r"^import\s+(\w,\s*)*(\w+)") pattern.findall(testString) </code></pre> <p>This gives me <code>[('math,','string')]</code>, but no <code>os</code>, so I tried to use the search method.</p> <pre><code>p.search(a).groups() </code></pre> <p>This gives me the same result as with findall.</p> <pre><code>p.search(a).group(0) </code></pre> <p>Gives me <code>'import os, math, string'</code></p> <p>How can i get the module name 'os' by regular expression?</p>
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> <p>or shorter</p> <pre><code>re.findall(r"(?!import)\s(\w.+)", testString) </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&#39;s &#39;private&#39; methods not actually private?</a></p> <p>The "best" example for encapsulation would be pimpl from c++: <a href="http://stackoverflow.com/questions/17847719/how-do-you-do-true-encapsulation-in-c">How do you do &quot;true&quot; encapsulation in C++?</a></p> <p>Encapsulation only makes real sense, when you want someone to not mess around with your inner variables.</p> <p>If you got full source accesss to such things, you can always have a look, change things ( for the better or the worse ).</p> <p>So, lets say, you are a software developer for the navigational system of a car. The manufacturer gave you an api-doc how to connect to the car, you can access informations via functions ( eg, get gps coordinates ) and can set informations yourself via functions. But the software handling the engine, is most likely hidden/locked for your navigation software ( well, in most cases its done badly... but just for example reasons) A good example would be the horse-power variable ( dunno if it exists ), you shoulnt be able to see/set/get that number in your navigation software... and thats all the fuss is about.</p>
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 be too small and the value inside begin not clear like in the attached image.</p> <p>How can I change the size of the heatmap to be more bigger ? Thank you<a href="http://i.stack.imgur.com/pvCQG.png" rel="nofollow"><img src="http://i.stack.imgur.com/pvCQG.png" alt="enter image description here"></a></p> <p><strong>EDIT</strong></p> <p>I try : </p> <pre><code>df1.index = pd.to_datetime(df1.index) fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax) df1 = df1.set_index('TIMESTAMP') df1 = df1.resample('1d').mean() ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5) </code></pre> <p>But I get this error : </p> <pre><code>KeyError Traceback (most recent call last) C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance) 1944 try: -&gt; 1945 return self._engine.get_loc(key) 1946 except KeyError: pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)() KeyError: 'TIMESTAMP' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-779-acaf05718dd8&gt; in &lt;module&gt;() 2 fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches 3 sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax) ----&gt; 4 df1 = df1.set_index('TIMESTAMP') 5 df1 = df1.resample('1d').mean() 6 ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5) C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in set_index(self, keys, drop, append, inplace, verify_integrity) 2835 names.append(None) 2836 else: -&gt; 2837 level = frame[col]._values 2838 names.append(col) 2839 if drop: C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 1995 return self._getitem_multilevel(key) 1996 else: -&gt; 1997 return self._getitem_column(key) 1998 1999 def _getitem_column(self, key): C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key) 2002 # get column 2003 if self.columns.is_unique: -&gt; 2004 return self._get_item_cache(key) 2005 2006 # duplicate columns &amp; possible reduce dimensionality C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item) 1348 res = cache.get(item) 1349 if res is None: -&gt; 1350 values = self._data.get(item) 1351 res = self._box_item_values(item, values) 1352 cache[item] = res C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath) 3288 3289 if not isnull(item): -&gt; 3290 loc = self.items.get_loc(item) 3291 else: 3292 indexer = np.arange(len(self.items))[isnull(self.items)] C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -&gt; 1947 return self._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance) pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)() KeyError: 'TIMESTAMP' </code></pre> <p><strong>EDIT</strong></p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-890-86bff697504a&gt; in &lt;module&gt;() 2 df2.resample('30min').mean() 3 fig, ax = plt.subplots() ----&gt; 4 ax = sns.heatmap(df2.iloc[:, 1:6:], annot=True, linewidths=.5) 5 ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df2.index], rotation=0) C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, ax, xticklabels, yticklabels, mask, **kwargs) 483 plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt, 484 annot_kws, cbar, cbar_kws, xticklabels, --&gt; 485 yticklabels, mask) 486 487 # Add the pcolormesh kwargs here C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask) 165 # Determine good default values for the colormapping 166 self._determine_cmap_params(plot_data, vmin, vmax, --&gt; 167 cmap, center, robust) 168 169 # Sort out the annotations C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust) 202 cmap, center, robust): 203 """Use some heuristics to set good defaults for colorbar and range.""" --&gt; 204 calc_data = plot_data.data[~np.isnan(plot_data.data)] 205 if vmin is None: 206 vmin = np.percentile(calc_data, 2) if robust else calc_data.min() TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' </code></pre>
-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(figsize=(10,10)) # Sample figsize in inches sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax) </code></pre> <p><strong>EDIT</strong></p> <p>I remember answering a similar question of yours where you had to set the index as <code>TIMESTAMP</code>. So, you could then do something like below:</p> <pre><code>df = df.set_index('TIMESTAMP') df.resample('30min').mean() fig, ax = plt.subplots() ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5) ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0) </code></pre> <p>For the <code>head</code> of the dataframe you posted, the plot would look like:</p> <p><a href="http://i.stack.imgur.com/RqGom.png" rel="nofollow"><img src="http://i.stack.imgur.com/RqGom.png" alt="enter image description here"></a></p>
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 be too small and the value inside begin not clear like in the attached image.</p> <p>How can I change the size of the heatmap to be more bigger ? Thank you<a href="http://i.stack.imgur.com/pvCQG.png" rel="nofollow"><img src="http://i.stack.imgur.com/pvCQG.png" alt="enter image description here"></a></p> <p><strong>EDIT</strong></p> <p>I try : </p> <pre><code>df1.index = pd.to_datetime(df1.index) fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax) df1 = df1.set_index('TIMESTAMP') df1 = df1.resample('1d').mean() ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5) </code></pre> <p>But I get this error : </p> <pre><code>KeyError Traceback (most recent call last) C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance) 1944 try: -&gt; 1945 return self._engine.get_loc(key) 1946 except KeyError: pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)() KeyError: 'TIMESTAMP' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-779-acaf05718dd8&gt; in &lt;module&gt;() 2 fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches 3 sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax) ----&gt; 4 df1 = df1.set_index('TIMESTAMP') 5 df1 = df1.resample('1d').mean() 6 ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5) C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in set_index(self, keys, drop, append, inplace, verify_integrity) 2835 names.append(None) 2836 else: -&gt; 2837 level = frame[col]._values 2838 names.append(col) 2839 if drop: C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 1995 return self._getitem_multilevel(key) 1996 else: -&gt; 1997 return self._getitem_column(key) 1998 1999 def _getitem_column(self, key): C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key) 2002 # get column 2003 if self.columns.is_unique: -&gt; 2004 return self._get_item_cache(key) 2005 2006 # duplicate columns &amp; possible reduce dimensionality C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item) 1348 res = cache.get(item) 1349 if res is None: -&gt; 1350 values = self._data.get(item) 1351 res = self._box_item_values(item, values) 1352 cache[item] = res C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath) 3288 3289 if not isnull(item): -&gt; 3290 loc = self.items.get_loc(item) 3291 else: 3292 indexer = np.arange(len(self.items))[isnull(self.items)] C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -&gt; 1947 return self._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance) pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)() KeyError: 'TIMESTAMP' </code></pre> <p><strong>EDIT</strong></p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-890-86bff697504a&gt; in &lt;module&gt;() 2 df2.resample('30min').mean() 3 fig, ax = plt.subplots() ----&gt; 4 ax = sns.heatmap(df2.iloc[:, 1:6:], annot=True, linewidths=.5) 5 ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df2.index], rotation=0) C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, ax, xticklabels, yticklabels, mask, **kwargs) 483 plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt, 484 annot_kws, cbar, cbar_kws, xticklabels, --&gt; 485 yticklabels, mask) 486 487 # Add the pcolormesh kwargs here C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask) 165 # Determine good default values for the colormapping 166 self._determine_cmap_params(plot_data, vmin, vmax, --&gt; 167 cmap, center, robust) 168 169 # Sort out the annotations C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust) 202 cmap, center, robust): 203 """Use some heuristics to set good defaults for colorbar and range.""" --&gt; 204 calc_data = plot_data.data[~np.isnan(plot_data.data)] 205 if vmin is None: 206 vmin = np.percentile(calc_data, 2) if robust else calc_data.min() TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' </code></pre>
-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</p> <pre><code>ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, fmt="d") </code></pre>
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 self.fives=0 self.sixs=0 self.abovesum=0 self.bonus=0 self.onepair=0 self.twopair=0 self.threepair=0 self.fourpair=0 self.smalladder=0 self.bigladder=0 self.house=0 self.chance=0 self.yatzy=0 self.totalsum=0 #self.lista={"ones":0,"twos":0,"threes":0, "fours":0,"fives":0,"sixs":0,"abovesum":0,"bonus":0,"onepair":0,"twopair":0,"threepair":0,"fourpair":0,"smalladder":0,"bigladder":0,"house":0,"chance":0,"yatzy":0,"totalsum":0} def __repr__(self): return self.name def __str__(self): return self.name def countbonus(self): self.abovesum=self.ones+self.twos+self.threes+self.fours+self.fives+self.sixs if self.abovesum&gt;=63: self.bonus+=50 return self.abovesum, self.bonus else: return self.abovesum, self.bonus def counttotalsum(self): self.totalsum=self.abovesum+self.bonus+self.onepair+self.twopair+self.threepair+self.fourpair+self.smalladder+self.bigladder+self.house+self.chance+self.yatzy def add(self): moment=input("Where do you want to put your points?: ") #ej klar points=input("How many points did you get?: ") self.lista def visa(self): for i in self.name: print(i) def welcome(): print("Welcome to the yahtzee game!") players = int(input("How many players: ")) rounds=0 spelarlista=[] spelarlista.append("name") while not players==rounds: player=input("What is your name?: ") rounds=rounds+1 spelarlista.append(Player(player)) table_data = [spelarlista, ['Ettor',spelarlista[0].ones], ['Tvåor'], ['Treor'], ['Fyror'], ['femmor'], ['sexor']] table = AsciiTable(table_data) table.inner_row_border = True table.table_data[0][0] += '\n' print(table.table) welcome() </code></pre> <p>I'm currently getting the errormessage "Str"-object has no attribute "ones". I understand that the line spelarlista[0].ones is not working, but let's say I ru the programme with the players "James" and "Anders", and I want my yatzy to print out the table with the players current score, how do I refer to that, let's say I did type "James" first, what do I write to get his points? </p> <p>Thanks in advance!</p>
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>Details :</h2> <ul> <li>I use the <a href="https://github.com/rest-client/rest-client/tree/v1.8.0" rel="nofollow">RestClient gem (v1.8.0)</a> and am trying a simple GET request</li> <li><p>The <a href="https://github.com/aabde/sync-engine/blob/develop/abde/bin/inbox-api#L74" rel="nofollow">python code to launch the server</a> is as so :</p> <p>http_server = WSGIServer(('', int(port)), app, log=nylas_logger, handler_class=NylasWSGIHandler,<br> keyfile='/vagrant/server.key', certfile='/vagrant/server.crt')</p></li> <li>I use the same certificates (wildcard certificate COMODO) on another subdomain on another server (Nginx Passenger) and I can successfully launch my requests</li> </ul> <h2>What I tried :</h2> <ul> <li>I tried reinstalling Openssl using Brew</li> <li>I successfully launched my request passing the verify_ssl: false flag to the restclient gem (but I want to find a solution that does not use this workaround)</li> <li>I tried reinstalling Ruby (I'm using RVM) with the --disable-bynary flag</li> <li>I launched <code>rvm osx-ssl-certs update all</code></li> </ul> <p>The most surprising is that I actually can perform requests on another type of server using the same certificates so it seems the issue may be with the Python web server.</p>
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{ listen 80; return 301 https://$host$request_uri; } server{ listen 443; server_name subdomain.domain.com; ssl on; ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/cert.key; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proro $scheme; proxy_pass http://localhost:5555; proxy_read_timeout 90; proxy_pass_request_headers on; proxy_redirect http://localhost:5555 https://subdomain.domain.com; } } </code></pre> <p>And I restricted the python server to listen only to localhost requests.</p>
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>import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) GPIO.setup(13, GPIO.IN, GPIO.PUD_UP) GPIO.setup(7,GPIO.OUT) GPIO.setup(37, GPIO.OUT) Hologram = '/home/pi/Hologram/Hologram.mp4' from subprocess import Popen firstTimeOpen=0 while True: doorIsOpen = GPIO.input(13) if doorIsOpen==0 and firstTimeOpen == 0: firstTimeOpen=1 GPIO.output(7, 0) GPIO.output(37, 0) sleep(0.5) if doorIsOpen==1 and firstTimeOpen == 1: GPIO.output(7, 1) GPIO.output(37, 1) omxp = Popen(['omxplayer' ,Hologram]) sleep(87) GPIO.output(7, 0) GPIO.output(37, 0) firstTimeOpen=0 sleep(0.5) </code></pre>
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>import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) GPIO.setup(13, GPIO.IN, GPIO.PUD_UP) GPIO.setup(7,GPIO.OUT) GPIO.setup(37, GPIO.OUT) Hologram = '/home/pi/Hologram/Hologram.mp4' from subprocess import Popen firstTimeOpen=0 while True: doorIsOpen = GPIO.input(13) if doorIsOpen==0 and firstTimeOpen == 0: firstTimeOpen=1 GPIO.output(7, 0) GPIO.output(37, 0) sleep(0.5) if doorIsOpen==1 and firstTimeOpen == 1: GPIO.output(7, 1) GPIO.output(37, 1) omxp = Popen(['omxplayer' ,Hologram]) sleep(87) GPIO.output(7, 0) GPIO.output(37, 0) firstTimeOpen=0 sleep(0.5) </code></pre>
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: GPIO.output(18, 1) sleep(6) GPIO.output(18, 0) sleep(300) </code></pre> <p>Then, before you start running your main code, use</p> <pre><code>bg_runner = BackgroundRunner() bg_runner.start() </code></pre>
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>import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) GPIO.setup(13, GPIO.IN, GPIO.PUD_UP) GPIO.setup(7,GPIO.OUT) GPIO.setup(37, GPIO.OUT) Hologram = '/home/pi/Hologram/Hologram.mp4' from subprocess import Popen firstTimeOpen=0 while True: doorIsOpen = GPIO.input(13) if doorIsOpen==0 and firstTimeOpen == 0: firstTimeOpen=1 GPIO.output(7, 0) GPIO.output(37, 0) sleep(0.5) if doorIsOpen==1 and firstTimeOpen == 1: GPIO.output(7, 1) GPIO.output(37, 1) omxp = Popen(['omxplayer' ,Hologram]) sleep(87) GPIO.output(7, 0) GPIO.output(37, 0) firstTimeOpen=0 sleep(0.5) </code></pre>
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://docs.python.org/2/library/signal.html</a></p> <p>As an example:</p> <pre><code>import signal, os def handler(signum, frame): print 'Signal handler called with signal', signum handler.counter += 1 if not handler.counter % (300 / 6): GPIO.output(18, 0) else: GPIO.output(18, 1) handler.counter = 0 signal.signal(signal.ITIMER_REAL, handler) signal.setitimer(signal.ITIMER_REAL, 0, 6) </code></pre>
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, parent=None): super().__init__(parent) QtWidgets.QMessageBox.warning(self, "Warnung", error_code_string, QtWidgets.QMessageBox.Ok) id = give_id(self) def give_id(self): self.last_id += 1 return self.last_id def give_reply(self): if last_id == last_reply_id: return self.reply else: return None def set_reply(self, button, id): if button in (QMessageBox.Ok, QMessageBox.Yes): reply = True else: reply = False self.last_reply_id = id return reply </code></pre> <p>And the Test-Script comes with</p> <pre><code>from ErrorHandling import Error Error('Test') </code></pre> <p>If I am using the normal Code (practically the same Code, just wrapped in a class) the message appears and then at the line</p> <pre><code>id = give_id(self) </code></pre> <p>the Code stops without any errormessage from python, just:</p> <pre><code>Process finished with exit code 1 </code></pre> <p>If I use the test-script, there is nothing (No QMessageBox!) than this:</p> <pre><code>Process finished with exit code 1 </code></pre> <p>If I debug the Code, <strong>init</strong>() gets the same Objects and variables, but</p> <pre><code>super().__init__(parent) </code></pre> <p>fails without any message. So where is the mistake, or difference.</p> <p>Here a shortend Version of the Class (it's too long to show all code here), from which the "Error" works nearly fine:</p> <pre><code>from ErrorHandling import Error class MainWindow(QWidget): def __init__(self, parent=None): super().__init__(parent) # set some variables self.create_layout() def create_layout(self): # creates a GUI using QWidgets with some Inputboxes and one button [...] def button_start_clicked(self): Error('Check the input') </code></pre> <p>Here is the old question:</p> <p>I have a problem regarding the setup of QtWidgets.QMessageBox. All Code follows the description.</p> <p>The ErrorHandling-Modul should give a message about an error. If needed it may ask a question too. The function ErrorMsg.errorMessage is called from other Moduls in case of an catched exception. There will be more functions added.</p> <p>If I run the code the following error occurs:</p> <pre><code>Connected to pydev debugger (build 145.1504) Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\pydevd.py", line 1531, in &lt;module&gt; globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\pydevd.py", line 938, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Quellcode/AllgTest.py", line 5, in &lt;module&gt; reply = errm.errorMessage('Test') File "C:/Quellcode\ErrorHandling.py", line 20, in errorMessage msg_box.setIcon(QMessageBox.Warning) TypeError: QMessageBox.setIcon(QMessageBox.Icon): first argument of unbound method must have type 'QMessageBox' Process finished with exit code 1 </code></pre> <p>I tried quite some variations and googled, but I have no idea what the problem is since I found some examples that are using the line QMessageBox.setIcon(QMessageBox.Icon) So where is my mistake?</p> <p>And now the Code:</p> <p>There is the following testscript to test my ErrorMsg-class</p> <pre><code>from ErrorHandling import ErrorMsg errm = ErrorMsg() reply = errm.errorMessage('Test') </code></pre> <p>And here is my ErrorHandling-Modul</p> <pre><code>from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMainWindow class ErrorMsg(QMainWindow): def __init__(self): pass def giveback(self,button): if button in (QMessageBox.Ok, QMessageBox.Yes): reply = True else: reply = False return reply def errorMessage(self, error_msg, buttons='OK'): msg_box = QMessageBox msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle('Warning') if buttons == 'OK': msg_box.setStandardButtons(QMessageBox.Ok) elif buttons == 'YesNo': msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) else: error_msg = 'Unknown Button &gt;' + buttons + '&lt;, use &gt;OK&lt; or &gt;YesNo&lt;' raise ValueError(error_msg) msg_box.setText(error_msg) clicked_button = msg_box.exec() return giveback(clicked_button) </code></pre> <p>Thanks for your help</p> <p>James</p>
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. For example:</p> <pre><code>QMessageBox.warning(None, 'title', 'msg') </code></pre> <p>You also have some control over the butons, see <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qmessagebox.html" rel="nofollow">QMessageBox</a></p>
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 to store this emails, but also giving out the maximum occurring email address.</p> <p>The line to be looked for in the files is this :</p> <blockquote> <p>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008</p> </blockquote> <p>Any time this is found, the email part should be extracted out and then placed in a list before creating the dictionary.</p> <p>I came upon this code sample for printing the maximum key,value in a dict:</p> <pre><code>counts = dict() names = ['csev','owen','csev','zqian','cwen'] for name in names: counts[name] = counts.get(name,0) + 1 maximum = max(counts, key = counts.get) print maximum, counts[maximum] </code></pre> <p>From this sample code I then tried with this program: </p> <pre><code>import re name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) matches = [] addy = [] counts = dict() for lines in handle : # look for specific characters in document text if not lines.startswith("From ") : continue # increment the count variable for each math found lines.split() # append the required lines to the matches list matches.append(lines) # loop through the list to acess each line individually for email in matches : # place values in variable out = email # looking through each line for any email add found found = re.findall(r'[\w\.-]+@[\w\.-]+', out) # loop through the found emails and print them out for i in found : i.split() addy.append(i) for i in addy: counts[i] = counts.get(i, 0) + 1 maximum = max(counts, key=counts.get) print counts print maximum, counts[maximum] </code></pre> <p>Now the issue is that there are only 27 lines starting with from and the highest recurring email in that list should be 'cwen@iupui.edu' which occurs 5 times but when i run the code my output becomes this</p> <pre><code>{'gopal.ramasammycook@gmail.com': 1640, 'louis@media.berkeley.edu': 7207, 'cwen@ iupui.edu': 8888, 'antranig@caret.cam.ac.uk': 1911, 'rjlowe@iupui.edu': 10678, ' gsilver@umich.edu': 10140, 'david.horwitz@uct.ac.za': 4205, 'wagnermr@iupui.edu' : 2500, 'zqian@umich.edu': 16804, 'stephen.marquard@uct.ac.za': 7490, 'ray@media .berkeley.edu': 168} </code></pre> <p>Here's the link to the text file for better understanding : <a href="http://www.pythonlearn.com/code/mbox-short.txt" rel="nofollow">text file</a> </p>
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 addresses to <code>addy</code>. <strong>Afterwards</strong> you have to iterate over this list. I.e.,</p> <pre><code>for lines in handle : # look for specific characters in document text ... for email in matches : ... for i in found : i.split() addy.append(i) for i in addy: counts[i] = counts.get(i, 0) + 1 maximum = max(counts, key=counts.get) </code></pre>
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 to store this emails, but also giving out the maximum occurring email address.</p> <p>The line to be looked for in the files is this :</p> <blockquote> <p>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008</p> </blockquote> <p>Any time this is found, the email part should be extracted out and then placed in a list before creating the dictionary.</p> <p>I came upon this code sample for printing the maximum key,value in a dict:</p> <pre><code>counts = dict() names = ['csev','owen','csev','zqian','cwen'] for name in names: counts[name] = counts.get(name,0) + 1 maximum = max(counts, key = counts.get) print maximum, counts[maximum] </code></pre> <p>From this sample code I then tried with this program: </p> <pre><code>import re name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) matches = [] addy = [] counts = dict() for lines in handle : # look for specific characters in document text if not lines.startswith("From ") : continue # increment the count variable for each math found lines.split() # append the required lines to the matches list matches.append(lines) # loop through the list to acess each line individually for email in matches : # place values in variable out = email # looking through each line for any email add found found = re.findall(r'[\w\.-]+@[\w\.-]+', out) # loop through the found emails and print them out for i in found : i.split() addy.append(i) for i in addy: counts[i] = counts.get(i, 0) + 1 maximum = max(counts, key=counts.get) print counts print maximum, counts[maximum] </code></pre> <p>Now the issue is that there are only 27 lines starting with from and the highest recurring email in that list should be 'cwen@iupui.edu' which occurs 5 times but when i run the code my output becomes this</p> <pre><code>{'gopal.ramasammycook@gmail.com': 1640, 'louis@media.berkeley.edu': 7207, 'cwen@ iupui.edu': 8888, 'antranig@caret.cam.ac.uk': 1911, 'rjlowe@iupui.edu': 10678, ' gsilver@umich.edu': 10140, 'david.horwitz@uct.ac.za': 4205, 'wagnermr@iupui.edu' : 2500, 'zqian@umich.edu': 16804, 'stephen.marquard@uct.ac.za': 7490, 'ray@media .berkeley.edu': 168} </code></pre> <p>Here's the link to the text file for better understanding : <a href="http://www.pythonlearn.com/code/mbox-short.txt" rel="nofollow">text file</a> </p>
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 variable for each math found lines.split() # append the required lines to the matches list matches.append(lines) # loop through the list to acess each line individually for email in matches: </code></pre> <p>So with that change you know are iterating over the matches once.</p> <p>Then since we know that there are only one from in each match we can change the find to:</p> <pre><code>found = re.findall(r'[\w\.-]+@[\w\.-]+', out)[0] </code></pre> <p>To count how many of each we've seen i've changed:</p> <pre><code># loop through the found emails and print them out for i in found : i.split() addy.append(i) for i in addy: counts[i] = counts.get(i, 0) + 1 maximum = max(counts, key=counts.get) </code></pre> <p>To a more readable:</p> <pre><code>if found in counts: counts[found] += 1 else: counts[found] = 1 </code></pre> <p>Then you can get the max out at the end rather than saving it all the time like so:</p> <pre><code>print counts print max(counts, key=lambda x : x[1]) </code></pre> <p>Putting it togeather you get:</p> <pre><code>import re name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) matches = [] addy = [] counts = dict() for lines in handle : # look for specific characters in document text if not lines.startswith("From ") : continue # increment the count variable for each math found lines.split() # append the required lines to the matches list matches.append(lines) # loop through the list to acess each line individually for email in matches: # place values in variable out = email # looking through each line for any email add found found = re.findall(r'[\w\.-]+@[\w\.-]+', out)[0] # loop through the found emails and print them out if found in counts: counts[found] += 1 else: counts[found] = 1 print counts print max(counts, key=lambda x : x[1]) </code></pre> <p>Which returns:</p> <pre><code>{'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3, 'cwen@iupui.edu': 5, 'antranig@caret.cam.ac.uk': 1, 'rjlowe@iupui.edu': 2, 'gsilver@umich.edu': 3, 'david.horwitz@uct.ac.za': 4, 'wagnermr@iupui.edu': 1, 'zqian@umich.edu': 4, 'stephen.marquard@uct.ac.za': 2, 'ray@media.berkeley.edu': 1} cwen@iupui.edu </code></pre>
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 to store this emails, but also giving out the maximum occurring email address.</p> <p>The line to be looked for in the files is this :</p> <blockquote> <p>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008</p> </blockquote> <p>Any time this is found, the email part should be extracted out and then placed in a list before creating the dictionary.</p> <p>I came upon this code sample for printing the maximum key,value in a dict:</p> <pre><code>counts = dict() names = ['csev','owen','csev','zqian','cwen'] for name in names: counts[name] = counts.get(name,0) + 1 maximum = max(counts, key = counts.get) print maximum, counts[maximum] </code></pre> <p>From this sample code I then tried with this program: </p> <pre><code>import re name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) matches = [] addy = [] counts = dict() for lines in handle : # look for specific characters in document text if not lines.startswith("From ") : continue # increment the count variable for each math found lines.split() # append the required lines to the matches list matches.append(lines) # loop through the list to acess each line individually for email in matches : # place values in variable out = email # looking through each line for any email add found found = re.findall(r'[\w\.-]+@[\w\.-]+', out) # loop through the found emails and print them out for i in found : i.split() addy.append(i) for i in addy: counts[i] = counts.get(i, 0) + 1 maximum = max(counts, key=counts.get) print counts print maximum, counts[maximum] </code></pre> <p>Now the issue is that there are only 27 lines starting with from and the highest recurring email in that list should be 'cwen@iupui.edu' which occurs 5 times but when i run the code my output becomes this</p> <pre><code>{'gopal.ramasammycook@gmail.com': 1640, 'louis@media.berkeley.edu': 7207, 'cwen@ iupui.edu': 8888, 'antranig@caret.cam.ac.uk': 1911, 'rjlowe@iupui.edu': 10678, ' gsilver@umich.edu': 10140, 'david.horwitz@uct.ac.za': 4205, 'wagnermr@iupui.edu' : 2500, 'zqian@umich.edu': 16804, 'stephen.marquard@uct.ac.za': 7490, 'ray@media .berkeley.edu': 168} </code></pre> <p>Here's the link to the text file for better understanding : <a href="http://www.pythonlearn.com/code/mbox-short.txt" rel="nofollow">text file</a> </p>
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 : if not lines.startswith("From ") : continue found = re.search(r'[\w\.-]+@[\w\.-]+', lines).group() addy.append(found.split('@')[0]) print collections.Counter(addy).most_common(1) # out: [('cwen', 5)] </code></pre></li> </ol>
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 to store this emails, but also giving out the maximum occurring email address.</p> <p>The line to be looked for in the files is this :</p> <blockquote> <p>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008</p> </blockquote> <p>Any time this is found, the email part should be extracted out and then placed in a list before creating the dictionary.</p> <p>I came upon this code sample for printing the maximum key,value in a dict:</p> <pre><code>counts = dict() names = ['csev','owen','csev','zqian','cwen'] for name in names: counts[name] = counts.get(name,0) + 1 maximum = max(counts, key = counts.get) print maximum, counts[maximum] </code></pre> <p>From this sample code I then tried with this program: </p> <pre><code>import re name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) matches = [] addy = [] counts = dict() for lines in handle : # look for specific characters in document text if not lines.startswith("From ") : continue # increment the count variable for each math found lines.split() # append the required lines to the matches list matches.append(lines) # loop through the list to acess each line individually for email in matches : # place values in variable out = email # looking through each line for any email add found found = re.findall(r'[\w\.-]+@[\w\.-]+', out) # loop through the found emails and print them out for i in found : i.split() addy.append(i) for i in addy: counts[i] = counts.get(i, 0) + 1 maximum = max(counts, key=counts.get) print counts print maximum, counts[maximum] </code></pre> <p>Now the issue is that there are only 27 lines starting with from and the highest recurring email in that list should be 'cwen@iupui.edu' which occurs 5 times but when i run the code my output becomes this</p> <pre><code>{'gopal.ramasammycook@gmail.com': 1640, 'louis@media.berkeley.edu': 7207, 'cwen@ iupui.edu': 8888, 'antranig@caret.cam.ac.uk': 1911, 'rjlowe@iupui.edu': 10678, ' gsilver@umich.edu': 10140, 'david.horwitz@uct.ac.za': 4205, 'wagnermr@iupui.edu' : 2500, 'zqian@umich.edu': 16804, 'stephen.marquard@uct.ac.za': 7490, 'ray@media .berkeley.edu': 168} </code></pre> <p>Here's the link to the text file for better understanding : <a href="http://www.pythonlearn.com/code/mbox-short.txt" rel="nofollow">text file</a> </p>
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) &lt; 1 : name = "mbox-short.txt" handle = open(name) email_matches = [] found_emails = [] final_emails = [] counts = dict() for lines in handle : # look for specific characters in document text if not lines.startswith("From ") : continue # increment the count variable for each math found lines.split() # append the required lines to the matches list email_matches.append(lines) for email in email_matches : out = email found = re.findall(r'[\w\.-]+@[\w\.-]+', out) found_emails.append(found) for item in found_emails : count = item[0] final_emails.append(count) for items in final_emails: counts[items] = counts.get(items,0) + 1 maximum = max(counts, key = lambda x: counts.get(x)) print maximum, counts[maximum] </code></pre> <p>And the output</p> <pre><code>cwen@iupui.edu 5 </code></pre>
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 &gt; -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><code>logging.basicConfig(filename='sample.log',level=logging.DEBUG) </code></pre> <p>again and again. In order to resolve this i declared function which returns logger object as follows:</p> <pre><code>class sample() def set_log(self): l = logging.getLogger(logger_name) l.setLevel(logging.DEBUG) formatter = logging.Formatter(' %(levelname)s : %(message)s') fileHandler = logging.FileHandler("c:/sample.log", mode='w') fileHandler.setFormatter(formatter) streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) l.addHandler(fileHandler) return l def func(self): log = self.set_log() log.info("hsdhkhd") </code></pre> <p>Now i am using set_log() inside func() but what happens is it sometimes it inserts NUll at various locations inside the log but actually null should not get entered. So, why is it that i am getting null inside the log files sometimes?</p>
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 (in configured state) with <code>logging.getLogger()</code>. That's because the <code>logging</code> module uses <em>singletons</em>, global state, to configure all logging operations.</p> <p>The convention is to store a global reference to a logger in your module:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>Here the module name is used to indicate where log messages come from, and this also lets you adjust configuration per module.</p> <p>However, subsequent calls to <code>logging.getLogger(somename)</code> will always return the same singleton logger object (not passing in the name gives you the root <code>Logger</code> in the hierarchy).</p> <p>At any rate, the top-level <code>logging.info()</code> function just delegates to the root logger, it is equivalent to <code>logging.getLogger().info()</code>. It does call <code>logging.basicConfig()</code> <em>if it wasn't already called before</em>.</p> <hr> <p>Your updated sample function will add new <code>FileHandler()</code> and <code>StreamHandler()</code> instance to the singleton <code>logger_name</code> logger object each time <code>self.set_log()</code> is called. That'll lead to undefined results you re-open the file (truncating it each time).</p> <p>Stick to calling <code>basicConfig()</code> <strong>once</strong>, at the start of your program. The rest of your code should only concern themselves with direct <code>logging.getLogger()</code> calls.</p>
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 and it will not be active so it will receive no input.</p> <p>Is there any way to ensure a Python script will be active (the top window), even while using SSH to launch it? Or, is there another way to get user input without using <code>raw_input</code>, and works in the background (without an active window)?</p> <p>Thanks in advance :)</p> <p>PS: If I have to use other languages (like C) then invoke it in Python, this is fine, I will be able to do that.</p>
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([executable, 'window.py'], creationflags=CREATE_NEW_CONSOLE) </code></pre> <p>and <code>window.py</code> is simply a test script that prints some text and waits for a certain amount of time...</p> <pre><code>import time print("Hello M8!") time.sleep(5) </code></pre> <p><code>window.py</code> will be the script that takes the input as that is the one that has the window.</p>
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 models like:</p> <pre><code>class Rectangle(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class Point(models.Model): rectangle = models.ForeignKey(Rectangle, on_delete = models.CASCADE) x1 = models.FloatField() y1 = models.FloatField() def __str__(self): return '{} , {}'.format(self.x1, self.y1, self.x2, self.y2) </code></pre> <p>If I keep 2 models, then writing serializers and class based views to handle the provided data will get a bit complicated. What should I do? Any suggestions?</p>
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 need to query for the points). Then when retrieving the points, just use split to extract the pairs and return that via API.</p>
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 &lt;&lt;&lt; exit &gt; /dev/null 2&gt;&amp;1 </code></pre> <p>It works when I execute it locally with all my shell (sh 4.3, bash, zsh) on arch, it works when I execute it in subprocess.check_call([command], shell=True) (also on my computer) but it doesn't work on the server because /bin/sh is used by check_call and the version installed does not allow redirection like "&lt;&lt;&lt; exit".</p> <p>I get this error : /bin/sh: 1: Syntax error: redirection unexpected</p> <p>I really need the "exit" keyword passed to the process once it is connected to the sftp to automatically close the connection. For that, I need to either find the correct command to pass to the old /bin/sh or tell subprocess to use /bin/bash instead of /bin/sh.</p> <p>Anybody knows how I can fix this ? </p> <p>server 3.16.0-60-generic #80~14.04.1-Ubuntu</p> <p>Thank you very much.</p>
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': u'000031043206'}, {u'index': 3, u'no': 'C', u'met': u'0031043207'}] </code></pre> <p><code>To JSONL</code>:</p> <pre><code>{u'index': 1, u'no': 'A', u'met': u'1043205'} {u'index': 2, u'no': 'B', u'met': u'031043206'} {u'index': 3, u'no': 'C', u'met': u'0031043207'} </code></pre> <p>My current solution is to read the JSON file as a text file and remove the <code>[</code> from the beginning and the <code>]</code> from the end. Thus, creating a valid JSON object on each line, rather than a nested object containing lines.</p> <p>I wonder if there is a more elegant solution? I suspect something could go wrong using string manipulation on the file.</p> <p>The motivation is to read <code>json</code> files into RDD on Spark. See related question - <a href="http://stackoverflow.com/questions/38895057/reading-json-with-apache-spark-corrupt-record/38895521#38895521">Reading JSON with Apache Spark - `corrupt_record`</a></p>
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') as outfile: for entry in JSON_file: json.dump(entry, outfile) outfile.write('\n') </code></pre> <p>The default configuration for the <code>json</code> module is to output JSON without newlines embedded.</p> <p>Assuming your <code>A</code>, <code>B</code> and <code>C</code> names are really strings, that would produce:</p> <pre><code>{"index": 1, "met": "1043205", "no": "A"} {"index": 2, "met": "000031043206", "no": "B"} {"index": 3, "met": "0031043207", "no": "C"} </code></pre> <p>If you started with a JSON document containing a list of entries, just parse that document first with <code>json.load()</code>/<code>json.loads()</code>.</p>
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,vk.com,vk.com,None,None,33.0,1 2,838271,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos,2015-12-31 09:17:32,34,vk.com,vk.com,None,None,54.0,1 3,322026,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos&amp;z=photo143297356_397216312%2Ffeed1_143297356_1451504298,2015-12-31 09:18:06,4,vk.com,vk.com,None,None,34.0,1 4,838275,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos,2015-12-31 09:18:10,4,vk.com,vk.com,None,None,4.0,1 5,322028,7602962fb83ac2e2a0cb44158ca88464,vk.com/feed?section=comments,2015-12-29 09:18:14,8,vk.com,vk.com,None,None,4.0,1 6,322029,7602962fb83ac2e2a0cb44158ca88464,megarand.ru/contest/121070,2015-12-30 09:18:22,16,megarand.ru,megarand.ru,None,None,8.0,1 7,1870917,7602962fb83ac2e2a0cb44158ca88464,vk.com/feed?section=comments,2015-12-31 09:18:38,6,vk.com,vk.com,None,None,16.0,1 </code></pre> <p>I need to print dirrerence between first and last date to every <code>ID</code>. How can I do it? I tried to use <code>df.groupby('ID')['used_at'].diff().dt.seconds</code> but it print difference between every 2 strings</p>
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="nofollow"><code>last</code></a>:</p> <pre><code>g = df.groupby('ID')['used_at'] print (g.first() - g.last()) ID 0120bc30e78ba5582617a9f3d6dfd8ca -1 days +23:57:55 7602962fb83ac2e2a0cb44158ca88464 -3 days +23:59:36 Name: used_at, dtype: timedelta64[ns] </code></pre> <p>Or apply <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a>:</p> <pre><code>print (df.groupby('ID')['used_at'].apply(lambda g: g.iloc[0] - g.iloc[-1])) ID 0120bc30e78ba5582617a9f3d6dfd8ca -1 days +23:57:55 7602962fb83ac2e2a0cb44158ca88464 -3 days +23:59:36 Name: used_at, dtype: timedelta64[ns] </code></pre> <p>With converting <code>timedelta</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.seconds.html" rel="nofollow"><code>seconds</code></a>:</p> <pre><code>g = df.groupby('ID')['used_at'] print ((g.first() - g.last()).dt.seconds) ID 0120bc30e78ba5582617a9f3d6dfd8ca 86275 7602962fb83ac2e2a0cb44158ca88464 86376 Name: used_at, dtype: int64 print (df.groupby('ID')['used_at'].apply(lambda g: g.iloc[0] - g.iloc[-1]).dt.seconds) ID 0120bc30e78ba5582617a9f3d6dfd8ca 86275 7602962fb83ac2e2a0cb44158ca88464 86376 Name: used_at, dtype: int64 </code></pre> <p>Thank you <code>juanpa.arrivillaga</code> for <a href="http://stackoverflow.com/questions/38915186/pandas-use-groupby-to-count-difference-between-dates/38915411?noredirect=1#comment65188500_38915411">comment</a>:</p> <p>If datetimes are sorted, you can use:</p> <pre><code>df.groupby('ID').used_at.min() - df.groupby('ID').used_at.max() </code></pre> <p><strong>Timings</strong>:</p> <pre><code>In [216]: %timeit (a(df)) The slowest run took 4.30 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 1.78 ms per loop In [217]: %timeit (b(df)) 1000 loops, best of 3: 1.8 ms per loop In [218]: %timeit (df.groupby('ID')['used_at'].apply(lambda g: g.iloc[0] - g.iloc[-1]).dt.seconds) 1000 loops, best of 3: 1.53 ms per loop In [219]: %timeit (df.groupby('ID').agg(['first','last']).apply( lambda r: r['used_at','first'] - r['used_at','last'], axis=1).dt.seconds) 100 loops, best of 3: 14.4 ms per loop </code></pre> <p>Code for timings:</p> <pre><code>df = pd.concat([df]*1000).reset_index(drop=True) def a(df): g = df.groupby('ID')['used_at'] return ((g.first() - g.last()).dt.seconds) def b(df): g = df.groupby('ID')['used_at'] return ((g.min() - g.max()).dt.seconds) </code></pre>
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,vk.com,vk.com,None,None,33.0,1 2,838271,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos,2015-12-31 09:17:32,34,vk.com,vk.com,None,None,54.0,1 3,322026,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos&amp;z=photo143297356_397216312%2Ffeed1_143297356_1451504298,2015-12-31 09:18:06,4,vk.com,vk.com,None,None,34.0,1 4,838275,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos,2015-12-31 09:18:10,4,vk.com,vk.com,None,None,4.0,1 5,322028,7602962fb83ac2e2a0cb44158ca88464,vk.com/feed?section=comments,2015-12-29 09:18:14,8,vk.com,vk.com,None,None,4.0,1 6,322029,7602962fb83ac2e2a0cb44158ca88464,megarand.ru/contest/121070,2015-12-30 09:18:22,16,megarand.ru,megarand.ru,None,None,8.0,1 7,1870917,7602962fb83ac2e2a0cb44158ca88464,vk.com/feed?section=comments,2015-12-31 09:18:38,6,vk.com,vk.com,None,None,16.0,1 </code></pre> <p>I need to print dirrerence between first and last date to every <code>ID</code>. How can I do it? I tried to use <code>df.groupby('ID')['used_at'].diff().dt.seconds</code> but it print difference between every 2 strings</p>
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 and java environment .i have installed both and i tried to run meTypeset.py and its say error message like no modules named lxml (for your quicker reference pls refer image1)..hence tried to install module in python like ths "pip3 install lxml" its show like "FILE "" syntax error (for your quicker reference pls refer image 2).</p> <p>I have following questions now 1. how to install metypeset properly 2. what are all prerequisite for installing metypeset.. 3.what version of python is required to use metypeset.. 4.suggestion for converting docs to xml 5.suggestions about JATS xml editor 6.suggestion about validation in xml conversions(high priority)</p> <p>Thanks in advance </p> <p><a href="http://i.stack.imgur.com/ZQvXu.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZQvXu.png" alt="image1"></a> <a href="http://i.stack.imgur.com/YvCYi.png" rel="nofollow"><img src="http://i.stack.imgur.com/YvCYi.png" alt="enter image description here"></a></p>
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 MyGUI import main_window_GUI from Modules import Module.py class MainWindow(QMainWindow, main_window_GUI.Ui_main_window): def __init__(self): QMainWindow.__init__(self) main_window_GUI.Ui_main_window.__init__(self) self.setupUI(self) sub_win = QMdiSubWindow() sub_win.setWidget(Module.moduleWindow()) self.mdi.addSubWindow(sub_win) # this part reports error saying: # 'PyQt5.QtCore.pyqtSignal' object has no attribute 'connect' Module.moduleWindow.my_signal.connect(self.do_something) def do_something(self): pass </code></pre> <p><strong>Module.py</strong></p> <pre><code>from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from MyGUI import module_window_GUI class moduleWindow(QMainWindow, module_window_GUI.Ui_module_window): my_signal = pyqtSignal() def __init__(self): QMainWindow.__init__(self) module_window_GUI.Ui_module_window.__init__(self) self.setupUI(self) # the rest is not important # what is important is th following function def closeEvent(self, event): # when the user closes this subwindow signal needs to # be emitted so that the MainWindow class knows that # it's been closed. self.my_signal.emit() event.accept() </code></pre> <p>Any kind of help is more than welcome. Thanks in advance.</p>
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_window_GUI.Ui_main_window): def __init__(self): QMainWindow.__init__(self) main_window_GUI.Ui_main_window.__init__(self) self.setupUI(self) sub_win = QMdiSubWindow() module_window = Module.moduleWindow() sub_win.setWidget(module_window) self.mdi.addSubWindow(sub_win) module_window.my_signal.connect(self.do_something) @pyqtSlot() def do_something(self): pass </code></pre> <p>I would also recommend to decorate the do_something method with <code>pyqtSlot</code> as reported in the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html" rel="nofollow">documentation</a></p>
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 cell manually in a *.xlsx file, the xlrd can also get the value of the formula.</p> <p>It seems that I cannot read the value of formula cell only when I write a forumla to *.xlsx and then read it in the same program.</p> <p>Python: 3.4.3 xlrd: 1.0.0 xlsxwriter: 0.9.3</p> <pre><code>import xlrd import xlsxwriter name = 'abc.xlsx' sheet_name = 'sheet1' # write a formula in 'D1' as '=A1+C1' out_book = xlsxwriter.Workbook(name, {'im_memory': True}) out_sheet = out_book.add_worksheet(sheet_name) out_sheet.write('A1', 1) out_sheet.write('C1', 2) out_sheet.write_formula(0, 3, '=A1+C1') out_book.close() #After closing excel, read the cell tmp = xlrd.open_workbook(name) sheet = tmp.sheet_by_name(sheet_name) #show '2.0' print (sheet.cell_value(0, 2)) #show '0.0' print (sheet.cell_value(0, 3)) </code></pre> <p>The result is : 2.0 0.0</p> <p>But I expect it to be: 2.0 3.0</p> <p>How can I solve it? Thanks a lot!</p>
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 like</p> <pre><code>ColA ColB ColC ColD B A A C NaN B A A C D D A NaN A A B </code></pre> <p>And I'm trying to fill these <code>NaN</code> using <code>ffill</code> , so they are populated by the last known value.</p> <p><code>fill = df.fillna(method='ffill', inplace = True)</code></p> <p>This doesn't make a difference, also tried <code>Na</code> instead of <code>NaN</code></p>
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['ColA'].replace(['A'], np.nan) print (sample) ColA ColB ColC ColD 0 B A A C 1 NaN B A A 2 C D D A 3 NaN A A B </code></pre> <p>If use <code>inplace = True</code>, it return <code>None</code>, but inplace fill values:</p> <pre><code>sample.fillna(method='ffill', inplace = True) #sample.ffill(inplace = True) print (sample) ColA ColB ColC ColD 0 B A A C 1 B B A A 2 C D D A 3 C A A B </code></pre>
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", line 40, in &lt;module&gt; print parse_shop_meta() File "/Users/kr/PycharmProjects/education_py/vape_map.py", line 35, in parse_shop_meta VALUES (%s, %s, %s, %s)""",(shop_title, shop_address, shop_phone, shop_site, shop_desc)) File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 210, in execute query = query % args TypeError: not all arguments converted during string formatting </code></pre> <p>My code: </p> <pre><code># -- coding: utf-8 -- import requests from lxml.html import fromstring import csv import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="***", db="vape_map", charset='utf8') def get_shop_urls(): i = 1 all_shop_urls = [] while i &lt; 2: url = requests.get("http://vapemap.ru/shop/?city=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&amp;page={}".format(i)) page_html = fromstring(url.content) shop_urls = page_html.xpath('//h3[@class="title"]/a/@href') all_shop_urls += shop_urls i +=1 return all_shop_urls def parse_shop_meta(): shops_meta = [] csvfile = open('vape_shops.csv', 'wb') writer = csv.writer(csvfile, quotechar='|', quoting=csv.QUOTE_ALL) cursor = db.cursor() for shop in get_shop_urls(): url = requests.get("http://vapemap.ru{}".format(shop), 'utf-8') page_html = fromstring(url.content) shop_title = page_html.xpath('//h1[@class="title"]/text()') shop_address = page_html.xpath('//div[@class="address"]/text()') shop_phone = page_html.xpath('//div[@class="phone"]/a/text()') shop_site = page_html.xpath('//div[@class="site"]/a/text()') shop_desc = page_html.xpath('//div[@class="shop-desc"]/text()') sql = """INSERT INTO vape_shops(title, address, phone, site, description) VALUES (%s, %s, %s, %s)""",(shop_title, shop_address, shop_phone, shop_site, shop_desc) cursor.execute(sql, (shop_title[0], shop_address[0], shop_phone[0], shop_site[0], shop_desc[0])) db.commit() db.close() return shops_meta print parse_shop_meta() </code></pre>
-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/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored">More details</a> and <a href="http://mysql.rjweb.org/doc.php/charcoll#python" rel="nofollow">Python-specifics</a></p>
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"; instead it had to have matched on "sixty six", but the capture returns ('six', 'six').</p> <p>What is happening here and how can I return ('sixty', 'six')?</p>
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' &gt;&gt;&gt; if re.match(r'the (?:(?:sixty|six)[ -]+)+items', s): ... re.findall(r"\b(sixty|six)[ -]+(?=.*\bitems\b)", s) ... ['sixty', 'six'] </code></pre> <hr> <p>Your question has this code:</p> <pre><code>&gt;&gt;&gt; r = "the ((sixty|six)[ -]+)+items" &gt;&gt;&gt; s = "the sixty six items" &gt;&gt;&gt; re.findall(r, s) </code></pre> <p>Which is returning <code>[('six ', 'six')]</code> because of quantifier used after your group i.e. <code>((sixty|six)[ -]+)+</code></p> <p><code>findall</code> returns 2 values that are </p> <ol> <li><code>captured group #1</code> is <code>"six "</code> (note a space here due to <code>[ -]+</code> in your first group) </li> <li><code>captured group #2</code> is <code>"six"</code> (inner group i.e. <code>(sixty|six)</code>)</li> </ol>
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"; instead it had to have matched on "sixty six", but the capture returns ('six', 'six').</p> <p>What is happening here and how can I return ('sixty', 'six')?</p>
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"; instead it had to have matched on "sixty six", but the capture returns ('six', 'six').</p> <p>What is happening here and how can I return ('sixty', 'six')?</p>
3
2016-08-12T10:16:04Z
38,915,780
<p>Use <code>\b</code> assertion: Hope this helps.</p> <pre><code>&gt;&gt;&gt; s = "the sixty six items" &gt;&gt;&gt; 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>Without <code>\b</code></p> <pre><code>&gt;&gt;&gt; s = "the sixty sixteen six items" &gt;&gt;&gt; print(re.findall(r'(?is)(sixty|six)',s)) ['sixty', 'six', 'six'] </code></pre> <p>With <code>\b</code> (advantage)</p> <pre><code>&gt;&gt;&gt; s = "the sixty sixteen six items" &gt;&gt;&gt; print(re.findall(r'(?is)(\bsixty\b|\bsix\b)',s)) ['sixty', 'six'] </code></pre>
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"; instead it had to have matched on "sixty six", but the capture returns ('six', 'six').</p> <p>What is happening here and how can I return ('sixty', 'six')?</p>
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> (without a trailing space) matches the inner group.</p> <p>You can do what you want using two un-nested capture groups inside some non-capture groups, which use the <code>(?:...)</code> syntax. </p> <pre><code>import re r = "the (?:(?:(sixty)|(six))[ -]+)+items" s = "the sixty six items" m = re.search(r, s) if m: print(m.groups()) </code></pre> <p><strong>output</strong></p> <pre><code>('sixty', 'six') </code></pre> <p>This returns a tuple of two items because we have two capture groups in the pattern.</p> <p>Here's a longer demo.</p> <pre><code>import re pat = re.compile("the (?:(?:(sixty)|(six))[ -]+)+items") data = ( "the items", "the six items", "the six six items", "the sixty items", "the six sixty items", "the sixty six items", "the sixty-six items", "the six sixty sixty items", ) for s in data: m = pat.search(s) print('{!r} -&gt; {}'.format(s, m.groups() if m else None)) </code></pre> <p><strong>output</strong></p> <pre><code>'the items' -&gt; None 'the six items' -&gt; (None, 'six') 'the six six items' -&gt; (None, 'six') 'the sixty items' -&gt; ('sixty', None) 'the six sixty items' -&gt; ('sixty', 'six') 'the sixty six items' -&gt; ('sixty', 'six') 'the sixty-six items' -&gt; ('sixty', 'six') 'the six sixty sixty items' -&gt; ('sixty', 'six') </code></pre>
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=st.cpu_cores, cpu_mhz=st.cpu_mhz, ram_mb=st.ram_mb FROM servers WHERE server.provider_id IN (%s) ''' % ','.join([ ... ])) </code></pre> <p>Is it possible to replace <code>%</code> operator with <code>in_</code> method here? Or I should re-implement this query using <code>session.query</code>?</p>
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 the <a href="https://www.python.org/dev/peps/pep-0249/#paramstyle" rel="nofollow"><code>paramstyle</code></a> of the DB driver you are using.</p> <p>Otherwise, the easiest way is to translate this into a <code>session.query</code> or <code>update().where()</code> construct.</p>
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 10.230.3.2) if state is >= 0. Likewise, i want to read all the neighbors where corresponding state column is >=0.</p> <p>Please suggest me how can I do this? Any help is appreciated. Thanks in advance!</p>
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 formatted it with spaces this will work</p> <pre><code>with open("filename.txt", "r") as f: for row in f: data = row.split(" ") if data[4]&gt;=0: print data[0] </code></pre>
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 10.230.3.2) if state is >= 0. Likewise, i want to read all the neighbors where corresponding state column is >=0.</p> <p>Please suggest me how can I do this? Any help is appreciated. Thanks in advance!</p>
0
2016-08-12T10:29:24Z
38,916,031
<p>You can use pandas.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; 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)] &gt;&gt;&gt; df = pd.DataFrame(data = data_set, columns=['Neighbour', 'InQ', 'OutQ', 'Up/Down', 'State']) &gt;&gt;&gt; df Neighbour InQ OutQ Up/Down State 0 10.230.3.2 0 0 33w5d 1177 1 10.230.4.2 0 0 33w5d 1175 2 125.62.173.253 0 0 8w3d 2637 3 125.62.173.254 0 0 1w3d 2657 4 127.0.0.1 0 0 1w0d -1 &gt;&gt;&gt; df[df.State &gt;=0 ]['Neighbour'] 0 10.230.3.2 1 10.230.4.2 2 125.62.173.253 3 125.62.173.254 Name: Neighbour, dtype: object &gt;&gt;&gt; df[df.State &lt;0 ]['Neighbour'] 4 127.0.0.1 Name: Neighbour, dtype: object </code></pre> <p><code>pandas</code> is available via <code>pip</code>.</p>
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 10.230.3.2) if state is >= 0. Likewise, i want to read all the neighbors where corresponding state column is >=0.</p> <p>Please suggest me how can I do this? Any help is appreciated. Thanks in advance!</p>
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>&gt;&gt;&gt; for i in range(1, len(t)): ... temp = t[i].split() ... if int(temp[4]) &gt;= 0: ... print temp[0] ... 10.230.3.2 10.230.4.2 125.62.173.253 125.62.173.254 </code></pre> <p><strong>If you wish to write it to a .txt file</strong></p> <pre><code>t = tuple(open('source_filename', 'r')) tfile = open('destination_filename', 'a') for i in range(1, len(t)): temp = t[i].split() if int(temp[4]) &gt;= 0: tfile.write('%s\n' % temp[0]) tfile.close() </code></pre>
0
2016-08-12T11:14:00Z
[ "python" ]