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
sequence |
---|---|---|---|---|---|---|---|---|---|
Why z3c.RML ignores the pageSize Attribute of <template> | 40,085,840 | <p>I am trying to get an A4-Landscape output file. The Document i am modifying is A4-Portrait, so i thought simple switch: <strong><em>pageSize="(21cm, 29.7cm)"</em></strong> to <strong><em>pageSize="(29.7cm, 21cm)"</em></strong>, but nothing happend.</p>
<p>I then fount an Attribute: <strong><em>rotation="90"</em></strong>. The Page on the Screen ist still A4-Portrait, but the content ist turned 90 degres around. On paper it woulde be fine, but on screen i have to turn my head by 90 degress, not very comfortable.</p>
<p>After this i tryed: <strong><em>pageSize="(10cm, 10cm)"</em></strong>, thought this should look terrible, but nothing changed.</p>
<p>Could it be possible, that the Size of the generated PDF-File is set in thePython-Code and not set by the RML-File?</p>
<p>This is the Python Code:</p>
<pre><code>#!venv/bin/python
# -*- coding: utf-8 -*-
from z3c.rml import pagetemplate
rmlPageTemplate = pagetemplate.RMLPageTemplateFile("test.rml")
open('test.pdf', 'wb').write(rmlPageTemplate())
</code></pre>
<p>My RML-File locks like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE document SYSTEM "rml_1_0.dtd">
<document test.pdf">
<docinit>
...
</docinit>
<template pageSize="(10cm, 10cm)"
rotation="90"
leftMargin="2.5cm"
rightMargin="2.5cm"
topMargin="2.5cm"
bottomMargin="2.5cm"
showBoundary="1"
>
<pageTemplate id="main">
<frame id="first" x1="2.5cm" y1="2.5cm" width="24.7cm" height="16cm" showBoundary="1"/>
</pageTemplate>
</template>
<stylesheet>
...
</stylesheet>
<story>
...
</story>
</document>
</code></pre>
<p>Thank you very much.</p>
| 0 | 2016-10-17T11:59:52Z | 40,088,238 | <p><a href="https://github.com/zopefoundation/z3c.rml/blob/master/RML-DIFFERENCES.rst" rel="nofollow">https://github.com/zopefoundation/z3c.rml/blob/master/RML-DIFFERENCES.rst</a></p>
<p><strong>RML2PDF and z3c.rml Implementation Differences</strong></p>
<p>This document outlines the differences between ReportLab Inc.'s RML2PDF library and z3c.rml.</p>
<p><strong>Incompatibilies</strong></p>
<p>
<em>page<strong>S</strong>ize</em>: This is called page<strong>s</strong>ize in this implementation to match the API.</p>
| 0 | 2016-10-17T13:51:38Z | [
"python",
"reportlab",
"rml"
] |
Python: How to 'refresh' random variables | 40,085,844 | <p>I have this code, i want to know if there is anyway i can get rid of all these variables and instead only have one for each purpose. My code is a password generator with three different password strengths. Code will work without this but for design sake i want to make it smaller. I've tried making them functions but that didn't work. I'm probably missing something obvious:</p>
<pre><code>import time
import random
import string
ps = ""
name = ""
ans1 = ""
list_s = ["!","£","~","%","*","(","}","#",";","@","/",":","-"]
list_w = ["mouse","human","dog","tree","boom","thief","killer","dealer","feeler","man","woman","death"]
list_w2 =["help","yelp","empire","squire","lier","fryer","kitchen","bed","matress", "criminal","drug"]
rc1 = random.choice(string.ascii_lowercase)
rc2 = random.choice(string.ascii_lowercase)
rc3 = random.choice(string.ascii_lowercase)
rc4 = random.choice(string.ascii_lowercase)
rc5 = random.choice(string.ascii_uppercase)
rc6 = random.choice(string.ascii_uppercase)
rc7 = random.randrange(10)
rc8 = random.randrange(10)
rc9 = random.randrange(10)
rc10 = random.choice(list_s)
rc11 = random.choice(list_s)
rc12 = random.choice(list_w)
rc13 = random.choice(list_w2)
while name == "":
name = str(input("Welcome to password64, before we begin enter your name:"))
while ans1 == "":
ans1 = str(input("Have you used password64 before " + name + " ?"))
ans1 = ans1[0].lower()
if ans1 == "n":
print ("Thank you for trying password64 for the first time " + name + " !")
time.sleep(4)
print ("I will ask you the strength of the password you want, there will be three options: Strong, Medium or Weak")
time.sleep(6)
print ("A strong password is a mix of random numbers, letters and symbols")
time.sleep(3)
print ("A medium password will be a couple of words with random numbers and symbols")
time.sleep(3)
print ("A weak password will be a couple of words with a number")
elif ans1 == "y":
print ("Thank you for reusing password64 " + name + " !")
time.sleep(2)
print ("Let's get straight on with it then")
while ps == "":
ps = str(input("Do you with to generate a strong, medium or weak password?"))
ps = ps[0].lower()
if ps == "s":
a = [rc1 , rc2, rc3, rc4, rc5, rc6, rc7, rc8, rc9, rc10, rc11]
elif ps == "m":
a = [rc12, rc13, rc7, rc8, rc10, rc11]
elif ps == "w":
a = [rc12, rc13, rc7]
else:
print ("You did not enter a valid password strength")
exit()
random.shuffle(a,random.random)
print ("Your password is generating....")
for i in range(0,len(a)):
time.sleep(1)
print (a[i], end="")
print ("")
print ("Your password is ready to be used " + name + ". Thank you for using password64")
</code></pre>
| 0 | 2016-10-17T12:00:10Z | 40,086,830 | <p>why don't you put the randoms into a function?</p>
<p>f.e.</p>
<pre><code># -*- coding: cp1252 -*-
import string
import random
import time
random_type = ("lower","upper","digit","strange","wordlist1","wordlist2")
list_s = ["!","£","~","%","*","(","}","#",";","@","/",":","-"]
list_w = ["mouse","human","dog","tree","boom","thief","killer","dealer","feeler","man","woman","death"]
list_w2 =["help","yelp","empire","squire","lier","fryer","kitchen","bed","matress", "criminal","drug"]
def random_part(which_type):
if which_type == "lower":
return random.choice(string.ascii_lowercase)
elif which_type == "upper":
return random.choice(string.ascii_uppercase)
elif which_type == "digit":
return str(random.randrange(10))
elif which_type == "digit":
return str(random.randrange(10))
elif which_type == "strange":
return random.choice(list_s)
elif which_type == "wordlist1":
return random.choice(list_w)
else:
return random.choice(list_w2)
def generate_pw(password_strength):
if password_strength == 'w':
l = ['wordlist1','wordlist2','digit']
elif password_strength == 'm':
l = ['wordlist1','wordlist2','digit','digit','strange','strange']
else:
l = ['wordlist1','wordlist2','digit','digit','strange','strange','lower','upper'] #whatever you want to
result = []
for x in l:
result.append(random_part(x))
return result
print generate_pw('s')
</code></pre>
<p>by the way: you could use only one word list, if you would eliminate the Chosen value from list. So you could use more than 2 words in your Password. Same you could do with strange chars, so every char could only appear once.
And jaou could shuffle the result.
But it is your decision</p>
| 0 | 2016-10-17T12:49:19Z | [
"python",
"list",
"variables",
"random"
] |
Matplotlib axis not displayed | 40,085,850 | <p>The python code (python 2.7) running on windows 7 shown below results in the following inconsistent behaviour with respect to the display of axis which I do not understand:</p>
<p>1 - a window is opened and a plot without an axis is displayed showing a point
2 - on closing the window, another window is opened and a plot is displayed showing the same point but this time with an axis. </p>
<pre><code>from osgeo import ogr
import pylab
from ospybook.vectorplotter import VectorPlotter
vp = VectorPlotter(False)
myLoc = ogr.Geometry(ogr.wkbPoint)
myLoc.AddPoint(59.5,13)
vp.plot(myLoc,'rs')
pylab.show() ## the plot is displayed --without-- axes displayed
myLoc.AddPoint(59.5,13)
vp.plot(myLoc,'rs')
pylab.show() ## the plot is displayed with axes displayed
</code></pre>
<p>Please note that in my environment, if the vector plotter interactive mode is set to True, pylab.show() opens window but no plot is displayed.</p>
| 0 | 2016-10-17T12:00:23Z | 40,086,527 | <p>try </p>
<pre><code>vp = VectorPlotter(interactive=False, ticks=True)
</code></pre>
| 1 | 2016-10-17T12:34:45Z | [
"python",
"matplotlib"
] |
Localization in 2D world | 40,085,860 | <p>I am struggling with the following code for the localization of robot on 2D world of red and green grid cells. I am basically getting the error which states that list index out of range.</p>
<p><a href="https://i.stack.imgur.com/vZfh9.png" rel="nofollow"><img src="https://i.stack.imgur.com/vZfh9.png" alt="enter image description here"></a></p>
<pre><code>p=[.2,.2,.2,.2,.2]# Initial cell probability
w=[['R','G','G','R','R'],
['R','R','G','R','R'],
['R','R','G','G','R'],
['R','R','R','R','R']]# World
meas = ['G','G','G','G','G'] # measurements
mov = [[0,0],[0,1],[1,0],[1,0],[0,1]] # motion
phit = .6 # Probability to measure: R->0.6
pmiss = .2 # Probability to measure: R->0.2
pExact = .8 # Prob. exact motion
pOver = .1 # Prob. overshoot
pUnder = .1 # Prob. undershoot
def entropy (p):
s = [p[i]*log(p[i]) for i in range(len(p))]
return round(-sum(s), 2)
def sense(p, z):
q = []
for i in range(len(p)):
hit = w[i]==z
q.append( p[i]*(phit*hit + pmiss*(1-hit)) )
s = sum(q)
q = [i/s for i in q]
return q
#Moving u cells
def move(p, u):
q = []
for i in range(len(p)):
motion = pExact * p[(i-u)%len(p)]
motion += pOver * p[(i-u-1)%len(p)]
motion += pUnder * p[(i-u+1)%len(p)]
q.append(motion)
return q
for i in range(len(meas)):
p = sense(p, meas[i])
r = [format(j,'.3f') for j in p]
print "Sense %i:"%(i),
print r, entropy(p)
p = move(p, mov[i])
r = [format(j,'.3f') for j in p]
print "Move %i:"%(i),
print r, entropy(p)
print
</code></pre>
| 1 | 2016-10-17T12:01:10Z | 40,086,332 | <p>In routine sense() your program tries to access the 5th element of list <strong>w</strong> (index 4 in the list), unfortunately <strong>w</strong> only has 4 elements (only indices 0, 1, 2, 3 are valid)</p>
<p><strong>range(len(p))</strong> returns [0, 1, 2, 3, 4]</p>
<p>Also <strong>w[i]==z</strong> will never be true: indeed <strong>w[i]</strong> is a list of characters, <strong>z</strong> is a single character</p>
<p>sense() is probably not doing what you intended to originally.</p>
| 0 | 2016-10-17T12:24:41Z | [
"python",
"grid",
"cells"
] |
recover values from ipyparallel map if a single evaluation failed | 40,085,888 | <p>I run a quite time consuming (>3 days) simulation using ipyparallel's map function like that in Jupyter Notebook</p>
<pre><code>from ipyparallel import Client
rc = Client()
lview = rc.load_balanced_view()
ar = lview.map(runsimulation, parameter)
</code></pre>
<p>and I really need those results. But unfortunately a single instance died because of memory starvation. Now i can not access the result using ar[i] anymore. Is there a chance to recover all the other results that where most certainly computed (I can see the characteristic memory and cpu time consumption in the Ganglia Monitor of the cluster).</p>
<p>I still have the object ar in the Jupyter Notebook.</p>
| 1 | 2016-10-17T12:02:19Z | 40,106,864 | <p>You can get partial results for individual msg_ids. With map, each message corresponds to a chunk of the map (a list):</p>
<pre><code>import ipyparallel as ipp
results = []
for msg_id in ar.msg_ids:
chunk_ar = rc.get_result(msg_id)
try:
chunk = chunk_ar.get()
except ipp.RemoteError as e:
print('ignoring error: %s' % e)
results.extend(chunk)
</code></pre>
| 1 | 2016-10-18T11:21:06Z | [
"python",
"jupyter",
"ipython-parallel"
] |
How to set a specific download location in Mozilla - Marionette web driver? | 40,086,011 | <p>I am having an automation script which worked well before the recent mozilla update. The selenium-python script automates some of my browser actions, and save certain reports (csv) to a defined location.</p>
<p>I have been using selenium 2.53.6, which uses the following code :</p>
<pre><code>profile = webdriver.firefox.firefox_profile.FirefoxProfile()
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',"text/csv, application/pdf,application/octet-stream")
profile.set_preference('browser.download.folderList',2)
profile.set_preference("browser.download.manager.showWhenStarting",False)
profile.set_preference('browser.download.dir','D:\Downloads')
driver = webdriver.Firefox(firefox_profile=profile)
</code></pre>
<p>Currently I use selenium-python 3.0.1 and Firefox 48. Here I had added the geckodriver path to environment variables and was able to launch firefox using the code below:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
driver = webdriver.Firefox(capabilities=caps)
</code></pre>
<p>I am curious on how to do a <code>profile.set_preference</code> equivalent in firefox-marionette driver. I couldn't find any documentations on it.</p>
<p>Please advise.</p>
| 1 | 2016-10-17T12:08:17Z | 40,088,192 | <p>You can pass <code>profile</code> as well to launch <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.firefox.webdriver.WebDriver" rel="nofollow"><code>FirefoxDriver</code></a> as :-</p>
<pre><code>driver = webdriver.Firefox(capabilities=caps, firefox_profile=profile)
</code></pre>
<p>You can also set <code>firefox_profile</code> into <code>capabilities</code> as :-</p>
<pre><code>caps["firefox_profile"] = profile
driver = webdriver.Firefox(capabilities=caps)
</code></pre>
| 1 | 2016-10-17T13:49:56Z | [
"python",
"selenium",
"firefox",
"firefox-marionette"
] |
Error: [Errno 71] Protocol error: pyvenv | 40,086,091 | <p>I am using Centos7 with vagrant and virtualbox on windows10.
I am trying to create pyvenv virtual environment to develop python web apps with django. I have installed python 3.4. </p>
<p>However, when I type
<code>pyvenv-3.4 name_of_environment</code>,
it gives back an error <code>Error: [Errno 71] Protocol error: 'lib' -> '/vagrant/django_apps/app1/name_of_environment/lib64'</code></p>
<p>What is wrong?</p>
| -1 | 2016-10-17T12:13:05Z | 40,120,623 | <p><code>pyvenv-3.4 --without-pip name_of_environment</code>
worked</p>
<p>looks like pip was not installed.</p>
<p>thanks for the help.</p>
| 0 | 2016-10-19T01:30:50Z | [
"python",
"django",
"python-3.x",
"vagrant",
"centos7"
] |
Interpreter can find a 3rd party module but WIN-R and command line can't | 40,086,193 | <p>I have installed a 3rd party module named <code>pyperclip</code> to my <code>\python31\Lib\site-packages</code> folder using <code>pip install --target</code> as I also have python 2.7 on the computer and it appears modules are put in 2.7 as a default.</p>
<p>I can run the script below through IDLE just fine. </p>
<pre><code>import pyperclip
import shelve
import sys
import os
curdir = os.getcwd()
mc_shelf = shelve.open(os.path.join(curdir, "mcb2"))
# save clipboard content
if len(sys.argv) == 3 and sys.argv[1].lower() == "save":
mc_shelf[sys.argv[2]] = pyperclip.paste()
print("Saved contents of clipboard to keyword \"{}\".".format(sys.argv[2]))
elif len(sys.argv) == 2:
keyword = sys.argv[1].lower()
if keyword == "list":
pyperclip.copy(", ".join(keyword for keyword in mc_shelf))
print("Copied list to clipboard.")
elif keyword in mc_shelf:
pyperclip.copy(mc_shelf[keyword])
print("Pasted text to clipboard.")
mc_shelf.close()
</code></pre>
<p>However using WIN-R/ the command line I get an ImportError, eg:</p>
<pre><code>PS C:\users\dave\Desktop\2016Coding\AutomateBoring\8-RWFiles> py.exe mcb2.pyw save dave
py.exe : Traceback (most recent call last):
At line:1 char:1
+ py.exe mcb2.pyw save dave
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
File "mcb2.pyw", line 7, in <module>
import pyperclip
ImportError: No module named 'pyperclip'
</code></pre>
<p>What exactly might be going on here? Is it something to do with the paths used by each application? I've set environment variables, and set a pythonpath in system variables(this in particular led to a different error) but to be quite honest I'm plain confused.</p>
<p>Attempt at using pip3 to install:</p>
<pre><code>PS C:\> pip install pyperclip
Requirement already satisfied (use --upgrade to upgrade): pyperclip in c:\python27\lib\site-packages
PS C:\> pip3 install pyperclip
pip3 : The term 'pip3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:1
+ pip3 install pyperclip
+ ~~~~
+ CategoryInfo : ObjectNotFound: (pip3:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
| 0 | 2016-10-17T12:17:16Z | 40,086,249 | <p>You need to install packages using <code>pip3</code> if you want it to install in your Python3 environment. IE</p>
<pre><code>pip3 install pyperclip
</code></pre>
<blockquote>
<p>I have installed a 3rd party module named pyperclip to my \python31\Lib\site-packages folder using <code>pip install --target</code></p>
</blockquote>
<p>What you're effectively doing here is using the Python2 version of pip to try to install a Python3 package. Your Python3 environment has its own version of <code>pip</code> -- If your Python3 environment is also in your PATH, you can call pip for Python3 by <code>pip3</code></p>
| 1 | 2016-10-17T12:20:31Z | [
"python",
"module"
] |
Errors with pytest | 40,086,292 | <p>I am using @pytest.mark.parametrize with various testcases and expected outputs. Its passing perfectly fine with few test cases and giving this error with some other cases. Not even able to google it. I want to know what could have gone wrong. I would be glad if someone can tell me how to atleast google for this error !</p>
<blockquote>
<p>============================= test session starts =============================
platform win32 -- Python 2.7.12, pytest-3.0.3, py-1.4.31, pluggy-0.4.0 -- c:\python27\python.exe</p>
<p>cachedir: .cache</p>
<p>rootdir: C:\Python27, inifile:</p>
<p>collected 0 items / 1 errors</p>
<p>=================================== ERRORS ====================================</p>
<p>___________________ ERROR collecting test_mod_pppoe_disc.py ___________________</p>
<p>lib\site-packages\py_path\local.py:650: in pyimport</p>
<p><strong>import</strong>(modname)</p>
<p>lib\site-packages\pytest-3.0.3-py2.7.egg_pytest\assertion\rewrite.py:131: in find_module</p>
<p>source_stat, co = _rewrite_test(self.config, fn_pypath)</p>
<p>lib\site-packages\pytest-3.0.3-py2.7.egg_pytest\assertion\rewrite.py:322: in _rewrite_test</p>
<p>tree = ast.parse(source)</p>
<p>lib\ast.py:37: in parse</p>
<p>return compile(source, filename, mode, PyCF_ONLY_AST)</p>
<p>E ValueError: invalid \x escape</p>
<p>!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.21 seconds ===========================</p>
</blockquote>
<pre><code>@pytest.mark.parametrize("test_input1,test_input2,expected", [
(ARP(sha='D\x85\x00\xa2}\xad', spa='\n\xc4@=', tha='\x00\x00\x00\x00\x00\x00', tpa='\n\xc4@\x01'),"<socket._socketobject object at 0x0000000003DC8118>",0),
(ARP(sha='jrofalfeoiexad', spa='\nenkajf@=', tha='\x00\x00\x00\x02jfcalkfel', tpa='\n\xcjfeiafa1'),"<socket._socketobject object at 0x0000000003D2BD48>",0),
(ARP(eioakn iejfoeajoijea),"<socket._socketobject object at 0x0000000003DC8118>",0)
])
def test_mod_arp(test_input1,test_input2,expected):
assert mod_arp(test_input1,test_input2) == expected
</code></pre>
<p>Description about code: This is the code where I was getting error. I have appropriate functions defined. Working fine with first test case. Was failing with last two test cases.</p>
| 0 | 2016-10-17T12:22:35Z | 40,094,988 | <p>The example you pasted can be minimized a bit into this file:</p>
<pre><code>import pytest
@pytest.mark.parametrize("foo", ['\n\xcjfeiafa1'])
def test_escapes(foo):
pass
</code></pre>
<p>Which gives us the same error with Python 2, and a clearer error with Python 3:</p>
<pre><code>/usr/lib/python3.5/site-packages/_pytest/python.py:410: in _importtestmodule
mod = self.fspath.pyimport(ensuresyspath=importmode)
/usr/lib/python3.5/site-packages/py/_path/local.py:650: in pyimport
__import__(modname)
E File "/home/florian/tmp/foo.py", line 3
E @pytest.mark.parametrize("foo", ['\n\xcjfeiafa1'])
E ^
E SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \xXX escape
</code></pre>
<p>The reason this happens is due to your <code>\xcj</code> escape, which is not a valid escape. </p>
| 1 | 2016-10-17T20:20:23Z | [
"python",
"py.test"
] |
datetime format does not match with content | 40,086,365 | <p>I have checked quite a lot of questions related to this topic but I'm not able to find my error. </p>
<p>My code can be simplified to:</p>
<pre><code>date = "2016/07/20"
time = "11:44:20.920"
date_time = datetime.strptime(date + " " + time, '%y/%m/%d %H:%M:%S.%f')
</code></pre>
<p>The error I get is the following:</p>
<pre><code>Traceback (most recent call last):
File "adma_shortener.py", line 50, in <module>
adma_time[ii] = datetime.strptime(a, '%y/%m/%d %H:%M:%S.%f').replace(microsecond=0)
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2016/07/20 11:44:20.920' does not match format '%y/%m/%d %H:%M:%S.%f'
</code></pre>
<p>Can someone see my error?
Thanks in advance</p>
| 2 | 2016-10-17T12:26:13Z | 40,086,403 | <p>The year directive should be in caps:</p>
<pre><code>date_time = datetime.strptime(date + " " + time, '%Y/%m/%d %H:%M:%S.%f')
# ^
</code></pre>
<blockquote>
<p><code>%y</code> Year without century as a zero-padded decimal number </p>
<p><code>%Y</code> Year with century as a decimal number.</p>
</blockquote>
<hr>
<p>Reference:</p>
<p><a href="http://strftime.org/">http://strftime.org/</a></p>
| 6 | 2016-10-17T12:28:34Z | [
"python",
"datetime"
] |
datetime format does not match with content | 40,086,365 | <p>I have checked quite a lot of questions related to this topic but I'm not able to find my error. </p>
<p>My code can be simplified to:</p>
<pre><code>date = "2016/07/20"
time = "11:44:20.920"
date_time = datetime.strptime(date + " " + time, '%y/%m/%d %H:%M:%S.%f')
</code></pre>
<p>The error I get is the following:</p>
<pre><code>Traceback (most recent call last):
File "adma_shortener.py", line 50, in <module>
adma_time[ii] = datetime.strptime(a, '%y/%m/%d %H:%M:%S.%f').replace(microsecond=0)
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2016/07/20 11:44:20.920' does not match format '%y/%m/%d %H:%M:%S.%f'
</code></pre>
<p>Can someone see my error?
Thanks in advance</p>
| 2 | 2016-10-17T12:26:13Z | 40,086,417 | <p><code>%y</code> is the specifier for "Year without century as a zero-padded decimal number.", which means a two-digit number. Use <code>%Y</code> instead.</p>
| 2 | 2016-10-17T12:29:20Z | [
"python",
"datetime"
] |
datetime format does not match with content | 40,086,365 | <p>I have checked quite a lot of questions related to this topic but I'm not able to find my error. </p>
<p>My code can be simplified to:</p>
<pre><code>date = "2016/07/20"
time = "11:44:20.920"
date_time = datetime.strptime(date + " " + time, '%y/%m/%d %H:%M:%S.%f')
</code></pre>
<p>The error I get is the following:</p>
<pre><code>Traceback (most recent call last):
File "adma_shortener.py", line 50, in <module>
adma_time[ii] = datetime.strptime(a, '%y/%m/%d %H:%M:%S.%f').replace(microsecond=0)
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2016/07/20 11:44:20.920' does not match format '%y/%m/%d %H:%M:%S.%f'
</code></pre>
<p>Can someone see my error?
Thanks in advance</p>
| 2 | 2016-10-17T12:26:13Z | 40,086,534 | <p>If you are not very familiar with the <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow">datetime directives</a>, I will suggest you to use <a href="http://dateutil.readthedocs.io/en/stable/parser.html" rel="nofollow"><code>dateutil.parser</code></a> instead. It is much simpler. For example:</p>
<pre><code>>>> import dateutil.parser
>>> date = "2016/07/20"
>>> time = "11:44:20.920"
>>> my_date = dateutil.parser.parse('{date} {time}'.format(date=date, time=time))
>>> my_date
datetime.datetime(2016, 7, 20, 11, 44, 20, 920000)
</code></pre>
| 1 | 2016-10-17T12:35:03Z | [
"python",
"datetime"
] |
Pandas to_sql() not working with Posgresql - value too long for type character varying | 40,086,386 | <p>I'm using Pandas with SQLAlchemy to apply some ETL on one CSV file</p>
<p>After validating the fields and transforming some of them I try to export to my PostgreSQL database, but I'm getting one error which does not make sense:</p>
<pre><code>sqlalchemy.exc.DataError: (psycopg2.DataError) value too long for type character varying(50)
</code></pre>
<p>I already changed the field to many values (it was initially setup as 15). I tried to get <code>NaN</code> values for that field and replacing with '' (there was only one field). For that I used:</p>
<pre><code>>>> df.loc[df['foo'].isnull(), 'foo'] = ''
</code></pre>
<p>I tried changing the <code>chunksize</code> to 5000 and 1000. Initially, it was not set.</p>
<pre><code>>>> df.to_sql("mytable", con, index=False, if_exists='append', chunksize=1000)
</code></pre>
<p>The command above worked with <code>sqlite</code></p>
<p>After having those problems I checked the column which was throwing the error again to see if there was any problem with its length. Apparently, it did not, but I ran the following code anyway:</p>
<pre><code>>>> df.foo.str.len().max()
11.0
</code></pre>
<p>I also tried the following:</p>
<pre><code>>>> df.fillna(value='', inplace=True)
>>> df['foo'] = df['foo'].str.strip()
</code></pre>
<p>Then I also added</p>
<pre><code>for f in Inventory._meta.get_fields():
if f.get_internal_type() == 'CharField':
df[f.name] = df[f.name].str[:f.max_length]
</code></pre>
<p>But it did not work either</p>
<p>I finally put the length of the column to 100, but this is not right. The field contains only 11 char per row. I ran out of ideas. This error is strange, and I'd appreciate some help.</p>
| 3 | 2016-10-17T12:27:48Z | 40,092,512 | <p>Ok, it's pretty embarrassing what happened. The code above was right since the beginning. The problem is that I'm merging some rows and concatenating in that column the merged values in a different function and I forgot. I thought the error was only in my validation function when it was never there.</p>
<p>What did I do to find it out?</p>
<p>I change the value of the column to a big value (100) so the code above would work, then I ran the following SQL:</p>
<pre><code>SELECT length(foo) AS ln_foo FROM inventory WHERE length(foo) > 11
</code></pre>
| 0 | 2016-10-17T17:40:18Z | [
"python",
"django",
"postgresql",
"pandas",
"django-models"
] |
python importing all images from a local directory | 40,086,387 | <pre><code>import cv2
import os
for filename in os.listdir('C:/Users/Akhil/Downloads/New'):
image = cv2.imread(filename)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite('gray_image.png',gray_image)
cv2.imshow('color_image',image)
cv2.imshow('gray_image',gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>I am importing all the images from a directory as shown above and turning each image into a grey scale image. But when I run this code, I am facing the following error:</p>
<pre><code>OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::ipp_cvtColor, file C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\color.cpp, line 7456
Traceback (most recent call last):
File "11.py", line 7, in <module>
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor
</code></pre>
| 0 | 2016-10-17T12:27:49Z | 40,086,844 | <p>This is often a symptom of failing to find the image. </p>
<p>Note that the <code>filename</code>s returned by <code>os.listdir()</code> are relative to the directory passed to listdir(). So OpenCV is searching for a file named "image_01.jpg" for example, in your current working directory, and can't find anything. But instead of failing, it returns an empty image. </p>
<p>Try <code>path_to_image = os.path.join(my_image_folder, filename)</code> and imread that.</p>
| 1 | 2016-10-17T12:49:52Z | [
"python",
"opencv",
"python-import"
] |
Tryng to run 2 Python applications with different Python versions with mod_wsgi | 40,086,415 | <p>I have in my Apache 2 applications: Django app and MoinMoin app. The first one is running now with Python3.4 and the second one (MoinMoin) with Python2.7</p>
<p>When running dpkg:</p>
<pre><code>ruben@babylon:/var/log/apache2$ dpkg -l | grep wsgi
rc libapache2-mod-wsgi 3.4-4ubuntu2.1.14.04.2 amd64 Python WSGI adapter module for Apache
ii libapache2-mod-wsgi-py3 3.4-4ubuntu2.1.14.04.2 amd64 Python 3 WSGI adapter module for Apache
</code></pre>
<p>but Apache can't run the 2 modules at the same time. Django (Python3) is working but MoinMoin (Python2.7) not. How can I fix that?</p>
<p>Thanks.</p>
| 1 | 2016-10-17T12:29:16Z | 40,094,813 | <p>As you were told already in:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/40043543/virtual-environment-not-recognized-in-wsgipythonpath">Virtual environment not recognized in WSGIPythonPath</a></li>
</ul>
<p>you cannot do that within a single Apache instance.</p>
<p>The simple answer as was described is to run a separate WSGI server such as <code>mod_wsgi-express</code>, or you can use <code>gunicorn</code> our something else as well, and set it up behind the main Apache instance it with Apache proxying to it.</p>
<p>There are a lot of details around doing this and as also suggested, you are better off asking on the mod_wsgi mailing list if you want to do this with mod_wsgi.</p>
<p>If don't wish to use the mod_wsgi mailing list, then you can find some information in:</p>
<ul>
<li><a href="http://blog.dscpl.com.au/2015/06/proxying-to-python-web-application.html" rel="nofollow">http://blog.dscpl.com.au/2015/06/proxying-to-python-web-application.html</a></li>
<li><a href="http://blog.dscpl.com.au/2015/07/redirection-problems-when-proxying-to.html" rel="nofollow">http://blog.dscpl.com.au/2015/07/redirection-problems-when-proxying-to.html</a></li>
</ul>
<p>It talks about proxying to backend WSGI application running in Docker, but all the same principles apply as to setting up the proxy fronted and the issues that arise.</p>
| 1 | 2016-10-17T20:08:09Z | [
"python",
"django",
"apache",
"mod-wsgi",
"moinmoin"
] |
python calculations are being weird | 40,086,419 | <p>Am having some problems with my code. I need to limit an input by multiples of 5 under a changing maximum.</p>
<p>With what I have now it should work but it isn't. What have i missed?</p>
<pre><code>while True:
print("Place your bet. Must be a multiple of 5")
posBets = range(5, (balance + 1), 5)
bet = str(input())
if bet == posBets:
print("You have bet $" + str(bet))
loop = 0
elif bet != posBets:
print("Please bet an amount that is a multiple of 5, or an amount that is within your balance")
print("Press enter to continue")
input()
loop = 1
if not(loop == 1):break #Exit loop
</code></pre>
<p>there is also a problem with a loop. When im trying to get my new value it needs to subtract from the original value and send it back to the main function however it always adds it then doenst change the value that it sends to the main</p>
<pre><code>win = 1
lose = 2
tie = 3
r = win or lose or tie
print("Battle shall now commence")
print("Choose an attack")
print("The attacks you can use are as follows")
print("(1)Fury Punch")
print("(2)Punishment kick")
print("(3)Sword of justice")
print("(4)Shuriken of Vengence")
print("(5)Numchucks of Anger")
print("(6)Knife of Freedom")
attack = int(input())
while attack < 1 or attack > 6:
print("please input either: 1, 2, 3, 4, 5 or 6")
attack = int(input())
winLose(attack, win, lose, tie,)
if r == win:
newBalance = int(balance) + int(bet)
elif r == lose:
newBalance = int(balance) - int(bet)
else:
if r == tie:
balance = newBalance
print("Your Balance is $" + str(newBalance))
return(bet, newBalance)
</code></pre>
<p>here is the full code
thank you for any help</p>
<pre><code>def attack1(pcMove, win, tie, lose):
if pcMove == 1:
print("Your opponent has choosen Fury Punch")
print("it is a tie there is no winner")
r = tie
elif pcMove == 2:
print("Your opponent has choosen Punishment Kick")
print("You have lost")
r = lose
elif pcMove == 3:
print("Your opponent has choosen Sword of Justice")
print("You have lost")
r = lose
elif pcMove == 4:
print("Your opponent has choosen Shuriken of Vengeance")
print("You have won. Good job")
r = win
elif pcMove == 5:
print("Your opponent has choosen Numchucks of Anger")
print("You have won. Good job")
r = win
else:
print("Your opponent has choosen Knife of Freedom")
print("You have lost")
r = lose
return(r)
def attack2(pcMove, win, tie, lose):
if pcMove == 1:
print("Your opponent has choosen Fury Punch")
print("You have won. Good job")
r = win
elif pcMove == 2:
print("Your opponent has choosen Punishment Kick")
print("it is a tie there is no winner")
r = tie
elif pcMove == 3:
print("Your opponent has choosen Sword of Justice")
print("You have lost")
r = lose
elif pcMove == 4:
print("Your opponent has choosen Shuriken of Vengeance")
print("You have lost")
r = lose
elif pcMove == 5:
print("Your opponent has choosen Numchucks of Anger")
print("You have won. Good job")
r = win
else:
print("Your opponent has choosen Knife of Freedom")
print("You have lost")
r = lose
return(r)
def attack3(pcMove, win, tie, lose):
if pcMove == 1:
print("Your opponent has choosen Fury Punch")
print("You have won. Good job")
r = win
elif pcMove == 2:
print("Your opponent has choosen Punishment Kick")
print("You have won. Good job")
r = win
elif pcMove == 3:
print("Your opponent has choosen Sword of Justice")
print("it is a tie there is no winner")
r = tie
elif pcMove == 4:
print("Your opponent has choosen Shuriken of Vengeance")
print("You have lost")
r = lose
elif pcMove == 5:
print("Your opponent has choosen Numchucks of Anger")
print("You have lost")
r = lose
else:
print("Your opponent has choosen Knife of Freedom")
print("You have won. Good job")
r = win
return(r)
def attack4(pcMove, win, tie, lose):
if pcMove == 1:
print("Your opponent has choosen Fury Punch")
print("You have lost")
r = lose
elif pcMove == 2:
print("Your opponent has choosen Punishment Kick")
print("You have won. Good job")
r = win
elif pcMove == 3:
print("Your opponent has choosen Sword of Justice")
print("You have won. Good job")
r = win
elif pcMove == 4:
print("Your opponent has choosen Shuriken of Vengeance")
print("it is a tie there is no winner")
r = tie
elif pcMove == 5:
print("Your opponent has choosen Numchucks of Anger")
print("You have lost")
r = lose
else:
print("Your opponent has choosen Knife of Freedom")
print("You have won. Good job")
r = win
return(r)
def attack5(pcMove, win, tie, lose):
if pcMove == 1:
print("Your opponent has choosen Fury Punch")
print("You have lost")
r = lose
elif pcMove == 2:
print("Your opponent has choosen Punishment Kick")
print("You have lost")
r = lose
elif pcMove == 3:
print("Your opponent has choosen Sword of Justice")
print("You have won. Good job")
r = win
elif pcMove == 4:
print("Your opponent has choosen Shuriken of Vengeance")
print("You have won. Good job")
r = win
elif pcMove == 5:
print("Your opponent has choosen Numchucks of Anger")
print("it is a tie there is no winner")
r = tie
else:
print("Your opponent has choosen Knife of Freedom")
print("You have lost")
r = lose
return(r)
def attack6(pcMove, win, tie, lose):
if pcMove == 1:
print("Your opponent has choosen Fury Punch")
print("You have won. Good job")
r = win
elif pcMove == 2:
print("Your opponent has choosen Punishment Kick")
print("You have won. Good job")
r = win
elif pcMove == 3:
print("Your opponent has choosen Sword of Justice")
print("You have lost")
r = lose
elif pcMove == 4:
print("Your opponent has choosen Shuriken of Vengeance")
print("You have lost")
r = lose
elif pcMove == 5:
print("Your opponent has choosen Numchucks of Anger")
print("You have won. Good job")
r = win
else:
print("Your opponent has choosen Knife of Freedom")
print("it is a tie there is no winner")
r = tie
return(r)
def winLose(attack, win, tie, lose):
import random
pcMove = random.randint(1, 6);
while pcMove == 0:
pcMove = random.randint(1, 6);
if attack == 1:
print("You have choosen to use Fury Punch. Good Luck")
print("Ready for battle. Press enter to start")
enter = input()
attack1(pcMove, win, tie, lose)
r = win or lose or tie
elif attack == 2:
print("You have choosen to use Punishment Kick. Good Luck")
print("Ready for battle. Press enter to start")
enter = input()
attack2(pcMove, win, tie, lose)
r = win or lose or tie
elif attack == 3:
print("You have choosen to use Sword of Justice. Good Luck")
print("Ready for battle. Press enter to start")
enter = input()
attack3(pcMove, win, tie, lose)
r = win or lose or tie
elif attack == 4:
print("You have choosen to use Shuriken of Vengence. Good Luck")
print("Ready for battle. Press enter to start")
enter = input()
attack4(pcMove, win, tie, lose)
r = win or lose or tie
elif attack == 5:
print("You have choosen to use Numchucks of Anger. Good Luck")
print("Ready for battle. Press enter to start")
enter = input()
attack5(pcMove, win, tie, lose)
r = win or lose or tie
else:
print("You have choosen to use Knife of Freedom. Good Luck")
print("Ready for battle. Press enter to start")
enter = input()
attack6(pcMove, win, tie, lose)
r = win or lose or tie
return(r)
def instructions(name):
print("Welcome to Ultimate Ninja Combat!!!" + name)
print("You will be playing against the computer, and the winner gets bragging rights. Before each match you will have to place a bet which must be an amount which must be a multiple of 5. if you win you get that amount back from the computer. if you lose you lose the money. if your amount drops to zero you will be removed from the game")
print("you will start with 100 dollars use it wisely")
print("Each turn you will be asked to pick one of the following attacks")
print("(1)Fury Punch")
print("(2)Punishment kick")
print("(3)Sword of justice")
print("(4)Shuriken of Vengence")
print("(5)Numchucks of Anger")
print("(6)Knife of Freedom")
print("choose wisely")
print(" ")
print(" ")
print(" ")
def gameplay(balance):
while True:
print("Place your bet. Must be a multiple of 5")
posBets = range(5, (balance + 1), 5)
bet = str(input())
if bet == posBets:
print("You have bet $" + str(bet))
loop = 0
elif bet != posBets:
print("Please bet an amount that is a multiple of 5, or an amount that is within your balance")
print("Press enter to continue")
input()
loop = 1
if not(loop == 1):break #Exit loop
return(bet)
win = 1
lose = 2
tie = 3
r = win or lose or tie
print("Battle shall now commence")
print("Choose an attack")
print("The attacks you can use are as follows")
print("(1)Fury Punch")
print("(2)Punishment kick")
print("(3)Sword of justice")
print("(4)Shuriken of Vengence")
print("(5)Numchucks of Anger")
print("(6)Knife of Freedom")
attack = int(input())
while attack < 1 or attack > 6:
print("please input either: 1, 2, 3, 4, 5 or 6")
attack = int(input())
winLose(attack, win, lose, tie,)
if r == win:
newBalance = int(balance) + int(bet)
elif r == lose:
newBalance = int(balance) - int(bet)
else:
if r == tie:
balance = newBalance
print("Your Balance is $" + str(newBalance))
return(bet, newBalance)
def menu(name):
balance = 100
while True:
newBalance = balance
print("Your current balance is $" + str(balance))
print("Choose an option " + name)
print("(I)nstructions")
print("(P)lay game")
print("(Q)uit game")
print("Please Input I,P or Q")
menuChoice = input()
if menuChoice == "i" or menuChoice == "I":
instructions(name)
loop = 1
elif menuChoice == "p" or menuChoice == "P":
gameplay(balance)
loop = 1
print("Press enter to contiue")
enter = input()
elif menuChoice == "q" or menuChoice == "Q":
loop = 0
else:
print("I did not understand the response. Please Input I, P or Q")
print("Press enter to continue")
enter = input()
loop = 1
if not(loop == 1): break #Exit loop
return(menuChoice)
def main():
print("Welcome to Ultimate Ninja Combat!!! What is your name?")
name = input()
print ("Welcome " + name)
menu(name)
</code></pre>
<p>main() </p>
| -1 | 2016-10-17T12:29:25Z | 40,086,984 | <p>Your <code>bet = str(input())</code> converts the number into a string, which is why it can never equal the range. </p>
<p>Even if it was an int, a number cannot equal a range.</p>
<p>What you want is </p>
<pre><code> bet = int(input())
if bet in posBets:
</code></pre>
<p>the rest of the code seems full of errors to me: </p>
<ul>
<li><p>functions need to be indented when <code>def</code>ined</p></li>
<li><p>saying stuff like <code>r = win or lose or tie</code> after saying <code>win=1</code> <code>lose=2</code> <code>tie=3</code> is basically asking <code>r=1 or 2 or 3</code> which is always <code>1</code> because <code>1</code> evaluates as <code>True</code> and <code>or</code> stops as soon as it gets a <code>True</code> (just like <code>and</code> stops if it gets a <code>False</code>)</p></li>
</ul>
| 1 | 2016-10-17T12:55:48Z | [
"python",
"python-3.x"
] |
How to save/copy value of table column not listed in csv column list in vertica copy command | 40,086,452 | <p>I am using following code to copy data from csv to vertica table.</p>
<pre><code>copy_command = 'COPY cb.table_format2 (ACC_NO, REF_NO, CUSTOMER_NAME, ADDRESS) FROM STDIN '\
'ENCLOSED BY \'"\' delimiter \',\' SKIP 1 '\
'exceptions \'' + file_path_exception + '\' rejected data \'' + file_path_rejected + '\';'
with open(file_path, "rb") as inf:
cur.copy(copy_command, inf)
</code></pre>
<p>I have another field named 'FileId' in vertica table and i want to populate it with value of my local variable, so that i can check later that which data is entered against which fileId, and in my future requirements, i also want to save created on date and user session id in other columns too. </p>
<p>Please let me know how can i do this? Either even this is possible or not?
If this can't be done then what are other ways to make sure which data is saved/copied against which time stamp and user session?</p>
<p>Thanks for help in advance.</p>
<p>Update:-
I am using python 3 and vertica_python module to connect to vertica from python.</p>
| 1 | 2016-10-17T12:30:56Z | 40,086,880 | <p>You need to use <code>AS</code> to sql expressions to fields. You don't mention which python module you are using, but you can do it as a literal. Add in a new field entry that looks like: </p>
<pre><code>FILEID AS 123456
</code></pre>
<p>And just get your string to look that way (probably using a formatter, or a bind value). </p>
| 1 | 2016-10-17T12:51:37Z | [
"python",
"vertica"
] |
Using external class methods inside the imported module | 40,086,500 | <p>My python application consists of various <em>separate</em> processing algorithms/modules combined within a single (Py)Qt GUI for ease of access. </p>
<p>Every processing algorithm sits within its own module and all the communication with GUI elements is implemented within a single class in the main module.
In particular, this GUI class has a progressbar (<a href="http://pyqt.sourceforge.net/Docs/PyQt4/qprogressbar.html" rel="nofollow">QProgressBar</a>) object designed to represent the current processing progress of a chosen algorithm.
This object has <code>.setValue()</code> method (<code>self.dlg.progressBar.setValue(int)</code>).</p>
<p>The problem is that since <code>self.dlg.progressBar.setValue()</code> is a class method I cannot use it inside my imported processing modules <em>to report their progress state within their own code</em>. </p>
<p>The only workaround I found is to add <code>progressbar</code> variable to definition of each processing module, pass there <code>self.dlg.progressBar</code> inside the main module and then blindly call <code>progressbar.setValue(%some_processing_var%)</code> inside the processing module. </p>
<p>Is this the only way to use outer class methods inside imported modules or are there better ways? </p>
| 2 | 2016-10-17T12:33:18Z | 40,086,840 | <p>No. I think this approach somewhat breaks software engineering principles (e.g. <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow">single responsibility</a>). In single responsibility principle, each module is only in charge of its assigned task and nothing else. If we consider UI a separate layer, so your processing modules shouldn't have anything to do with the UI layer.</p>
<p>In this case, your modules should have a method called <code>publish_progress(callback)</code> which <code>callback</code> is a function to be called for each progress step (<a href="https://en.wikipedia.org/wiki/Callback_(computer_programming)" rel="nofollow">more info</a>). Then, in your UI layer define a function which is given an integer (between 0 to 100) and updates the progress bar. Once you've defined it, you should register it with <code>publish_progress</code> method of your modules.</p>
<pre><code>def progress_callback(prg):
self.dlg.progressBar.setValue(prg)
</code></pre>
<p>Registering it:</p>
<pre><code>my_module.publish_progress(progress_callback)
</code></pre>
<p>Calling the callback in your module:</p>
<pre><code>progress_callback(0)
...
# do something
...
progress_callback(20)
...
# do something
...
progress_callback(100)
</code></pre>
| 4 | 2016-10-17T12:49:47Z | [
"python",
"qt",
"class",
"module",
"pyqt"
] |
Retrieve Exchange Calendar event with Python & Suds | 40,086,507 | <p>I'm trying to retrieve Exchange calendar events in Python using the suds library.</p>
<p>I'm able to read FreeBusyResponse data, but I'm not successfull in retrieving the actual calendar event.</p>
<p>The soap requests seems fine:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:ns0="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:ns1="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<t:RequestServerVersion Version="Exchange2010_SP1"/>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:FindItem Traversal="Shallow">
<ns1:ItemShape>
<ns0:BaseShape>Default</ns0:BaseShape>
</ns1:ItemShape>
<ns1:CalendarView xsi:type="ns0:CalendarViewType" StartDate="2016-10-17T14:10:41.620151+01:00" EndDate="2016-10-17T14:10:41.620176+01:00"/>
<ns1:ParentFolderIds>
<ns0:DistinguishedFolderId xsi:type="ns0:DistinguishedFolderIdType" Id="calendar">
<ns0:Mailbox>
<ns0:EmailAddress>[email protected]</ns0:EmailAddress>
</ns0:Mailbox>
</ns0:DistinguishedFolderId>
</ns1:ParentFolderIds>
</ns1:FindItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>Relvant part in the code:</p>
<pre><code>find_item_request = client.factory.create('FindItemType')
shape_types = client.factory.create('ns1:DefaultShapeNamesType')
shape_type = client.factory.create('ns1:ItemResponseShapeType')
shape_type.BaseShape = 'Default'
find_item_request.ItemShape = shape_type
find_item_request._Traversal = 'Shallow'
mailbox = Element('ns1:Mailbox')
emailaddress = Element('ns1:EmailAddress').setText('[email protected]')
mailbox.append(emailaddress)
folder_id_type = client.factory.create('ns1:DistinguishedFolderId')
folder_id_type.Mailbox = mailbox
folder_id_type._Id = 'calendar'
folder_ids = client.factory.create('ns1:NonEmptyArrayOfBaseFolderIdsType')
folder_ids.DistinguishedFolderId = folder_id_type
find_item_request.ParentFolderIds = folder_ids
calendar_view = client.factory.create('ns1:CalendarViewType')
calendar_view._StartDate = start
calendar_view._EndDate = end
find_item_request.CalendarView = calendar_view
client.service.FindItem.method.soap.input.body.wrapped = False
try:
find_item_response = client.service.FindItem(find_item_request)
except WebFault as e:
raise e
msg = result.FindItemResponseMessage
</code></pre>
<p>Should I use something else than a CalendarView?</p>
| 0 | 2016-10-17T12:33:43Z | 40,094,046 | <p>I've found the following solution:</p>
<pre><code>import time
import datetime
import pytz
from suds.client import WebFault
from suds.client import Client
from suds.sax.element import Element
from suds.transport.http import HttpTransport
from suds.sudsobject import asdict
< auth and transport comes here >
# Todo: fix timezones displayed in suds output.
start = datetime.datetime.now(pytz.timezone('Europe/Brussels')).isoformat()
end = datetime.datetime.now(pytz.timezone('Europe/Brussels')).isoformat()
fi = client.factory.create('FindItem')
fi.ItemShape.BaseShape = 'AllProperties'
fi.ParentFolderIds.DistinguishedFolderId = client.factory.create('t:DistinguishedFolderIdType')
fi.ParentFolderIds.DistinguishedFolderId._Id = 'calendar'
fi._Traversal = 'Shallow'
calendar_view = client.factory.create('CalendarView')
calendar_view._StartDate = start
calendar_view._EndDate = end
fi.CalendarView = calendar_view
#client.service.FindItem.method.soap.input.body.wrapped = False
try:
response = client.service.FindItem(**asdict(fi))
print response
except WebFault as e:
raise e
</code></pre>
| 0 | 2016-10-17T19:18:57Z | [
"python",
"ews",
"exchangewebservices",
"suds"
] |
Convert python list of string to bytearray | 40,086,641 | <p>I would write a list on serial COM through pySerial.</p>
<p>I create a list of string, where each string is a parameter, and then I pass the list to serial write function. There is an error because I cannot write list of string directly on serial</p>
<p>This is my code:</p>
<pre><code>import datetime
import time
import sys
import serial
date = datetime.datetime.now()
dateStr = str(date.strftime('%d-%m-%Y'))
unixTime = int(time.time())
crc = str("1234")
packet = list()
packet.append('test')
packet.append(dateStr)
packet.append(unixTime)
packet.append('4')
packet.append('81')
packet.append('1')
packet.append('0')
packet.append('00.7')
packet.append('4')
packet.append('9')
packet.append('0')
packet.append('18.8')
packet.append('5')
packet.append('3')
packet.append('0')
packet.append('15.3')
packet.append('4')
packet.append('6')
packet.append('0')
packet.append('2')
packet.append('0')
packet.append('13')
packet.append('0')
packet.append('0')
packet.append('0')
packet.append('185.6')
# add semicolon between list elements
serialCOM.write(packet)
</code></pre>
<p>Is there a way to concatenate each list elements into a list or bytearray?</p>
<p>Furthermore I need to add a semicolon between each list elements.</p>
<p>Thanks for the help!</p>
| 0 | 2016-10-17T12:41:03Z | 40,086,942 | <p>If you want an actual bytearray object, pass the list into the bytearray constructor. </p>
<pre><code>serialCOM.write(bytearray(packet))
</code></pre>
<p>Note that <code>unixTime</code> is not converted to a string so you must convert that first.</p>
<p>But what you probably want (based on the comment about semicolons) is to just join the strings using the join method of a string like this:</p>
<pre><code># Force all items in the list to be strings
msg = ';'.join(map(str,packet))
serialCOM.write(msg)
</code></pre>
<p>The result of the join is then:</p>
<pre><code>In[50]: ';'.join(map(str,packet))
Out[50]: 'test;17-10-2016;1476708605;4;81;1;0;00.7;4;9;0;18.8;5;3;0;15.3;4;6;0;2;0;13;0;0;0;185.6'
</code></pre>
| 1 | 2016-10-17T12:54:05Z | [
"python",
"python-2.7",
"type-conversion",
"concatenation",
"pyserial"
] |
How to deal with 0 in modulo in python | 40,086,642 | <p>I want to create code that tells me what date it is based on how many hours passed.</p>
<p>I don't want to import any libraries I just want to calculate this myself. I want code to be flexible and work with whatever snodiy (simple number of days in year), nohiod (number of hours in one day) and number of months I'll give it. Only absolute is hour which will always be the same and have 60 minutes.</p>
<p>Code below works really well but the problem is that instead of 12 months I have 13 (0-12) and I don't know how to deal with 0 in most efficient manner. Example below. I have number of hours that gives me 0 days 0 months and correct year (2016).</p>
<pre><code>dev = True
# simple number of days in year
snodiy = 365.25
# number of hours in one day
nohiod = 24
# total hours passed
# 17672256 current year
thp = 17672257
dayc = 30 # number of days in a month #
# get date
def gd():
year = (thp / snodiy) / nohiod
rest = thp % (snodiy * nohiod)
if dev:
print("dev year rest:", rest)
month = rest / (dayc * nohiod)
rest %= (dayc * nohiod)
if dev:
print("dev month rest:", rest)
day = rest / nohiod
rest %= nohiod
if dev:
print("dev hour rest:", rest)
hour = rest
if dev:
print("Year:", "%d" % year)
print("Month:", "%d" % month)
print("Day:", "%d" % day)
print("Hour:", "%d" % hour)
print("Hour:", "%d" % hour, "of", "%d" % day, "%d" % month, "%d" % year)
gd()
</code></pre>
| -1 | 2016-10-17T12:41:04Z | 40,087,367 | <p><em>I'm going to assume we're not bound by all the constraints of real-world time issues like leap years, leap seconds, DST, etc. If we are, you're taking on an extremely non-trivial task, and as others have mentioned you're probably best off leaving it to libraries. Moving on...</em></p>
<p>The essence of the problem is your implicit assumption that a year is exactly 12 months. You define a year as <code>365.25 * 24 = 8766</code> hours long. You define a month as <code>30 * 24 = 720</code> hours long. 12 months would be <code>720 * 12 = 8640</code> hours. Your year is longer than 12 months, so it's not surprising you're getting a 13th month in your calculations.</p>
<p>You're overconstrained. You need to do one of three things:</p>
<ul>
<li><code>dayc = snodiy / 12</code></li>
<li><code>snodiy = dayc * 12</code></li>
<li>Accept (and be able to deal with) the fact that there are not exactly 12 months in a year.</li>
</ul>
| 1 | 2016-10-17T13:13:24Z | [
"python",
"modulo"
] |
Integrating Python with PingFederate | 40,086,684 | <p>Our application is written in python. I would like to integrate this with PingFederate. Is there any python library I can use for this purpose ?</p>
| -1 | 2016-10-17T12:42:37Z | 40,112,721 | <p>While there's no Python library commercially available from Ping Identity, there are a few options including using the PingFederate Agentless Integration Kit (<a href="https://documentation.pingidentity.com/display/AIK11/Introduction" rel="nofollow">https://documentation.pingidentity.com/display/AIK11/Introduction</a>), or a standards based protocol (like OpenID Connect - for which there are open source libraries).</p>
<p>The "right" choice requires further analysis based on the goal of your integration and the integration effort you wish to undertake. Ping Identity does have a more detailed guide that should help you: <a href="https://developer.pingidentity.com/en/resources/application-integration-overview.html" rel="nofollow">https://developer.pingidentity.com/en/resources/application-integration-overview.html</a></p>
| 1 | 2016-10-18T15:48:52Z | [
"python",
"ping",
"pingfederate"
] |
Importing identically named methods | 40,086,787 | <p>So I have two separate Python packages that I'm importing into my Python script for Raspberry Pi. In this case as;</p>
<pre><code>from rflib import*
from Rpi.GPIO import*
</code></pre>
<p>However, both packages have their own seperate method <code>cleanup(self)</code></p>
<p>So, at the end of the script when I use the command
<code>cleanup()</code>, how do I a) know which package the method is coming from (they both do utterly different things b) control which one is run?</p>
<p>I've looked into similarly named <a href="http://stackoverflow.com/questions/21482427/two-classes-with-a-structurally-identical-method-but-one-differently-named-varia">questions</a>, but which seem to deal with inheritance overloading rather than package imports</p>
| 1 | 2016-10-17T12:47:15Z | 40,086,866 | <p>It is not a good practice to use <code>*</code> with <code>import</code>. You should be doing something like:</p>
<pre><code>import rflib
from Rpi import GPIO
# Clean Up 1
rflib.cleanup
#Clean Up 2
GPIO.cleanup()
</code></pre>
<hr>
<p><em>Additional pice of information:</em> </p>
<p>In case your files/objects are of same name, in that case you should use <code>as</code> with <code>import</code>. For example:</p>
<pre><code> from file1 import utils as file1_utils
from file2 import utils as file2_utils
file1_utils.my_func()
file2_utils.my_func()
</code></pre>
| 2 | 2016-10-17T12:51:01Z | [
"python",
"python-import"
] |
Importing identically named methods | 40,086,787 | <p>So I have two separate Python packages that I'm importing into my Python script for Raspberry Pi. In this case as;</p>
<pre><code>from rflib import*
from Rpi.GPIO import*
</code></pre>
<p>However, both packages have their own seperate method <code>cleanup(self)</code></p>
<p>So, at the end of the script when I use the command
<code>cleanup()</code>, how do I a) know which package the method is coming from (they both do utterly different things b) control which one is run?</p>
<p>I've looked into similarly named <a href="http://stackoverflow.com/questions/21482427/two-classes-with-a-structurally-identical-method-but-one-differently-named-varia">questions</a>, but which seem to deal with inheritance overloading rather than package imports</p>
| 1 | 2016-10-17T12:47:15Z | 40,086,901 | <p><code>from <module> import *</code> takes all names in a module (those that don't start with a <code>_</code> or everything listed in <code><module>.__all__</code> and assigns those names as globals in your current module.</p>
<p>If two modules define the same name, that means that the last one imported this way wins; <code>cleanup = rflib.cleanup</code> is replaced by <code>cleanup = Rpi.GPIO.cleanup</code> with the second <code>from Rpi.GPIO import *</code> statement.</p>
<p>You generally want to <em>avoid</em> using <code>from <module> import *</code>. Import specific names, or just the module itself.</p>
<p>In this case, you can do:</p>
<pre><code>from rflib import cleanup as rflib_cleanup
from Rpi.GPIO import cleanup as rpigpio_cleanup
</code></pre>
<p>which would bind those two functions as <em>different</em> names.</p>
<p>Or you could just import the modules:</p>
<pre><code>import rflib
from Rpi import GPIO
</code></pre>
<p>which gives you only the <code>rflib</code> and <code>GPIO</code> names, each a reference to the module object, so now you can reference each of the <code>cleanup</code> functions as attributes on those modules:</p>
<pre><code>rflib.cleanup()
GPIO.cleanup()
</code></pre>
<p>If you need to use a lot of names from either module, the latter style is preferred because that limits the number of imports you need to do, keeps your namespace clean and un-cluttered, and gives you more context whereever those names are used in your code.</p>
| 5 | 2016-10-17T12:52:31Z | [
"python",
"python-import"
] |
How to check the language of any text present on Website using Selenium | 40,086,815 | <p>I am testing a website which contains user reviews for hotels which can be in any lang...i.e, Czech or russian or spanish or english etc... and have a question about how can i check in which language the text is by reading the text using Selenium. </p>
<p>for example i am using to element.text method of selenium to read the text, then i want to place a check if its in english then do this else for any other language do that.</p>
<p>This is one of the html element</p>
<pre><code><div class="innerBubble">
<div class="quote"><a href="/ShowUserReviews-g1-d8729164-r427772133-TAP_Portugal-World.html#CHECK_RATES_CONT" onclick="ta.setEvtCookie('Reviews','title','',0,this.href); setPID();" id="r427772133">â<span class="noQuotes">TRES SATISFAITS</span>â</a></div>
<div class="rating reviewItemInline">
<span class="rate sprite-rating_s rating_s"> <img class="sprite-rating_s_fill rating_s_fill s40" width="56" src="https://static.tacdn.com/img2/x.gif" alt="4 of 5 stars">
</span>
<span class="ratingDate relativeDate" title="October 13, 2016">Reviewed 3 days ago
<span class="new redesigned">NEW</span> </span>
</div>
<div class="googleTranslation reviewItem">
<span class="link" onclick="ta.call('ta.overlays.Factory.reviewTranslate', event, this, '/MachineTranslation?g=1&amp;d=8729164&amp;r=427772133&amp;page=review&amp;sl=fr&amp;tl=en'); ta.trackEventOnPage('Reviews', 'google_translate')">
<img alt="Google Translation" src="https://static.tacdn.com/img2/buttons/googleTranslation.gif">
</span>
</div>
<div class="entry">
<p>
Un peu d'appréhension avant mais vite levée. Très bon accueil et bon service de la part des pnc, repas chaud et bon, même pour ce court vol (1h50). Bonne ponctualité et embarquement des plus efficaces
</p>
</div>
</code></pre>
| 0 | 2016-10-17T12:48:27Z | 40,088,603 | <p>Detect a language it is not trivial unless the html tag put the current lang.</p>
<p>If you are using selenium in python you can use this function, for that you need to install nltk and the corpus stopwords:</p>
<pre><code>from nltk import word_tokenize
from nltk.corpus import stopwords
def detect_lang(text):
lang_ratios = {}
tokens = word_tokenize(text)
words = [word.lower() for word in tokens]
for language in stopwords.fileids():
stopwords_set = set(stopwords.words(language))
words_set = set(words)
common_elements = words_set.intersection(stopwords_set)
lang_ratios[language] = len(common_elements)
return max(lang_ratios, key=lang_ratios.get)
</code></pre>
<p>With this function you can ask for the lang used:</p>
<pre><code>lang = detect_lang(text)
if(lang == 'english'):
...
</code></pre>
| 0 | 2016-10-17T14:07:10Z | [
"python",
"selenium-webdriver"
] |
How to check the language of any text present on Website using Selenium | 40,086,815 | <p>I am testing a website which contains user reviews for hotels which can be in any lang...i.e, Czech or russian or spanish or english etc... and have a question about how can i check in which language the text is by reading the text using Selenium. </p>
<p>for example i am using to element.text method of selenium to read the text, then i want to place a check if its in english then do this else for any other language do that.</p>
<p>This is one of the html element</p>
<pre><code><div class="innerBubble">
<div class="quote"><a href="/ShowUserReviews-g1-d8729164-r427772133-TAP_Portugal-World.html#CHECK_RATES_CONT" onclick="ta.setEvtCookie('Reviews','title','',0,this.href); setPID();" id="r427772133">â<span class="noQuotes">TRES SATISFAITS</span>â</a></div>
<div class="rating reviewItemInline">
<span class="rate sprite-rating_s rating_s"> <img class="sprite-rating_s_fill rating_s_fill s40" width="56" src="https://static.tacdn.com/img2/x.gif" alt="4 of 5 stars">
</span>
<span class="ratingDate relativeDate" title="October 13, 2016">Reviewed 3 days ago
<span class="new redesigned">NEW</span> </span>
</div>
<div class="googleTranslation reviewItem">
<span class="link" onclick="ta.call('ta.overlays.Factory.reviewTranslate', event, this, '/MachineTranslation?g=1&amp;d=8729164&amp;r=427772133&amp;page=review&amp;sl=fr&amp;tl=en'); ta.trackEventOnPage('Reviews', 'google_translate')">
<img alt="Google Translation" src="https://static.tacdn.com/img2/buttons/googleTranslation.gif">
</span>
</div>
<div class="entry">
<p>
Un peu d'appréhension avant mais vite levée. Très bon accueil et bon service de la part des pnc, repas chaud et bon, même pour ce court vol (1h50). Bonne ponctualité et embarquement des plus efficaces
</p>
</div>
</code></pre>
| 0 | 2016-10-17T12:48:27Z | 40,089,095 | <p>Here Nothing to do with selenium driver just get the text and use the below code
If you need to detect language in response to a user action then you could use <a href="http://code.google.com/apis/language/translate/v1/using_rest_langdetect.html" rel="nofollow">google ajax language API</a>:</p>
<pre><code>#!/usr/bin/env python
import json
import urllib, urllib2
def detect_language(text,
userip=None,
referrer="http://stackoverflow.com/q/4545977/4279",
api_key=None):
query = {'q': text.encode('utf-8') if isinstance(text, unicode) else text}
if userip: query.update(userip=userip)
if api_key: query.update(key=api_key)
url = 'https://ajax.googleapis.com/ajax/services/language/detect?v=1.0&%s'%(
urllib.urlencode(query))
request = urllib2.Request(url, None, headers=dict(Referer=referrer))
d = json.load(urllib2.urlopen(request))
if d['responseStatus'] != 200 or u'error' in d['responseData']:
raise IOError(d)
return d['responseData']['language']
print detect_language("Python - can I detect unicode string language code?")
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>en
</code></pre>
| 0 | 2016-10-17T14:30:34Z | [
"python",
"selenium-webdriver"
] |
Is there a way to pin an exe in taskbar using python | 40,087,054 | <p>I'm extracting an zip folder contains an EXE file using python. Once extracted, I want to pin the EXE file to the task bar. Is there a way to do that using python?</p>
| 0 | 2016-10-17T12:58:39Z | 40,106,444 | <p><a href="https://blogs.msdn.microsoft.com/oldnewthing/20141230-00/?p=43273/" rel="nofollow">Programs aren't supposed to do this in the first place; there is no supported way to do it even with an installer, so Python isn't going to be any more supported. If you forcibly pin your program, <em>your program is a bad actor</em>.</a></p>
| 0 | 2016-10-18T11:00:47Z | [
"python",
"python-3.x"
] |
Getter and setter methods in a Peewee model | 40,087,094 | <p>I have the following simple model in Peewee:</p>
<pre><code>class SiteText(BaseModel):
url = TextField()
text = TextField()
my_counter = IntegerField()
def get_text_by_url(url):
d = [s.text for s in SiteText.select(SiteText.url == url)]
d = d[0] if len(d) > 0 else None
return d
def save_text(updates):
# updates is a dict containing, url, text, my_counter
SiteText.upsert(**updates)
def get_outage_counter(url):
c = [c.my_counter for c in SiteText.select(SiteText.url == url)]
c = c[0] if len(c) > 0 else None
return c
def set_outage_counter(url, counter):
c = SiteText.get(SiteText.url == url)
c.counter = counter
c.save()
</code></pre>
<p>However, it feels rather strange writing getters and setters for some of the attributes. Is there a more Pythonic way of doing this? Should I, for example, have a single method for getting and setting the outage counter for a specified URL? Should I convert the getter and setter functions to properties (though then they would clash with the actual attributes). Feedback welcome!</p>
| 0 | 2016-10-17T13:00:16Z | 40,087,382 | <p>Actualy using proporties wouldn't clash with your actual attribute name, because they can be different than the getter/setter function.</p>
<pre><code>class Example:
def __init__(self):
self.value = 5
@property
def value(self):
print('Entering value getter')
return self._value
@value.setter
def value(self, val):
print('Entering value setter')
self._value = val
</code></pre>
<p>Let say we have the class as above. You can see that the getter function is returning <code>_value</code> which might be strange for someone who would see that in <code>__init__</code> method there is only <code>self.value = 5</code> but not <code>self._value</code>.</p>
<p>Let say that we do this next:</p>
<pre><code>a = Example()
</code></pre>
<p>Just after instantiating the class object, <code>__init__</code> is calling the <code>value.setter</code> function due to <code>self.value = 5</code>, and because of that, we got:</p>
<pre><code>a = Example()
Entering value setter
print(a.value)
Entering value getter
5
print(a.__dict__)
{'_value': 5} # _value was created in setter function
</code></pre>
<p>So as you can see, u can use property that way and be fine with it.</p>
| 1 | 2016-10-17T13:14:15Z | [
"python",
"peewee"
] |
"LookupError: Couldn't find path to unrar library" on Win10 | 40,087,192 | <p>I have installed unrar library by using <code>pip install unrar</code>, which installed <code>unrar-0.3</code>.
After compiling my code using <code>unrar</code> library in <code>pydev-eclipse</code> I am getting the following error message:</p>
<pre><code>File "C:\Python27\lib\site-packages\unrar\unrarlib.py", line 57, in <module>
raise LookupError("Couldn't find path to unrar library.")
LookupError: Couldn't find path to unrar library.
</code></pre>
<p>I have looked over in <code>C:\Python27\lib\site-packages\unrar\unrarlib.py</code> and there its written:</p>
<pre><code>lib_path = os.environ.get('UNRAR_LIB_PATH', None)
# find and load unrar library
unrarlib = None
if platform.system() == 'Windows':
from ctypes.wintypes import HANDLE as WIN_HANDLE
HANDLE = WIN_HANDLE
UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint,
ctypes.c_long, ctypes.c_long,
ctypes.c_long)
lib_path = lib_path or find_library("unrar.dll")
if lib_path:
unrarlib = ctypes.WinDLL(lib_path)
else:
# assume unix
</code></pre>
<p>I cannot find the <code>unrar.dll</code> anywhere. Whereas the installation is done correctly. I don't know how to fix it. On my previous computer(win7 platform), it was working without any errors.</p>
| 0 | 2016-10-17T13:04:31Z | 40,087,566 | <p>You should download the UnRAR.dll Library from <a href="http://www.rarlab.com/rar/UnRARDLL.exe" rel="nofollow">http://www.rarlab.com/rar/UnRARDLL.exe</a> and extract it anywhere in your PATH</p>
<p>Edit: You should set the UNRAR_LIB_PATH environment variable with the location of unrar.dll</p>
<p>Edit2: As a last resort:</p>
<ol>
<li>extract <code>UnRARDLL.exe</code> into <code>C:\Program Files (x86)\UnrarDLL\</code></li>
<li>if you're using Python2.7 64bit, select <code>UnRAR64.dll</code> and <code>UnRAR64.lib</code> files from <code>C:\Program Files (x86)\UnrarDLL\x64</code> and rename them to <code>unrar.dll</code> and <code>unrar.lib</code></li>
<li>copy them in <code>C:\Windows\System32</code>.</li>
<li>if you're using a 32bit version of python, simply copy unrar.dll and unrar.lib from <code>C:\Program Files (x86)\UnrarDLL\</code> to <code>C:\Windows\System32</code></li>
</ol>
| 0 | 2016-10-17T13:22:16Z | [
"python",
"eclipse",
"python-2.7",
"rar",
"unrar"
] |
String manipulation in Python: Quotation marks and apostrophes | 40,087,232 | <p>So I'm having this issue with python: I'm trying to create a string I can use for a gdal operation using os.system on python. My aim is using this operation for a variable number of inputfiles:</p>
<pre><code>os.system('gdal_calc.py -A {0} -B {1} -C {2} --outfile={4} --calc="(1-A)(1-B)(1-C)" '.format(File1, File2, File3, outputfile))
</code></pre>
<p>So here's how my function looked like:</p>
<pre><code>def Mergefilesforoperation(Inputfiles= None):
ABC = ["A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
partstring = []
for i in range(len(Inputfiles)-1):
partstring.append(" -" + ABC[i] + " '" + Inputfiles[i] + "'")
wholestring = "".join(partstring)
outputfile = 'outputfile.tif'
operationstring = "gdal_calc.py" + wholestring + " --outfile= {0}".format(outputfile) + ' --calc="(1-A)*(1-B)*(1-C)*(1-D)"'
return wholestring, operationstring
</code></pre>
<p>But when I return the fuction with: </p>
<pre><code>File1 = '/home/File1.tif' File2 = '/home/File2.tif' File3 = '/home/File3.tif'
Mergefilesforoperation(Inputfiles=[File1, File2, File3])
</code></pre>
<p>it gives me the following output:</p>
<pre><code>Wholestring = " -A '/home/File1.tif' -B '/home/File2.tif' -C '/home/File3.tif'"
operationstring = 'gdal_calc.py -A \'/home/File1.tif\' -B \'/home/File2.tif\' -C \'/home/File3.tif\' --outfile= outputfile.tif --calc="(1-A)(1-B)(1-C)"')
</code></pre>
<p>how do I get rid of the \ sign after the alphabet in "operationstring"?</p>
| 1 | 2016-10-17T13:07:04Z | 40,087,887 | <p>Do it:</p>
<pre><code>String = ""
for i in range(len(Inputfiles)-1):
String +=" -" + ABC[i] + " '" + Inputfiles[i] + "'"
</code></pre>
<p>Instead of:</p>
<pre><code> for i in range(len(Inputfiles)-1):
partstring.append(" -" + ABC[i] + " '" + Inputfiles[i] + "'")
</code></pre>
<p>And pay attetion with quotes, we can mix quotes but it is so clear to follow a method.</p>
<p>operationstring = "gdal_calc.py" + wholestring + " --outfile= {0}".format(outputfile) + ' --calc="(1-A)<em>(1-B)</em>(1-C)*(1-D)"'</p>
<p>operationstring = "gdal_calc.py" + wholestring + " --outfile= {0}".format(outputfile) + <strong>"</strong> --calc=<strong>'</strong>(1-A)<em>(1-B)</em>(1-C)*(1-D)<strong>'</strong> <strong>"</strong></p>
<p>With this changes it may work. I tried it.</p>
| 0 | 2016-10-17T13:35:46Z | [
"python",
"string",
"operating-system"
] |
String manipulation in Python: Quotation marks and apostrophes | 40,087,232 | <p>So I'm having this issue with python: I'm trying to create a string I can use for a gdal operation using os.system on python. My aim is using this operation for a variable number of inputfiles:</p>
<pre><code>os.system('gdal_calc.py -A {0} -B {1} -C {2} --outfile={4} --calc="(1-A)(1-B)(1-C)" '.format(File1, File2, File3, outputfile))
</code></pre>
<p>So here's how my function looked like:</p>
<pre><code>def Mergefilesforoperation(Inputfiles= None):
ABC = ["A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
partstring = []
for i in range(len(Inputfiles)-1):
partstring.append(" -" + ABC[i] + " '" + Inputfiles[i] + "'")
wholestring = "".join(partstring)
outputfile = 'outputfile.tif'
operationstring = "gdal_calc.py" + wholestring + " --outfile= {0}".format(outputfile) + ' --calc="(1-A)*(1-B)*(1-C)*(1-D)"'
return wholestring, operationstring
</code></pre>
<p>But when I return the fuction with: </p>
<pre><code>File1 = '/home/File1.tif' File2 = '/home/File2.tif' File3 = '/home/File3.tif'
Mergefilesforoperation(Inputfiles=[File1, File2, File3])
</code></pre>
<p>it gives me the following output:</p>
<pre><code>Wholestring = " -A '/home/File1.tif' -B '/home/File2.tif' -C '/home/File3.tif'"
operationstring = 'gdal_calc.py -A \'/home/File1.tif\' -B \'/home/File2.tif\' -C \'/home/File3.tif\' --outfile= outputfile.tif --calc="(1-A)(1-B)(1-C)"')
</code></pre>
<p>how do I get rid of the \ sign after the alphabet in "operationstring"?</p>
| 1 | 2016-10-17T13:07:04Z | 40,088,278 | <p>For this to work you will have to enclose double quote inside single quote and not other way around.</p>
<p>Though in most of the scenarios both of then should have identical impact but this is one of the corner scenario where it matters Its because of the ways string are represented internally in Python. </p>
<pre><code>>>> os.system('dir "C:\\Program Files"')
Volume in drive C has no label.
Volume Serial Number is 26BC-5144
Directory of C:\Program Files
03-10-2016 12:41 <DIR> .
03-10-2016 12:41 <DIR> ..
18-07-2016 12:29 <DIR> Bonjour
>>> os.system("dir 'C:\\Program Files'")
The filename, directory name, or volume label syntax is incorrect.
1
</code></pre>
<p>Also notice the difference how the strings are represented internally</p>
<pre><code>>>> a
"dir 'C:\\Program Files'"
>>> a.__repr__()
'"dir \'C:\\\\Program Files\'"'
>>> a = 'dir "C:\\Program Files"'
>>> a.__repr__()
'\'dir "C:\\\\Program Files"\''
</code></pre>
| 0 | 2016-10-17T13:53:34Z | [
"python",
"string",
"operating-system"
] |
Importing error in python package skimage | 40,087,362 | <p>I want to use <strong>skimage.restoration.denoise_wavelet</strong> to denoise a image. But problem occurs on importing.</p>
<p><code>from skimage.restoration import denoise_nl_means,denoise_wavelet</code> </p>
<p><code>ImportError Traceback (most recent call last)
<ipython-input-2-161a32d32528> in <module>()
----> 1 from skimage.restoration import denoise_nl_means,denoise_wavelet
ImportError: cannot import name denoise_wavelet</code></p>
<p>There is no problem in importing <strong>denoise_nl_means</strong> which is in the same category with <strong>denoise_wavelet</strong>. It doesn't make sense. </p>
<p>I used <strong>pip</strong> for installing and updating the skimage package and <strong>jupyter notebook</strong> for coding.
I installed all requirements before installing scikit-image 0.12.3. The requirement items I installed were:</p>
<p><code>matplotlib 1.5.1,numpy 1.11.1,scipy 0.18.1,six 1.10.0,networkx 1.11,pillow 3.4.1,dask 0.10.0,PyWavelets 0.4.0</code>.</p>
| 0 | 2016-10-17T13:13:04Z | 40,087,546 | <p>As you installed this library with pip, it probably installed the latest stable release, which is something within the <strong>0.12</strong> branch.</p>
<p>There are different documentations for different versions of scikit-learn.
<strong>The function</strong> which you want to import <strong>does not exist yet in any stable branch</strong> if we interpret the following correctly:</p>
<p><a href="http://scikit-image.org/docs/dev/search.html?q=denoise_wavelet&check_keywords=yes&area=default" rel="nofollow">Search for function-name in docs of development-branch</a>: OK!</p>
<p><a href="http://scikit-image.org/docs/0.12.x/search.html?q=denoise_wavelet&check_keywords=yes&area=default" rel="nofollow">Search for function-name in docs of 0.12 branch</a> No hits!</p>
<p>Sadly, the docs of scikit-image do not say when a function was added to the library (as done by scipy).</p>
<p>Further analysis can be done on <a href="https://github.com/scikit-image/scikit-image/blame/2f71b5787662ce7589bb878c55359cd076f84c83/skimage/restoration/_denoise.py" rel="nofollow">github + blame here</a>.</p>
<p>So if you need this function, grab the development-branch and install from sources! Always read the corresponding doc-versions!</p>
| 0 | 2016-10-17T13:21:36Z | [
"python",
"image-processing",
"filter",
"wavelet",
"skimage"
] |
Python JSON List to Get Data and Retrieve Column Name | 40,087,376 | <p>I am a newbie and can't find the answer so apologies in advance if this is a repeat question.</p>
<p>I'm accessing a historical metal prices api that returns a dictionary of lists. The first item in the list is the column names, and the rest is data that falls under those column headers.</p>
<p>I'm trying to write code that will return the Date and Cash Buyer values for all dates on record.</p>
<p>Here's what I've written so far. I've tried several dictionary and list methods and have not been able to get this to work. I'm sure it's me.</p>
<p>The URL is purposefully restricted to 1 row (rows=1) for this posting and stripped of my API key. However, this URL will work for anyone but is rate limited without an API key:</p>
<pre><code>import urllib
import json
url = "https://www.quandl.com/api/v1/datasets/LME/PR_CU.json?rows=1"
response = urllib.urlopen(url)
data = json.loads(response.read())
</code></pre>
<p>Here's a sample output as is:</p>
<pre><code>{
"code": "PR_CU",
"column_names": [
"Date",
"Cash Buyer",
"Cash Seller & Settlement",
"3-months Buyer",
"3-months Seller",
"15-months Buyer",
"15-months Seller",
"Dec 1 Buyer",
"Dec 1 Seller",
"Dec 2 Buyer",
"Dec 2 Seller",
"Dec 3 Buyer",
"Dec 3 Seller"
],
"data": [
[
"2016-10-14",
4672.0,
4672.5,
4691.0,
4692.0,
4730.0,
4740.0,
null,
null,
null,
null,
null,
null
]
],
"description": "LME Official Prices i
"display_url": null,
"errors": {},
"frequency": "daily",
"from_date": "2012-01-03",
"id": 19701916,
"name": "Copper Prices",
"premium": false,
"private": false,
"source_code": "LME",
"source_name": "London Metal Exchange"
"to_date": "2016-10-14",
"type": null,
"updated_at": "2016-10-17T07:05:00.54
"urlize_name": "Copper-Prices"
}
</code></pre>
<p>Thanks for your help in advance,
Me</p>
| 0 | 2016-10-17T13:13:49Z | 40,088,349 | <p>One way would be to get the position of 'Date' and 'Cache Buyer' columns, and then iterate through the <em>data</em> part of the JSON. </p>
<p>I will name the dictionary that you loaded from the JSON as dictionary in my example:</p>
<pre><code># Get the columns and the data part of the response dictionary
columns = dictionary['column_names']
data = dictionary['data']
# This is done in case that the columns are not always in the same order
# if they are, you can just hardcode the values to 0 and 1
index_of_date = columns.index('Date')
index_of_cash_buyer = columns.index('Cash Buyer')
# As data section is a list of lists we need to
# iterate through lists of data and collect the desired values
for piece_of_data in data:
date = piece_of_data[index_of_date]
cash_buyer = piece_of_data[index_of_cash_buyer]
print date, cash_buyer
</code></pre>
| 1 | 2016-10-17T13:56:55Z | [
"python",
"json",
"python-2.7",
"web-services",
"getjson"
] |
Python list integrateUpper/Lowercase check? | 40,087,556 | <p>I currently use following code to select rows from a dataframe:</p>
<pre><code>list = ['3d block','3D Block','3D block','3d Block','cafe','Cafe']
data[data['description'].str.contains('|'.join(list))]
</code></pre>
<p>As you can see, I currently implement different queries for upper/lowercase, as I realized that '3d print' didn't really match all the items in question.</p>
<p>Can the code above be improved or shortened, so that the list includes all possible variations of upper/lowercase characters, both for one and two words?</p>
| 1 | 2016-10-17T13:21:57Z | 40,087,594 | <p>You can simply convert them all to lower using the <code>string.lower()</code> function</p>
<p>Make your list contain only lower case characters. But you can do a safe check for that too</p>
<pre><code>my_list=['3d block', 'cafe']
# As karthik suggested, just to be safe, convert your list to lowercase
for i in range(len(my_list)):
my_list[i]=ele.lower()
my_query='3D bLoCk'
if my_query.lower() in my_list:
print('yes')
</code></pre>
<p>prints <code>yes</code></p>
| 2 | 2016-10-17T13:23:17Z | [
"python",
"list",
"uppercase",
"lowercase"
] |
Python list integrateUpper/Lowercase check? | 40,087,556 | <p>I currently use following code to select rows from a dataframe:</p>
<pre><code>list = ['3d block','3D Block','3D block','3d Block','cafe','Cafe']
data[data['description'].str.contains('|'.join(list))]
</code></pre>
<p>As you can see, I currently implement different queries for upper/lowercase, as I realized that '3d print' didn't really match all the items in question.</p>
<p>Can the code above be improved or shortened, so that the list includes all possible variations of upper/lowercase characters, both for one and two words?</p>
| 1 | 2016-10-17T13:21:57Z | 40,087,719 | <p>You can do a <em>case InSeNsitIvE</em> selection by passing the <code>case</code> parameter as <code>False</code>:</p>
<pre><code>lst = ['3D Block', 'cafe']
data[data['description'].str.contains('|'.join(lst), case=False)]
</code></pre>
<p>And remember to not use <code>list</code> as a name as this will shadow the builtin <code>list</code> function, and make it unusable later in your code.</p>
<hr>
<p>Reference:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.Series.str.contains.html" rel="nofollow">pandas.Series.str.contains</a></p>
| 2 | 2016-10-17T13:28:59Z | [
"python",
"list",
"uppercase",
"lowercase"
] |
Numpy array size is shrinking, changing randomly. Index out of bounds error | 40,087,573 | <p>I am making a large, 3-column 10,000 row array and filling it with random numbers. Then, I am indexing through the rows and deleting rows that don't match my criteria. For some reason, as I index through I get the following error:
<code>Traceback (most recent call last):
File "hw_2.py", line 16, in <module>
if math.sqrt(cube[y,0]**(2) + cube[y,1]**(2) + cube[y,2]**(2)) > 1:
IndexError: index 6786 is out of bounds for axis 0 with size 6786</code></p>
<p>My code is the following:</p>
<pre><code> import numpy as np
import math
#Create a large empty array that can be filled with random numbers
cube=np.empty([10000,3]);
#Fill the array with 1x3 (x,y,z) randos in a 1x1 cube
for x in xrange(0,10000):
cube[x] = np.random.uniform(-1,1,3)
#Consider each coordinate as a vector from the origin; reject all sets of x,y,z vectors whose magnitudes are greater than the radius of the sphere
for y in xrange(0,10000):
if math.sqrt(cube[y,0]**(2) + cube[y,1]**(2) + cube[y,2]**(2)) > 1:
cube = np.delete(cube, (y), axis=0)
#Reject all sets of vectors whose x,y components lay in a circle in the x,y plane of radius 0.25
for i in xrange(0,10000):
if cube[i,0] > 0 and cube[i,0]**(2) + cube[i,1]**(2) <= 0.25:
cube = np.delete(cube, (i), axis=0)
#Report the average of all coordinates in each plane, this will be the location of the center of mass
centermass = np.mean(cube, axis=0)`
</code></pre>
<p>I don't understand why the size of the axis would be less than 10,000 at this point, all 10,000 rows should be filled by the second command.</p>
| 0 | 2016-10-17T13:22:32Z | 40,088,017 | <p>So you're trying to select certain parts of the array, it seems. There's typically no need to do <code>np.delete</code>, you can use boolean masks instead: </p>
<pre><code>In [34]: np.random.seed(1234)
In [35]: cube = np.random.uniform(-1, 1, size=10000*3).reshape(10000, 3)
In [36]: mask = (cube**2).sum(axis=1) > 0.5
In [37]: mask.shape
Out[37]: (10000,)
In [38]: cube[~mask].shape
Out[38]: (1812, 3)
In [39]: np.mean(cube[~mask], axis=0)
Out[39]: array([ 1.39564967e-07, -2.78051170e-03, -1.13108653e-03])
</code></pre>
| 0 | 2016-10-17T13:41:29Z | [
"python",
"arrays",
"numpy",
"indexing"
] |
Mute printing of an imported Python script | 40,087,681 | <p>I want to import a python script in to another script. </p>
<pre><code>$ cat py1.py
test=("hi", "hello")
print test[0]
$ cat py2.py
from py1 import test
print test
</code></pre>
<p>If I execute <code>py2.py</code>:</p>
<pre><code>$ python py2.py
hi
('hi', 'hello')
</code></pre>
<p>Can I anyway mute the first <code>print</code> which is coming from the <code>from py1 import test</code>?</p>
<p>I can't comment the <code>print</code> in <code>py1</code>, since it is being used somewhere else. </p>
| 2 | 2016-10-17T13:27:02Z | 40,087,743 | <p>Simply open the /dev/null device and overwrite the <code>sys.stdout</code> variable to that value when you need it to be quiet.</p>
<pre><code>import os
import sys
old_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
from py1 import test
sys.stdout = old_stdout
print test
</code></pre>
| 3 | 2016-10-17T13:29:54Z | [
"python"
] |
Mute printing of an imported Python script | 40,087,681 | <p>I want to import a python script in to another script. </p>
<pre><code>$ cat py1.py
test=("hi", "hello")
print test[0]
$ cat py2.py
from py1 import test
print test
</code></pre>
<p>If I execute <code>py2.py</code>:</p>
<pre><code>$ python py2.py
hi
('hi', 'hello')
</code></pre>
<p>Can I anyway mute the first <code>print</code> which is coming from the <code>from py1 import test</code>?</p>
<p>I can't comment the <code>print</code> in <code>py1</code>, since it is being used somewhere else. </p>
| 2 | 2016-10-17T13:27:02Z | 40,087,752 | <p>py1.py use an <code>if __name__=="__main__":</code></p>
<p>So like your py1.py would look like: </p>
<pre><code>def main():
test=("hi", "hello")
print test[0]
if __name__=="__main__":
main()
</code></pre>
<p>This will allow you to still use py1.py normally, but when you import it, it won't run the <code>main()</code> function unless you call it.</p>
<p><a href="https://docs.python.org/3/library/__main__.html" rel="nofollow">This explains what's going on</a></p>
| 5 | 2016-10-17T13:30:23Z | [
"python"
] |
Mute printing of an imported Python script | 40,087,681 | <p>I want to import a python script in to another script. </p>
<pre><code>$ cat py1.py
test=("hi", "hello")
print test[0]
$ cat py2.py
from py1 import test
print test
</code></pre>
<p>If I execute <code>py2.py</code>:</p>
<pre><code>$ python py2.py
hi
('hi', 'hello')
</code></pre>
<p>Can I anyway mute the first <code>print</code> which is coming from the <code>from py1 import test</code>?</p>
<p>I can't comment the <code>print</code> in <code>py1</code>, since it is being used somewhere else. </p>
| 2 | 2016-10-17T13:27:02Z | 40,087,778 | <p>You might want to consider changing the other script to still print when its run 'in the other place' - if you're running py1 as a shell command, try to make sure all "executable statements" in a file are inside a block.</p>
<pre><code>if __name__ == "__main__":
print test
</code></pre>
<p>(see <a href="http://stackoverflow.com/questions/419163/what-does-if-name-main-do">What does `if __name__ == "__main__":` do?</a>)</p>
<p>This would fix the underlying issue without having you do weird things (which would be redirecting the standard out, and then putting it back etc), or opening the file and executing line by line on an if block.</p>
| 0 | 2016-10-17T13:31:31Z | [
"python"
] |
Mute printing of an imported Python script | 40,087,681 | <p>I want to import a python script in to another script. </p>
<pre><code>$ cat py1.py
test=("hi", "hello")
print test[0]
$ cat py2.py
from py1 import test
print test
</code></pre>
<p>If I execute <code>py2.py</code>:</p>
<pre><code>$ python py2.py
hi
('hi', 'hello')
</code></pre>
<p>Can I anyway mute the first <code>print</code> which is coming from the <code>from py1 import test</code>?</p>
<p>I can't comment the <code>print</code> in <code>py1</code>, since it is being used somewhere else. </p>
| 2 | 2016-10-17T13:27:02Z | 40,087,816 | <p>You could implement this functionality with methods:</p>
<p><code>py1.py</code></p>
<pre><code>test=("hi", "hello")
def print_test():
print(test)
def print_first_index():
print(test[0])
</code></pre>
<p><code>py2.py</code></p>
<pre><code>import py1
py1.print_test()
</code></pre>
<p>As MooingRawr pointed out, this would require you to change whichever classes use <code>py1.py</code> to import it and call the <code>py1.print_first_index()</code> function which may not be to your liking.</p>
| 0 | 2016-10-17T13:33:13Z | [
"python"
] |
How to convert nested list to object | 40,087,800 | <p>When I receive JSON data like </p>
<pre><code>[
{
"id":1,
"name":"New Island",
"residents":[
{
"name":"Paul",
"age":"25"
}
]
},
{
"id":2,
"name":"One Nation",
"residents":[
{
"name":"James",
"age":"23"
},
{
"name":"Jessica",
"age":"26"
}
]
}
]
</code></pre>
<p>drf deserializer makes it to list which contain OrderedDict</p>
<p>But I want to make it to list of class object.</p>
<p>Here are my django models</p>
<pre><code>class Country(models.Model):
name = models.CharField(max_length=20)
class Resident(models.Model):
name = models.CharField(max_length=20)
country = models.ForeignKey('Country', related_name='residents')
</code></pre>
| 0 | 2016-10-17T13:32:40Z | 40,088,045 | <p>Override the serializer methods that control transformation from primitive to internal <a href="http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior" rel="nofollow">http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior</a></p>
| 0 | 2016-10-17T13:42:45Z | [
"python",
"django",
"django-rest-framework"
] |
How to convert nested list to object | 40,087,800 | <p>When I receive JSON data like </p>
<pre><code>[
{
"id":1,
"name":"New Island",
"residents":[
{
"name":"Paul",
"age":"25"
}
]
},
{
"id":2,
"name":"One Nation",
"residents":[
{
"name":"James",
"age":"23"
},
{
"name":"Jessica",
"age":"26"
}
]
}
]
</code></pre>
<p>drf deserializer makes it to list which contain OrderedDict</p>
<p>But I want to make it to list of class object.</p>
<p>Here are my django models</p>
<pre><code>class Country(models.Model):
name = models.CharField(max_length=20)
class Resident(models.Model):
name = models.CharField(max_length=20)
country = models.ForeignKey('Country', related_name='residents')
</code></pre>
| 0 | 2016-10-17T13:32:40Z | 40,088,119 | <p>From Python's <a href="https://docs.python.org/3.5/library/json.html" rel="nofollow">JSON library</a></p>
<pre><code>import json
data = '[{"id":1,"name":"New Island","residents":[{"name":"Paul","age":"25"}]},{"id":2,"name":"One Nation","residents":[{"name":"James","age":"23"},{"name":"Jessica","age":"26"}]}]'
x = json.loads(data)
for each_set in x:
for every_person in each_set["residents"]:
print(every_person["name"]) #getting resident's name
print(every_person["age"]) #getting age
print(each_set["name"]) #getting the country name
</code></pre>
<p>From there it's as easy as passing in the proper parameters to classes like</p>
| 1 | 2016-10-17T13:46:35Z | [
"python",
"django",
"django-rest-framework"
] |
Docker container and virtual python environment | 40,087,910 | <p>I'm getting started working with Docker. I installed Docker Toolbox on Windows 10 and downloaded the desired container. I need full access to containerâs filesystem with the ability to add and edit files. Can I transfer the contents of the container into a Virtual Python Environment in Windows filesystem? How to do it?</p>
| 1 | 2016-10-17T13:36:57Z | 40,097,954 | <p>Transferring files between Windows and Linux might be a little annoying because of <a href="https://blog.codinghorror.com/the-great-newline-schism/" rel="nofollow">different line endings</a>.</p>
<p>Putting that aside, sounds like you are looking to create a Docker based development environment. There are good tutorials online that walk you through setting one up, I would start with one of these</p>
<ol>
<li><a href="https://blog.codeship.com/running-rails-development-environment-docker/" rel="nofollow">Running a Rails Development Environment in Docker</a>. This one is about Rails, but the principles will be the same. Section 3 specifically talks about about sharing code between your host machine and the Docker container.</li>
<li><a href="https://www.digitalocean.com/community/tutorials/how-to-work-with-docker-data-volumes-on-ubuntu-14-04" rel="nofollow">How To Work with Docker Data Volumes on Ubuntu 14.04</a> includes an brief introduction to Docker containers, different use cases for <a href="https://docs.docker.com/engine/tutorials/dockervolumes/" rel="nofollow">data volumes</a>, and how to get each one working. <em>Sharing Data Between the Host and the Docker Container</em> section talks about what you are trying to do. This example talks about reading log files created inside the container, but the principle is the same for adding/updating files in the container.</li>
</ol>
| 0 | 2016-10-18T01:09:14Z | [
"python",
"docker"
] |
Open cv face recognition python | 40,087,957 | <p>I started learning some object recognition and I'm interested in <code>openCV</code>. First of all, I tried the tutorial where your face is recognized. I installed numPy and <code>openCV</code>. When I tried running the program below, I received this error: </p>
<blockquote>
<p>File "path to my program\camera.py", line 4, in
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cv2.error:
D:\Build\OpenCV\opencv-3.1.0\modules\core\src\persistence.cpp:2220:
error: (-212) haarcascade_frontalface_default.xml(1): Valid XML should
start with '' in function icvXMLParse</p>
</blockquote>
<p>I was trying to find the answer to this question everywhere but I failed. I found a lot of other people had this problem, but the solutions didn't work. I tried re-installing python, installing a different <code>openCV</code> etc.</p>
<p>My code is here: </p>
<pre><code>import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p>I will be grateful for any help.</p>
<p>P.S.: My <code>xml</code> program starts with <code><?xml...?></code></p>
| 0 | 2016-10-17T13:38:51Z | 40,088,784 | <p>I just tried it out and I didn't get the error. If I intentionally mess up one or both of the files I get that error, but not the ones directly from the github project. These are the first ten lines of each file for me:</p>
<pre><code>$ head haarcascade_*.xml
==> haarcascade_eye.xml <==
<?xml version="1.0"?>
<!--
Stump-based 20x20 frontal eye detector.
Created by Shameem Hameed (http://umich.edu/~shameem)
////////////////////////////////////////////////////////////////////////////////////////
IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
By downloading, copying, installing or using the software you agree to this license.
==> haarcascade_frontalface_default.xml <==
<?xml version="1.0"?>
<!--
Stump-based 24x24 discrete(?) adaboost frontal face detector.
Created by Rainer Lienhart.
////////////////////////////////////////////////////////////////////////////////////////
IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
By downloading, copying, installing or using the software you agree to this license.
</code></pre>
<p>What does <code>head haarcascade_*.xml</code> output for you? If yours look the same as mine, is there a chance some odd control characters or something got into your file? Try <code>head haarcascade_frontalface_default.xml | hexdump -C</code> to see the exact bytes at the beginning of the file. For me, it outputs:</p>
<pre><code>00000000 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 |<?xml version="1|
00000010 2e 30 22 3f 3e 0a 3c 21 2d 2d 0a 20 20 20 20 53 |.0"?>.<!--. S|
00000020 74 75 6d 70 2d 62 61 73 65 64 20 32 34 78 32 34 |tump-based 24x24|
00000030 20 64 69 73 63 72 65 74 65 28 3f 29 20 61 64 61 | discrete(?) ada|
00000040 62 6f 6f 73 74 20 66 72 6f 6e 74 61 6c 20 66 61 |boost frontal fa|
00000050 63 65 20 64 65 74 65 63 74 6f 72 2e 0a 20 20 20 |ce detector.. |
00000060 20 43 72 65 61 74 65 64 20 62 79 20 52 61 69 6e | Created by Rain|
00000070 65 72 20 4c 69 65 6e 68 61 72 74 2e 0a 0a 2f 2f |er Lienhart...//|
00000080 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f 2f |////////////////|
*
000000d0 2f 2f 2f 2f 2f 2f 0a 0a 20 20 49 4d 50 4f 52 54 |//////.. IMPORT|
000000e0 41 4e 54 3a 20 52 45 41 44 20 42 45 46 4f 52 45 |ANT: READ BEFORE|
000000f0 20 44 4f 57 4e 4c 4f 41 44 49 4e 47 2c 20 43 4f | DOWNLOADING, CO|
00000100 50 59 49 4e 47 2c 20 49 4e 53 54 41 4c 4c 49 4e |PYING, INSTALLIN|
00000110 47 20 4f 52 20 55 53 49 4e 47 2e 0a 0a 20 20 42 |G OR USING... B|
00000120 79 20 64 6f 77 6e 6c 6f 61 64 69 6e 67 2c 20 63 |y downloading, c|
00000130 6f 70 79 69 6e 67 2c 20 69 6e 73 74 61 6c 6c 69 |opying, installi|
00000140 6e 67 20 6f 72 20 75 73 69 6e 67 20 74 68 65 20 |ng or using the |
00000150 73 6f 66 74 77 61 72 65 20 79 6f 75 20 61 67 72 |software you agr|
00000160 65 65 20 74 6f 20 74 68 69 73 20 6c 69 63 65 6e |ee to this licen|
00000170 73 65 2e 0a |se..|
00000174
</code></pre>
| 0 | 2016-10-17T14:15:43Z | [
"python",
"xml",
"opencv",
"face-recognition"
] |
Open cv face recognition python | 40,087,957 | <p>I started learning some object recognition and I'm interested in <code>openCV</code>. First of all, I tried the tutorial where your face is recognized. I installed numPy and <code>openCV</code>. When I tried running the program below, I received this error: </p>
<blockquote>
<p>File "path to my program\camera.py", line 4, in
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cv2.error:
D:\Build\OpenCV\opencv-3.1.0\modules\core\src\persistence.cpp:2220:
error: (-212) haarcascade_frontalface_default.xml(1): Valid XML should
start with '' in function icvXMLParse</p>
</blockquote>
<p>I was trying to find the answer to this question everywhere but I failed. I found a lot of other people had this problem, but the solutions didn't work. I tried re-installing python, installing a different <code>openCV</code> etc.</p>
<p>My code is here: </p>
<pre><code>import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p>I will be grateful for any help.</p>
<p>P.S.: My <code>xml</code> program starts with <code><?xml...?></code></p>
| 0 | 2016-10-17T13:38:51Z | 40,096,889 | <p>Problem solved by re-downloading xml-files. Simple as that, but it takes me a long time to figure.</p>
| 0 | 2016-10-17T22:52:16Z | [
"python",
"xml",
"opencv",
"face-recognition"
] |
Python read lines from a file and write from a specific line number to another file | 40,087,970 | <p>I want to read the lines from a file and write from a specific line number to another file. I have this script, which writes all the read lines. I need to skip the first four lines and write the rest to another fils. Any ideas?</p>
<pre><code>for k in range (0,16):
print 'k =',k
from abaqus import session
k=k+1
print k
f1 = open('VY_NM_VR_lin_o1_bonded_results_{k}.txt'.format(k=k))
#with open('VY_{k}'.format(k=k), 'a') as f1:
lines = f1.readlines()
for i, line in enumerate(lines):
#print i
print(repr(line))
#if line.startswith(searchquery):
f2.write(line)
#f2.write('%s'%listc + "\n")
i = i+1
#else :
# i = i+1
#os.close(f1)
f1.close()
f2.close()
</code></pre>
| 0 | 2016-10-17T13:39:24Z | 40,088,047 | <p><a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code> is designed for this</a>:</p>
<pre><code>import itertools
with open('VY_NM_VR_lin_o1_bonded_results_{k}.txt'.format(k=k)) as f1:
# islice w/4 & None skips first four lines of f1, then generates the rest,
# and writelines can take that iterator directly to write them all out
f2.writelines(itertools.islice(f1, 4, None))
</code></pre>
<p>If you need to process the lines as you go, then skip <code>writelines</code> and go back to:</p>
<pre><code> for line in itertools.islice(f1, 4, None):
... do stuff with line ...
f2.write(line)
</code></pre>
<p>Either way, you never even see the first four lines (Python is reading them and discarding them for you seamlessly).</p>
| 4 | 2016-10-17T13:42:48Z | [
"python",
"file"
] |
BeautifulSoup errors | 40,088,055 | <p>I am getting errors when running it.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = "http://sport.citifmonline.com/"
url_page_2 = "url" + "2016/10/15/chelsea-3-0-leicester-city-dominant-blues-comfortable-against-champions-photos/"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html5lib")
links = soup.find_all("a")
for link in links:
print "<a href='%s'>%s</a>" %(link.get("href"), link.text)
g_data = soup.find_all("div", {"class": "wrapper"})
for item in g_data:
articles = item.content[0].find_all("a", {"class": "cat-box-content"})[0].text
try:
print item.contents[1].find_all("h3", {"class": "post-box-title"})[0].text
except:
pass
</code></pre>
| -7 | 2016-10-17T13:43:05Z | 40,088,313 | <p>If you haven't installed <code>html5lib</code> (e.g. with <code>pip install html5lib</code>), you won't be able to use this parser without getting an error. You could either install it or go e.g. for <code>"html.parser"</code> instead which is also mentioned in the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">documentation of BeautifulSoup</a> - just to avoid any errors:</p>
<pre><code>soup = BeautifulSoup(r.content, "html.parser")
</code></pre>
<p>Furthermore, the first line of your inner/second <code>for</code> loop throws a <code>TypeError</code> because you are trying to index something that is not subscriptable (because it's not a list or something like that, see e.g. <a href="http://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-or-not">here</a> for more details). Actually, it's not even existing - the property <code>content</code> you're trying to access is <code>None</code> (which is of course not subscriptable). You should rather do direct calls of <code>find_all</code> on each of the elements:</p>
<pre><code>item.find_all(...)
</code></pre>
| 0 | 2016-10-17T13:55:04Z | [
"python",
"beautifulsoup",
"html-parsing"
] |
Tensorflow MNIST (Weight and bias variables) | 40,088,132 | <p>I'm learning how to use Tensorflow with the MNIST tutorial, but I'm blocking on a point of the tutorial.</p>
<p>Here is the code provided : </p>
<pre><code>from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
saver = tf.train.Saver()
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
</code></pre>
<p>But I actually don't understand at all how the variables "W" (The weight) and "b" (The bias) are changed while the computing ?
On each batch, they are initialized at zero, but after ?
I don't see at all where in the code they're going to change ?</p>
<p>Thanks you very much in advance!</p>
| 0 | 2016-10-17T13:47:16Z | 40,089,052 | <p>TensorFlow <a href="https://www.tensorflow.org/versions/r0.11/how_tos/variables/index.html" rel="nofollow">variables</a> maintain their state from one <code>run()</code> call to the next. In your program they will be initialized to zero, and then progressively updated in the training loop.</p>
<p>The code that changes the values of the variables is created, implicitly, by this line:</p>
<pre><code>train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
</code></pre>
<p>In TensorFlow, a <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/train.html#optimizers" rel="nofollow"><code>tf.train.Optimizer</code></a> is a class that creates operations for updating variables, typically based on the gradient of some tensor (e.g. a loss) with respect to those variables. By default, when you
call <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/train.html#Optimizer.minimize" rel="nofollow"><code>Optimizer.minimize()</code></a>, TensorFlow creates operations to update <strong>all variables</strong> on which the given tensor (in this case <code>cross_entropy</code>) depends.</p>
<p>When you call <code>sess.run(train_step)</code>, this runs a graph that includes those update operations, and therefore instructs TensorFlow to update the values of the variables.</p>
| 2 | 2016-10-17T14:28:04Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow"
] |
How to get current test case(s) status pass/failed in Robot Framework | 40,088,154 | <p>I have used ${TEST STATUS} (Automatic variable) for getting the status giving error.</p>
| -1 | 2016-10-17T13:48:18Z | 40,088,667 | <p>There is a global variable called <code>${TEST_STATUS}</code>. You can use it in <code>teardown</code> section.</p>
<p>See the corresponding part <code>Automatic Variables</code> in the documentation. </p>
<p><a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#id514" rel="nofollow">http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#id514</a></p>
| 0 | 2016-10-17T14:09:50Z | [
"python",
"python-2.7",
"robotframework"
] |
How to get current test case(s) status pass/failed in Robot Framework | 40,088,154 | <p>I have used ${TEST STATUS} (Automatic variable) for getting the status giving error.</p>
| -1 | 2016-10-17T13:48:18Z | 40,124,861 | <p>you can use that variable only in <strong>teardown</strong> section. like below example. robot is maintaining two levels "test levels" and "suit levels". inside test level there is another two things called "setup" and "teardown". <strong>setup</strong> means before executing every testcase it will run. and <strong>teardown</strong> means after executing every testcase it will run. In below example before executing Default_values, Overridden setup, No_teardown,etc. testcases Open_Application will run and after exiting the testcases Close Application will run. you can use that automatic variable in the tear down section only as described in docs and demonstated in the No_teardown testcase. In the No_teardown testcase it is checking whether it is true or not. you can change anything according to your need.</p>
<pre><code>*** Settings ***
Test Setup Open Application App A
Test Teardown Close Application
*** Test Cases ***
Default values
[Documentation] Setup and teardown from setting table
Do Something
Overridden setup
[Documentation] Own setup, teardown from setting table
[Setup] Open Application App B
Do Something
No teardown
[Documentation] Default setup, no teardown at all
Do Something
[Teardown] Should Be True '${TEST STATUS}' == 'True'
No teardown 2
[Documentation] Setup and teardown can be disabled also with special value NONE
Do Something
[Teardown] NONE
Using variables
[Documentation] Setup and teardown specified using variables
[Setup] ${SETUP}
Do Something
[Teardown] ${TEARDOWN}
</code></pre>
<p>This example is modified version of this robot docs link:-
<a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-setup-and-teardown." rel="nofollow">http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-setup-and-teardown</a></p>
<p>Hope this will remove your doubts.</p>
| 1 | 2016-10-19T07:28:27Z | [
"python",
"python-2.7",
"robotframework"
] |
python/matplotlib : imposed ticks with ticker partially missing | 40,088,157 | <p>When plotting my figure with <code>plt.axis('auto')</code>, 'natural' x-ticks are written with frequency 500,</p>
<p><a href="https://i.stack.imgur.com/bcG6u.png" rel="nofollow"><img src="https://i.stack.imgur.com/bcG6u.png" alt="enter image description here"></a></p>
<p>Wishing a frequency 200, I have used:</p>
<pre><code> import matplotlib.ticker as ticker
ticks_loc = ticker.MultipleLocator(base=200)
fig = plt.figure('Cutlines x-axis')
ax = fig.add_subplot(111)
...
plt.axis('equal')
ax.xaxis.set_major_locator(ticks_loc)
ax.yaxis.set_major_locator(ticks_loc)
plt.grid()
</code></pre>
<p>which gives,</p>
<p><a href="https://i.stack.imgur.com/vVwMG.png" rel="nofollow"><img src="https://i.stack.imgur.com/vVwMG.png" alt="enter image description here"></a></p>
<p>Curiously </p>
<ol>
<li>all the ticks are not represented (ticks -1000, -800, -600 are missing) </li>
<li><code>plt.show()</code> differs from <code>savefig</code> (in <code>plt.show()</code> 'only' ticks -1000 and -800 are missing, not -600).</li>
</ol>
<p>I have tried reducing the font size (with very tiny one) and/or by writing vertically -> no effect : always the same ticks are missing.</p>
<p>Is there a way to have all the ticks visible (in horizontal mode) ?</p>
| 1 | 2016-10-17T13:48:26Z | 40,088,308 | <p>Why don't you simply use <code>xticks</code> instead of <code>ticker</code></p>
<pre><code>fig = plt.figure('Cutlines x-axis')
ax = fig.add_subplot(111)
...
xlim = ax.get_xlim()
plt.xticks(np.arange(xlim[0], xlim[1]+200, 200))
</code></pre>
| 1 | 2016-10-17T13:54:54Z | [
"python",
"matplotlib",
"ticker"
] |
Python sending files over scp using pexpect | 40,088,323 | <p>So I'm trying to send all my torrent files to a server with scp using pexpect. This works for the most part but not all my torrent files get sent. Even though the print function in 'if i==0' prints out all the torrents. And if I go to the server and delete everything that got sent and run it again, the same torrent files get sent. Does anyone know what the problem might be?</p>
<pre><code>import os
import getpass
import subprocess
import pexpect
filepath = 'my downloads dir'
os.chdir(filepath)
var_password = str(getpass.getpass())
destination = "user@server:dir"
for filename in os.listdir():
if filename.endswith('.torrent'):
try:
var_command = "scp " + filepath + filename + " " + destination
var_child = pexpect.spawn(var_command)
i = var_child.expect(["password:", pexpect.EOF])
if i==0: # send password
print('Sending: ' + filename)
var_child.sendline(var_password)
var_child.expect(pexpect.EOF)
elif i==1:
print("Got the key or connection timeout")
pass
except Exception as e:
print("Oops Something went wrong buddy")
print(e)
</code></pre>
| 1 | 2016-10-17T13:55:38Z | 40,088,980 | <p>I think I figured it out, thanks to David's comment. The files that include spaces and icelandic letters (since I'm icelandic) don't get transferred.</p>
| 1 | 2016-10-17T14:25:06Z | [
"python",
"operating-system",
"scp",
"pexpect",
"torrent"
] |
groupby on NaN-only column gives IndexError | 40,088,441 | <p>The following gives IndexError: index out of bounds:</p>
<pre><code>import pandas as pd
from numpy import nan
df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-11'}, 'Stock': {0: 'ABC', 1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'ABC', 5: 'XYZ'}, 'StartTime': {0: '08:00:00.241', 1: '08:00:00.243', 2: '12:34:23.563', 3: '08:14.05.908', 4: '18:54:50.100', 5: '10:08:36.657'}, 'EndTime': {0: nan,1: nan, 2: nan, 3: nan, 4: nan, 5: nan}})
df1.groupby(['Stock','EndTime']).head(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/users/.../egg_cache/p/pandas-0.16.2-py2.7-linux-x86_64.egg/pandas/core/groupby.py", line 994, in head
in_head = self._cumcount_array() < n
File "/users/.../egg_cache/p/pandas-0.16.2-py2.7-linux-x86_64.egg/pandas/core/groupby.py", line 1034, in _cumcount_array
arr = np.arange(self.grouper._max_groupsize, dtype='int64')
File "pandas/src/properties.pyx", line 34, in pandas.lib.cache_readonly.__get__ (pandas/lib.c:41917)
File "/users/.../egg_cache/p/pandas-0.16.2-py2.7-linux-x86_64.egg/pandas/core/groupby.py", line 1343, in _max_groupsize
if self.indices:
File "pandas/src/properties.pyx", line 34, in pandas.lib.cache_readonly.__get__ (pandas/lib.c:41917)
File "/users/.../egg_cache/p/pandas-0.16.2-py2.7-linux-x86_64.egg/pandas/core/groupby.py", line 1309, in indices
return _get_indices_dict(label_list, keys)
File "/users/.../egg_cache/p/pandas-0.16.2-py2.7-linux-x86_64.egg/pandas/core/groupby.py", line 3767, in _get_indices_dict
return lib.indices_fast(sorter, group_index, keys, sorted_labels)
File "pandas/lib.pyx", line 1385, in pandas.lib.indices_fast (pandas/lib.c:23875)
File "pandas/src/util.pxd", line 41, in util.get_value_at (pandas/lib.c:62901)
IndexError: index out of bounds
</code></pre>
<p>However if I exclude all NaN column it works fine as follows:</p>
<pre><code>df1.groupby(['Stock','Date']).head(1)
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
5 2016-10-11 NaN 10:08:36.657 XYZ
</code></pre>
<p>Any idea, if this is a bug in Pandas or am I missing something here. I am reading following: <a href="https://github.com/pandas-dev/pandas/issues/11016" rel="nofollow">https://github.com/pandas-dev/pandas/issues/11016</a> <br>
If its a bug, any suggestions for a workaround, assuming getting rid of all Nan columns is not an option.</p>
<p><strong>Some more interesting observations:</strong></p>
<pre><code>df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-11'}, 'Stock': {0: 'ABC', 1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'ABC', 5: 'XYZ'}, 'StartTime': {0: '08:00:00.241', 1: '08:00:00.243', 2: '12:34:23.563', 3: '08:14.05.908', 4: '18:54:50.100', 5: '10:08:36.657'}, 'EndTime': {0: nan,1: nan, 2: 1, 3: nan, 4: nan, 5: nan}})
print df1
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
1 2016-10-11 NaN 08:00:00.243 ABC
2 2016-10-11 1 12:34:23.563 ABC
3 2016-10-11 NaN 08:14.05.908 ABC
4 2016-10-11 NaN 18:54:50.100 ABC
5 2016-10-11 NaN 10:08:36.657 XYZ
df1.groupby(['Stock','EndTime']).head(1)
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
2 2016-10-11 1 12:34:23.563 ABC
</code></pre>
<p>The above output looks incorrect to me. Shouldn't it be:</p>
<pre><code> Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
2 2016-10-11 1 12:34:23.563 ABC
5 2016-10-11 NaN 10:08:36.657 XYZ
</code></pre>
<p>Now for the following case:</p>
<pre><code>df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-11'}, 'Stock': {0: 'ABC', 1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'ABC', 5: 'XYZ'}, 'StartTime': {0: '08:00:00.241', 1: '08:00:00.243', 2: '12:34:23.563', 3: '08:14.05.908', 4: '18:54:50.100', 5: '10:08:36.657'}, 'EndTime': {0: nan,1: nan, 2: nan, 3: nan, 4: nan, 5: 1}})
print df1
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
1 2016-10-11 NaN 08:00:00.243 ABC
2 2016-10-11 NaN 12:34:23.563 ABC
3 2016-10-11 NaN 08:14.05.908 ABC
4 2016-10-11 NaN 18:54:50.100 ABC
5 2016-10-11 1 10:08:36.657 XYZ
df1.groupby(['Stock','EndTime']).head(1)
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
5 2016-10-11 1 10:08:36.657 XYZ
</code></pre>
<p>This one is fine.</p>
| 0 | 2016-10-17T14:00:21Z | 40,089,575 | <p>@Rahul, here is the output of your code when using Pandas 0.19.0:</p>
<pre><code>In [5]: df1
Out[5]:
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
1 2016-10-11 NaN 08:00:00.243 ABC
2 2016-10-11 NaN 12:34:23.563 ABC
3 2016-10-11 NaN 08:14.05.908 ABC
4 2016-10-11 NaN 18:54:50.100 ABC
5 2016-10-11 NaN 10:08:36.657 XYZ
In [6]: df1.groupby(['Stock','EndTime']).head(1)
Out[6]:
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
In [7]: df1.groupby(['Stock','Date']).head(1)
Out[7]:
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
5 2016-10-11 NaN 10:08:36.657 XYZ
In [8]: df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-11'}, 'Stock': {
...: 0: 'ABC', 1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'ABC', 5: 'XYZ'}, 'StartTime': {0: '08:00:00.241', 1: '08:00:00.243', 2: '12:34:23.563', 3: '08:14
...: .05.908', 4: '18:54:50.100', 5: '10:08:36.657'}, 'EndTime': {0: nan,1: nan, 2: 1, 3: nan, 4: nan, 5: nan}})
...:
In [9]: df1.groupby(['Stock','EndTime']).head(1)
Out[9]:
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
2 2016-10-11 1.0 12:34:23.563 ABC
In [10]: df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-11'}, 'Stock':
...: {0: 'ABC', 1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'ABC', 5: 'XYZ'}, 'StartTime': {0: '08:00:00.241', 1: '08:00:00.243', 2: '12:34:23.563', 3: '08:
...: 14.05.908', 4: '18:54:50.100', 5: '10:08:36.657'}, 'EndTime': {0: nan,1: nan, 2: nan, 3: nan, 4: nan, 5: 1}})
...:
In [11]: df1.groupby(['Stock','EndTime']).head(1)
Out[11]:
Date EndTime StartTime Stock
0 2016-10-11 NaN 08:00:00.241 ABC
5 2016-10-11 1.0 10:08:36.657 XYZ
</code></pre>
| 0 | 2016-10-17T14:52:05Z | [
"python",
"pandas",
"dataframe",
"group-by",
null
] |
django app multiple hard drives [Errno 18] Invalid cross-device link | 40,088,442 | <p>I have a django app on a debian server and my current site_media directory on the current disk is full. So I want to upload files On a second disk. The path on server is /disk :</p>
<pre><code> obj = form.save(commit=False)
obj.user_id = self.request.user.pk
obj.save()
initial_path = obj.file.path
print(initial_path)
new = settings.MEDIA_ROOT_NEW + obj.file.name
print(new)
os.rename(initial_path,new)
shutil.move(initial_path, new)
</code></pre>
<p>and in my settings.py I have:</p>
<pre><code> MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media/')
MEDIA_ROOT_NEW = '/disk/site_media/'
</code></pre>
<p>still I get error:
django [Errno 18] Invalid cross-device link</p>
<p>Any ideas???</p>
| 0 | 2016-10-17T14:00:21Z | 40,090,305 | <p><code>os.rename()</code> may fail across different file systems.</p>
<blockquote>
<p>The operation may fail on some Unix flavors if src and dst are on different filesystems.
<a href="https://docs.python.org/3/library/os.html#os.rename" rel="nofollow">https://docs.python.org/3/library/os.html#os.rename</a></p>
</blockquote>
<p><code>shutil.move()</code> should work</p>
<blockquote>
<p>If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied (using shutil.copy2()) to dst and then removed.
<a href="https://docs.python.org/3.4/library/shutil.html#shutil.move" rel="nofollow">https://docs.python.org/3.4/library/shutil.html#shutil.move</a></p>
</blockquote>
<p>but you've got a <code>os.rename(initial_path,new)</code> just before your <code>shutil.move(initial_path, new)</code>. Remove the first <code>os.rename()</code> and it should work.</p>
| 1 | 2016-10-17T15:29:04Z | [
"python",
"django",
"server",
"debian-based"
] |
How to use Python's RotatingFileHandler | 40,088,496 | <p>I'm trying to do a test run of the <code>logging</code> module's <code>RotatingFileHandler</code> as follows:</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
# logging.basicConfig(filename="example.log", level=logging.DEBUG)
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug("Hello, world!")
</code></pre>
<p>However, with <code>logging.basicConfig</code> line commented out, the resulting <code>my_log.log</code> file contains no data:</p>
<p><a href="https://i.stack.imgur.com/Q3CoP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Q3CoP.png" alt="enter image description here"></a></p>
<p>If I comment in the line with <code>logging.basicConfig(filename="example.log", level=logging.DEBUG)</code>, I get the expected <code>my_log.log</code> files with numbered suffixes. However, there is also the <code>example.log</code> which is a (relatively) large file:</p>
<p><a href="https://i.stack.imgur.com/J77C7.png" rel="nofollow"><img src="https://i.stack.imgur.com/J77C7.png" alt="enter image description here"></a></p>
<p>How can I set up the logging so that it only generates the <code>my_log.log</code> files, and not the large <code>example.log</code> file?</p>
| 0 | 2016-10-17T14:02:31Z | 40,088,591 | <p>Python provides 5 logging levels out of the box (in increasing order of severity): <code>DEBUG</code>, <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code> and <code>CRITICAL</code>. The default one <a href="https://docs.python.org/3/howto/logging.html#what-happens-if-no-configuration-is-provided" rel="nofollow">is <code>WARNING</code></a>. The docs says, that</p>
<blockquote>
<p>Logging messages which are less severe than <em>lvl</em> will be ignored.</p>
</blockquote>
<p>So if you use <code>.debug</code> with the default settings, you won't see anything in your logs.</p>
<p>The easiest fix would be to use <code>logger.warning</code> function rather that <code>logger.debug</code>:</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.warning('Hello, world!')
</code></pre>
<p>And if you want to change logger level you can use <a href="https://docs.python.org/3/library/logging.html#logging.Logger.setLevel" rel="nofollow"><code>.setLevel</code></a> method:</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug('Hello, world!')
</code></pre>
| 2 | 2016-10-17T14:06:37Z | [
"python",
"logging"
] |
How to use Python's RotatingFileHandler | 40,088,496 | <p>I'm trying to do a test run of the <code>logging</code> module's <code>RotatingFileHandler</code> as follows:</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
# logging.basicConfig(filename="example.log", level=logging.DEBUG)
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug("Hello, world!")
</code></pre>
<p>However, with <code>logging.basicConfig</code> line commented out, the resulting <code>my_log.log</code> file contains no data:</p>
<p><a href="https://i.stack.imgur.com/Q3CoP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Q3CoP.png" alt="enter image description here"></a></p>
<p>If I comment in the line with <code>logging.basicConfig(filename="example.log", level=logging.DEBUG)</code>, I get the expected <code>my_log.log</code> files with numbered suffixes. However, there is also the <code>example.log</code> which is a (relatively) large file:</p>
<p><a href="https://i.stack.imgur.com/J77C7.png" rel="nofollow"><img src="https://i.stack.imgur.com/J77C7.png" alt="enter image description here"></a></p>
<p>How can I set up the logging so that it only generates the <code>my_log.log</code> files, and not the large <code>example.log</code> file?</p>
| 0 | 2016-10-17T14:02:31Z | 40,088,663 | <p>I found that to obtain the desired behavior one has to use the same name in the <code>basicConfig</code> and <code>RotatingFileHandler</code> initializations:</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(filename="my_log.log", level=logging.DEBUG)
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)
for _ in range(10000):
logger.debug("Hello, world!")
</code></pre>
<p>Here, I have chose the same name <code>my_log.log</code>. This results in only the 'size-limited' logs being created:</p>
<p><a href="https://i.stack.imgur.com/85XGh.png" rel="nofollow"><img src="https://i.stack.imgur.com/85XGh.png" alt="enter image description here"></a></p>
| 0 | 2016-10-17T14:09:38Z | [
"python",
"logging"
] |
python django call chat.py in template $ajax ? giving error not found | 40,088,503 | <p>hi i am new at python django.
i have template where i wana call a file through ajax</p>
<pre><code> $.ajax({
type: "POST",
url: "chat.py",
data: {foo: 'bar', bar: 'foo'},
</code></pre>
<p>and <code>urls.py</code></p>
<pre><code>from django.conf.urls import include , url
from . import views
from . import chat
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', chat.main, name='main'),
]
</code></pre>
<p>and <code>chat.py</code></p>
<pre><code>import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append("../../tf_seq2seq_chatbot_parent")
import tensorflow as tf
from tf_seq2seq_chatbot.lib.chat import chat
def main(_):
#chat()
print('kjgjkh')
if __name__ == "__main__":
tf.app.run()
</code></pre>
<p>and <code>views.py</code></p>
<pre><code>from django.shortcuts import render
def index(request):
return render(request , "base.html" , {})
error: poll/chat.py not found
</code></pre>
| 0 | 2016-10-17T14:02:43Z | 40,088,766 | <p>You haven't got a URL "chat.py". Your URLs are defined in the regexes in your urls.py; but you've only defined one, which is just /, although you've defined it twice which can't possibly work.</p>
<p>Make those two URLs different, and use the one you want in your Ajax call.</p>
| 0 | 2016-10-17T14:14:58Z | [
"python",
"ajax",
"django"
] |
Sorting dict items by key, beyond alphanumeric sorting | 40,088,527 | <p>I have written this code:</p>
<pre><code>n=5
dizN={}
for q in range(0,n+1):
h=n-q
dizN['a'+str(q)+'p'+str(h)]=0
</code></pre>
<p>that creates such a dictionary:</p>
<p>dizN</p>
<pre><code>Out[120]: {'a0p5': 0, 'a1p4': 0, 'a2p3': 0, 'a3p2': 0, 'a4p1': 0, 'a5p0': 0}
</code></pre>
<p>Note that "n" is the basic parameter for my code. As you can see, the sum of integers present in dict keys string is always =n (=5 in this case, where n=5).</p>
<p>It is important for me (for more difficult purposes in my program) that, for every n anyone can choose, the dict is ordered in this way: </p>
<pre><code>{'a0p(n)': 0, 'a1p(n-1)': 0, ....., 'a(n-1)p1': 0, 'a(n)p0': 0}
</code></pre>
<p>My code is ok, but only for n<10.
If n is >=10, this is what happens: (n=12) dizN:</p>
<pre><code>Out[121]:
{'a0p12': 0,
'a10p2': 0,
'a11p1': 0,
'a12p0': 0,
'a1p11': 0,
'a2p10': 0,
'a3p9': 0,
'a4p8': 0,
'a5p7': 0,
'a6p6': 0,
'a7p5': 0,
'a8p4': 0,
'a9p3': 0}
</code></pre>
<p>As you can see the interpreter follows alphanumeric sorting;</p>
<p>Anybody know if there is a way to obtain the same dict sorted this way:</p>
<pre><code>{'a0p12': 0,
'a1p11': 0,
'a2p10': 0,
'a3p9': 0,
'a4p8': 0,
'a5p7': 0,
'a6p6': 0,
'a7p5': 0,
'a8p4': 0,
'a9p3': 0,
'a10p2': 0,
'a11p1': 0,
'a12p0': 0}
</code></pre>
<p>?</p>
<p>I know that dictionaries are basically non sortable, but i hope somebody knows some trick to obtain my purpose anyway :)</p>
<p>Thanks a lot!</p>
| 1 | 2016-10-17T14:03:44Z | 40,088,802 | <p><em>dicts</em> are <em>unordered</em>, so to get the order you are going to have to sort the items and use an <em>OrderedDict</em> to maintain the sorted order. To get the order you want you can create tuples from the groups of integers so you sort as integers in lexicographical order:</p>
<pre><code>from itertools import groupby
from collections import OrderedDict
d = {'a0p12': 0, 'a10p2': 0, 'a11p1': 0, 'a12p0': 0, 'a1p11': 0, 'a2p10': 0,
'a3p9': 0, 'a4p8': 0, 'a5p7': 0, 'a6p6': 0, 'a7p5': 0, 'a8p4': 0, 'a9p3': 0}
def key_func(x):
"""'a0p12' -> (0, 12)"""
return tuple(int("".join(v)) for k,v in groupby(x[0], key=str.isdigit) if k)
od = OrderedDict(sorted(d.items(), key=key_func))
print(od)
</code></pre>
<p>Which would give you:</p>
<pre><code>OrderedDict([('a0p12', 0), ('a1p11', 0), ('a2p10', 0), ('a3p9', 0),
('a4p8', 0), ('a5p7', 0), ('a6p6', 0), ('a7p5', 0), ('a8p4', 0),
('a9p3', 0), ('a10p2', 0), ('a11p1', 0), ('a12p0', 0)])
</code></pre>
<p>You could also use a <em>regex</em> to find the groups of digits:</p>
<pre><code>from collections import OrderedDict
import re
d = {'a0p12': 0, 'a10p2': 0, 'a11p1': 0, 'a12p0': 0, 'a1p11': 0, 'a2p10': 0,
'a3p9': 0, 'a4p8': 0, 'a5p7': 0, 'a6p6': 0, 'a7p5': 0, 'a8p4': 0, 'a9p3': 0}
def key_func(x,patt=re.compile("\d+")):
"""'a0p12' -> (0, 12)"""
return tuple(map(int, patt.findall(x[0])))
od = OrderedDict(sorted(d.items(), key=key_func))
print(od)
</code></pre>
| 0 | 2016-10-17T14:16:22Z | [
"python",
"sorting",
"dictionary",
"tuples"
] |
Python - Check if two words are in a string | 40,088,559 | <p>I would like to check whether 2 words "car" and "motorbike" are in each element of an array in Python. I know how to check for one word with <code>in</code> but have no idea how to do with 2 words. Really appreciate any help</p>
| 2 | 2016-10-17T14:05:20Z | 40,088,783 | <p>Two word solution:</p>
<pre><code>for string in array:
if 'car' in string and 'motorbike' in string.split():
print("Car and motorbike are in string")
</code></pre>
<p>n-word solution to check if <strong>all</strong> words in <code>test_words</code> are in <code>string</code>:</p>
<pre><code>test_words = ['car', 'motorbike']
contains_all = True
for string in array:
for test_word in test_words:
if test_word not in string.split()::
contains_all = False
break
if not contains_all:
break
if contains_all:
print("All words in each string")
else:
print("Not all words in each string")
</code></pre>
| 4 | 2016-10-17T14:15:37Z | [
"python"
] |
Python - Check if two words are in a string | 40,088,559 | <p>I would like to check whether 2 words "car" and "motorbike" are in each element of an array in Python. I know how to check for one word with <code>in</code> but have no idea how to do with 2 words. Really appreciate any help</p>
| 2 | 2016-10-17T14:05:20Z | 40,088,805 | <p>Use an auxiliar boolean.</p>
<pre><code>car=False
motorbike=False
for elem in array:
if "car" in elem:
car=True
if "motorbike" in elem:
motorbike=True
if car and motorbike:
break
</code></pre>
<p>EDIT: I just read "in each element". Just use AND.</p>
| 1 | 2016-10-17T14:16:25Z | [
"python"
] |
Python - Check if two words are in a string | 40,088,559 | <p>I would like to check whether 2 words "car" and "motorbike" are in each element of an array in Python. I know how to check for one word with <code>in</code> but have no idea how to do with 2 words. Really appreciate any help</p>
| 2 | 2016-10-17T14:05:20Z | 40,089,159 | <p>I think a simple solution is this:</p>
<pre class="lang-py prettyprint-override"><code>all(map(lambda w: w in text, ('car', 'motorbike')))
</code></pre>
<p>But there might be a problem with this, depending on how picky you need the comparison to be:</p>
<pre class="lang-py prettyprint-override"><code>>>> text = 'Can we buy motorbikes in carshops?'
>>> all(map(lambda w: w in text, ('car', 'motorbike')))
True
</code></pre>
<p>The words 'car' and 'motorbike' are NOT in the <code>text</code>, and this still says <code>True</code>. You might need a full match in words. I would do this:</p>
<pre class="lang-py prettyprint-override"><code>>>> words = ('car', 'motorbike')
>>> text = 'Can we buy motorbikes in carshops?'
>>> set(words).issubset(text.split())
False
>>> text = 'a car and a motorbike'
>>> set(words).issubset(text.split())
True
</code></pre>
<p>And now it works!</p>
| 0 | 2016-10-17T14:33:19Z | [
"python"
] |
I have this python function for DFS, why is it throwing error? | 40,088,560 | <pre><code>##This function will return the edges for an undirected graph####
###Example: when edges = [[1,2],[3,2]]
### this will return
{
1: {'nbr': [2], 'id': 1, 'visited': False},
2: {'nbr': [1, 3], 'id': 2, 'visited': False},
3: {'nbr': [2], 'id': 3, 'visited': False}
}
def createEdges(edges):
E = {}
for y in edges:
for x in edges:
if x[0] not in E:
E[x[0]] = {"id": x[0], "nbr": [x[1]], "visited": False}
elif x[1] not in E:
E[x[1]] = {"id": x[1], "nbr": [x[0]], "visited": False}
elif x[0] in E and x[1] not in E[x[0]]['nbr']:
E[x[0]]['nbr'].append(x[1])
elif x[1] in E and x[0] not in E[x[1]]['nbr']:
E[x[1]]['nbr'].append(x[0])
return E
####A function to explore the a vertex of the graph with edges E
def explore(vertex, E):
if vertex not in E:
return
E[vertex]['ccNum'] = cc
E[vertex]['visited'] = True
for x in E[vertex]['nbr']:
if E[x]['visited'] == False:
explore(x, E)
### this function will set the visited index to true for
### all the connecting points of the vertex
### A function for DFS
def DFS(E):
cc = 1
for x in E:
if E[x]['visited'] == False:
explore(x, E)
cc += 1
</code></pre>
<p>Everything was running well before the introduction of "cc" which keep tracks
of total connecting sub graphs</p>
Its now throwing error that:
<h3>Global name cc is not defined</h3>
<p>although cc is defined expose is being called under DFS, which has cc defined in its scope</p>
| 0 | 2016-10-17T14:05:23Z | 40,088,736 | <p>Yes, <code>cc</code> is defined in scope of <code>DFS</code>, that does not make it visible inside <code>explore</code>. You could define it as a parameter to <code>explore</code>;</p>
<pre><code>def explore(vertex, E, cc):
</code></pre>
<p>and pass in the value;</p>
<pre><code>. . .
explore(x, E, cc)
. . .
</code></pre>
| 0 | 2016-10-17T14:13:42Z | [
"python",
"graph"
] |
I have this python function for DFS, why is it throwing error? | 40,088,560 | <pre><code>##This function will return the edges for an undirected graph####
###Example: when edges = [[1,2],[3,2]]
### this will return
{
1: {'nbr': [2], 'id': 1, 'visited': False},
2: {'nbr': [1, 3], 'id': 2, 'visited': False},
3: {'nbr': [2], 'id': 3, 'visited': False}
}
def createEdges(edges):
E = {}
for y in edges:
for x in edges:
if x[0] not in E:
E[x[0]] = {"id": x[0], "nbr": [x[1]], "visited": False}
elif x[1] not in E:
E[x[1]] = {"id": x[1], "nbr": [x[0]], "visited": False}
elif x[0] in E and x[1] not in E[x[0]]['nbr']:
E[x[0]]['nbr'].append(x[1])
elif x[1] in E and x[0] not in E[x[1]]['nbr']:
E[x[1]]['nbr'].append(x[0])
return E
####A function to explore the a vertex of the graph with edges E
def explore(vertex, E):
if vertex not in E:
return
E[vertex]['ccNum'] = cc
E[vertex]['visited'] = True
for x in E[vertex]['nbr']:
if E[x]['visited'] == False:
explore(x, E)
### this function will set the visited index to true for
### all the connecting points of the vertex
### A function for DFS
def DFS(E):
cc = 1
for x in E:
if E[x]['visited'] == False:
explore(x, E)
cc += 1
</code></pre>
<p>Everything was running well before the introduction of "cc" which keep tracks
of total connecting sub graphs</p>
Its now throwing error that:
<h3>Global name cc is not defined</h3>
<p>although cc is defined expose is being called under DFS, which has cc defined in its scope</p>
| 0 | 2016-10-17T14:05:23Z | 40,089,792 | <p>you need to define "cc" as parameter of explore or define it as a global var.</p>
<pre><code> cc = 0
def explore(vertex, E):
global cc
if vertex not in E:
return
E[vertex]['ccNum'] = cc
E[vertex]['visited'] = True
for x in E[vertex]['nbr']:
if E[x]['visited'] == False:
explore(x, E)
### this function will set the visited index to true for
### all the connecting points of the vertex
### A function for DFS
def DFS(E):
cc = 1
for x in E:
if E[x]['visited'] == False:
explore(x, E)
cc += 1
</code></pre>
| 0 | 2016-10-17T15:03:19Z | [
"python",
"graph"
] |
Python - find highest dictionary key with value greater than zero | 40,088,576 | <p>I have a dictionary</p>
<pre><code>{0: 12, 1: 1, 2: 13, 3: 7, 4: 0}
</code></pre>
<p>I want to find the highest dictionary key with a value greater than 0.</p>
<p>In this case, the answer is 3.</p>
<p>What's the best way to do this?</p>
| 1 | 2016-10-17T14:06:01Z | 40,088,649 | <p>You can use <code>max</code> and <code>dict.items()</code> to do this:</p>
<pre><code>d = {0: 12, 1: 1, 2: 13, 3: 7, 4: 0}
highest = max(i for i,j in d.items() if j > 0)
</code></pre>
| 2 | 2016-10-17T14:09:04Z | [
"python",
"dictionary"
] |
Python - find highest dictionary key with value greater than zero | 40,088,576 | <p>I have a dictionary</p>
<pre><code>{0: 12, 1: 1, 2: 13, 3: 7, 4: 0}
</code></pre>
<p>I want to find the highest dictionary key with a value greater than 0.</p>
<p>In this case, the answer is 3.</p>
<p>What's the best way to do this?</p>
| 1 | 2016-10-17T14:06:01Z | 40,088,687 | <p>Use a genexpr to filter out the "bad" values, and <code>max</code> to keep the highest that remains:</p>
<pre><code># On Py2, use .iteritems() instead of .items()
max(k for k, v in mydict.items() if v > 0)
</code></pre>
<p>Or if you need to have a default if no keys qualify without an exception being raised:</p>
<pre><code># Py3 max has default, which makes this super-easy:
max((k for k, v in mydict.items() if v > 0), default=SOMEVALUEGOESHERE)
# Py2 doesn't have default; workaround is to catch exception and use a default (EAFP):
try:
mymax = max(k for k, v in mydict.iteritems() if v > 0)
except ValueError:
mymax = SOMEVALUEGOESHERE
# Or if you can't do that for some reason, make a listcomp instead of genexpr
# and check for at least one surviving key before calling max (LBYL)
goodkeys = [k for k, v in mydict.iteritems() if v > 0]
mymax = max(goodkeys) if goodkeys else SOMEVALUEGOESHERE
</code></pre>
| 3 | 2016-10-17T14:10:55Z | [
"python",
"dictionary"
] |
Turn off error bars in Seaborn Bar Plot | 40,088,585 | <p>I'm using GridSpec in matplotlib to create a page that has 9 subplots. One of the subplots is a Seaborn bar plot created with the following code:</p>
<pre><code>import seaborn as sns
sns.barplot(x=df['Time'], y=df['Volume_Count'], ax=ax7)
</code></pre>
<p>Is there a way to turn off the vertical error bars of the bar plot? If not, is it possible to reduce the horizontal width of the bars?</p>
<p>Thanks!</p>
| 0 | 2016-10-17T14:06:28Z | 40,090,469 | <p>I'm not 100% sure since the seaborn website seems to be down, but have you tried the <code>ci</code> argument? According to the documentation:</p>
<blockquote>
<p>ci : float or None, optional
Size of confidence intervals to draw around estimated values. If
<code>None</code>, no bootstrapping will be performed, and error bars will
not be drawn.</p>
</blockquote>
<pre><code>sns.barplot(x=df['Time'], y=df['Volume_Count'], ax=ax7, ci=None)
</code></pre>
| 2 | 2016-10-17T15:38:00Z | [
"python",
"matplotlib",
"seaborn"
] |
Linux : unable to install kivy in virtual environment | 40,088,622 | <p>I am using python2.7 and created a virtual environment 'kivyenv'.
First i install Cython and then kivy in kivyenv.</p>
<pre><code>pip install Cython
pip install kivy
</code></pre>
<p>kivy failed to install giving some error :-</p>
<pre><code>In file included from /tmp/pip-build-4T9oG4/kivy/kivy/graphics/opengl.c:274:0:
/tmp/pip-build-4T9oG4/kivy/kivy/graphics/gl_redirect.h:43:22: fatal error: GL/gl.h: No such file or directory
# include <GL/gl.h>
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Command "/root/kivyenv/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-4T9oG4/kivy/setup.py';
exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"
install --record /tmp/pip-3__DxE-record/install-record.txt --single-version-externally-managed --compile --install-headers
/root/kivyenv/include/site/python2.7/kivy" failed with error code 1 in /tmp/pip-build-4T9oG4/kivy/
</code></pre>
<p>I am using Ubuntu 16.</p>
| 0 | 2016-10-17T14:07:40Z | 40,089,362 | <p>This is happening because you do not have dependency libraries installed on your system, specifically the ones for OpenGL - most likely you do not have mesa packages installed.</p>
<p>Follow the instructions for your specific distribution on how to install all of the needed dependencies at: <a href="https://kivy.org/docs/installation/installation-linux.html#using-software-packages" rel="nofollow">https://kivy.org/docs/installation/installation-linux.html#using-software-packages</a></p>
| 2 | 2016-10-17T14:42:41Z | [
"python",
"linux",
"python-2.7",
"virtualenv",
"kivy"
] |
forcing a program to calculate an input | 40,088,634 | <p>I was wondering if I could force the program to calculate an input before converting it to an integer.
for example my code is</p>
<pre><code> shift=int(raw_input("input the shift you want "))
</code></pre>
<p>If I was to input 4**2 which should then in theory equal 16 however as the raw input is a string this cannot happen.
I would like to know if there was force the program to calculate the input meaning if I inputted a calculation then the program would work it out instead of just converting it to an integer and causing an error.</p>
| 0 | 2016-10-17T14:08:07Z | 40,089,205 | <p>If you don't mind being terribly unsafe, you can use <a href="https://docs.python.org/2/library/functions.html#eval" rel="nofollow">eval</a>, which accepts a single string argument as input, and executes it as Python code:</p>
<pre><code>shift = eval(raw_input("input the shift you want "))
</code></pre>
<p><a href="http://stackoverflow.com/a/1933481/2615940">And here is an explanation of why you shouldn't do this in any kind of production code</a>.</p>
<p>A better option is to actually build a proper parser to behave like a calculator. There are plenty of resources for this floating around SO and elsewhere online.</p>
| 4 | 2016-10-17T14:35:31Z | [
"python",
"python-2.7",
"input",
"raw-input"
] |
How to set the default working directory for run configurations in PyCharm | 40,088,657 | <p>When I want to run one of our many python scripts I hit run, which creates a new run configuration. The working directory for that configuration is the folder in which the python script file resides. Instead, it should run from a project wide fixed folder. I'd like to set that somehow but I really cannot figure out why, which is a bit odd as I'd expect many people to want to have this functionality.
Do you know how to pull this off?</p>
| 1 | 2016-10-17T14:09:23Z | 40,088,730 | <p>If you hit the <code>Edit configurations...</code> button in the submenu appearing when clicking on your currently selected run configuration in the top right of PyCharm, you are able to edit the fields (and therefore also the working directory) of Python run configurations by selecting <code>Python</code> from the <code>Defaults</code> and specifying the desired values. (Don't forget to hit <code>Apply</code>/<code>OK</code> before creating new run configurations which should contain the default values!)</p>
<p>As far as I know, these defaults are local to one project.
See also: <a href="https://www.jetbrains.com/help/pycharm/2016.2/creating-and-editing-run-debug-configurations.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.2/creating-and-editing-run-debug-configurations.html</a></p>
| 2 | 2016-10-17T14:13:20Z | [
"python",
"pycharm",
"run-configuration"
] |
Python help using 'numpy.masked_where' conditionally from another list | 40,088,691 | <p>I am writing an astronomy observation simulation. I have a data array which is 1 measurement per 24 hours:</p>
<pre><code>data = [0,1,2,3,4]
</code></pre>
<p>And I have a array which is the minutes of cloud/rain in a 24 hour period, rounded to the nearest hour:</p>
<pre><code>weather = [0,60,120,180,0]
</code></pre>
<p>I want to use a masked array to hide the values in the data array based off the values in the weather array. Masking is important (instead of deleting) for plotting and data analysis further down the line.</p>
<p>So if I want to only show data points where there was < 120 mins of downtime I do:</p>
<pre><code>downtime = 120
data_masked = np.ma.masked_where(weather < downtime, data)
</code></pre>
<p>This should result in:</p>
<pre><code>data_masked = [0, 1, ---, ---, 4]
</code></pre>
<p>But my data_masked seems to be doing the opposite. If I plot both my data and weather on the same axis. I am masking the points where the weather downtime is <em>below</em> my threshold.</p>
<p>I've tried inverting the operator which just seems to keep everything in. Any ideas or am I missing the point of numpy.ma?</p>
<p>Thanks!</p>
| 0 | 2016-10-17T14:11:15Z | 40,089,060 | <p>Using <code>numpy.ma</code> returns a mask. That is, it <strong>hides</strong> (masks) everything that fits the condition <code>weather < downtime</code>. If you want to <strong>show</strong> everything that fits the condition, just invert the condition:</p>
<pre><code>data = np.array([0,1,2,3,4])
weather = np.array([0,60,120,180,0])
downtime = 120
data_masked = np.ma.masked_where(weather >= downtime, data)
data_masked
</code></pre>
<p>Then the output will be:</p>
<pre><code>masked_array(data = [0 1 -- -- 4],
mask = [False False True True False],
fill_value = 999999)
</code></pre>
<p>To access the data, use <code>data_masked.data</code>.</p>
| 2 | 2016-10-17T14:28:33Z | [
"python",
"arrays",
"numpy",
"masked-array"
] |
Python help using 'numpy.masked_where' conditionally from another list | 40,088,691 | <p>I am writing an astronomy observation simulation. I have a data array which is 1 measurement per 24 hours:</p>
<pre><code>data = [0,1,2,3,4]
</code></pre>
<p>And I have a array which is the minutes of cloud/rain in a 24 hour period, rounded to the nearest hour:</p>
<pre><code>weather = [0,60,120,180,0]
</code></pre>
<p>I want to use a masked array to hide the values in the data array based off the values in the weather array. Masking is important (instead of deleting) for plotting and data analysis further down the line.</p>
<p>So if I want to only show data points where there was < 120 mins of downtime I do:</p>
<pre><code>downtime = 120
data_masked = np.ma.masked_where(weather < downtime, data)
</code></pre>
<p>This should result in:</p>
<pre><code>data_masked = [0, 1, ---, ---, 4]
</code></pre>
<p>But my data_masked seems to be doing the opposite. If I plot both my data and weather on the same axis. I am masking the points where the weather downtime is <em>below</em> my threshold.</p>
<p>I've tried inverting the operator which just seems to keep everything in. Any ideas or am I missing the point of numpy.ma?</p>
<p>Thanks!</p>
| 0 | 2016-10-17T14:11:15Z | 40,089,070 | <p>You'll want to use</p>
<pre><code>np.ma.MaskedArray(data,mask)
</code></pre>
<p>Note that the mask specifies the data that is to be masked. Also, for the following type of operation</p>
<pre><code>weather < downtime
</code></pre>
<p>to work as you intend, 'weather' needs to be an array rather than a list, so:</p>
<pre><code>weather = np.array([0,60,120,180,0])
...
data_masked=np.ma.MaskedArray(data, weather >= downtime)
</code></pre>
<p>Note that I used '>=' instead of '<' to get your required result</p>
| 1 | 2016-10-17T14:29:12Z | [
"python",
"arrays",
"numpy",
"masked-array"
] |
Python Pandas - filtering df by the number of unique values within a group | 40,088,710 | <p>Here is an example of data I'm working on. (as a pandas df)</p>
<pre><code> index inv Rev_stream Bill_type Net_rev
1 1 A Original -24.77
2 1 B Original -24.77
3 2 A Original -409.33
4 2 B Original -409.33
5 2 C Original -409.33
6 2 D Original -409.33
7 3 A Original -843.11
8 3 A Rebill 279.5
9 3 B Original -843.11
10 4 A Rebill 279.5
11 4 B Original -843.11
12 5 B Rebill 279.5
</code></pre>
<p>How could I filter this df, in a way to only get the lines where invoice/Rev_stream combo has both original and rebill kind of Net_rev. In the example above it would be only lines with index 7 and 8. </p>
<p>Is there an easy way to do it, without iterating over the whole dataframe and building dictionaries of invoice+RevStream : Bill_type?</p>
<p>What I'm looking for is some kind of</p>
<pre><code>df = df[df[['inv','Rev_stream']]['Bill_type'].unique().len() == 2]
</code></pre>
<p>Unfortunately the code above doesn't work.</p>
<p>Thanks in advance.</p>
| 1 | 2016-10-17T14:12:04Z | 40,089,226 | <p>You can group your data by <code>inv</code> and <code>Rev_stream</code> columns and then check for each group if both <code>Original</code> and <code>Rebill</code> are in the <code>Bill_type</code> values and filter based on the condition:</p>
<pre><code>(df.groupby(['inv', 'Rev_stream'])
.filter(lambda g: 'Original' in g.Bill_type.values and 'Rebill' in g.Bill_type.values))
</code></pre>
<p><a href="https://i.stack.imgur.com/P9a9T.png" rel="nofollow"><img src="https://i.stack.imgur.com/P9a9T.png" alt="enter image description here"></a></p>
| 2 | 2016-10-17T14:36:24Z | [
"python",
"pandas",
"dataframe",
"filtering"
] |
How to create a loop to return to the start of a function python | 40,088,732 | <p>I am unable to get my <code>while</code> loop to start back at the beginning not to sure what is wrong.</p>
<p>First attempt</p>
<pre><code>def start() :
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
else:
print("Uh oh, I don't know about that item")
start()
</code></pre>
<p>second attempt</p>
<pre><code>the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
</code></pre>
<p>I just can't seem to figure it out. </p>
| 0 | 2016-10-17T14:13:25Z | 40,088,943 | <p>Your second attempt looks close, but you need an esape if all items are done: but look at your spaces: the if is inside the while:</p>
<pre><code>choice = next_choice()
found = false
while found & :
if choice in weapon_stash:
inventory.append(choice)
found = True
else:
choice = next_choice() # get from user?
if choice == None:
break; # break out on some condition otherwise infinite loop
# found is now either true (a thing was found), or false (the user quit)
</code></pre>
| 1 | 2016-10-17T14:23:15Z | [
"python",
"python-2.7"
] |
How to create a loop to return to the start of a function python | 40,088,732 | <p>I am unable to get my <code>while</code> loop to start back at the beginning not to sure what is wrong.</p>
<p>First attempt</p>
<pre><code>def start() :
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
else:
print("Uh oh, I don't know about that item")
start()
</code></pre>
<p>second attempt</p>
<pre><code>the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
</code></pre>
<p>I just can't seem to figure it out. </p>
| 0 | 2016-10-17T14:13:25Z | 40,089,304 | <p>The reason I commented Visual Studio might not be the best python editor is that other editors would have warned you that you did not increase the indentation after your function definition <code>start()</code> in your first attempt, nor did you indent after the start of your <code>while</code> loop in your second attempt. It always helps to include your error messages to help describe your problem, but if I were to guess, you are getting something to the tune of <code>IndentationError</code> messages. </p>
<p>Indentation is one of the most important concepts of python coding and serves the same purpose as curly braces in java or c++. <a href="https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation" rel="nofollow">Wikipedia</a> has a pretty straightforward description of how to do it.</p>
<p>As for editors, I am a personal fan of <a href="https://github.com/spyder-ide/spyder" rel="nofollow">spyder</a> although there are many great ones out there: <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">Pycharm</a>, <a href="http://www.pydev.org/" rel="nofollow">pydev</a>, etc.. </p>
| 1 | 2016-10-17T14:40:15Z | [
"python",
"python-2.7"
] |
How to create a loop to return to the start of a function python | 40,088,732 | <p>I am unable to get my <code>while</code> loop to start back at the beginning not to sure what is wrong.</p>
<p>First attempt</p>
<pre><code>def start() :
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
else:
print("Uh oh, I don't know about that item")
start()
</code></pre>
<p>second attempt</p>
<pre><code>the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
</code></pre>
<p>I just can't seem to figure it out. </p>
| 0 | 2016-10-17T14:13:25Z | 40,089,476 | <p>There are only indentation faults in the second attempt.
Try below code.</p>
<pre><code>the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
</code></pre>
<p>This will stuck in a constant loop if the user keeps entering a value not in the list (weapon), so you can put a counter for every <code>False</code> and update like below.</p>
<pre><code>counter=0
the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
counter=counter+1
if counter >= 3:
print('You have made 3 wrong attempts ')
break
</code></pre>
| 0 | 2016-10-17T14:47:39Z | [
"python",
"python-2.7"
] |
How to download nasa satellite OPeNDAP data using python | 40,088,745 | <p>I have tried requests, pydap, urllib, and netcdf4 and keep either getting redirect errors or permission errors when trying to download the following NASA data:</p>
<p>GLDAS_NOAH025SUBP_3H: GLDAS Noah Land Surface Model L4 3 Hourly 0.25 x 0.25 degree Subsetted V001 (<a href="http://disc.sci.gsfc.nasa.gov/uui/datasets/GLDAS_NOAH025SUBP_3H_V001/summary?keywords=Hydrology" rel="nofollow">http://disc.sci.gsfc.nasa.gov/uui/datasets/GLDAS_NOAH025SUBP_3H_V001/summary?keywords=Hydrology</a>)</p>
<p>I am attempting to download about 50k files, here is an example of one, which works when pasted into google chrome browser (if you have proper username and password): </p>
<p><a href="http://hydro1.gesdisc.eosdis.nasa.gov/daac-bin/OTF/HTTP_services.cgi?FILENAME=%2Fdata%2FGLDAS_V1%2FGLDAS_NOAH025SUBP_3H%2F2016%2F244%2FGLDAS_NOAH025SUBP_3H.A2016244.2100.001.2016256190725.grb&FORMAT=TmV0Q0RGLw&BBOX=-11.95%2C28.86%2C-0.62%2C40.81&LABEL=GLDAS_NOAH025SUBP_3H.A2016244.2100.001.2016286201048.pss.nc&SHORTNAME=GLDAS_NOAH025SUBP_3H&SERVICE=SUBSET_GRIB&VERSION=1.02&LAYERS=AAAB&DATASET_VERSION=001" rel="nofollow">http://hydro1.gesdisc.eosdis.nasa.gov/daac-bin/OTF/HTTP_services.cgi?FILENAME=%2Fdata%2FGLDAS_V1%2FGLDAS_NOAH025SUBP_3H%2F2016%2F244%2FGLDAS_NOAH025SUBP_3H.A2016244.2100.001.2016256190725.grb&FORMAT=TmV0Q0RGLw&BBOX=-11.95%2C28.86%2C-0.62%2C40.81&LABEL=GLDAS_NOAH025SUBP_3H.A2016244.2100.001.2016286201048.pss.nc&SHORTNAME=GLDAS_NOAH025SUBP_3H&SERVICE=SUBSET_GRIB&VERSION=1.02&LAYERS=AAAB&DATASET_VERSION=001</a></p>
<p>Anyone have any experience getting OPeNDAP NASA data from the web using python? I am happy to provide more information if desired. </p>
<p>Here is the requests attempt which gives 401 error:</p>
<pre><code>import requests
def httpdownload():
'''loop through each line in the text file and open url'''
httpfile = open(pathlist[0]+"NASAdownloadSample.txt", "r")
for line in httpfile:
print line
outname = line[-134:-122]+".hdf"
print outname
username = ""
password = "*"
r = requests.get(line, auth=("username", "password"), stream=True)
print r.text
print r.status_code
with open(pathlist[0]+outname, 'wb') as out:
out.write(r.content)
print outname, "finished" # keep track of progress
</code></pre>
<p>And here is the pydap example which gives redirect error:</p>
<pre><code>import install_cas_client
from pydap.client import open_url
def httpdownload():
'''loop through each line in the text file and open url'''
username = ""
password = ""
httpfile = open(pathlist[0]+"NASAdownloadSample.txt", "r")
fileone = httpfile.readline()
filetot = fileone[:7]+username+":"+password+"@"+fileone[7:]
print filetot
dataset = open_url(filetot)
</code></pre>
| 2 | 2016-10-17T14:14:02Z | 40,110,569 | <p>I did not find a solution using python, but given the information I have now it should be possible. I used wget with a .netrc file and cookie file shown as follows (<a href="http://disc.sci.gsfc.nasa.gov/recipes/?q=recipes/How-to-Download-Data-Files-from-HTTP-Service-with-wget" rel="nofollow">http://disc.sci.gsfc.nasa.gov/recipes/?q=recipes/How-to-Download-Data-Files-from-HTTP-Service-with-wget</a>):</p>
<pre><code>#!/bin/bash
cd # path to output files
touch .netrc
echo "machine urs.earthdata.nasa.gov login <username> password <password>" >> .netrc
chmod 0600 .netrc
touch .urs_cookies
wget --content-disposition --trust-server-names --load-cookies ~/.urs_cookies --save-cookies ~/.urs_cookies --auth-no-challenge=on --keep-session-cookies
-i <path to text file of url list>
</code></pre>
<p>Hope it helps anyone else working with NASA data from this server. </p>
| 2 | 2016-10-18T14:11:44Z | [
"python",
"httprequest",
"netcdf",
"opendap"
] |
Convert directory structure to json? | 40,088,789 | <p>I want to convert a project hierarchy with some properties for each class or package in a JSON dictionary. for example</p>
<p>I am using python for this. Can anyone please give me some basic outline. How I can implement this.Thank you. thus i want something like:</p>
<pre><code>a = package, a.b = package, a.b.c = class, a.b.d = class
j_string = {
"my_data": {
"a": "info": {},
"b": {
"info": {},
"c": {
"info": {}
},
"d": {
"info": {}
}
}
}
}
</code></pre>
| 1 | 2016-10-17T14:15:59Z | 40,089,320 | <p>try to use <code>pkgutil.walk_packages</code> combine with <code>importlib.import_module</code>.</p>
<pre><code>def get_all_module_of_a_package(pkg_name):
pkg = importlib.import_module(pkg_name)
for importer, name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.'):
if is_pkg:
continue
print name # I just print them, you can build a dict you desired
# do some other things (if you want to get member of a module)
# use inspect.getmembers
>>> get_all_module_of_a_package('json')
json.decoder
json.encoder
json.scanner
json.tests.test_check_circular
json.tests.test_decode
json.tests.test_default
json.tests.test_dump
json.tests.test_encode_basestring_ascii
json.tests.test_fail
json.tests.test_float
json.tests.test_indent
json.tests.test_pass1
json.tests.test_pass2
json.tests.test_pass3
json.tests.test_recursion
json.tests.test_scanstring
json.tests.test_separators
json.tests.test_speedups
json.tests.test_tool
json.tests.test_unicode
json.tool
</code></pre>
| 0 | 2016-10-17T14:40:51Z | [
"python",
"json"
] |
How this code convert to arduino | 40,088,907 | <p>I have a problem with implement this python algorithm to arduino. Help me to do this..</p>
<pre><code>def Process(lst):
for k in range(len(lst)):
for i in range(len(lst)-1):
if abs(lst[i]-lst[i+1])==2 and lst[i+1]!=0:
for j in range(i,len(lst)-2):
lst[j]=lst[j+2]
lst[-1]=lst[-2]=0
return(lst)
</code></pre>
| 0 | 2016-10-17T14:21:26Z | 40,094,496 | <p>Some ideas to get you started:
You don't really have lists in C on the Arduino. A data structure you could use there is an array. See <a href="https://www.arduino.cc/en/Reference/Array" rel="nofollow">https://www.arduino.cc/en/Reference/Array</a> for more info.</p>
<p>Passing around arrays to e.g. functions is done via a pointer to the first element of the array. Since this is not enough information to determine the size of an array you typically also provide the size/number of elements. This leads to a possible signature of the function:</p>
<pre><code>int* process(int* lst, int numberOfElements) { ... }
</code></pre>
<p><code>range(n)</code> in Python returns all numbers from 0 to n-1. In order to do the same in C and iterate over the elements of an array you basically loop from 0 to numberOfElements-1. You can then access the elements in the array by their index, i.e.:</p>
<pre><code>for(int i = 0; i < numberOfElements; i++) {
(...)
lst[i] = lst[j + 2];
}
</code></pre>
<p>Hope this is enough information to get you started.</p>
| 0 | 2016-10-17T19:48:27Z | [
"python",
"arduino"
] |
recursion: make changes with fewest coins | 40,088,908 | <p>I'm studing the data structure and algorithm in python. Here is the classic problem of recursion involving making change with the fewest coins. Here are the codes.
What I do not understand is line 2. why do we need <code>minCoins = change</code>? what does line 8-9 mean? can anyone helo explain that? thank you very much for help!</p>
<pre><code>def recMC(coinValueList,change):
minCoins = change
if change in coinValueList:
return 1
else:
for i in [c for c in coinValueList if c <= change]:
numCoins = 1 + recMC(coinValueList,change-i)
if numCoins < minCoins:
minCoins = numCoins
return minCoins
print(recMC([1,5,10,25],63))
</code></pre>
| -1 | 2016-10-17T14:21:28Z | 40,089,188 | <p><code>minCoins = change</code>: <code>minCoins</code> is initialized with the value of <code>change</code> which is the maximum value that <code>recMC</code> can return as the minimum value of a coin is 1, assuming integer values of coins.</p>
<p><code>if change in coinValueList: return 1</code>: base case 1 - if some coin has a value of that of <code>change</code> we just need to grab this 1 coin, thus returning 1</p>
<p> <code>for i in [c for c in coinValueList if c <= change]:</code>:
The function then loops through all possible values of 1 single coin to</p>
<p>  <code>numCoins = 1 + recMC(coinValueList,change-i)</code>: deduct the coin value <code>i</code> from <code>change</code>, add 1 coin to the number of coins needed which is recursively calculated for the leftover change (<code>change-i</code>). This works inductively from the <em>2</em> base cases</p>
<p>  <code>if numCoins < minCoins: minCoins = numCoins</code> inside this loop effectively assigns the smallest number of coins possible to <code>minCoins</code></p>
<p>If <code>change</code> still had the initialized value of <code>minCoins</code> (implying no value <code>c</code> in <code>coinValueList</code> satisfies <code>c <= change</code>), this means that the number of coins needed is also the value of <code>change</code>, i.e. <code>change</code> 1-unit coins. This is base case 2 that is based on the pre-condition that the coin with value 1 is always available.</p>
| 1 | 2016-10-17T14:34:45Z | [
"python",
"algorithm",
"recursion"
] |
Code that makes cyclic reference for x spaces in list | 40,088,930 | <p>I have a tasko to make a program in which i get m, n and k. I should create a list a with <code>n*m</code> element.
List <code>b</code> is supposed to have <code>n*m</code> element. It is created from list a with cyclic shift k to the right for m elements of lists.
I know it is poorly explained. Example is:</p>
<pre><code>n=3
m=4
A=1 2 3 4 5 6 7 8 9 10 11 12
k=1
B=4 1 2 3 8 5 6 7 12 9 10 11
</code></pre>
<p>What i have at the moment is:</p>
<pre><code>from random import randint
n = int(input())
m=int(input())
A = []
B=[0]
B=B*n*m
for i in range(n*m):
A = A + [randint(1, 30)]
print('\nLista A:\n')
for i in range(n*m):
print(A[i], end = ' ')
print()
k=int(input())
for i in range(-1, m*n, m):
B[m-1-i]=A[i]
print(B[m-1-i])
print('\nLista B:\n')
for i in range(n*m):
print(B[i], end = ' ')
</code></pre>
<p>Thanks</p>
| 2 | 2016-10-17T14:22:35Z | 40,089,268 | <p>Try this... </p>
<pre><code># Start with an empty list
B = []
# Take A in chunks of m
for i in range( int(len(A)/m) ):
# Take an m-sized chunk of A
chunk = A[m*i:m*(i+1)]
# Shift it to the right by k (python style!)
shift = chunk[-k:] + chunk[:-k]
# Add it to B
B += shift
print (B)
</code></pre>
| 1 | 2016-10-17T14:38:32Z | [
"python",
"list",
"cyclic-reference"
] |
Code that makes cyclic reference for x spaces in list | 40,088,930 | <p>I have a tasko to make a program in which i get m, n and k. I should create a list a with <code>n*m</code> element.
List <code>b</code> is supposed to have <code>n*m</code> element. It is created from list a with cyclic shift k to the right for m elements of lists.
I know it is poorly explained. Example is:</p>
<pre><code>n=3
m=4
A=1 2 3 4 5 6 7 8 9 10 11 12
k=1
B=4 1 2 3 8 5 6 7 12 9 10 11
</code></pre>
<p>What i have at the moment is:</p>
<pre><code>from random import randint
n = int(input())
m=int(input())
A = []
B=[0]
B=B*n*m
for i in range(n*m):
A = A + [randint(1, 30)]
print('\nLista A:\n')
for i in range(n*m):
print(A[i], end = ' ')
print()
k=int(input())
for i in range(-1, m*n, m):
B[m-1-i]=A[i]
print(B[m-1-i])
print('\nLista B:\n')
for i in range(n*m):
print(B[i], end = ' ')
</code></pre>
<p>Thanks</p>
| 2 | 2016-10-17T14:22:35Z | 40,089,666 | <p>Alternative:</p>
<pre><code>m=4
n=3
k=1
A=list(range(1,1+m*n))
print (A)
t_1=[A[_:_+4] for _ in range(0,len(A), 4)]
print (t_1)
t_2=[]
for sublist in t_1:
t_2.append(sublist[-k:]+sublist[:-k])
print (t_2)
B=[]
for sublist in t_2:
B.extend(sublist)
print (B)
</code></pre>
<p>If you want greater speed then you could use a <strong>deque</strong> from the <strong>collections</strong> module to build <strong>t_2</strong>.</p>
<p>Here's the result.</p>
<pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[4, 1, 2, 3], [8, 5, 6, 7], [12, 9, 10, 11]]
[4, 1, 2, 3, 8, 5, 6, 7, 12, 9, 10, 11]
</code></pre>
| 0 | 2016-10-17T14:56:58Z | [
"python",
"list",
"cyclic-reference"
] |
Django add common conditions in model | 40,089,017 | <p>I have model </p>
<pre><code>class QuerySetManager(models.Manager):
def get_query_set(self):
return self.model.QuerySet(self.model)
class Post(models.Model):
objects = QuerySetManager()
STATUS = (
(1, 'PENDING'),
(2, 'ACTIVE'),
)
title = models.CharField(max_length=512,blank=False,null=True)
status = models.IntegerField(default=1,choices=STATUS)
class QuerySet(models.query.QuerySet):
def active(self):
return self.filter(status=2)
</code></pre>
<p>When I try to access this way</p>
<pre><code>Post.objects.active().filter(other_condition='xxx').all()
</code></pre>
<p>it throws error <code>'QuerySetManager' object has no attribute 'active'</code></p>
<p>Can anyone help me to achieve this?</p>
| 0 | 2016-10-17T14:26:43Z | 40,089,165 | <p>I can't understand what you're doing here at all. The way to get a manager to return a queryset with the same methods is to use the <a href="https://docs.djangoproject.com/en/1.10/topics/db/managers/#creating-a-manager-with-queryset-methods" rel="nofollow"><code>as_manager</code> classmethod</a>.</p>
<pre><code>class PostQuerySet(models.QuerySet):
def active(self):
return self.filter(status=2)
class Post(models.Model):
objects = PostQuerySet.as_manager()
</code></pre>
| 0 | 2016-10-17T14:33:46Z | [
"python",
"django"
] |
Fill missing categorial values using pandas? | 40,089,042 | <p>I'd like to fill missing categorial cells with new values per column. For example:</p>
<pre><code>c1 c2 c3
a nan a
b q nan
c d nan
a p z
</code></pre>
<p>should become something like</p>
<pre><code>c1 c2 c3
a n1 a
b q n2
c d n2
a p z
</code></pre>
<p>My current problem is that I am using DictVectorizer for categorials column, but it leaves NaNs as-is.</p>
| 1 | 2016-10-16T21:51:30Z | 40,089,043 | <p>Fillna with some uniq string does what you want:</p>
<pre><code>categorial_data = pd.DataFrame({'sex': ['male', 'female', 'male', 'female'],
'nationality': ['American', 'European', float('nan'), 'European']})
print(categorial_data)
categorial_data=categorial_data.fillna('some_unique_string')
print('after replacement')
print(categorial_data)
encoder = DV(sparse = False)
encoded_data = encoder.fit_transform(categorial_data.T.to_dict().values())
print(encoded_data)
</code></pre>
<p>gives you</p>
<pre><code> nationality sex
0 American male
1 European female
2 NaN male
3 European female
after replacement
nationality sex
0 American male
1 European female
2 some_unique_string male
3 European female
[[ 1. 0. 0. 0. 1.]
[ 0. 1. 0. 1. 0.]
[ 0. 0. 1. 0. 1.]
[ 0. 1. 0. 1. 0.]]
</code></pre>
| 0 | 2016-10-16T23:47:28Z | [
"python",
"missing-data",
"pandas"
] |
Difference between GET data as a function parameter and an item from requests.arg | 40,089,134 | <p>I would like to know if there is any difference between:</p>
<pre><code>@app.route('/api/users/<int:id>', methods=['GET'])
def get_user(id):
pass # handle user here with given id
</code></pre>
<p>and</p>
<pre><code>@app.route('/api/users')
def get_user():
id = request.args.get('id')
# handle user here with given id
</code></pre>
<p>Furthermore, is there a way to get multiple parameters in the former? Can they be optional parameters?</p>
| 2 | 2016-10-17T14:32:33Z | 40,089,289 | <p>Yes, it is. </p>
<p>First method:</p>
<pre><code>@app.route('/api/users/<int:id>', methods=['GET']
def get_user(id):
pass # handle user here with given id
</code></pre>
<p>Defines a route and a method. This function is only triggered with this method over this path.</p>
<p>Second method:</p>
<pre><code>@app.route('/api/users')
def get_user():
id = request.args.get('id')
# handle user here with given id
</code></pre>
<p>It just defines a route. You can execute the function with all methods. </p>
<p>The route in the first method is: <code>webexample.com/api/users/1</code> for user 1</p>
<p>The route in the second one is: <code>webexample.com/api/users?id=1</code> for user 1</p>
| 2 | 2016-10-17T14:39:43Z | [
"python",
"python-3.x",
"flask",
"flask-restful"
] |
Difference between GET data as a function parameter and an item from requests.arg | 40,089,134 | <p>I would like to know if there is any difference between:</p>
<pre><code>@app.route('/api/users/<int:id>', methods=['GET'])
def get_user(id):
pass # handle user here with given id
</code></pre>
<p>and</p>
<pre><code>@app.route('/api/users')
def get_user():
id = request.args.get('id')
# handle user here with given id
</code></pre>
<p>Furthermore, is there a way to get multiple parameters in the former? Can they be optional parameters?</p>
| 2 | 2016-10-17T14:32:33Z | 40,089,844 | <p>The main difference is that the URL triggering your function will be different. </p>
<p>If you use the flask function <a href="http://flask.pocoo.org/docs/0.11/api/#flask.url_for" rel="nofollow">url_for</a>(that i REALLY recommend), the URL structure returned by the function will be different because all the variables that you use and are not part of the endpoint will be treated like query parameters. </p>
<p>So in this case you can change your route without impacting your existing codebase. </p>
<p>In other words in your case you would have: </p>
<p>Using method variables: </p>
<pre><code>url_for('get_user', id=1) => '/api/users/1'
</code></pre>
<p>Without method variables:</p>
<pre><code>url_for('get_user', id=1) => '/api/users?id=1'
</code></pre>
<p>Which approach is better depends from the context you are working on.
If you want to realize a REST based API you should define the identifiers argument as path arguments and the metadata as query arguments(you can read more about that <a href="https://tools.ietf.org/html/rfc3986" rel="nofollow">here</a>). </p>
| 1 | 2016-10-17T15:06:30Z | [
"python",
"python-3.x",
"flask",
"flask-restful"
] |
export tables from google bigquery to google storage | 40,089,238 | <p>I'm new on bigQuery. I need to export tables from BigQuery to google storage.
For the moment, I can list all tables by dataset.
Does some boody can help me with how can I export then tables?
My python code is below :</p>
<pre><code>#!/usr/bin/env python
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from bigquery_client import client
credentials = GoogleCredentials.get_application_default()
service = discovery.build('bigquery', 'v2', credentials=credentials)
# * Project ID of the datasets to be listed
projectId = 'xxxxxxxxx'
datasets = service.datasets()
request = datasets.list(projectId=projectId)
response = request.execute()
for dataset in response['datasets']:
datasetId = dataset['datasetReference']['datasetId']
tables = service.tables()
request = tables.list(projectId=projectId, datasetId=datasetId)
response = request.execute()
if 'tables' in response :
for table in response['tables']:
print ('Dataset name treated is :' + '%s' % dataset['datasetReference']['datasetId'])
print ('%s' % dataset['datasetReference']['datasetId'])
print ('Is table number:' + '%s' % table['tableReference']['tableId'])
</code></pre>
<p>Thanks</p>
| 0 | 2016-10-17T14:37:11Z | 40,089,413 | <p>There is a full Python example on the docs page. Two functions you need is there.
<a href="https://cloud.google.com/bigquery/docs/exporting-data" rel="nofollow">https://cloud.google.com/bigquery/docs/exporting-data</a></p>
<p>including here for future reference:</p>
<pre><code>def export_data_to_gcs(dataset_name, table_name, destination):
bigquery_client = bigquery.Client()
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(table_name)
job_name = str(uuid.uuid4())
job = bigquery_client.extract_table_to_storage(
job_name, table, destination)
job.begin()
wait_for_job(job)
print('Exported {}:{} to {}'.format(
dataset_name, table_name, destination))
</code></pre>
<p>and the second</p>
<pre><code>def wait_for_job(job):
while True:
job.reload()
if job.state == 'DONE':
if job.error_result:
raise RuntimeError(job.error_result)
return
time.sleep(1)
</code></pre>
| 0 | 2016-10-17T14:44:59Z | [
"python",
"google-bigquery"
] |
I cannot get pygame to work with python | 40,089,274 | <p>I have had a few dozen attempts at installing pygame to my python. I have tried many different versions of the programs.</p>
<p>I am running a 64 bit version of windows 10, and seem to be required to use an unofficial .whl file to get pygame, however i do not know how to use this file. </p>
<p>I have tried running several variants of commands that was explained in many areas, however they all ether return errors, or yield no success. </p>
<p>Am i doing something wrong?</p>
| -2 | 2016-10-17T14:38:48Z | 40,089,479 | <p>Download the correct .whl file from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame" rel="nofollow">here</a> and save this file to whatever directory you like. Open a command prompt and navigate to the directory where you saved the .whl file.</p>
<p>Lets say you downloaded the file <code>pygame-1.9.2b1-cp27-cp27m-win_amd64.whl</code> and saved it into <code>my_directory</code>, then you would enter the following commands:</p>
<p><code>cd c:\my_directory</code></p>
<p><code>pip install pygame-1.9.2b1-cp27-cp27m-win_amd64.whl</code></p>
<p>Note: You must download the correct .whl file for your system and for your version of Python.</p>
| 0 | 2016-10-17T14:47:57Z | [
"python",
"windows",
"installation",
"pygame",
"64bit"
] |
How to convert this comprehension to a for-loop in Python? | 40,089,306 | <pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']]
base_counts = [[Counter(base) for base in sub] for sub in sample]
#Output : [[Counter({'G': 2, 'C': 1}), Counter({'T': 2, 'A': 1})], [Counter({'C': 2, 'G': 2}), Counter({'A': 3, 'T': 1})]]
base_freqs = [[{k_v[0]:k_v[1]/len(bases[i]) for i,k_v in enumerate(count.items())} for count in counts] for counts, bases in zip(base_counts, sample)]
#Output 2 [[{'C': 0.3333333333333333, 'G': 0.6666666666666666}, {'A': 0.3333333333333333, 'T': 0.6666666666666666}], [{'C': 0.5, 'G': 0.5}, {'A': 0.75, 'T': 0.25}]]
</code></pre>
<p>The sample is the input and the Output2 is the final output of the program. The program with base_freqs, computes the frequency of "bases" (bases = ATGC) in each pair of the sample. The output provides the correct answer. However, I would like to see the code in a for-loop format than comprehensions. </p>
<p>This code has been originally taken from the answer posted <a href="http://stackoverflow.com/a/40076570/6820344">here</a></p>
| 0 | 2016-10-17T14:40:17Z | 40,089,448 | <p>It's not really easier with for loop, but here is how it should look like.</p>
<pre><code>result = []
for counts, bases in zip(base_counts, sample):
some_list = []
for count in counts:
some_dict = {}
for i,k_v in enumerate(count.items()):
some_dict[k_v[0]] = k_v[1]/len(bases[i])
some_list.append(some_dict)
result.append(some_list)
</code></pre>
| 1 | 2016-10-17T14:46:16Z | [
"python",
"for-loop",
"for-comprehension"
] |
How to convert this comprehension to a for-loop in Python? | 40,089,306 | <pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']]
base_counts = [[Counter(base) for base in sub] for sub in sample]
#Output : [[Counter({'G': 2, 'C': 1}), Counter({'T': 2, 'A': 1})], [Counter({'C': 2, 'G': 2}), Counter({'A': 3, 'T': 1})]]
base_freqs = [[{k_v[0]:k_v[1]/len(bases[i]) for i,k_v in enumerate(count.items())} for count in counts] for counts, bases in zip(base_counts, sample)]
#Output 2 [[{'C': 0.3333333333333333, 'G': 0.6666666666666666}, {'A': 0.3333333333333333, 'T': 0.6666666666666666}], [{'C': 0.5, 'G': 0.5}, {'A': 0.75, 'T': 0.25}]]
</code></pre>
<p>The sample is the input and the Output2 is the final output of the program. The program with base_freqs, computes the frequency of "bases" (bases = ATGC) in each pair of the sample. The output provides the correct answer. However, I would like to see the code in a for-loop format than comprehensions. </p>
<p>This code has been originally taken from the answer posted <a href="http://stackoverflow.com/a/40076570/6820344">here</a></p>
| 0 | 2016-10-17T14:40:17Z | 40,089,532 | <p>Yes. The way to read comprehensions in outside in and left to right. Let's format it a little for readability:</p>
<pre><code>base =[
[
{ k_v[0] : k_v[1]/len(bases[i])
for i,k_v in enumerate(count.items())
}
for count in counts
]
for counts, bases in zip(base_counts, sample)
]
</code></pre>
<p>Is the same as:</p>
<pre><code>bases = []
for counts, bases in zip(base_counts, sample):
temp_list = []
for count in counts:
temp_dict = {}
for i, k_v in enumerate(count.items()):
temp_dict[k_v[0]] = k_v[1] / len(bases[i])
temp_list.append(temp_dict)
bases.append(temp_list)
</code></pre>
<p>The list comprehension is better from a performance standpoint because you aren't constantly creating new lists and dicts, or calling methods like append, which have some overhead. </p>
| 2 | 2016-10-17T14:50:22Z | [
"python",
"for-loop",
"for-comprehension"
] |
How to convert this comprehension to a for-loop in Python? | 40,089,306 | <pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']]
base_counts = [[Counter(base) for base in sub] for sub in sample]
#Output : [[Counter({'G': 2, 'C': 1}), Counter({'T': 2, 'A': 1})], [Counter({'C': 2, 'G': 2}), Counter({'A': 3, 'T': 1})]]
base_freqs = [[{k_v[0]:k_v[1]/len(bases[i]) for i,k_v in enumerate(count.items())} for count in counts] for counts, bases in zip(base_counts, sample)]
#Output 2 [[{'C': 0.3333333333333333, 'G': 0.6666666666666666}, {'A': 0.3333333333333333, 'T': 0.6666666666666666}], [{'C': 0.5, 'G': 0.5}, {'A': 0.75, 'T': 0.25}]]
</code></pre>
<p>The sample is the input and the Output2 is the final output of the program. The program with base_freqs, computes the frequency of "bases" (bases = ATGC) in each pair of the sample. The output provides the correct answer. However, I would like to see the code in a for-loop format than comprehensions. </p>
<p>This code has been originally taken from the answer posted <a href="http://stackoverflow.com/a/40076570/6820344">here</a></p>
| 0 | 2016-10-17T14:40:17Z | 40,089,596 | <p>You can always translate a list comprehension such as</p>
<pre><code>ls = [<EXPR> for <VARS> in <ITERABLE> if <CONDITIONAL>]
</code></pre>
<p>to</p>
<pre><code>ls = []
for <VARS> in <ITERABLE>:
if <CONDITIONAL>:
ls.append(<EXPR>)
</code></pre>
<p>Multiple <code>for</code> clauses in the comprehension correspond to nested <code>for</code> loops in the translation, with the leftmost <code>for</code> clause corresponding to the outermost <code>for</code> loop. </p>
<p>Translations for generator, dict and set comprehensions are analogous.</p>
| 2 | 2016-10-17T14:53:05Z | [
"python",
"for-loop",
"for-comprehension"
] |
python 2.6 - print French characters | 40,089,612 | <p>My question regarding printing French characters with python 2.6.
There is no problems when I use python 3.4 but I need using python 2.6!
Instead of société mère I've got société mère etc.
I already tried:</p>
<pre><code>#!/usr/bin/python
# coding=utf-8
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: iso-8859-1 -*-
</code></pre>
<p>without success.
I create a .csv file and need to fill headings with French titles. Also, some French characters will be input from .xml file.</p>
<p>Thanks in advance</p>
| 1 | 2016-10-17T14:54:15Z | 40,089,742 | <p>Try prefixing your string literals with u:</p>
<pre><code>print u'société mère'
</code></pre>
<p>Docs: <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">https://docs.python.org/2/howto/unicode.html</a></p>
| 1 | 2016-10-17T15:00:33Z | [
"python",
"python-2.6",
"non-ascii-characters"
] |
creating two separate lists read from a file in python | 40,089,617 | <p>Can i please know how the data from a file can be split into two separate lists. For example,
file contains data as 1,2,3,4;5,6,7 </p>
<pre><code>my code:
for num in open('filename','r'):
list1 = num.strip(';').split()
</code></pre>
<p>Here , i want a new list before semi colon (i.e) [1,2,3,4] and new list after semi colon (i.e) [5,6,7]</p>
| 0 | 2016-10-17T14:54:28Z | 40,089,733 | <p>Depending on the size of your file, you could simply read the whole file into a string at once and then first split by semicolon, then by comma:</p>
<pre class="lang-python prettyprint-override"><code>with open('filename', 'r') as f: #open file
s = f.read() #read entire contents into string
lists = s.split(';') #split separate lists by semicolon delimiters
for l in lists: #for each list
l = [int(x) for x in l.split(',')] #separate the string by commas and convert to integers
</code></pre>
| 0 | 2016-10-17T15:00:04Z | [
"python",
"python-2.7",
"python-3.x"
] |
creating two separate lists read from a file in python | 40,089,617 | <p>Can i please know how the data from a file can be split into two separate lists. For example,
file contains data as 1,2,3,4;5,6,7 </p>
<pre><code>my code:
for num in open('filename','r'):
list1 = num.strip(';').split()
</code></pre>
<p>Here , i want a new list before semi colon (i.e) [1,2,3,4] and new list after semi colon (i.e) [5,6,7]</p>
| 0 | 2016-10-17T14:54:28Z | 40,089,736 | <p>If you are certain that your file only contains 2 lists, you can use a list comprehension:</p>
<pre><code>l1, l2 = [sub.split(',') for sub in data.split(';')]
# l1 = ['1', '2', '3', '4']
# l2 = ['5', '6', '7']
</code></pre>
<p>More generally,</p>
<pre><code>lists = [sub.split(',') for sub in data.split(';')]
# lists[0] = ['1', '2', '3', '4']
# lists[1] = ['5', '6', '7']
</code></pre>
<p>If integers are needed, you can use a second list comprehension:</p>
<pre><code>lists = [[int(item) for item in sub.split(',')] for sub in data.split(';')]
</code></pre>
| 2 | 2016-10-17T15:00:14Z | [
"python",
"python-2.7",
"python-3.x"
] |
creating two separate lists read from a file in python | 40,089,617 | <p>Can i please know how the data from a file can be split into two separate lists. For example,
file contains data as 1,2,3,4;5,6,7 </p>
<pre><code>my code:
for num in open('filename','r'):
list1 = num.strip(';').split()
</code></pre>
<p>Here , i want a new list before semi colon (i.e) [1,2,3,4] and new list after semi colon (i.e) [5,6,7]</p>
| 0 | 2016-10-17T14:54:28Z | 40,089,744 | <p>To get the final list you need to split on <code>","</code> as well (and probably <code>map()</code> the result to <code>int()</code>):</p>
<pre><code>with open("filename") as f:
for line in f:
list1, list2 = [x.split(",") for x in line.rstrip().split(";")]
</code></pre>
| 1 | 2016-10-17T15:00:35Z | [
"python",
"python-2.7",
"python-3.x"
] |
I trying to print sequence but getting KeyError? in python | 40,089,678 | <p>I am getting only first input file correct output but I have A , B, C, D chain in my first file and getting right output, in this case in second input file does't have c and d chain in this case, our code is copying same data of first file data of C and D.? and also I am unable to increase this ids: chainIDs = ['A', 'B', 'C', 'D']</p>
<p>I want to search A to Z chain ID, If I replace with chainIDs = ['A', 'B', 'C', 'D'] to chainIDs = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].</p>
<p>If any chain id is not present in input file then code just ignore and continue for others.</p>
<p>Showing error: </p>
<pre><code>f.write(d[chainID][atomIDs[i+j]]+ '\n')
KeyError: 'E'
</code></pre>
<p>Script:</p>
<pre><code>import os
d = {}
atomIDs = ['C4B', 'O4B', 'C1B', 'C2B', 'C3B', 'C4B', 'O4B', 'C1B']
chainIDs = ['A', 'B', 'C', 'D', 'E', 'F']
with open('filename.txt') as pdbline:
for line in pdbline:
filenames=line[:8]
with open(filenames) as pdbfile:
for line in map(str.rstrip, pdbfile):
if line[:6] != "HETATM":
continue
chainID = line[21:22]
atomID = line[13:16].strip()
if chainID not in chainIDs:
continue
if atomID not in atomIDs:
continue
try:
d[chainID][atomID] = line
except KeyError:
d[chainID] = {atomID: line}
n = 4
for chainID in chainIDs:
for i in range(len(atomIDs)-n+1):
for j in range(n):
f = open(filenames+'out.pdb', 'a')
f.write(d[chainID][atomIDs[i+j]]+ '\n')
f.close()
</code></pre>
<p>First Input File:</p>
<pre><code>HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C
HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O
HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C
HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C
HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C
HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C
HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O
HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C
HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C
HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C
HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C
HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O
HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C
HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C
HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C
HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C
HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O
HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C
HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C
HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C
</code></pre>
<p>Second Input File:</p>
<pre><code>HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
</code></pre>
<p>Getting Result for Second File:</p>
<pre><code>HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C
HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O
HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C
HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C
HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O
HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C
HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C
HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C
HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C
HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C
HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C
HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C
HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C
HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C
HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C
HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O
HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C
HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C
HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O
HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C
HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C
HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O
HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C
HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C
HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O
HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C
HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C
HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C
HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C
HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C
HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C
HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C
HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C
HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C
HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C
HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O
HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C
HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C
HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O
HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C
HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C
HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O
HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C
HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C
HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O
HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C
HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C
HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C
HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C
HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C
HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C
HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C
HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C
HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C
HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C
HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O
HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C
HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C
HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O
HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C
</code></pre>
<p><strong>Expected Output: I want to print all chain ID in present input file in following sequence (Only present chain id):</strong></p>
<pre><code>HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2475 C2B NAD A 352 91.477 22.027 50.635 1.00 48.07 C
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2473 C3B NAD A 352 90.818 23.341 50.501 1.00 49.46 C
HETATM 2471 C4B NAD A 352 91.432 24.158 51.658 1.00 51.58 C
HETATM 2472 O4B NAD A 352 92.697 23.519 52.005 1.00 47.28 O
HETATM 2477 C1B NAD A 352 92.868 22.416 51.075 1.00 49.66 C
</code></pre>
| 0 | 2016-10-17T14:57:46Z | 40,091,354 | <p>Just change the output loop to something like this:</p>
<pre><code>for chainID in chainIDs:
if chainID in d:
for atom_id in d[chainID]:
with open(filenames+'out.pdb', 'a') as f:
f.write(d[chainID][atom_id] + '\n')
</code></pre>
| 0 | 2016-10-17T16:28:27Z | [
"python",
"python-2.7",
"python-3.x",
"bioinformatics"
] |
Sharing global information across requests to flask endpoints on heroku | 40,089,685 | <p>I have a flask application with a single endpoint, like this (simplified below):</p>
<pre><code>@app.route('/classify', methods=['POST'])
def classify():
p = g.model_loader.get_model()
json = request.get_json()
text = json['text']
return p.classify(text)
def main():
model_loader = ResourceLoader()
with app.app_context():
g.model_loader = model_loader
app.run()
if __name__ == '__main__':
main()
</code></pre>
<p>The application needs to load a machine learning model into memory once, <strong>in the <code>main</code> method</strong>, and then use that model to classify text that is being sent via POST to a flask endpoint. I've tried to do this using an application context, which works locally, but doesn't work on heroku. My understanding currently is that this is because the application context isn't shared across workers. How can I give the <code>classify</code> endpoint access to the model loader?</p>
<p>EDIT: I didn't word the initial question correctly. Each worker should run <code>main()</code> and should thus have access to <code>model_loader</code> in its own application context. However, when I run this on heroku, I get <code>AttributeError: '_AppCtxGlobals' object has no attribute 'model_loader'</code>. Does the application context differ on heroku?</p>
| 0 | 2016-10-17T14:57:59Z | 40,089,812 | <p>You can't load it into memory once, because Heroku workers might be on completely different machines. You need to run this code in every worker, or store the data somewhere it can be read by any process.</p>
| 0 | 2016-10-17T15:04:27Z | [
"python",
"heroku",
"flask"
] |
BeautifulSoup parse table data that doesn't load immediately | 40,089,724 | <p>I'm trying to download earnings announcement data from <a href="https://www.zacks.com/stock/research/MMM/earnings-announcements" rel="nofollow">https://www.zacks.com/stock/research/MMM/earnings-announcements</a> using beautifulsoup. When I look at the tables, the table I am interested in (earnings_announcements_earnings_table) shows only "Loading Dataâ¦". However, if I print the entire contents of the soup, I do see the information I am looking for is in there. I can isolate this data just a "script" element, but that contains a lot of other unwanted info. How can I select and parse just the specific data I'm looking for, which is the contents of the "earnings_announcements_earnings_table" table, which looks like this:</p>
<p>" var obj = {
"earnings_announcements_earnings_table" :
[ [ "10/25/2016", "9/2016", "$2.14", "--", "--", "Before Open" ] ,..."</p>
<p>Here is what I have so far:</p>
<pre><code>from urllib import request
from urllib import error
from bs4 import BeautifulSoup
def download_parse_earnings(symbol):
request_string = "https://www.zacks.com/stock/research/%s/earnings-announcements" % symbol
print(request_string)
try:
web = request.urlopen(request_string)
except error.HTTPError:
return
soup = BeautifulSoup(web.read(), 'lxml')
data = soup.find_all("script")[28].string
print(data)
</code></pre>
| 0 | 2016-10-17T14:59:40Z | 40,089,939 | <p>One way would be to fire up Selenium and make use of its Javascript engine. That's not really simple, and I offer here an alternative solution which is a total hack, but it should work for the pages you are interested in.</p>
<p>Assuming the pages are generated automatically, we observe that the data you want is in (continuing from you program):</p>
<pre><code>import json
earnings = json.loads(data.split('var obj =')[1].splitlines()[2])
</code></pre>
<p>This is leveraging the fact that Javascript objects are JSON, and so we read directly from the source. The result is a list of lists like this one:</p>
<pre><code>[['10/25/2016', '9/2016', '.14', '--', '--', 'Before Open'],
['7/26/2016',
'6/2016',
'.08',
'.08',
'<div class=right pos_na showinline>0.00 (0.00%)</div>',
'Before Open'],
['4/26/2016',
'3/2016',
'.92',
'.05',
'<div class=right pos positive pos_icon showinline up>0.13 (6.77%)</div>',
'Before Open'],
['1/26/2016',
'12/2015',
'.62',
'.80',
'<div class=right pos positive pos_icon showinline up>0.18 (11.11%)</div>',
'Before Open'],
['10/22/2015',
'9/2015',
'.01',
'.05',
'<div class=right pos positive pos_icon showinline up>0.04 (1.99%)</div>',
'Before Open'],
...
]
</code></pre>
<p>The first element corresponds to the first row of the table, i.e. the header. You just have to clean up the data now.</p>
| 1 | 2016-10-17T15:10:58Z | [
"python",
"beautifulsoup"
] |
BeautifulSoup parse table data that doesn't load immediately | 40,089,724 | <p>I'm trying to download earnings announcement data from <a href="https://www.zacks.com/stock/research/MMM/earnings-announcements" rel="nofollow">https://www.zacks.com/stock/research/MMM/earnings-announcements</a> using beautifulsoup. When I look at the tables, the table I am interested in (earnings_announcements_earnings_table) shows only "Loading Dataâ¦". However, if I print the entire contents of the soup, I do see the information I am looking for is in there. I can isolate this data just a "script" element, but that contains a lot of other unwanted info. How can I select and parse just the specific data I'm looking for, which is the contents of the "earnings_announcements_earnings_table" table, which looks like this:</p>
<p>" var obj = {
"earnings_announcements_earnings_table" :
[ [ "10/25/2016", "9/2016", "$2.14", "--", "--", "Before Open" ] ,..."</p>
<p>Here is what I have so far:</p>
<pre><code>from urllib import request
from urllib import error
from bs4 import BeautifulSoup
def download_parse_earnings(symbol):
request_string = "https://www.zacks.com/stock/research/%s/earnings-announcements" % symbol
print(request_string)
try:
web = request.urlopen(request_string)
except error.HTTPError:
return
soup = BeautifulSoup(web.read(), 'lxml')
data = soup.find_all("script")[28].string
print(data)
</code></pre>
| 0 | 2016-10-17T14:59:40Z | 40,091,287 | <p>Without using Selenium but still using json as in the first answer you can dig out the content you need with BS.</p>
<pre><code>>>> from bs4 import BeautifulSoup
>>> from urllib import request
>>> URL='https://www.zacks.com/stock/research/MMM/earnings-announcements'
>>> HTML=request.urlopen(URL).read()
>>> soup=BeautifulSoup(HTML)
>>> import json
>>> scripts=soup.findAll('script')
>>> len(scripts)
36
>>> for script in scripts:
... if script.has_attr('type') and script.attrs['type']=='text/javascript' and script.text.strip().startswith('$(document).ready(function()'):
... break
</code></pre>
<p>With this the javascript becomes available as script.text. You would still need to do something mildly clever to extract the lines shown in <a href="http://stackoverflow.com/users/448496/rubik">Rubik's</a> answer. Nothing like impossible though.</p>
| 0 | 2016-10-17T16:24:10Z | [
"python",
"beautifulsoup"
] |
Perfect Square function that doesn't return | 40,089,750 | <p>I'm a beginner working with Python and I was given this task: <em>write a function which returns the highest perfect square which is less or equal to its parameter (a positive integer).</em></p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
if xy != n:
print (("%s is not a perfect square.") % (n))
x -= 1
print (("%s is the next highest perfect square.") % (xy))
else:
return(print(("%s is a perfect square of %s.") % (n, x)))
</code></pre>
<p>When I run the code to execute the function it doesn't output anything. I'll admit, I'm struggling and if you could give me some advice on how to fix this, I would be grateful.</p>
| 0 | 2016-10-17T15:00:53Z | 40,089,952 | <p>Like Patrick Haugh says, try examining when the while loop exits. It can be helpful to put print() statements throughout your method to figure out how your method executes. In order to figure out when your loop exits, look at the exit condition of your while loop: xy < n. </p>
<p>Remember, a variable isn't updated until you update it.</p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
print("xy: {}".format(xy))
if n >= 0:
while xy < n:
x += 1
print("xy in loop: {}".format(xy))
if xy != n:
print (("%s is not a perfect square.") % (n))
x -= 1
print (("%s is the next highest perfect square.") % (xy))
else:
return(print(("%s is a perfect square of %s.") % (n, x)))
</code></pre>
| 0 | 2016-10-17T15:11:38Z | [
"python",
"loops",
"if-statement"
] |
Perfect Square function that doesn't return | 40,089,750 | <p>I'm a beginner working with Python and I was given this task: <em>write a function which returns the highest perfect square which is less or equal to its parameter (a positive integer).</em></p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
if xy != n:
print (("%s is not a perfect square.") % (n))
x -= 1
print (("%s is the next highest perfect square.") % (xy))
else:
return(print(("%s is a perfect square of %s.") % (n, x)))
</code></pre>
<p>When I run the code to execute the function it doesn't output anything. I'll admit, I'm struggling and if you could give me some advice on how to fix this, I would be grateful.</p>
| 0 | 2016-10-17T15:00:53Z | 40,089,961 | <p>I see your mistake, and it's an easy one for someone to make. When you define</p>
<pre><code>xy = x*x
</code></pre>
<p>the computer calculates <code>x*x</code> and assigns that <em>number</em> to be the value of <code>xy</code>. So when you then add one to <code>x</code> it does not change the value of <code>xy</code>. You have to tell the computer to recalculate <code>xy</code> every time:</p>
<pre><code>while xy < n:
x += 1
xy = x*x
</code></pre>
| -1 | 2016-10-17T15:12:00Z | [
"python",
"loops",
"if-statement"
] |
Subsets and Splits