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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Removing \xa0 from string in a list | 38,830,308 | <p>I have a list with a bunch of words:</p>
<pre><code>lista = ['Jeux Olympiques De Rio\xa02016', 'Sahara Ray', 'Michael Phelps', 'Amber Alert']
</code></pre>
<p>I tried to replace the <code>'\xa0'</code>:</p>
<pre><code>for element in listor:
element = element.replace('\xa0',' ')
</code></pre>
<p>But it didn't work. Also, when I <code>print</code> the elements, it prints:</p>
<pre><code>print(lista[0])
Jeux Olympiques De Rio 2016
</code></pre>
<p>Does anyone have an idea on how to solve this?</p>
| 1 | 2016-08-08T13:19:36Z | 38,830,660 | <p>the easiest way:</p>
<pre><code>lista = [el.replace('\xa0',' ') for el in lista]
</code></pre>
| 2 | 2016-08-08T13:35:14Z | [
"python",
"string",
"python-3.x"
] |
Using py2neo v3 with google app engine | 38,830,407 | <p>I'm trying to set a backend using py2neo on google app engine. It works just fine when pushed on the dev on app engine, however, unfortunately, it doesn't work when I use it on localhost.</p>
<p>First, i've setted the HOME environment variable in python (thanks to that tip, my code works on my dev) but it doesn't fix the localhost problem</p>
<p>Then, i've followed that advice <a href="http://stackoverflow.com/questions/16192916/importerror-no-module-named-ssl-with-dev-appserver-py-from-google-app-engine/16937668#16937668">"ImportError: No module named _ssl" with dev_appserver.py from Google App Engine</a>
it prevents one exception but another rises after.</p>
<p>Here is my traceback</p>
<pre><code> ft1.1: Traceback (most recent call last):
File "/Users/Arnaud/Documents/project/app/test/neo4j/test_graph_handler.py", line 13, in test_get_direct_neighbours
selection = self.graph_handler.get_direct_neighbours("8")
File "/Users/Arnaud/Documents/project/app/neo4j/graph_handler.py", line 20, in get_direct_neighbours
labels(l) AS `relationship`" % self.protect(ean))
File "/Users/Arnaud/Documents/project/app/libs/py2neo/database/__init__.py", line 694, in run
return self.begin(autocommit=True).run(statement, parameters, **kwparameters)
File "/Users/Arnaud/Documents/project/app/libs/py2neo/database/__init__.py", line 370, in begin
return self.transaction_class(self, autocommit)
File "/Users/Arnaud/Documents/project/app/libs/py2neo/database/__init__.py", line 1212, in __init__
self.session = driver.session()
File "/Users/Arnaud/Documents/project/app/libs/py2neo/packages/neo4j/v1/session.py", line 126, in session
connection = connect(self.address, self.ssl_context, **self.config)
File "/Users/Arnaud/Documents/project/app/libs/py2neo/packages/neo4j/v1/bolt.py", line 444, in connect
if not store.match_or_trust(host, der_encoded_server_certificate):
File "/Users/Arnaud/Documents/project/app/libs/py2neo/packages/neo4j/v1/bolt.py", line 397, in match_or_trust
f_out = os_open(self.path, O_CREAT | O_APPEND | O_WRONLY, 0o600) # TODO: Windows
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 73, in fake_open
raise OSError(errno.EROFS, 'Read-only file system', filename)
OSError: [Errno 30] Read-only file system: '/Users/Arnaud/.neo4j/known_hosts'
</code></pre>
<p>As everything lauches in a sandboxed environnement and with a fake user, the exception is normal but it does not happen on the dev.</p>
<p>And here is /Users/Arnaud/Documents/project/app/neo4j/graph_handler.py:20</p>
<pre><code> 13 def get_direct_neighbours(self, ean):
14 selection = self.graph.run("\
15 MATCH\
16 (:Product {ean: '%s'})-->(l)<--(n:Product)\
17 RETURN\
18 n.ean AS `ean`,\
19 n.name AS `name`,\
20 labels(l) AS `relationship`" % self.protect(ean))
21 return selection
</code></pre>
<p>So to understand why it would work on the dev, I tried to localize where sandbox and dev execution start being different. and it is right here in
/Users/Arnaud/Documents/project/app/libs/py2neo/packages/neo4j/v1/bolt.py:427</p>
<pre><code>427 if ssl_context and SSL_AVAILABLE:
428 host, port = host_port
429 if __debug__: log_info("~~ [SECURE] %s", host)
430 try:
431 s = ssl_context.wrap_socket(s, server_hostname=host if HAS_SNI else None)
432 except SSLError as cause:
433 error = ProtocolError("Cannot establish secure connection; %s" % cause.args[1])
434 error.__cause__ = cause
435 raise error
436 else:
437 # Check that the server provides a certificate
438 der_encoded_server_certificate = s.getpeercert(binary_form=True)
439 if der_encoded_server_certificate is None:
440 raise ProtocolError("When using a secure socket, the server should always provide a certificate")
441 trust = config.get("trust", TRUST_DEFAULT)
442 if trust == TRUST_ON_FIRST_USE:
443 store = PersonalCertificateStore()
444 if not store.match_or_trust(host, der_encoded_server_certificate):
445 raise ProtocolError("Server certificate does not match known certificate for %r; check "
446 "details in file %r" % (host, KNOWN_HOSTS))
447 else:
448 der_encoded_server_certificate = None
</code></pre>
<p>Because in the dev, ssl loading fails in ssl_compat.py while on localhost, it succeeds and so the code goes inside the if statement and fails at line 444</p>
<p>To understand that I forced SSL_AVAILABLE to be falsy, however even with that I have wierd problems about app engine sockets which are not recognized as sockets</p>
<pre><code>ft1.1: Traceback (most recent call last):
File "/Users/Arnaud/Documents/project/app/test/neo4j/test_graph_handler.py", line 13, in test_get_direct_neighbours
selection = self.graph_handler.get_direct_neighbours("8")
File "/Users/Arnaud/Documents/project/app/neo4j/graph_handler.py", line 20, in get_direct_neighbours
labels(l) AS `relationship`" % self.protect(ean))
File "/Users/Arnaud/Documents/project/app/libs/py2neo/database/__init__.py", line 694, in run
return self.begin(autocommit=True).run(statement, parameters, **kwparameters)
File "/Users/Arnaud/Documents/project/app/libs/py2neo/database/__init__.py", line 370, in begin
return self.transaction_class(self, autocommit)
File "/Users/Arnaud/Documents/project/app/libs/py2neo/database/__init__.py", line 1212, in __init__
self.session = driver.session()
File "/Users/Arnaud/Documents/project/app/libs/py2neo/packages/neo4j/v1/session.py", line 126, in session
connection = connect(self.address, self.ssl_context, **self.config)
File "/Users/Arnaud/Documents/project/app/libs/py2neo/packages/neo4j/v1/bolt.py", line 460, in connect
ready_to_read, _, _ = select((s,), (), (), 0)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 483, in select
_SetState(request, _GetSocket(value), POLLIN)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 425, in _GetSocket
raise ValueError('select only supported on socket objects.')
ValueError: select only supported on socket objects.
</code></pre>
<p>If anyone have faced the same issues, I would be interested in that because having to push on the dev before any test quite painful.</p>
<p><strong>EDIT:</strong>
For those who would want to know, as I have no answer from nigel yet and I needed some fast solution, i've created my own class to send and recieve cypher requests, it's compatible with app engine and i've putted it on a gist: <a href="https://gist.github.com/ArnaudParan/e26f291ba8b3c08e5b762d549667c7d6" rel="nofollow">https://gist.github.com/ArnaudParan/e26f291ba8b3c08e5b762d549667c7d6</a> It's experimental and might not work if you ask for full nodes but if it can help, i publish it</p>
| 0 | 2016-08-08T13:23:49Z | 38,831,353 | <p>The 1st traceback could indicate that the py2neo package may be incompatible with <a href="https://cloud.google.com/appengine/docs/python/runtime#Python_The_sandbox" rel="nofollow">GAE's sandbox restrictions</a>. In particular it shows an attempt to open the <code>/Users/Arnaud/.neo4j/known_hosts</code> file in write mode (<code>os_open(self.path, O_CREAT | O_APPEND | O_WRONLY, 0o600)</code>) which is not allowed. Check if it's somehow possible to configure py2neo to not do that.</p>
<p>The sandbox also has restrictions on sockets, see <a href="https://cloud.google.com/appengine/docs/python/sockets/#limitations_and_restrictions" rel="nofollow">Limitations and restrictions</a>.</p>
| 0 | 2016-08-08T14:05:23Z | [
"python",
"google-app-engine",
"ssl",
"neo4j",
"py2neo"
] |
Groupby and any() | all() | 38,830,423 | <p>I have the following <code>pd.DataFrame</code></p>
<pre><code>In [155]: df1
Out[155]:
ORDER_ID ACQ DATE UID
2 3 False 2014-01-03 1
3 4 True 2014-01-04 2
4 5 False 2014-01-05 3
6 7 True 2014-01-08 5
7 8 False 2014-01-08 5
9 10 False 2014-01-10 6
0 11 False 2014-01-11 6
</code></pre>
<p>where each entry is an order, with values for <code>ORDER_ID</code>, <code>DATE</code>, <code>UID</code> and <code>ACQ</code> (indicates whether this is the first order for the associated <code>UID</code> in the dataset).</p>
<p>I am trying to filter and keep all orders that were placed by users that have made their first order inside the time period covered in the dataset (i.e. at least one of the orders of such users satisfy <code>ACQ == True</code>).</p>
<p>So, the desired output would be:</p>
<pre><code> ORDER_ID ACQ DATE UID
3 4 True 2014-01-04 2
6 7 True 2014-01-08 5
7 8 False 2014-01-08 5
</code></pre>
<p>and I have managed to reach this by:</p>
<pre><code>In [156]: df1.groupby('UID').filter(lambda x: x.ACQ.any() == True)
Out[156]:
ORDER_ID ACQ DATE UID
3 4 True 2014-01-04 2
6 7 True 2014-01-08 5
7 8 False 2014-01-08 5
</code></pre>
<p>However, when I try to find all the orders that were placed by users that have made their first order outside the time period covered in the dataset (i.e. All their orders should satisfy <code>ACQ == False</code>) I seem to be lost. I have tried this:</p>
<pre><code>In [159]: df1.groupby('UID').filter(lambda x: x.ACQ.all() == False)
Out[159]:
ORDER_ID ACQ DATE UID
2 3 False 2014-01-03 1
4 5 False 2014-01-05 3
6 7 True 2014-01-08 5 ## <- This order is an acquisition, therefore all orders with UID == 5 should be filtered out.
7 8 False 2014-01-08 5
9 10 False 2014-01-10 6
0 11 False 2014-01-11 6
</code></pre>
<p>How should I go about filtering out all the orders placed by users that have ALL their orders satisfy <code>ACQ == False</code>?</p>
<p>Any ideas are very much appreciated, thanks!</p>
| 2 | 2016-08-08T13:24:27Z | 38,830,719 | <p>You need first use condition and then add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.all.html" rel="nofollow"><code>all</code></a>:</p>
<pre><code>print (df1.groupby('UID').filter(lambda x: (x.ACQ == False).all()))
ORDER_ID ACQ DATE UID
2 3 False 2014-01-03 1
4 5 False 2014-01-05 3
9 10 False 2014-01-10 6
0 11 False 2014-01-11 6
</code></pre>
| 1 | 2016-08-08T13:38:07Z | [
"python",
"pandas"
] |
Non-error message from another script when importing library | 38,830,469 | <p>I produced a very strange error today, using Python 2.7 on a Windows 10 system. I wrote a Python script, <code>C:\Users\$me\copy.py</code> looking something like this:</p>
<pre><code>import subprocess
import sys
try:
out = subprocess.check_output("do_stuff.bat")
except subprocess.CalledProcessError as e:
print "Doing stuff failed."
do_stuff_did_something = out.find("String to be found in do_stuffs output.")
if do_stuff_did_something == -1:
print "Do_stuff didn't do it."
else:
print "Do_stuff did do it."
</code></pre>
<p>So far, so good, this works perfectly fine and does what it's supposed to do: run the batch file, look for a specific string in its output, and return a message according to whether it found the string or not.</p>
<p>Some time afterwards, I installed the OpenOPC library. At some point which I don't clearly remember, this started happening:</p>
<pre><code>C:\Users\$me>python
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import OpenOPC
Do_stuff did do it.
>>>
</code></pre>
<p>This also happens if I run a <code>python script.py</code> including the OpenOPC import. It does not happen with any other libraries (that I tried). And it's not an error message since OpenOPC works perfectly fine. I'm just afraid that I somehow messed up something which might catch me later.</p>
<p>I couldn't find a clue in <code>OpenOPC.py</code> as to when this message might get printed.</p>
<p>The error persists after rebooting.</p>
<p>So what happened here? How can I fix it?</p>
| 4 | 2016-08-08T13:26:31Z | 38,830,626 | <p>It's possible that your script is getting imported before (or because Python thinks it is part of) the <code>OpenOPC</code> library. Is your script by chance called <code>OpenOPC.py</code> or similar, or does it reside in a <a href="http://docs.python-guide.org/en/latest/writing/structure/#packages" rel="nofollow">package/folder hierarchy</a>?</p>
<p>Alternatively, where did you save your original script? Is it in the package/module hierarchy of OpenOPC? That might also trigger its load in some unusual cases.</p>
<p>Lastly: does the error behavior reoccur if your run your <code>python somescript.py</code> (where <code>somescript.py</code> is <em>not</em> the one containing the script content at the top of your question) from a new/different directory than the one you've been usually running it from?</p>
<p>All of those tweaks will try to isolate the problem away from the situation in which your script is getting interpreted as part of the OpenOPC module. That's an unusual situation to be in, but is possible; if the problematic behavior goes away due to any of those steps, move/rename your script.</p>
| 1 | 2016-08-08T13:33:42Z | [
"python"
] |
How to take info from particular amount of elements with the same class name? | 38,830,500 | <p>I have a lot of tables on the same screen. And i need to take tex from only one of it
Simple example:
Table:Phone</p>
<pre><code>div id="phone_type" type-id="pass" class="panel panel-default sort_table">
<div class="panel-heading">
<h3 class="panel-title">PHONE</h3>
</div>
<ul class="list-group ui-sortable">
<li class="list-group-item ui-sortable-handle" id="pass">
<div class="row">
<div class="col-md-8 col-xs-8 increase_padding">Home</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" href="pass">Edit</a>
</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" rel="nofollow" data-method="delete" href="pass">Delete</a>
</div>
</div>
</li>
<li class="list-group-item ui-sortable-handle" id="pass">
<div class="row">
<div class="col-md-8 col-xs-8 increase_padding">Work</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" href="pass">Edit</a>
</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" rel="nofollow" data-method="delete" href="pass">Delete</a>
</div>
</div>
</li>
</ul>
</form>
</div>
</div>
</code></pre>
<p>Table:Condo</p>
<pre><code> <div id="condo_type" type-id="pass" class="panel panel-default sort_table">
<div class="panel-heading">
<h3 class="panel-title">CONDO</h3>
</div>
<ul class="list-group ui-sortable">
<li class="list-group-item ui-sortable-handle" id="pass">
<div class="row">
<div class="col-md-8 col-xs-8 increase_padding">Limited</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" href="pass">Edit</a>
</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" rel="nofollow" data-method="delete" href="pass">Delete</a>
</div>
</div>
</li>
<li class="list-group-item ui-sortable-handle" id="pass">
<div class="row">
<div class="col-md-8 col-xs-8 increase_padding">Free</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" href="pass">Edit</a>
</div>
<div class="col-md-2 col-xs-2 text-center">
<a data-remote="true" rel="nofollow" data-method="delete" href="pass">Delete</a>
</div>
</div>
</li>
</ul>
</form>
</div>
</div>
</code></pre>
<p>And i need to take text of <code>col-md-8 col-xs-8 increase_padding</code></p>
<p>But the problem is that when i am using:</p>
<pre><code>table_content = driver.find_elements_by_css_selector('.col-md-8.col-xs-8.increase_padding')
</code></pre>
<p>it also takes info from tables that i am currently don't need.
But i need to take text only from 1 particular table.
Those tables are dynamic, so I can't take particular amount from </p>
<pre><code>table_content
</code></pre>
<p>and append it to another list.
Is it a way to address to particular table and work with its outer HTML?</p>
| 0 | 2016-08-08T13:28:16Z | 38,830,711 | <p>Just make <em>context-specific searches</em>. E.g. If you need this element from a "phone type" table:</p>
<pre><code>phone_type = driver.find_element_by_id("phone_type")
print(phone_type.find_element_by_css_selector('.col-md-8.col-xs-8.increase_padding').text)
</code></pre>
<p>Or, in one go:</p>
<pre><code>print(driver.find_element_by_css_selector('#phone_type .col-md-8.col-xs-8.increase_padding').text)
</code></pre>
| 4 | 2016-08-08T13:37:43Z | [
"python",
"selenium-webdriver"
] |
To redirect os.system() output to a .txt file | 38,830,596 | <p>I'm new to Python. I have list of Unix commmands <code>("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")</code> and I want to run them and redirect the entire output to a <code>.txt</code> file. I searched a lot but didn't get a proper solution, or I understood things wrongly.</p>
<p>I'm able to get the output on stdout with this for loop but I can't redirect to a file. </p>
<pre><code>def commandsoutput():
command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")
for i in command:
print (os.system(i))
commandsoutput()
</code></pre>
| 2 | 2016-08-08T13:32:29Z | 38,830,757 | <p>This answer uses <code>os.popen</code>, which allows you to write the output of the command in your file:</p>
<pre><code>import os
def commandsoutput():
commands = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")
with open('output.txt','a') as outfile:
for command in commands:
outfile.write(os.popen(command).read()+"\n")
commandsoutput()
</code></pre>
| 1 | 2016-08-08T13:39:59Z | [
"python"
] |
To redirect os.system() output to a .txt file | 38,830,596 | <p>I'm new to Python. I have list of Unix commmands <code>("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")</code> and I want to run them and redirect the entire output to a <code>.txt</code> file. I searched a lot but didn't get a proper solution, or I understood things wrongly.</p>
<p>I'm able to get the output on stdout with this for loop but I can't redirect to a file. </p>
<pre><code>def commandsoutput():
command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")
for i in command:
print (os.system(i))
commandsoutput()
</code></pre>
| 2 | 2016-08-08T13:32:29Z | 38,830,786 | <p><code>os.system</code> returns the exit code of the command, not its output. It is also deprecated. </p>
<p>Use <code>subprocess</code> instead:</p>
<pre><code>import subprocess
def commandsoutput():
command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")
with open('log.txt', 'a') as outfile:
for i in command:
subprocess.call(i, stdout=outfile)
commandsoutput()
</code></pre>
| 3 | 2016-08-08T13:41:12Z | [
"python"
] |
Access Jupyter notebook running on Docker container | 38,830,610 | <p>I created a docker image with python libraries and Jupyter.
I start the container with the option <code>-p 8888:8888</code>, to link ports between host and container.
When I launch a Jupyter kernel inside the container, it is running on <code>localhost:8888</code> (and does not find a browser). I used the command <code>jupyter notebook</code></p>
<p>But from my host, what is the IP address I have to use to work with Jupyter in host's browser ? </p>
<p>With the command <code>ifconfig</code>, I find <code>eth0</code>, <code>docker</code>, <code>wlan0</code>, <code>lo</code> ...</p>
<p>Thanks ! </p>
| 0 | 2016-08-08T13:33:01Z | 38,936,551 | <p>You need to run your notebook on <code>0.0.0.0</code>: <code>jupyter notebook -i 0.0.0.0</code>. Running on localhost make it available only from inside the container.</p>
| 0 | 2016-08-13T20:07:00Z | [
"python",
"docker",
"jupyter-notebook"
] |
How to represent fractions in python | 38,830,869 | <p>I am trying to implement a method that takes a matrix from the matrix class i've defined and returns a triagonal matrix using gaussian elimination.
Consider the following matrix:</p>
<pre><code>m1 = [[2, -3, -4],
[-1, 4, 5],
[1, -3, -4]]
</code></pre>
<p>Basically i need to add to each row, a multiple of another previous row, until i end up with a matrix which has 0 in all places below the main diagonal. Following this process, i should have the following matrix:</p>
<pre><code>m2 = [[2, -3, -4],
[0, 5/2, 3],
[0, 0, -1/5]]
</code></pre>
<p>The problem is that fractions like 1/3 will often come up and i wouldn't want to lose precision by using floats. So is there any way to represent fractions? Will i have to define special behaviour for those?
For the sake of doing it by myself i don't want to use any external modules.</p>
| -1 | 2016-08-08T13:45:24Z | 38,830,986 | <p>There is a class that does exactly what you want: <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow"><code>fractions.Fraction</code></a>:</p>
<pre><code>>>> from fractions import Fraction
>>> print(Fraction(5, 6))
5/6
</code></pre>
<p>Fractions behave like regular numbers in most situations:</p>
<pre><code>>>> print(Fraction(5, 6) + 6)
41/6
>>> print(Fraction(5, 6) + Fraction(1, 2))
4/3
>>> print(Fraction(5, 6) + 17.445)
18.278333333333332
</code></pre>
<p>The last example shows that the fraction gets converted to a <code>float</code> if the other operand is a <code>float</code>. This makes sense, since you would not expect a float of undetermined precision to be converted to a <code>Fraction</code>.</p>
| 1 | 2016-08-08T13:50:26Z | [
"python",
"matrix",
"fractions"
] |
Django update model entry using form fails | 38,830,937 | <p>I want to update a model entry using a form. the problem is that instead of updating the entry it creates a new entry.</p>
<pre><code>def edit(request, c_id):
instance = get_object_or_404(C, id=int(c_id))
if request.POST:
form = CForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/a/b', c_id)
else:
form = CForm(instance=instance)
args = {}
args.update(csrf(request))
args['form'] = form
args['c_id'] = c_id
return render_to_response('a/b.html', args)
</code></pre>
<p>HTML code:</p>
<pre><code><form action="/a/edit/{{ c_id }}/" method="post">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<input type="submit" value="Submit"/>
</form>
</code></pre>
<p>CForm class code</p>
<pre><code>class CForm(forms.ModelForm):
class Meta:
model = C
fields = ['name', 'code']
</code></pre>
| 0 | 2016-08-08T13:48:12Z | 38,831,117 | <p>You're checking the request for a <code>POST</code> method incorrectly. <a href="https://docs.djangoproject.com/ja/1.9/ref/request-response/#django.http.HttpRequest.POST" rel="nofollow"><code>request.POST</code></a> isn't a boolean, it contains a dictionary of post variables and is always going to have the CSRF token in it so it will always be "truthy". What you need is <a href="https://docs.djangoproject.com/ja/1.9/ref/request-response/#django.http.HttpRequest.method" rel="nofollow"><code>request.method</code></a>.</p>
<p>Instead of:</p>
<pre><code>if request.POST:
</code></pre>
<p>Replace it with:</p>
<pre><code>if request.method == "POST":
</code></pre>
| 2 | 2016-08-08T13:56:22Z | [
"python",
"django",
"forms"
] |
How to make a function determining the winner of Tic-Tac-Toe more concise | 38,830,944 | <p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p>
<pre><code>import numpy as np
class Board():
def __init__(self, grid = np.ones((3,3))*np.nan):
self.grid = grid
def winner(self):
rows = [self.grid[i,:] for i in range(3)]
cols = [self.grid[:,j] for j in range(3)]
diag = [np.array([self.grid[i,i] for i in range(3)])]
cross_diag = [np.array([self.grid[2-i,i] for i in range(3)])]
lanes = np.concatenate((rows, cols, diag, cross_diag))
if any([np.array_equal(lane, np.ones(3)) for lane in lanes]):
return 1
elif any([np.array_equal(lane, np.zeros(3)) for lane in lanes]):
return 0
</code></pre>
<p>So for example, if I execute</p>
<pre><code>board = Board()
board.grid = np.diag(np.ones(3))
print board.winner()
</code></pre>
<p>I get the result <code>1</code>. What bothers me slightly is the repetition of the <code>any</code> statements. I would think there would be a more concise, DRY way of coding this. (I was thinking of a switch/case as in MATLAB but this doesn't exist in Python). Any suggestions?</p>
| 2 | 2016-08-08T13:48:32Z | 38,831,029 | <p>I have made a loop instead, and return only once, to conform with PEP8 and to be honest to my personal coding standards :)</p>
<p><code>enumerate</code> in the correct order will yield <code>0,zeromatrix</code> then <code>1,onematrix</code></p>
<pre><code>rval = None
for i,m in enumerate([np.zeros(3),np.ones(3)]):
if any([np.array_equal(lane, m) for lane in lanes]):
rval = i; break
return rval
</code></pre>
| 1 | 2016-08-08T13:52:20Z | [
"python",
"numpy"
] |
How to make a function determining the winner of Tic-Tac-Toe more concise | 38,830,944 | <p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p>
<pre><code>import numpy as np
class Board():
def __init__(self, grid = np.ones((3,3))*np.nan):
self.grid = grid
def winner(self):
rows = [self.grid[i,:] for i in range(3)]
cols = [self.grid[:,j] for j in range(3)]
diag = [np.array([self.grid[i,i] for i in range(3)])]
cross_diag = [np.array([self.grid[2-i,i] for i in range(3)])]
lanes = np.concatenate((rows, cols, diag, cross_diag))
if any([np.array_equal(lane, np.ones(3)) for lane in lanes]):
return 1
elif any([np.array_equal(lane, np.zeros(3)) for lane in lanes]):
return 0
</code></pre>
<p>So for example, if I execute</p>
<pre><code>board = Board()
board.grid = np.diag(np.ones(3))
print board.winner()
</code></pre>
<p>I get the result <code>1</code>. What bothers me slightly is the repetition of the <code>any</code> statements. I would think there would be a more concise, DRY way of coding this. (I was thinking of a switch/case as in MATLAB but this doesn't exist in Python). Any suggestions?</p>
| 2 | 2016-08-08T13:48:32Z | 38,831,050 | <p>I found out one way, by using a Lambda function:</p>
<pre><code>any_lane = lambda x: any([np.array_equal(lane, x) for lane in lanes])
if any_lane(np.ones(3)):
return 1
elif any_lane(np.zeros(3)):
return 0
</code></pre>
<p>This adds an extra line to the code but makes it more legible overall, I reckon.</p>
| 0 | 2016-08-08T13:53:26Z | [
"python",
"numpy"
] |
How to make a function determining the winner of Tic-Tac-Toe more concise | 38,830,944 | <p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p>
<pre><code>import numpy as np
class Board():
def __init__(self, grid = np.ones((3,3))*np.nan):
self.grid = grid
def winner(self):
rows = [self.grid[i,:] for i in range(3)]
cols = [self.grid[:,j] for j in range(3)]
diag = [np.array([self.grid[i,i] for i in range(3)])]
cross_diag = [np.array([self.grid[2-i,i] for i in range(3)])]
lanes = np.concatenate((rows, cols, diag, cross_diag))
if any([np.array_equal(lane, np.ones(3)) for lane in lanes]):
return 1
elif any([np.array_equal(lane, np.zeros(3)) for lane in lanes]):
return 0
</code></pre>
<p>So for example, if I execute</p>
<pre><code>board = Board()
board.grid = np.diag(np.ones(3))
print board.winner()
</code></pre>
<p>I get the result <code>1</code>. What bothers me slightly is the repetition of the <code>any</code> statements. I would think there would be a more concise, DRY way of coding this. (I was thinking of a switch/case as in MATLAB but this doesn't exist in Python). Any suggestions?</p>
| 2 | 2016-08-08T13:48:32Z | 38,831,389 | <p>Another option is to check the sum of <code>lanes</code>.</p>
<pre><code> s = np.sum(lanes, axis=1)
if 3 in s:
return 1
elif 0 in s:
return 0
</code></pre>
| 2 | 2016-08-08T14:06:35Z | [
"python",
"numpy"
] |
How to make a function determining the winner of Tic-Tac-Toe more concise | 38,830,944 | <p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p>
<pre><code>import numpy as np
class Board():
def __init__(self, grid = np.ones((3,3))*np.nan):
self.grid = grid
def winner(self):
rows = [self.grid[i,:] for i in range(3)]
cols = [self.grid[:,j] for j in range(3)]
diag = [np.array([self.grid[i,i] for i in range(3)])]
cross_diag = [np.array([self.grid[2-i,i] for i in range(3)])]
lanes = np.concatenate((rows, cols, diag, cross_diag))
if any([np.array_equal(lane, np.ones(3)) for lane in lanes]):
return 1
elif any([np.array_equal(lane, np.zeros(3)) for lane in lanes]):
return 0
</code></pre>
<p>So for example, if I execute</p>
<pre><code>board = Board()
board.grid = np.diag(np.ones(3))
print board.winner()
</code></pre>
<p>I get the result <code>1</code>. What bothers me slightly is the repetition of the <code>any</code> statements. I would think there would be a more concise, DRY way of coding this. (I was thinking of a switch/case as in MATLAB but this doesn't exist in Python). Any suggestions?</p>
| 2 | 2016-08-08T13:48:32Z | 38,832,650 | <p>This can be done in two lines, starting from the board (<code>grid</code>): simple sums along columns, rows and the two main diagonals gives you a value of 0 or 3 depending on who is winning (or some intermediate values only if nobody is winning). You can thus calculate something like:</p>
<pre><code># Score along each column, row and both main diagonals:
scores = (grid.sum(axis=0).tolist() + grid.sum(axis=1).tolist()
+[grid.trace(), np.flipud(grid).trace()])
# If there is no winner, None is declared the winner:
print "Winner:", 1 if 3 in scores else 0 if 0 in scores else None
</code></pre>
<p>where <code>flipud()</code> transforms the diagonal into the anti-diagonal (the diagonal at 90° from the main diagonal) by flipping the array horizontally, so that a simple <code>trace()</code> gives the total value along the anti-diagonal.</p>
| 0 | 2016-08-08T15:05:14Z | [
"python",
"numpy"
] |
tkinter populate treeview using threading pool | 38,830,958 | <p>I'm looking for "best" way to populate treeview using threads.
I have multiple mail account which I'm checking for new emails.</p>
<p>My plan is to use <code>Queue</code> to store accounts which will be checked
using <code>check_mail</code> method. This method will return a list of new
mails.</p>
<p>Can I use another <code>Queue</code> which I will populate with new mails and
somehow loop while threads are alive?</p>
<p>Is there any thread-safe, good pattern to solve this?</p>
| 0 | 2016-08-08T13:49:17Z | 38,832,489 | <p>Your question is very broad, so this answer will also be.</p>
<p>Generally speaking, <code>tkinter</code> doesn't play well with multi-threading. You can do it, but must make sure only the main thread interacts with the GUI. A common way to do this is to use the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow">universal widget method</a> <code>after()</code> to schedule handling of data going out to or being retrieved from background threads, typically via <code>Queue</code>s, at regular intervals.</p>
| 0 | 2016-08-08T14:58:12Z | [
"python",
"multithreading",
"design-patterns",
"tkinter"
] |
tkinter populate treeview using threading pool | 38,830,958 | <p>I'm looking for "best" way to populate treeview using threads.
I have multiple mail account which I'm checking for new emails.</p>
<p>My plan is to use <code>Queue</code> to store accounts which will be checked
using <code>check_mail</code> method. This method will return a list of new
mails.</p>
<p>Can I use another <code>Queue</code> which I will populate with new mails and
somehow loop while threads are alive?</p>
<p>Is there any thread-safe, good pattern to solve this?</p>
| 0 | 2016-08-08T13:49:17Z | 38,868,204 | <p>I'm not sure if this is the best idea but it works</p>
<pre><code>class Main(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.some_service = SomeService()
self.some_service.run()
self.init_gui()
self.after(60000, self.check_for_updates) # Use it to run service
self.after(2000, self.update_gui) # Update GUI every 2 seconds.
def check_for_updates(self):
data = ['a', 'b', 'c', 'd']
self.some_service.populate_job_queue(data)
self.after(60000, self.check_for_updates)
def update_gui(self):
if not self.some_service.update_queue.empty():
update = self.some_service.update_queue.get()
## Do something with update ##
self.text.insert(tk.END, update)
self.after(2000, self.update_gui)
class SomeService(object):
def __init__(self):
self.update_queue = Queue()
self.job_queue = Queue()
def populate_job_queue(self, jobs):
for job in jobs:
self.job_queue.put(job)
def run(self):
for x in range(8):
worker = Thread(target=self.do_something, daemon=True)
worker.start()
def do_something(self):
## Do something with data
while True:
if not self.job_queue.empty():
job = self.job_queue.get()
# Do something
self.update_queue.put(some_data)
</code></pre>
| 0 | 2016-08-10T08:37:24Z | [
"python",
"multithreading",
"design-patterns",
"tkinter"
] |
Extract subarray from collection of 2D coordinates? | 38,831,006 | <p>In Python, I have a large 2D array containing data, and another Mx2 2D array containing a collection of M 2D coordinates of interest, e.g.</p>
<pre><code>coords=[[150, 123], [151, 123], [152, 124], [153, 125]]
</code></pre>
<p>I would like to extract the Mx1 array containing the values of the data array at these coordinates (indices) locations. Obviously, <code>data[coords]</code> does not work.</p>
<p>I suspect there is an easy way to do that, but stackoverflow failed me up to now. Thanks in advance for your help.</p>
<p>EDIT: An example would be</p>
<pre><code>data=[[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 2, 1, 0, 0],
[0, 0, 0, 1, 23, 40, 0, 0],
[0, 0, 0, 1, 1, 2, 0, 0],
[0, 0, 3, 2, 0, 0, 0, 0],
[0, 0, 4, 5, 6, 2, 1, 0],
[0, 0, 0, 0, 1, 20, 0, 0],
[0, 0, 0, 3, 1, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]
coords=[[1,4],[2,4],[2,5],[5,3],[6,5]]
</code></pre>
<p>and the desired output would be</p>
<pre><code>out=[2,23,40,5,20]
</code></pre>
| 2 | 2016-08-08T13:51:19Z | 38,831,291 | <p>You could use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>In [73]: [data[i][j] for i,j in coords]
Out[73]: [2, 23, 40, 5, 20]
</code></pre>
<p>The result returned by the list comprehension is equivalent to</p>
<pre><code>result = []
for i,j in coords:
result.append(data[i][j])
</code></pre>
| 2 | 2016-08-08T14:02:59Z | [
"python",
"arrays"
] |
Twitter Streaming in Python: cp949 codec | 38,831,077 | <p>I am currently using tweepy to gather data using Streaming API.</p>
<p>Here is my code and I ran this on Acaconda command prompt. When streaming starts, it returns tweets and then after giving few tweets it gives the following error:</p>
<pre><code>Streaming Started ...
RT @ish10040: Crack Dealer Released Early From Prison By Obama Murders Woman And Her 2 Young Kids⦠Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Jae Hee\Anaconda2\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Users\Jae Hee\Anaconda2\lib\threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\Jae Hee\Anaconda2\lib\site-packages\tweepy\streaming.py", line 294, in _run
raise exception
UnicodeEncodeError: 'cp949' codec can't encode character u'\xab' in position 31: illegal multibyte sequence
</code></pre>
<p>I believe that it has to do with encoding so I used chcp 65001 to deal with this issue but it does not give the solution!</p>
<p>Here is the code</p>
<pre><code>auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text)
def on_error(self, status_code):
#returning False in on_data disconnects the stream
if status_code == 420:
return False
def main():
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener)
print "Streaming Started ..."
try:
myStream.filter(track=['Obama'], async = True)
except:
print "error!"
myStream.disconnect()
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-08-08T13:54:39Z | 38,831,233 | <p>All text produced and accepted through the twitter API should be encoded as UTF-8, so your code should be using that codec to decode what's coming back.</p>
<p>See here: <a href="https://dev.twitter.com/overview/api/counting-characters" rel="nofollow">https://dev.twitter.com/overview/api/counting-characters</a></p>
| 0 | 2016-08-08T14:00:48Z | [
"python",
"twitter",
"tweepy"
] |
Remove cancelling rows from Pandas Dataframe | 38,831,088 | <p>I have a list of invoices sent out to customers. However, sometimes a bad invoice is sent, which is later cancelled. My Pandas Dataframe looks something like this, except much larger (~3 million rows)</p>
<pre><code>index | customer | invoice_nr | amount | date
---------------------------------------------------
0 | 1 | 1 | 10 | 01-01-2016
1 | 1 | 1 | -10 | 01-01-2016
2 | 1 | 1 | 11 | 01-01-2016
3 | 1 | 2 | 10 | 02-01-2016
4 | 2 | 3 | 7 | 01-01-2016
5 | 2 | 4 | 12 | 02-01-2016
6 | 2 | 4 | 8 | 02-01-2016
7 | 2 | 4 | -12 | 02-01-2016
8 | 2 | 4 | 4 | 02-01-2016
... | ... | ... | ... | ...
... | ... | ... | ... | ...
</code></pre>
<p>Now, I want to drop all rows for which the <code>customer</code>, <code>invoice_nr</code> and <code>date</code> are identical, but the <code>amount</code> has opposite values.<br>
Corrections of invoices always take place on the same day with identical invoice number. The invoice number is uniquely bound to the customer and always corresponds to one transaction (which can consist of multiple components, for example for <code>customer = 2</code>, <code>invoice_nr = 4</code>). Corrections of invoices only occur either to change <code>amount</code> charged, or to split <code>amount</code> in smaller components. Hence, the cancelled value is not repeated on the same <code>invoice_nr</code>.</p>
<p>Any help how to program this would be much appreciated.</p>
| 4 | 2016-08-08T13:55:02Z | 38,832,006 | <p>What if you just do a groupby on all 3 fields? The resulting sums would net out any canceled invoices:</p>
<pre><code>df2 = df.groupby(['customer','invoice_nr','date']).sum()
</code></pre>
<p>results in</p>
<pre><code>customer invoice_nr date
1 1 2016/01/01 11
2 2016/02/01 10
2 3 2016/01/01 7
</code></pre>
| 0 | 2016-08-08T14:35:12Z | [
"python",
"pandas"
] |
Remove cancelling rows from Pandas Dataframe | 38,831,088 | <p>I have a list of invoices sent out to customers. However, sometimes a bad invoice is sent, which is later cancelled. My Pandas Dataframe looks something like this, except much larger (~3 million rows)</p>
<pre><code>index | customer | invoice_nr | amount | date
---------------------------------------------------
0 | 1 | 1 | 10 | 01-01-2016
1 | 1 | 1 | -10 | 01-01-2016
2 | 1 | 1 | 11 | 01-01-2016
3 | 1 | 2 | 10 | 02-01-2016
4 | 2 | 3 | 7 | 01-01-2016
5 | 2 | 4 | 12 | 02-01-2016
6 | 2 | 4 | 8 | 02-01-2016
7 | 2 | 4 | -12 | 02-01-2016
8 | 2 | 4 | 4 | 02-01-2016
... | ... | ... | ... | ...
... | ... | ... | ... | ...
</code></pre>
<p>Now, I want to drop all rows for which the <code>customer</code>, <code>invoice_nr</code> and <code>date</code> are identical, but the <code>amount</code> has opposite values.<br>
Corrections of invoices always take place on the same day with identical invoice number. The invoice number is uniquely bound to the customer and always corresponds to one transaction (which can consist of multiple components, for example for <code>customer = 2</code>, <code>invoice_nr = 4</code>). Corrections of invoices only occur either to change <code>amount</code> charged, or to split <code>amount</code> in smaller components. Hence, the cancelled value is not repeated on the same <code>invoice_nr</code>.</p>
<p>Any help how to program this would be much appreciated.</p>
| 4 | 2016-08-08T13:55:02Z | 38,832,078 | <pre><code>def remove_cancelled_transactions(df):
trans_neg = df.amount < 0
return df.loc[~(trans_neg | trans_neg.shift(-1))]
groups = [df.customer, df.invoice_nr, df.date, df.amount.abs()]
df.groupby(groups, as_index=False, group_keys=False) \
.apply(remove_cancelled_transactions)
</code></pre>
<p><a href="http://i.stack.imgur.com/dag21.png" rel="nofollow"><img src="http://i.stack.imgur.com/dag21.png" alt="enter image description here"></a></p>
| 3 | 2016-08-08T14:38:15Z | [
"python",
"pandas"
] |
Remove cancelling rows from Pandas Dataframe | 38,831,088 | <p>I have a list of invoices sent out to customers. However, sometimes a bad invoice is sent, which is later cancelled. My Pandas Dataframe looks something like this, except much larger (~3 million rows)</p>
<pre><code>index | customer | invoice_nr | amount | date
---------------------------------------------------
0 | 1 | 1 | 10 | 01-01-2016
1 | 1 | 1 | -10 | 01-01-2016
2 | 1 | 1 | 11 | 01-01-2016
3 | 1 | 2 | 10 | 02-01-2016
4 | 2 | 3 | 7 | 01-01-2016
5 | 2 | 4 | 12 | 02-01-2016
6 | 2 | 4 | 8 | 02-01-2016
7 | 2 | 4 | -12 | 02-01-2016
8 | 2 | 4 | 4 | 02-01-2016
... | ... | ... | ... | ...
... | ... | ... | ... | ...
</code></pre>
<p>Now, I want to drop all rows for which the <code>customer</code>, <code>invoice_nr</code> and <code>date</code> are identical, but the <code>amount</code> has opposite values.<br>
Corrections of invoices always take place on the same day with identical invoice number. The invoice number is uniquely bound to the customer and always corresponds to one transaction (which can consist of multiple components, for example for <code>customer = 2</code>, <code>invoice_nr = 4</code>). Corrections of invoices only occur either to change <code>amount</code> charged, or to split <code>amount</code> in smaller components. Hence, the cancelled value is not repeated on the same <code>invoice_nr</code>.</p>
<p>Any help how to program this would be much appreciated.</p>
| 4 | 2016-08-08T13:55:02Z | 38,832,926 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a> all values, where each group has values where sum is <code>0</code> and modulo by <code>2</code> is <code>0</code>:</p>
<pre><code>print (df.groupby([df.customer, df.invoice_nr, df.date, df.amount.abs()])
.filter(lambda x: (len(x.amount.abs()) % 2 == 0 ) and (x.amount.sum() == 0)))
customer invoice_nr amount date
index
0 1 1 10 01-01-2016
1 1 1 -10 01-01-2016
5 2 4 12 02-01-2016
6 2 4 -12 02-01-2016
idx = df.groupby([df.customer, df.invoice_nr, df.date, df.amount.abs()])
.filter(lambda x: (len(x.amount.abs()) % 2 == 0 ) and (x.amount.sum() == 0)).index
print (idx)
Int64Index([0, 1, 5, 6], dtype='int64', name='index')
print (df.drop(idx))
customer invoice_nr amount date
index
2 1 1 11 01-01-2016
3 1 2 10 02-01-2016
4 2 3 7 01-01-2016
7 2 4 8 02-01-2016
8 2 4 4 02-01-2016
</code></pre>
<p>EDIT by comment:</p>
<p>If in real data are not duplicates for one invoice and one customer and one date, so you can use this way:</p>
<pre><code> print (df)
index customer invoice_nr amount date
0 0 1 1 10 01-01-2016
1 1 1 1 -10 01-01-2016
2 2 1 1 11 01-01-2016
3 3 1 2 10 02-01-2016
4 4 2 3 7 01-01-2016
5 5 2 4 12 02-01-2016
6 6 2 4 -12 02-01-2016
7 7 2 4 8 02-01-2016
8 8 2 4 4 02-01-2016
df['amount_abs'] = df.amount.abs()
df.drop_duplicates(['customer','invoice_nr', 'date', 'amount_abs'], keep=False, inplace=True)
df.drop('amount_abs', axis=1, inplace=True)
print (df)
index customer invoice_nr amount date
2 2 1 1 11 01-01-2016
3 3 1 2 10 02-01-2016
4 4 2 3 7 01-01-2016
7 7 2 4 8 02-01-2016
8 8 2 4 4 02-01-2016
</code></pre>
| 2 | 2016-08-08T15:18:03Z | [
"python",
"pandas"
] |
Convert Python to Java 8 | 38,831,101 | <p>Iâm working in a project that use java 8, this project is about get some geographic information and work with this.
I already have done part of this work in python, and now Iâm translating this part did in Python to java 8, well in Python I use this lines bellow to convert coordinates in Google format to Postgis format:</p>
<pre><code>s1 = tuple(value.split(" "))
s2 = zip(s1[1::2], s1[::2])
</code></pre>
<p><strong>For example:</strong></p>
<p>I have a entrance like: value = "<strong>11.12345679</strong> <em>12.987655</em> <strong>11.3434454</strong> <em>12.1223323</em>" and so on
The Python code above changes de entrance to:
s2 = "<em>12.987655</em> <strong>11.12345679</strong> <em>12.1223323</em>" and so on.</p>
<p>Changing the position of each coordinate pair, each entrance have thousands of coordinates.
To get the same effect with java (before java 8):
Using my knowledge of java (acquired before the java 8) I will need do that:</p>
<pre><code>try {
String result = "", right = "", left = "";
String[] txt = str.split(" ");
for (int i = 0; i < txt.length; i += 2) {
right = txt[i];
left = txt[i + 1];
result += "," + left + " " + right;
}
return result.substring(1);
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
</code></pre>
<p>I will execute the java code above thousands of times, my question is: Java 8 has some new way to do this code above more like Python ?</p>
<p>My motivation to ask that question is because I came across with this news about Java 8:</p>
<pre><code>List<String> someList = new ArrayList<>();
// Add some elements
someList.add("Generic (1.5)");
someList.add("Functional (8)");
// Open a stream
someList.stream()
// Turn all texts in Upper Case
.map(String::toUpperCase)
// Loop all elemnst in Upper Case
.forEach(System.out::println);
</code></pre>
<p><strong>Updating:</strong></p>
<p>The solution of Jean-François Savard was perfect using Java 8 like I asked, thank you so much Jean-Francois Savard</p>
<pre><code>String str = "11.12345679 12.987655 11.3434454 12.1223323 11.12345679 12.987655 11.3434454 12.1223323";
String[] strs = str.split(" ");
str = IntStream.range(0, strs.length) .filter(i -> i % 2 == 0) .mapToObj(i -> strs[i + 1] + " " + strs[i]) .collect(Collectors.joining(","));
System.out.println(str);
>> 12.987655 11.12345679,12.1223323 11.3434454,12.987655 11.12345679,12.1223323 11.3434454
</code></pre>
<p>The solution shown by Vampire and Tukayi fit perfectly in my problem, thanks a lot guys</p>
<pre><code>String str = "11.12345679 12.987655 11.3434454 12.1223323 11.12345679
12.987655 11.3434454 12.1223323";
str = str.replaceAll("([^\\s]+) ([^\\s]+)(?: |$)", ",$2 $1").substring(1);
System.out.println(str);
</code></pre>
| -4 | 2016-08-08T13:55:33Z | 38,831,186 | <p>Java 8 added (among other things) Lambdas, Streams and Functional interfaces.</p>
<p>You can use streams to simplify looping over objects. But the syntax like you see in Python isn't the same as in java like that.</p>
| -5 | 2016-08-08T13:58:53Z | [
"java",
"python",
"postgis"
] |
Convert Python to Java 8 | 38,831,101 | <p>Iâm working in a project that use java 8, this project is about get some geographic information and work with this.
I already have done part of this work in python, and now Iâm translating this part did in Python to java 8, well in Python I use this lines bellow to convert coordinates in Google format to Postgis format:</p>
<pre><code>s1 = tuple(value.split(" "))
s2 = zip(s1[1::2], s1[::2])
</code></pre>
<p><strong>For example:</strong></p>
<p>I have a entrance like: value = "<strong>11.12345679</strong> <em>12.987655</em> <strong>11.3434454</strong> <em>12.1223323</em>" and so on
The Python code above changes de entrance to:
s2 = "<em>12.987655</em> <strong>11.12345679</strong> <em>12.1223323</em>" and so on.</p>
<p>Changing the position of each coordinate pair, each entrance have thousands of coordinates.
To get the same effect with java (before java 8):
Using my knowledge of java (acquired before the java 8) I will need do that:</p>
<pre><code>try {
String result = "", right = "", left = "";
String[] txt = str.split(" ");
for (int i = 0; i < txt.length; i += 2) {
right = txt[i];
left = txt[i + 1];
result += "," + left + " " + right;
}
return result.substring(1);
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
</code></pre>
<p>I will execute the java code above thousands of times, my question is: Java 8 has some new way to do this code above more like Python ?</p>
<p>My motivation to ask that question is because I came across with this news about Java 8:</p>
<pre><code>List<String> someList = new ArrayList<>();
// Add some elements
someList.add("Generic (1.5)");
someList.add("Functional (8)");
// Open a stream
someList.stream()
// Turn all texts in Upper Case
.map(String::toUpperCase)
// Loop all elemnst in Upper Case
.forEach(System.out::println);
</code></pre>
<p><strong>Updating:</strong></p>
<p>The solution of Jean-François Savard was perfect using Java 8 like I asked, thank you so much Jean-Francois Savard</p>
<pre><code>String str = "11.12345679 12.987655 11.3434454 12.1223323 11.12345679 12.987655 11.3434454 12.1223323";
String[] strs = str.split(" ");
str = IntStream.range(0, strs.length) .filter(i -> i % 2 == 0) .mapToObj(i -> strs[i + 1] + " " + strs[i]) .collect(Collectors.joining(","));
System.out.println(str);
>> 12.987655 11.12345679,12.1223323 11.3434454,12.987655 11.12345679,12.1223323 11.3434454
</code></pre>
<p>The solution shown by Vampire and Tukayi fit perfectly in my problem, thanks a lot guys</p>
<pre><code>String str = "11.12345679 12.987655 11.3434454 12.1223323 11.12345679
12.987655 11.3434454 12.1223323";
str = str.replaceAll("([^\\s]+) ([^\\s]+)(?: |$)", ",$2 $1").substring(1);
System.out.println(str);
</code></pre>
| -4 | 2016-08-08T13:55:33Z | 38,844,665 | <p>Define the following in your class to precompile a Regex pattern</p>
<pre><code>private static final Pattern pattern = Pattern.compile("([^ ]++) ([^ ]++)(?: |$)");
</code></pre>
<p>Then in your method use</p>
<pre><code>if ((new StringTokenizer(str, " ").countTokens() % 2) == 1) {
return null;
}
return pattern.matcher(str).replaceAll(",$2 $1").substring(1);
</code></pre>
<p>to get the same result as in your original code.</p>
<hr>
<p>If you depend on using Streams why-o-ever, here a Streams solution</p>
<pre><code>String[] strs = str.split(" ");
return IntStream.range(0, strs.length)
.filter(i -> i % 2 == 0)
.mapToObj(i -> strs[i + 1] + " " + strs[i])
.collect(Collectors.joining(","));
</code></pre>
| 0 | 2016-08-09T07:31:57Z | [
"java",
"python",
"postgis"
] |
Annotation DB has no 'select' method in rpy2 | 38,831,169 | <p>I have the following code in R:</p>
<pre><code>require(hgu133a.db)
entrezIDs <- select(hgu133a.db, probeNames, "ENTREZID")
</code></pre>
<p>where <code>probeNames</code> is a list of strings corresponding to probes found in this database.</p>
<p>I am attempting to translate it to Python using rpy2:</p>
<pre><code>from rpy2.robjects.packages import importr
hgu133a_db = importr('hgu133a.db')
entrez_ids = hgu133a_db.select(hgu133a_db, probe_names, 'ENTREZID')
</code></pre>
<p>But receive the error:</p>
<blockquote>
<p>AttributeError: module 'hgu133a.db' has no attribute 'select'</p>
</blockquote>
<p>I've searched the documentation (<code>?select</code>) and as far as I can tell the database <strong>hgu133a.db</strong> inherits a <code>select</code> method from the <strong>AnnotationDbi</strong> class.</p>
<p>How do I properly resolve the library where <code>select()</code> is coming from, so I can use it in Python?</p>
| 0 | 2016-08-08T13:58:20Z | 38,832,083 | <p>Apparently there are two issues with the above. First, <strong>AnnotationDbi</strong> should be used to resolve the <code>select()</code> method. Second, <code>hgu133a_db</code> is an <strong>InstallSTPackage</strong> object - instead one must use <code>hgu133a_db.hgu133a_db</code>. Putting it together, the translation from R to Python is:</p>
<pre><code>from rpy2.robjects.packages import importr
annotation_dbi = importr('AnnotationDbi')
hgu133a_db = importr('hgu133a.db')
entrez_ids = annotation_dbi.select(hgu133a_db.hgu133a_db, probe_names, 'ENTREZID')
</code></pre>
| 0 | 2016-08-08T14:38:28Z | [
"python",
"rpy2",
"bioconductor"
] |
Annotation DB has no 'select' method in rpy2 | 38,831,169 | <p>I have the following code in R:</p>
<pre><code>require(hgu133a.db)
entrezIDs <- select(hgu133a.db, probeNames, "ENTREZID")
</code></pre>
<p>where <code>probeNames</code> is a list of strings corresponding to probes found in this database.</p>
<p>I am attempting to translate it to Python using rpy2:</p>
<pre><code>from rpy2.robjects.packages import importr
hgu133a_db = importr('hgu133a.db')
entrez_ids = hgu133a_db.select(hgu133a_db, probe_names, 'ENTREZID')
</code></pre>
<p>But receive the error:</p>
<blockquote>
<p>AttributeError: module 'hgu133a.db' has no attribute 'select'</p>
</blockquote>
<p>I've searched the documentation (<code>?select</code>) and as far as I can tell the database <strong>hgu133a.db</strong> inherits a <code>select</code> method from the <strong>AnnotationDbi</strong> class.</p>
<p>How do I properly resolve the library where <code>select()</code> is coming from, so I can use it in Python?</p>
| 0 | 2016-08-08T13:58:20Z | 38,884,147 | <p>[should have been a comment to @merv 's answer, but exceeded the number characters]</p>
<p><code>rpy2</code>'s <code>importr()</code> is trying to help a being specific about which package namespace an R object is coming from, while R's common usage is much less so (and can lead to annoyances such as the loading order of R packages having an influence on which one of the functions with the same name is executed).</p>
<p>The tradeoff with <code>importr</code> is that one has to know where an R symbol is coming from. There is a less-known function in <code>rpy2</code> that can help finding where a given R symbol is defined(*): <a href="https://rpy2.readthedocs.io/en/version_2.8.x/robjects_rpackages.html#finding-where-an-r-symbol-is-coming-from" rel="nofollow">https://rpy2.readthedocs.io/en/version_2.8.x/robjects_rpackages.html#finding-where-an-r-symbol-is-coming-from</a> .</p>
<p>Otherwise, one can also use <code>r()</code> to retrieve the object that would be picked(*) in an R session.</p>
<pre><code>from rpy2.robjects import r
r('select')
</code></pre>
<p>(*: as mentioned earlier, the order in which R packages were loaded earlier in the session can have an influence on which R object is picked).</p>
| 1 | 2016-08-10T21:50:40Z | [
"python",
"rpy2",
"bioconductor"
] |
Qt/Spyder scaling with 4K display | 38,831,239 | <p>I've recently made the switch from an old macbook pro to a razer blade stealth laptop. I have many programs that I've written that have pyqt4 GUIs, and I usually do most of my coding in spyder. Upon switching to a computer with a 4K screen spyder has become unusable as it does not scale properly, in addition all the GUIs that I have written don't scale correctly and are thus unusable.</p>
<p>Does anyone have any experience with this problem and/or have any tips on how to get these things to scale correctly on high DPI screens?</p>
| 0 | 2016-08-08T14:01:00Z | 38,832,329 | <p>The next version of Spyder (3.0.0) will natively support high dpi screen and makes use for vector icons.</p>
<p>You can try the latest beta (Spyder 3.0.0 beta4) if you want to be an early adopter.</p>
<p>Check out the talk on "what's new in Spyder 3.0" at the last Scipy conference:
<a href="https://www.youtube.com/watch?v=5boKDo1C144" rel="nofollow">https://www.youtube.com/watch?v=5boKDo1C144</a></p>
| 0 | 2016-08-08T14:50:21Z | [
"python",
"qt",
"pyqt",
"spyder",
"pyqtgraph"
] |
JWT integration with django | 38,831,298 | <p>I am new to Django (not DRF) and I have a hard time configuring my authentication requirements. I have an external authentication service that gets a username and password and returns a JWT. After I have the JWT how should I save the token and provide it with every request from the browser. And after that where can I validate it?</p>
<p>Thanks!</p>
| 0 | 2016-08-08T14:03:10Z | 38,831,519 | <p>For every call that your service get there should be header to that call</p>
<pre><code>{'Authorization':'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'}
</code></pre>
<p>And you can use that in views.py as :</p>
<pre><code> if request.user.is_authenticated():
</code></pre>
<p>It has to be included in the settings file of that django project.</p>
<pre><code>JWT_AUTH = {
# 'JWT_ENCODE_HANDLER':
# 'rest_framework_jwt.utils.jwt_encode_handler',
# 'JWT_DECODE_HANDLER':
# 'rest_framework_jwt.utils.jwt_decode_handler',
# 'JWT_PAYLOAD_HANDLER':
# 'rest_framework_jwt.utils.jwt_payload_handler',
# 'JWT_PAYLOAD_GET_USER_ID_HANDLER':
# 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
# 'JWT_RESPONSE_PAYLOAD_HANDLER':
# 'rest_framework_jwt.utils.jwt_response_payload_handler',
# 'JWT_SECRET_KEY': settings.SECRET_KEY,
# 'JWT_ALGORITHM': 'HS256',
# 'JWT_VERIFY': True,
# 'JWT_VERIFY_EXPIRATION': False,
# 'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
# 'JWT_AUDIENCE': None,
# 'JWT_ISSUER': None,
# 'JWT_ALLOW_REFRESH': False,
# 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
# 'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
</code></pre>
<p>Read more about it <a href="http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow">here</a>.</p>
| 0 | 2016-08-08T14:12:00Z | [
"python",
"django",
"jwt",
"json-web-token"
] |
Not getting an output when I call __str__ on a class instance? | 38,831,442 | <p>I am just a beginner so be easy on me. i was just playing with the <code>__str__</code> method and found that when I try to print the instance it just doesn't work</p>
<pre><code>import random
brand = ("Samsung","Nokia","Sony","ATAT","Reliance")
no_of_sim = ("Dual-sim","Single-sim")
color = ("Blue","Violet","Orange","Green")
no_of_camera =("Front","Front-Back","Back")
no_of_cores = ("Dual Core","Quad Core","Octa Core")
additional = ("Bluetooth","NFS","Gps")
class mobile:
def __init__(self,**kwargs):
name = self
self.brand = random.choice(brand)
self.sim = random.choice(no_of_sim)
self.color = random.choice(color)
self.camera = random.choice(no_of_camera)
self.cores = random.choice(no_of_cores)
self.additional = random.choice(additional)
for key,value in kwargs.items():
setattr(self,key,value)
def __str__(self):
return "{} Is a {} color {} phone with {} facing cameras and it a {} with {}".format(self.__class__.__name__,self.color,self.brand,self.camera,self.cores,self,additional)
</code></pre>
<pre><code>from mobile_phone import mobile
swiss = mobile()
print(swiss)
# It doesnt show up
</code></pre>
| 0 | 2016-08-08T14:08:46Z | 38,831,942 | <p>There is a typo in the end of <strong>str</strong> method:</p>
<pre><code>self,additional
</code></pre>
<p>It makes <strong>str</strong> method recursive. Changing "," to "." removes the problem.</p>
| 1 | 2016-08-08T14:32:32Z | [
"python"
] |
Not getting an output when I call __str__ on a class instance? | 38,831,442 | <p>I am just a beginner so be easy on me. i was just playing with the <code>__str__</code> method and found that when I try to print the instance it just doesn't work</p>
<pre><code>import random
brand = ("Samsung","Nokia","Sony","ATAT","Reliance")
no_of_sim = ("Dual-sim","Single-sim")
color = ("Blue","Violet","Orange","Green")
no_of_camera =("Front","Front-Back","Back")
no_of_cores = ("Dual Core","Quad Core","Octa Core")
additional = ("Bluetooth","NFS","Gps")
class mobile:
def __init__(self,**kwargs):
name = self
self.brand = random.choice(brand)
self.sim = random.choice(no_of_sim)
self.color = random.choice(color)
self.camera = random.choice(no_of_camera)
self.cores = random.choice(no_of_cores)
self.additional = random.choice(additional)
for key,value in kwargs.items():
setattr(self,key,value)
def __str__(self):
return "{} Is a {} color {} phone with {} facing cameras and it a {} with {}".format(self.__class__.__name__,self.color,self.brand,self.camera,self.cores,self,additional)
</code></pre>
<pre><code>from mobile_phone import mobile
swiss = mobile()
print(swiss)
# It doesnt show up
</code></pre>
| 0 | 2016-08-08T14:08:46Z | 38,832,011 | <p>You have a comma where you need a dot:</p>
<pre><code>import random
brand = ("Samsung","Nokia","Sony","ATAT","Reliance")
no_of_sim = ("Dual-sim","Single-sim")
color = ("Blue","Violet","Orange","Green")
no_of_camera =("Front","Front-Back","Back")
no_of_cores = ("Dual Core","Quad Core","Octa Core")
additional = ("Bluetooth","NFS","Gps")
class mobile:
def __init__(self,**kwargs):
name = self
self.brand = random.choice(brand)
self.sim = random.choice(no_of_sim)
self.color = random.choice(color)
self.camera = random.choice(no_of_camera)
self.cores = random.choice(no_of_cores)
self.additional = random.choice(additional)
for key,value in kwargs.items():
setattr(self,key,value)
def __str__(self):
return("{} Is a {} color {} phone with "
"{} facing cameras and it a {} with {}".format(
self.__class__.__name__,
self.color,
self.brand,
self.camera,
self.cores,
self.additional)) # changed from self,additional
#from mobile_phone import mobile
swiss = mobile()
print(swiss)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>mobile Is a Green color Reliance phone with Front-Back facing cameras and it a Dual Core with Bluetooth
</code></pre>
| 0 | 2016-08-08T14:35:23Z | [
"python"
] |
Am I using virtualenv wrong or is this a limitation of it? | 38,831,613 | <p>So I used <code>virtualenv</code> to define environments for a number of projects I am working on. I defined the <code>virtualenv</code> python as being version 3.4. Eventually, my global python was upgraded from 3.4.0 to 3.4.3. This proved to be a problem because the <code>virtualenv</code> was dependent on the global binaries (the contents of <code>/lib/python3.4</code> in my <code>virtualenv</code> is actually just links to the global binaries), and these aren't defined up to their minor versions. In other words, when the upgrade was done, the contents of the binary folder <code>/usr/lib/python3.4</code> was replaced. This is because python doesn't install things separately in 3.4.0 and 3.4.3 but only into a single folder named <code>/usr/lib/python3.4</code>. Since the python executable in my <code>virtualenv</code> was 3.4.0, there were obviously compatibility issues with the 3.4.3 binaries (it would fail to load <code>ctypes</code> which prevented just about anything python dependent to run). The only fix to this I've found is to downgrade my global python installation, but this feels "dirty". What if I had one project running 3.4.0 and another running 3.4.3 ? Is there no way to make them work in parallel on the same machine given that only one binary folder can exist for any 3.4.x installation ?</p>
<p>I'm trying to understand if I'm missing something obvious here or if this is a common problem with <code>virtualenv</code>, given that I've heard quite a few people complain about issues with binares when using <code>virtualenv</code>.</p>
<p>In the future, is there anyway of telling <code>virtualenvwrapper</code> to copy the binaries rather than link to them ?</p>
| 1 | 2016-08-08T14:16:14Z | 38,833,295 | <p>Virtualenvs were not desiged to be portable, both across machines or across Python versions.</p>
<p>This means upgrading Python versions sometimes breaks virtualenvs. You need to recreate them and reinstall everything inside of it (run this in your virtualenv root):</p>
<pre><code># Save a list of what you had installed
pip freeze > freeze.txt
# Trash the entire virtualenv
deactivate
rm -rf lib/ bin/ share/ man/ include/ .Python pip-selfcheck.json
# Create it anew
virtualenv .
# Install all libraries you had before
pip install -r freeze.txt
</code></pre>
| 2 | 2016-08-08T15:35:27Z | [
"python",
"virtualenv"
] |
How does asyncio's event loop know when an awaitable resource is ready? | 38,831,687 | <p>I'm learning Python asyncio for asynchronous programing. I know that the event loop watch over Future objects until they are ready and then resumes the appropriate coroutines to continue the execution in the point where the await keyword occurred. </p>
<p>This is very understandable when you use something like <code>asyncio.sleep</code> because the sleeping function knows how many time it will take and so will know the event loop but <strong>what happens with something that relies on networking ( for example) where the waiting time is unknown?</strong>. </p>
<p>How does the event loop know when a resource is ready or how many time will take to gather data from some source? </p>
| 0 | 2016-08-08T14:19:52Z | 38,838,700 | <blockquote>
<p>How does the event loop know when a resource is ready or how many time will take to gather data from some source?</p>
</blockquote>
<p>The default event loop (based on <a href="https://docs.python.org/3.4/library/asyncio-eventloops.html#asyncio.SelectorEventLoop" rel="nofollow">SelectorEventLoop</a>) uses the <a href="https://docs.python.org/3.4/library/selectors.html#module-selectors" rel="nofollow">selector</a> module to keep track of all the resources to monitor and get notified when new data is ready. <a href="https://docs.python.org/3.4/library/selectors.html#selectors.BaseSelector.select" rel="nofollow">BaseSelector.select</a> is <a href="https://github.com/python/asyncio/blob/c288d5b771a4381655894e78afc97b4557c4d7f4/asyncio/base_events.py#L1276" rel="nofollow">where the magic happens</a>.</p>
| 2 | 2016-08-08T21:20:26Z | [
"python",
"asynchronous",
"python-asyncio"
] |
Is it possible to overload operators for native datatypes? | 38,831,695 | <p>For example, if I try to do:</p>
<pre><code>a_string + an_int
</code></pre>
<p>... where a_string is type 'str' and an_int is type 'int', or:</p>
<pre><code>an_int + a_string
</code></pre>
<p>There would be a <code>TypeError</code> because there is no implicit conversion of the types. I understand that if I were using my own subclasses of int and string, I would be able to overload the <code>__add__()</code> method in my classes to achieve this. </p>
<p>However, out of curiosity, I would like to know: would it be possible to overload the + operator in the class definitions of <code>int</code> and <code>str</code>, so that <code>__add__(int,str)</code> and <code>__add__(str,int)</code> automatically concatenate them as strings? </p>
<p>If not, what are the reasons why a programmer should not overload the operators for a native datatype? </p>
| 3 | 2016-08-08T14:20:15Z | 38,832,002 | <p>In general, without reverting to the C-level API, you cannot modify attributes of builtin types (see <a href="http://stackoverflow.com/questions/2444680/how-do-i-add-my-own-custom-attributes-to-existing-built-in-python-types-like-a">here</a>). You can, however, subclass builtin types and do what you want on the new types. For the question you specifically asked (making the addition string based), you'd modify <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow"><code>__add__</code> and <code>__radd__</code></a>:</p>
<pre><code>class Int(int):
def __add__(self, other):
return Int(int(str(self) + str(other)))
def __radd__(self, other):
return Int(str(other) + str(self))
>>> Int(5) + 3
53
>>> 3 + Int(5) + 87
3587
</code></pre>
| 2 | 2016-08-08T14:35:04Z | [
"python",
"operator-overloading",
"overloading"
] |
Is it possible to overload operators for native datatypes? | 38,831,695 | <p>For example, if I try to do:</p>
<pre><code>a_string + an_int
</code></pre>
<p>... where a_string is type 'str' and an_int is type 'int', or:</p>
<pre><code>an_int + a_string
</code></pre>
<p>There would be a <code>TypeError</code> because there is no implicit conversion of the types. I understand that if I were using my own subclasses of int and string, I would be able to overload the <code>__add__()</code> method in my classes to achieve this. </p>
<p>However, out of curiosity, I would like to know: would it be possible to overload the + operator in the class definitions of <code>int</code> and <code>str</code>, so that <code>__add__(int,str)</code> and <code>__add__(str,int)</code> automatically concatenate them as strings? </p>
<p>If not, what are the reasons why a programmer should not overload the operators for a native datatype? </p>
| 3 | 2016-08-08T14:20:15Z | 38,832,741 | <p>As pointed out above, you can't (unless you are up to building your own Python implementation). That is, you cannot change the way <code>'1'+1</code> is handled if encountered in code. But you can mess with builtin <em>functions</em> however you please:</p>
<pre><code>>>> int = str
>>> type(1)
<class 'int'>
>>> type('1')
<class 'str'>
>>> int(1)
'1'
>>> type(int(1))
<class 'str'>
</code></pre>
<p>It's little more than an enlightening example of first-class functions' awesomeness, thoug. Any changes you make stay in a namespace you are making them in. Consider this:</p>
<pre><code>>>> str=int
>>> str('1')
1
>>> str('asd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'asd'
>>> input()
2
'2'
>>>
</code></pre>
<p>You are using whatever you put in <code>str</code>, in this case <code>int</code>. But <code>input()</code> knows better and falls back to the builtins. There may be some weird trick with closures that'll make it refer to your implementation, but I can't find it. By the way, original <code>str</code> is in <code>__builtins__.str</code>, should you need it back.</p>
<p>Pulling the same trick on builtin's methods doesn't work:</p>
<pre><code>>>> int.__add__ = str.__add__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'
</code></pre>
| 2 | 2016-08-08T15:09:25Z | [
"python",
"operator-overloading",
"overloading"
] |
How to read a line from python currently in console? | 38,831,703 | <p>I want to use a line of code that can read what I was typing in console, for use with <code>asyncio</code> module in python. My code prints data when it receives it from the server, and after it does that, I want it to read what I was typing and save it to a variable. I am fine with having to use a non-standard module.</p>
<p>Information about program:</p>
<ul>
<li>Currently reads stdin non-blocking using asyncio loop.run_in_executor</li>
<li>Program runs using loop.create_connection, then uses loop.run_forever with the stdin reader added as a task.</li>
</ul>
<p>Code:</p>
<pre><code>#!python3.5
#chatroom client
import socket, sys, os, traceback, asyncio
from threading import Lock
DBG = False #More Error printing using full_error function
#async stuf
loop = asyncio.get_event_loop()
lock = Lock()
prev_stdin = ""
#Server Location
target = 'localhost'
port = 17532
buffer_size = 1024
server = None
transports = [] #an array of async.iotransport`s
#Functions for Error handling
full_error = lambda: traceback.print_exception(*sys.exc_info())
pause = lambda: None #make it global for below
#Pause system compatability
if os.name[0:5]=='posix':
def pause():
os.system('read -n1 -r -p "Press any key to continue . . ." key')
elif os.name[0:2]=='nt':
def pause():
os.system("pause")
else:
def pause():
input("Press enter to continue . . .")
def empty_stdin():
output = ""
while True:
temp = sys.stdin.buffer.read(1)
if temp == "":
break
else:
output += temp
return output
if DBG:
loop.set_debug(DBG)
async def write():
loop = asyncio.get_event_loop()
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
line = prev_stdin + line
prev_stdin = ""
for i in transports:
loop.call_soon(i.write,line.encode('utf-8'))
class Server(asyncio.Protocol):
def connection_made(self,transport):
self.transport = transport
transport.write(b"Connected")
def data_received(self, data):
print("\n%s"%data.decode('utf-8'))
prev_stdin = empty_stdin()
print(prev_stdin,)
try:
coro = loop.create_connection(Server, host=target, port=port)
task = loop.create_task(coro)
print("hi")
print(transports)
server, serverp = loop.run_until_complete(task)
transports += [server]
user_input = loop.create_task(write())
#loop.add_reader(sys.stdin, write)
loop.run_forever()
print('end')
except Exception as e:
if DBG:
full_error()
else:
print(type(e))
print(e)
pause()
sys.exit()
</code></pre>
| -4 | 2016-08-08T14:20:53Z | 38,926,940 | <p>I solved the problem (Windows only) by using <code>msvcrt</code> to catch a single character and some code changes.</p>
<p>New Functions/Changes</p>
<ol>
<li><p>draw_screen:</p>
<ul>
<li>clear screen using <code>os.system("cls")</code></li>
<li><strong>print lines that I save when I print info (Could get laggy)</strong></li>
<li>print a cursor with what I am currently typing (">> Hello")</li>
</ul></li>
<li><p>write:</p>
<ul>
<li><strong>replaced sys.stdin.readline with msvcrt.getch</strong></li>
<li>A lot more changes</li>
</ul></li>
<li><p>everywhere:</p>
<ul>
<li><strong>Whenever I would print, instead add it to <code>screen</code> variable which is an array that holds everything. Then it calls draw_screen()</strong></li>
<li>removed prev_stdin stuff</li>
<li>removed some other print statements</li>
</ul></li>
</ol>
<p>Final Code (For now):</p>
<pre><code>#!python3.5
#chatroom client
import sys, os, traceback, asyncio, msvcrt
from threading import Lock
DBG = False #More Error printing using full_error function
screen = [] #holds lines of text that are printed to the screen
line = ""
#async stuf
loop = asyncio.get_event_loop()
lock = Lock()
#Server Location
target = 'localhost'
port = 17532
buffer_size = 1024
server = None
transports = [] #an array of async.iotransport`s
#Functions for Error handling
full_error = lambda: traceback.print_exception(*sys.exc_info())
#system compatable functions
if os.name[0:5]=='posix':
def pause():
os.system('read -n1 -r -p "Press any key to continue . . ." key')
def cls():
os.system("clear")
elif os.name[0:2]=='nt':
def pause():
os.system("pause")
def cls():
os.system("cls")
else:
def pause():
input("Press enter to continue . . .")
def cls():
os.system("clear")
def draw_screen():
cls()
for i in screen:
print(i)
print("> ", line, end="\r") #Draws current line of text being typed
if DBG:
loop.set_debug(DBG)
async def write():
global line
while True:
temp = await loop.run_in_executor(None, msvcrt.getch)
temp = temp.decode('utf-8')
if temp == "\b":
line = line[0:len(line)-1]
elif not (temp == "\r" or temp == "\n"):
line += temp
else:
for i in transports:
loop.call_soon(i.write,line.encode('utf-8'))
line = ""
draw_screen()
class Server(asyncio.Protocol):
def connection_made(self,transport):
self.transport = transport
transport.write(b"Connected")
def data_received(self, data):
global screen
screen += ["%s"%data.decode('utf-8')]
draw_screen()
try:
coro = loop.create_connection(Server, host=target, port=port)
task = loop.create_task(coro)
server, serverp = loop.run_until_complete(task)
transports += [server]
user_input = loop.create_task(write())
loop.run_forever()
print('end')
except Exception as e:
if DBG:
full_error()
else:
print(type(e))
print(e)
pause()
sys.exit()
</code></pre>
| 0 | 2016-08-12T21:50:34Z | [
"python",
"console",
"python-asyncio"
] |
Reading hex to double-precision float python | 38,831,808 | <p>I am trying to <code>unpack</code> a hex string to a double in Python. </p>
<p>When I try to unpack the following: </p>
<pre><code>unpack('d', "4081637ef7d0424a");
</code></pre>
<p>I get the following error: </p>
<pre><code>struct.error: unpack requires a string argument of length 8
</code></pre>
<p>This doesn't make very much sense to me because a double is 8 bytes long, and</p>
<p>2 character <strong>=</strong> 1 hex value <strong>=</strong> 1 byte </p>
<p>So in essence, a double of 8 bytes long would be a 16 character hex string.</p>
<p>Any pointers of unpacking this hex to a double would be super appreciated. </p>
| 4 | 2016-08-08T14:25:41Z | 38,831,901 | <p>Try this:</p>
<pre><code>a = "\x40\x81\x63\x7e\xf7\xd0\x42\x4a"
unpack('d', a);
</code></pre>
| 0 | 2016-08-08T14:30:59Z | [
"python",
"hex"
] |
Reading hex to double-precision float python | 38,831,808 | <p>I am trying to <code>unpack</code> a hex string to a double in Python. </p>
<p>When I try to unpack the following: </p>
<pre><code>unpack('d', "4081637ef7d0424a");
</code></pre>
<p>I get the following error: </p>
<pre><code>struct.error: unpack requires a string argument of length 8
</code></pre>
<p>This doesn't make very much sense to me because a double is 8 bytes long, and</p>
<p>2 character <strong>=</strong> 1 hex value <strong>=</strong> 1 byte </p>
<p>So in essence, a double of 8 bytes long would be a 16 character hex string.</p>
<p>Any pointers of unpacking this hex to a double would be super appreciated. </p>
| 4 | 2016-08-08T14:25:41Z | 38,831,910 | <p>You need to convert the hex digits to a binary string first:</p>
<pre><code>struct.unpack('d', "4081637ef7d0424a".decode("hex"))
</code></pre>
<p>or</p>
<pre><code>struct.unpack('d', binascii.unhexlify("4081637ef7d0424a"))
</code></pre>
<p>The latter version works in both Python 2 and 3, the former only in Python 2</p>
| 4 | 2016-08-08T14:31:14Z | [
"python",
"hex"
] |
Video Chat feature for Django and possibly Ionic | 38,831,929 | <p>I developed a website with Django (Python). This website allows users to make 1-to-1 video chat with each others.
For the video chat feature I'm currently using WebRTC with quite good results.</p>
<p>Now I'm planning to: </p>
<ul>
<li>upgrade to a paid service for video chat (to improve preformances and fix browser incompatibilities)</li>
<li>ideally using the same paid service for a Ionic app (both Android and iOS) - so that service should provide Android/iOS SDKs</li>
</ul>
<p>I'm thinking about CometChat. Do you have any experience with it or other services? Any suggestion will be really appreciated.</p>
| -2 | 2016-08-08T14:31:58Z | 38,889,100 | <p>You will have to create an API for charging your users and provide us the same according to the below-mentioned steps: </p>
<ol>
<li>Create a feature on your site which allows users to purchase credits (by making payment)</li>
<li>Create a simple API to deduct credits and check number of credits </li>
</ol>
<p>Once you provide us the API, we will then modify CometChat so that when a user sends a message we can check the number of credits and deduct them using your API.</p>
<p>Please let know if you need any further assistance about the same.</p>
<p>Regards</p>
| 0 | 2016-08-11T06:45:16Z | [
"android",
"python",
"django",
"video",
"ionic-framework"
] |
What is the "Python" way to parse through mroutes | 38,831,931 | <p>I am a network engineer who is trying to script out a specific "mroute" (multicast route) from some exported data. I am trying to figure out the most "pythonic" path to do this. </p>
<p>The data looks something like this (nothing specific to my network, just lab exports):</p>
<pre>
(*,224.0.0.0/4) RPF nbr: 96.34.35.36 Flags: C RPF P
Up: 1w5d
(*,224.0.0.0/24) Flags: D P
Up: 1w5d
(*,224.0.1.39) Flags: S P
Up: 1w5d
(96.34.246.55,224.0.1.39) RPF nbr: 96.34.35.36 Flags: RPF
Up: 1w4d
Incoming Interface List
Bundle-Ether434 Flags: F A, Up: 1w4d
Outgoing Interface List
BVI100 Flags: F, Up: 1w4d
TenGigE0/0/0/3 Flags: F, Up: 1w4d
TenGigE0/0/1/1 Flags: F, Up: 1w4d
TenGigE0/0/1/2 Flags: F, Up: 1w4d
TenGigE0/0/1/3 Flags: F, Up: 1w4d
TenGigE0/1/1/1 Flags: F, Up: 1w4d
TenGigE0/1/1/2 Flags: F, Up: 1w4d
TenGigE0/2/1/0 Flags: F, Up: 1w4d
TenGigE0/2/1/1 Flags: F, Up: 1w4d
TenGigE0/2/1/2 Flags: F, Up: 1w4d
Bundle-Ether234 (0/3/CPU0) Flags: F, Up: 2d17h
Bundle-Ether434 Flags: F A, Up: 1w4d
(*,224.0.1.40) Flags: S P
Up: 1w5d
Outgoing Interface List
TenGigE0/2/1/0 Flags: II, Up: 1w5d
</pre>
<p>I have tried to replicate C style for loops to move the index incrementer up when I regex certain lines. </p>
<p>The end result is I only want to show a multicast group if it has specific output in the "Outgoing" section.</p>
<p>A horrible example of what I have tried so far (not complete, the data is handed off in a list):</p>
<pre><code>myarray = []
myarray = output.split("\n")
max_count = len(myarray)
i= 0
while (i < max_count):
if (re.match(r"(^\()", myarray[i])):
group = myarray[i]
print group
i+=1
while (re.match(r'(?!^\()', myarray[i])):
if (re.match(r" Outgoing Interface List", myarray[i])):
outgoing = myarray[i]
print outgoing
i+=1
while (re.match(r'(?!^\()', myarray[i])):
print myarray[i]
i+=1
else:
i+=1
else:
i+=1
</code></pre>
<p>Thanks for any advice.</p>
| 1 | 2016-08-08T14:32:03Z | 38,833,799 | <p>Using a for loop eliminates having to use a variable counter, since it already returns the sequence number while looping.</p>
<p>There's probably a simpler or better way still available to do it also, but here's just one way i thought of i hope you get the same results.</p>
<pre><code>myarray = output.split("\n")
for i in range(len(myarray)):
if re.match('(^\()', myarray[i]):
group = myarray[i]
print group
if (re.match('(?!^\()', myarray[i])):
if re.match('\s+Outgoing Interface List', myarray[i]):
outgoing = myarray[i]
print outgoing
if re.match('(?!^\()', myarray[i]):
print myarray[i]
</code></pre>
<p>My results were:</p>
<pre><code>(*,224.0.0.0/4)
(*,224.0.0.0/24)
(*,224.0.1.39)
(96.34.246.55,224.0.1.39)
(0/3/CPU0)
(*,224.0.1.40)
</code></pre>
| 1 | 2016-08-08T16:02:46Z | [
"python",
"networking"
] |
What is the "Python" way to parse through mroutes | 38,831,931 | <p>I am a network engineer who is trying to script out a specific "mroute" (multicast route) from some exported data. I am trying to figure out the most "pythonic" path to do this. </p>
<p>The data looks something like this (nothing specific to my network, just lab exports):</p>
<pre>
(*,224.0.0.0/4) RPF nbr: 96.34.35.36 Flags: C RPF P
Up: 1w5d
(*,224.0.0.0/24) Flags: D P
Up: 1w5d
(*,224.0.1.39) Flags: S P
Up: 1w5d
(96.34.246.55,224.0.1.39) RPF nbr: 96.34.35.36 Flags: RPF
Up: 1w4d
Incoming Interface List
Bundle-Ether434 Flags: F A, Up: 1w4d
Outgoing Interface List
BVI100 Flags: F, Up: 1w4d
TenGigE0/0/0/3 Flags: F, Up: 1w4d
TenGigE0/0/1/1 Flags: F, Up: 1w4d
TenGigE0/0/1/2 Flags: F, Up: 1w4d
TenGigE0/0/1/3 Flags: F, Up: 1w4d
TenGigE0/1/1/1 Flags: F, Up: 1w4d
TenGigE0/1/1/2 Flags: F, Up: 1w4d
TenGigE0/2/1/0 Flags: F, Up: 1w4d
TenGigE0/2/1/1 Flags: F, Up: 1w4d
TenGigE0/2/1/2 Flags: F, Up: 1w4d
Bundle-Ether234 (0/3/CPU0) Flags: F, Up: 2d17h
Bundle-Ether434 Flags: F A, Up: 1w4d
(*,224.0.1.40) Flags: S P
Up: 1w5d
Outgoing Interface List
TenGigE0/2/1/0 Flags: II, Up: 1w5d
</pre>
<p>I have tried to replicate C style for loops to move the index incrementer up when I regex certain lines. </p>
<p>The end result is I only want to show a multicast group if it has specific output in the "Outgoing" section.</p>
<p>A horrible example of what I have tried so far (not complete, the data is handed off in a list):</p>
<pre><code>myarray = []
myarray = output.split("\n")
max_count = len(myarray)
i= 0
while (i < max_count):
if (re.match(r"(^\()", myarray[i])):
group = myarray[i]
print group
i+=1
while (re.match(r'(?!^\()', myarray[i])):
if (re.match(r" Outgoing Interface List", myarray[i])):
outgoing = myarray[i]
print outgoing
i+=1
while (re.match(r'(?!^\()', myarray[i])):
print myarray[i]
i+=1
else:
i+=1
else:
i+=1
</code></pre>
<p>Thanks for any advice.</p>
| 1 | 2016-08-08T14:32:03Z | 38,849,790 | <p>Not sure that it is more pythonic, but i prefer to use iterator/generator instead of direct array indexing.</p>
<pre><code>import re
def print_out_ifaces( group, iterator ):
"""
function print output interfaces with its group (ip)
It uses fact that you have empty line between 2 groups
"""
for iface_list in iterator:
iface_list = iface_list.rstrip() #remove tail \n
if not iface_list:
return
if not re.match( r" *Outgoing Interface List", iface_list ):
continue
print "group is " + group.rstrip()
print iface_list # will print "Outgoing Interface List"
for iface in iterator:
iface = iface.rstrip(); #remove tail \n
if not iface:
print # add additional empty line beween 2 groups
return
print iface
output = open( 'routes', 'r' ); # i saved your routes example in file "routes"
#if your "output" is string with routes
#then after "split('\n')" run "iter( myarray )"
for line in output:
if line.startswith( "(" ): # startswith much faster then checking first symbol by re
group = line;
print_out_ifaces( group, output )
</code></pre>
<p>Also it's possible to use special tools for parsing (like Pyparsing or PLY), but I think it will be overkill for this task.</p>
| 0 | 2016-08-09T11:43:46Z | [
"python",
"networking"
] |
django auth system 'created' | 38,832,122 | <p><a href="http://i.stack.imgur.com/PejnM.png" rel="nofollow"><img src="http://i.stack.imgur.com/PejnM.png" alt="enter image description here"></a></p>
<p>I'm working with django 1.7.11. I have a preexisting project and I've decided to try to use the built in admin panel (I have not created a superuser). When I opened the auth page I saw :</p>
<p><a href="http://i.stack.imgur.com/WJMyK.png" rel="nofollow"><img src="http://i.stack.imgur.com/WJMyK.png" alt="enter image description here"></a></p>
<p>Thinking there may be a problem with the tables I decided to delete the sqlite database and rerun everything:</p>
<pre><code>$ python manage.py makemigrations app1
Migrations for 'app1':
0001_initial.py:
- Create model Seller
$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: crispy_forms
Apply all migrations: admin, contenttypes, auth, app1, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying app1.0001_initial... FAKED
$ python manage.py syncdb
Operations to perform:
Synchronize unmigrated apps: crispy_forms
Apply all migrations: admin, contenttypes, auth, app1, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
No migrations to apply.
You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Created:
Error: '' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.
Created:
</code></pre>
<p>How can I fix this?</p>
<p>edit:</p>
<p>app1/models.py:</p>
<pre><code>from django.db import models
# from django.contrib.auth.models import AbstractUser
class Seller(models.Model):
# Address
contact_name = models.CharField(max_length=50)
contact_address = models.CharField(max_length=50)
contact_email = models.CharField(max_length=50)
contact_phone = models.CharField(max_length=50)
............
created = models.DateTimeField(auto_now_add=True,unique=True)
REQUIRED_FIELDS = ('contact_name','contact_email','contact_address','contact_phone')
USERNAME_FIELD = 'created'
</code></pre>
| 0 | 2016-08-08T14:40:16Z | 38,833,806 | <p>Your <code>username</code> field is set to <code>created</code>. Change it to contact_name to use a "name" to log in.</p>
<p>However!... You should probably extend the AbstractUser model and not change the USERNAME_FIELD unless you really have to. The way you are doing it now will require you to write custom login views etc..</p>
<p>EDIT:</p>
<p>To use the default user model just delete the line AUTH_USER_MODEL from settings.py then re-run the createsupseruser management command. Then go back to the admin login page and login with the username and password.</p>
| 1 | 2016-08-08T16:03:16Z | [
"python",
"django"
] |
pyqt4: How to change button event without adding a new event? | 38,832,143 | <p>I have a click button that I want to change events when the button is pressed. A minimal version of the existing code looks like this:</p>
<pre><code># Event that happens the first time
def first_event(self):
button.setText("Second Event")
button.clicked.connect(second_event)
# Event that happens the second time
def second_event(self):
button.setText("First Event")
button.clicked.connect(first_event)
button = QtGui.QPushButton("First Event")
button.clicked.connect(first_event)
</code></pre>
<p>Unfortunately, instead of <strong>changing</strong> the event that happens, it simply <strong>adds</strong> and event to the clicked signal, meaning that the following happens:</p>
<p>First button press - calls first_event</p>
<p>Second button press - calls first_event and second_event</p>
<p>Third button press - calls first_event twice and second_event</p>
<p>etc...</p>
<p>My desired behavior would be to have the button <strong>change functions when it is pressed</strong>, so that the resulting behavior would be:</p>
<p>First button press - calls first_event</p>
<p>Second button press - calls second_event</p>
<p>Third button press - calls first_event</p>
<p>etc...</p>
<p>Is there a way to make it so that it changes the click event instead of adding a new one? Is there a way to remove events after the fact?</p>
| 0 | 2016-08-08T14:41:33Z | 38,835,964 | <p>I found a way to separate old events from signals using the <code>disconnect()</code> method. Here is an edited version that accomplishes what I originally wanted to do:</p>
<pre><code># Event that happens the first time
def first_event(self):
button.setText("Second Event")
button.clicked.disconnect()
button.clicked.connect(second_event)
# Event that happens the second time
def second_event(self):
button.setText("First Event")
button.clicked.disconnect()
button.clicked.connect(first_event)
button = QtGui.QPushButton("First Event")
button.clicked.connect(first_event)
</code></pre>
<p>It's worth noting that instead of doing this, I eventually did what ekhumoro mentioned in the comments, and created a wrapper function with a flag to record the current state, and then call <code>first_event()</code> or <code>second_event()</code> based on the value of the flag.</p>
| 0 | 2016-08-08T18:20:01Z | [
"python",
"events",
"signals",
"pyqt4"
] |
Traverse through .tar.gz directories and concatenate files (without uncompressing the folders) | 38,832,182 | <p>I have a folder of about 20000 tar.gz directories, each containing a bunch of files. I want to go in the source folder, traverse through the tar.gz directories (<strong>without decompressing</strong>) and concatenate the files so at the end I will have three big files.</p>
<p>For e.g. I have a root folder <code>pnoc</code> which has <code>.tar.gz</code> directories, each compressed folder has three folders - <code>Kallisto</code>, <code>RSEM</code> and <code>Hugo</code>. I have uncompressed one such directory and looks like this:</p>
<pre><code>pnoc/
âââ C021_0001_20140916_tumor_RNASeq.tar.gz
âââ C021_0002_001113_tumor_RNASeq.tar.gz
âââ C021_0003_001409_tumor_RNASeq.tar.gz
âââ C021_0004_001418_tumor_RNASeq.tar.gz
âââ C021_0005_001661_tumor_RNASeq.tar.gz
âââ C021_0007_001669_tumor_RNASeq.tar.gz
âââ C021_0008_001699_tumor_RNASeq.tar.gz
âââ C021_0009_001766_tumor_RNASeq.tar.gz
âââ C021_0010_001774_tumor_RNASeq.tar.gz
âââ C021_0011_001786_tumor_RNASeq.tar.gz
âââ C021_0012_001825_tumor_RNASeq.tar.gz
âââ C021_0013_001872_tumor_RNASeq.tar.gz
âââ CPBT_0001_1_tumor_RNASeq.tar.gz
âââ CPBT_0003_1_tumor_RNASeq.tar.gz
âââ CPBT_0004_1_tumor_RNASeq.tar.gz
âââ CPBT_0005_1_tumor_RNASeq.tar.gz
âââ CPBT_0006_1_tumor_RNASeq.tar.gz
âââ CPBT_0007_1_tumor_RNASeq.tar.gz
âââ CPBT_0008_1_tumor_RNASeq.tar.gz
âââ CPBT_0009_1_tumor_RNASeq.tar.gz
âââ IMPROPERLY_PAIRED.C021_0006_001666_tumor_RNASeq.tar.gz
âââ pnoc-manifest
C021_0001_20140916_tumor_RNASeq
âââ Kallisto
â  âââ C021_0001_20140916_tumor_RNASeq.abundance.h5
â  âââ C021_0001_20140916_tumor_RNASeq.abundance.tsv
â  âââ C021_0001_20140916_tumor_RNASeq.run_info.json
âââ RSEM
âââ C021_0001_20140916_tumor_RNASeq.rsem.genes.norm_counts.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem.genes.raw_counts.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem.isoform.norm_counts.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem.isoform.raw_counts.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem_genes.results
âââ C021_0001_20140916_tumor_RNASeq.rsem_isoforms.results
âââ Hugo
âââ C021_0001_20140916_tumor_RNASeq.rsem.genes.norm_counts.hugo.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem.genes.raw_counts.hugo.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem.isoform.norm_counts.hugo.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem.isoform.raw_counts.hugo.tab
âââ C021_0001_20140916_tumor_RNASeq.rsem_genes.hugo.results
âââ C021_0001_20140916_tumor_RNASeq.rsem_isoforms.hugo.results
</code></pre>
<p>So I want to concatenate all the *.abundance.tsv in one, *.rsem.genes.norm_counts.tab in second and *.rsem_genes.hugo.results in third file. What's the best and most efficient way to do that? I am okay with anything - <code>R</code>, <code>Python</code> or <code>Bash</code>.</p>
<pre><code>$ find --version
find (GNU findutils) 4.5.11
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION SELINUX FTS(FTS_CWDFD) CBO(level=2)
</code></pre>
<p>Thanks!</p>
| 3 | 2016-08-08T14:43:15Z | 38,832,277 | <p>Using <code>bash</code> <code>find</code> command as below; The <code>cat</code> command in <code>exec</code> is applied to all the files returned by the command. The <code>+</code> option is to ensure no more than one instance of the <code>cat</code> is spawned by the shell.</p>
<p>Here <code>{}</code> denotes the files returned the find command. Refer more about <a href="http://tldp.org/LDP/abs/html/moreadv.html" rel="nofollow"><code>find -exec</code></a></p>
<pre><code>find . -type f -name '*.abundance.tsv' -exec cat "{}" + >> ../AbundanceTSV.tsv
find . -type f -name '*.rsem.genes.norm_counts.tab' -exec cat "{}" + >> ../GenesNormCounts.tab
find . -type f -name '*.rsem_genes.hugo.results' -exec cat "{}" + >> ../HugoResults.results
</code></pre>
| 3 | 2016-08-08T14:47:56Z | [
"python",
"bash",
"shell",
"find"
] |
Regex subbing in Python leads to ASCII characters appearing | 38,832,203 | <p>I am trying to use regex to replace some issues in some text.</p>
<p>Strings look like this:</p>
<p><code>a = "Here is a shortString with various issuesWith spacing"</code></p>
<p>My regex looks like this right now:
<code>new_string = re.sub("[a-z][A-Z]", "\1 \2", a)</code>.</p>
<p>This takes those places with missing spaces (there is always a capital letter after a lowercase letter), and adds a space.</p>
<p>Unfortunately, the output looks like this:</p>
<p><code>Here is a shor\x01 \x02tring with various issue\x01 \x02ith spacing</code></p>
<p>I want it to look like this:</p>
<p><code>b = "Here is a short String with various issues With spacing"</code></p>
<p>It seems that the regex is properly matching the correct instances of things I want to change, but there is something wrong with my substitution. I thought <code>\1 \2</code> meant replace with the first part of the regex, add a space, and then add the second matched item. But for some reason I get something else?</p>
| 1 | 2016-08-08T14:44:17Z | 38,832,261 | <pre><code>>>> a = "Here is a shortString with various issuesWith spacing"
>>> re.sub("([a-z])([A-Z])", r"\1 \2", a)
'Here is a short String with various issues With spacing'
</code></pre>
<p>capturing group and backslash escaping was missing.</p>
<p>you can go even further:</p>
<pre><code>>>> a = "Here is a shortString with various issuesWith spacing"
>>> re.sub('([a-z])([A-Z])', r'\1 \2', a).lower().capitalize()
'Here is a short string with various issues with spacing'
</code></pre>
| 2 | 2016-08-08T14:47:12Z | [
"python",
"regex",
"string"
] |
Regex subbing in Python leads to ASCII characters appearing | 38,832,203 | <p>I am trying to use regex to replace some issues in some text.</p>
<p>Strings look like this:</p>
<p><code>a = "Here is a shortString with various issuesWith spacing"</code></p>
<p>My regex looks like this right now:
<code>new_string = re.sub("[a-z][A-Z]", "\1 \2", a)</code>.</p>
<p>This takes those places with missing spaces (there is always a capital letter after a lowercase letter), and adds a space.</p>
<p>Unfortunately, the output looks like this:</p>
<p><code>Here is a shor\x01 \x02tring with various issue\x01 \x02ith spacing</code></p>
<p>I want it to look like this:</p>
<p><code>b = "Here is a short String with various issues With spacing"</code></p>
<p>It seems that the regex is properly matching the correct instances of things I want to change, but there is something wrong with my substitution. I thought <code>\1 \2</code> meant replace with the first part of the regex, add a space, and then add the second matched item. But for some reason I get something else?</p>
| 1 | 2016-08-08T14:44:17Z | 38,832,267 | <p>You need to define capturing groups, and use raw string literals:</p>
<pre><code>import re
a = "Here is a shortString with various issuesWith spacing"
new_string = re.sub(r"([a-z])([A-Z])", r"\1 \2", a)
print(new_string)
</code></pre>
<p>See the <a href="https://ideone.com/CoE8xR" rel="nofollow">Python demo</a>.</p>
<p>Note that without the <code>r''</code> prefix Python interpreted the <code>\1</code> and <code>\2</code> as characters rather than as backreferences since the <code>\</code> was parsed as part of an escape sequence. In raw string literals, <code>\</code> is parsed as a literal backslash.</p>
| 1 | 2016-08-08T14:47:31Z | [
"python",
"regex",
"string"
] |
Regex subbing in Python leads to ASCII characters appearing | 38,832,203 | <p>I am trying to use regex to replace some issues in some text.</p>
<p>Strings look like this:</p>
<p><code>a = "Here is a shortString with various issuesWith spacing"</code></p>
<p>My regex looks like this right now:
<code>new_string = re.sub("[a-z][A-Z]", "\1 \2", a)</code>.</p>
<p>This takes those places with missing spaces (there is always a capital letter after a lowercase letter), and adds a space.</p>
<p>Unfortunately, the output looks like this:</p>
<p><code>Here is a shor\x01 \x02tring with various issue\x01 \x02ith spacing</code></p>
<p>I want it to look like this:</p>
<p><code>b = "Here is a short String with various issues With spacing"</code></p>
<p>It seems that the regex is properly matching the correct instances of things I want to change, but there is something wrong with my substitution. I thought <code>\1 \2</code> meant replace with the first part of the regex, add a space, and then add the second matched item. But for some reason I get something else?</p>
| 1 | 2016-08-08T14:44:17Z | 38,833,842 | <p>You can have a try like this:</p>
<pre><code>>>>> import re
>>>> a = "Here is a shortString with various issuesWith spacing"
>>>> re.sub(r"(?<=[a-z])(?=[A-Z])", " ", a)
>>>> Here is a short String with various issues With spacing
</code></pre>
| 0 | 2016-08-08T16:04:43Z | [
"python",
"regex",
"string"
] |
How to 'unpack' a list or tuple in Python | 38,832,218 | <p>I'm writing a Python program to play Tic Tac Toe, using Numpy arrays with "X" represented by <code>1</code> and "O" by <code>0</code>. The class includes a function to place a mark on the board:</p>
<pre><code>import numpy as np
class Board():
def __init__(self, grid = np.ones((3,3))*np.nan):
self.grid = grid
def place_mark(self, pos, mark):
self.grid[pos[0],pos[1]] = mark
</code></pre>
<p>so that, for example, </p>
<pre><code>board = Board()
board.place_mark([0,1], 1)
print board.grid
</code></pre>
<p>yields</p>
<pre><code>[[ nan 1. nan]
[ nan nan nan]
[ nan nan nan]]
</code></pre>
<p>I was wondering if the <code>pos[0], pos[1]</code> argument in the <code>place_mark</code> function could somehow be replaced by the 'unpacked' contents of <code>pos</code> (which is always a list of length 2). In Ruby this would be done using the splat operator: <code>*pos</code>, but this does not appear to be valid syntax in Python.</p>
| 2 | 2016-08-08T14:45:00Z | 38,832,442 | <p>As suggested by Lukasz, the input argument should be a tuple. In this example it can be converted to one:</p>
<pre><code>def place_mark(self, pos, mark):
self.grid[tuple(pos)] = mark
</code></pre>
<p>My question is not the same <a href="http://stackoverflow.com/questions/2238355/what-is-the-pythonic-way-to-unpack-tuples">What is the pythonic way to unpack tuples?</a> because <code>pos</code> does not constitute the input arguments to a function, but rather the indices of a 2-dimensional array.</p>
| 2 | 2016-08-08T14:55:46Z | [
"python",
"numpy"
] |
How to 'unpack' a list or tuple in Python | 38,832,218 | <p>I'm writing a Python program to play Tic Tac Toe, using Numpy arrays with "X" represented by <code>1</code> and "O" by <code>0</code>. The class includes a function to place a mark on the board:</p>
<pre><code>import numpy as np
class Board():
def __init__(self, grid = np.ones((3,3))*np.nan):
self.grid = grid
def place_mark(self, pos, mark):
self.grid[pos[0],pos[1]] = mark
</code></pre>
<p>so that, for example, </p>
<pre><code>board = Board()
board.place_mark([0,1], 1)
print board.grid
</code></pre>
<p>yields</p>
<pre><code>[[ nan 1. nan]
[ nan nan nan]
[ nan nan nan]]
</code></pre>
<p>I was wondering if the <code>pos[0], pos[1]</code> argument in the <code>place_mark</code> function could somehow be replaced by the 'unpacked' contents of <code>pos</code> (which is always a list of length 2). In Ruby this would be done using the splat operator: <code>*pos</code>, but this does not appear to be valid syntax in Python.</p>
| 2 | 2016-08-08T14:45:00Z | 38,832,648 | <p>With Numpy, there's a difference between indexing with lists and multi-dimensional indexing. <code>self.grid[[0,1]]</code> is equivalent to concatenating <code>self.grid[0]</code> and <code>self.grid[1]</code>, each 3x1 arrays, into a 3x2 array.</p>
<p>If you use tuples instead of lists for indexing, then it will be correctly interpreted as multi-dimensional indexing: <code>self.grid[(0, 1)]</code> is interpreted the same as <code>self.grid[0, 1]</code>.</p>
<p>There is a <code>*</code> operator for unpacking sequences, but in the context of function arguments only, at least in Python 2. So, with lists you could also do this:</p>
<pre><code>def place_mark(self, mark, x, y):
self.grid[x, y] = mark
place_mark(1, *[0, 1])
</code></pre>
<p>NB. <a href="https://eev.ee/blog/2016/07/31/python-faq-why-should-i-use-python-3/#unpacking" rel="nofollow">(Expanded usefulness of <code>*</code> in Python 3)</a></p>
| 3 | 2016-08-08T15:05:10Z | [
"python",
"numpy"
] |
How to discretize large dataframe by columns with variable bins in Pandas/Dask | 38,832,219 | <p>I am able to discretize a Pandas dataframe by columns with this code:</p>
<pre><code>import numpy as np
import pandas as pd
def discretize(X, n_scale=1):
for c in X.columns:
loc = X[c].median()
# median absolute deviation of the column
scale = mad(X[c])
bins = [-np.inf, loc - (scale * n_scale),
loc + (scale * n_scale), np.inf]
X[c] = pd.cut(X[c], bins, labels=[-1, 0, 1])
return X
</code></pre>
<p>I want to discretize each column using as parameters: loc (the median of the column) and scale (the <a href="https://en.wikipedia.org/wiki/Median_absolute_deviation" rel="nofollow">median absolute deviation</a> of the column).</p>
<p>With small dataframes the time required is acceptable (since it is a single thread solution).</p>
<p>However, with larger dataframes I want to exploit more threads (or processes) to speed up the computation.</p>
<p>I am no expert of <a href="http://dask.pydata.org/en/latest/index.html" rel="nofollow">Dask</a>, which should provide the solution for this problem.</p>
<p>However, in my case the discretization should be feasible with the code:</p>
<pre><code>import dask.dataframe as dd
import numpy as np
import pandas as pd
def discretize(X, n_scale=1):
# I'm using only 2 partitions for this example
X_dask = dd.from_pandas(X, npartitions=2)
# FIXME:
# how can I define bins to compute loc and scale
# for each column?
bins = [-np.inf, loc - (scale * n_scale),
loc + (scale * n_scale), np.inf]
X = X_dask.apply(pd.cut, axis=1, args=(bins,), labels=[-1, 0, 1]).compute()
return X
</code></pre>
<p>but the problem here is that <code>loc</code> and <code>scale</code> are dependent on column values, so they should be computed for each column, either before or during the apply.</p>
<p>How can it be done?</p>
| 2 | 2016-08-08T14:45:03Z | 38,841,341 | <p>I've never used <code>dask</code>, but I guess you can define a new function to be used in <code>apply</code>.</p>
<pre><code>import dask.dataframe as dd
import multiprocessing as mp
import numpy as np
import pandas as pd
def discretize(X, n_scale=1):
X_dask = dd.from_pandas(X.T, npartitions=mp.cpu_count()+1)
X = X_dask.apply(_discretize_series,
axis=1, args=(n_scale,),
columns=X.columns).compute().T
return X
def _discretize_series(x, n_scale=1):
loc = x.median()
scale = mad(x)
bins = [-np.inf, loc - (scale * n_scale),
loc + (scale * n_scale), np.inf]
x = pd.cut(x, bins, labels=[-1, 0, 1])
return x
</code></pre>
| 1 | 2016-08-09T02:57:04Z | [
"python",
"pandas",
"dataframe",
"parallel-processing",
"dask"
] |
Find number of breaks in a sequence | 38,832,238 | <p>I have a program that is parsing allele sequences. I am trying to write a code that determines if the allele is complete or not. To do so, I need to count the number of breaks in the reference sequence. A break is signified by a string of '-'. If there is more than one break I want the program to say "Incomplete Allele." </p>
<p>How can I figure out how to count the number of breaks in the sequence? </p>
<p>Here is an example of a "broken" sequence:</p>
<pre><code>>DQB1*04:02:01
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
--ATGTCTTGGAAGAAGGCTTTGCGGAT-------CCCTGGAGGCCTTCGGGTAGCAACT
GTGACCTT----GATGCTGGCGATGCTGAGCACCCCGGTGGCTGAGGGCAGAGACTCTCC
CGAGGATTTCGTGTTCCAGTTTAAGGGCATGTGCTACTTCACCAACGGGACCGAGCGCGT
GCGGGGTGTGACCAGATACATCTATAACCGAGAGGAGTACGCGCGCTTCGACAGCGACGT
GGGGGTGTATCGGGCGGTGACGCCGCTGGGGCGGCTTGACGCCGAGTACTGGAATAGCCA
GAAGGACATCCTGGAGGAGGACCGGGCGTCGGTGGACACCGTATGCAGACACAACTACCA
GTTGGAGCTCCGCACGACCTTGCAGCGGCGA-----------------------------
-----------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
---GTGGAGCCCACAGTGACCATCTCCCCATCCAGGACAGAGGCCCTCAACCACCACAAC
CTGCTGGTCTGCTCAGTGACAGATTTCTATCCAGCCCAGATCAAAGTCCGGTGGTTTCGG
AATGACCAGGAGGAGACAACTGGCGTTGTGTCCACCCCCCTTATTAGGAACGGTGACTGG
ACCTTCCAGATCCTGGTGATGCTGGAAATGACTCCCCAGCGTGGAGACGTCTACACCTGC
CACGTGGAGCACCCCAGCCTCCAGAACCCCATCATCGTGGAGTGGCGGGCTCAGTCTGAA
TCTGCCCAGAGCAAGATGCTGAGTGG----CATTGGAGGCTTCGTGCTGGGGCTGATCTT
CCTCGGGCTGGGCCTTATTATC--------------CATCACAGGAGTCAGAAAGGGCTC
CTGCACTGA---------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
</code></pre>
<p>The code I have so far is as follows:</p>
<pre><code>idx=[]
for m in range(len(sequence)):
for n in re.finditer('-',sequence[0]):
idx.append(n.start())
counter=0
min_val=[]
for n in range(len(idx)):
if counter==idx[n]:
counter=counter+1
elif counter !=0:
min_val.append(idx[n-1])
counter=0
</code></pre>
<p>My reasoning for the above code was if I could find the start positions of the '-' then I can see how many times they appear within the sequence and if they break the sequence at all. However, I know there are some flaws in the above code. </p>
| 4 | 2016-08-08T14:46:08Z | 38,832,430 | <p>I think this should do:</p>
<pre><code>def test(sequence):
sequence = ''.join(sequence.splitlines()[1:]) # remove first line (header and line breaks)
S = [segments for segments in sequence.split('-') if block != '']
if len(S)>2: # len(S) should be the number of remaining segments
print "Incomplete Allele."
</code></pre>
| 0 | 2016-08-08T14:55:15Z | [
"python",
"string",
"python-2.7"
] |
Find number of breaks in a sequence | 38,832,238 | <p>I have a program that is parsing allele sequences. I am trying to write a code that determines if the allele is complete or not. To do so, I need to count the number of breaks in the reference sequence. A break is signified by a string of '-'. If there is more than one break I want the program to say "Incomplete Allele." </p>
<p>How can I figure out how to count the number of breaks in the sequence? </p>
<p>Here is an example of a "broken" sequence:</p>
<pre><code>>DQB1*04:02:01
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
--ATGTCTTGGAAGAAGGCTTTGCGGAT-------CCCTGGAGGCCTTCGGGTAGCAACT
GTGACCTT----GATGCTGGCGATGCTGAGCACCCCGGTGGCTGAGGGCAGAGACTCTCC
CGAGGATTTCGTGTTCCAGTTTAAGGGCATGTGCTACTTCACCAACGGGACCGAGCGCGT
GCGGGGTGTGACCAGATACATCTATAACCGAGAGGAGTACGCGCGCTTCGACAGCGACGT
GGGGGTGTATCGGGCGGTGACGCCGCTGGGGCGGCTTGACGCCGAGTACTGGAATAGCCA
GAAGGACATCCTGGAGGAGGACCGGGCGTCGGTGGACACCGTATGCAGACACAACTACCA
GTTGGAGCTCCGCACGACCTTGCAGCGGCGA-----------------------------
-----------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
---GTGGAGCCCACAGTGACCATCTCCCCATCCAGGACAGAGGCCCTCAACCACCACAAC
CTGCTGGTCTGCTCAGTGACAGATTTCTATCCAGCCCAGATCAAAGTCCGGTGGTTTCGG
AATGACCAGGAGGAGACAACTGGCGTTGTGTCCACCCCCCTTATTAGGAACGGTGACTGG
ACCTTCCAGATCCTGGTGATGCTGGAAATGACTCCCCAGCGTGGAGACGTCTACACCTGC
CACGTGGAGCACCCCAGCCTCCAGAACCCCATCATCGTGGAGTGGCGGGCTCAGTCTGAA
TCTGCCCAGAGCAAGATGCTGAGTGG----CATTGGAGGCTTCGTGCTGGGGCTGATCTT
CCTCGGGCTGGGCCTTATTATC--------------CATCACAGGAGTCAGAAAGGGCTC
CTGCACTGA---------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
</code></pre>
<p>The code I have so far is as follows:</p>
<pre><code>idx=[]
for m in range(len(sequence)):
for n in re.finditer('-',sequence[0]):
idx.append(n.start())
counter=0
min_val=[]
for n in range(len(idx)):
if counter==idx[n]:
counter=counter+1
elif counter !=0:
min_val.append(idx[n-1])
counter=0
</code></pre>
<p>My reasoning for the above code was if I could find the start positions of the '-' then I can see how many times they appear within the sequence and if they break the sequence at all. However, I know there are some flaws in the above code. </p>
| 4 | 2016-08-08T14:46:08Z | 38,832,440 | <p>It seems like you can just count the occurrances of <code>-+</code>, i.e. a sequence of <em>one or more</em> <code>-</code> symbols. The only problem are the line breaks, but you could either incorporate those into the regex, or split and join the string before matching.</p>
<pre><code>>>> sequence = """>DQB1*04:02:01....."""
>>> joined = ''.join(sequence.splitlines())
>>> sum(1 for m in re.finditer("-+", joined))
7
</code></pre>
<p>Note: This includes the <code>-</code> at the start and end of the sequence.</p>
<p>Or reverse the approach: Instead of counting the gaps, count the groups:</p>
<pre><code>>>> sum(1 for m in re.finditer("[GATC]+", joined))
6
</code></pre>
| 0 | 2016-08-08T14:55:45Z | [
"python",
"string",
"python-2.7"
] |
Find number of breaks in a sequence | 38,832,238 | <p>I have a program that is parsing allele sequences. I am trying to write a code that determines if the allele is complete or not. To do so, I need to count the number of breaks in the reference sequence. A break is signified by a string of '-'. If there is more than one break I want the program to say "Incomplete Allele." </p>
<p>How can I figure out how to count the number of breaks in the sequence? </p>
<p>Here is an example of a "broken" sequence:</p>
<pre><code>>DQB1*04:02:01
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
--ATGTCTTGGAAGAAGGCTTTGCGGAT-------CCCTGGAGGCCTTCGGGTAGCAACT
GTGACCTT----GATGCTGGCGATGCTGAGCACCCCGGTGGCTGAGGGCAGAGACTCTCC
CGAGGATTTCGTGTTCCAGTTTAAGGGCATGTGCTACTTCACCAACGGGACCGAGCGCGT
GCGGGGTGTGACCAGATACATCTATAACCGAGAGGAGTACGCGCGCTTCGACAGCGACGT
GGGGGTGTATCGGGCGGTGACGCCGCTGGGGCGGCTTGACGCCGAGTACTGGAATAGCCA
GAAGGACATCCTGGAGGAGGACCGGGCGTCGGTGGACACCGTATGCAGACACAACTACCA
GTTGGAGCTCCGCACGACCTTGCAGCGGCGA-----------------------------
-----------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
---GTGGAGCCCACAGTGACCATCTCCCCATCCAGGACAGAGGCCCTCAACCACCACAAC
CTGCTGGTCTGCTCAGTGACAGATTTCTATCCAGCCCAGATCAAAGTCCGGTGGTTTCGG
AATGACCAGGAGGAGACAACTGGCGTTGTGTCCACCCCCCTTATTAGGAACGGTGACTGG
ACCTTCCAGATCCTGGTGATGCTGGAAATGACTCCCCAGCGTGGAGACGTCTACACCTGC
CACGTGGAGCACCCCAGCCTCCAGAACCCCATCATCGTGGAGTGGCGGGCTCAGTCTGAA
TCTGCCCAGAGCAAGATGCTGAGTGG----CATTGGAGGCTTCGTGCTGGGGCTGATCTT
CCTCGGGCTGGGCCTTATTATC--------------CATCACAGGAGTCAGAAAGGGCTC
CTGCACTGA---------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
</code></pre>
<p>The code I have so far is as follows:</p>
<pre><code>idx=[]
for m in range(len(sequence)):
for n in re.finditer('-',sequence[0]):
idx.append(n.start())
counter=0
min_val=[]
for n in range(len(idx)):
if counter==idx[n]:
counter=counter+1
elif counter !=0:
min_val.append(idx[n-1])
counter=0
</code></pre>
<p>My reasoning for the above code was if I could find the start positions of the '-' then I can see how many times they appear within the sequence and if they break the sequence at all. However, I know there are some flaws in the above code. </p>
| 4 | 2016-08-08T14:46:08Z | 38,832,553 | <p>You could just filter out all the '-' characters and based on the number of remaining segments determine number of breaks.</p>
<pre><code>str_list = filter(None, sequence.split('-'))
if len(str_list) > 2:
return "Incomplete Allele"
else:
return "Complete Allele"
</code></pre>
| 1 | 2016-08-08T15:00:39Z | [
"python",
"string",
"python-2.7"
] |
How to make the regexp ignore a new line in python? | 38,832,239 | <p>I use the regex like that</p>
<pre><code>return(\s+([^"\n;]+))?;
</code></pre>
<p>in order to match the return statement in obj-c,but when I use it through python like this:</p>
<pre><code>re.sub(r'return(\s+([^"\n;]+))?;',r'{\g<0>}',str(content))
</code></pre>
<p>I find that it match like this statement</p>
<pre><code>//please {return
[self funcA];}
</code></pre>
<p>and make the code error.How can I deal with it ?</p>
| 2 | 2016-08-08T14:46:08Z | 38,832,599 | <p>I think the issue is that your regex has <code>\s</code> that matches any whitespace.</p>
<p>You might want to just match literal spaces or tabs with <code>[ \t]</code>:</p>
<pre><code>r'return([ \t]+([^"\n;]+))?;'
</code></pre>
<p>(<a href="https://regex101.com/r/mM6mK2/2" rel="nofollow">demo</a>) or - better:</p>
<pre><code>r'return[ \t]+[^"\n;]*;'
</code></pre>
<p>See <a href="https://regex101.com/r/mM6mK2/3" rel="nofollow">the regex demo</a></p>
| 2 | 2016-08-08T15:02:51Z | [
"python",
"regex"
] |
pcapy.PcapError: eth1: You don't have permission to capture on that device | 38,832,347 | <p>I am trying to run pcapy_sniffer.py but i get this</p>
<p>pcapy.PcapError: eth1: You don't have permission to capture on that device (socket: Operation not permitted)</p>
| 0 | 2016-08-08T14:50:48Z | 38,832,386 | <p>If you're running on linux or OS X try running as root or with <code>sudo</code>, otherwise if you're on windows try running as administrator.</p>
| 0 | 2016-08-08T14:53:03Z | [
"python",
"scapy",
"pcap"
] |
Change pd datetime object to integer | 38,832,486 | <p>I have a pandas dataframe with two dates in them. I want to take the difference in days between them. But the resulting difference looks like a string ex ('7 days'). Is there a way to change this to just the integer date difference?</p>
<pre><code>y['datePulled'] = pd.to_datetime(y['datePulled'])
y['Dates'] = pd.to_datetime(y['Dates'])
y['Datediff'] = y['datePulled'] - y['Dates']
y['Datediff']
0 7 days
1 6 days
2 5 days
3 4 days
4 3 days
5 2 days
6 1 days
</code></pre>
| 1 | 2016-08-08T14:57:50Z | 38,832,514 | <p>You can use:</p>
<pre><code>(y['Datediff'] / np.timedelta64(1, 'D')).astype(int)
</code></pre>
<p>Or:</p>
<pre><code>y['Datediff'].dt.days
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
import numpy as np
y = pd.DataFrame({ 'datePulled': ['2016-01-05','2016-01-04'],
'Dates': ['2016-01-01','2016-01-02']})
y['datePulled'] = pd.to_datetime(y['datePulled'])
y['Dates'] = pd.to_datetime(y['Dates'])
y['Datediff'] = y['datePulled'] - y['Dates']
print (y)
#output is float, cast to int
y['Datediff1'] = (y['Datediff'] / np.timedelta64(1, 'D')).astype(int)
y['Datediff2'] = y['Datediff'].dt.days
print (y)
Dates datePulled Datediff Datediff1 Datediff2
0 2016-01-01 2016-01-05 4 days 4 4
1 2016-01-02 2016-01-04 2 days 2 2
</code></pre>
<p>In larger DataFrame first method is faster:</p>
<pre><code>y = pd.concat([y]*1000).reset_index(drop=True)
In [236]: %timeit (y['Datediff'] / np.timedelta64(1, 'D')).astype(int)
1000 loops, best of 3: 789 µs per loop
In [237]: %timeit y['Datediff'].dt.days
100 loops, best of 3: 15.3 ms per loop
</code></pre>
| 2 | 2016-08-08T14:59:09Z | [
"python",
"date",
"pandas"
] |
TypeError: get() missing 1 required positional argument: 'self' - NOT USING CLASS - Python 3.5 | 38,832,494 | <p>due to my crude knowledge of Python, I am expecting more mistakes with the following script than just the positional argument error. Hence, I would very much appreciate any and all kind of observations/corrections. Again, I would like, if at all possible, to fix the positional argument error without having to use class. Thank you all very much.</p>
<pre><code># Python 3.5.1
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("300x200+150+50")
total = 0.0
amount = 0.0
n = 0
x = 0
def total_amount():
total = Entry.get()
print ('got total!')
lb=ttk.Label(root, text="Enter total").grid(row=n, column=1)
totalEnt=ttk.Entry(root).grid(row=n, column=2)
button=ttk.Button(root, text='ok', command=total_amount).grid(row=n, column=3)
if total !=0:
while True:
if amount < total:
while True:
n = n + 1
if x == 0:
def amount_entered(event):
amount = amount + Entry.get()
x = x + 1
print ('got amount!')
lb=ttk.Label(root, text="Enter amount").grid(row=n, column=1)
amountEnt=ttk.Entry(root).grid(row=n, column=2)
button=ttk.Button(root, text='Ok', command=amount_entered).grid(row=n, column=3)
elif x != 0:
print ('gone from internal loop!')
break
elif sub == total:
print ('done!')
break
else:
print ('sum of amount(s) cannot be greater than total')
else:
pass
root.mainloop()
</code></pre>
| 0 | 2016-08-08T14:58:24Z | 38,862,779 | <p>You're getting the error message because .get() won't work on the class Entry. It will work on an object such as totalEnt that is an instance of Entry.</p>
<p>So you need </p>
<pre><code>total = totalEnt.get()
</code></pre>
<p>Also, something like</p>
<pre><code>totalEnt=ttk.Entry(root).grid(row=n, column=2)
</code></pre>
<p>won't work. If you need to give a name to an object such as totalEnt, you need to create it first, then call grid on it.</p>
<pre><code>totalEnt=ttk.Entry(root)
totalEnt.grid(row=n, column=2)
</code></pre>
<p>You don't necessarily have to write any of your own classes, but to use tkinter (or probably any gui package in a object oriented language) you have to use some of the classes that are part of it. When you do something like</p>
<pre><code>totalEnt=ttk.Entry(root)
</code></pre>
<p>You are creating an object, totalEnt, which is an instance of the class ttk.Entry. You imported the class from tkinter.</p>
| 0 | 2016-08-10T01:16:20Z | [
"python",
"python-3.x",
"variables",
"tkinter",
"arguments"
] |
Saving print statement to new file | 38,832,545 | <p>New to python (should be noted). Go easy on me. </p>
<p>I have written the following to isolate a very specific part of a file</p>
<pre><code>for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
print line
</code></pre>
<p>the output appears as such </p>
<pre><code>PLY/1,48.107478621032,-69.733975000000
PLY/2,48.163516399836,-70.032838888053
PLY/3,48.270000002883,-70.032838888053
PLY/4,48.270000002883,-69.712824977522
PLY/5,48.192379262383,-69.711801581207
PLY/6,48.191666671083,-69.532840015422
PLY/7,48.033358898628,-69.532840015422
PLY/8,48.033359033880,-69.733975000000
PLY/9,48.107478621032,-69.733975000000
</code></pre>
<p>Ideally what I am hoping for is the output to create a CSV file with the coordinates. (The PLY/1, PLY/2 etc. Does not need to stay). Is this doable? If not, at least can the print statement result in a new textfile with the same name as the KAP file? </p>
| 1 | 2016-08-08T15:00:22Z | 38,832,657 | <p>you can use csv module</p>
<pre><code>import csv
with open('120301.csv', 'w', newline='') as file:
writer = csv.writer(file)
for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
writer.writerow(rec.split(','))
</code></pre>
<p>In the similar way <code>csv.reader</code> can easily read records from your input file.
<a href="https://docs.python.org/3/library/csv.html?highlight=csv#module-contents" rel="nofollow">https://docs.python.org/3/library/csv.html?highlight=csv#module-contents</a></p>
<p><strong>edit #1</strong></p>
<p>In python 2.x you should open the file in binary mode:</p>
<pre><code>import csv
with open('120301.csv', 'wb') as file:
writer = csv.writer(file)
for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
writer.writerow(rec.split(','))
</code></pre>
| 1 | 2016-08-08T15:05:42Z | [
"python",
"writing"
] |
Saving print statement to new file | 38,832,545 | <p>New to python (should be noted). Go easy on me. </p>
<p>I have written the following to isolate a very specific part of a file</p>
<pre><code>for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
print line
</code></pre>
<p>the output appears as such </p>
<pre><code>PLY/1,48.107478621032,-69.733975000000
PLY/2,48.163516399836,-70.032838888053
PLY/3,48.270000002883,-70.032838888053
PLY/4,48.270000002883,-69.712824977522
PLY/5,48.192379262383,-69.711801581207
PLY/6,48.191666671083,-69.532840015422
PLY/7,48.033358898628,-69.532840015422
PLY/8,48.033359033880,-69.733975000000
PLY/9,48.107478621032,-69.733975000000
</code></pre>
<p>Ideally what I am hoping for is the output to create a CSV file with the coordinates. (The PLY/1, PLY/2 etc. Does not need to stay). Is this doable? If not, at least can the print statement result in a new textfile with the same name as the KAP file? </p>
| 1 | 2016-08-08T15:00:22Z | 38,832,783 | <p>This is totally doable! Here are a couple links to some docs: <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> #for writing/reading CSV.
You could also just make your own CSV with the regular file reading/writing functions. </p>
<pre><code>file = open('data', rw)
output = open('output.csv', w)
file.write('your infos') #add a comma to each string you output?
</code></pre>
<p>i think that should work. </p>
| 1 | 2016-08-08T15:11:00Z | [
"python",
"writing"
] |
Saving print statement to new file | 38,832,545 | <p>New to python (should be noted). Go easy on me. </p>
<p>I have written the following to isolate a very specific part of a file</p>
<pre><code>for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
print line
</code></pre>
<p>the output appears as such </p>
<pre><code>PLY/1,48.107478621032,-69.733975000000
PLY/2,48.163516399836,-70.032838888053
PLY/3,48.270000002883,-70.032838888053
PLY/4,48.270000002883,-69.712824977522
PLY/5,48.192379262383,-69.711801581207
PLY/6,48.191666671083,-69.532840015422
PLY/7,48.033358898628,-69.532840015422
PLY/8,48.033359033880,-69.733975000000
PLY/9,48.107478621032,-69.733975000000
</code></pre>
<p>Ideally what I am hoping for is the output to create a CSV file with the coordinates. (The PLY/1, PLY/2 etc. Does not need to stay). Is this doable? If not, at least can the print statement result in a new textfile with the same name as the KAP file? </p>
| 1 | 2016-08-08T15:00:22Z | 38,832,918 | <p>You could open the file at the beginning of your code and then just add a write statement after the print line. Something like this:</p>
<pre><code>target = open(filename, 'w')
for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
print line
target.write(line)
target.write("\n") #writes a new line
</code></pre>
| 1 | 2016-08-08T15:17:45Z | [
"python",
"writing"
] |
Saving print statement to new file | 38,832,545 | <p>New to python (should be noted). Go easy on me. </p>
<p>I have written the following to isolate a very specific part of a file</p>
<pre><code>for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
print line
</code></pre>
<p>the output appears as such </p>
<pre><code>PLY/1,48.107478621032,-69.733975000000
PLY/2,48.163516399836,-70.032838888053
PLY/3,48.270000002883,-70.032838888053
PLY/4,48.270000002883,-69.712824977522
PLY/5,48.192379262383,-69.711801581207
PLY/6,48.191666671083,-69.532840015422
PLY/7,48.033358898628,-69.532840015422
PLY/8,48.033359033880,-69.733975000000
PLY/9,48.107478621032,-69.733975000000
</code></pre>
<p>Ideally what I am hoping for is the output to create a CSV file with the coordinates. (The PLY/1, PLY/2 etc. Does not need to stay). Is this doable? If not, at least can the print statement result in a new textfile with the same name as the KAP file? </p>
| 1 | 2016-08-08T15:00:22Z | 38,833,887 | <p>The simplest way is to redirect stdout to a file:</p>
<pre><code>for i in range(10):
print str(i) + "," + str(i*2)
</code></pre>
<p>will output:</p>
<pre><code>0,0
1,2
2,4
3,6
4,8
5,10
6,12
7,14
8,16
9,18
</code></pre>
<p>if you run it as <code>python myprog.py > myout.txt</code> the result go to myout.txt </p>
| 0 | 2016-08-08T16:06:42Z | [
"python",
"writing"
] |
Dynamic dict value access with dot separated string | 38,832,563 | <p>I'm using Python 3.5.1</p>
<p>So what I am trying to do is pass in a dict a <em>dot separated string</em> representing the path to a key and a default value. I want to check for the keys existence and if it's not there , provide the default value. The problem with this is that the key I want to access could be nested in other dicts and I will not know until run time. So what I want to do is something like this:</p>
<pre><code>def replace_key(the_dict, dict_key, default_value):
if dict_key not in the_dict:
the_dict[dict_key] = default_value
return the_dict
some_dict = {'top_property': {'first_nested': {'second_nested': 'the value'}}}
key_to_replace = 'top_property.first_nested.second_nested'
default_value = 'replaced'
#this would return as {'top_property': {'first_nested': {'second_nested': 'replaced'}}}
replace_key(some_dict, key_to_replace, default_value)
</code></pre>
<p>What I'm looking for is a way to do this without having to do a split on '.' in the string and iterating over the possible keys as this could get messy. I would rather not have to use a third party library. I feel like there is clean built in Pythonic way to do this but I just can't find it. I've dug through the docs but to no avail. If anyone has any suggestion as to how I could do this it would be very much appreciated. Thanks!</p>
| 1 | 2016-08-08T15:01:12Z | 38,832,961 | <p>You could use recursivity:</p>
<pre><code>def replace_key(the_dict, dict_keys, default_value):
if dict_keys[0] in the_dict:
if len(dict_keys)==1:
the_dict[dict_keys[0]]=default_value
else:
replace_key(the_dict[dict_keys[0]], dict_keys[1:],default_value)
else:
raise Exception("wrong key")
some_dict = {'top_property': {'first_nested': {'second_nested': 'the value'}}}
key_to_replace = 'top_property.first_nested.second_nested'
default_value = 'replaced'
#this would return as {'top_property': {'first_nested': {'second_nested': 'replaced'}}}
replace_key(some_dict, key_to_replace.split("."), default_value)
</code></pre>
<p>But it still uses the split(). But maybe you consider it to be less messy?</p>
| 1 | 2016-08-08T15:19:40Z | [
"python",
"python-3.x"
] |
Get table name for field in database result in Python (PostgreSQL) | 38,832,646 | <p>I'm trying to get table name for field in result set that I got from database (Python, Postgres). There is a function in PHP to get table name for field, I used it and it works so I know it can be done (in PHP). I'm looking for similar function in Python.</p>
<p><a href="http://php.net/manual/en/function.pg-field-table.php" rel="nofollow">pg_field_table()</a> function in PHP gets results and field number and "returns the name of the table that field belongs to". That is exactly what I need, but in Python.</p>
<p>Simple exaple - create tables, insert rows, select data:</p>
<pre><code>CREATE TABLE table_a (
id INT,
name VARCHAR(10)
);
CREATE TABLE table_b (
id INT,
name VARCHAR(10)
);
INSERT INTO table_a (id, name) VALUES (1, 'hello');
INSERT INTO table_b (id, name) VALUES (1, 'world');
</code></pre>
<p>When using <code>psycopg2</code> or <code>sqlalchemy</code> I got right data and right field names but without information about table name.</p>
<pre><code>import psycopg2
query = '''
SELECT *
FROM table_a A
LEFT JOIN table_b B
ON A.id = B.id
'''
con = psycopg2.connect('dbname=testdb user=postgres password=postgres')
cur = con.cursor()
cur.execute(query)
data = cur.fetchall()
print('fields', [desc[0] for desc in cur.description])
print('data', data)
</code></pre>
<p>The example above prints field names. The output is:</p>
<pre><code>fields ['id', 'name', 'id', 'name']
data [(1, 'hello', 1, 'world')]
</code></pre>
<p>I know that there is <code>cursor.description</code>, but it does not contain table name, just the field name.</p>
<p>What I need - some way to retrieve table names for fields in result set when using raw SQL to query data.</p>
<p><strong>EDIT 1</strong>: I need to know if "hello" came from "table_a" or "table_b", both fields are named same ("name"). Without information about table name you can't tell in which table the value is.</p>
<p><strong>EDIT 2</strong>: I know that there are some workarounds like SQL aliases: <code>SELECT table_a.name AS name1, table_b.name AS name2</code> but I'm really asking how to retrieve table name from result set.</p>
<p><strong>EDIT 3</strong>: I'm looking for solution that allows me to write any raw SQL query, sometimes <code>SELECT *</code>, sometimes <code>SELECT A.id, B.id ...</code> and after executing that query I will get field names and table names for fields in the result set.</p>
| 2 | 2016-08-08T15:05:04Z | 38,834,445 | <p>It is necessary to query the <a href="https://www.postgresql.org/docs/current/static/catalog-pg-attribute.html" rel="nofollow"><code>pg_attribute</code> catalog</a> for the table qualified column names:</p>
<pre><code>query = '''
select
string_agg(format(
'%%1$s.%%2$s as "%%1$s.%%2$s"',
attrelid::regclass, attname
) , ', ')
from pg_attribute
where attrelid = any (%s::regclass[]) and attnum > 0 and not attisdropped
'''
cursor.execute(query, ([t for t in ('a','b')],))
select_list = cursor.fetchone()[0]
query = '''
select {}
from a left join b on a.id = b.id
'''.format(select_list)
print cursor.mogrify(query)
cursor.execute(query)
print [desc[0] for desc in cursor.description]
</code></pre>
<p>Output:</p>
<pre><code> select a.id as "a.id", a.name as "a.name", b.id as "b.id", b.name as "b.name"
from a left join b on a.id = b.id
['a.id', 'a.name', 'b.id', 'b.name']
</code></pre>
| 0 | 2016-08-08T16:39:38Z | [
"python",
"postgresql",
"psycopg2"
] |
Suppress warnings in Hachoir | 38,832,691 | <p>I'm using <a href="http://hachoir3.readthedocs.io/index.html" rel="nofollow">hachior-parser</a> to grab the duration of a large set of video files. (I'm resetting the "Last modified" date based on the file's timestamp, plus its duration.) I'm using code adapted from <a href="http://stackoverflow.com/questions/17185348/how-to-get-avi-files-length">this question</a>.</p>
<p>The problem I'm running into is that hachior reports four warnings for each file, and this is cluttering up my output. I still get my duration from the file, so I'd like to know how to suppress these warnings in the output, if possible.</p>
<p>Python isn't really my strong suit, so I'm not sure where to look and the documentation for hachior seems pretty sparse on the error reporting. I'd prefer not to resort to grepping the lines from the output of my script.</p>
<p><strong>Edit:</strong> Running <code>python -W ignore set_last_modified.py</code> results in the same <code>[warn]</code> lines being printed.</p>
<pre class="lang-none prettyprint-override"><code>[warn] [/headers/stream[2]/stream_fmt] Can't get field "stream_hdr" from /headers/stream[2]
[warn] [/headers/stream[2]/stream_fmt] [Autofix] Fix parser error: stop parser, add padding
[warn] [/headers/stream[3]/stream_fmt] Can't get field "stream_hdr" from /headers/stream[3]
[warn] [/headers/stream[3]/stream_fmt] [Autofix] Fix parser error: stop parser, add padding
</code></pre>
| 0 | 2016-08-08T15:06:54Z | 38,832,806 | <p>You can use the <a href="https://docs.python.org/2/using/cmdline.html#cmdoption-W" rel="nofollow"><code>-W</code></a> option to suppress warnings in python. </p>
<pre><code>python -W ignore my_file.py
</code></pre>
<p>Edit: since you've already tried the above, you could try the following. </p>
<pre><code>import warnings
# add the following before you call the function that gives warnings.
warnings.filterwarnings("ignore")
# run your function here
</code></pre>
| 0 | 2016-08-08T15:12:29Z | [
"python",
"hachoir-parser"
] |
Suppress warnings in Hachoir | 38,832,691 | <p>I'm using <a href="http://hachoir3.readthedocs.io/index.html" rel="nofollow">hachior-parser</a> to grab the duration of a large set of video files. (I'm resetting the "Last modified" date based on the file's timestamp, plus its duration.) I'm using code adapted from <a href="http://stackoverflow.com/questions/17185348/how-to-get-avi-files-length">this question</a>.</p>
<p>The problem I'm running into is that hachior reports four warnings for each file, and this is cluttering up my output. I still get my duration from the file, so I'd like to know how to suppress these warnings in the output, if possible.</p>
<p>Python isn't really my strong suit, so I'm not sure where to look and the documentation for hachior seems pretty sparse on the error reporting. I'd prefer not to resort to grepping the lines from the output of my script.</p>
<p><strong>Edit:</strong> Running <code>python -W ignore set_last_modified.py</code> results in the same <code>[warn]</code> lines being printed.</p>
<pre class="lang-none prettyprint-override"><code>[warn] [/headers/stream[2]/stream_fmt] Can't get field "stream_hdr" from /headers/stream[2]
[warn] [/headers/stream[2]/stream_fmt] [Autofix] Fix parser error: stop parser, add padding
[warn] [/headers/stream[3]/stream_fmt] Can't get field "stream_hdr" from /headers/stream[3]
[warn] [/headers/stream[3]/stream_fmt] [Autofix] Fix parser error: stop parser, add padding
</code></pre>
| 0 | 2016-08-08T15:06:54Z | 38,851,150 | <p>I found the solution by checking the issues page for the project on BitBucket.</p>
<p><a href="https://bitbucket.org/haypo/hachoir/issues/54/control-log-level-whith-the-python-api" rel="nofollow">https://bitbucket.org/haypo/hachoir/issues/54/control-log-level-whith-the-python-api</a></p>
<pre class="lang-py prettyprint-override"><code>from hachoir_core import config as HachoirConfig
HachoirConfig.quiet = True
</code></pre>
| 0 | 2016-08-09T12:45:41Z | [
"python",
"hachoir-parser"
] |
How to assign months to their numeric equivalents in Python / Pandas? | 38,832,968 | <p>Currently, I'm using the following for loop based on an if condition for each month to assign months to their numeric equivalents. It seems to be quite efficient in terms of runtime, but is too manual and ugly for my preferences.</p>
<p>How could this be better executed? I imagine it's possible to improve on it by simplifying/condensing the multiple if conditions somehow, as well as by using some sort of translator that is made for date conversions? Each of which would be preferable?</p>
<pre><code>#make numeric month
combined = combined.sort_values('month')
combined.index = range(len(combined))
combined['month_numeric'] = None
for i in combined['month'].unique():
first = combined['month'].searchsorted(i, side='left')
last = combined['month'].searchsorted(i, side='right')
first_num = list(first)[0] #gives first instance
last_num = list(last)[0] #gives last instance
if i == 'January':
combined['month_numeric'][first_num:last_num] = "01"
elif i == 'February':
combined['month_numeric'][first_num:last_num] = "02"
elif i == 'March':
combined['month_numeric'][first_num:last_num] = "03"
elif i == 'April':
combined['month_numeric'][first_num:last_num] = "04"
elif i == 'May':
combined['month_numeric'][first_num:last_num] = "05"
elif i == 'June':
combined['month_numeric'][first_num:last_num] = "06"
elif i == 'July':
combined['month_numeric'][first_num:last_num] = "07"
elif i == 'August':
combined['month_numeric'][first_num:last_num] = "08"
elif i == 'September':
combined['month_numeric'][first_num:last_num] = "09"
elif i == 'October':
combined['month_numeric'][first_num:last_num] = "10"
elif i == 'November':
combined['month_numeric'][first_num:last_num] = "11"
elif i == 'December':
combined['month_numeric'][first_num:last_num] = "12"
</code></pre>
| 1 | 2016-08-08T15:20:02Z | 38,833,040 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="nofollow"><code>month</code></a>, convert to string and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html" rel="nofollow"><code>zfill</code></a>:</p>
<pre><code>print (pd.to_datetime(df['month'], format='%B').dt.month.astype(str).str.zfill(2))
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({ 'month': ['January','February', 'December']})
print (df)
month
0 January
1 February
2 December
print (pd.to_datetime(df['month'], format='%B').dt.month.astype(str).str.zfill(2))
0 01
1 02
2 12
Name: month, dtype: object
</code></pre>
<p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> by dict <code>d</code>:</p>
<pre><code>d = {'January':'01','February':'02','December':'12'}
print (df['month'].map(d))
0 01
1 02
2 12
Name: month, dtype: object
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>df = pd.DataFrame({ 'month': ['January','February', 'December']})
print (df)
df = pd.concat([df]*1000).reset_index(drop=True)
print (pd.to_datetime(df['month'], format='%B').dt.month.astype(str).str.zfill(2))
print (df['month'].map({'January':'01','February':'02','December':'12'}))
In [200]: %timeit (pd.to_datetime(df['month'], format='%B').dt.month.astype(str).str.zfill(2))
100 loops, best of 3: 13.5 ms per loop
In [201]: %timeit (df['month'].map({'January':'01','February':'02','December':'12'}))
1000 loops, best of 3: 462 µs per loop
</code></pre>
| 4 | 2016-08-08T15:22:51Z | [
"python",
"datetime",
"pandas"
] |
How to assign months to their numeric equivalents in Python / Pandas? | 38,832,968 | <p>Currently, I'm using the following for loop based on an if condition for each month to assign months to their numeric equivalents. It seems to be quite efficient in terms of runtime, but is too manual and ugly for my preferences.</p>
<p>How could this be better executed? I imagine it's possible to improve on it by simplifying/condensing the multiple if conditions somehow, as well as by using some sort of translator that is made for date conversions? Each of which would be preferable?</p>
<pre><code>#make numeric month
combined = combined.sort_values('month')
combined.index = range(len(combined))
combined['month_numeric'] = None
for i in combined['month'].unique():
first = combined['month'].searchsorted(i, side='left')
last = combined['month'].searchsorted(i, side='right')
first_num = list(first)[0] #gives first instance
last_num = list(last)[0] #gives last instance
if i == 'January':
combined['month_numeric'][first_num:last_num] = "01"
elif i == 'February':
combined['month_numeric'][first_num:last_num] = "02"
elif i == 'March':
combined['month_numeric'][first_num:last_num] = "03"
elif i == 'April':
combined['month_numeric'][first_num:last_num] = "04"
elif i == 'May':
combined['month_numeric'][first_num:last_num] = "05"
elif i == 'June':
combined['month_numeric'][first_num:last_num] = "06"
elif i == 'July':
combined['month_numeric'][first_num:last_num] = "07"
elif i == 'August':
combined['month_numeric'][first_num:last_num] = "08"
elif i == 'September':
combined['month_numeric'][first_num:last_num] = "09"
elif i == 'October':
combined['month_numeric'][first_num:last_num] = "10"
elif i == 'November':
combined['month_numeric'][first_num:last_num] = "11"
elif i == 'December':
combined['month_numeric'][first_num:last_num] = "12"
</code></pre>
| 1 | 2016-08-08T15:20:02Z | 38,833,202 | <p>You can use a map:</p>
<pre><code>month2int = {"January":1, "February":2, ...}
combined["month_numeric"] = combined["month"].map(month2int)
</code></pre>
| 1 | 2016-08-08T15:30:36Z | [
"python",
"datetime",
"pandas"
] |
How can I remove all non-alphanumeric characters from a string, except for '#', with regex? | 38,833,054 | <p>I currently have this line <code>address = re.sub('[^A-Za-z0-9]+', ' ', address).lstrip()</code> which will remove all special characters from my string <code>address</code>. How can I modify this line to keep <code>#</code>?</p>
| 1 | 2016-08-08T15:23:26Z | 38,833,139 | <p>In order to avoid removing the hash symbol, you need to add it into the <a href="http://www.regular-expressions.info/charclass.html#negated" rel="nofollow">negated character class</a>:</p>
<pre><code>r'[^A-Za-z0-9#]+'
^
</code></pre>
<p>See the <a href="https://regex101.com/r/xP1yL8/1" rel="nofollow">regex demo</a></p>
| 4 | 2016-08-08T15:28:14Z | [
"python",
"regex"
] |
Ruffus pipeline with internal inputs | 38,833,119 | <p>I'd like to create a pipeline with the Ruffus package for Python and I am struggling with its simplest concepts. Two tasks should be executed one after the other. The second task depends on output of the first task. In Ruffus documentation everything is designed for import/export from/to external files. I'd like to handle internal data types like dictionaries.</p>
<p>The problem is that @follows doesn't take inputs and @transform doesn't take dicts. Am I missing something?</p>
<pre><code>def task1():
# generate dict
properties = {'status': 'original'}
return properties
@follows(task1)
def task2(properties):
# update dict
properties['status'] = 'updated'
return properties
</code></pre>
<p>Eventually the pipeline should combine a set of functions in a class that update the class object on the go.</p>
| 0 | 2016-08-08T15:26:56Z | 38,849,678 | <p>I suggest you only use the Ruffus decorators when there are input/output <em>files</em>. For example, if <code>task1</code> generates <code>file1.txt</code> and this is the input for <code>task2</code>, which generates <code>file2.txt</code> then you could write a pipeline as follows:</p>
<pre><code>@originate("file1.txt")
def task1(output):
out_file = open(output,"w")
# write stuff to out_file
@follows(task1)
@transform(task1, suffix("1.txt"),"2.txt")
def task2(input,output):
in_file = open(input,"r")
# read in in_file and do stuff
out_file = open(output,"w")
# write stuff to out_file
</code></pre>
<p>If you just want to take a dictionary as an input, you don't need Ruffus, you can just call <code>task1</code> in <code>task2</code>:</p>
<pre><code>def task1():
properties = {'status': 'original'}
return properties
def task2():
properties = task1()
properties['status'] = 'updated'
return properties
</code></pre>
| 0 | 2016-08-09T11:38:20Z | [
"python",
"cluster-computing",
"distributed-computing",
"pipeline"
] |
Search for a part of a tuple in a list of tuples | 38,833,275 | <p>I am working on a sudoku solver in python. The coordinates of the boxes are given by this code:</p>
<pre><code>for row in range(1, 10):
for column in range(1,10):
boxes.append((row, column))
</code></pre>
<p>Later, I have a list of tuples in the format of (row, column, box, number). I need to organize them so that they are in the order of the first list. Both are the same length, so I though I could make a new list by finding each (row, column) pair in the larger list. In other words, for the item (1, 1), I want to find a tuple in the other list where item 0 is '1' and item 1 is '1'.</p>
<p>How can I do this?</p>
| 0 | 2016-08-08T15:34:30Z | 38,833,438 | <p>I believe this should work for finding the (row, column) pair:</p>
<pre><code>entry = [e for e in tuple_list if (e[0] == row and e[1] == column)][0]
</code></pre>
<p>You essentially end up with a list of all entries <code>e</code> that match the (1, 1) pattern and then get the first of these using <code>[0]</code>.</p>
<p>Use this in a loop to find each one individually:</p>
<pre><code>sorted_tuple_list = []
for row in range(1, 10):
for column in range(1,10):
entry = [e for e in tuple_list if (e[0] == row and e[1] == column)][0]
sorted_tuple_list.append(entry)
</code></pre>
| 0 | 2016-08-08T15:42:37Z | [
"python",
"list",
"tuples"
] |
RabbitMQ: Consuming only one message at a time from multiple queues | 38,833,309 | <p>I'm trying to stay connected to multiple queues in RabbitMQ. Each time I pop a new message from one of these queue, I'd like to spawn an external process.</p>
<p>This process will take some time to process the message, and I don't want to start processing another message from that specific queue until the one I popped earlier is completed. If possible, I wouldn't want to keep a process/thread around just to wait on the external process to complete and ack the server. Ideally, I would like to ack in this external process, maybe passing some identifier so that it can connect to RabbitMQ and ack the message.</p>
<p>Is it possible to design this system with RabbitMQ? I'm using Python and Pika, if this is relevant to the answer.</p>
<p>Thanks!</p>
| 0 | 2016-08-08T15:36:31Z | 38,833,846 | <p>RabbitMQ can do this.</p>
<p>You only want to read from the queue when you're ready - so spin up a thread that can spawn the external process and watch it, then fetch the next message from the queue when the process is done. You can then have mulitiple threads running in parallel to manage multiple queues.</p>
<p>I'm not sure what you want an ack for? Are you trying to stop RabbitMQ from adding new elements to that queue if it gets too full (because its elements are being processed too slowly/not at all)? There might be a way to do this when you add messages to the queues - before adding an item, check to make sure that the number of messages already in that queue is not "much greater than" the average across all queues?</p>
| 0 | 2016-08-08T16:04:44Z | [
"python",
"rabbitmq",
"amqp",
"pika"
] |
Merge dataframes on nearest datetime / timestamp | 38,833,362 | <p>I have two data frames as follows:</p>
<pre><code>A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["06/22/2014","07/02/2014","01/01/2015","01/01/1991","08/02/1999"]})
B = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["02/15/2015","06/30/2014","07/02/1999","10/05/1990","06/24/2014"], "value": ["3","5","1","7","8"] })
</code></pre>
<p>Which look like the following:</p>
<pre><code>>>> A
ID date
0 A 2014-06-22
1 A 2014-07-02
2 C 2015-01-01
3 B 1991-01-01
4 B 1999-08-02
>>> B
ID date value
0 A 2015-02-15 3
1 A 2014-06-30 5
2 C 1999-07-02 1
3 B 1990-10-05 7
4 B 2014-06-24 8
</code></pre>
<p>I want to merge A with the values of B using the nearest date. In this example, none of the dates match, but it could the the case that some do.</p>
<p>The output should be something like this:</p>
<pre><code>>>> C
ID date value
0 A 06/22/2014 8
1 A 07/02/2014 5
2 C 01/01/2015 3
3 B 01/01/1991 7
4 B 08/02/1999 1
</code></pre>
<p>It seems to me that there should be a native function in pandas that would allow this. </p>
<p>Note: as similar question has been asked here
<a href="http://stackoverflow.com/questions/21201618/pandas-merge-match-the-nearest-time-stamp-the-series-of-timestamps">pandas.merge: match the nearest time stamp >= the series of timestamps</a></p>
| 0 | 2016-08-08T15:39:15Z | 38,833,547 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> with <code>method='nearest'</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p>
<pre><code>A['date'] = pd.to_datetime(A.date)
B['date'] = pd.to_datetime(B.date)
A.sort_values('date', inplace=True)
B.sort_values('date', inplace=True)
B1 = B.set_index('date').reindex(A.set_index('date').index, method='nearest').reset_index()
print (B1)
print (pd.merge(A,B1, on='date'))
ID_x date ID_y value
0 B 1991-01-01 B 7
1 B 1999-08-02 C 1
2 A 2014-06-22 B 8
3 A 2014-07-02 A 5
4 C 2015-01-01 A 3
</code></pre>
<p>You can also add parameter <code>suffixes</code>:</p>
<pre><code>print (pd.merge(A,B1, on='date', suffixes=('_', '')))
ID_ date ID value
0 B 1991-01-01 B 7
1 B 1999-08-02 C 1
2 A 2014-06-22 B 8
3 A 2014-07-02 A 5
4 C 2015-01-01 A 3
</code></pre>
| 1 | 2016-08-08T15:48:26Z | [
"python",
"pandas"
] |
dataframe append not visible out of function scope | 38,833,433 | <p>According to my understanding of python, mutable references to data can be modified within a function scope and reflect the change outside. However the behavior below confuses me:</p>
<p>1) Consider a list:</p>
<pre><code>my_list = []
def checklistappend( list ):
list.append( 1 )
checklistappend( my_list )
print ( my_list )
</code></pre>
<p>As expected the variable my_list = [1]</p>
<p>2) However consider the following scenario with a dataframe:</p>
<pre><code>my_df = pd.DataFrame(columns=['A'])
def checkdfappend ( df ):
df.append( [1] )
checkdfappend( my_df )
print( my_df )
</code></pre>
<p>In this case the result of my_df is still an empty data frame with columns 'A' which is non-intuitive and the only explaination I can come up with is that the dataframe append method internally assigns to a new variable which is the behavior I would not expect.</p>
<p>I am using python 2.7.2 with pandas 0.13.1 , changing either of which is not in my control.</p>
<p>Is there another way to achieve the same objective without making so many copies ?</p>
| 0 | 2016-08-08T15:42:32Z | 38,833,709 | <p>You need to assign the output back to <code>df</code>.</p>
<pre><code>df = df.append([1])
</code></pre>
| 0 | 2016-08-08T15:57:49Z | [
"python",
"pandas",
"pass-by-reference"
] |
Python Scrapy Spider: Inconsistent results | 38,833,506 | <p>I would love to know what you guys think about this please. I have researched for a few days now and I can't seem to find where I am going wrong. Any help will be highly appreciated.</p>
<p>I want to systematically crawl this url: <a href="https://studyacer.com/latest/" rel="nofollow">Question site</a> using the pagination to crawl the rest of the pages.</p>
<p>My current code: </p>
<pre><code>import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import Selector
from scrapy.spiders import CrawlSpider, Rule
from acer.items import AcerItem
class AcercrawlerSpider(CrawlSpider):
name = 'acercrawler'
allowed_domains = ['studyacer.com']
start_urls = ['http://www.studyacer.com/latest']
rules = (
Rule(LinkExtractor(), callback='parse_item', follow=True),
)
def parse_item(self, response):
questions= Selector(response).xpath('//td[@class="word-break"]/a/@href').extract()
for question in questions:
item= AcerItem()
item['title']= question.xpath('//h1/text()').extract()
item['body']= Selector(response).xpath('//div[@class="row-fluid"][2]//p/text()').extract()
yield item
</code></pre>
<p>When I ran the spider it doesn't throw any errors but instead outputs inconsistent results. Sometimes scraping an article page twice. I am thinking it might be something to do with the selectors I have used but I can't narrow it any further. Any help with this please?</p>
| 0 | 2016-08-08T15:46:17Z | 38,834,852 | <p>kevin; I had a similar but slightly different problem earlier today, where my crawlspider was visiting unwanted pages. Someone responded to my question with the suggestion of checking the linkextractor as you suggested here : <a href="http://doc.scrapy.org/en/latest/topics/link-extractors.html" rel="nofollow">http://doc.scrapy.org/en/latest/topics/link-extractors.html</a></p>
<pre><code>class scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor(allow=(), deny=(), allow_domains=(), deny_domains=(), deny_extensions=None, restrict_xpaths=(), restrict_css=(), tags=('a', 'area'), attrs=('href', ), canonicalize=True, unique=True, process_value=None)
</code></pre>
<p>I ended up reviewing my allow / deny components to focus the crawler on to specific subsets of pages. You can specify using regex to express the relevant substrings of the links to allow (include) or deny (exclude). I tested the expressions using <a href="http://www.regexpal.com/" rel="nofollow">http://www.regexpal.com/</a></p>
<p>I found this approach was sufficient to prevent duplicates, but if you're still seeing them, I also found this article I was looking at earlier in the day on how to prevent duplicates, although I have to say I didn't have to implement this fix:</p>
<p><a href="http://stackoverflow.com/questions/17660552/avoid-duplicate-url-crawling">Avoid Duplicate URL Crawling</a></p>
<p><a href="http://stackoverflow.com/a/21344753/6582364">http://stackoverflow.com/a/21344753/6582364</a></p>
| 0 | 2016-08-08T17:04:09Z | [
"python",
"css-selectors",
"scrapy"
] |
Match dictionary with list (Python) | 38,833,527 | <p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p>
<pre><code>dictionary = {
"object" : 'hat',
"animal" : 'cat',
"human" : 'steve'
}
list_of_things = ["steve", "tom", "cat"]
for categories,things in dictionary.iteritems():
for stuff in list_of_things:
if stuff in things:
print categories
if stuff not in things:
print "dump as usual"
</code></pre>
<p>Currently the output looks like this:</p>
<pre><code>dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal
</code></pre>
<p>But I want the output to look like this: </p>
<pre><code>human
dump as usual
animal
</code></pre>
<p>I don't want my list to print everything it iterates through in the dictionary. I only want it to print terms that match. How would I do this? </p>
| 1 | 2016-08-08T15:47:25Z | 38,833,578 | <p>You could use a boolean inside the inner <code>for</code> loop, which changes from False (category not found) to True (category was found), and then only print the <code>categories</code> at the <em>end</em> of the <code>for</code> loop <code>if boolean = False:</code></p>
<pre><code>isMatchFound = False
for categories, things in dictionary.iteritems():
isMatchFound = False
for stuff in list_of_things:
if stuff in things:
isMatchFound = True
print stuff
if isMatchFound == False:
print("dump as usual")
</code></pre>
| 1 | 2016-08-08T15:50:49Z | [
"python",
"dictionary"
] |
Match dictionary with list (Python) | 38,833,527 | <p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p>
<pre><code>dictionary = {
"object" : 'hat',
"animal" : 'cat',
"human" : 'steve'
}
list_of_things = ["steve", "tom", "cat"]
for categories,things in dictionary.iteritems():
for stuff in list_of_things:
if stuff in things:
print categories
if stuff not in things:
print "dump as usual"
</code></pre>
<p>Currently the output looks like this:</p>
<pre><code>dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal
</code></pre>
<p>But I want the output to look like this: </p>
<pre><code>human
dump as usual
animal
</code></pre>
<p>I don't want my list to print everything it iterates through in the dictionary. I only want it to print terms that match. How would I do this? </p>
| 1 | 2016-08-08T15:47:25Z | 38,833,669 | <p>Depending on how much your actual data look like your example, you could do</p>
<pre><code>category_thing= {
"object" : 'hat',
"animal" : 'cat',
"human" : 'steve'
}
list_of_things = ["steve", "tom", "cat"]
thingset=set(list_of_things) # just for speedup
for category,thing in category_thing.iteritems():
if thing in thingset:
print category
else:
print "dump as usual"
</code></pre>
<p>or if your mapping really is as simple as in your example you can do</p>
<pre><code>category_thing= {
"object" : 'hat',
"animal" : 'cat',
"human" : 'steve'
}
thing_category=dict((t,c) for c,t in category_thing.items()) # reverse the dict - if you have duplicate values (things), you should not do this
list_of_things = ["steve", "tom", "cat"]
for stuff in list_of_things:
msg=thing_category.get(stuff,"dump as usual")
print msg
</code></pre>
| 1 | 2016-08-08T15:55:47Z | [
"python",
"dictionary"
] |
Match dictionary with list (Python) | 38,833,527 | <p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p>
<pre><code>dictionary = {
"object" : 'hat',
"animal" : 'cat',
"human" : 'steve'
}
list_of_things = ["steve", "tom", "cat"]
for categories,things in dictionary.iteritems():
for stuff in list_of_things:
if stuff in things:
print categories
if stuff not in things:
print "dump as usual"
</code></pre>
<p>Currently the output looks like this:</p>
<pre><code>dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal
</code></pre>
<p>But I want the output to look like this: </p>
<pre><code>human
dump as usual
animal
</code></pre>
<p>I don't want my list to print everything it iterates through in the dictionary. I only want it to print terms that match. How would I do this? </p>
| 1 | 2016-08-08T15:47:25Z | 38,833,814 | <p>Since you want only 3 lines in output, your for-loops should be re-ordered.</p>
<pre><code>for stuff in list_of_things:
print_val = None
for categories,things in dictionary.iteritems():
if stuff in things:
print_val=categories
if print_val is None:
print_val="dump as usual"
print print_val
</code></pre>
| 0 | 2016-08-08T16:03:30Z | [
"python",
"dictionary"
] |
Match dictionary with list (Python) | 38,833,527 | <p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p>
<pre><code>dictionary = {
"object" : 'hat',
"animal" : 'cat',
"human" : 'steve'
}
list_of_things = ["steve", "tom", "cat"]
for categories,things in dictionary.iteritems():
for stuff in list_of_things:
if stuff in things:
print categories
if stuff not in things:
print "dump as usual"
</code></pre>
<p>Currently the output looks like this:</p>
<pre><code>dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal
</code></pre>
<p>But I want the output to look like this: </p>
<pre><code>human
dump as usual
animal
</code></pre>
<p>I don't want my list to print everything it iterates through in the dictionary. I only want it to print terms that match. How would I do this? </p>
| 1 | 2016-08-08T15:47:25Z | 38,834,795 | <p>First of all, your dictionary is poorly structured; it seems to have its keys and values swapped. By using the categories as keys, you can only have one object per category, which is probably not what you want. It also means that you have to read every entry in the dictionary in order to look up an item, which is generally a bad sign. The fix for this is simple: put the item on the left of the colon, and the category on the right. You can then use the 'in' operator to easily search the dictionary.</p>
<p>As far as the question you are directly asking, you should be looping over the list_of_things first, checking each against the dictionary, then printing the result. This will print exactly one thing per item in the list.</p>
<pre><code>dictionary = {
'hat' : 'object',
'cat' : 'animal',
'steve' : 'human'
}
list_of_things = ['steve', 'tom', 'cat']
for thing in list_of_things:
if thing in dictionary:
print dictionary[thing]
else:
print "dump as usual"
</code></pre>
<p>This outputs:</p>
<pre><code>human
dump as usual
animal
</code></pre>
| 1 | 2016-08-08T17:01:01Z | [
"python",
"dictionary"
] |
OSError: [Errno 8] Exec format error selenium | 38,833,589 | <p>Trying to learn how to use selenium, I managed to overcome first error which involved chrome driver not being in the path name but it has thrown up another error. </p>
<pre><code> from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('/Users/williamneal/Scratch/Titanic/chromedriver')
driver.get("http://www.bbc.com")
</code></pre>
<p>The error:
Traceback (most recent call last):</p>
<pre><code> File "<ipython-input-1-84256e62b8db>", line 5, in <module>
driver = webdriver.Chrome('/Users/williamneal/Scratch/Titanic/chromedriver')
File "/Users/williamneal/anaconda/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/Users/williamneal/anaconda/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 64, in start
stdout=self.log_file, stderr=self.log_file)
File "/Users/williamneal/anaconda/lib/python3.5/subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "/Users/williamneal/anaconda/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
OSError: [Errno 8] Exec format error
</code></pre>
<p>There is a potential solution <a href="http://stackoverflow.com/questions/36141032/python-selenium-chromedriver-oserror-errno-8-exec-format-error">here</a>, which involves installing Chrome Drivers via Home Brew but that option is not available to me. </p>
<p>Any ideas?</p>
| 1 | 2016-08-08T15:51:47Z | 38,836,361 | <p>Looks like this is complaining about the format of chromedriver binary.
It might be because of platform and chromedriver format mismatch. For example windows requires chromedriver.exe while there are different formats for linux and mac.</p>
<p>If you don't want to install through package manager, just download chromedriver from <a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/downloads</a></p>
<p>Note : Choose file as per your os</p>
<p>Then place it anywhere on the os and pass that path as an argument. You can also set webdriver.chrome.driver environment variable if you don't want to pass the location every time.</p>
| 0 | 2016-08-08T18:44:12Z | [
"python",
"selenium"
] |
Python program to check matching of simple parentheses | 38,833,819 | <p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p>
<p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</p>
<pre><code>def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
</code></pre>
<p>The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.</p>
<p>Thanks for your time!</p>
| 3 | 2016-08-08T16:03:36Z | 38,834,005 | <p>A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that <code>matched(")(")</code> will return <code>False</code>.</p>
<pre><code>def matched(str):
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0
</code></pre>
| 5 | 2016-08-08T16:13:37Z | [
"python"
] |
Python program to check matching of simple parentheses | 38,833,819 | <p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p>
<p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</p>
<pre><code>def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
</code></pre>
<p>The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.</p>
<p>Thanks for your time!</p>
| 3 | 2016-08-08T16:03:36Z | 38,834,134 | <p>Most blatant error done by you is:</p>
<pre><code> if l == ")":
clo = clo + [")"]
else:
return(ope, clo) # here
</code></pre>
<p>By using return, you exit from function when first char not equal to "(" or ")" is encountered. Also some indentation is off.</p>
<p>Minimal change which allows your code to run (although it <strong>won't</strong> give correct answers for all possible input strings) is:</p>
<pre><code>def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
elif l == ")":
clo = clo + [")"]
if len(ope)==len(clo):
return True
else:
return False
</code></pre>
| 3 | 2016-08-08T16:21:27Z | [
"python"
] |
Python program to check matching of simple parentheses | 38,833,819 | <p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p>
<p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</p>
<pre><code>def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
</code></pre>
<p>The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.</p>
<p>Thanks for your time!</p>
| 3 | 2016-08-08T16:03:36Z | 38,834,144 | <p>The problem with your approach is that you don't consider the order. Following line would pass: <code>))) (((</code>.
I'd suggest to keep the count of open and closed parenthesis:</p>
<ul>
<li><code>counter</code> starts from 0</li>
<li>every <code>(</code> symbol increment counter</li>
<li>every <code>)</code> symbol decrements counter</li>
<li>if at any moment counter is negative it is an error</li>
<li>if at the end of the line counter is 0 - string has matching parenthesis </li>
</ul>
| 1 | 2016-08-08T16:22:06Z | [
"python"
] |
Python program to check matching of simple parentheses | 38,833,819 | <p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p>
<p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</p>
<pre><code>def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
</code></pre>
<p>The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.</p>
<p>Thanks for your time!</p>
| 3 | 2016-08-08T16:03:36Z | 38,834,249 | <p>This checks whether parentheses are properly matched, not just whether there is an equal number of opening and closing parentheses. We use a <code>list</code> as a stack and push onto it when we encounter opening parentheses and pop from it when we encounter closing parentheses.</p>
<p>The main problem with your solution is that it only <em>counts</em> the number of parentheses but does not <em>match</em> them. One way of keeping track of the current depth of nesting is by pushing opening parentheses onto a stack and popping them from the stack when we encounter a closing parenthesis.</p>
<pre><code>def do_parentheses_match(input_string):
s = []
balanced = True
index = 0
while index < len(input_string) and balanced:
token = input_string[index]
if token == "(":
s.append(token)
elif token == ")":
if len(s) == 0:
balanced = False
else:
s.pop()
index += 1
return balanced and len(s) == 0
</code></pre>
| 1 | 2016-08-08T16:28:34Z | [
"python"
] |
Python program to check matching of simple parentheses | 38,833,819 | <p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p>
<p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</p>
<pre><code>def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
</code></pre>
<p>The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.</p>
<p>Thanks for your time!</p>
| 3 | 2016-08-08T16:03:36Z | 38,834,251 | <p>this code works fine </p>
<pre><code>def matched(s):
p_list=[]
for i in range(0,len(s)):
if s[i] =='(':
p_list.append('(')
elif s[i] ==')' :
if not p_list:
return False
else:
del p_list[-1]
if not p_list:
return True
else:
return False
</code></pre>
| 1 | 2016-08-08T16:28:43Z | [
"python"
] |
Python - Pass a range of float (without step) as an argument of a function | 38,833,828 | <p>I created a function and I would like to be able to call it with a set of keyworded-parameters that I call <code>**criterias</code>:</p>
<pre><code>def actionBasedOnParameters(**criterias):
# my code
</code></pre>
<p>Inside this set of parameters one of them will be called 'SumInc' and I would like to pass a range to it. The range will be of the form of [1:15] or [1:] or [:15]. Something that will essentially let me check whether a variable in my code is greater than a certain boundary or lower than another boundary or both.
In the same way, as these lines of codes do:</p>
<pre><code>In [188]: 1 <= 15.98877 <= 15
Out[188]: False
In [188]: 1 <= 15.98877
Out[188]: True
In [188]: 15.98877 <= 15
Out[188]: False
</code></pre>
<p>But I am looking for a neater way to pass both boundaries without having to create a parameter for each and many if conditions to get things done.</p>
<p>Something that would look like this:</p>
<pre><code>In [189]: criterias = dict(SumInc=[:15])
def actionBasedOnParameters(**criterias):
if criterias['SumInc'] is not None:
if my_variable is in criterias['SumInc']:
#action1
else:
#action2
</code></pre>
<p>Is there something of this kind existing?</p>
<p>Thanks for your tips,</p>
| 0 | 2016-08-08T16:03:59Z | 38,836,398 | <p>Something like this?</p>
<pre><code>criterias = dict(SumInc=(1,15))
def actionBasedOnParameters(**criterias):
if 'SumInc' in criterias:
lower, upper = criterias['SumInc']
if lower <= my_variable <= upper:
#action1
else:
#action2
infinity = float('inf')
actionBasedOnParameters(SumInc=(1, 15))
actionBasedOnParameters(SumInc=(-infinity, 15))
actionBasedOnParameters(SumInc=(1, infinity))
</code></pre>
<p>Also, you'd better use <code>'SumInc' in criterias</code> instead of <code>criterias['SumInc'] is not None</code> because in your case if there is no <code>'SumInc'</code> it will raise you a <code>KeyError</code> exception.</p>
| 2 | 2016-08-08T18:46:19Z | [
"python",
"function",
"arguments",
"range",
"keyword-argument"
] |
pandas: sum of each column results a NaN value? | 38,833,837 | <p>I have a dataframe in pandas as below. I am trying to add a row with row-name ="Total", which is the sum of each column. I am using the following code : <strong>df.loc["Total"] = df.sum(axis =1)</strong></p>
<p>I am getting NaN as a sum of each column. Any idea why and how to solve it ?</p>
<p><a href="http://i.stack.imgur.com/9QXbb.jpg" rel="nofollow">dataframe with "Total" row</a></p>
| -3 | 2016-08-08T16:04:29Z | 38,833,949 | <p>Use:</p>
<pre><code>df.loc["Total"] = df.sum()
</code></pre>
<p>Or if need convert first string values of columns to float:</p>
<pre><code>df.loc["Total"] = df.astype(float).sum()
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
df.loc["Total"] = df.sum()
print (df)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
Total 6 15 24 9 14 14
</code></pre>
| 0 | 2016-08-08T16:10:55Z | [
"python",
"pandas",
"sum",
"row"
] |
How can I add items to Context.data without loosing it once I exit the inner_function | 38,833,859 | <p>I am having some trouble with Python Closures, hoping someone here could help. Below is my code.</p>
<pre><code>import time
from multiprocessing import Process
class Context(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.data = []
context = Context(1, 2)
def test(text):
def inner_function():
for i in range(0, 10):
text.data.append(i)
time.sleep(1)
print(text.data.__len__())
thread = Process(target=inner_function)
thread.daemon = True
thread.start()
test(context)
time.sleep(12)
print("Final {0}".format(context.data.__len__()))
</code></pre>
<p>The output that I am seeing is</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
Final 0
</code></pre>
<p>I want Final to have a value of 10. I am using Python 2.7</p>
| 0 | 2016-08-08T16:05:21Z | 38,834,463 | <p>Your problem is not about closures but about <a href="https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">sharing data between processes</a> as in <code>thread</code> everything works as expected but you do not pass back your data to the main process. </p>
<p>You could return <code>context</code> explicity and maybe using <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply" rel="nofollow">Pool.apply</a> or apply_async is the right thing for this.</p>
| 1 | 2016-08-08T16:40:42Z | [
"python",
"python-2.7",
"closures"
] |
How to force Django to delete objects using multiple inheritance | 38,833,866 | <p>I have an object model as follows:</p>
<pre><code>class Corporation(models.Model):
corp_id = models.AutoField(primary_key=True)
original_name = models.CharField(max_length=1000, blank=True, null=True)
address = models.ManyToManyField(Address, related_name='corp_address')
class Person(models.Model):
person_id = models.AutoField(primary_key=True)
person_address = models.ManyToManyField(Address, related_name='person_address')
class Address(models.Model):
address1 = models.CharField(max_length=500, blank=True, null=True)
address2 = models.CharField(max_length=500, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
state = models.CharField(max_length=100, blank=True, null=True)
zipcode = models.CharField(max_length=20, blank=True, null=True)
country = models.CharField(max_length=100, blank=True, null=True)
class Committee(Corporation):
name = models.CharField(blank=True, max_length=200, null=True)
industry = models.CharField(blank=True, max_length=100, null=True)
</code></pre>
<p>When I create a Committee object, I create a Corporation and an Address object. A single Address object may have multiple Corporations pointing to it.</p>
<p>However, when I do Committee.objects.delete(), Django deletes the Committee object but not the related Corporation or Address object.</p>
<p>When I delete a Committee object, I want to delete the associated Address object if another object does not point to it. I also want to delete the associated Corporation object if another object does not point to it.</p>
<p>How can I do this conditional cascaded delete?</p>
| 1 | 2016-08-08T16:05:40Z | 38,833,974 | <p>Check out <a href="https://docs.djangoproject.com/ja/1.9/ref/models/fields/#module-django.db.models.fields.related" rel="nofollow">on_delete</a> set to cascade in django which will delete the associated records also . </p>
<p>In your models please add on_delete = models.CASCADE in this fashion:</p>
<pre><code> class Car(models.Model):
manufacturer = models.ForeignKey(
'Manufacturer', on_delete=models.CASCADE)
</code></pre>
<p>Here is a good <a href="http://stackoverflow.com/questions/3937194/django-cascade-deletion-in-manytomanyrelation">post</a> which explains models.CASCADE delete and ManyToMany relation on Django.</p>
| 1 | 2016-08-08T16:12:06Z | [
"python",
"django",
"multiple-inheritance"
] |
Write Custom Python-Based Gradient Function for an Operation? (without C++ Implementation) | 38,833,934 | <p>I'm trying to write a custom gradient function for 'my_op' which for the sake of the example contains just a call to tf.identity() (ideally, it could be any graph).</p>
<pre><code>import tensorflow as tf
from tensorflow.python.framework import function
def my_op_grad(x):
return [tf.sigmoid(x)]
@function.Defun(a=tf.float32, python_grad_func=my_op_grad)
def my_op(a):
return tf.identity(a)
a = tf.Variable(tf.constant([5., 4., 3., 2., 1.], dtype=tf.float32))
sess = tf.Session()
sess.run(tf.initialize_all_variables())
grad = tf.gradients(my_op(a), [a])[0]
result = sess.run(grad)
print(result)
sess.close()
</code></pre>
<p>Unfortunately I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "custom_op.py", line 19, in <module>
grad = tf.gradients(my_op(a), [a])[0]
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 528, in __call__
return call_function(self._definition, *args, **kwargs)
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 267, in call_function
compute_shapes=False)
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2285, in create_op
raise TypeError("Input #%d is not a tensor: %s" % (idx, a))
TypeError: Input #0 is not a tensor: <tensorflow.python.ops.variables.Variable object at 0x1080d2710>
</code></pre>
<p>I know that it is possible to create a custom C++ operation, but in my case I just need to write a custom gradient for a function which can be easily written in Python using standard TensorFlow operations, so I would like to avoid writing unnecessary C++ code.</p>
<p>Also, I'm using the upstream version of TensorFlow from GitHub.</p>
| 1 | 2016-08-08T16:10:13Z | 38,862,401 | <p>Note that python_grad_func needs the same interface as ops.RegisterGradient (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/function.py#L349" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/function.py#L349</a>). </p>
<p>Here is the modified code example:</p>
<pre><code>def my_op_grad(op, grad): ### instead of my_op_grad(x)
return tf.sigmoid(op.inputs[0])
@function.Defun(a=tf.float32, python_grad_func=my_op_grad)
def my_op(a):
return tf.identity(a)
def main(unused_argv):
a = tf.Variable(tf.constant([-5., 4., -3., 2., 1.], dtype=tf.float32))
sess = tf.Session()
sess.run(tf.initialize_all_variables())
a = tf.identity(a) #workaround for bug github.com/tensorflow/tensorflow/issues/3710
grad = tf.gradients(my_op(a), [a])[0]
result = sess.run(grad)
print(result)
sess.close()
</code></pre>
<p>Output:</p>
<pre><code>[ 0.00669286 0.98201376 0.04742587 0.88079709 0.7310586 ]
</code></pre>
| 1 | 2016-08-10T00:22:52Z | [
"python",
"tensorflow",
"gradient-descent"
] |
Write Custom Python-Based Gradient Function for an Operation? (without C++ Implementation) | 38,833,934 | <p>I'm trying to write a custom gradient function for 'my_op' which for the sake of the example contains just a call to tf.identity() (ideally, it could be any graph).</p>
<pre><code>import tensorflow as tf
from tensorflow.python.framework import function
def my_op_grad(x):
return [tf.sigmoid(x)]
@function.Defun(a=tf.float32, python_grad_func=my_op_grad)
def my_op(a):
return tf.identity(a)
a = tf.Variable(tf.constant([5., 4., 3., 2., 1.], dtype=tf.float32))
sess = tf.Session()
sess.run(tf.initialize_all_variables())
grad = tf.gradients(my_op(a), [a])[0]
result = sess.run(grad)
print(result)
sess.close()
</code></pre>
<p>Unfortunately I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "custom_op.py", line 19, in <module>
grad = tf.gradients(my_op(a), [a])[0]
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 528, in __call__
return call_function(self._definition, *args, **kwargs)
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 267, in call_function
compute_shapes=False)
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2285, in create_op
raise TypeError("Input #%d is not a tensor: %s" % (idx, a))
TypeError: Input #0 is not a tensor: <tensorflow.python.ops.variables.Variable object at 0x1080d2710>
</code></pre>
<p>I know that it is possible to create a custom C++ operation, but in my case I just need to write a custom gradient for a function which can be easily written in Python using standard TensorFlow operations, so I would like to avoid writing unnecessary C++ code.</p>
<p>Also, I'm using the upstream version of TensorFlow from GitHub.</p>
| 1 | 2016-08-08T16:10:13Z | 39,565,081 | <p>The following seems work fine. Do you have any reason prefering python_grad_func instead?</p>
<pre><code>@tf.function.Defun(tf.float32, tf.float32)
def bprop(x, dy):
return tf.sigmoid(x)
@tf.function.Defun(tf.float32, grad_func=bprop)
def fprop(x):
return x # identity
a = tf.Variable(tf.constant([-5., 4., -3., 2., 1.], dtype=tf.float32))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
a = tf.identity(a)
grad = tf.gradients(fprop(a), [a])
result = sess.run(grad)
print(result)
</code></pre>
| 0 | 2016-09-19T03:50:42Z | [
"python",
"tensorflow",
"gradient-descent"
] |
Compare only part of two of three items in triple | 38,833,937 | <p>I have a list that goes something like this, and new content is added in a loop.</p>
<pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
</code></pre>
<p>In the loop I want to add items like so:</p>
<pre><code>list.append(("strawberry", "b", 4))
</code></pre>
<p>however, this cannot occur if the first and second item in that sequence is already in the list together. For instance, the following list cannot be added to <code>list</code> because the first item already contains "banana" together with "a".</p>
<pre><code>("banana", "a", 5) # Should NOT be appended
("banana", "c", 6) # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
</code></pre>
<p>In a regular list we'd do something like the following to avoid duplicates:</p>
<pre><code>if not item in list:
list.append(item)
</code></pre>
<p>but note that my case does only involve partial duplicate, i.e. the first two items cannot be identical between sublists.</p>
<p>I am looking for a very efficient solution because the list can contain thousands of items.</p>
| 1 | 2016-08-08T16:10:21Z | 38,834,137 | <p>A time-efficient solution would be to keep a <code>set</code> with added items</p>
<pre><code>li = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
se= set(t[:2] for t in li)
add=[
("banana", "a", 5), # Should NOT be appended
("banana", "c", 6), # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
]
for t in add:
ct=t[:2]
if ct not in se:
li.append(t)
se.add(ct)
</code></pre>
<p>after that, <code>li</code> is <code>[('banana', 'a', 0), ('banana', 'b', 1), ('coconut', 'a', 2), ('banana', 'c', 6), ('strawberry', 'a', 7)]</code> </p>
| 0 | 2016-08-08T16:21:34Z | [
"python",
"list",
"duplicates",
"append"
] |
Compare only part of two of three items in triple | 38,833,937 | <p>I have a list that goes something like this, and new content is added in a loop.</p>
<pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
</code></pre>
<p>In the loop I want to add items like so:</p>
<pre><code>list.append(("strawberry", "b", 4))
</code></pre>
<p>however, this cannot occur if the first and second item in that sequence is already in the list together. For instance, the following list cannot be added to <code>list</code> because the first item already contains "banana" together with "a".</p>
<pre><code>("banana", "a", 5) # Should NOT be appended
("banana", "c", 6) # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
</code></pre>
<p>In a regular list we'd do something like the following to avoid duplicates:</p>
<pre><code>if not item in list:
list.append(item)
</code></pre>
<p>but note that my case does only involve partial duplicate, i.e. the first two items cannot be identical between sublists.</p>
<p>I am looking for a very efficient solution because the list can contain thousands of items.</p>
| 1 | 2016-08-08T16:10:21Z | 38,834,141 | <p>you may check the presence of an new item with</p>
<pre><code>#check for every item if newItem matches an Item in the list
if not any( True for item in list if newItem[:2]==item[:2] ):
# add your newItem
</code></pre>
| 1 | 2016-08-08T16:21:48Z | [
"python",
"list",
"duplicates",
"append"
] |
Compare only part of two of three items in triple | 38,833,937 | <p>I have a list that goes something like this, and new content is added in a loop.</p>
<pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
</code></pre>
<p>In the loop I want to add items like so:</p>
<pre><code>list.append(("strawberry", "b", 4))
</code></pre>
<p>however, this cannot occur if the first and second item in that sequence is already in the list together. For instance, the following list cannot be added to <code>list</code> because the first item already contains "banana" together with "a".</p>
<pre><code>("banana", "a", 5) # Should NOT be appended
("banana", "c", 6) # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
</code></pre>
<p>In a regular list we'd do something like the following to avoid duplicates:</p>
<pre><code>if not item in list:
list.append(item)
</code></pre>
<p>but note that my case does only involve partial duplicate, i.e. the first two items cannot be identical between sublists.</p>
<p>I am looking for a very efficient solution because the list can contain thousands of items.</p>
| 1 | 2016-08-08T16:10:21Z | 38,834,175 | <p>You can use tuples as keys in a dictionary:</p>
<pre><code>fruits = {
('banana', 'a'): 0,
('banana', 'b'): 1,
('coconut', 'a'): 2,
}
</code></pre>
<p>Then, you can just check if <code>(item[0], item[1])</code> is already in the dictionary:</p>
<pre><code>item = ('strawberry', 'b', 4)
if (item[0], item[1]) not in fruits:
fruits[item[0], item[1]] = item[2]
</code></pre>
<p>If you want to preserve order, you can use <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a> instead of the built-in dictionary.</p>
<p>This avoids using more memory to store a set of keys and is also efficient regarding lookup.</p>
| 1 | 2016-08-08T16:23:55Z | [
"python",
"list",
"duplicates",
"append"
] |
Compare only part of two of three items in triple | 38,833,937 | <p>I have a list that goes something like this, and new content is added in a loop.</p>
<pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
</code></pre>
<p>In the loop I want to add items like so:</p>
<pre><code>list.append(("strawberry", "b", 4))
</code></pre>
<p>however, this cannot occur if the first and second item in that sequence is already in the list together. For instance, the following list cannot be added to <code>list</code> because the first item already contains "banana" together with "a".</p>
<pre><code>("banana", "a", 5) # Should NOT be appended
("banana", "c", 6) # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
</code></pre>
<p>In a regular list we'd do something like the following to avoid duplicates:</p>
<pre><code>if not item in list:
list.append(item)
</code></pre>
<p>but note that my case does only involve partial duplicate, i.e. the first two items cannot be identical between sublists.</p>
<p>I am looking for a very efficient solution because the list can contain thousands of items.</p>
| 1 | 2016-08-08T16:10:21Z | 38,834,306 | <pre><code>data = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
items = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)]
for item in items:
if item[:2] not in map(lambda x: x[:2], data):
data.append(item)
</code></pre>
<p>Output:</p>
<pre><code> [('banana', 'a', 0),
('banana', 'b', 1),
('coconut', 'a', 2),
('banana', 'c', 6),
('strawberry', 'a', 7)]
</code></pre>
| 1 | 2016-08-08T16:31:20Z | [
"python",
"list",
"duplicates",
"append"
] |
Compare only part of two of three items in triple | 38,833,937 | <p>I have a list that goes something like this, and new content is added in a loop.</p>
<pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
</code></pre>
<p>In the loop I want to add items like so:</p>
<pre><code>list.append(("strawberry", "b", 4))
</code></pre>
<p>however, this cannot occur if the first and second item in that sequence is already in the list together. For instance, the following list cannot be added to <code>list</code> because the first item already contains "banana" together with "a".</p>
<pre><code>("banana", "a", 5) # Should NOT be appended
("banana", "c", 6) # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
</code></pre>
<p>In a regular list we'd do something like the following to avoid duplicates:</p>
<pre><code>if not item in list:
list.append(item)
</code></pre>
<p>but note that my case does only involve partial duplicate, i.e. the first two items cannot be identical between sublists.</p>
<p>I am looking for a very efficient solution because the list can contain thousands of items.</p>
| 1 | 2016-08-08T16:10:21Z | 38,834,467 | <p>I would highly recommend using a <em>dictionary</em> for this type of data coupling structure, along with <strong>O(1)</strong> look-up times, you'll also be implementing better design. However, you could do this with your current data structure using the following:</p>
<p><strong>Sample output:</strong></p>
<p><em>With current structure</em>: </p>
<pre><code>l = [ ("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2) ]
items_to_add = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)]
for item_to_add in items_to_add:
if not item_to_add[:2] in [i[:2] for i in l]:
l.append(item_to_add)
print l
>>> [('banana', 'a', 0), ('banana', 'b', 1), ('coconut', 'a', 2),
('banana', 'c', 6), ('strawberry', 'a', 7)]
</code></pre>
<p>Other wise, you can use a dictionary (<em>factor out your two first elements to be your key</em>):</p>
<p><em>With dictionary</em>:</p>
<pre><code>d = { ("banana", "a") : 0, ("banana", "b") : 1, ("coconut", "a") : 2 }
items_to_add = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)]
for item_to_add in items_to_add:
key = item_to_add[:2]
value = item_to_add[-1]
if not key in d:
d[key] = value
print d
>>> {('coconut', 'a'): 2, ('strawberry', 'a'): 7, ('banana', 'c'): 6,
('banana', 'a'): 0, ('banana', 'b'): 1}
</code></pre>
<p>A dictionary works very well in this scenario as you're trying to leverage properties of <strong>key/value</strong> data structure. Unique keys are ensured, and this will be the most efficient route as well. </p>
| 1 | 2016-08-08T16:40:59Z | [
"python",
"list",
"duplicates",
"append"
] |
Using Python to manipulate 31-bits | 38,833,978 | <p>I have a specification which outlines how instructions should be sent over serial.</p>
<p>Currently I am crafting the packets that will go over the connection.</p>
<p>One segment of the packet, requires a 32-bit (4 byte) binary number.
The first 31-bits are 'data' and the last bit is merely a flag.</p>
<p>So, The max decimal number that could fit in data is: 2147483647 (2^31). Data could never be bigger than this, Cool!</p>
<p>My problem, is how do I go about encoding the data to 31-bits binary, then setting the final bit to enable the flag?</p>
<p>Say my data is <code>7AAAAAAA</code> what is the desirable way of converting this to 31 bit binary then adding 1 or a 0 to the end?</p>
<p><strong>Edit - I'm Using Python 3.4</strong></p>
| 2 | 2016-08-08T16:12:16Z | 38,834,214 | <p>The only thing which comes to my mind is operation on strings</p>
<p>Say we have two variables:</p>
<pre><code>>>> data = '7AAAAAAA'
>>> flag = '1'
</code></pre>
<p>Convert the data hex to number</p>
<pre><code>>>> num = int(data, 16)
>>> num
2058005162
</code></pre>
<p>Convert the number to string binary representation:</p>
<pre><code>>>> bin_num = bin(num)
>>> bin_num
'0b1111010101010101010101010101010'
</code></pre>
<p>Append flag to the end</p>
<pre><code>>>> bin_num += flag
>>> bin_num
'0b11110101010101010101010101010101'
</code></pre>
<p>Evaluate string to get number and convert back to hex or whatever you need:</p>
<pre><code>>>> eval(bin_num)
4116010325
</code></pre>
<p><strong>#edit1</strong></p>
<p>In order to extend the value to 4-bytes you can use:</p>
<pre><code>>>> final_val = eval(bin_num)
>>> int.to_bytes(final_val, 4, 'big')
b'\xf5UUU'
</code></pre>
<p><strong>#edit2</strong></p>
<pre><code>def convert(data, flag):
with_flag = eval(bin(int(data, 16)) + flag)
return int.to_bytes(with_flag, 4, 'big')
def unconvert(byte_data):
bin_str = bin(int.from_bytes(byte_data, 'big'))
flag = bin_str[-1]
data = bin_str[:-1]
return (hex(eval(data)), flag)
</code></pre>
| 1 | 2016-08-08T16:26:28Z | [
"python",
"binary",
"hex",
"python-3.4",
"pyserial"
] |
Using Python to manipulate 31-bits | 38,833,978 | <p>I have a specification which outlines how instructions should be sent over serial.</p>
<p>Currently I am crafting the packets that will go over the connection.</p>
<p>One segment of the packet, requires a 32-bit (4 byte) binary number.
The first 31-bits are 'data' and the last bit is merely a flag.</p>
<p>So, The max decimal number that could fit in data is: 2147483647 (2^31). Data could never be bigger than this, Cool!</p>
<p>My problem, is how do I go about encoding the data to 31-bits binary, then setting the final bit to enable the flag?</p>
<p>Say my data is <code>7AAAAAAA</code> what is the desirable way of converting this to 31 bit binary then adding 1 or a 0 to the end?</p>
<p><strong>Edit - I'm Using Python 3.4</strong></p>
| 2 | 2016-08-08T16:12:16Z | 38,834,450 | <p>I think you can use binary shift to add your flag to a number:</p>
<pre><code>a = 0x7AAAAAAA # 2058005162 = 0b1111010101010101010101010101010
f = 1 # 1 = 0b1
packet = a + (f << 31) # a + 0b10000000000000000000000000000000
bin(packet) # 0b11111010101010101010101010101010
</code></pre>
<p>To unpack you can use mask and binary AND like this:</p>
<pre><code>mask = (1 << 31) - 1 # 2147483647 = 0b1111111111111111111111111111111
a = packet & mask # 2058005162 = 0b1111010101010101010101010101010
f = packet >> 31 # 1 = 0b1
</code></pre>
| 2 | 2016-08-08T16:39:53Z | [
"python",
"binary",
"hex",
"python-3.4",
"pyserial"
] |
Using Python to manipulate 31-bits | 38,833,978 | <p>I have a specification which outlines how instructions should be sent over serial.</p>
<p>Currently I am crafting the packets that will go over the connection.</p>
<p>One segment of the packet, requires a 32-bit (4 byte) binary number.
The first 31-bits are 'data' and the last bit is merely a flag.</p>
<p>So, The max decimal number that could fit in data is: 2147483647 (2^31). Data could never be bigger than this, Cool!</p>
<p>My problem, is how do I go about encoding the data to 31-bits binary, then setting the final bit to enable the flag?</p>
<p>Say my data is <code>7AAAAAAA</code> what is the desirable way of converting this to 31 bit binary then adding 1 or a 0 to the end?</p>
<p><strong>Edit - I'm Using Python 3.4</strong></p>
| 2 | 2016-08-08T16:12:16Z | 38,834,714 | <p>See if this works, similar to other answers but accounts for original bit length.</p>
<p>Define the final number of bits</p>
<pre><code>>>> bits = 16
</code></pre>
<p>Start with a bytes literal</p>
<pre><code>>>> a = b'10'
</code></pre>
<p>Convert to an <code>int</code></p>
<pre><code>>>> b = int(a, base = 16)
</code></pre>
<p>Shift left to the required bit length</p>
<pre><code>>>> shift = bits - b.bit_length()
>>> c = b << shift
</code></pre>
<p>Add the <em>flag</em></p>
<pre><code>>>> d = c | 1
>>>
>>> a
b'10'
>>> b
16
>>> c
32768
>>> d
32769
>>> bin(b)
'0b10000'
>>> bin(c)
'0b1000000000000000'
>>> bin(d)
'0b1000000000000001'
>>>
</code></pre>
| 0 | 2016-08-08T16:55:46Z | [
"python",
"binary",
"hex",
"python-3.4",
"pyserial"
] |
Use a.empty, a.bool(), a.item(), a.any() or a.all() | 38,834,028 | <pre><code>import random
import pandas as pd
heart_rate = [random.randrange(45,125) for _ in range(500)]
blood_pressure_systolic = [random.randrange(140,230) for _ in range(500)]
blood_pressure_dyastolic = [random.randrange(90,140) for _ in range(500)]
temperature = [random.randrange(34,42) for _ in range(500)]
respiratory_rate = [random.randrange(8,35) for _ in range(500)]
pulse_oximetry = [random.randrange(95,100) for _ in range(500)]
vitalsign = {'heart rate' : heart_rate,
'systolic blood pressure' : blood_pressure_systolic,
'dyastolic blood pressure' : blood_pressure_dyastolic,
'temperature' : temperature,
'respiratory rate' : respiratory_rate,
'pulse oximetry' : pulse_oximetry}
df = pd.DataFrame(vitalsign)
df.to_csv('vitalsign.csv')
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
df.loc[mask, "class"]
</code></pre>
<p>it seems to be that,</p>
<p>error that i am receiving : ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). how can i sort it out</p>
| 0 | 2016-08-08T16:14:54Z | 38,834,238 | <p>solution is easy:</p>
<p>replace</p>
<pre><code> mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
</code></pre>
<p>by </p>
<pre><code>mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
</code></pre>
| 0 | 2016-08-08T16:28:00Z | [
"python",
"pandas"
] |
Use a.empty, a.bool(), a.item(), a.any() or a.all() | 38,834,028 | <pre><code>import random
import pandas as pd
heart_rate = [random.randrange(45,125) for _ in range(500)]
blood_pressure_systolic = [random.randrange(140,230) for _ in range(500)]
blood_pressure_dyastolic = [random.randrange(90,140) for _ in range(500)]
temperature = [random.randrange(34,42) for _ in range(500)]
respiratory_rate = [random.randrange(8,35) for _ in range(500)]
pulse_oximetry = [random.randrange(95,100) for _ in range(500)]
vitalsign = {'heart rate' : heart_rate,
'systolic blood pressure' : blood_pressure_systolic,
'dyastolic blood pressure' : blood_pressure_dyastolic,
'temperature' : temperature,
'respiratory rate' : respiratory_rate,
'pulse oximetry' : pulse_oximetry}
df = pd.DataFrame(vitalsign)
df.to_csv('vitalsign.csv')
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
df.loc[mask, "class"]
</code></pre>
<p>it seems to be that,</p>
<p>error that i am receiving : ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). how can i sort it out</p>
| 0 | 2016-08-08T16:14:54Z | 38,834,618 | <p>As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use <code>&</code>. That also requires using parentheses so that <code>&</code> wouldn't take precedence. </p>
<p>It would go something like this:</p>
<pre><code>mask = ((50 < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
</code></pre>
<p>In order to avoid that, you can build series for lower and upper limits:</p>
<pre><code>low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
</code></pre>
<p>Now you can slice it as follows:</p>
<pre><code>mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out:
dyastolic blood pressure heart rate pulse oximetry respiratory rate \
17 136 62 97 15
69 110 85 96 18
72 105 85 97 16
161 126 57 99 16
286 127 84 99 12
435 92 67 96 13
499 110 66 97 15
systolic blood pressure temperature
17 141 37
69 155 38
72 154 36
161 153 36
286 156 37
435 155 36
499 149 36
</code></pre>
<p>And for assignment you can use np.where:</p>
<pre><code>df['class'] = np.where(mask, 'excellent', 'critical')
</code></pre>
| 2 | 2016-08-08T16:49:38Z | [
"python",
"pandas"
] |
Calculating mean value in DataFrame using a mask | 38,834,031 | <p>I have the following DataFrame:</p>
<pre><code> DATA Price1 Price2 Price3
sys dis
27 0.8 43.89 83.06 33.75
0.9 2.56 12.19 2.48
1.0 42.28 1.87 1.93
1.2 22.70 1.41 3.64
1.4 20.38 1.36 2.02
28 0.8 22.024 35.47 16.96
0.9 2.69 36.41 19.33
1.0 59.30 8.90 11.41
1.2 25.08 4.55 11.99
1.4 26.85 3.30 7.37
1.6 437.82 3.50 5.65
1.8 55.21 2.91 1.84
2.0 32.54 4.68 5.03
2.5 52.91 5.42 6.58
</code></pre>
<p>I need to calculate <code>mean</code> Prices for <code>dis < 1.0</code> and seperately for <code>dis > 1.0</code>. </p>
<p>I've tried to create a mask function:</p>
<pre><code>def mask(df):
df.loc[df.index.get_level_values('dis').between(0.8,1.0), 'Price1'].mean()
df.loc[df.index.get_level_values('dis').between(1.0,2.6), 'Price1'].mean()
return df
print (df_new.ix[:,'Price1']).apply(mask)
</code></pre>
<p>Thought I am getting the following error : </p>
<blockquote>
<p>AttributeError: ("'Float64Index' object has no attribute 'between'").</p>
</blockquote>
| 1 | 2016-08-08T16:15:02Z | 38,834,158 | <p>easiest solution is</p>
<pre><code>df['price_low']=df.ix[df.reset_index()['dis'] < 1,'price']
df['price_high']=df.ix[df.reset_index()['dis'] > 1, 'price']
df.price_low.mean()
df.price_high.mean()
</code></pre>
| 0 | 2016-08-08T16:22:53Z | [
"python",
"pandas",
"dataframe"
] |
Calculating mean value in DataFrame using a mask | 38,834,031 | <p>I have the following DataFrame:</p>
<pre><code> DATA Price1 Price2 Price3
sys dis
27 0.8 43.89 83.06 33.75
0.9 2.56 12.19 2.48
1.0 42.28 1.87 1.93
1.2 22.70 1.41 3.64
1.4 20.38 1.36 2.02
28 0.8 22.024 35.47 16.96
0.9 2.69 36.41 19.33
1.0 59.30 8.90 11.41
1.2 25.08 4.55 11.99
1.4 26.85 3.30 7.37
1.6 437.82 3.50 5.65
1.8 55.21 2.91 1.84
2.0 32.54 4.68 5.03
2.5 52.91 5.42 6.58
</code></pre>
<p>I need to calculate <code>mean</code> Prices for <code>dis < 1.0</code> and seperately for <code>dis > 1.0</code>. </p>
<p>I've tried to create a mask function:</p>
<pre><code>def mask(df):
df.loc[df.index.get_level_values('dis').between(0.8,1.0), 'Price1'].mean()
df.loc[df.index.get_level_values('dis').between(1.0,2.6), 'Price1'].mean()
return df
print (df_new.ix[:,'Price1']).apply(mask)
</code></pre>
<p>Thought I am getting the following error : </p>
<blockquote>
<p>AttributeError: ("'Float64Index' object has no attribute 'between'").</p>
</blockquote>
| 1 | 2016-08-08T16:15:02Z | 38,834,889 | <p>You could use boolean comparators:</p>
<pre><code>mean_low = df.loc[(df.index.get_level_values('dis') < 1.0), 'Price1'].mean()
mean_high = df.loc[(df.index.get_level_values('dis') > 1.0), 'Price1'].mean()
</code></pre>
| 2 | 2016-08-08T17:06:52Z | [
"python",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.