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 |
---|---|---|---|---|---|---|---|---|---|
Extract a number from a string, after a certain character
| 39,481,788 |
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p>
<pre><code>s = "abcdef,12"
v = "gbhjjj,699"
</code></pre>
<p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p>
<p>I tried <code>s[-2:]</code> and <code>v[-3:]</code> which works, but how do I make it work without knowing the number of digits?</p>
| 1 |
2016-09-14T02:53:01Z
| 39,481,834 |
<p>Using <code>split</code> is superior because it is very clear and fast:</p>
<pre><code>>>> s = "abcdef,12"
>>> s.split(',')[1]
'12'
</code></pre>
<p>Another way is with <code>index</code> or <code>find</code>:</p>
<pre><code>>>> s = "abcdef,12"
>>> s[s.find(',')+1:]
'12'
</code></pre>
<p>And another way with <code>re</code>:</p>
<pre><code>>>> import re
>>> s = "abcdef,12"
>>> re.search(r',(.*)', s).group(1)
'12'
</code></pre>
<p>And with <code>csv</code> (and <code>io</code> so I don't have to write a file to the hard drive):</p>
<pre><code>>>> import csv
>>> import io
>>> s = "abcdef,12"
>>> r = csv.reader(i)
>>> for line in r:
... print(line[1])
...
12
</code></pre>
<p>I'm sure there are other ways to accomplish this task. This is just a small sample.</p>
| 1 |
2016-09-14T02:58:38Z
|
[
"python"
] |
Extract a number from a string, after a certain character
| 39,481,788 |
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p>
<pre><code>s = "abcdef,12"
v = "gbhjjj,699"
</code></pre>
<p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p>
<p>I tried <code>s[-2:]</code> and <code>v[-3:]</code> which works, but how do I make it work without knowing the number of digits?</p>
| 1 |
2016-09-14T02:53:01Z
| 39,481,897 |
<p>Maybe you can try with a <a href="https://docs.python.org/3.5/library/re.html" rel="nofollow">regular expression</a></p>
<pre><code>import re
input_strings = ["abcdef,12", "gbhjjj,699"]
matcher = re.compile("\d+$")
for input_string in input_strings:
is_matched = matcher.search(input_string)
if is_matched:
print(is_matched.group())
</code></pre>
| 1 |
2016-09-14T03:05:55Z
|
[
"python"
] |
Extract a number from a string, after a certain character
| 39,481,788 |
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p>
<pre><code>s = "abcdef,12"
v = "gbhjjj,699"
</code></pre>
<p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p>
<p>I tried <code>s[-2:]</code> and <code>v[-3:]</code> which works, but how do I make it work without knowing the number of digits?</p>
| 1 |
2016-09-14T02:53:01Z
| 39,482,263 |
<p>I like <code>.partition()</code> for this kind of thing:</p>
<pre><code>for text in ('gbhjjj,699', 'abcdef,12'):
x, y, z = text.partition(',')
number = int(z)
print(number)
</code></pre>
<p>Unlike <code>.split()</code> it will always return three values.</p>
<p>I'll sometimes do this to emphasize that I don't care about certain values:</p>
<pre><code>_, _, z = text.partition(',')
</code></pre>
| 1 |
2016-09-14T03:55:35Z
|
[
"python"
] |
Extract a number from a string, after a certain character
| 39,481,788 |
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p>
<pre><code>s = "abcdef,12"
v = "gbhjjj,699"
</code></pre>
<p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p>
<p>I tried <code>s[-2:]</code> and <code>v[-3:]</code> which works, but how do I make it work without knowing the number of digits?</p>
| 1 |
2016-09-14T02:53:01Z
| 39,484,260 |
<p>Assuming:</p>
<ul>
<li>You <em>know</em> there is a comma in the string, so you don't have to search the entire string to find out if there is or not.</li>
<li>You know the pattern is <code>'many_not_digits,few_digits'</code> so there is a big imbalance between the size of the left/right parts either side of the comma.</li>
<li>You can get to the end of the string without walking it, which <a href="http://stackoverflow.com/questions/38043461/time-complexity-of-python-string-index-access">you can in Python because string indexing is constant time</a></li>
</ul>
<p>Then you could start from the end and walk backwards looking for the comma, which would be less overall work <em>for your examples</em> than walking from the left looking for the comma.</p>
<p>Doing work in Python code is way slower than using Python engine code written in C, right? So would it really be faster?</p>
<ol>
<li>Make a string "aaaaa....,12"</li>
<li>use the <code>timeit</code> module to compare each approach - split, or right-walk. </li>
<li>Timeit does a million runs of some code.</li>
<li>Extend the length of "aaaaaaaaaaaaaaaa....,12" to make it extreme.</li>
</ol>
<p>How do they compare?</p>
<ul>
<li>String split: 1400 "a"'s run a million times took 1 second.</li>
<li>String split: 4000 "a"'s run a million times took 2 seconds.</li>
<li>Right walk: 1400 "a"'s run a million times took 0.4 seconds. </li>
<li>Right walk: 999,999 "a"'s run a million times took ... 0.4 seconds.</li>
</ul>
<p>!</p>
<pre><code>from timeit import timeit
_split = """num = x.split(',')[-1]"""
_rwalk = """
i=-1
while x[i] != ',':
i-=1
num = x[i+1:]
"""
print(timeit(_split, setup='x="a"*1400 + ",12"'))
print(timeit(_rwalk, setup='x="a"*999999 + ",12"'))
</code></pre>
<p>e.g.</p>
<pre><code>1.0063155219977489 # "aaa...,12" for 1400 chars, string split
0.4027107510046335 # "aaa...,12" for 999999 chars, rwalked. Faster.
</code></pre>
<p><a href="https://repl.it/D9PX" rel="nofollow">Try it online at repl.it</a></p>
<p>I don't think this is algorithmically better than O(n), but with the constraints of the assumptions I made you have more knowledge than str.split() has, and can leverage that to skip walking most of the string and beat it in practise - and the longer the text part, and shorter the digit part, the more you benefit. </p>
| 1 |
2016-09-14T06:59:20Z
|
[
"python"
] |
Extract a number from a string, after a certain character
| 39,481,788 |
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p>
<pre><code>s = "abcdef,12"
v = "gbhjjj,699"
</code></pre>
<p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p>
<p>I tried <code>s[-2:]</code> and <code>v[-3:]</code> which works, but how do I make it work without knowing the number of digits?</p>
| 1 |
2016-09-14T02:53:01Z
| 39,485,269 |
<p>If you are worried about using split from the left because of lots of unwanted characters in the beginning, use rsplit.</p>
<pre><code>s = "abcdef,12"
s.rsplit(",", 1)[-1]
</code></pre>
<p>Here, rsplit will start splitting the string from the right and the optional second argument we used will stop rsplit to proceed further than the first comma operator it encountered. </p>
<pre><code>(eg):
s = "abc,def,12"
s.rsplit(",", 1)[-1]
# Outputs 12
s = "abcdef12"
s.rsplit(",", 1)[-1]
# Outputs abcdef12
</code></pre>
<p>This will be lot simpler and cleaner to get the string of numbers in the end rather than doing anything manually.</p>
<p>Not to mention, it will be lot easier if we wish to check whether we get only numbers with this. Even if it is a list of strings.</p>
<pre><code>def get_numbers(string_list, skip_on_error=True):
numbers_list = []
for input_string in string_list:
the_number = input_string.rsplit(",", 1)[-1]
if the_number.isdigit():
numbers_list.append(the_number)
elif skip_on_error:
numbers_list.append("")
else:
raise Exception("Wrong Format occurred: %s" % (input_string))
return numbers_list
</code></pre>
<p>And if you are looking for even further optimization and sure that most(if not all) strings will be of the correct format, you can even use try except if you are going to go with an integer list instead of string list. Like this:</p>
<pre><code># Instead of the if.. elif.. else construct
try:
numbers_list.append(int(the_number))
except ValueError:
if skip_on_error:
numbers_list.append(0)
else:
raise Exception("Wrong Format occurred: %s" % (input_string))
</code></pre>
<p>But always remember the <a href="https://www.python.org/dev/peps/pep-0020/#id3" rel="nofollow" title="Zen of Python">Zen Of Python</a> and using split/rsplit follows these:</p>
<ol>
<li>Beautiful is better than ugly</li>
<li>Explicit is better than implicit</li>
<li>Simple is better than complex</li>
<li>Readability counts</li>
<li>There should be one-- and preferably only one --obvious way to do it</li>
</ol>
<p>And also remember Donald Knuth:</p>
<blockquote>
<p>We should forget about small efficiencies, say about 97% of the time: <strong>premature optimization is the root of all evil</strong>. Yet we should not pass up our opportunities in that critical 3%</p>
</blockquote>
| 2 |
2016-09-14T07:57:04Z
|
[
"python"
] |
Django Model to Associative Array
| 39,481,796 |
<p>Is there any way to convert a django models to an associative array using a loop for HttpResponse.</p>
<pre><code>class Guest(models.Model):
fname = models.CharField(max_length=200)
mname = models.CharField(max_length=200, default="", blank=True, null=True)
lname = models.CharField(max_length=200)
gender = models.CharField(max_length=20, choices=gender_choices, default="")
birth_date = models.DateField()
address = models.TextField()
phone = models.CharField(max_length=20)
mobile = models.CharField(max_length=20, default="", blank=True, null=True)
fax = models.CharField(max_length=20, default="", blank=True, null=True)
email = models.CharField(max_length=200)
id_type = models.CharField(max_length=200, default="", blank=True, null=True)
id_number = models.CharField(max_length=200, default="", blank=True, null=True)
</code></pre>
<p>my expected result was like this</p>
<pre><code>{
"fname" : "sample",
"mname" : "sample",
"lname" : "sample",
...
}
</code></pre>
| 0 |
2016-09-14T02:53:56Z
| 39,483,007 |
<pre><code>guest = Guest.objects.get(pk=1)
print guest.__dict__
</code></pre>
| 0 |
2016-09-14T05:25:18Z
|
[
"python",
"django"
] |
Django Model to Associative Array
| 39,481,796 |
<p>Is there any way to convert a django models to an associative array using a loop for HttpResponse.</p>
<pre><code>class Guest(models.Model):
fname = models.CharField(max_length=200)
mname = models.CharField(max_length=200, default="", blank=True, null=True)
lname = models.CharField(max_length=200)
gender = models.CharField(max_length=20, choices=gender_choices, default="")
birth_date = models.DateField()
address = models.TextField()
phone = models.CharField(max_length=20)
mobile = models.CharField(max_length=20, default="", blank=True, null=True)
fax = models.CharField(max_length=20, default="", blank=True, null=True)
email = models.CharField(max_length=200)
id_type = models.CharField(max_length=200, default="", blank=True, null=True)
id_number = models.CharField(max_length=200, default="", blank=True, null=True)
</code></pre>
<p>my expected result was like this</p>
<pre><code>{
"fname" : "sample",
"mname" : "sample",
"lname" : "sample",
...
}
</code></pre>
| 0 |
2016-09-14T02:53:56Z
| 39,483,048 |
<pre><code>SomeModel.objects.filter(id=pk).values()[0]
</code></pre>
<p>You will get</p>
<pre><code>{
"fname" : "sample",
"mname" : "sample",
"lname" : "sample",
...
}
</code></pre>
<p>I discourage the using of <code>__dict__</code> because you will get extra fields that you don't care about.</p>
<p>Or you can create <code>to_dict</code> method in your models if you want to something more customisable in order to add calculated fields.</p>
<pre><code>class Guest(models.Model):
#fields....
def get_dict(self):
return {
"fname" : self.fname,
"mname" : self.mname,
"lname" : self.lname,
}
</code></pre>
<p>use it as it: <code>instance.get_dict()</code></p>
| 1 |
2016-09-14T05:28:50Z
|
[
"python",
"django"
] |
How to find characters ahead of word using re?
| 39,481,838 |
<p>So I would like to obtain the number that is ahead of the word pies. How would I do this?</p>
<pre><code>import re
string='latin 1,394 pies'
m = re.search('', string)
print(m.group(0))
#want 1,394
</code></pre>
| -3 |
2016-09-14T02:59:02Z
| 39,481,883 |
<pre><code>In [137]: import re
...: string='latin 1,394 pies'
...: m = re.search(r'([\d,]+) pies', string)
...: print(m.group(1))
...:
1,394
([\d,]+) pies
</code></pre>
<p><img src="https://www.debuggex.com/i/gXGzdV9i3-VyuTBM.png" alt="Regular expression visualization"></p>
<p><a href="https://regex101.com/r/dT8gE8/1" rel="nofollow">Regex101 Explanation</a></p>
| 0 |
2016-09-14T03:03:48Z
|
[
"python",
"regex"
] |
Python: Replacing character error with read in file
| 39,481,870 |
<p>Goal: I just want to take the comma away as that is the only character that will screw up my (course required) file parsing for bayesian analysis (i.e word,2,4) instead of say (i.e. word,,2,4)</p>
<p>So I'm currently trying to read in an email in the form of a text file from the Enron public corpus online and building a bayesian spam filter.</p>
<p>I've noticed that reading in some of the files are raising errors when trying to manipulate the strings that are present. I am fully aware that some of theses files contain viruses so the encoding of some of the characters might not be valid. However, I'm trying to simply replace a comma within a string and I'm getting the following error:</p>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc1 in position 1169: ordinal not in range(128)</p>
<p>I have tried everything that this forum has to offer and i've searched everywhere for a solution such as:</p>
<pre><code>with open(file+file_path_stings[i],'r') as filehandle:
words = str(filehandle.read())
words = words.replace(',','')
words = words.split()
</code></pre>
<p>I've also tried many regex attempts... this is one of the versions:</p>
<pre><code>with open(file+file_path_stings[i],'r') as filehandle:
words = str(filehandle.read())
words = re.sub(',','',words)
words = words.split()
</code></pre>
<p>Now, I can simply just regex a version that only lets A-Za-z through but I'm noticing that spam accuracy is heavily being affected by the fact that a lot of the spam files have such special characters.</p>
<p>Any suggestion would be most appreciated. Thanks.</p>
<p>-Robert</p>
| 1 |
2016-09-14T03:02:54Z
| 39,486,810 |
<p>If you just want to remove the extra comma and as you said nothing is working out you can use the simple split and join (assuming comma is the only delimiter here)</p>
<pre><code>','.join([s for s in 'word,,2,4'.split(',') if s])
</code></pre>
| 2 |
2016-09-14T09:21:09Z
|
[
"python",
"spam",
"bayesian"
] |
Python: Replacing character error with read in file
| 39,481,870 |
<p>Goal: I just want to take the comma away as that is the only character that will screw up my (course required) file parsing for bayesian analysis (i.e word,2,4) instead of say (i.e. word,,2,4)</p>
<p>So I'm currently trying to read in an email in the form of a text file from the Enron public corpus online and building a bayesian spam filter.</p>
<p>I've noticed that reading in some of the files are raising errors when trying to manipulate the strings that are present. I am fully aware that some of theses files contain viruses so the encoding of some of the characters might not be valid. However, I'm trying to simply replace a comma within a string and I'm getting the following error:</p>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc1 in position 1169: ordinal not in range(128)</p>
<p>I have tried everything that this forum has to offer and i've searched everywhere for a solution such as:</p>
<pre><code>with open(file+file_path_stings[i],'r') as filehandle:
words = str(filehandle.read())
words = words.replace(',','')
words = words.split()
</code></pre>
<p>I've also tried many regex attempts... this is one of the versions:</p>
<pre><code>with open(file+file_path_stings[i],'r') as filehandle:
words = str(filehandle.read())
words = re.sub(',','',words)
words = words.split()
</code></pre>
<p>Now, I can simply just regex a version that only lets A-Za-z through but I'm noticing that spam accuracy is heavily being affected by the fact that a lot of the spam files have such special characters.</p>
<p>Any suggestion would be most appreciated. Thanks.</p>
<p>-Robert</p>
| 1 |
2016-09-14T03:02:54Z
| 39,537,047 |
<p>So I ended up using another implementation that I found useful as well. It turns out, for some reason, python retains any prior information it had for any previous strings that were originally present. So i've learned its always a good idea to just re-assign it to a different(new) variable as follows:</p>
<pre><code>with open(file+file_path_stings[i],'r') as filehandle:
words = str(filehandle.read()).split()
new_array = []
for word in words:
new_array.append(word.replace(',','').lower())
return new_array
</code></pre>
<p>Its a little more expensive as far as storing and assigning data to a whole other variable. However, I've noticed its a lot safer in terms of your string not getting casted to a unicode string. The original problem was this output</p>
<pre><code> print words
[u'hello,',u'what?',u'is',u'going',u'on?']
</code></pre>
<p>The comma in 'hello' would not get replaced. With the code above you're guaranteed that the comma will be stripped from each word and not casted into a unicode string</p>
<pre><code>print new_array
['hello','what?',u'is',u'going',u'on?']
</code></pre>
<p>As far as performance of the code goes, I'm still training massive files at a decent speed. So it should effect you that much. </p>
<p>Hope this helps!</p>
<p>-Robert</p>
| 0 |
2016-09-16T17:23:33Z
|
[
"python",
"spam",
"bayesian"
] |
In Ansible is there a way to use with_items and host variables at the same time?
| 39,481,925 |
<p>So I have 3 hosts I want to run a playbook on. Each host needs 3 files (all with the same names).</p>
<p>the files are going to be</p>
<ul>
<li>lacpbond.100</li>
<li>lacpbond.200</li>
<li>lacpbond.300</li>
</ul>
<p>Each file has a unique IP address that goes into it based on the vars/ file.</p>
<p>The task looks like this-></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>- name: configure subinterface bonds
template: src="ifcfg-lacpbondsub.j2" dest=/etc/sysconfig/network-scripts/ifcfg-lacpbond.{{item.vlan}}
with_items:
- { vlan: "100" }
- { vlan: "200" }
- { vlan: "300" }
tags:
- bonding
</code></pre>
</div>
</div>
</p>
<p>So the vars looks like this-></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> server01:
loopbacks:
ipv4: "10.0.0.100"
SVIS:
100:
ipv4: "192.168.0.1"
prefix: "28"
200:
ipv4: "192.168.1.1"
prefix: "28"
300:
ipv4: "192.168.2.1"
prefix: "28"</code></pre>
</div>
</div>
</p>
<p>Now here comes the problem. I am not sure how to use with_items and vars in the same time so I can use with_items to defer which variable to use.... this would greatly simplify the complexity of the playbook</p>
<p>here is the template file-></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{% set host = interfaces[ansible_hostname] -%}
{% set VLAN = item.vlan -%}
DEVICE=lacpbond.{{item.vlan}}
IPADDR={{host.SVIS.{{item.vlan}}.ipv4}}
ONBOOT=yes
BOOTPROTO=none
VLAN=yes</code></pre>
</div>
</div>
</p>
<p>So the above works obviously if I don't use the {{}} within another {{}}. But you can see what I am trying. I can use item.X by itself fine, and I can use anything from vars/ fine. But I don't know how to do something like
host.SVIS[VLAN].ipv4....</p>
<p>is this possible? Otherwise I will need 3 tasks with 3 templates.... and if i need more files this is not as scalable....</p>
| 1 |
2016-09-14T03:10:07Z
| 39,482,320 |
<p>Your question is a bit unclear (in part because of the issue I pointed out in my comment), but if I understand what you're asking, you can just do something like:</p>
<pre><code>IPADDR={{host.SVIS[item.vlan].ipv4}}
</code></pre>
<p>See the <a href="http://jinja.pocoo.org/docs/dev/templates/#variables" rel="nofollow">Variables</a> section of the Jinja documentation, which says:</p>
<blockquote>
<p>The following lines do the same thing:</p>
<pre><code>{{ foo.bar }}
{{ foo['bar'] }}
</code></pre>
</blockquote>
<p><strong>Update</strong></p>
<p>You are getting that error ("AnsibleUndefinedVariable: 'dict object' has no attribute u'100'") because the keys in your dictionary are integers, but the values of the <code>vlan</code> keys in your with_items loop are strings. That is, <code>host.SVIS[100]</code> exists, but <code>hosts.SVIS['100']</code> does not exist.</p>
<p>Given this playbook:</p>
<pre><code>- hosts: localhost
vars:
interfaces:
server01:
loopbacks:
ipv4: "10.0.0.100"
SVIS:
100:
ipv4: "192.168.0.1"
prefix: "28"
200:
ipv4: "192.168.1.1"
prefix: "28"
300:
ipv4: "192.168.2.1"
prefix: "28"
ansible_hostname: server01
tasks:
- name: configure subinterface bonds
template:
src: "ifcfg-lacpbondsub.j2"
dest: ./ifcfg-lacpbond.{{item.vlan}}
with_items:
- { vlan: 100 }
- { vlan: 200 }
- { vlan: 300 }
tags:
- bonding
</code></pre>
<p>And this template:</p>
<pre><code>{% set host = interfaces[ansible_hostname] -%}
DEVICE=lacpbond.{{item.vlan}}
IPADDR={{host.SVIS[item.vlan].ipv4}}
ONBOOT=yes
BOOTPROTO=none
VLAN=yes
Raw
</code></pre>
<p>I get three files:</p>
<pre><code>$ ls ifcfg-lacpbond.*
ifcfg-lacpbond.100 ifcfg-lacpbond.200 ifcfg-lacpbond.300
</code></pre>
<p>The content of each looks something like:</p>
<pre><code>DEVICE=lacpbond.100
IPADDR=192.168.0.1
ONBOOT=yes
BOOTPROTO=none
VLAN=yes
</code></pre>
| 1 |
2016-09-14T04:04:42Z
|
[
"python",
"ansible",
"ansible-playbook"
] |
Fixing Negative Assertion for end of string
| 39,482,021 |
<p>I am trying to accept a capture group only if the pattern matches and there is not a specific word before the end of the group. I've tried a # of approaches and none seem to work, clearly I'm not getting the concept:</p>
<p><a href="https://regex101.com/r/iP2xY0/3" rel="nofollow">https://regex101.com/r/iP2xY0/3</a>
<a href="https://regex101.com/r/iP2xY0/4" rel="nofollow">https://regex101.com/r/iP2xY0/4</a></p>
<p>Regardless of what I do my capture group captures something and my goal is if the reject word exists in the middle of the pattern to return no match.</p>
<pre><code>RC:\*.*?(?P<Capture>(Bob|David|Ted|Alice))(?!Reject).*
</code></pre>
<ul>
<li>RC:* Hi Bob Smith<\person></li>
<li>RC:* Hi David Jones *Notes Bla bla<\person></li>
<li>RC:* Hi Ted Warren *Rejected <\person></li>
</ul>
<p>Capture Namegrouop is supposed to return:</p>
<ul>
<li>Bob</li>
<li>David</li>
<li>''</li>
</ul>
<p>So "Reject" says if the NameGroup Capture is found followed by anything ending in <code><</code> capture it, if between the NameGroup and the < the word <code>Reject</code> appears do not.</p>
| 0 |
2016-09-14T03:22:36Z
| 39,494,466 |
<p>I would recommend putting your negative look-ahead at the beginning of your pattern. This first checks if your reject word exists in your string and only if it isn't there does it try to match the rest of the string:</p>
<p><code>(?!.*Rejected.*)RC:\*.*?(?P<Capture>(Bob|David|Ted|Alice)).*</code></p>
<p><a href="https://regex101.com/r/iP2xY0/6" rel="nofollow">https://regex101.com/r/iP2xY0/6</a></p>
| 0 |
2016-09-14T15:34:46Z
|
[
"python",
"regex-negation",
"regex-lookarounds"
] |
How to pass named arguments into python function from hy
| 39,482,091 |
<p>I am trying to use a python function with named arguments from hy.</p>
<p>I'm using the NLTK library as well.</p>
<p>In python I would do something like this</p>
<pre><code>from nltk.corpus import brown
brown.words(categories='news')
</code></pre>
<p>to get a list of words in the 'news' category.</p>
<p>I would like to do the same thing in hy. The only way I have figured out to do that is by finding out what order to pass the arguments in, and set all the ones I don't want to <code>None</code></p>
<pre><code>(import [nltk.corpus [brown]])
(.words brown None "news")
</code></pre>
<p>Is there another way to do this in hy that makes my intentions more clear? Imagine trying doing this with a function that has a lot of optional named arguments.</p>
| 0 |
2016-09-14T03:30:49Z
| 39,482,128 |
<p>Found the answer in the docs. </p>
<p><a href="http://docs.hylang.org/en/latest/language/api.html#defn" rel="nofollow">defn documentation</a></p>
<p>It would be done like this</p>
<pre><code>(.words brown :categories "news")
</code></pre>
| 0 |
2016-09-14T03:37:39Z
|
[
"python",
"hy"
] |
Changing image on button click
| 39,482,273 |
<p>this is my first python programming code. I am trying to change the image on click of a button. I have 2 buttons, <kbd>Start Conversation</kbd> & <kbd>Stop Conversation</kbd>. </p>
<p>When the form loads there is no image. when <em>Start</em> button is clicked, ABC image will be displayed. When the <em>Stop</em> button is clicked, xyz image should be displayed. </p>
<p>The problem I am facing is, when I click Start, the corresponding image appears, but when I click Stop, the new image appears but the previous image doesn't disappear. Both the images are displayed one after other</p>
<p>My code is below</p>
<pre><code>root = Tk()
prompt = StringVar()
root.title("AVATAR")
label = Label(root, fg="dark green")
label.pack()
frame = Frame(root,background='red')
frame.pack()
</code></pre>
<h1>Function definition</h1>
<pre><code>def Image1():
image = Image.open("C:\Python27\Agent.gif")
photo = ImageTk.PhotoImage(image)
canvas = Canvas(height=200,width=200)
canvas.image = photo # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=photo)
canvas.pack()
def Image2():
image = Image.open("C:\Python27\Hydrangeas.gif")
photo = ImageTk.PhotoImage(image)
canvas = Canvas(height=200,width=200)
canvas.image = photo # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=photo)
canvas.pack()
#Invoking through button
TextWindow = Label(frame,anchor = tk.NW, justify = tk.LEFT, bg= 'white', fg = 'blue', textvariable = prompt, width = 75, height=20)
TextWindow.pack(side = TOP)
conversationbutton = Button(frame, text='Start Conversation',width=25,fg="green",command = Image1)
conversationbutton.pack(side = RIGHT)
stopbutton = Button(frame, text='Stop',width=25,fg="red",command = Image2)
stopbutton.pack(side = RIGHT)
root.mainloop()
</code></pre>
| 1 |
2016-09-14T03:56:58Z
| 39,483,467 |
<p>The most important issue is that you do not clear your canvas before the new image is created. Start your (button) functions with:</p>
<pre><code>canvas.delete("all")
</code></pre>
<p>However, the same goes for your canvas; you keep creating it. Better split the creation of the canvas and setting the image:</p>
<pre><code>from Tkinter import *
root = Tk()
prompt = StringVar()
root.title("AVATAR")
label = Label(root, fg="dark green")
label.pack()
frame = Frame(root,background='red')
frame.pack()
# Function definition
# first create the canvas
canvas = Canvas(height=200,width=200)
canvas.pack()
def Image1():
canvas.delete("all")
image1 = PhotoImage(file = "C:\Python27\Agent.gif")
canvas.create_image(0,0,anchor='nw',image=image1)
canvas.image = image1
def Image2():
canvas.delete("all")
image1 = PhotoImage(file = "C:\Python27\Hydrangeas.gif")
canvas.create_image(0,0,anchor='nw',image=image1)
canvas.image = image1
#Invoking through button
TextWindow = Label(frame,anchor = NW, justify = LEFT, bg= 'white', fg = 'blue', textvariable = prompt, width = 75, height=20)
TextWindow.pack(side = TOP)
conversationbutton = Button(frame, text='Start Conversation',width=25,fg="green",command = Image1)
conversationbutton.pack(side = RIGHT)
stopbutton = Button(frame, text='Stop',width=25,fg="red",command = Image2)
stopbutton.pack(side = RIGHT)
root.mainloop()
</code></pre>
<p>This also prevents the somewhat strange extension of the window on button push.
To make the code fit for <code>python3</code>, replace <code>from Tkinter import*</code> by <code>from tkinter import*</code></p>
| 1 |
2016-09-14T06:04:28Z
|
[
"python",
"python-2.7",
"tkinter"
] |
Unable to scrape the content though it appears in the inspect element
| 39,482,313 |
<p>I have been trying to scrape the user reviews from the cnet page. The pros and cons of the user reviews information. (<a href="http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/" rel="nofollow">http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/</a>)</p>
<p>I have used selenium to dynamically load the page but still the html source and inspect element source are different. I also have used requests to get the source code. I am not sure about the difference in between the two.</p>
<p>Can you please suggest me a work around? </p>
<p>The code used for selenium:</p>
<pre><code>driver.get("http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/")
driver.wait = WebDriverWait(driver, 2)
soup= BeautifulSoup(driver.page_source,"html.parser")
</code></pre>
<p>requests code:</p>
<pre><code>try:
r = requests.get("http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/", timeout = 10)
except Exception,e:
print("borken")
data = r.text
soup = BeautifulSoup(data)
</code></pre>
<p>PS: I gave a search in stack overflow and google, but I couldn't find a working answer. It would also be helpful if anyone can give me a link. </p>
| -3 |
2016-09-14T04:03:02Z
| 39,487,260 |
<p>That page has quite a bit of JavaScript so I think using selenium is going to be your best bet to load all of the content. In your current code you are only waiting 2 seconds which may not be enough time. I would recommend using an explicit wait that returns when the comment section elements have completely loaded.</p>
<p>There is a good explanation and example here: <a href="http://selenium-python.readthedocs.io/waits.html" rel="nofollow">http://selenium-python.readthedocs.io/waits.html</a> </p>
<p>It looks like each of the comment blocks have the form</p>
<pre><code><article class= "fyre-comment-article fyre-comment-source-0"..../>
</code></pre>
<p>so you could start by modifying the example from the above link like this: (I don't have the ability to actually run this code on my current machine so just use it as an example of a way to modify the code from the link. Read here for more ways to locate elements: <a href="http://selenium-python.readthedocs.io/locating-elements.html" rel="nofollow">http://selenium-python.readthedocs.io/locating-elements.html</a>)</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = <yourdriver>
driver.get("http://www.cnet.com/products/samsung-galaxy-s7/user-reviews/")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.XPATH,
'//article[class="fyre-comment-article fyre-comment-source-0"]'))
)
finally:
driver.quit()
</code></pre>
| 0 |
2016-09-14T09:41:47Z
|
[
"python",
"selenium",
"web-scraping"
] |
model IntegerField() to django-template with ordinal
| 39,482,332 |
<p>I have a model with IntegerField()</p>
<pre><code>class Room(models.Model):
type = models.CharField(max_length=50)
floor = models.IntegerField()
</code></pre>
<p>And i would like it to display in a template with ordinal suffix.</p>
<pre><code>{% for room in rooms %}
<div>
<p> {{ room.type }}</p>
<p> {{ room.floor }} </p>
</div>
{% endfor %}
</code></pre>
<p>I would like the floor output like this.</p>
<p><code>1st, 2nd, 3rd, 4th... 10th.. 12th.. 13th.. 15th...</code></p>
| -1 |
2016-09-14T04:06:39Z
| 39,482,578 |
<p>You can use <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/humanize/#ordinal" rel="nofollow">ordinal</a> function from django.contrib.humanize package</p>
| 1 |
2016-09-14T04:39:43Z
|
[
"python",
"django"
] |
How to completely restart a python program
| 39,482,411 |
<p>For a project, i used a Raspberry Pi (running dexter industries modified raspbian) and Brick Pi to run lego motors. I wroted a program with python and it works great and all, but i need the entire program to run repeatedly if the pressure sensor was not pressed. I tried calling the function sensorValue() (which detects whether the pressure sensor was being pushed) under while True:. But once i did that stuff became weird. It would just continue to repeat indefinitely and even if i pushed the sensor, the recurring 0 would turn to 1 but it wouldn't call the next function i need it to run. </p>
<p>Please help, this is my first time actually using python to write anything and i am a massive beginner so any help is GREATLY APPRECIATED. </p>
<p>Thanks Again</p>
<pre><code>from BrickPi import *
BrickPiSetup()
BrickPi.MotorEnable[PORT_A] = 1
BrickPi.SensorType[PORT_4] = TYPE_SENSOR_TOUCH
BrickPiSetupSensors()
def sensorValue():
result = BrickPiUpdateValues()
if not result :
print BrickPi.Sensor[PORT_4]
time.sleep(.01)
if BrickPi.Sensor[PORT_4] == 0:
def programBody():
print ("program rest/pause")
BrickPi.MotorSpeed[PORT_A] = 0
BrickPiUpdateValues()
time.sleep(3)
print ("reminder/alarm = 200 value")
BrickPi.MotorSpeed[PORT_A] = 200
ot = time.time()
while(time.time() - ot <3):
BrickPiUpdateValues()
time.sleep(.01)
print ("reminder/alarm = 125 value")
BrickPi.MotorSpeed[PORT_A] = 125
ot = time.time()
while(time.time() - ot <3):
BrickPiUpdateValues()
time.sleep(.01)
sensorValue() #I would put while True: here but...
if BrickPi.Sensor[PORT_4]:
print "program successfully initiatied"
programBody()
</code></pre>
| 0 |
2016-09-14T04:17:41Z
| 39,482,687 |
<p>try this </p>
<pre><code>import BrickPi,time
BrickPiSetup()
BrickPi.MotorEnable[PORT_A] = 1
BrickPi.SensorType[PORT_4] = TYPE_SENSOR_TOUCH
BrickPiSetupSensors()
z = 0
def mainprogram():
print ("running")
while x == 1:
z = z + 1
print ("the plate has been pressed for %s seconds" % z)
time.sleep(1)
while True:
time.sleep(.1)
if BrickPi.Sensor[PORT_4]:
print "program successfully initiatied"
mainprogram()
</code></pre>
| 1 |
2016-09-14T04:51:17Z
|
[
"python",
"raspberry-pi",
"lego"
] |
py.test : How do I access a test_function's parameter from within an @pytest.fixture
| 39,482,428 |
<p>My objective is to gain access to a test_function's "args" from within a pytest.fixture that lives in conftest.py, in order to pytest.skip() if a certain condition is met.</p>
<p>Here is the conftest.py code:</p>
<pre class="lang-py prettyprint-override"><code># conftest.py
import pytest
def pytest_generate_tests(metafunc):
if 'param1' in metafunc.fixturenames:
metafunc.parametrize("param1", [0, 1, 'a', 3, 4])
@pytest.fixture(autouse=True, scope="function")
def skip_if(request):
# I want to do something like this
# (but obviously request.node.param1 is not a real attribute):
if request.node.param1 == 'a':
xfail()
</code></pre>
<p>And the test.py code:</p>
<pre class="lang-py prettyprint-override"><code># test.py
def test_isdig(param1):
assert isinstance(param1, int)
</code></pre>
<p>Does anyone happen to know if the request object can smoehow have access to the the current param1 value, so that my autouse skip_if() fixture can skip it on a certain conditions? I know that I can put the pytest.skip() call inside test_isdig() but I am trying to do it from within the fixture somehow. Any advice/guidance is very much appreciated!</p>
| 0 |
2016-09-14T04:20:28Z
| 39,482,692 |
<p>Adding the parameter to the fixture as well as the test function seems to work.</p>
<p>Test code:</p>
<pre><code>import pytest
def pytest_generate_tests(metafunc):
if 'param1' in metafunc.fixturenames:
metafunc.parametrize("param1", [0, 1, 'a', 3, 4])
@pytest.fixture(autouse=True, scope="function")
def skip_if(param1):
if param1 == 'a':
pytest.xfail()
def test_isint(param1):
assert isinstance(param1, int)
</code></pre>
<p>Results:</p>
<pre><code>============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-3.0.0, py-1.4.31, pluggy-0.3.1
rootdir: D:\Development\Hacks\StackOverflow\39482428 - Accessing test function p
arameters from pytest fixture, inifile:
collected 5 items
test_print_request_contents.py ..x..
===================== 4 passed, 1 xfailed in 0.10 seconds =====================
</code></pre>
<p>Note however that this <code>skip_if</code> fixture would be run for all tests, regardless of whether they had the <code>param1</code> parameter, so that could be problematic. It may be better, in that instance, to explicitly include the fixture in the relevant tests, or to even wrap the parameter in the fixture, so that only the fixture has <code>param1</code> as a parameter, which it then returns, and the test instead has the fixture as its parameter.</p>
| 1 |
2016-09-14T04:51:54Z
|
[
"python",
"automated-tests",
"py.test"
] |
Why does pyinstaller generated cx_oracle application work on fresh CentOS machine but not on one with Oracle client installed?
| 39,482,504 |
<p>I wrote a python application that uses <code>cx_Oracle</code> and then generates a pyinstaller bundle (folder/single executable). I should note it is on 64 bit linux. I have a custom spec file that includes the Oracle client libraries so everything that is needed is in the bundle. </p>
<p>When I run the bundled executable on a freshly installed CentOS 7.1 VM, (no Oracle software installed), the program connects to the database successfully and runs without error. However, when I install the bundled executable on another system that contains RHEL 7.2, and I try to run it, I get</p>
<blockquote>
<p>Unable to acquire Oracle environment handle. </p>
</blockquote>
<p>My understanding is this is due to an Oracle client installation that has some sort of conflict. I tried unsetting ORACLE_HOME on the machine giving me errors. It's almost as though the program is looking for the Oracle client libraries in a location other than in the location where I bundled the client files. </p>
<p>It seems like it should work on both machines or neither machine. I guess I'm not clear on how the Python application/cx_Oracle finds the Oracle client libraries. Again, it seems to have found them fine on a machine with a fresh operating system installation. Any ideas on why this is happening?</p>
| 0 |
2016-09-14T04:30:16Z
| 39,503,038 |
<p>One thing that you may be running into is the fact that if you used the instant client RPMs when you built cx_Oracle an RPATH would have been burned into the shared library. You can examine its contents and change it using the chrpath command. You can use the special path $ORIGIN in the modified RPATH to specify a path relative to the shared library.</p>
<p>If an RPATH isn't the culprit, then you'll want to examine the output from the ldd command and see where it is looking and then adjust things to make it behave itself!</p>
| 1 |
2016-09-15T04:18:09Z
|
[
"python",
"pyinstaller",
"cx-oracle"
] |
Converting a Text file to JSON format using Python
| 39,482,614 |
<p>I am not new to programming but not good at python data structures. I would like to know a way to convert a text file into JSON format using python since I heard using python the task is much easier with a module called <code>import.json</code>.</p>
<p>The file looks like </p>
<pre><code> Source Target Value
B cells Streptococcus pneumoniae 226
B cells Candida albicans 136
B cells Mycoplasma 120
</code></pre>
<p>For the first line "B cells" is the source, target is the "Streptococcus pneumoniae" and value is "226". I just started with the code, but couldnot finish it. Please help</p>
<pre><code>import json
prot2_names = {}
tmpfil = open("file.txt", "r");
for lin in tmpfil.readlines():
flds = lin.rstrip().split("\t")
prot2_names[flds[0]] = "\"" + flds[1] + "\""
print prot2_names+"\t",
tmpfil.close()
</code></pre>
<p>Wants the output to be like</p>
<pre><code>{
"nodes": [
{
"name": "B cells"
},
{
"name": "Streptococcus pneumoniae"
},
{
"name": "Candida albicans"
},
{
"name": "Mycoplasma"
},
{
"links": [
{
"source": 0,
"target": 1,
"value": "226"
},
{
"source": 0,
"target": 2,
"value": "136"
},
{
"source": 0,
"target": 3,
"value": "120"
}
]
}
</code></pre>
| 0 |
2016-09-14T04:44:10Z
| 39,482,884 |
<p>You can read it as a <code>csv</code> file and convert it into <code>json</code>. But, be careful with spaces as you've used it as separator, the values with spaces should be carefully handled. Otherwise, if possible make the separator <code>,</code> instead of <code>space</code>.</p>
<p>the working code for what you're trying,</p>
<pre><code>import csv
import json
with open('file.txt', 'rb') as csvfile:
filereader = csv.reader(csvfile, delimiter=' ')
i = 0
header = []
out_data = []
for row in filereader:
row = [elem for elem in row if elem]
if i == 0:
i += 1
header = row
else:
row[0:2] = [row[0]+" "+row[1]]
_dict = {}
for elem, header_elem in zip(row, header):
_dict[header_elem] = elem
out_data.append(_dict)
print json.dumps(out_data)
</code></pre>
<p>output,</p>
<pre><code>[
{
"Source":"B cells",
"Target":"Streptococcus",
"Value":"pneumoniae"
},
{
"Source":"B cells",
"Target":"Candida",
"Value":"albicans"
},
{
"Source":"B cells",
"Target":"Mycoplasma",
"Value":"120"
},
{
"Source":"B cells",
"Target":"Neisseria",
"Value":"111"
},
{
"Source":"B cells",
"Target":"Pseudomonas",
"Value":"aeruginosa"
}
]
</code></pre>
<p>UPDATE: Just noticed your updated question with <code>json</code> sample that you require. Hope, you could build it with the above example I've written.</p>
| 0 |
2016-09-14T05:12:35Z
|
[
"python",
"json"
] |
Python way to convert argument list to string
| 39,482,695 |
<p>I've inherited some Python code that constructs a string from the string arguments passed into <code>__init__</code>:</p>
<pre><code>self.full_tag = prefix + number + point + suffix
</code></pre>
<p>Maybe I'm just over-thinking it but is this the best way to concatenate the arguments? I know it's possible to do something like:</p>
<pre><code>self.full_tag = "".join([prefix, number, point, suffix])
</code></pre>
<p>Or just using string format function:</p>
<pre><code>self.full_tag = '{}{}{}{}'.format(prefix, number, point, suffix)
</code></pre>
<p>What is the Python way of doing this?</p>
| 2 |
2016-09-14T04:52:07Z
| 39,483,084 |
<p>The documentation recommends <code>join</code> for better performance over <code>+</code>:</p>
<blockquote>
<p><a href="https://docs.python.org/2/library/stdtypes.html#index-22" rel="nofollow">6. ... For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.</a></p>
</blockquote>
<p>If performance is not too important, it's more of a matter of taste.</p>
<p>Personally, I find <code>"".join</code> cleaner and more readable than all of those braces in the <code>format</code> version.</p>
| 2 |
2016-09-14T05:32:20Z
|
[
"python",
"python-2.7"
] |
Python way to convert argument list to string
| 39,482,695 |
<p>I've inherited some Python code that constructs a string from the string arguments passed into <code>__init__</code>:</p>
<pre><code>self.full_tag = prefix + number + point + suffix
</code></pre>
<p>Maybe I'm just over-thinking it but is this the best way to concatenate the arguments? I know it's possible to do something like:</p>
<pre><code>self.full_tag = "".join([prefix, number, point, suffix])
</code></pre>
<p>Or just using string format function:</p>
<pre><code>self.full_tag = '{}{}{}{}'.format(prefix, number, point, suffix)
</code></pre>
<p>What is the Python way of doing this?</p>
| 2 |
2016-09-14T04:52:07Z
| 39,483,180 |
<p><em>Pythonic</em> way is to follow <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">The Zen of Python</a>, which has several things to say about this case:</p>
<ul>
<li><p>Beautiful is better than ugly.</p></li>
<li><p>Simple is better than complex.</p></li>
<li><p>Readability counts.</p></li>
</ul>
<p>Add to that the famous quote by DonaldKnuth:</p>
<blockquote>
<p>We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil.</p>
</blockquote>
<p>With those in mind, the best of your choices is:</p>
<pre><code>self.full_tag = prefix + number + point + suffix
</code></pre>
<p>Although, if number is really a number and point point is really a point, then this is more explicit:</p>
<pre><code>self.full_tag = "%s%d.%s" % (prefix, number, suffix)
</code></pre>
<ul>
<li>Explicit is better than implicit.</li>
</ul>
| 3 |
2016-09-14T05:41:45Z
|
[
"python",
"python-2.7"
] |
How to print DataFrame on single line
| 39,482,722 |
<p>With:</p>
<pre><code>import pandas as pd
df = pd.read_csv('pima-data.csv')
print df.head(2)
</code></pre>
<p>the print is automatically formatted across multiple lines:</p>
<pre><code> num_preg glucose_conc diastolic_bp thickness insulin bmi diab_pred \
0 6 148 72 35 0 33.6 0.627
1 1 85 66 29 0 26.6 0.351
age skin diabetes
0 50 1.3790 True
1 31 1.1426 False
</code></pre>
<p>I wonder if there is a way to avoid the multi-line formatting. I would rather have it printed in a single line like so:</p>
<pre><code> num_preg glucose_conc diastolic_bp thickness insulin bmi diab_pred age skin diabetes
0 6 148 72 35 0 33.6 0.627 50 1.3790 True
1 1 85 66 29 0 26.6 0.351 31 1.1426 False
</code></pre>
| 1 |
2016-09-14T04:54:27Z
| 39,482,727 |
<p>You need set:</p>
<pre><code>pd.set_option('expand_frame_repr', False)
</code></pre>
<p><code>option_context</code> context manager has been exposed through the top-level API, allowing you to execute code with given option values. Option values are restored automatically when you exit the with block:</p>
<pre><code>#temporaly set expand_frame_repr
with pd.option_context('expand_frame_repr', False):
print (df)
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/options.html#frequently-used-options" rel="nofollow">Pandas documentation</a>.</p>
| 3 |
2016-09-14T04:55:13Z
|
[
"python",
"pandas",
"dataframe"
] |
parse table using beautifulsoup in python
| 39,482,760 |
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p>
<p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228004","2016-09-10","player persistently infringes the laws of the game","C" (new line)</p>
<p>2nd row) "AVIATORS SOCCER CLUB","G12DB - AVIATORS-G12DB-REYNGOUDT","Saskia Reyes","Player 224463","2016-09-11","player/sub guilty of unsporting behavior"," C" (new line)</p>
<pre><code><div style="overflow:auto; border:1px #cccccc solid;">
<table cellspacing="0" cellpadding="3" align="left" border="0" width="100%">
<tbody>
<tr class="tblHeading">
<td colspan="7">AMERICANS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11EB - AMERICANS-B11EB-WARZALA</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cameron Coya </td>
<td width="19%" class="tdUnderLine">
Rozel, Max
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=228004" target="_blank">228004</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 02:15 PM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">AVIATORS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">G12DB - AVIATORS-G12DB-REYNGOUDT</td>
</tr>
<tr bgcolor="#FBFBFB">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Saskia Reyes </td>
<td width="19%" class="tdUnderLine">
HollaenderNardelli, Eric
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=224463" target="_blank">224463</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/11/16 06:45 PM
</td>
<td width="30%" class="tdUnderLine"> player/sub guilty of unsporting behavior </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">BERGENFIELD SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11CW - BERGENFIELD-B11CW-NARVAEZ</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Christian Latorre </td>
<td width="19%" class="tdUnderLine">
Coyle, Kevin
</td>
<td width="06%" class="tdUnderLine">
09-10-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=226294" target="_blank">226294</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 11:00 AM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
</code></pre>
<p>I tried with following code. </p>
<pre><code>import requests
from bs4 import BeautifulSoup
import re
try:
import urllib.request as urllib2
except ImportError:
import urllib2
url = r"G:\Freelancer\NC Soccer\Northern Counties Soccer Association ©.html"
page = open(url, encoding="utf8")
soup = BeautifulSoup(page.read(),"html.parser")
#tableList = soup.findAll("table")
for tr in soup.find_all("tr"):
for td in tr.find_all("td"):
print(td.text.strip())
</code></pre>
<p>but it is obvious that it will return text form all td and I will not able to identify particular column name or will not able to determine start of new record. I want to know </p>
<p>1) how to identify each column(because class name is same) and there are headings as well (I will appreciate if you provide code for that) </p>
<p>2) how to identify new record in such structure</p>
| 1 |
2016-09-14T04:58:16Z
| 39,482,791 |
<p>If the data is really structured like a table, there's a good chance you can read it into pandas directly with pd.read_table(). Note that it accepts urls in the filepath_or_buffer argument.
<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html</a></p>
| 1 |
2016-09-14T05:02:18Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
parse table using beautifulsoup in python
| 39,482,760 |
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p>
<p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228004","2016-09-10","player persistently infringes the laws of the game","C" (new line)</p>
<p>2nd row) "AVIATORS SOCCER CLUB","G12DB - AVIATORS-G12DB-REYNGOUDT","Saskia Reyes","Player 224463","2016-09-11","player/sub guilty of unsporting behavior"," C" (new line)</p>
<pre><code><div style="overflow:auto; border:1px #cccccc solid;">
<table cellspacing="0" cellpadding="3" align="left" border="0" width="100%">
<tbody>
<tr class="tblHeading">
<td colspan="7">AMERICANS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11EB - AMERICANS-B11EB-WARZALA</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cameron Coya </td>
<td width="19%" class="tdUnderLine">
Rozel, Max
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=228004" target="_blank">228004</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 02:15 PM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">AVIATORS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">G12DB - AVIATORS-G12DB-REYNGOUDT</td>
</tr>
<tr bgcolor="#FBFBFB">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Saskia Reyes </td>
<td width="19%" class="tdUnderLine">
HollaenderNardelli, Eric
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=224463" target="_blank">224463</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/11/16 06:45 PM
</td>
<td width="30%" class="tdUnderLine"> player/sub guilty of unsporting behavior </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">BERGENFIELD SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11CW - BERGENFIELD-B11CW-NARVAEZ</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Christian Latorre </td>
<td width="19%" class="tdUnderLine">
Coyle, Kevin
</td>
<td width="06%" class="tdUnderLine">
09-10-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=226294" target="_blank">226294</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 11:00 AM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
</code></pre>
<p>I tried with following code. </p>
<pre><code>import requests
from bs4 import BeautifulSoup
import re
try:
import urllib.request as urllib2
except ImportError:
import urllib2
url = r"G:\Freelancer\NC Soccer\Northern Counties Soccer Association ©.html"
page = open(url, encoding="utf8")
soup = BeautifulSoup(page.read(),"html.parser")
#tableList = soup.findAll("table")
for tr in soup.find_all("tr"):
for td in tr.find_all("td"):
print(td.text.strip())
</code></pre>
<p>but it is obvious that it will return text form all td and I will not able to identify particular column name or will not able to determine start of new record. I want to know </p>
<p>1) how to identify each column(because class name is same) and there are headings as well (I will appreciate if you provide code for that) </p>
<p>2) how to identify new record in such structure</p>
| 1 |
2016-09-14T04:58:16Z
| 39,483,767 |
<p>There seems to be a pattern. After every 7 tr(s), there is a new line.
So, what you can do is keep a counter starting from 1, when it touches 7, append a new line and restart it to 0.</p>
<pre><code>counter = 1
for tr in find_all("tr"):
for td in tr.find_all("td"):
# place code
counter = counter + 1
if counter == 7:
print "\n"
counter = 1
</code></pre>
| 0 |
2016-09-14T06:26:40Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
parse table using beautifulsoup in python
| 39,482,760 |
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p>
<p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228004","2016-09-10","player persistently infringes the laws of the game","C" (new line)</p>
<p>2nd row) "AVIATORS SOCCER CLUB","G12DB - AVIATORS-G12DB-REYNGOUDT","Saskia Reyes","Player 224463","2016-09-11","player/sub guilty of unsporting behavior"," C" (new line)</p>
<pre><code><div style="overflow:auto; border:1px #cccccc solid;">
<table cellspacing="0" cellpadding="3" align="left" border="0" width="100%">
<tbody>
<tr class="tblHeading">
<td colspan="7">AMERICANS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11EB - AMERICANS-B11EB-WARZALA</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cameron Coya </td>
<td width="19%" class="tdUnderLine">
Rozel, Max
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=228004" target="_blank">228004</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 02:15 PM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">AVIATORS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">G12DB - AVIATORS-G12DB-REYNGOUDT</td>
</tr>
<tr bgcolor="#FBFBFB">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Saskia Reyes </td>
<td width="19%" class="tdUnderLine">
HollaenderNardelli, Eric
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=224463" target="_blank">224463</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/11/16 06:45 PM
</td>
<td width="30%" class="tdUnderLine"> player/sub guilty of unsporting behavior </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">BERGENFIELD SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11CW - BERGENFIELD-B11CW-NARVAEZ</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Christian Latorre </td>
<td width="19%" class="tdUnderLine">
Coyle, Kevin
</td>
<td width="06%" class="tdUnderLine">
09-10-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=226294" target="_blank">226294</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 11:00 AM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
</code></pre>
<p>I tried with following code. </p>
<pre><code>import requests
from bs4 import BeautifulSoup
import re
try:
import urllib.request as urllib2
except ImportError:
import urllib2
url = r"G:\Freelancer\NC Soccer\Northern Counties Soccer Association ©.html"
page = open(url, encoding="utf8")
soup = BeautifulSoup(page.read(),"html.parser")
#tableList = soup.findAll("table")
for tr in soup.find_all("tr"):
for td in tr.find_all("td"):
print(td.text.strip())
</code></pre>
<p>but it is obvious that it will return text form all td and I will not able to identify particular column name or will not able to determine start of new record. I want to know </p>
<p>1) how to identify each column(because class name is same) and there are headings as well (I will appreciate if you provide code for that) </p>
<p>2) how to identify new record in such structure</p>
| 1 |
2016-09-14T04:58:16Z
| 39,483,922 |
<pre><code>from __future__ import print_function
import re
import datetime
from bs4 import BeautifulSoup
soup = ""
with open("/tmp/a.html") as page:
soup = BeautifulSoup(page.read(),"html.parser")
table = soup.find('div', {'style': 'overflow:auto; border:1px #cccccc solid;'}).find('table')
trs = table.find_all('tr')
table_dict = {}
game = ""
section = ""
for tr in trs:
if tr.has_attr('class'):
game = tr.text.strip('\n')
if tr.has_attr('bgcolor'):
if tr['bgcolor'] == '#CCE4F1':
section = tr.text.strip('\n')
else:
tds = tr.find_all('td')
extracted_text = [re.sub(r'([^\x00-\x7F])+','', td.text) for td in tds]
extracted_text = [x.strip() for x in extracted_text]
extracted_text = list(filter(lambda x: len(x) > 2, extracted_text))
extracted_text.pop(1)
extracted_text[2] = "Player " + extracted_text[2]
extracted_text[3] = datetime.datetime.strptime(extracted_text[3], '%m/%d/%y %I:%M %p').strftime("%Y-%m-%d")
extracted_text = ['"' + x + '"' for x in [game, section] + extracted_text]
print(','.join(extracted_text))
</code></pre>
<p>And when run:</p>
<pre><code>$ python a.py
"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228004","2016-09-10","player persistently infringes the laws of the game","C"
"AVIATORS SOCCER CLUB","G12DB - AVIATORS-G12DB-REYNGOUDT","Saskia Reyes","Player 224463","2016-09-11","player/sub guilty of unsporting behavior","C"
"BERGENFIELD SOCCER CLUB","B11CW - BERGENFIELD-B11CW-NARVAEZ","Christian Latorre","Player 226294","2016-09-10","player persistently infringes the laws of the game","C"
</code></pre>
<p>Based on further conversation with the OP, the input was <a href="https://paste.fedoraproject.org/428111/87928814/raw/" rel="nofollow">https://paste.fedoraproject.org/428111/87928814/raw/</a> and the output after running the above code is: <a href="https://paste.fedoraproject.org/428110/38792211/raw/" rel="nofollow">https://paste.fedoraproject.org/428110/38792211/raw/</a></p>
| 0 |
2016-09-14T06:37:41Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
parse table using beautifulsoup in python
| 39,482,760 |
<p>I want to traverse through each row and capture values of td.text. However problem here is table does not have class. and all the td got same class name. I want to traverse through each row and want following output:</p>
<p>1st row)"AMERICANS SOCCER CLUB","B11EB - AMERICANS-B11EB-WARZALA","Cameron Coya","Player 228004","2016-09-10","player persistently infringes the laws of the game","C" (new line)</p>
<p>2nd row) "AVIATORS SOCCER CLUB","G12DB - AVIATORS-G12DB-REYNGOUDT","Saskia Reyes","Player 224463","2016-09-11","player/sub guilty of unsporting behavior"," C" (new line)</p>
<pre><code><div style="overflow:auto; border:1px #cccccc solid;">
<table cellspacing="0" cellpadding="3" align="left" border="0" width="100%">
<tbody>
<tr class="tblHeading">
<td colspan="7">AMERICANS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11EB - AMERICANS-B11EB-WARZALA</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cameron Coya </td>
<td width="19%" class="tdUnderLine">
Rozel, Max
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=228004" target="_blank">228004</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 02:15 PM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">AVIATORS SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">G12DB - AVIATORS-G12DB-REYNGOUDT</td>
</tr>
<tr bgcolor="#FBFBFB">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Saskia Reyes </td>
<td width="19%" class="tdUnderLine">
HollaenderNardelli, Eric
</td>
<td width="06%" class="tdUnderLine">
09-11-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=224463" target="_blank">224463</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/11/16 06:45 PM
</td>
<td width="30%" class="tdUnderLine"> player/sub guilty of unsporting behavior </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
<tr class="tblHeading">
<td colspan="7">BERGENFIELD SOCCER CLUB</td>
</tr>
<tr bgcolor="#CCE4F1">
<td colspan="7">B11CW - BERGENFIELD-B11CW-NARVAEZ</td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="19%" class="tdUnderLine"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Christian Latorre </td>
<td width="19%" class="tdUnderLine">
Coyle, Kevin
</td>
<td width="06%" class="tdUnderLine">
09-10-2016
</td>
<td width="05%" class="tdUnderLine" align="center">
<a href="http://www.ncsanj.com/gameRefReportPrint.cfm?gid=226294" target="_blank">226294</a>
</td>
<td width="16%" class="tdUnderLine" align="center">
09/10/16 11:00 AM
</td>
<td width="30%" class="tdUnderLine"> player persistently infringes the laws of the game </td>
<td class="tdUnderLine"> Cautioned </td>
</tr>
</code></pre>
<p>I tried with following code. </p>
<pre><code>import requests
from bs4 import BeautifulSoup
import re
try:
import urllib.request as urllib2
except ImportError:
import urllib2
url = r"G:\Freelancer\NC Soccer\Northern Counties Soccer Association ©.html"
page = open(url, encoding="utf8")
soup = BeautifulSoup(page.read(),"html.parser")
#tableList = soup.findAll("table")
for tr in soup.find_all("tr"):
for td in tr.find_all("td"):
print(td.text.strip())
</code></pre>
<p>but it is obvious that it will return text form all td and I will not able to identify particular column name or will not able to determine start of new record. I want to know </p>
<p>1) how to identify each column(because class name is same) and there are headings as well (I will appreciate if you provide code for that) </p>
<p>2) how to identify new record in such structure</p>
| 1 |
2016-09-14T04:58:16Z
| 39,484,094 |
<pre><code>count = 0
string = ""
for td in soup.find_all("td"):
string += "\""+td.text.strip()+"\","
count +=1
if(count % 9 ==0):
print string[:-1] + "\n\n" # string[:-1] to remove the last ","
string = ""
</code></pre>
<p>as the table is not in the proper required format we shall just go with the td rather than going into each row then going into td in each row which complicates the work. I just used a string you can append the data into a list of lists and get process it for later use.<br>
Hope this solves your problem</p>
| 1 |
2016-09-14T06:47:34Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
How do I import tables from another database in sqlite using Python?
| 39,482,796 |
<p>How do I import data from a column in another table in another database into the current database's table's column? </p>
<p>I tried using the "ATTACH" command, but I'm only allowed to execute one statement at a time. </p>
<pre><code> cursor.execute(
"ATTACH DATABASE other.db AS other;\
INSERT INTO table \
(column1) \
SELECT column1\
FROM other.table;")
</code></pre>
| 0 |
2016-09-14T05:02:48Z
| 39,485,832 |
<p>In place of <code>execute</code> you may want to do an <code>executescript</code>. Like so...</p>
<pre><code>cursor.executescript("""ATTACH DATABASE 'other.db' AS other;
INSERT INTO table (column1)
SELECT column1
FROM other.table;""")
</code></pre>
<p>(assuming other.db is an sqlite file)</p>
| 1 |
2016-09-14T08:29:27Z
|
[
"python",
"sqlite"
] |
How do I import tables from another database in sqlite using Python?
| 39,482,796 |
<p>How do I import data from a column in another table in another database into the current database's table's column? </p>
<p>I tried using the "ATTACH" command, but I'm only allowed to execute one statement at a time. </p>
<pre><code> cursor.execute(
"ATTACH DATABASE other.db AS other;\
INSERT INTO table \
(column1) \
SELECT column1\
FROM other.table;")
</code></pre>
| 0 |
2016-09-14T05:02:48Z
| 39,486,211 |
<p>I had to call <code>execute</code> twice, and enclose <code>other.db</code> is single quotations </p>
<pre><code> cursor.execute("ATTACH DATABASE 'other.db' AS other;")
cursor.execute("\
INSERT INTO table \
(ID) \
SELECT ID \
FROM other.table ;")
</code></pre>
| 0 |
2016-09-14T08:49:49Z
|
[
"python",
"sqlite"
] |
why output list is empty in my code in Python 2.7
| 39,482,800 |
<p>Using Python 2.7 and trying to do simple tokenization on UTF-8 encoded files. The output of <code>a</code> seems a byte string, which is expected, since after <code>tk[0].encode('utf-8')</code>, it converts from Python <code>unicode</code> type to <code>str/byte</code>. My major confusion is why output of <code>b</code> is empty list? I think without encoding (I mean without calling <code>.encode('utf-8')</code>), it should be raw unicode character (e.g. I expect some Chinese character printed, as <code>1.txt</code> is UTF-8 encoded Chinese character file).</p>
<p><strong>Source code</strong>,</p>
<pre><code>import jieba
if __name__ == "__main__":
with open('1.txt', 'r') as content_file:
content = content_file.read()
segment_list = jieba.tokenize(content.decode('utf-8'), mode='search')
if segment_list is None:
print 'segment is None'
else:
a = [tk[0].encode('utf-8') for tk in segment_list]
b = [tk[0] for tk in segment_list]
print a
print b
</code></pre>
<p>** Output **,</p>
<pre><code>['\xe4\xb8\x8a\xe6\xb5\xb7', '\xe6\xb5\xb7\xe5\xb8\x82', '\xe4\xb8\x8a\xe6\xb5\xb7\xe5\xb8\x82', '\xe6\xb7\xb1\xe5\x9c\xb3', '\xe6\xb7\xb1\xe5\x9c\xb3\xe5\xb8\x82', '\xe7\xa6\x8f\xe7\x94\xb0', '\xe7\xa6\x8f\xe7\x94\xb0\xe5\x8c\xba', '\xe6\xa2\x85\xe6\x9e\x97', '\xe6\x9e\x97\xe8\xb7\xaf', '\xe6\xa2\x85\xe6\x9e\x97\xe8\xb7\xaf', '\xe4\xb8\x8a\xe6\xb5\xb7', '\xe6\xb5\xb7\xe5\xb8\x82', '\xe6\xb5\xa6\xe4\xb8\x9c', '\xe6\x96\xb0\xe5\x8c\xba', '\xe4\xb8\x8a\xe6\xb5\xb7\xe5\xb8\x82', '\xe4\xb8\x8a\xe6\xb5\xb7\xe5\xb8\x82\xe6\xb5\xa6\xe4\xb8\x9c\xe6\x96\xb0\xe5\x8c\xba', '\xe8\x80\x80\xe5\x8d\x8e', '\xe8\xb7\xaf', '\r\n']
[]
</code></pre>
| 1 |
2016-09-14T05:03:02Z
| 39,482,843 |
<p>It appears that <code>jieba.tokenize()</code> returns a generator. A generator can be iterated over only once. Better do</p>
<pre><code> b = [tk[0] for tk in segment_list]
a = [tk.encode('utf-8') for tk in b]
</code></pre>
| 1 |
2016-09-14T05:07:54Z
|
[
"python",
"python-2.7",
"unicode"
] |
Why is my decimal to binary program returning the value backwards and in a table format?
| 39,482,836 |
<p>I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.</p>
<pre><code>number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2
base2 = srt(number) + str(rem)
print(rem)
#This was to prevent the end text from sticking to the print
input('\nEnter to end')
</code></pre>
<p>It returns the correct values, but backwards and in a column and I don't know why.</p>
| 0 |
2016-09-14T05:07:03Z
| 39,482,942 |
<p>Your code prints the lowest bit of remaining number on separate lines so that's why you see them in reverse order. You could change your code to store bits to an array and then after the loop print them in reverse order:</p>
<pre><code>number = int(input('Enter a number in base 10: '))
base2 = []
while(number > 0):
base2.append(str(number % 2))
number = number // 2
print(''.join(reversed(base2)))
</code></pre>
<p>Python also has built-in method <a href="https://docs.python.org/3.5/library/functions.html#bin" rel="nofollow"><code>bin</code></a> than can do the conversion for you:</p>
<pre><code>>>> bin(10)
'0b1010'
</code></pre>
| 0 |
2016-09-14T05:18:48Z
|
[
"python",
"binary",
"decimal",
"converter",
"data-conversion"
] |
Why is my decimal to binary program returning the value backwards and in a table format?
| 39,482,836 |
<p>I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.</p>
<pre><code>number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2
base2 = srt(number) + str(rem)
print(rem)
#This was to prevent the end text from sticking to the print
input('\nEnter to end')
</code></pre>
<p>It returns the correct values, but backwards and in a column and I don't know why.</p>
| 0 |
2016-09-14T05:07:03Z
| 39,484,013 |
<p>Some modifications to your code:</p>
<pre><code>number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2 # can be number //= 2, or number >>= 1
base2 += str(rem)
#print(rem) # no need to print
print(base2[::-1])
</code></pre>
<p>Or more simple:</p>
<pre><code>base2 = bin(number)[2:]
</code></pre>
| 0 |
2016-09-14T06:43:06Z
|
[
"python",
"binary",
"decimal",
"converter",
"data-conversion"
] |
Python - NumPy Array Logical XOR operation byte wise
| 39,482,865 |
<p>I am reading an image via Pillow and converting it to a numpy array.</p>
<pre><code> A = numpy.asarray(Image.open(
ImageNameA).convert("L"))
B = numpy.asarray(Image.open(
ImageNameB).convert("L"))
print A
[[255 255 255 ..., 255 255 255]
[255 255 255 ..., 255 255 255]
[255 255 255 ..., 255 255 255]
...,
[255 255 255 ..., 255 255 255]
[255 255 255 ..., 255 255 255]
[255 255 255 ..., 255 255 255]]
</code></pre>
<p>Now when I do any logical operation on these 2 numpy arrays, I get it in form of 'True' and 'False'</p>
<pre><code>Answer = numpy.logical_xor(A,B)
print numpy.logical_xor(A,C)
[[False False False ..., False False False]
[False False False ..., False False False]
[False False False ..., False False False]
...,
[False False False ..., False False False]
[False False False ..., False False False]
[False False False ..., False False False]]
</code></pre>
<p>My image processing functions cant work with True, False ... How can i get an image in form of 0 , 255 (in bytes)</p>
| 1 |
2016-09-14T05:09:56Z
| 39,483,395 |
<p>From the question title, I suppose the function you meant to use is actualy <code>numpy.bitwise_xor</code> it will output arrays in the 0-255 range as you expect. </p>
<p><code>logical_xor</code> treats all number above 1 as <code>True</code> and 0 as <code>False</code> and always outputs a boolean array (only 0s and 1s).</p>
| 2 |
2016-09-14T05:57:26Z
|
[
"python",
"numpy",
"pillow"
] |
Is there an equivalent to python reduce() function in scala?
| 39,482,883 |
<p>I've just started learning Scala and functional programming and I'm trying to convert the following from Python to Scala:</p>
<pre><code>def immutable_iterative_fibonacci(position):
if (position ==1):
return [1]
if (position == 2):
return [1,1]
next_series = lambda series, _: series + [series [-1] + series [-2]]
return reduce(next_series, range(position - 2), [1, 1])
</code></pre>
<p>I can't figure out what the equivalent of reduce in Scala is. This is what I currently have. Everything works fine except the last line.</p>
<pre><code>def immutable_fibonacci(position: Int) : ArrayBuffer[Int] = {
if (position == 1){
return ArrayBuffer(1)
}
if (position == 2){
return ArrayBuffer(1,1)
}
var next_series = (series: ArrayBuffer[Int]) => series :+ ( series( series.size - 1) + series( series.size -2))
return reduce(next_series, 2 to position, ArrayBuffer(1,1))
}
</code></pre>
| 3 |
2016-09-14T05:12:27Z
| 39,483,031 |
<p>Summary of Python <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce</code></a>, for reference:</p>
<pre><code>reduce(function, iterable[, initializer])
</code></pre>
<h2>Traversable</h2>
<p>A good type to look at is <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Traversable" rel="nofollow"><code>Traversable</code></a>, a supertype of <code>ArrayBuffer</code>. You may want to just peruse that API for a while, because there's a lot of useful stuff in there.</p>
<h2>Reduce</h2>
<p>The equivalent of Python's <code>reduce</code>, when the <code>initializer</code> arg is omitted, is Scala's <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Traversable@reduceLeft[B>:A](op:(B,A)=>B):B" rel="nofollow"><code>Traversable[A]#reduceLeft</code></a>:</p>
<pre><code>reduceLeft[B >: A](op: (B, A) => B): B
</code></pre>
<p>The <code>iterable</code> arg from the Python function corresponds to the <code>Traversable</code> instance, and the <code>function</code> arg from the Python function corresponds to <code>op</code>.</p>
<p>Note that there are also methods named <code>reduce</code>, <code>reduceRight</code>, <code>reduceLeftOption</code>, and <code>reduceRightOption</code>, which are similar but slightly different.</p>
<h2>Fold</h2>
<p>Your example, which does provide an <code>initializer</code> arg, corresponds to Scala's <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Traversable@foldLeft[B](z:B)(op:(B,A)=>B):B" rel="nofollow"><code>Traversable[A]#foldLeft</code></a>:</p>
<pre><code>foldLeft[B](z: B)(op: (B, A) => B): B
</code></pre>
<p>The <code>initializer</code> arg from the Python function corresponds to the <code>z</code> arg in <code>foldLeft</code>.</p>
<p>Again, note that there are some related methods named <code>fold</code> and <code>foldRight</code>.</p>
<h2>Fibonacci</h2>
<p>Without changing the algorithm, here's a cleaned-up version of your code:</p>
<pre><code>def fibonacci(position: Int): Seq[Int] =
position match {
case 1 => Vector(1)
case 2 => Vector(1, 1)
case _ =>
(2 to position).foldLeft(Vector(1, 1)) { (series, _) =>
series :+ (series(series.size - 1) + series(series.size - 2))
}
}
</code></pre>
<p>A few miscellaneous notes:</p>
<ul>
<li>We generally never use the <code>return</code> keyword</li>
<li>Pattern matching (what we're doing with the <code>match</code> keyword) is often considered cleaner than an <code>if</code>-<code>else</code> chain</li>
<li>Replace <code>var</code> (which allows multiple assignment) with <code>val</code> (which doesn't) wherever possible</li>
<li>Don't use a mutable collection (<code>ArrayBuffer</code>) if you don't need to. <code>Vector</code> is a good general-purpose immutable sequence.</li>
</ul>
<p>And while we're on the topic of collections and the Fibonacci series, for fun you may want to check out the first example in the <a href="http://www.scala-lang.org/api/current/#scala.collection.immutable.Stream" rel="nofollow"><code>Stream</code></a> documentation:</p>
<pre><code>val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #::
fibs.zip(fibs.tail).map { n => n._1 + n._2 }
fibs.drop(1).take(6).mkString(" ")
// "1 1 2 3 5 8"
</code></pre>
| 9 |
2016-09-14T05:27:28Z
|
[
"python",
"scala",
"lambda",
"functional-programming",
"reduce"
] |
Print leading zeros of a floating point number
| 39,482,902 |
<p>I am trying to print something:</p>
<pre><code>>>> print "%02i,%02i,%02g" % (3, 4, 5.66)
03,04,5.66
</code></pre>
<p>However this is not correct. If you notice, the zeroes get correctly pre-pended
to all the integer floating points (the first two numbers). I need it such that there will be one leading zero if the there is a single digit to the left of the decimal point. </p>
<p>I.e. the solution above should return:</p>
<pre><code>03,04,05.66
</code></pre>
<p>What am I doing wrong?</p>
| 3 |
2016-09-14T05:14:15Z
| 39,482,975 |
<p>Use different format i.e. <code>f</code>:</p>
<pre><code>print "%02i,%02i,%05.2f" % (3, 4, 5.66)
^^^^^^
</code></pre>
<p>or with <code>g</code>:</p>
<pre><code> print "%02i,%02i,%05.3g" % (3, 4, 5.66)
^^^^^^
</code></pre>
<p>But I would stick to <code>f</code>. I guess that's what you trying to do here (<code>g</code> can sometimes use decimal format). More info here: <a href="https://docs.python.org/2/library/stdtypes.html#string-formatting" rel="nofollow">formatting strings with %</a></p>
<pre><code>'f' Floating point decimal format.
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
</code></pre>
| 4 |
2016-09-14T05:22:57Z
|
[
"python"
] |
Print leading zeros of a floating point number
| 39,482,902 |
<p>I am trying to print something:</p>
<pre><code>>>> print "%02i,%02i,%02g" % (3, 4, 5.66)
03,04,5.66
</code></pre>
<p>However this is not correct. If you notice, the zeroes get correctly pre-pended
to all the integer floating points (the first two numbers). I need it such that there will be one leading zero if the there is a single digit to the left of the decimal point. </p>
<p>I.e. the solution above should return:</p>
<pre><code>03,04,05.66
</code></pre>
<p>What am I doing wrong?</p>
| 3 |
2016-09-14T05:14:15Z
| 39,482,976 |
<p>For <code>g</code>, specify and width and precision:</p>
<pre><code>>>> print "%02i,%02i,%05.3g" % (3, 4, 5.66)
03,04,05.66
</code></pre>
<h3>f versus g</h3>
<p>The difference between <code>f</code> and <code>g</code> is illustrated here:</p>
<pre><code>>>> print "%07.1f, %07.1f, %07.1f" % (1.23, 4567.8, 9012345678.2)
00001.2, 04567.8, 9012345678.2
>>> print "%07.1g, %07.1g, %07.1g" % (1.23, 4567.8, 9012345678.2)
0000001, 005e+03, 009e+09
</code></pre>
<p>When given large numbers, <code>g</code> switches to scientific notation while <code>f</code> just uses more spaces.</p>
<p>Similarly, <code>g</code> switches to scientific notation, when needed, for small numbers:</p>
<pre><code>>>> print "%07.1f, %07.1f, %07.1f" % (.01, .0001, .000001)
00000.0, 00000.0, 00000.0
>>> print "%07.1g, %07.1g, %07.1g" % (.01, .0001, .000001)
0000.01, 00.0001, 001e-06
</code></pre>
| 5 |
2016-09-14T05:22:57Z
|
[
"python"
] |
Print leading zeros of a floating point number
| 39,482,902 |
<p>I am trying to print something:</p>
<pre><code>>>> print "%02i,%02i,%02g" % (3, 4, 5.66)
03,04,5.66
</code></pre>
<p>However this is not correct. If you notice, the zeroes get correctly pre-pended
to all the integer floating points (the first two numbers). I need it such that there will be one leading zero if the there is a single digit to the left of the decimal point. </p>
<p>I.e. the solution above should return:</p>
<pre><code>03,04,05.66
</code></pre>
<p>What am I doing wrong?</p>
| 3 |
2016-09-14T05:14:15Z
| 39,482,977 |
<p>The format <code>%02g</code> specifies minimum width of 2. You can use <code>%0m.n</code> syntax where <code>m</code> is the minimum width and <code>n</code> is the number of decimals. What you need is this:</p>
<pre><code>>>> print "%02i,%02i,%05.2f" % (3, 4, 5.66)
03,04,05.66
</code></pre>
| 4 |
2016-09-14T05:22:58Z
|
[
"python"
] |
Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
| 39,482,968 |
<p>So for example</p>
<pre><code>['John','John','Mike','Mike','Kate','Kate']
</code></pre>
<p>Should return:</p>
<pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>
<p>How can I write code so there is order instead of those three pairs just being in random order?</p>
<p>I need to sort the list of tuples by count from biggest to smallest unless there are ties, then I need to sort the times alphabetically.</p>
| 2 |
2016-09-14T05:21:49Z
| 39,483,009 |
<p>This works:</p>
<pre><code>>>> names = ['John','John','Mike','Mike','Kate','Kate']
>>> sorted(Counter(names).items(), key=lambda item: (-item[1], item[0]))
[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>
<p>The counter's items will give you tuples of <code>(name, count)</code>. Normally you'd use <code>Counter.most_common</code> to get the items in order of their counts, but as far as I can tell, it only sorts by count and disregards any key (name) information in the sorting.</p>
<p>Since we have to re-sort again anyway, we might as well use <code>sorted</code> on the items instead. Since tuples sort lexicographically, and you want to sort primarily by the count, the key function should return a tuple of the format <code>(count, name)</code>. However, since you want this to be <em>decreasing</em> by count, but <em>increasing</em> by name, the only thing we can do is return a tuple of the format <code>(-count, name)</code>. This way, larger count will result in a lower value so it will sort <em>before</em> values with lower counts.</p>
| 2 |
2016-09-14T05:25:24Z
|
[
"python",
"python-3.x"
] |
Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
| 39,482,968 |
<p>So for example</p>
<pre><code>['John','John','Mike','Mike','Kate','Kate']
</code></pre>
<p>Should return:</p>
<pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>
<p>How can I write code so there is order instead of those three pairs just being in random order?</p>
<p>I need to sort the list of tuples by count from biggest to smallest unless there are ties, then I need to sort the times alphabetically.</p>
| 2 |
2016-09-14T05:21:49Z
| 39,483,086 |
<p>There are two ways to do this. In the first method, a sorted list is returned. In the second method, the list is sorted in-place.</p>
<pre><code>import operator
# Method 1
a = [('Mike', 2), ('John', 2), ('Kate', 2), ('Arvind', 5)]
print(sorted(a, key = lambda x : (x[0],)))
# Method 2
a = [('Mike', 2), ('John', 2), ('Kate', 2), ('Arvind', 5)]
a.sort(key=operator.itemgetter(0))
print(a)
</code></pre>
| 0 |
2016-09-14T05:32:28Z
|
[
"python",
"python-3.x"
] |
Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
| 39,482,968 |
<p>So for example</p>
<pre><code>['John','John','Mike','Mike','Kate','Kate']
</code></pre>
<p>Should return:</p>
<pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>
<p>How can I write code so there is order instead of those three pairs just being in random order?</p>
<p>I need to sort the list of tuples by count from biggest to smallest unless there are ties, then I need to sort the times alphabetically.</p>
| 2 |
2016-09-14T05:21:49Z
| 39,483,440 |
<p>You can sort your result using <code>sorted()</code> function using the <code>key</code> argument to define how to sort the items:</p>
<pre><code>result = [('John', 2), ('Kate', 2), ('Mike', 3)]
sorted_result = sorted(result, key=lambda x: (-x[1], x[0]))
</code></pre>
<p>As you want to sort the result in descending order on the count value and then the name in ascending order, so the key <code>(-x[1], x[0])</code> will do the trick.</p>
<p>The <code>sorted_result</code> will be:</p>
<pre><code>[('Mike', 3), ('John', 2), ('Kate', 2)]
</code></pre>
| 2 |
2016-09-14T06:01:01Z
|
[
"python",
"python-3.x"
] |
Django upload limits
| 39,483,099 |
<p>I want to make've limited the number of users on the upload file. For example:
Every day, users are limited to 1 image file. </p>
<p><strong>Views</strong></p>
<pre><code>class Upload(views.LoginRequiredMixin, generic.CreateView):
model = Posts
form_class = UploadForm
template_name = 'icerik_yukle.html'
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.author= self.request.user
self.object.save()
return super(Upload, self).form_valid(form)
</code></pre>
<p><strong>Models</strong></p>
<pre><code>class Gonderi(models.Model):
author= models.ForeignKey(User, related_name="gonderi")
slug = models.SlugField(unique=True, max_length=10, default=id_olustur)
image = models.FileField(upload_to=yukleme_adresi, blank=True)
subject= models.CharField(max_length=50, blank=True)
descrip = models.TextField(max_length=250, blank=True)
category= models.ForeignKey(Kategori, verbose_name="Kategori")
tags = TaggableManager()
created= models.DateTimeField(auto_now_add=True)
updated= models.DateTimeField(auto_now=True)
is_public = models.BooleanField(verbose_name='Göster', default=True)
</code></pre>
| 0 |
2016-09-14T05:33:26Z
| 39,483,176 |
<p>Check if exists a record for the current day and if it has a valid picture for the user. If there is, raise an exception</p>
<pre><code>def form_valid(self, form):
from datetime import datetime
query = Gonderi.objects.filter(created__date=datetime.now().date(),
author=request.user)
instance = query[0] if query.count() > 0 else None
if instance and instance.image:
#raise your error over here
self.object = form.save(commit=False)
self.object.author= self.request.user
self.object.save()
return super(Upload, self).form_valid(form)
</code></pre>
| 2 |
2016-09-14T05:41:38Z
|
[
"python",
"django"
] |
How to get only word for selected tag in NLTK Part of Speech (POS) tagging?
| 39,483,108 |
<p>Sorry I am new to Pandas and NLTK. I'm trying to build set of customize returned POS. My data contents:</p>
<pre><code> comment
0 [(have, VERB), (you, PRON), (pahae, VERB)]
1 [(radio, NOUN), (television, NOUN), (lid, NOUN)]
2 [(yes, ADV), (you're, ADJ)]
3 [(ooi, ADJ), (work, NOUN), (barisan, ADJ)]
4 [(national, ADJ), (debt, NOUN), (increased, VERB)]
</code></pre>
<p>Any idea how can I get only word that match selected tag (<code>VERB</code> or <code>NOUN</code>), like below? And return <code>NaN</code> if none matching.</p>
<pre><code> comment
0 [(have), (pahae)]
1 [(radio), (television), (lid)]
2 [NaN]
3 [(work)]
4 [(debt), (increased)]
</code></pre>
| 2 |
2016-09-14T05:34:24Z
| 39,483,414 |
<p>You can use <code>list comprehension</code> and then replace empty <code>list</code> to <code>[NaN]</code>:</p>
<pre><code>df = pd.DataFrame({'comment': [
[('have', 'VERB'), ('you', 'PRON'), ('pahae', 'VERB')],
[('radio', 'NOUN'), ('television', 'NOUN'), ('lid', 'NOUN')],
[('yes', 'ADV'), ("you're", 'ADJ')],
[('ooi', 'ADJ'), ('work', 'NOUN'), ('barisan', 'ADJ')],
[('national', 'ADJ'), ('debt', 'NOUN'), ('increased', 'VERB')]
]})
print (df)
comment
0 [(have, VERB), (you, PRON), (pahae, VERB)]
1 [(radio, NOUN), (television, NOUN), (lid, NOUN)]
2 [(yes, ADV), (you're, ADJ)]
3 [(ooi, ADJ), (work, NOUN), (barisan, ADJ)]
4 [(national, ADJ), (debt, NOUN), (increased, VE...
</code></pre>
<pre><code>df.comment = df.comment.apply(lambda x: [(t[0],) for t in x if t[1]=='VERB' or t[1]=='NOUN'])
df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]]
print (df)
comment
0 [(have,), (pahae,)]
1 [(radio,), (television,), (lid,)]
2 [nan]
3 [(work,)]
4 [(debt,), (increased,)]
</code></pre>
| 1 |
2016-09-14T05:58:51Z
|
[
"python",
"list",
"pandas",
"tuples",
"nltk"
] |
How to get only word for selected tag in NLTK Part of Speech (POS) tagging?
| 39,483,108 |
<p>Sorry I am new to Pandas and NLTK. I'm trying to build set of customize returned POS. My data contents:</p>
<pre><code> comment
0 [(have, VERB), (you, PRON), (pahae, VERB)]
1 [(radio, NOUN), (television, NOUN), (lid, NOUN)]
2 [(yes, ADV), (you're, ADJ)]
3 [(ooi, ADJ), (work, NOUN), (barisan, ADJ)]
4 [(national, ADJ), (debt, NOUN), (increased, VERB)]
</code></pre>
<p>Any idea how can I get only word that match selected tag (<code>VERB</code> or <code>NOUN</code>), like below? And return <code>NaN</code> if none matching.</p>
<pre><code> comment
0 [(have), (pahae)]
1 [(radio), (television), (lid)]
2 [NaN]
3 [(work)]
4 [(debt), (increased)]
</code></pre>
| 2 |
2016-09-14T05:34:24Z
| 39,483,488 |
<h3>Setup reference</h3>
<pre><code>s = pd.Series([
[('have', 'VERB'), ('you', 'PRON'), ('pahae', 'VERB')],
[('radio', 'NOUN'), ('television', 'NOUN'), ('lid', 'NOUN')],
[('yes', 'ADV'), ("you're", 'ADJ')],
[('ooi', 'ADJ'), ('work', 'NOUN'), ('barisan', 'ADJ')],
[('national', 'ADJ'), ('debt', 'NOUN'), ('increased', 'VERB')]
], name='comment')
s
0 [(have, VERB), (you, PRON), (pahae, VERB)]
1 [(radio, NOUN), (television, NOUN), (lid, NOUN)]
2 [(yes, ADV), (you're, ADJ)]
3 [(ooi, ADJ), (work, NOUN), (barisan, ADJ)]
4 [(national, ADJ), (debt, NOUN), (increased, VE...
Name: comment, dtype: object
</code></pre>
<hr>
<h3>Solution</h3>
<pre><code>s1 = s.apply(pd.Series).stack().apply(pd.Series)
s2 = s1.loc[s1[1].isin(['VERB', 'NOUN']), 0]
s3 = s2.groupby(level=0).apply(zip).reindex_like(s)
s3.loc[s3.isnull()] = [[np.nan]]
s3
0 [(have,), (pahae,)]
1 [(radio,), (television,), (lid,)]
2 [nan]
3 [(work,)]
4 [(debt,), (increased,)]
Name: 0, dtype: object
</code></pre>
<hr>
<p><strong><em>For Python 3</em></strong><br>
per @jezrael</p>
<pre><code>s1 = s.apply(pd.Series).stack().apply(pd.Series)
s2 = s1.loc[s1[1].isin(['VERB', 'NOUN']), 0]
s3 = s2.groupby(level=0).apply(lambda x: list(zip(x))).reindex_like(s)
s3.loc[s3.isnull()] = [[np.nan]]
s3
</code></pre>
| 1 |
2016-09-14T06:05:41Z
|
[
"python",
"list",
"pandas",
"tuples",
"nltk"
] |
PyQt window closes after opening
| 39,483,114 |
<p>I have two files, namely <em>main.py</em> and <em>client_window.py</em>. I want to show the client window after the progress bar completes its progress. But I find that the client window opens and closes immediately. Can someone suggest how to change the code, so that I'll grasp the correct logic?</p>
<p>This is <em>main.py</em>:</p>
<pre><code>"""
This module defines the User Interface
"""
import sys
import time
from cloudL.ui import client_window
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtGui import *
class ProgressBarWidget(QtGui.QDialog):
def __init__(self, parent=None):
super(ProgressBarWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
self.label = QLabel()
self.tryAgain = QPushButton("Try Again")
self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,100)
self.tryAgain.setEnabled(False)
layout.addWidget(self.label)
layout.addWidget(self.progressBar)
layout.addWidget(self.tryAgain)
self.myLongTask = TaskThread()
self.myLongTask.notifyProgress.connect(self.onProgress)
self.myLongTask.start()
def onStart(self):
self.tryAgain.setEnabled(False)
self.myLongTask.start()
self.label.setText("")
def onProgress(self, i):
self.progressBar.setValue(i)
if(self.progressBar.value() == 100):
#app = QApplication(sys.argv)
#global ex
ex = client_window.main()
ex.show()
#ex.main()
#ex.show()
#sys.exit(app.exec_())
else:
self.tryAgain.setEnabled(True)
self.tryAgain.clicked.connect(self.onStart)
self.label.setText("Cannot connect to Server! Please Try Again!")
class TaskThread(QtCore.QThread):
notifyProgress = QtCore.pyqtSignal(int)
def run(self):
for i in range(101):
self.notifyProgress.emit(i)
time.sleep(0.005)
class MainWindow(QWidget):
"""
This window will be the first screen to appear
"""
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
"""
Initializes parameters required by the MainWindow
"""
self.option = "" # to specify the if the selected option is Server or Client
self.ex = None
def main(self):
"""
This function is the origin where the initiation of the control takes place
:return: Returns nothing
"""
mainLayout = QVBoxLayout()
mainLayout.setAlignment(QtCore.Qt.AlignCenter)
radioLayout = QHBoxLayout()
mainLayout.setAlignment(QtCore.Qt.AlignCenter)
label = QLabel()
label.setText("Select whether to act as a Server or a Client")
labelFont = QFont()
labelFont.setBold(True)
labelFont.setPointSize(15)
label.setFont(labelFont)
mainLayout.addWidget(label)
mainLayout.addStretch()
b1 = QRadioButton("Server")
b1.setChecked(True)
b1.toggled.connect(lambda : btnstate(b1))
radioLayout.addWidget(b1)
b2 = QRadioButton("Client")
b2.toggled.connect(lambda : btnstate(b2))
radioLayout.addWidget(b2)
self.option = ""
def btnstate(b):
"""
Nested function to define the action when radio button is toggled
:param b: Button which is toggled currently
:return: Returns nothing
"""
if b.text() == "Server" and b.isChecked() == True:
self.option = "Server"
if b.text() == "Client" and b.isChecked() == True:
self.option = "Client"
start = QPushButton("Start")
mainLayout.addLayout(radioLayout)
mainLayout.addStretch()
mainLayout.addWidget(start)
self.setLayout(mainLayout)
self.setGeometry(400, 200, 300, 300)
self.setWindowTitle("CloudL")
start.clicked.connect(self.showdialog)
def showdialog(self):
"""
A sample message box to check and display which option is chosen
:return: Returns nothing
"""
#app = QApplication(sys.argv)
self.ex = ProgressBarWidget(self)
self.ex.setGeometry(400, 200, 500, 150)
self.destroy()
self.ex.setWindowTitle("CloudL")
self.ex.show()
"""
Execute the required action
"""
app = QApplication(sys.argv)
ex = MainWindow()
ex.main()
ex.show()
sys.exit(app.exec_())
</code></pre>
<p>And <em>client_window.py</em> is as follows:</p>
<pre><code>#client_window.py
import sys
from PyQt4 import QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class myListWidget(QListWidget):
def Clicked(self, item):
QMessageBox.information(self, "ListWidget", "You clicked: " + item.text())
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.listWidget = None
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
topleftLayout = QVBoxLayout()
topleftLayout.setAlignment(QtCore.Qt.AlignTop)
topleft = QFrame()
topleft.setFrameShape(QFrame.StyledPanel)
label = QLabel()
label.setText("SERVER LIST")
label.setAlignment(QtCore.Qt.AlignCenter)
topleftLayout.addWidget(label)
self.addServerList(topleftLayout)
topleft.setLayout(topleftLayout)
bottom = QFrame()
bottom.setFrameShape(QFrame.StyledPanel)
splitter1 = QSplitter(Qt.Horizontal)
textedit = QTextEdit()
splitter1.addWidget(topleft)
splitter1.addWidget(textedit)
splitter1.setSizes([100, 200])
splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(splitter1)
splitter2.addWidget(bottom)
splitter2.setSizes([225, 100])
hbox.addWidget(splitter2)
self.setLayout(hbox)
QApplication.setStyle(QStyleFactory.create('Cleanlooks'))
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('QSplitter demo')
self.showMaximized()
def addServerList(self, layout):
self.listWidget = myListWidget()
self.listWidget.resize(300, 120)
self.listWidget.addItem("Item 1");
self.listWidget.addItem("Item 2");
self.listWidget.addItem("Item 3");
self.listWidget.addItem("Item 4");
self.listWidget.setWindowTitle('PyQT QListwidget Demo')
self.listWidget.itemClicked.connect(self.listWidget.Clicked)
layout.addWidget(self.listWidget)
def main():
ex = Example()
ex.showMaximized()
return ex
if __name__ == '__main__':
app = QApplication(sys.argv)
main()
sys.exit(app.exec_())
</code></pre>
<p>I'm making the call to <code>client_window</code> at:</p>
<pre><code>def onProgress(self, i):
self.progressBar.setValue(i)
if(self.progressBar.value() == 100):
#app = QApplication(sys.argv)
#global ex
ex = client_window.main()
ex.show()
#ex.main()
#ex.show()
#sys.exit(app.exec_())
else:
self.tryAgain.setEnabled(True)
self.tryAgain.clicked.connect(self.onStart)
self.label.setText("Cannot connect to Server! Please Try Again!")
</code></pre>
<p>Also, if I include the lines <code>app = QApplication(sys.argv)</code> and <code>sys.exit(app.exec_())</code> in the client window I'm getting the following error:</p>
<blockquote>
<p>QCoreApplication::exec: The event loop is already running pyqt error</p>
</blockquote>
| 0 |
2016-09-14T05:35:28Z
| 39,516,110 |
<p>You need to keep a reference to the client window, otherwise it will be garbage-collected as soon as <code>onProgress</code> returns:</p>
<pre><code>def onProgress(self, i):
self.progressBar.setValue(i)
if self.progressBar.value() == 100:
self.client_window = client_window.main()
else:
self.tryAgain.setEnabled(True)
self.tryAgain.clicked.connect(self.onStart)
self.label.setText("Cannot connect to Server! Please Try Again!")
</code></pre>
| 0 |
2016-09-15T16:31:55Z
|
[
"python",
"qt",
"python-3.x",
"pyqt",
"pyqt4"
] |
"sqlalchemy.exc.InvalidRequestError Entity '<class ''>' has no property ... " exception after updating database
| 39,483,136 |
<p>I am trying to update row in SQLite table by id. </p>
<p>I have class</p>
<pre><code>class newTestCaseData(Base):
__tablename__ = 'test_cases'
__table_args__ = {"useexisting": True}
failure_datails = Column('failure_details', String)
exec_status = Column('exec_status', String)
execution_duration = Column('execution_duration', String)
def __init__(self, failure_details=None, execution_duration=None, exec_status = None):
self.failure_datails = failure_details
self.execution_duration = execution_duration
self.exec_status = exec_status
</code></pre>
<p>And here is my method for updating row in the table:</p>
<pre><code>def update_by_external_id(self, tc_external_id, add_tc_status, add_tc_duration, add_failure_details):
self.new_session.query(newTestCaseData).filter_by(external_id=tc_external_id).\
update({
'exec_status': add_tc_status,
'execution_duration': add_tc_duration,
'failure_details': add_failure_details})
self.new_session.commit()
</code></pre>
<p>After this execution I get error: <code>sqlalchemy.exc.InvalidRequestError: Entity '<class 'models.TestCaseData.newTestCaseData'>' has no property 'failure_details'</code></p>
<p>But everything works fine if I delete 'failure_details' from method 'update_by_external_id':</p>
<pre><code>def update_by_external_id(self, tc_external_id, add_tc_status, add_tc_duration):
self.new_session.query(TestCaseDatas).filter_by(external_id=tc_external_id).\
update({
'exec_status': add_tc_status,
'execution_duration': add_tc_duration})
self.new_session.commit()
</code></pre>
<p>Here is 'failure_details' column in SQLite Studio:
<a href="http://i.stack.imgur.com/ejX4O.png" rel="nofollow"><img src="http://i.stack.imgur.com/ejX4O.png" alt="enter image description here"></a></p>
<p>What am I doing wrong? </p>
| 1 |
2016-09-14T05:38:10Z
| 39,492,593 |
<p>There is spelling mistake in the "failure_datails"</p>
| 0 |
2016-09-14T14:09:33Z
|
[
"python",
"sqlite",
"sqlalchemy"
] |
How to get the edge object data of a vertex in orient db using python
| 39,483,354 |
<pre><code>import pyorient
# create connection
client = pyorient.OrientDB("localhost", 2424)
# open databse
client.db_open( "Apple", "admin", "admin" )
requiredObj = client.command(' select from chat where app_cat=appCategory and module=module and type=type and prob_cat=problemCategory ')
print requiredObj[0]
</code></pre>
<p>Output:</p>
<pre><code>#Output
{'@Chat':{'prob_cat': 'PERFORMANCE', 'type': 'NON FUNCTIONAL', 'module': 'app', 'out_': <pyorient.otypes.OrientBinaryObject object at 0x10d1d6c10>, 'app_cat': 'RETAIL', 'issue': 'Non Capture of Data'},'version':7,'rid':'#22:0'}
</code></pre>
<p>Here I want to rebind the <code>out_': <pyorient.otypes.OrientBinaryObject object></code> using python. When I try this code to debind the object this error comes</p>
<pre><code>print requiredObj[0].out_[0]
TypeError: 'OrientBinaryObject' object does not support indexing
</code></pre>
| 0 |
2016-09-14T05:54:02Z
| 39,484,619 |
<p>You could use </p>
<pre><code>requiredObj = client.command(' select expand(out()[0]) from chat where app_cat=appCategory and module=module and type=type and prob_cat=problemCategory ')
print(requiredObj[0])
</code></pre>
<p>Hope it helps</p>
| 0 |
2016-09-14T07:19:18Z
|
[
"python",
"orientdb"
] |
Why MATLAB/Numpy/Scipy performance is slow and doesn't reach CPU capabilities (flops)?
| 39,483,409 |
<p>First of all, I know there are multiple threads that touch this issue, however I could not get a straight answer and encountered some flops miscalculations.</p>
<p>I have prepared a MATLAB and Python benchmark of element-wise multiplication. This is the simplest and most forward way one can easily calculate the flop count. </p>
<p>It uses NxN array (matrix) but does not do a matrix multiplication, rather an element wise multiplication. This is important because when using the matrix multiplication the number of operation is not N^3 !!!</p>
<p>The <a href="https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm" rel="nofollow">lower level algorithm that performs matrix multiplication</a> does it in less than N^3 operations.</p>
<p>The execution of element-wise multiplication of randomly generated numbers however, will have to be performed in N^2 operations</p>
<p>I have an intel i7-4770 (which I think have 4 physical cores and 8 virtual cores) @ 3.5GHz. So if assuming 4flops per cycle that should be 14 GFLOPS per core!</p>
<p>MATLAB/Numpy/Scipy don't get anywhere near.</p>
<p>Why?</p>
<p>MATLAB:</p>
<pre><code>%element wise multiplication benchmark
N = 10^4;
nOps = N^2;
m1 = randn(N);
m2 = randn(size(m1));
m = randn(size(m1));
m1 = single(m1);
m2 = single(m2);
% clear m
tic
m1 = m1 .* m2;
t = toc;
gflops = nOps/t*1e-9;
t_gflops = [t gflops]
% clear m
tic
m1 = m1.*m2;
t = toc;
gflops = nOps/t*1e-9;
t_gflops = [t gflops]
% clear m
tic
m1 = m1.*m2;
t = toc;
gflops = nOps/t*1e-9;
t_gflops = [t gflops]
version('-blas')
version('-lapack')
</code></pre>
<p>Which results in:</p>
<pre><code>t_gflops =
0.0978 1.0226
t_gflops =
0.0743 1.3458
t_gflops =
0.0731 1.3682
ans =
Intel(R) Math Kernel Library Version 11.1.1 Product Build 20131010 for Intel(R) 64 architecture applications
ans =
Intel(R) Math Kernel Library Version 11.1.1 Product Build 20131010 for Intel(R) 64 architecture applications
Linear Algebra PACKage Version 3.4.1
</code></pre>
<p>And now Python:</p>
<pre><code>import numpy as np
# import gnumpy as gnp
import scipy as sp
import scipy.linalg as la
import time
if __name__ == '__main__':
N = 10**4
nOps = N**2
a = np.random.randn(N,N).astype(np.float32)
b = np.random.randn(N,N).astype(np.float32)
t = time.time()
c = a*b
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
t = time.time()
c = np.multiply(a, b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
t = time.time()
c = sp.multiply(a, b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
t = time.time()
c = sp.multiply(a, b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
a = np.random.randn(N,1).astype(np.float32)
b = np.random.randn(1,N).astype(np.float32)
t = time.time()
c1 = np.dot(a, b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
t = time.time()
c = np.dot(a, b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
t = time.time()
c = la.blas.dgemm(1.0,a,b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
t = time.time()
c = la._fblas.dgemm(1.0,a,b)
dt = time.time()-t
gflops = nOps/dt*1e-9
print("dt = ", dt, ", gflops = ", gflops)
print("numpy config")
np.show_config()
print("scipy config")
sp.show_config()
# numpy
</code></pre>
<p>Which result in:</p>
<pre><code>dt = 0.16301608085632324 , gflops = 0.6134364136022663
dt = 0.16701674461364746 , gflops = 0.5987423610209003
dt = 0.1770176887512207 , gflops = 0.5649152957845881
dt = 0.188018798828125 , gflops = 0.5318617107612401
dt = 0.151015043258667 , gflops = 0.6621856858903415
dt = 0.17201733589172363 , gflops = 0.5813367558659613
dt = 0.3080308437347412 , gflops = 0.3246428142959423
dt = 0.39503931999206543 , gflops = 0.253139358385916
</code></pre>
<p>numpy config</p>
<p>mkl_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library\\include']
</code></pre>
<p>lapack_mkl_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_lapack95_lp64', 'mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library\\include']
</code></pre>
<p>lapack_opt_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_lapack95_lp64', 'mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library\\include']
</code></pre>
<p>blas_opt_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library\\include']
</code></pre>
<p>openblas_lapack_info:</p>
<p>NOT AVAILABLE
blas_mkl_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library\\include']
</code></pre>
<p>scipy config</p>
<p>mkl_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library', 'C:\\Minonda\\envs\\_build\\Library\\include', 'C:\\Minonda\\envs\\_build\\Library\\lib']
</code></pre>
<p>lapack_mkl_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_lapack95_lp64', 'mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library', 'C:\\Minonda\\envs\\_build\\Library\\include', 'C:\\Minonda\\envs\\_build\\Library\\lib']
</code></pre>
<p>lapack_opt_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_lapack95_lp64', 'mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library', 'C:\\Minonda\\envs\\_build\\Library\\include', 'C:\\Minonda\\envs\\_build\\Library\\lib']
</code></pre>
<p>blas_opt_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library', 'C:\\Minonda\\envs\\_build\\Library\\include', 'C:\\Minonda\\envs\\_build\\Library\\lib']
</code></pre>
<p>openblas_lapack_info:</p>
<p>NOT AVAILABLE
blas_mkl_info:</p>
<pre><code>define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:\\Minonda\\envs\\_build\\Library\\lib']
include_dirs = ['C:\\Minonda\\envs\\_build\\Library', 'C:\\Minonda\\envs\\_build\\Library\\include', 'C:\\Minonda\\envs\\_build\\Library\\lib']
</code></pre>
<p>Process finished with exit code 0</p>
| 1 |
2016-09-14T05:58:38Z
| 39,496,508 |
<p>Well, in this case you're being limited by memory bandwidth, not CPU power. Assuming:</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/DDR3_SDRAM#JEDEC_standard_modules" rel="nofollow">PC3-12800
RAM</a>
in dual channel mode; </li>
<li>for every multiplication (single precision) 12 bytes need to be transferred between CPU and RAM;</li>
</ul>
<p>The theoretical maximum sustained performance would be about 2 GFLOPS. I calculated this number as <code>peak DDR3 transfer rate</code> * <code>number of RAM channels</code> / <code>bytes tranferred per FLOP</code>.</p>
<p>BTW, in numpy elementwise operations are not accelerated by BLAS. I'm not sure about MATAB.</p>
| 2 |
2016-09-14T17:36:18Z
|
[
"python",
"performance",
"matlab",
"numpy",
"scipy"
] |
How to access pandas multiindex by element within a nested dict?
| 39,483,417 |
<p>I have a dict of types of regions, within each a dict of sub-regions, and within each of those a pandas dataframe object, indexed to the period from which I need to compute each parameter (column) time series. Additionally, I need it in two units.</p>
<p>So I created something like this:</p>
<pre><code>regions = ['region_x', 'region_y']
sub_regions = ['a', 'b', 'c']
parameters = ['x', 'y', 'z']
units = ['af', 'cbm']
start = datetime(2000, 01, 01)
end = datetime(2000, 01, 03)
arrays = [parameters * 2, units * 3]
cols = pd.MultiIndex.from_arrays(arrays)
empty_df = pd.DataFrame(index=pd.date_range(start, end), columns=cols).fillna(0.0)
tab_dict = {}
for region in regions:
tab_dict.update({region: {}})
for sub_region in sub_regions:
tab_dict[region].update({sub_region: empty_df})
</code></pre>
<p>Which returns </p>
<pre><code>{'region_y':
{'a': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'c': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'b': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0},
'region_x':
{'a': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'c': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'b': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0}}
</code></pre>
<p>Now I need to extract a value from each day (using <code>np.random</code> here) and somehow insert that into it's proper place. I have had success getting into a single-nested dict and updating a DataFrame object (using <code>dict_[key].loc[date] = x</code>), but a 'similar' approach here returns SettingWithCopyWarning and does not update the dataframes.</p>
<pre><code>for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
for region in regions:
for sub_region in sub_regions:
for parameter in parameters:
for unit in units:
unit_af = np.random.randint(100)
unit_cbm = unit_af * 2
tab_dict[region][sub_region][parameter]['af'].loc[day] = unit_af
tab_dict[region][sub_region][parameter]['cbm'].loc[day] = unit_cbm
</code></pre>
<p>It just returns what I had started with. I would greatly appreciate any advice on how to update these values. Excuse the messy code, this was the simplest I could write to reproduce my (much uglier) problem.</p>
| 1 |
2016-09-14T05:59:06Z
| 39,483,830 |
<p>specify both index and column in <code>loc</code><br>
Try</p>
<pre><code>for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
for region in regions:
for sub_region in sub_regions:
for parameter in parameters:
for unit in units:
unit_af = np.random.randint(100)
unit_cbm = unit_af * 2
tab_dict[region][sub_region][parameter].loc[day, 'af'] = unit_af
tab_dict[region][sub_region][parameter].loc[day, 'cbm'] = unit_cbm
</code></pre>
| 2 |
2016-09-14T06:31:05Z
|
[
"python",
"pandas",
"dictionary",
"multi-index"
] |
How to make dtype converter function in Pandas?
| 39,483,427 |
<p>I would like to make functions and pass pipe or apply method in <code>pandas</code> to avoid recursive assignment and for practice.</p>
<p>Here is my example dataframe.</p>
<pre><code>A
0 1
1 2
2 3
3 4
</code></pre>
<p>And I defined my converter function,to pass pipe method.</p>
<pre><code>def converter(df,cols,types):
df.cols=df.cols.astype(types)
return df
</code></pre>
<p>then pass to pipe method.</p>
<pre><code>df.pipe(converter,cols=df.A,types="str")
</code></pre>
<p>but it causes an error.</p>
<blockquote>
<p>AttributeError:'DataFrame' object has no attribute 'cols'</p>
</blockquote>
<p>How can I avoid this kind of error?</p>
| 1 |
2016-09-14T05:59:57Z
| 39,483,474 |
<p>You need add <code>[]</code> for select columns:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3,4]})
print (df)
A
0 1
1 2
2 3
3 4
def converter(df,cols,types):
df[cols]=df[cols].astype(types)
return df
print (converter(df, 'A', float))
A
0 1.0
1 2.0
2 3.0
3 4.0
</code></pre>
| 1 |
2016-09-14T06:04:46Z
|
[
"python",
"pandas",
"indexing",
"dataframe",
"casting"
] |
get_dummies split character
| 39,483,546 |
<p>I have data labelled which I need to apply one-hot-encoding: <code>'786.2'</code>, <code>'ICD-9-CM|786.2'</code>, <code>'ICD-9-CM'</code>, <code>'786.2b|V13.02'</code>, <code>'V13.02'</code>, <code>'279.12'</code>, <code>'ICD-9-CM|V42.81'</code> is labels. The <code>|</code> mean that the document have 2 labels at the same time. So I wrote the code like this:</p>
<pre><code>labels = np.asarray(label_docs)
labels = np.array([u'786.2', u'ICD-9-CM|786.2', u'|ICD-9-CM', u'786.2b|V13.02', u'V13.02', u'279.12', u'ICD-9-CM|V42.81|'])
df = pd.DataFrame(labels, columns=['label'])
labels = df['label'].str.get_dummies(sep='|')
</code></pre>
<p>and the result: </p>
<pre><code>279.12 786.2 786.2b ICD-9-CM V13.02 V42.81
0 0 1 0 0 0 0
1 0 1 0 1 0 0
2 0 0 0 1 0 0
3 0 0 1 0 1 0
4 0 0 0 0 1 0
5 1 0 0 0 0 0
6 0 0 0 1 0 1
</code></pre>
<p>However, now I only want 1 label for each document: </p>
<p><code>'ICD-9-CM|786.2'</code> is <code>'ICD-9-CM'</code>,</p>
<p><code>'ICD-9-CM|V42.81|'</code> is <code>'ICD-9-CM'</code>.</p>
<p>How could I do seperate by <code>get_dummies</code> like that?</p>
| 2 |
2016-09-14T06:10:17Z
| 39,483,690 |
<p>I think you need <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> and then select first item of list by <code>str[0]</code>:</p>
<pre><code>print (df.label.str.strip('|').str.split('|').str[0])
0 786.2
1 ICD-9-CM
2 ICD-9-CM
3 786.2b
4 V13.02
5 279.12
6 ICD-9-CM
Name: label, dtype: object
labels = df.label.str.strip('|').str.split('|').str[0].str.get_dummies()
print (labels)
279.12 786.2 786.2b ICD-9-CM V13.02
0 0 1 0 0 0
1 0 0 0 1 0
2 0 0 0 1 0
3 0 0 1 0 0
4 0 0 0 0 1
5 1 0 0 0 0
6 0 0 0 1 0
</code></pre>
<p>If in row with index <code>2</code> need no value, remove <code>str.strip</code>:</p>
<pre><code>print (df.label.str.split('|').str[0])
0 786.2
1 ICD-9-CM
2
3 786.2b
4 V13.02
5 279.12
6 ICD-9-CM
Name: label, dtype: object
labels = df.label.str.split('|').str[0].str.get_dummies(sep='|')
print (labels)
279.12 786.2 786.2b ICD-9-CM V13.02
0 0 1 0 0 0
1 0 0 0 1 0
2 0 0 0 0 0
3 0 0 1 0 0
4 0 0 0 0 1
5 1 0 0 0 0
6 0 0 0 1 0
</code></pre>
| 4 |
2016-09-14T06:20:28Z
|
[
"python",
"pandas",
"one-hot-encoding"
] |
How do I fix plotting my boxplot?
| 39,483,639 |
<p>I am trying to plot my boxplot but I am getting a 'nonetype attribute error.' </p>
<p>Please, how can I fix this? </p>
<p>My Code:</p>
<pre><code>Failed = train_df['Fees'][train_df['Passedornot'] == 0]
Passed = train_df['Fees'][train_df['Passedornot'] ==1]
average_fees = DataFrame([mean(Passed), mean(Failed)])
std_fees = DataFrame([standard_deviation(Passed), standard_deviation(Failed)])
fig, axis4 = plt.subplots(1,1)
train_df['Fees'].plot(kind='hist', figsize=(15,5),bins=100, xlim=(0,30), ax=axis4)
fig, axis5 = plt.subplots(1,1)
average_fees.plot(kind='', legend=False, ax=axis5)
</code></pre>
<p>Error:</p>
<pre><code>average_fees.plot(kind='bp', legend=False, ax=axis5)
AttributeError: 'NoneType' object has no attribute 'plot'
</code></pre>
<p>Sample of Data:</p>
<pre><code> Name Sex Age Score Passedornot Fees
Tim Cole male 18 148 1 90
Ellen James female 47 143 1 80
Jerome Miles male 62 144 0 80
Waltz Albert male 27 153 0 90
</code></pre>
| 1 |
2016-09-14T06:16:50Z
| 39,484,737 |
<p>Not sure what happens there, but I think your <code>average_fees</code> is not a proper pandas dataframe. Furthermore, my compiler is complaining about <code>kind='bp'</code>. That is one of the reasons why the community always asks for a fully functional working example.</p>
<p>Here is a working snippet for Python3, run in a Jupyter notebook, for the piece of data you provided saved to a file sample.txt:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
train_df = pd.read_csv('sample.txt', sep='\t')
# train_df.head()
Failed = train_df['Fees'][train_df['Passedornot'] == 0]
Passed = train_df['Fees'][train_df['Passedornot'] == 1]
average_fees = pd.DataFrame([np.mean(Passed), np.mean(Failed)])
std_fees = pd.DataFrame([np.std(Passed), np.std(Failed)])
fig1, axis4 = plt.subplots(1,1)
n, bins, patches = plt.hist(train_df.Fees, 100, linewidth=1)
plt.axis([0, 100, 0, 3])
plt.show()
fig2, axis5 = plt.subplots(1,1)
# print(type(average_fees))
average_fees.boxplot(return_type='axes')
</code></pre>
| 0 |
2016-09-14T07:26:17Z
|
[
"python",
"dataframe"
] |
Is using type as dictionary keys considered good practice in Python?
| 39,483,667 |
<p>I have a lookup table like this:</p>
<pre><code>lookup = {
"<class 'Minority.mixin'>": report_minority,
"<class 'Majority.mixin'>": report_majority,
}
def report(o):
h = lookup[str(type(o))]
h()
</code></pre>
<p>It looks awkward to me as the <code>key</code> is precariously linked to how <code>type()</code> returns and represents a <code>class</code> in <code>string</code>. If one day Python changes its way to represents <code>class</code> types in <code>string</code>, all the codes like this are broken. So I want to have some advice from pros, is such type of keys considered good or bad? Thanks.</p>
| 0 |
2016-09-14T06:19:09Z
| 39,484,819 |
<p>Take a look at that script, I don't think it's perfect but it works and I think it's more elegant than your solution :</p>
<pre><code>#!/usr/bin/env python3
class Person:
pass
def display_person():
print("Person !")
class Car:
pass
def display_car():
print("Car !")
lookup = {
Person: display_person,
Car: display_car
}
def report(o):
lookup[o.__class__]()
report(Person())
report(Car())
</code></pre>
<p>Edit : modification for Python3</p>
| 0 |
2016-09-14T07:31:10Z
|
[
"python",
"python-3.x",
"dictionary"
] |
Is using type as dictionary keys considered good practice in Python?
| 39,483,667 |
<p>I have a lookup table like this:</p>
<pre><code>lookup = {
"<class 'Minority.mixin'>": report_minority,
"<class 'Majority.mixin'>": report_majority,
}
def report(o):
h = lookup[str(type(o))]
h()
</code></pre>
<p>It looks awkward to me as the <code>key</code> is precariously linked to how <code>type()</code> returns and represents a <code>class</code> in <code>string</code>. If one day Python changes its way to represents <code>class</code> types in <code>string</code>, all the codes like this are broken. So I want to have some advice from pros, is such type of keys considered good or bad? Thanks.</p>
| 0 |
2016-09-14T06:19:09Z
| 39,487,963 |
<p>Just remove the <code>str</code> from the lookup and from the dictionary. So</p>
<pre><code>lookup = {
Minority.mixin : report_minority,
Majority.mixin : report_majority,
}
def report(o):
h = lookup[type(o)]
h()
</code></pre>
<p>This fixes your immediate concern and is fairly reasonable code. However, it seems like dispatching on the type is exactly what OO is for. So why not make those varying report functions methods on the <code>o</code> object derived from its type? Then you could just write:</p>
<pre><code>o.report()
</code></pre>
<p>and the correct variant would be obtained from the class.</p>
| 1 |
2016-09-14T10:18:44Z
|
[
"python",
"python-3.x",
"dictionary"
] |
Is using type as dictionary keys considered good practice in Python?
| 39,483,667 |
<p>I have a lookup table like this:</p>
<pre><code>lookup = {
"<class 'Minority.mixin'>": report_minority,
"<class 'Majority.mixin'>": report_majority,
}
def report(o):
h = lookup[str(type(o))]
h()
</code></pre>
<p>It looks awkward to me as the <code>key</code> is precariously linked to how <code>type()</code> returns and represents a <code>class</code> in <code>string</code>. If one day Python changes its way to represents <code>class</code> types in <code>string</code>, all the codes like this are broken. So I want to have some advice from pros, is such type of keys considered good or bad? Thanks.</p>
| 0 |
2016-09-14T06:19:09Z
| 39,488,179 |
<p>The question would more be <em>why are you doing this in the first place</em>? What advantage do <em>you</em> think using strings has?</p>
<p>Class objects are hashable, so you can use <code>Minority.mixin</code> and <code>Majority.mixin</code> <em>directly</em> as keys. And when you do so, you ensure that the key is <em>always</em> the exact same object provided your classes are globals in their respective modules, making them singletons your program. Moreover, there is no chance of accidental confusion when you later on refactor your code to rename modules and you end up with a <em>different</em> type with that exact <code>repr()</code> output.</p>
<p>So unless you have a specific usecase where you <em>can't</em> use the class directly, you should not be using the string representations.</p>
<p>(And even if you were to generate classes with a factory function, using a baseclass and <code>isinstance</code> checks or extracting a base class from the MRO would probably be preferable).</p>
<p>So, for your usecase, stick to:</p>
<pre><code>lookup = {
Minority.mixin: report_minority,
Majority.mixin: report_majority,
}
def report(o):
h = lookup[type(o)])
h()
</code></pre>
<p>Next, if you ensure that <code>report_minority</code> and <code>report_majority</code> are <em>functions</em> (and not methods, for example), you can use <a href="https://docs.python.org/3/library/functools.html#functools.singledispatch" rel="nofollow"><code>functools.singledispatch()</code></a> and dispense with your mapping altogether:</p>
<pre><code>from functools import singledispatch
@singledispatch
def report(o):
raise ValueError('Unhandled type {}'.format(type(o)))
@report.register(Minority.mixin)
def report_minority(o):
# handle a Minority instance
@report.register(Majority.mixin)
def report_majority(o):
# handle a Majority instance
</code></pre>
<p>Note that this won't work with methods, as methods have to take multiple arguments for dispatch to work, as they always take <code>self</code>.</p>
<p>Single-dispatch handles <em>subclasses</em> much better, unlike your <code>str</code>-based mapping or even the direct class mapping.</p>
| 2 |
2016-09-14T10:30:27Z
|
[
"python",
"python-3.x",
"dictionary"
] |
How to improve performance of pymongo queries
| 39,483,692 |
<p>I inherited an old Mongo database. Let's focus on the following two collections <em>(removed most of their content for better readability)</em>:</p>
<p>Collection user</p>
<pre><code>db.user.find_one({"email": "user@host.com"})
{'lastUpdate': datetime.datetime(2016, 9, 2, 11, 40, 13, 160000),
'creationTime': datetime.datetime(2016, 6, 23, 7, 19, 10, 6000),
'_id': ObjectId('576b8d6ee4b0a37270b742c7'),
'email': 'user@host.com' }
</code></pre>
<p>Collections entry (one user to many entries):</p>
<pre><code>db.entry.find_one({"userId": _id})
{'date_entered': datetime.datetime(2015, 2, 7, 0, 0),
'creationTime': datetime.datetime(2015, 2, 8, 14, 41, 50, 701000),
'lastUpdate': datetime.datetime(2015, 2, 9, 3, 28, 2, 115000),
'_id': ObjectId('54d775aee4b035e584287a42'),
'userId': '576b8d6ee4b0a37270b742c7',
'data': 'test'}
</code></pre>
<p><em>As you can see, there is no DBRef between the two.</em></p>
<p>What I would like to do is to count the total number of entries, and the number of entries updated after a given date. </p>
<p>To do this I used Python's pymongo library. The code below gets me what I need, but it is painfully slow.</p>
<pre><code>from pymongo import MongoClient
client = MongoClient('mongodb://foobar/')
db = client.userdata
# First I need to fetch all user ids. Otherwise db cursor will time out after some time.
user_ids = [] # build a list of tuples (email, id)
for user in db.user.find():
user_ids.append( (user['email'], str(user['_id'])) )
date = datetime(2016, 1, 1)
for user_id in user_ids:
email, _id = user_id
t0 = time.time()
query = {"userId": _id}
no_of_all_entries = db.entry.find(query).count()
query = {"userId": _id, "lastUpdate": {"$gte": date}}
no_of_entries_this_year = db.entry.find(query).count()
t1 = time.time()
print("delay ", round(t1 - t0, 2))
print(email, no_of_all_entries, no_of_entries_this_year)
</code></pre>
<p>It takes around 0.83 second to run both <code>db.entry.find</code> queries on my laptop, and 0.54 on an AWS server (not the MongoDB server).</p>
<p>Having ~20000 users it takes painful 3 hours to get all the data.
Is that the kind of latency you'd expect to see in Mongo ? What can I do to improve this ? Bear in mind that MongoDB is fairly new to me.</p>
| 0 |
2016-09-14T06:20:40Z
| 39,485,092 |
<p>Instead of running two aggregates for all users separately you can just get both aggregates for all users with <a href="http://api.mongodb.com/python/current/examples/aggregation.html" rel="nofollow"><code>db.collection.aggregate()</code></a>.</p>
<p>And instead of a <code>(email, userId)</code> tuples we make it a dictionary as it is easier to use to get the corresponding email.</p>
<pre><code>user_emails = {str(user['_id']): user['email'] for user in db.user.find()}
date = datetime(2016, 1, 1)
entry_counts = db.entry.aggregate([
{"$group": {
"_id": "$userId",
"count": {"$sum": 1},
"count_this_year": {
"$sum": {
"$cond": [{"$gte": ["$lastUpdate", date]}, 1, 0]
}
}
}}
])
for entry in entry_counts:
print(user_emails.get(entry['_id']),
entry['count'],
entry['count_this_year'])
</code></pre>
<p>I'm pretty sure getting the user's email address into the result could be done but I'm not a mongo expert either.</p>
| 1 |
2016-09-14T07:46:23Z
|
[
"python",
"mongodb",
"python-3.x",
"pymongo",
"pymongo-3.x"
] |
How to write numpy arrays to .txt file, starting at a certain line?
| 39,483,774 |
<p>I need to write 3 numpy arrays into a txt file. The head of the file looks like that:</p>
<pre><code>#Filexy
#time operation1 operation2
</code></pre>
<p>The numpy arrays look like the following:</p>
<pre><code>time = np.array([0,60,120,180,...])
operation1 = np.array([12,23,68,26,...)]
operation2 = np.array([100,123,203,301,...)]
</code></pre>
<p>In the end, the .txt file should look like this (delimiter should be a tab):</p>
<pre><code>#Filexy
#time operation1 operation2
0 12 100
60 23 123
120 68 203
180 26 301
.. ... ...
</code></pre>
<p>I tried it with "numpy.savetxt" - but I did not get the format that I want.</p>
<p>Thank you very much for your help!</p>
| 5 |
2016-09-14T06:27:06Z
| 39,483,844 |
<p>Try this:</p>
<pre><code>f = open(name_of_the_file, "a")
np.savetxt(f, data, newline='\n')
f.close()
</code></pre>
| 0 |
2016-09-14T06:32:28Z
|
[
"python",
"numpy",
"writetofile"
] |
How to write numpy arrays to .txt file, starting at a certain line?
| 39,483,774 |
<p>I need to write 3 numpy arrays into a txt file. The head of the file looks like that:</p>
<pre><code>#Filexy
#time operation1 operation2
</code></pre>
<p>The numpy arrays look like the following:</p>
<pre><code>time = np.array([0,60,120,180,...])
operation1 = np.array([12,23,68,26,...)]
operation2 = np.array([100,123,203,301,...)]
</code></pre>
<p>In the end, the .txt file should look like this (delimiter should be a tab):</p>
<pre><code>#Filexy
#time operation1 operation2
0 12 100
60 23 123
120 68 203
180 26 301
.. ... ...
</code></pre>
<p>I tried it with "numpy.savetxt" - but I did not get the format that I want.</p>
<p>Thank you very much for your help!</p>
| 5 |
2016-09-14T06:27:06Z
| 39,483,874 |
<p>I'm not sure what you tried, but you need to use the <code>header</code> parameter in <code>np.savetxt</code>. Also, you need to concatenate your arrays properly. The easiest way to do this is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html" rel="nofollow"><code>np.c_</code></a>, which forces your 1D-arrays into 2D-arrays, and then concatenates them the way you expect.</p>
<pre><code>>>> time = np.array([0,60,120,180])
>>> operation1 = np.array([12,23,68,26])
>>> operation2 = np.array([100,123,203,301])
>>> np.savetxt('example.txt', np.c_[time, operation1, operation2],
header='Filexy\ntime operation1 operation2', fmt='%d',
delimiter='\t')
</code></pre>
<p><code>example.txt</code> now contains:</p>
<pre><code># Filexy
# time operation1 operation2
0 12 100
60 23 123
120 68 203
180 26 301
</code></pre>
<p>Also note the usage of <code>fmt='%d'</code> to get integer values in the output. <code>savetxt</code> will save as float by default, even for an integer array.</p>
<p>Regarding the delimiter, you just need to use the <code>delimiter</code> argument. It's not clear here, but there are, in fact, tabs between the columns. For instance, <code>vim</code> shows me tabs using dots:</p>
<pre><code># Filexy
# time operation1 operation2
0· 12· 100
60· 23· 123
120·68· 203
180·26· 301
</code></pre>
<p><strong>Addendum:</strong></p>
<p>If you want to add headers <em>and</em> add an extra line before the arrays, you are better off creating a custom header, complete with your own comment characters. Use the <code>comment</code> argument to prevent <code>savetxt</code> from adding extra <code>#</code>'s.</p>
<pre><code>>>> extra_text = 'Answer to life, the universe and everything = 42'
>>> header = '# Filexy\n# time operation1 operation2\n' + extra_text
>>> np.savetxt('example.txt', np.c_[time, operation1, operation2],
header=header, fmt='%d', delimiter='\t', comments='')
</code></pre>
<p>which produces</p>
<pre><code># Filexy
# time operation1 operation2
Answer to life, the universe and everything = 42
0 12 100
60 23 123
120 68 203
180 26 301
</code></pre>
| 4 |
2016-09-14T06:34:11Z
|
[
"python",
"numpy",
"writetofile"
] |
Python: Acessing each frame within a while loop
| 39,483,882 |
<p>In Psychopy/Python: within a while loop, I need to read in some information (using pyserial) and append it to a list on every frame. </p>
<pre><code>t = trialClock.getTime()
while True:
line = ser.readline() #read in line
if line:
lines.append(line) #append to list
...
</code></pre>
<p>How can I access each frame using the trial clock? I need to read a line and append to the list every 0.016ms (60hz).</p>
<p>Thanks
Steve</p>
| 0 |
2016-09-14T06:35:03Z
| 39,484,026 |
<p>You need to have a:</p>
<pre><code>win.flip()
</code></pre>
<p>at the end of your code within the while loop so that the loop only iterates once per frame refresh. i.e. the code pauses at that point until the screen is actually redrawn, limiting your loop to 60 Hz (assuming your screen refreshes at that rate).</p>
<p>That way, you are using very precise hardware timing, rather than using a software timer.</p>
| 0 |
2016-09-14T06:44:07Z
|
[
"python",
"psychopy"
] |
MATLAB sort() vs Numpy argsort() - how to match results?
| 39,484,073 |
<p>I'm porting a MATLAB code to Python's Numpy.</p>
<p>In MATLAB (Octave, actually), I have something like:</p>
<pre><code>>> someArr = [9, 8, 7, 7]
>> [~, ans] = sort(someArr, 'descend')
ans =
1 2 3 4
</code></pre>
<p>So in Numpy I'm doing:</p>
<pre><code>>>> someArr = np.array([9, 8, 7, 7])
>>> np.argsort(someArr)[::-1]
array([0, 1, 3, 2])
</code></pre>
<p>I got <code>1, 2, 3, 4</code> in MATLAB while <code>0, 1, 3, 2</code> on Numpy, and I need <code>0, 1, 2, 3</code> on Numpy. </p>
<p>I believe it due to the sorting algorithm used in each function, But I checked and it looks like both are using "quicksort" (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow">here</a> and <a href="https://www.mathworks.com/matlabcentral/answers/96656-what-type-of-sort-does-the-sort-function-in-matlab-perform" rel="nofollow">here</a>). </p>
<p>How can I match the Numpy's solution to the MATLAB one?</p>
| 1 |
2016-09-14T06:46:17Z
| 39,484,418 |
<p>You can choose between different sorting algorithms. Changing it to <code>heapsort</code> worked for me:</p>
<pre><code>>> np.argsort(someArr, kind="heapsort")[::-1]
array([0, 1, 2, 3], dtype=int32)
</code></pre>
<p>Edit: This only works for a few test cases I looked at. For <code>[9, 8, 7, 7, 4, 1, 1]</code> it stops working. My answer is probably not a good solution.</p>
| 0 |
2016-09-14T07:08:46Z
|
[
"python",
"matlab",
"sorting",
"numpy"
] |
MATLAB sort() vs Numpy argsort() - how to match results?
| 39,484,073 |
<p>I'm porting a MATLAB code to Python's Numpy.</p>
<p>In MATLAB (Octave, actually), I have something like:</p>
<pre><code>>> someArr = [9, 8, 7, 7]
>> [~, ans] = sort(someArr, 'descend')
ans =
1 2 3 4
</code></pre>
<p>So in Numpy I'm doing:</p>
<pre><code>>>> someArr = np.array([9, 8, 7, 7])
>>> np.argsort(someArr)[::-1]
array([0, 1, 3, 2])
</code></pre>
<p>I got <code>1, 2, 3, 4</code> in MATLAB while <code>0, 1, 3, 2</code> on Numpy, and I need <code>0, 1, 2, 3</code> on Numpy. </p>
<p>I believe it due to the sorting algorithm used in each function, But I checked and it looks like both are using "quicksort" (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow">here</a> and <a href="https://www.mathworks.com/matlabcentral/answers/96656-what-type-of-sort-does-the-sort-function-in-matlab-perform" rel="nofollow">here</a>). </p>
<p>How can I match the Numpy's solution to the MATLAB one?</p>
| 1 |
2016-09-14T06:46:17Z
| 39,484,419 |
<p>In order to make this work, we need to be a little bit clever. <code>numpy</code> doesn't have the <code>'descend'</code> analog. You're mimicking it by reversing the results of the sort (which is ultimately you're undoing).</p>
<p>I'm not sure how <code>matlab</code> accomplishes it, but they claim to use a <a href="http://www.mathworks.com/company/newsletters/articles/an-adventure-of-sortsbehind-the-scenes-of-a-matlab-upgrade.html" rel="nofollow">stable variant of quicksort</a>. Specifically, for descending sorts:</p>
<blockquote>
<p>If the flag is 'descend', the output is reversed just before being returned. After the reversal, we ran the index vector sorts to restore stability.</p>
</blockquote>
<p>It appears that <code>octave</code> follows suit here.</p>
<p>Since their sort is stable, you have the guarantee that the order of equal values in the input will be preserved in the output. <code>numpy</code> on the other hand makes no such guarantees for it's quicksort. If we want a stable sort in numpy, we need to use <code>mergesort</code>:</p>
<pre><code>>>> np.argsort(someArr, kind='mergesort')
array([2, 3, 1, 0])
</code></pre>
<p>Ok, this output makes sense. <code>someArr[2] == someArr[3]</code> and the third element comes before the fourth so it is sensible that <code>2</code> would be before <code>3</code> in the output (without a guaranteed stable sorting algorithm, we couldn't make this claim). Now comes the clever stepping... You want the "descending" values, but rather than reversing the output of <code>argsort</code>, why don't we negate the input? That will have the effect of larger numbers sorting before than their lower counterparts just as a descending sort would do...</p>
<pre><code>>>> np.argsort(-someArr, kind='quicksort')
array([0, 1, 2, 3])
</code></pre>
<p>Now we're talkin! And since mergesort is guaranteed to be stable, elements (with equal values) which appear at lower indices will appear in the output first -- Just like matlab/octave. Nice.</p>
| 3 |
2016-09-14T07:08:46Z
|
[
"python",
"matlab",
"sorting",
"numpy"
] |
setting distances between (labels, values)
| 39,484,247 |
<p>I have to mention that I am a beginner by dealing with data frames, and I am grateful for any tips :)</p>
<p>I have a dataframe contains names of files and their sizes (~8000 records). I am trying to figure out which bunch of files can be deleted or moved. so I tried to plot names vs. size.</p>
<p><strong>the problem:</strong></p>
<p>The labels and (most probably the lines are also overlapping, even when i used <code>linewidth</code> property)</p>
<p>basically, the code I used</p>
<pre><code>>>> g = sns.barplot(y='size',x='files',data=df)
>>> for item in g.get_xticklabels():
... item.set_rotation(45)
</code></pre>
<p>the resuls
<a href="http://i.stack.imgur.com/mXL9c.png" rel="nofollow"><img src="http://i.stack.imgur.com/mXL9c.png" alt="enter image description here"></a></p>
<p>the code with the <code>linewidth</code> property on samller sample </p>
<pre><code>>>> g = sns.barplot(y='size',x='files',data=dfs, linewidth=2)
>>> for item in g.get_xticklabels():
... item.set_rotation(90)
</code></pre>
<p>the result
<a href="http://i.stack.imgur.com/1ff1p.png" rel="nofollow"><img src="http://i.stack.imgur.com/1ff1p.png" alt="enter image description here"></a></p>
<p>I am using python3.5 and OS 10.11.6</p>
| 0 |
2016-09-14T06:58:12Z
| 39,486,130 |
<p>As I said in the comments, I don't think a graph is the best way to do this. I would start by simplifying the dataframe to get the average size of each file:</p>
<pre><code>average_size = df.groupby('files')['size'].mean()
</code></pre>
<p>You can then get the top 10 files (for instance) with:</p>
<pre><code>average_size.nlargest(10, columns='size')
</code></pre>
| 2 |
2016-09-14T08:45:38Z
|
[
"python",
"database",
"pandas",
"seaborn"
] |
Python - How to sum all combinations of a list of numbers in order to reach a goal. Use of number is optional
| 39,484,255 |
<p>I have a list of numbers</p>
<pre><code>lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
</code></pre>
<p>that I would like to sum in various ways in order to try and reach the goal number of 8276. I also need to see whether throwing away the cents or rounding helps reaching the goal. Note that use of a number is optional.</p>
<p>I tried </p>
<pre><code>from itertools import combinations
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
for i in xrange(1, len(lis) + 1): #xrange will return the values 1,2,3,4 in this loop
if sum(list(combinations(lis, i))) == 8276:
print list(combinations(lis, i))
</code></pre>
<p>but this gives me </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
</code></pre>
<p>which I'm not sure why or how to fix.</p>
| 1 |
2016-09-14T06:58:50Z
| 39,484,348 |
<p>You're trying to sum all the combinations with given length instead of calculating a sum of a single combination. Instead you should loop over the combinations and check the sum for each one:</p>
<pre><code>from itertools import combinations
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
for i in xrange(1, len(lis) + 1):
for comb in combinations(lis, i):
if sum(comb) == 8276:
print comb
</code></pre>
<p>The reason for the specific error is that <a href="https://docs.python.org/2.7/library/functions.html#sum" rel="nofollow"><code>sum</code></a> takes optional argument <code>start</code> which is the default value. If argument is not provided it defaults to <code>0</code>. Essentially your original code is trying to do following:</p>
<pre><code>>>> sum([(1,), (2,)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
</code></pre>
| 3 |
2016-09-14T07:04:25Z
|
[
"python",
"sum",
"combinations",
"permutation"
] |
Python - How to sum all combinations of a list of numbers in order to reach a goal. Use of number is optional
| 39,484,255 |
<p>I have a list of numbers</p>
<pre><code>lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
</code></pre>
<p>that I would like to sum in various ways in order to try and reach the goal number of 8276. I also need to see whether throwing away the cents or rounding helps reaching the goal. Note that use of a number is optional.</p>
<p>I tried </p>
<pre><code>from itertools import combinations
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
for i in xrange(1, len(lis) + 1): #xrange will return the values 1,2,3,4 in this loop
if sum(list(combinations(lis, i))) == 8276:
print list(combinations(lis, i))
</code></pre>
<p>but this gives me </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
</code></pre>
<p>which I'm not sure why or how to fix.</p>
| 1 |
2016-09-14T06:58:50Z
| 39,485,563 |
<p>Since you mention:</p>
<blockquote>
<p>I also need to see whether throwing away the cents or rounding helps reaching the goal. </p>
</blockquote>
<p>..the code below will show the closest n- combinations, and the absolute difference they show to the targeted number. </p>
<p>Works on both <code>python3</code>and <code>python2</code></p>
<pre><code>from itertools import combinations
# set the number of closest combinations to show, the targeted number and the list
show = 5
target = 8276
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
diffs = []
for n in range(1, len(lis)+1):
numbers = combinations(lis, n)
# list the combinations and their absolute difference to target
for combi in numbers:
diffs.append([combi, abs(target - sum(combi))])
diffs.sort(key=lambda x: x[1])
for item in diffs[:show]:
print(item[0], round(item[1],10))
</code></pre>
<p>The output will show the top- n closest combinations (combination / absolute difference to the targeted number):</p>
<pre class="lang-none prettyprint-override"><code>(5084, 3298.85) 106.85
(10, 5084, 3298.85) 116.85
(5084, 156.43, 3298.85) 263.28
(10, 5084, 156.43, 3298.85) 273.28
(5084, 381.3, 3298.85) 488.15
</code></pre>
<p>This shows that the closest you can get is <code>(5084, 3298.85)</code>, showing a difference of <code>106.85</code>.</p>
<hr>
<h3>Note</h3>
<p>See btw <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">Note on floating point calculation</a>:</p>
<hr>
<h2>Edit</h2>
<p>For the sport of it, a condensed version of the above script:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import combinations
# set the number of closest combinations to show, the targeted number and the list
show = 5
target = 8276
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
diffs = [item for sublist in [[
[combi, abs(target - sum(combi))] for combi in combinations(lis, n)
] for n in range(1, len(lis)+1)] for item in sublist]
diffs.sort(key=lambda x: x[1])
[print(item[0], round(item[1],10)) for item in diffs[:show]]
</code></pre>
| 1 |
2016-09-14T08:13:51Z
|
[
"python",
"sum",
"combinations",
"permutation"
] |
Python - How to sum all combinations of a list of numbers in order to reach a goal. Use of number is optional
| 39,484,255 |
<p>I have a list of numbers</p>
<pre><code>lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
</code></pre>
<p>that I would like to sum in various ways in order to try and reach the goal number of 8276. I also need to see whether throwing away the cents or rounding helps reaching the goal. Note that use of a number is optional.</p>
<p>I tried </p>
<pre><code>from itertools import combinations
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
for i in xrange(1, len(lis) + 1): #xrange will return the values 1,2,3,4 in this loop
if sum(list(combinations(lis, i))) == 8276:
print list(combinations(lis, i))
</code></pre>
<p>but this gives me </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
</code></pre>
<p>which I'm not sure why or how to fix.</p>
| 1 |
2016-09-14T06:58:50Z
| 39,507,297 |
<p>Here is a solution if you want to consider the cases where you can throw away the cents, or you can round to the nearest whole number. This requirement turned a simple solution to a pretty complicated one. In order to account for the above requirement, I expanded each number to include the additional possible cases. The expanded list shows the new list to get the combinations:</p>
<pre><code>import math
import itertools as it
tolerance = 150
target_sum = 8392
found = False
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
def add_throw_and_round(num):
num_list = [num]
if int(num) != float(num):
num_list.append(math.floor(num))
if round(num) not in num_list:
num_list.append(round(num))
return sorted(num_list)
lis_expanded = map(add_throw_and_round, lis)
print "Expanded list:\n", lis_expanded, "\n\nTarget sum:\n", target_sum, "\n"
for n in range(1,len(lis) + 1): # n is number of summands in pick
lis_combos = it.combinations(lis_expanded, n)
for lis_combo_n in lis_combos:
for combo_n in (it.product(*lis_combo_n)):
sum_ = sum(combo_n)
if sum_ == target_sum:
found = True
answer = combo_n
if sum_ > target_sum - tolerance and sum_ < target_sum + tolerance:
print "sum:", sum_, "\tCombination: ", combo_n
if found:
print "\nThere is a match: ", answer
else:
print "\nNo exact match found"
</code></pre>
<p>So I decided to show all sums that was within 150 of the target sum, just to see if it was working. There were no matches were the sum was exactly 8276:</p>
<pre><code>>>>
===== RESTART: C:/Users/Joe/Desktop/scripts/Stack_overflow/cents_py2.py =====
Expanded list:
[[497.0, 497.96, 498.0], [10], [5084], [156.0, 156.43], [381.0, 381.3], [3298.0, 3298.85, 3299.0], [625.0, 625.68, 626.0]]
Target sum:
8276
sum: 8382.0 Combination: (5084, 3298.0)
sum: 8382.85 Combination: (5084, 3298.85)
sum: 8383.0 Combination: (5084, 3299.0)
sum: 8392.0 Combination: (10, 5084, 3298.0)
sum: 8392.85 Combination: (10, 5084, 3298.85)
sum: 8393.0 Combination: (10, 5084, 3299.0)
No exact match found
>>>
</code></pre>
<p>Notice above that it tests cases where cents are thrown out, and rounded.
Just to test whether it will report a match when the target sum does match, I tried target_sum = 8392 because the output shows one combination should match it. So here is the output in that case:</p>
<pre><code>>>>
===== RESTART: C:/Users/Joe/Desktop/scripts/Stack_overflow/cents_py2.py =====
Expanded list:
[[497.0, 497.96, 498.0], [10], [5084], [156.0, 156.43], [381.0, 381.3], [3298.0, 3298.85, 3299.0], [625.0, 625.68, 626.0]]
Target sum:
8392
sum: 8382.0 Combination: (5084, 3298.0)
sum: 8382.85 Combination: (5084, 3298.85)
sum: 8383.0 Combination: (5084, 3299.0)
sum: 8392.0 Combination: (10, 5084, 3298.0)
sum: 8392.85 Combination: (10, 5084, 3298.85)
sum: 8393.0 Combination: (10, 5084, 3299.0)
sum: 8538.0 Combination: (5084, 156.0, 3298.0)
sum: 8538.85 Combination: (5084, 156.0, 3298.85)
sum: 8539.0 Combination: (5084, 156.0, 3299.0)
sum: 8538.43 Combination: (5084, 156.43, 3298.0)
sum: 8539.28 Combination: (5084, 156.43, 3298.85)
sum: 8539.43 Combination: (5084, 156.43, 3299.0)
There is a match: (10, 5084, 3298.0)
>>>
</code></pre>
| 0 |
2016-09-15T09:17:22Z
|
[
"python",
"sum",
"combinations",
"permutation"
] |
Matrices addition in numpy
| 39,484,262 |
<p>I need to calculate the sum of a list of matrices, however, I can't use <code>np.sum</code>, even with <code>axis=0</code>, I don't know why. The current solution is a loop, but is there a better way for that? </p>
<pre><code>import numpy as np
SAMPLE_SIZES = [10, 100, 1000, 10000]
ITERATIONS = 1
MEAN = np.array([1, 1])
COVARIANCE = np.array([[1, 0.5], [0.5, 1]])
for sample_size in SAMPLE_SIZES:
max = -1
for i in range(ITERATIONS):
xs = np.random.multivariate_normal(MEAN, COVARIANCE, size=sample_size)
sigma = [[0, 0], [0, 0]]
for x in xs:
sigma += np.outer((x-MEAN), (x-MEAN)) / (sample_size-1)
</code></pre>
<p>In the code above, can I replace the last loop using some <code>numpy</code> function? I guess using a loop would be not efficient if the data is very large.</p>
| 1 |
2016-09-14T06:59:23Z
| 39,494,065 |
<p>If you just want to compute the empirical covariance then I would suggest using <code>numpy.cov(xs.T)</code>. </p>
<p>Otherwise, the last 3 lines can be replaced by:</p>
<pre><code>xm = xs - np.mean(xs, axis=0)
sigma = np.inner(xm.T. xm.T) / (sample_size-1)
</code></pre>
| 0 |
2016-09-14T15:15:02Z
|
[
"python",
"numpy"
] |
Matrices addition in numpy
| 39,484,262 |
<p>I need to calculate the sum of a list of matrices, however, I can't use <code>np.sum</code>, even with <code>axis=0</code>, I don't know why. The current solution is a loop, but is there a better way for that? </p>
<pre><code>import numpy as np
SAMPLE_SIZES = [10, 100, 1000, 10000]
ITERATIONS = 1
MEAN = np.array([1, 1])
COVARIANCE = np.array([[1, 0.5], [0.5, 1]])
for sample_size in SAMPLE_SIZES:
max = -1
for i in range(ITERATIONS):
xs = np.random.multivariate_normal(MEAN, COVARIANCE, size=sample_size)
sigma = [[0, 0], [0, 0]]
for x in xs:
sigma += np.outer((x-MEAN), (x-MEAN)) / (sample_size-1)
</code></pre>
<p>In the code above, can I replace the last loop using some <code>numpy</code> function? I guess using a loop would be not efficient if the data is very large.</p>
| 1 |
2016-09-14T06:59:23Z
| 39,496,912 |
<p>Read up about numpy <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a>.</p>
<pre><code>xs = np.random.multivariate_normal(MEAN, COVARIANCE, size=sample_size)
</code></pre>
<p><code>xs</code> now has shape <code>(sample_size, 2)</code>, which means you can just subtract <code>MEAN</code> directly. You now need to take the outer product between <code>xs - MEAN</code> and <code>xs - MEAN</code> while adding over the <code>sample_size</code> axis. This is best done using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>:</p>
<pre><code>>>> sigma = np.einsum('ij,ik->jk', xs - MEAN, xs - MEAN) / sample_size
>>> sigma
array([[ 1.00216043, 0.49549231],
[ 0.49549231, 1.00004423]])
</code></pre>
<p>An alternative is to use broadcasting:</p>
<pre><code>>>> sigma = np.sum((xs - MEAN)[:, :, np.newaxis]
* (xs - MEAN)[:, np.newaxis, :], axis=0) / sample_size
</code></pre>
<p>Though the broadcasting solution seems easier to understand, <code>np.einsum</code> will usually be <a href="http://stackoverflow.com/a/39482794/525169">more efficient</a> than broadcasting.</p>
<p><strong>Additional note:</strong> Note that I've divided by <code>sample_size</code>, and not by <code>sample_size - 1</code>. This is because for estimating the covariance matrix of a random variable with known mean, you need to divide by <code>sample_size</code>. Use <code>sample_size - 1</code> when you are estimating the mean from the same dataset as well, and using it in your covariance estimate. Otherwise your covariance estimate will be biased.</p>
| 3 |
2016-09-14T18:04:09Z
|
[
"python",
"numpy"
] |
Why does spark-submit in YARN cluster mode not find python packages on executors?
| 39,484,389 |
<p>I am running a <code>boo.py</code> script on AWS EMR using <code>spark-submit</code> (Spark 2.0).</p>
<p>The file finished successfully when I use</p>
<pre><code>python boo.py
</code></pre>
<p>However, it failed when I run</p>
<pre><code>spark-submit --verbose --deploy-mode cluster --master yarn boo.py
</code></pre>
<p>The log on <code>yarn logs -applicationId ID_number</code> shows:</p>
<pre><code>Traceback (most recent call last):
File "boo.py", line 17, in <module>
import boto3
ImportError: No module named boto3
</code></pre>
<p>The <code>python</code> and <code>boto3</code> module I am using is </p>
<pre><code>$ which python
/usr/bin/python
$ pip install boto3
Requirement already satisfied (use --upgrade to upgrade): boto3 in /usr/local/lib/python2.7/site-packages
</code></pre>
<p>How do I append this library path so that <code>spark-submit</code> could read the <code>boto3</code> module?</p>
| 3 |
2016-09-14T07:06:38Z
| 39,484,684 |
<p>When you are running spark, part of the code is running on the driver, and part is running on the executors.</p>
<p>Did you install boto3 on the driver only, or on driver + all executors (nodes) which might run your code?</p>
<p>One solution might be - to install boto3 on all executors (nodes)</p>
<p><strong>how to install python modules on Amazon EMR nodes</strong>:</p>
<p><a href="http://stackoverflow.com/questions/31525012/how-to-bootstrap-installation-of-python-modules-on-amazon-emr">How to bootstrap installation of Python modules on Amazon EMR?</a></p>
| 2 |
2016-09-14T07:23:07Z
|
[
"python",
"apache-spark",
"pyspark"
] |
CSV file creation error in python
| 39,484,395 |
<p>I am getting some error while writing contents to csv file in python</p>
<pre><code>import sys
reload(sys)
sys.setdefaultencoding('utf8')
import csv
a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']]
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
</code></pre>
<p>Error</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 10, in <module>
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
IOError: [Errno 2] No such file or directory: 'test_1/1/2013_.csv'
</code></pre>
<p>How to fix it and what is the error?</p>
| 0 |
2016-09-14T07:06:52Z
| 39,484,546 |
<p>You have error message - just read it.
The file test_1/1/2013_.csv doesn't exist.</p>
<p>In the file name that you create - you use a[0][0] and in this case it result in 1/1/2013.
Probably this two signs '/' makes that you are looking for this file in bad directory.
Check where are this file (current directory - or in .test_1/1 directory.</p>
| 1 |
2016-09-14T07:15:58Z
|
[
"python",
"csv"
] |
CSV file creation error in python
| 39,484,395 |
<p>I am getting some error while writing contents to csv file in python</p>
<pre><code>import sys
reload(sys)
sys.setdefaultencoding('utf8')
import csv
a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']]
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
</code></pre>
<p>Error</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 10, in <module>
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
IOError: [Errno 2] No such file or directory: 'test_1/1/2013_.csv'
</code></pre>
<p>How to fix it and what is the error?</p>
| 0 |
2016-09-14T07:06:52Z
| 39,484,788 |
<p>It's probably due to the directory not existing - Python will create the file for you if it doesn't exist already, but it won't automatically create directories.</p>
<p>To ensure the path to a file exists you can combine <a href="https://docs.python.org/3/library/os.html#os.makedirs" rel="nofollow">os.makedirs</a> and <a href="https://docs.python.org/3/library/os.path.html#os.path.dirname" rel="nofollow">os.path.dirname</a>.</p>
<pre><code>file_name = 'test_'+str(a[0][0])+'_.csv'
# Get the directory the file resides in
directory = os.path.dirname(file_name)
# Create the directories
os.makedirs(directory)
# Open the file
f3 = open(file_name, 'at')
</code></pre>
<p>If the directories aren't desired you should replace the slashes in the dates with something else, perhaps a dash (<code>-</code>) instead.</p>
<pre><code>file_name = 'test_' + str(a[0][0]).replace('/', '-') + '_.csv'
</code></pre>
| 0 |
2016-09-14T07:29:02Z
|
[
"python",
"csv"
] |
Python csv reader multi-character quotechar?
| 39,484,436 |
<p>I am dealing with Concordance loadfiles and have to edit them and thus I am using Python for that. The columns are delimited by the pilcrow char <code>¶</code> and have <code>þ</code> as the quotechar.</p>
<p>The problem is the quotechar, the csv module in python only accepts a single-char quote (there is no issue when I write a csv file).</p>
<p>Question: how can I read a CSV file in Python where the quotechar is multi-character?</p>
<p>Example of the CSV fle:</p>
<pre><code>þcol_1þ¶þcol_2þ¶þcol_3þ¶þcol_4þ
</code></pre>
| 0 |
2016-09-14T07:09:28Z
| 39,484,696 |
<p>The Concordance file format is 8-bit encoded, and the <code>¶</code> and <code>þ</code> characters are encoded in Latin-1, really. That means they are encoded to binary values 0xB6 and 0xFE, respectively.</p>
<p>The Python 2 <code>csv</code> module accepts those bytes quite happily:</p>
<pre><code>csv.reader(fileobj, delimiter='\xb6', quotechar='\xfe')
</code></pre>
<p>As usual for the <code>csv</code> module, make sure to open the file in binary mode to leave newline handling to the module.</p>
<p>In Python 3, open the file in text mode with <code>newline=''</code> and <code>encoding='latin1'</code>, and either use the above <code>\xhh</code> escapes or the actual characters, so <code>delimiter='¶', quotechar='þ'</code>.</p>
| 2 |
2016-09-14T07:23:54Z
|
[
"python",
"csv"
] |
are set of strings all substrings of another set
| 39,484,571 |
<p>I have many sets of strings and wish to test them against sets of substrings. I wish to identify which sets contain all of the substrings.</p>
<pre><code>set1 = {'A123', 'B234', 'C345'}
set2 = {'A123', 'F234', 'H345'}
substring_set1 = {'A', 'B'}
</code></pre>
<p>So something like this in pseudocode:</p>
<pre><code>all(substring_set1.areSubstrings(set1))
True
all(substring_set1.areSubstrings(set2)
False
</code></pre>
<p>Or something like this maybe?</p>
<pre><code>if all(x in v for v in set1 for x in substring_set1):
do stuff
</code></pre>
<p>I guess I could go about it with an array of for loops, but I feel there probably is a cleaner way of doing this. Any suggestions? Thanks!</p>
| 0 |
2016-09-14T07:16:57Z
| 39,485,276 |
<p>The following approach looks clean enough to me:</p>
<pre><code>>>> all(any(x in v for v in set1) for x in substring_set1)
True
>>> all(any(x in v for v in set2) for x in substring_set1)
False
</code></pre>
| 3 |
2016-09-14T07:57:21Z
|
[
"python",
"python-3.x"
] |
How to assign data array to a variable whos name is stored within another array?
| 39,484,712 |
<p>I have a series of loops set-up which each create an array of arrays, and where the sub-array contains two variable names and two data arrays.</p>
<p>For example:</p>
<pre><code>r1_radial_ZZ = np.array([ ["cCoh_AB", "Var_AB", trA_z.data, trB_z.data],
["cCoh_AC", "Var_AC", trA_z.data, trC_z.data],
["cCoh_AD", "Var_AD", trA_z.data, trD_z.data],
["cCoh_AE", "Var_AE", trA_z.data, trE_z.data],
["cCoh_AF", "Var_AF", trA_z.data, trF_z.data],
["cCoh_AG", "Var_AG", trA_z.data, trG_z.data] ], dtype=object)
</code></pre>
<p>The data arrays <code>trX_z.data</code> contained in the first array <code>r1_radial_ZZ</code> are then processed with another function which returns two more data arrays, the coherencey and variance, for which I want to assign the variable names using the strings <code>cCoh_XX</code> and <code>Var_XX</code> from the first array <code>r1_radial_ZZ</code>.</p>
<p>The code I currently have to do this is as follows:</p>
<pre><code> for i in range(r1_radial_ZZ.shape[0]):
cCoh_ens_freq, r1_radial_ZZ[i,0], r1_radial_ZZ[i,1] = scpw.coherency_ensemble(r1_radial_ZZ[i,2], r1_radial_ZZ[i,3])
</code></pre>
<p>Where the function <code>scpw.coherency_ensemble</code> returns some three arrays, the first of which I assign to the variable <code>cCoh_ens_freq</code>, and the second and third arrays I want to assign with the variable names stored in the first and second elements in my first array <code>r1_radial_ZZ</code>. In reality, what happens is that the variable names for my processed data are wiped out when I assign the processed data back to the first array, and when I go to call, for example, the variable <code>cCoh_AB</code> I get an error saying the local variable was referenced before assignment.</p>
<p>How can I re-arrange my code so that the elements in my first array which contain the variable names as strings end up as data arrays with the given variable name after the code has run? </p>
<p><strong>UPDATE</strong></p>
<p>Here is the simplified code example for my question:</p>
<pre><code>import numpy as np
def calculation(x, y):
x2 = 2*x
y2 = 2*y
return "double", x2, y2
def dict_example():
first_array = np.array([["cCoh_AB", "Var_AB", 1, 2]], dtype=object)
for i in range(first_array.shape[0]):
type, first_array[i, 0], first_array[i, 1] = calculation(first_array[i, 2], first_array[i, 3])
dict_example()
</code></pre>
<p>Essentially, I want to be able to call the variables <code>cCoh_AB</code> and <code>Var_AB</code> and have them return the values "2" and "4" respectively.</p>
| 0 |
2016-09-14T07:24:44Z
| 39,503,306 |
<p>The answer was to use the variable names in <code>first_array</code> to generate keys in an empty dictionary to which I could assign the data generated by the <code>calculation()</code> function:</p>
<pre><code>def calculation(x, y):
x2 = 2*x
y2 = 2*y
return "double", x2, y2
def dict_example():
cCoh_dict = {}
first_array = np.array([["cCoh_AB", "Var_AB", 1, 2]], dtype=object)
for i in range(first_array.shape[0]):
type, cCoh_dict[first_array[i, 0]], cCoh_dict[first_array[i, 1]] = calculation(first_array[i, 2], first_array[i, 3])
</code></pre>
<p>Then the values for the keys assigned with the variable names in <code>first_array</code> are as expected:</p>
<pre><code>print first_array[0,0]
>>> cCoh_AB
print cCoh_dict["cCoh_AB"]
>>> 2
print cCoh_dict["Var_AB"]
>>> 4
</code></pre>
| 0 |
2016-09-15T04:48:50Z
|
[
"python",
"numpy"
] |
how to connect to page and check a word exist in page
| 39,484,812 |
<p>i want connect to a site by <code>urllib2</code> in every 5 second and get all html
after this i want check a word is in page or not </p>
<p>for example i want connect to <a href="http://google.com" rel="nofollow">google</a> every 5 second and check google is in page or not</p>
<p>i try this code :</p>
<pre><code>import urllib2
import time
while true:
values = urllib2("http://google.com")
if "google" in values:
print("google is in my address")
else:
print("google not in my address")
time.sleep(5)
</code></pre>
<p>i use python 2.7 </p>
| -3 |
2016-09-14T07:30:42Z
| 39,484,852 |
<p>your code have error </p>
<p>change your code to this :</p>
<pre><code>import urllib2
import time
while true:
values = urllib2.urlopen("http://google.com").read()
if "google" in values:
print("google is in my address")
else:
print("google not in my address")
time.sleep(5)
</code></pre>
<p>this code every 5 second check your site</p>
| 1 |
2016-09-14T07:32:48Z
|
[
"python"
] |
UTF-8 and colour printing woesâ¦
| 39,484,912 |
<p>I have a console program that outputs in wonderful colour. For errors, the following code is used with some trivial examples at the bottom.</p>
<pre><code># coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from sys import stderr
from colored import fg
from colored import attr
from locale import getpreferredencoding
def format_error(x):
return '{0}{1}{2}'.format(fg(88), x, attr('reset'))
def print_error(x):
msg = format_error('â {0}\n'.format(x))
stderr.write(msg.encode(getpreferredencoding()))
print_error(str('ook'))
print_error(unicode(b'café', 'UTF-8'))
</code></pre>
<p>I have no control over that <code>x</code> is. It could be anything. Also, some of this script is called from a GUI that captures <code>stdout</code>/<code>stderr</code> via <a href="http://www.pygtk.org/docs/pygobject/glib-functions.html#function-glib--spawn-async" rel="nofollow" title="glib-spawn-async documentation">glib-spawn-async</a>. As such, from time to time, I get <code>UnicodeDecodeError</code> errors. I have read the <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow" title="Unicode HOWTO">Unicode HOWTo</a> but clearly I am missing something.</p>
<p><em>How can I harden my code such that <code>UnicodeDecodeError</code> are never raised?</em></p>
<p>For example, within a <code>gtk.textview</code>, I get the following whereas on the console, all is fine. Trace has been cut to remove irrelevant data.</p>
<pre><code> File "/home/usr/nifty_logger.py", line 96, in print_success
sys.stdout.write(msg.encode(getpreferredencoding()))
File "/home/usr/.virtualenvs/rprs_bootstrap/lib64/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
</code></pre>
| 0 |
2016-09-14T07:36:37Z
| 39,485,140 |
<p>The <a href="http://docs.python.org/library/stdtypes.html#str.encode" rel="nofollow">encode()</a> takes an optional argument defining the error handling:</p>
<pre><code>str.encode([encoding[, errors]])
</code></pre>
<p>From the docs:</p>
<blockquote>
<p>Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Codec Base Classes. For a list of possible encodings, see section Standard Encodings.</p>
</blockquote>
<p>In your case:</p>
<pre><code>msg.encode(getpreferredencoding(), 'backslashreplace')
</code></pre>
| 1 |
2016-09-14T07:49:21Z
|
[
"python",
"python-2.7",
"utf-8"
] |
How to pass *args or **kwargs itself to the target function of threading.Target?
| 39,484,973 |
<p>A function accepts <code>*args</code> and <code>**kwargs</code>:</p>
<pre><code>def b(num, *args, **kwargs):
print('num', num)
print('args', args)
print('kwargs', kwargs)
</code></pre>
<p>calling it as <code>b(5, *[1, 2], **{'a': 'b'})</code> produces the following output:</p>
<pre><code>num 5
args (1, 2)
kwargs {'a': 'b'}
</code></pre>
<p><code>threading.Thread(target=b, args=[5, [1, 2], {'a': 'b'}]).start()</code> gives:</p>
<pre><code>num 5
args ([1, 2], {'a': 'b'})
kwargs {}
</code></pre>
<p><code>threading.Thread(target=b, kwargs={'num': 5, '*args': [1, 2], '**kwargs': {'a': 'b'}}).start()</code> gives:</p>
<pre><code>num 5
args ()
kwargs {'**kwargs': {'a': 'b'}, '*args': [1, 2]}
</code></pre>
<p>What's the correct way to pass *args and **kwargs to this function?</p>
| -1 |
2016-09-14T07:39:50Z
| 39,484,974 |
<pre><code>threading.Thread(target=b, args=[5, 1, 2], kwargs={'a': 'b'}).start()
</code></pre>
<p>gives the expected output. Another option is to use functools. The following code also passes arguments correctly:</p>
<pre><code>threading.Thread(target=functools.partial(b, 5, *[1, 2], **{'a': 'b'})).start()
</code></pre>
| 1 |
2016-09-14T07:39:50Z
|
[
"python",
"python-multithreading"
] |
Python won't break from a while True
| 39,485,007 |
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p>
<pre><code>from random import randint
import sys
value = int(randint(1,10))
lives = int(5)
userinp = int(0)
if lives == 0:
print("no lives :(")
while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0:
print("this")
</code></pre>
| -3 |
2016-09-14T07:41:36Z
| 39,485,041 |
<p>You have to break the <code>while</code> when <code>lives == 0</code>, either by a <code>break</code> or by changing the while condition.</p>
| 0 |
2016-09-14T07:43:35Z
|
[
"python"
] |
Python won't break from a while True
| 39,485,007 |
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p>
<pre><code>from random import randint
import sys
value = int(randint(1,10))
lives = int(5)
userinp = int(0)
if lives == 0:
print("no lives :(")
while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0:
print("this")
</code></pre>
| -3 |
2016-09-14T07:41:36Z
| 39,485,066 |
<p>A <code>while True</code> is an infinite loop, consuming 100% of all CPU cycles and will never break - since a <code>while <condition></code> only ends when the condition becomes <code>False</code>, but that can never be, because it is always <code>True</code>!</p>
<p>Try not fighting the nature of your loop: </p>
<pre><code>while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0: # indent condition to fall within the loop
print("this")
if lives < 0: # add an extra case to handle what you want
break
</code></pre>
| 1 |
2016-09-14T07:45:07Z
|
[
"python"
] |
Python won't break from a while True
| 39,485,007 |
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p>
<pre><code>from random import randint
import sys
value = int(randint(1,10))
lives = int(5)
userinp = int(0)
if lives == 0:
print("no lives :(")
while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0:
print("this")
</code></pre>
| -3 |
2016-09-14T07:41:36Z
| 39,485,121 |
<p>Your loop essentially looks like:</p>
<pre><code>while True:
if lives != 0:
# do stuff with lives
</code></pre>
<p>This is an infinite loop. The loop wont break even if <code>lives == 0</code>, because this condition is tested as part of the loop block, not as the loop condition.
You should simply do :</p>
<pre><code>while lives != 0:
# do stuff with lives
</code></pre>
<p>Or even <code>while lives > 0:</code> in case you manage to loose several lives during 1 loop iteration (doesn't seem to be possible here but better safe than sorry).</p>
<p>And since you seem to want to learn Python, there are a few other things you may want to learn and improve also:</p>
<p>No need to convert integers to integers here:</p>
<pre><code>value = int(randint(1,10))
lives = int(5)
userinp = int(0)
</code></pre>
<p>Numbers like <code>5</code> and <code>0</code>, and <code>randint(1,10)</code> are integers by themselves. <code>"5"</code> and <code>"0"</code> are strings containing a number as single character and would need to be converted before being compared to integers, but it is not needed here. randint() returns integers.</p>
<p>This is dead code since you have set <code>lives</code> to <code>5</code> 2 lines above and not modified it afterwards:</p>
<pre><code>if lives == 0:
print("no lives :(")
</code></pre>
<p>You should check if the user actually inputs a valid integer convertible value instead of an arbitrary string: (<code>continue</code> will skip to the next loop iteration, so it will ask the user for input again without decrementing <code>lives</code></p>
<pre><code>userinp = input("Please enter a number from 1 to 10: ")
if not userinp.isnumeric(): continue
</code></pre>
<p>No need to convert your already integer <code>value</code> to an integer again and again and AGAIN:</p>
<pre><code>if int(userinp) == int(value):
elif int(userinp) > int(value):
elif int(userinp) < int(value):
</code></pre>
<p>Avoid using <code>sys.exit()</code>, you may just <code>break</code> instead (to get out of the loop and continue.</p>
<p>And finally, Python has handy <code>-=, +=, *=, /=</code> operators, so you can write <code>lives -= 1</code> instead of <code>lives = lives - 1</code></p>
| 2 |
2016-09-14T07:48:18Z
|
[
"python"
] |
Python won't break from a while True
| 39,485,007 |
<p>this is my code but as the title says I can not break and if I put something outside the while True and lives go below 0 nothing happens. </p>
<pre><code>from random import randint
import sys
value = int(randint(1,10))
lives = int(5)
userinp = int(0)
if lives == 0:
print("no lives :(")
while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0:
print("this")
</code></pre>
| -3 |
2016-09-14T07:41:36Z
| 39,486,128 |
<p>This is my solution, you can set the <code>break</code> condition specifically to end your while loop if a specific event occurs.</p>
<pre><code>while lives > 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
print("this")
</code></pre>
| 0 |
2016-09-14T08:45:36Z
|
[
"python"
] |
Python GeoIP2 AddressNotFoundError
| 39,485,054 |
<p>Im trying to use Python GeoIP to convert IP address to Geo details using Maxmind Database.</p>
<pre><code>import urllib2
import csv
import geoip2.database
db = geoip2.database.Reader("GeoLite2-City.mmdb")
target_url="http://myip/all.txt"
data = urllib2.urlopen(target_url)
for line in data:
response = db.city(line.strip())
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
</code></pre>
<p>Im getting the error "<strong>geoip2.errors.AddressNotFoundError:</strong> The address 103.229.234.197 is not in the database."</p>
<pre><code> Traceback (most recent call last):
File "script.py", line 14, in <module>
response = db.city(line.strip())
File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 110, in city
return self._model_for(geoip2.models.City, 'City', ip_address)
File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 180, in _model_for
record = self._get(types, ip_address)
File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 176, in _get
"The address %s is not in the database." % ip_address)
geoip2.errors.AddressNotFoundError: The address 103.229.234.197 is not in the database.
</code></pre>
<p>Maxmind db mentions as the address not in database. However its not going to hurt me but how can a ignore this error and get my output of which ever is available?</p>
<p>Tried to except any error (although not a best way) and also to expect particular AddressNotFoundError. </p>
<pre><code>try:
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
except:
pass
</code></pre>
<p>also,</p>
<pre><code>try:
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
except AddressNotFoundError:
pass
</code></pre>
<p>Still no luck.</p>
<p>Any suggestions.</p>
| 0 |
2016-09-14T07:44:24Z
| 39,487,501 |
<p>The problem here is the exception happening in db.city call, not in values printing, so you could try this:</p>
<pre><code>import urllib2
import csv
import geoip2.database
db = geoip2.database.Reader("GeoLite2-City.mmdb")
target_url="http://myip/all.txt"
data = urllib2.urlopen(target_url)
for line in data:
try:
response = db.city(line.strip())
print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
exception:
pass
</code></pre>
| 1 |
2016-09-14T09:54:30Z
|
[
"python",
"exception",
"exception-handling",
"geoip",
"maxmind"
] |
Python square brackets between function name and arguments: func[...](...)
| 39,485,083 |
<p>I was learning how to accelerate python computations on GPU from <a href="https://nbviewer.jupyter.org/gist/harrism/f5707335f40af9463c43" rel="nofollow">this notebook</a>, where one line confuses me:</p>
<pre><code>mandel_kernel[griddim, blockdim](-2.0, 1.0, -1.0, 1.0, d_image, 20)
</code></pre>
<p>Here, <code>mandel_kernel</code> is a decorated (by <code>cuda.jit</code>) function, <code>griddim</code> and <code>blockdim</code> are tuples of length 2: <code>griddim=(32,16)</code>, <code>blockdim=(32,8)</code>.</p>
<p>Is this square brackets in between function name and argument list part of python syntax, or something specific to the <code>cuda.jit</code> decoration?</p>
| 4 |
2016-09-14T07:46:00Z
| 39,486,357 |
<p>This is valid python syntax, i'll try to break it down for you:</p>
<p><code>mandel_kernel</code> is a dict, whose keys are 2-tuples (griddim, blockdim) and values are method (which is valid since methods are objects in python)</p>
<p><code>mandel_kernel[griddim, blockdim]</code> therefore 'returns' (or evaluates to) a method</p>
<p><code>mandel_kernel[griddim, blockdim](-2.0, 1.0, -1.0, 1.0, d_image, 20)</code> therefore calls that method with whatever arguments are inside the parenthesis.</p>
<p>This one line could be rewritten in three lines like so:</p>
<pre><code>key = tuple(griddim, blockdim)
method = mandel_kernel[key]
method(-2.0, 1.0, -1.0, 1.0, d_image, 20)
</code></pre>
| 5 |
2016-09-14T08:56:49Z
|
[
"python",
"python-decorators",
"numba",
"numba-pro"
] |
Python CGI Script "Cannot allocate memory" Import Error
| 39,485,160 |
<p>I have a simple CGI script on a shared 64bit Ubuntu hosting environment.</p>
<pre><code>#!/kunden/homepages/14/d156645139/htdocs/htdocs/anaconda2/bin/python
# -*- coding: UTF-8 -*-
import sys
import cgi
import cgitb
cgitb.enable()
import numpy
from pandas_datareader.yahoo.daily import YahooDailyReader
</code></pre>
<p>When I attempt to run the script I receive the following error:</p>
<pre><code> /kunden/homepages/14/d156645139/htdocs/finance/bin/py/test.py in ()
6 import cgitb
7 cgitb.enable()
=> 8 from pandas_datareader.yahoo.daily import YahooDailyReader
9 import datetime as dt
10 import numpy as np
pandas_datareader undefined, YahooDailyReader undefined
/kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas_datareader/yahoo/daily.py in ()
2
3
4 class YahooDailyReader(_DailyBaseReader):
5
6 """
pandas_datareader undefined, _DailyBaseReader undefined
/kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas_datareader/base.py in ()
7 from requests_file import FileAdapter
8
=> 9 from pandas import to_datetime
10 import pandas.compat as compat
11 from pandas.core.common import PandasError, is_number
pandas undefined, to_datetime undefined
/kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas/__init__.py in ()
35
36 # let init-time option registration happen
=> 37 import pandas.core.config_init
38
39 from pandas.core.api import *
pandas undefined
/kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas/core/config_init.py in ()
16 is_one_of_factory, get_default_val,
17 is_callable)
=> 18 from pandas.formats.format import detect_console_encoding
19
20 #
pandas undefined, detect_console_encoding undefined
/kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas/formats/format.py in ()
19 import pandas.lib as lib
20 from pandas.tslib import iNaT, Timestamp, Timedelta, format_array_from_datetime
=> 21 from pandas.tseries.index import DatetimeIndex
22 from pandas.tseries.period import PeriodIndex
23 import pandas as pd
pandas undefined, DatetimeIndex undefined
/kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas/tseries/index.py in ()
<type 'exceptions.ImportError'>: /kunden/homepages/14/d156645139/htdocs/anaconda2/lib/python2.7/site-packages/pandas/_period.so: failed to map segment from shared object: Cannot allocate memory
args = ('/kunden/homepages/14/d156645139/htdocs/anaconda2...egment from shared object: Cannot allocate memory',)
message = '/kunden/homepages/14/d156645139/htdocs/anaconda2...egment from shared object: Cannot allocate memory'
</code></pre>
<p>How can I trace the source of the memory error? For example, is there a way to understand the memory limits or even increase?</p>
| 0 |
2016-09-14T07:50:20Z
| 39,543,359 |
<p>I was able to increase the RAM of the machine to a guaranteed 2GB which solved the problem.</p>
| 0 |
2016-09-17T05:59:11Z
|
[
"python",
"pandas"
] |
Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors
| 39,485,178 |
<p>What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be interpolated. While I had some success for interpolating the colors for one axis, the two-dimensional calculation provides me some bad headaches. While the image seems to have a non-linear color gradient, I would be happy with a linear one.</p>
<p>If you could give me some hints how to do this with numpy or other tools I`ll be more than thankful.</p>
<p><a href="http://i.stack.imgur.com/o1BUK.png"><img src="http://i.stack.imgur.com/o1BUK.png" alt="enter image description here"></a></p>
| 7 |
2016-09-14T07:51:00Z
| 39,485,650 |
<p>Here's a super short solution using the <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.interpolation.zoom.html" rel="nofollow">zoom function</a> from <code>scipy.ndimage</code>. I define a 2x2 RGB image with the intial colors (here random ones) and simply zoom it to 256x256, <code>order=1</code> makes the interpolation linear. Here is the code :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
im=(np.random.rand(2,2,3)*255).astype(np.uint8)
from scipy.ndimage.interpolation import zoom
zoomed=zoom(im,(128,128,1),order=1)
plt.subplot(121)
plt.imshow(im,interpolation='nearest')
plt.subplot(122)
plt.imshow(zoomed,interpolation='nearest')
plt.show()
</code></pre>
<p>Output:</p>
<p><a href="http://i.stack.imgur.com/mMVYM.png" rel="nofollow"><img src="http://i.stack.imgur.com/mMVYM.png" alt="output from the script"></a></p>
| 4 |
2016-09-14T08:18:54Z
|
[
"python",
"numpy",
"image-processing"
] |
Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors
| 39,485,178 |
<p>What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be interpolated. While I had some success for interpolating the colors for one axis, the two-dimensional calculation provides me some bad headaches. While the image seems to have a non-linear color gradient, I would be happy with a linear one.</p>
<p>If you could give me some hints how to do this with numpy or other tools I`ll be more than thankful.</p>
<p><a href="http://i.stack.imgur.com/o1BUK.png"><img src="http://i.stack.imgur.com/o1BUK.png" alt="enter image description here"></a></p>
| 7 |
2016-09-14T07:51:00Z
| 39,486,574 |
<p>Here's a very short way to do it with <strong>ImageMagick</strong> which is installed on most Linux distros and is available for OSX and Windows. There are also Python bindings. Anyway, just at the command line, create a 2x2 square with the colours at the 4 corners of your image, then let ImageMagick expand and interpolate up to the full size:</p>
<pre><code>convert \( xc:"#59605c" xc:"#ebedb3" +append \) \
\( xc:"#69766d" xc:"#b3b3a0" +append \) \
-append -resize 256x256 result.png
</code></pre>
<p><a href="http://i.stack.imgur.com/IfObm.png" rel="nofollow"><img src="http://i.stack.imgur.com/IfObm.png" alt="enter image description here"></a></p>
<p>The first line makes a 1x1 pixel of each of your top-left and top-right corners and appends the two side by side. The second line makes a 1x1 pixel of each of your bottom-left and bottom-right corners and appends them side by side. The final line appends the bottom row below the top row and enlarges by interpolation to 256x256.</p>
<p>If you want to better understand what's going on, here is the same basic image but scaled up using nearest neighbour rather than interpolation:</p>
<pre><code>convert \( xc:"#59605c" xc:"#ebedb3" +append \) \
\( xc:"#69766d" xc:"#b3b3a0" +append \) \
-append -scale 20x20 result.png
</code></pre>
<p><a href="http://i.stack.imgur.com/NmzWs.png" rel="nofollow"><img src="http://i.stack.imgur.com/NmzWs.png" alt="enter image description here"></a></p>
| 2 |
2016-09-14T09:09:08Z
|
[
"python",
"numpy",
"image-processing"
] |
Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors
| 39,485,178 |
<p>What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be interpolated. While I had some success for interpolating the colors for one axis, the two-dimensional calculation provides me some bad headaches. While the image seems to have a non-linear color gradient, I would be happy with a linear one.</p>
<p>If you could give me some hints how to do this with numpy or other tools I`ll be more than thankful.</p>
<p><a href="http://i.stack.imgur.com/o1BUK.png"><img src="http://i.stack.imgur.com/o1BUK.png" alt="enter image description here"></a></p>
| 7 |
2016-09-14T07:51:00Z
| 39,515,362 |
<p>Here are 3 ways to do this bilinear interpolation. The first version does all the arithmetic in pure Python, the second uses <a href="https://python-pillow.org/" rel="nofollow">PIL</a> image composition, the third uses Numpy to do the arithmetic. As expected, the pure Python is significantly slower than the other approaches. The Numpy version (which was derived from code written by <a href="http://stackoverflow.com/users/5067311/andras-deak">Andras Deak</a>) is almost as fast as the PIL version for small images, but for larger images the PIL version is noticeably faster.</p>
<p>I also tried using jadsq's scaling technique in PIL but the results were not good - I suspect that PIL's interpolation code is a little buggy.</p>
<p>If you wanted to create lots of these bilinear gradient images of the same size, the PIL technique has another advantage: once you've created the composition masks you don't need to rebuild them for every image.</p>
<pre><code>#!/usr/bin/env python3
''' Simple bilinear interpolation
Written by PM 2Ring 2016.09.14
'''
from PIL import Image
from math import floor
import numpy as np
def color_square0(colors, size):
tl, tr, bl, br = colors
m = size - 1
r = range(size)
def interp_2D(tl, tr, bl, br, x, y):
u0, v0 = x / m, y / m
u1, v1 = 1 - u0, 1 - v0
return floor(0.5 + u1*v1*tl + u0*v1*tr + u1*v0*bl + u0*v0*br)
data = bytes(interp_2D(tl[i], tr[i], bl[i], br[i], x, y)
for y in r for x in r for i in (0, 1, 2))
return Image.frombytes('RGB', (size, size), data)
# Fastest
def color_square1(colors, size):
#Make an Image of each corner color
tl, tr, bl, br = [Image.new('RGB', (size, size), color=c) for c in colors]
#Make the composition mask
mask = Image.new('L', (size, size))
m = 255.0 / (size - 1)
mask.putdata([int(m * x) for x in range(size)] * size)
imgt = Image.composite(tr, tl, mask)
imgb = Image.composite(br, bl, mask)
return Image.composite(imgb, imgt, mask.transpose(Image.TRANSPOSE))
# This function was derived from code written by Andras Deak
def color_square2(colors, size):
tl, tr, bl, br = map(np.array, colors)
m = size - 1
x, y = np.mgrid[0:size, 0:size]
x = x[..., None] / m
y = y[..., None] / m
data = np.floor(x*y*br + (1-x)*y*tr + x*(1-y)*bl + (1-x)*(1-y)*tl + 0.5)
return Image.fromarray(np.array(data, dtype = 'uint8'), 'RGB')
color_square = color_square1
#tl = (255, 0, 0)
#tr = (255, 255, 0)
#bl = (0, 0, 255)
#br = (0, 255, 0)
tl = (108, 115, 111)
tr = (239, 239, 192)
bl = (124, 137, 129)
br = (192, 192, 175)
colors = (tl, tr, bl, br)
size = 256
img = color_square(colors, size)
img.show()
#img.save('test.png')
</code></pre>
<p><strong>output</strong></p>
<p><img src="http://i.stack.imgur.com/CswYU.png" alt="bilinear gradient"></p>
<hr>
<p>Just for fun, here's a simple GUI program using Tkinter which can be used to generate these gradients.</p>
<pre><code>#!/usr/bin/env python3
''' Simple bilinear colour interpolation
using PIL, in a Tkinter GUI
Inspired by http://stackoverflow.com/q/39485178/4014959
Written by PM 2Ring 2016.09.15
'''
import tkinter as tk
from tkinter.colorchooser import askcolor
from tkinter.filedialog import asksaveasfilename
from PIL import Image, ImageTk
DEFCOLOR = '#d9d9d9'
SIZE = 256
#Make the composition masks
mask = Image.new('L', (SIZE, SIZE))
m = 255.0 / (SIZE - 1)
mask.putdata([int(m * x) for x in range(SIZE)] * SIZE)
maskt = mask.transpose(Image.TRANSPOSE)
def do_gradient():
imgt = Image.composite(tr.img, tl.img, mask)
imgb = Image.composite(br.img, bl.img, mask)
img = Image.composite(imgb, imgt, maskt)
ilabel.img = img
photo = ImageTk.PhotoImage(img)
ilabel.config(image=photo)
ilabel.photo = photo
def set_color(w, c):
w.color = c
w.config(background=c, activebackground=c)
w.img = Image.new('RGB', (SIZE, SIZE), color=c)
def show_color(w):
c = w.color
newc = askcolor(c)[1]
if newc is not None and newc != c:
set_color(w, newc)
do_gradient()
def color_button(row, column, initcolor=DEFCOLOR):
b = tk.Button(root)
b.config(command=lambda w=b:show_color(w))
set_color(b, initcolor)
b.grid(row=row, column=column)
return b
def save_image():
filetypes = [('All files', '.*'), ('PNG files', '.png')]
fname = asksaveasfilename(title="Save Image",filetypes=filetypes)
if fname:
ilabel.img.save(fname)
print('Saved image as %r' % fname)
else:
print('Cancelled')
root = tk.Tk()
root.title("Color interpolation")
coords = ((0, 0), (0, 2), (2, 0), (2, 2))
tl, tr, bl, br = [color_button(r, c) for r,c in coords]
ilabel = tk.Label(root, relief=tk.SUNKEN)
do_gradient()
ilabel.grid(row=1, column=1)
b = tk.Button(root, text="Save", command=save_image)
b.grid(row=3, column=1)
root.mainloop()
</code></pre>
| 2 |
2016-09-15T15:49:59Z
|
[
"python",
"numpy",
"image-processing"
] |
How can I test a form with FileField in Django?
| 39,485,189 |
<p>I have this form:</p>
<pre><code># forms.py
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['book_title', 'language', 'author', 'release_year', 'genre', 'ages', 'cover']
</code></pre>
<p><strong>Type of fields:</strong>
Where <code>book_title</code> and <code>author</code> are <code>CharField</code>, <code>language</code> and <code>genre</code> are too <code>CharField</code> but for them I have choice option, <code>release_year</code> and <code>ages</code> are <code>IntegerField</code>, and the last <code>cover</code> are <code>FileField</code>.</p>
<p><strong>Choice Options:</strong></p>
<pre><code># models.py
ENGLISH = 'english'
LANGUAGE_CHOICES = (
(ENGLISH, 'English'),
)
ADVENTURE = 'adventure'
GENRE_CHOICES = (
(ADVENTURE, 'Adventure'),
)
</code></pre>
<p><strong>Now:</strong> I want to test this form, but I don't know how can test <code>cover</code>, here is my form test.</p>
<pre><code># test_forms.py
from .. import forms
from django.core.files import File
class TestBookForm:
def test_form(self):
form = forms.BookForm(data={})
assert form.is_valid() is False, 'Should be invalid if no data is given'
img = File(open('background'))
data = {'book_title': 'Lord Of The Rings',
'language': 'english',
'author': 'J. R. R. Tolkien',
'release_year': 1957,
'genre': 'adventure',
'ages': 16,
'cover': img}
form = forms.BookForm(data=data)
assert form.is_valid() is True
</code></pre>
<p><strong>I tried:</strong>
from django.core.files.uploadedfile import SimpleUploadedFile</p>
<pre><code>img = open('background')
uploaded = SimpleUploadedFile(img.name, img.read())
{'cover': uploaded}
</code></pre>
<p><strong>This is my error:</strong></p>
<pre><code>E assert False is True
E + where False = <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>>()
E + where <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>> = <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>
.is_valid
</code></pre>
<p><strong>NOTE:</strong> I use <code>Python 3.5</code>, <code>Django 1.9.4</code> and I start test using <code>py.test</code>.</p>
<p><strong>UPDATE:</strong> If i try <code>open('background.jpg')</code> don't work. <strong>Error:</strong> <code>FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg'</code> <strong>I fix this</strong></p>
<p><strong>UPDATE 2:</strong> </p>
<p>I try to use <code>mock</code></p>
<pre><code>from django.core.files import File
import mock
file_mock = mock.MagicMock(spec=File, name='FileMock')
file_mock.name = 'test1.jpg'
{'cover': file_mock}
</code></pre>
<p>I try to use <code>InMemoryUploadedFile</code></p>
<pre><code>from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
from PIL import Image
im = Image.new(mode='RGB', size=(200, 200)) # create a new image using PIL
im_io = BytesIO() # a StringIO object for saving image
im.save(im_io, 'JPEG') # save the image to im_io
im_io.seek(0) # seek to the beginning
image = InMemoryUploadedFile(
im_io, None, 'random-name.jpg', 'image/jpeg', None, None
)
{'cover': image}
</code></pre>
<p>I fix the path to my image.</p>
| 0 |
2016-09-14T07:51:36Z
| 39,485,485 |
<p>Either you create a file in your repository, so it is there physically, or you mock your test for your file.</p>
<p>Try <a href="https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html" rel="nofollow">THIS</a> </p>
<hr>
<p><strong>EDIT</strong></p>
<p>Try to pass full path </p>
<pre><code>import os
from django.conf import settings
file_path = os.path.join(settings.BASE_DIR, your_folder, background.jpg)
</code></pre>
| 0 |
2016-09-14T08:09:04Z
|
[
"python",
"django",
"python-3.x",
"django-forms",
"django-testing"
] |
How can I test a form with FileField in Django?
| 39,485,189 |
<p>I have this form:</p>
<pre><code># forms.py
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['book_title', 'language', 'author', 'release_year', 'genre', 'ages', 'cover']
</code></pre>
<p><strong>Type of fields:</strong>
Where <code>book_title</code> and <code>author</code> are <code>CharField</code>, <code>language</code> and <code>genre</code> are too <code>CharField</code> but for them I have choice option, <code>release_year</code> and <code>ages</code> are <code>IntegerField</code>, and the last <code>cover</code> are <code>FileField</code>.</p>
<p><strong>Choice Options:</strong></p>
<pre><code># models.py
ENGLISH = 'english'
LANGUAGE_CHOICES = (
(ENGLISH, 'English'),
)
ADVENTURE = 'adventure'
GENRE_CHOICES = (
(ADVENTURE, 'Adventure'),
)
</code></pre>
<p><strong>Now:</strong> I want to test this form, but I don't know how can test <code>cover</code>, here is my form test.</p>
<pre><code># test_forms.py
from .. import forms
from django.core.files import File
class TestBookForm:
def test_form(self):
form = forms.BookForm(data={})
assert form.is_valid() is False, 'Should be invalid if no data is given'
img = File(open('background'))
data = {'book_title': 'Lord Of The Rings',
'language': 'english',
'author': 'J. R. R. Tolkien',
'release_year': 1957,
'genre': 'adventure',
'ages': 16,
'cover': img}
form = forms.BookForm(data=data)
assert form.is_valid() is True
</code></pre>
<p><strong>I tried:</strong>
from django.core.files.uploadedfile import SimpleUploadedFile</p>
<pre><code>img = open('background')
uploaded = SimpleUploadedFile(img.name, img.read())
{'cover': uploaded}
</code></pre>
<p><strong>This is my error:</strong></p>
<pre><code>E assert False is True
E + where False = <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>>()
E + where <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>> = <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>
.is_valid
</code></pre>
<p><strong>NOTE:</strong> I use <code>Python 3.5</code>, <code>Django 1.9.4</code> and I start test using <code>py.test</code>.</p>
<p><strong>UPDATE:</strong> If i try <code>open('background.jpg')</code> don't work. <strong>Error:</strong> <code>FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg'</code> <strong>I fix this</strong></p>
<p><strong>UPDATE 2:</strong> </p>
<p>I try to use <code>mock</code></p>
<pre><code>from django.core.files import File
import mock
file_mock = mock.MagicMock(spec=File, name='FileMock')
file_mock.name = 'test1.jpg'
{'cover': file_mock}
</code></pre>
<p>I try to use <code>InMemoryUploadedFile</code></p>
<pre><code>from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
from PIL import Image
im = Image.new(mode='RGB', size=(200, 200)) # create a new image using PIL
im_io = BytesIO() # a StringIO object for saving image
im.save(im_io, 'JPEG') # save the image to im_io
im_io.seek(0) # seek to the beginning
image = InMemoryUploadedFile(
im_io, None, 'random-name.jpg', 'image/jpeg', None, None
)
{'cover': image}
</code></pre>
<p>I fix the path to my image.</p>
| 0 |
2016-09-14T07:51:36Z
| 39,489,599 |
<p><strong>I find the problem</strong> This is my code:</p>
<pre><code>#test_forms.py
from .. import forms
from django.core.files.uploadedfile import SimpleUploadedFile
import os
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_DATA_DIR = os.path.join(TEST_DIR, 'data')
class TestBookForm:
def test_form(self):
form = forms.BookForm(data={})
assert form.is_valid() is False, 'Should be invalid if no data is given'
test_image_path = os.path.join(TEST_DATA_DIR, 'background.jpg')
data = {'book_title': 'Lord Of The Rings',
'language': 'english',
'author': 'J. R. R. Tolkien',
'release_year': 1957,
'genre': 'adventure',
'ages': 16}
with open(test_image_path, 'rb') as f:
form = forms.BookForm(data=data, files={'cover': SimpleUploadedFile('cover', f.read())})
assert form.is_valid(), 'Invalid form, errors: {}'.format(form.errors)
</code></pre>
| 0 |
2016-09-14T11:44:35Z
|
[
"python",
"django",
"python-3.x",
"django-forms",
"django-testing"
] |
Better way to write so many values in files Python (Lack of memory in a device)
| 39,485,365 |
<p>I have a question about file output in Python.
I was designing a software that reads values from 3 sensors.
Each sensors read 100 values for 1 second, and between each process, I have to print them in file. </p>
<pre><code>time_memory = [k + i/100 for i in range(100)] # dividing 1 second into 100 intervals
x = [100 elements]
y = [100 elements]
z = [100 elements]
</code></pre>
<p>Below is the code of writing into the file. </p>
<pre><code>for i in range(self.samples):
self.time_memory[i] = file_time + self.time_index[i]
f.write("{0} {1} {2} {3}\n".format(self.time_memory[i], x[i], y[i], z[i]))
</code></pre>
<p>So the result in the file will look like</p>
<pre><code>time_value, x, y, z
time_value, x, y, z
...
</code></pre>
<p>However, when the measurement time is over 8000 seconds, the software stops.
I think it is due to so many data the device must proceed since the device I am using is kind of an old one. (I cannot change the device because the computer is connected to NI DAQ device.)</p>
<p>I tried to find many alternative ways to change the code above, but I couldn't find it. Is there anyone who can help me with this problem??</p>
| 1 |
2016-09-14T08:02:33Z
| 39,485,513 |
<p>One suggestion would be to write the data in binary mode. This should be faster than the text mode (it also needs less space). Therefore you have to open a file in binary mode like this:</p>
<pre><code>f = open('filename.data', 'wb')
</code></pre>
| -1 |
2016-09-14T08:10:05Z
|
[
"python",
"file",
"data-acquisition"
] |
Calling from the same class, why is one treated as bound method while the other plain function?
| 39,485,440 |
<p>I have the following code snippet in Python 3:</p>
<pre><code>from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Integer, String, Unicode, UnicodeText
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
import arrow
datetimeString_format = {
"UTC": "%Y-%m-%d %H:%M:%S+00:00",
"local_with_timezoneMarker": "%Y-%m-%d %H:%M:%S %Z",
"local_without_timezoneMarker": "%Y-%m-%d %H:%M:%S"
}
dateString_format = "%Y-%m-%d"
class My_TimePoint_Mixin:
# define output formats:
datetimeString_inUTC_format = "%Y-%m-%d %H:%M:%S+00:00"
datetimeString_naive_format = "%Y-%m-%d %H:%M:%S"
# instrumented fields:
_TimePoint_in_database = Column('timepoint', String, nullable=False)
_TimePoint_in_database_suffix = Column(
'timepoint_suffix', String, nullable=False)
@hybrid_property
def timepoint(self):
twoPossibleType_handlers = [
self._report_ACCRT_DATE,
self._report_ACCRT_DATETIME
]
for handler in twoPossibleType_handlers:
print("handler: ", handler)
try:
return handler(self)
except (AssertionError, ValueError) as e:
logging.warning("Try next handler!")
@timepoint.setter
def timepoint(self, datetimepointOBJ):
handlers_lookup = {
datetime.datetime: self._set_ACCRT_DATETIME,
datetime.date: self._set_ACCRT_DATE
}
this_time = type(datetimepointOBJ)
this_handler = handlers_lookup[this_time]
print("handler: ", this_handler)
this_handler(datetimepointOBJ)
def _report_ACCRT_DATE(self):
"""Accurate Date"""
assert self._TimePoint_in_database_suffix == "ACCRT_DATE"
date_string = self._TimePoint_in_database
dateString_format = "%Y-%m-%d"
# return a datetime.date
return datetime.datetime.strptime(date_string, dateString_format).date()
def _report_ACCRT_DATETIME(self):
"""Accurate DateTime"""
assert self._TimePoint_in_database_suffix in pytz.all_timezones_set
datetimeString_inUTC = self._TimePoint_in_database
utc_naive = datetime.datetime.strptime(
datetimeString_inUTC, self.datetimeString_inUTC_format)
utc_timepoint = arrow.get(utc_naive, "utc")
# localize
local_timepoint = utc_timepoint.to(self._TimePoint_in_database_suffix)
# return a datetime.datetime
return local_timepoint.datetime
def _set_ACCRT_DATETIME(self, datetimeOBJ_aware):
assert isinstance(datetimeOBJ_aware, datetime.datetime), "Must be a valid datetime.datetime!"
assert datetimeOBJ_aware.tzinfo is not None, "Must contain tzinfo!"
utctime_aware_arrow = arrow.get(datetimeOBJ_aware).to('utc')
utctime_aware_datetime = utctime_aware_arrow.datetime
store_datetime_string = utctime_aware_datetime.strftime(
self.datetimeString_inUTC_format)
self._TimePoint_in_database = store_datetime_string
def _set_ACCRT_DATE(self, dateOBJ):
store_date_string = dateOBJ.isoformat()
self._TimePoint_in_database = store_date_string
</code></pre>
<p>For some reason, the getter's handler is treated as a plain function rather than a method, hence the need to explicitly provide 'self' as its argument.</p>
<p>Is it because of the looping? Or because of the <code>try...except</code> structure? Why is this the case that within the same class, handlers are treated differently? (The setter's handlers are treated as bound method as expected).</p>
| 0 |
2016-09-14T08:06:38Z
| 39,487,502 |
<p>What you have is not a regular <code>property</code> here, you have a <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html" rel="nofollow">SQLAlchemy <code>@hybrid_property</code> object</a>. Quoting the documentation there:</p>
<blockquote>
<p>âhybridâ means the attribute has distinct behaviors defined at the class level and at the instance level.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>When dealing with the <code>Interval</code> class itself, the <code>hybrid_property</code> descriptor evaluates the function body given the <code>Interval</code> class as the argument, which when evaluated with SQLAlchemy expression mechanics returns a new SQL expression:</p>
<pre><code>>>> print Interval.length
interval."end" - interval.start
</code></pre>
</blockquote>
<p>So the property is used in a <em>dual capacity</em>, both on instances, and on the class.</p>
<p>In the case of the property being used on the class itself, <code>self</code> is bound to (a subclass of) <code>My_TimePoint_Mixin</code> and the methods are not bound. There is nothing to bind <em>to</em> in that case as there is no instance.</p>
<p>You'll have to take this into account when coding a <code>hybrid_property</code> getter (the setter only applies to the <em>on an instance</em> case). Your assertions at the start of <code>_report_ACCRT_DATE</code> and <code>_report_ACCRT_DATETIME</code> won't hold, for example.</p>
<p>You can distinguish between the <em>instance</em> case and the <em>expression</em> (on the class) case, by declaring a separate getter for the latter with the <code>hybrid_property.expression</code> decorator:</p>
<pre><code>@hybrid_property
def timepoint(self):
twoPossibleType_handlers = [
self._report_ACCRT_DATE,
self._report_ACCRT_DATETIME
]
for handler in twoPossibleType_handlers:
print("handler: ", handler)
try:
return handler(self)
except (AssertionError, ValueError) as e:
logging.warning("Try next handler!")
@timepoint.expression
def timepoint(cls):
# return a SQLAlchemy expression for this virtual column
</code></pre>
<p>SQLAlchemy will then use the <code>@timepoint.expression</code> class method for the <code>My_TimePoint_Mixin.timepoint</code> use, and use the original getter only on <code>My_TimePoint_Mixin().timepoint</code> instance access. See the <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html#defining-expression-behavior-distinct-from-attribute-behavior" rel="nofollow"><em>Defining Expression Behavior Distinct from Attribute Behavior</em> section</a>.</p>
| 1 |
2016-09-14T09:54:30Z
|
[
"python",
"function",
"python-3.x",
"methods",
"sqlalchemy"
] |
Django Tutorial 1 - ImportError: No module named apps
| 39,485,505 |
<p>I am following this Tutorial:
<a href="https://docs.djangoproject.com/en/1.10/intro/tutorial02/" rel="nofollow">https://docs.djangoproject.com/en/1.10/intro/tutorial02/</a></p>
<p>In subsection <em>"Activating models"</em> i should add some code in the </p>
<blockquote>
<p>mysite/settings.py</p>
</blockquote>
<pre><code>INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
</code></pre>
<p>when i run the command</p>
<pre><code>python manage.py makemigrations polls
</code></pre>
<p>i get the following errormessage</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/lib/python2.7/dist-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named apps
</code></pre>
<p>i don't have a folder or a file called "apps" in my "polls" folder, so i am wondering about the "polls.apps.PollsConfig" syntax. i found some posts in the web telling that in django version 1.7 there where some changes.</p>
<p>I am using:</p>
<ul>
<li>Ubuntu 16.04 LTS</li>
<li>Python 2.7.11+</li>
<li>django.VERSION (1, 8, 7, 'final', 0)</li>
</ul>
| 1 |
2016-09-14T08:09:49Z
| 39,485,750 |
<p>You're using a newer version of Django, who doesn't create the app.py configuration file in the folder because the old structure is different. You've two options:</p>
<p>1) Change the documentation version to 1.8</p>
<p>2) [RECOMMENDED] use the latest version of Django</p>
| 3 |
2016-09-14T08:24:30Z
|
[
"python",
"django"
] |
Failed to find HDF5 dataset data - Single Label Regression Using Caffe and HDF5 data
| 39,485,515 |
<p>I was using @shai 's code for creating my hdf5 file which is available here: </p>
<p><a href="http://stackoverflow.com/questions/31774953/test-labels-for-regression-caffe-float-not-allowed/31808324#31808324">Test labels for regression caffe, float not allowed?</a></p>
<p>My data is grayscale images (1000 images for a start) and label is one dimensional float numbers </p>
<p>So, I modified his code as:</p>
<pre><code>import h5py, os
import caffe
import numpy as np
SIZE = 224
with open( 'train.txt', 'r' ) as T :
lines = T.readlines()
X = np.zeros( (len(lines), 1, SIZE, SIZE), dtype='f4' ) #Changed 3 to 1
y = np.zeros( (len(lines)), dtype='f4' ) #Removed the "1,"
for i,l in enumerate(lines):
sp = l.split(' ')
img = caffe.io.load_image( sp[0], color=False ) #Added , color=False
img = caffe.io.resize( img, (SIZE, SIZE, 1) ) #Changed 3 to 1
# you may apply other input transformations here...
X[i] = img
y[i] = float(sp[1])
with h5py.File('train.h5','w') as H:
H.create_dataset( 'X', data=X ) # note the name X given to the dataset!
H.create_dataset( 'y', data=y ) # note the name y given to the dataset!
with open('train_h5_list.txt','w') as L:
L.write( 'train.h5' ) # list all h5 files you are going to use
</code></pre>
<h2>But I was getting this error:</h2>
<pre><code>ValueError Traceback (most recent call last)
<ipython-input-19-8148f7b9e03d> in <module>()
13 img = caffe.io.resize( img, (SIZE, SIZE, 1) ) #Changed 3 to 1
14 # you may apply other input transformations here...
---> 15 X[i] = img
16 y[i] = float(sp[1])
ValueError: could not broadcast input array from shape (224,224,1) into shape (1,224,224)
</code></pre>
<p>So I changed the line number 13 from:</p>
<pre><code>img = caffe.io.resize( img, (SIZE, SIZE, 1) )
</code></pre>
<p>to:</p>
<pre><code>img = caffe.io.resize( img, (1, SIZE, SIZE) )
</code></pre>
<p>And the code ran fine.</p>
<p>For training, I used this solver.prototxt file:</p>
<pre><code>net: "MyCaffeTrain/train_test.prototxt"
# Note: 1 iteration = 1 forward pass over all the images in one batch
# Carry out a validation test every 500 training iterations.
test_interval: 500
# test_iter specifies how many forward passes the validation test should carry out
# a good number is num_val_imgs / batch_size (see batch_size in Data layer in phase TEST in train_test.prototxt)
test_iter: 100
# The base learning rate, momentum and the weight decay of the network.
base_lr: 0.01
momentum: 0.9
weight_decay: 0.0005
# We want to initially move fast towards the local minimum and as we approach it, we want to move slower
# To this end, there are various learning rates policies available:
# fixed: always return base_lr.
# step: return base_lr * gamma ^ (floor(iter / step))
# exp: return base_lr * gamma ^ iter
# inv: return base_lr * (1 + gamma * iter) ^ (- power)
# multistep: similar to step but it allows non uniform steps defined by stepvalue
# poly: the effective learning rate follows a polynomial decay, to be zero by the max_iter: return base_lr (1 - iter/max_iter) ^ (power)
# sigmoid: the effective learning rate follows a sigmod decay: return base_lr * ( 1/(1 + exp(-gamma * (iter - stepsize))))
lr_policy: "inv"
gamma: 0.0001
power: 0.75
#stepsize: 10000 # Drop the learning rate in steps by a factor of gamma every stepsize iterations
# Display every 100 iterations
display: 100
# The maximum number of iterations
max_iter: 10000
# snapshot intermediate results, that is, every 5000 iterations it saves a snapshot of the weights
snapshot: 5000
snapshot_prefix: "MyCaffeTrain/lenet_multistep"
# solver mode: CPU or GPU
solver_mode: CPU
</code></pre>
<p>And my train_test.prototxt file is:</p>
<pre><code>name: "LeNet"
layer {
name: "mnist"
type: "HDF5Data"
top: "data"
top: "label"
hdf5_data_param {
source: "MyCaffeTrain/train_h5_list.txt"
batch_size: 1000
}
include: { phase: TRAIN }
}
layer {
name: "mnist"
type: "HDF5Data"
top: "data"
top: "label"
hdf5_data_param {
source: "MyCaffeTrain/test_h5_list.txt"
batch_size: 1000
}
include: { phase: TEST }
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 20
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 2
stride: 2
}
}
layer {
name: "conv2"
type: "Convolution"
bottom: "pool1"
top: "conv2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 50
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool2"
type: "Pooling"
bottom: "conv2"
top: "pool2"
pooling_param {
pool: MAX
kernel_size: 2
stride: 2
}
}
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool2"
top: "ip1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 500
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "relu1"
type: "ReLU"
bottom: "ip1"
top: "ip1"
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 10
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "accuracy"
type: "Accuracy"
bottom: "ip2"
bottom: "label"
top: "accuracy"
include {
phase: TEST
}
}
layer {
name: "loss"
type: "EuclideanLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
</code></pre>
<p>But when I train, I get this error:</p>
<pre><code>I0914 13:59:33.198423 8251 layer_factory.hpp:74] Creating layer mnist
I0914 13:59:33.198452 8251 net.cpp:96] Creating Layer mnist
I0914 13:59:33.198467 8251 net.cpp:415] mnist -> data
I0914 13:59:33.198510 8251 net.cpp:415] mnist -> label
I0914 13:59:33.198532 8251 net.cpp:160] Setting up mnist
I0914 13:59:33.198549 8251 hdf5_data_layer.cpp:80] Loading list of HDF5 filenames from: MyCaffeTrain/train_h5_list.txt
I0914 13:59:33.198884 8251 hdf5_data_layer.cpp:94] Number of HDF5 files: 1
F0914 13:59:33.200848 8251 io.cpp:237] Check failed: H5LTfind_dataset(file_id, dataset_name_) Failed to find HDF5 dataset data
*** Check failure stack trace: ***
@ 0x7fcfa9fb05cd google::LogMessage::Fail()
@ 0x7fcfa9fb2433 google::LogMessage::SendToLog()
@ 0x7fcfa9fb015b google::LogMessage::Flush()
@ 0x7fcfa9fb2e1e google::LogMessageFatal::~LogMessageFatal()
@ 0x7fcfaa426b13 caffe::hdf5_load_nd_dataset_helper<>()
@ 0x7fcfaa423ec5 caffe::hdf5_load_nd_dataset<>()
@ 0x7fcfaa34bd3d caffe::HDF5DataLayer<>::LoadHDF5FileData()
@ 0x7fcfaa345ae6 caffe::HDF5DataLayer<>::LayerSetUp()
@ 0x7fcfaa3fdd75 caffe::Net<>::Init()
@ 0x7fcfaa4001ff caffe::Net<>::Net()
@ 0x7fcfaa40b935 caffe::Solver<>::InitTrainNet()
@ 0x7fcfaa40cd6e caffe::Solver<>::Init()
@ 0x7fcfaa40cf36 caffe::Solver<>::Solver()
@ 0x411980 caffe::GetSolver<>()
@ 0x4093a6 train()
@ 0x406de0 main
@ 0x7fcfa9049830 __libc_start_main
@ 0x407319 _start
@ (nil) (unknown)
</code></pre>
<p>I have tried my best but still cannot find the reason behind this error.
Is my created database in correct format? I read somewhere that the data format should be:</p>
<pre><code>N, C, H, W (No. of Data, Channels, Height, Width)
For my case: 1000,1,224,224
on checking X.shape I get the same result : 1000,1,224,224
</code></pre>
<p>I am not getting where I am doing wrong. Any help would be appreciated. Thanks in advance.</p>
| 0 |
2016-09-14T08:10:41Z
| 39,503,530 |
<p>I solved the problem making following changes to the code:</p>
<pre><code>H.create_dataset( 'data', data=X ) # note the name X given to the dataset! Replaced X by data
H.create_dataset( 'label', data=y ) # note the name y given to the dataset! Replaced y by label
</code></pre>
<p>The error was gone.</p>
<p>I'm still having the problem with EuclideanLoss layer though I'll look onto it and post another question if required.</p>
| 0 |
2016-09-15T05:11:07Z
|
[
"python",
"regression",
"caffe",
"hdf5"
] |
Python: urllib2.URLError: <urlopen error [Errno 10060]
| 39,485,564 |
<p>I have some problem with reading some urls.</p>
<p>I try to use answer from this question <a href="http://stackoverflow.com/questions/5620263/using-an-http-proxy-python">Using an HTTP PROXY - Python </a> but it didn't help and I get an error <code>urllib2.URLError: <urlopen error [Errno 10060]</code></p>
<p>I have a list of url</p>
<pre><code>yandex.ru/search?text=авиÑо&lr=47
yandex.ru/search?text=ÑвеÑок%20киддиленд%20мÑзÑкалÑнÑй&lr=47
dns-shop.ru/product/c7bf1138670f3361/rul-hori-racing-wheel
dns-shop.ru/product/c7bf1138670f3361/rul-hori-racing-wheel#opinion
kaluga.onlinetrade.ru/catalogue/ruli_dgoystiki_geympadi-c31/hori/reviews/rul_hori_racing_wheel_controller_ps_4_ps4_020e_acps440-274260.html
kazan.onlinetrade.ru/catalogue/ruli_dgoystiki_geympadi-c31/hori/reviews/rul_hori_racing_wheel_controller_xboxone_xbox_005u_acxone34-274261.html
ebay.com
</code></pre>
<p>And code looks like </p>
<pre><code>for url in urls:
proxy = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
try:
html = urllib2.urlopen(url).read()
except ValueError or urllib2:
url = 'http://www.' + url
html = urllib2.urlopen(url).read()
</code></pre>
<p>Also I try </p>
<pre><code>s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}
for url in urls:
url = 'http://www.' + url
r = s.get(url)
print(r.text)
</code></pre>
<p>And it returns me </p>
<pre><code>requests.exceptions.ProxyError: HTTPConnectionPool(host='61.233.25.166', port=80): Max retries exceeded with url: http://www.yandex.ru/search?text=%D0%B8%D0%B3%D1%80%D1%83%D1%88%D0%BA%D0%B0%20%22%D0%B2%D0%B5%D1%81%D0%B5%D0%BB%D0%B0%D1%8F%20%D0%B3%D1%83%D1%81%D0%B5%D0%BD%D0%B8%D1%86%D0%B0%22%20keenway%20%D0%BE%D1%82%D0%B7%D1%8B%D0%B2%D1%8B&lr=47 (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x047D1090>: Failed to establish a new connection: [Errno 10060] \xcf\xee\xef\xfb\xf2\xea\xe0 \xf3\xf1\xf2\xe0\xed\xee\xe2\xe8\xf2\xfc \xf1\xee\xe5\xe4\xe8\xed\xe5\xed\xe8\xe5 \xe1\xfb\xeb\xe0 \xe1\xe5\xe7\xf3\xf1\xef\xe5\xf8\xed\xee\xe9, \xf2.\xea. \xee\xf2 \xe4\xf0\xf3\xe3\xee\xe3\xee \xea\xee\xec\xef\xfc\xfe\xf2\xe5\xf0\xe0 \xe7\xe0 \xf2\xf0\xe5\xe1\xf3\xe5\xec\xee\xe5 \xe2\xf0\xe5\xec\xff \xed\xe5 \xef\xee\xeb\xf3\xf7\xe5\xed \xed\xf3\xe6\xed\xfb\xe9 \xee\xf2\xea\xeb\xe8\xea, \xe8\xeb\xe8 \xe1\xfb\xeb\xee \xf0\xe0\xe7\xee\xf0\xe2\xe0\xed\xee \xf3\xe6\xe5 \xf3\xf1\xf2\xe0\xed\xee\xe2\xeb\xe5\xed\xed\xee\xe5 \xf1\xee\xe5\xe4\xe8\xed\xe5\xed\xe8\xe5 \xe8\xe7-',)))
</code></pre>
<p>Where is error there? </p>
| 0 |
2016-09-14T08:13:56Z
| 39,486,250 |
<p>Some of proxies didn't work.
And I use <code>urllib</code> instead <code>urllib2</code> and </p>
<pre><code>for url in urls:
proxies = {'http': 'http://109.172.106.3:9999', 'http': 'http://62.113.208.183:3128', 'http': 'http://178.22.148.122:3129', 'http': 'http://217.17.46.162:3128'}
url = 'http://www.' + url
html = urllib.urlopen(url, proxies=proxies).read()
</code></pre>
<p>And it works for me</p>
| 0 |
2016-09-14T08:51:46Z
|
[
"python",
"urllib2"
] |
Reverse characters of string in subset of 3
| 39,485,624 |
<p>Let say my string is as:</p>
<pre><code>x = 'abcdefghi'
</code></pre>
<p>I want to reverse it in subsets of 3, so that my output is:</p>
<pre><code>x = 'cbafedihg'
</code></pre>
<p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p>
<p>Below is my code based on converting the <code>string</code> to <code>list</code> and swap the elements within the list:</p>
<pre><code>string_list = list(x)
for i in range(len(string_list)/3):
string_list[i*3], string_list[i*3+2] = string_list[i*3+2], string_list[i*3]
''.join(string_list)
# Output: 'cbafedihg'
</code></pre>
<p>I want to know what will be the most efficient and most pythonic way to achieve it. </p>
<p>Note: <code>len(x)%3</code> will always be 0.</p>
| 0 |
2016-09-14T08:17:17Z
| 39,485,639 |
<p>The above code can be written using <code>string slicing</code> and <code>list comprehension</code> as:</p>
<pre><code># Here x[i*3:i*3+3][::-1] will reverse the substring of 3 chars
>>> ''.join([x[i*3:i*3+3][::-1] for i in range(len(x)/3)])
'cbafedihg'
</code></pre>
<p>Based on the comment by <a href="http://stackoverflow.com/users/2291710/delgan">Delgan</a>, it could be further simplified using <code>step</code> as 3 with <code>range</code> itself as:</p>
<pre><code>>>> ''.join(x[i:i+3][::-1] for i in range(0, len(x), 3))
'cbafedihg'
</code></pre>
| 6 |
2016-09-14T08:17:58Z
|
[
"python",
"string",
"python-2.7"
] |
Reverse characters of string in subset of 3
| 39,485,624 |
<p>Let say my string is as:</p>
<pre><code>x = 'abcdefghi'
</code></pre>
<p>I want to reverse it in subsets of 3, so that my output is:</p>
<pre><code>x = 'cbafedihg'
</code></pre>
<p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p>
<p>Below is my code based on converting the <code>string</code> to <code>list</code> and swap the elements within the list:</p>
<pre><code>string_list = list(x)
for i in range(len(string_list)/3):
string_list[i*3], string_list[i*3+2] = string_list[i*3+2], string_list[i*3]
''.join(string_list)
# Output: 'cbafedihg'
</code></pre>
<p>I want to know what will be the most efficient and most pythonic way to achieve it. </p>
<p>Note: <code>len(x)%3</code> will always be 0.</p>
| 0 |
2016-09-14T08:17:17Z
| 39,486,323 |
<p>Simply swap the elements of list with step as 3:</p>
<pre><code>>>> string_list = list(x)
>>> string_list[::3], string_list[2::3] = string_list[2::3], string_list[::3]
>>> ''.join(string_list)
'cbafedihg'
</code></pre>
| 1 |
2016-09-14T08:55:17Z
|
[
"python",
"string",
"python-2.7"
] |
Reverse characters of string in subset of 3
| 39,485,624 |
<p>Let say my string is as:</p>
<pre><code>x = 'abcdefghi'
</code></pre>
<p>I want to reverse it in subsets of 3, so that my output is:</p>
<pre><code>x = 'cbafedihg'
</code></pre>
<p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p>
<p>Below is my code based on converting the <code>string</code> to <code>list</code> and swap the elements within the list:</p>
<pre><code>string_list = list(x)
for i in range(len(string_list)/3):
string_list[i*3], string_list[i*3+2] = string_list[i*3+2], string_list[i*3]
''.join(string_list)
# Output: 'cbafedihg'
</code></pre>
<p>I want to know what will be the most efficient and most pythonic way to achieve it. </p>
<p>Note: <code>len(x)%3</code> will always be 0.</p>
| 0 |
2016-09-14T08:17:17Z
| 39,486,947 |
<p>Writing a function that is more readable and flexible?</p>
<pre><code>def get_string(input_str, step=3):
output = ""
i = 0
for _ in list(input_str):
if i == len(input_str):
return output
elif i+step-1 >= len(input_str):
output += input[len(input_str)-1:i-1:-1]
return output
else:
output += input_str[i+step-1:i:-1] + input_str[i]
i += step
return output
</code></pre>
<p>And here comes the flexible part:</p>
<pre><code>get_string("abcdefghi")
# Ouputs 'cbafedihg'
get_string("abcdefghi", 2)
# Outputs 'badcfehgi'
get_string("abcdefghi", 5)
# Outputs 'edcbaihgf'
</code></pre>
<p>Not to mention, if you want to add some more logic or change the logic, it is easier to change here.</p>
| 0 |
2016-09-14T09:27:23Z
|
[
"python",
"string",
"python-2.7"
] |
How to create a loop from this code?
| 39,485,625 |
<p>I have a python routine which puts PDF pages in booklet spread order. I'm trying to improve the code: there's a bit where I'm doing almost the same thing twice. When I write out the iteration, it works, but when I try to make it more general with more loops, it doesn't. The code puts two PDF pages onto a larger PDF page.</p>
<pre><code># For each side of the sheet, we must create a PDF page,
# take two source pages and place them differently, then close the page.
# If the source page number is 0, then move on without drawing.
Sides = len(imposedOrder) / pagesPerSide
count = 0
for n in range(Sides):
Quartz.CGContextBeginPage(writeContext, sheetSize)
if imposedOrder[count]:
page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
Quartz.CGContextSaveGState(writeContext)
Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, leftPage, 0, True))
Quartz.CGContextDrawPDFPage(writeContext, page)
Quartz.CGContextRestoreGState(writeContext)
count += 1
if imposedOrder[count]:
page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
Quartz.CGContextSaveGState(writeContext)
Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, rightPage, 0, True))
Quartz.CGContextDrawPDFPage(writeContext, page)
Quartz.CGContextRestoreGState(writeContext)
count += 1
Quartz.CGContextEndPage(writeContext)
</code></pre>
<p>So the only bit that is different each time is whether we use leftPage or rightPage. </p>
<p>Here's the version that DOESN'T work:</p>
<pre><code>count = 0
for n in range(Sides):
Quartz.CGContextBeginPage(writeContext, sheetSize)
for nn in range (1, pagesPerSide+1):
if nn%2 == 1:
position = leftPage
else:
position = rightPage
if imposedOrder[count]:
page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
Quartz.CGContextSaveGState(writeContext)
Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, position, 0, True))
Quartz.CGContextDrawPDFPage(writeContext, page)
Quartz.CGContextRestoreGState(writeContext)
count += 1
Quartz.CGContextEndPage(writeContext)
</code></pre>
| 0 |
2016-09-14T08:17:22Z
| 39,488,897 |
<p>This now works. I have no idea what has changed.</p>
<p>Many thanks for looking at it.</p>
| 0 |
2016-09-14T11:06:33Z
|
[
"python",
"logic"
] |
split cell to rows by pipe python
| 39,485,728 |
<p>I am trying to split a cell into 2 rows by pipe ("|").</p>
<p>For instance:</p>
<pre><code>ID Site Category Queries
1 0 38037 antique+wall+telephone|antique+wall+phone
</code></pre>
<p>will become:</p>
<pre><code>ID Site Category Queries
1 0 38037 antique+wall+telephone
1 0 38037 antique+wall+phone
</code></pre>
| 2 |
2016-09-14T08:23:21Z
| 39,485,857 |
<p>You can use .split()</p>
<pre><code>input = "antique+wall+telephone|antique+wall+phone"
output = input.split('|')
</code></pre>
<p>output will be a list of elements either side of the '|'</p>
<p>so output would be</p>
<pre><code>("antique+wall+telephone", "antique+wall+phone")
</code></pre>
<p>and then you can simply add the ID Number in front of each element of the list of strings</p>
<p>Hope that answers your question</p>
| 0 |
2016-09-14T08:31:15Z
|
[
"python"
] |
split cell to rows by pipe python
| 39,485,728 |
<p>I am trying to split a cell into 2 rows by pipe ("|").</p>
<p>For instance:</p>
<pre><code>ID Site Category Queries
1 0 38037 antique+wall+telephone|antique+wall+phone
</code></pre>
<p>will become:</p>
<pre><code>ID Site Category Queries
1 0 38037 antique+wall+telephone
1 0 38037 antique+wall+phone
</code></pre>
| 2 |
2016-09-14T08:23:21Z
| 39,485,928 |
<p>Here's one way:</p>
<pre><code>>>> id, site, category, queries
('1', '0', '38037', 'antique+wall+telephone|antique+wall+phone')
>>> for query in queries.split('|'):
... print id, site, category, query
...
1 0 38037 antique+wall+telephone
1 0 38037 antique+wall+phone
</code></pre>
| 2 |
2016-09-14T08:34:40Z
|
[
"python"
] |
split cell to rows by pipe python
| 39,485,728 |
<p>I am trying to split a cell into 2 rows by pipe ("|").</p>
<p>For instance:</p>
<pre><code>ID Site Category Queries
1 0 38037 antique+wall+telephone|antique+wall+phone
</code></pre>
<p>will become:</p>
<pre><code>ID Site Category Queries
1 0 38037 antique+wall+telephone
1 0 38037 antique+wall+phone
</code></pre>
| 2 |
2016-09-14T08:23:21Z
| 39,489,374 |
<p>Using talend, You can also use tNormalize component : you just have to specify the column to normalize in the dropdown menu. Be careful if you want to use "|" as the item separator, as it is a reserved character, you have to escape it using "\|".
<a href="http://i.stack.imgur.com/IuYbI.png" rel="nofollow"><img src="http://i.stack.imgur.com/IuYbI.png" alt="enter image description here"></a></p>
| 0 |
2016-09-14T11:32:48Z
|
[
"python"
] |
python running coverage on never ending process
| 39,485,731 |
<p>I have a multi processed web server with processes that never end, I would like to check my code coverage on the whole project in a live environment (not only from tests).</p>
<p>The problem is, that since the processes never end, I don't have a good place to set the <code>cov.start() cov.stop() cov.save()</code> hooks.</p>
<p>Therefore, I thought about spawning a thread that in an infinite loop will save and combine the coverage data and then sleep some time, however this approach doesn't work, the coverage report seems to be empty, except from the sleep line.</p>
<p>I would be happy to receive any ideas about how to get the coverage of my code,
or any advice about why my idea doesn't work. Here is a snippet of my code:</p>
<pre><code>import coverage
cov = coverage.Coverage()
import time
import threading
import os
class CoverageThread(threading.Thread):
_kill_now = False
_sleep_time = 2
@classmethod
def exit_gracefully(cls):
cls._kill_now = True
def sleep_some_time(self):
time.sleep(CoverageThread._sleep_time)
def run(self):
while True:
cov.start()
self.sleep_some_time()
cov.stop()
if os.path.exists('.coverage'):
cov.combine()
cov.save()
if self._kill_now:
break
cov.stop()
if os.path.exists('.coverage'):
cov.combine()
cov.save()
cov.html_report(directory="coverage_report_data.html")
print "End of the program. I was killed gracefully :)"
</code></pre>
| 4 |
2016-09-14T08:23:37Z
| 39,488,674 |
<p>Since you are willing to run your code differently for the test, why not add a way to end the process for the test? That seems like it will be simpler than trying to hack coverage.</p>
| 0 |
2016-09-14T10:55:34Z
|
[
"python",
"multithreading",
"python-multiprocessing",
"coverage.py"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.