title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python add an attribute to a method using decorators
39,537,757
<p>I'm trying to add an attribute to my method using decorators to determine if it has been called. I can't figure out why I got this error : TypeError: bet() missing 1 required positional argument: 'betsize'. </p> <p>file game.py</p> <pre><code>class Game(object): def __init__(self): .. @AddCalled def bet(self, betsize): print(betsize) </code></pre> <p>file addcalled.py :</p> <pre><code>class AddCalled(object): def __init__(self, f): self.f = f self.called = False def __call__(self, *args, **kwargs): self.f(*args, **kwargs) self.called = True </code></pre> <p>I get the betsize from a Qt signal (button click). The target slot function is bet() from game.py</p> <p>file mainui.py</p> <pre><code>class MainWindow(QtGui.QMainWindow, Ui_MainWindow): .. self.connect(self.ui.btnBet, SIGNAL("clicked()"), self.bet) def bet(self): #assuming 'game' is an instance of Game() self.game.bet(self.ui.betLine.text()) </code></pre> <p>Now I got this error whenever I click on the bet button </p> <pre><code>Traceback (most recent call last): File "/home/njl/projet/mainui.py", line 27, in bet self.game.bet(self.ui.betLine.text()) File "/home/njl/projet/addcalled.py", line 15, in __call__ self.f(*args, **kwargs) TypeError: bet() missing 1 required positional argument: 'betsize' </code></pre> <p>I would appreciate some help. Litteraly stuck in there.</p>
0
2016-09-16T18:15:25Z
39,537,941
<p>Your decorator doesn't properly pass <code>self</code> to the wrapped function.</p> <p>Normally, <code>self</code> is added by the descriptor mechanism of function objects, which converts them on the fly into method objects with the <code>self</code> rolled in. But you replaced your method with an AddDecorator object, which doesn't implement the descriptor protocol, so when your AddDecorator wrapper is called, it doesn't know what instance it's being called on (i.e., what <code>self</code> should be).</p> <p>You could implement the descriptor protocol on your AddDecorator class by giving it a <code>__get__</code> method. Or you could just write a regular decorator using a function:</p> <pre><code>def addCalled(func): def newFunc(*args, **kwargs): newFunc.called = True func(*args, **kwargs) newFunc.called = False return newFunc </code></pre>
2
2016-09-16T18:26:54Z
[ "python", "qt", "class", "decorator" ]
python add an attribute to a method using decorators
39,537,757
<p>I'm trying to add an attribute to my method using decorators to determine if it has been called. I can't figure out why I got this error : TypeError: bet() missing 1 required positional argument: 'betsize'. </p> <p>file game.py</p> <pre><code>class Game(object): def __init__(self): .. @AddCalled def bet(self, betsize): print(betsize) </code></pre> <p>file addcalled.py :</p> <pre><code>class AddCalled(object): def __init__(self, f): self.f = f self.called = False def __call__(self, *args, **kwargs): self.f(*args, **kwargs) self.called = True </code></pre> <p>I get the betsize from a Qt signal (button click). The target slot function is bet() from game.py</p> <p>file mainui.py</p> <pre><code>class MainWindow(QtGui.QMainWindow, Ui_MainWindow): .. self.connect(self.ui.btnBet, SIGNAL("clicked()"), self.bet) def bet(self): #assuming 'game' is an instance of Game() self.game.bet(self.ui.betLine.text()) </code></pre> <p>Now I got this error whenever I click on the bet button </p> <pre><code>Traceback (most recent call last): File "/home/njl/projet/mainui.py", line 27, in bet self.game.bet(self.ui.betLine.text()) File "/home/njl/projet/addcalled.py", line 15, in __call__ self.f(*args, **kwargs) TypeError: bet() missing 1 required positional argument: 'betsize' </code></pre> <p>I would appreciate some help. Litteraly stuck in there.</p>
0
2016-09-16T18:15:25Z
39,538,000
<p>When you write:</p> <pre><code>@AddCalled def bet(self, betsize): print(betsize) </code></pre> <p>This is equivalent to:</p> <pre><code>def bet(self, betsize): print(betsize) bet = AddCalled(bet) </code></pre> <p>So, the argument passed to <code>AddCalled</code> is the <code>bet</code> function.</p>
-1
2016-09-16T18:29:43Z
[ "python", "qt", "class", "decorator" ]
Orthogonality issue in scipy's legendre polynomials
39,537,794
<p>I recently stumbled upon a curious issue concerning the <code>scipy.special.legendre()</code> (<a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.legendre.html" rel="nofollow">scipy documentation</a>). The legendre polynomials should be pairwise orthogonal. However, when I calculate them over a range <code>x=[-1,1]</code> and build the scalar product of two polynomials of different degree I don't always get zero or values close to zero. Do I misinterpret the functions behaviour? In the following I have written a short example, which produces the scalar product of certain pairs of legendre polynomials:</p> <pre><code>from __future__ import print_function, division import numpy as np from scipy import special import matplotlib.pyplot as plt # create range for evaluation x = np.linspace(-1,1, 500) degrees = 6 lp_array = np.empty((degrees, len(x))) for n in np.arange(degrees): LP = special.legendre(n)(x) # alternatively: # LP = special.eval_legendre(n, x) lp_array[n, ] = LP plt.plot(x, LP, label=r"$P_{}(x)$".format(n)) plt.grid() plt.gca().set_ylim([-1.1, 1.1]) plt.legend(fontsize=9, loc="lower right") plt.show() </code></pre> <p>The plot of the single polynomials actually looks fine: <img src="http://i.stack.imgur.com/ji6UA.png" alt="Legendre polynomials from degree 0 to 5"></p> <p>But if I calculate the scalar products manually – multiply two legendre polynomials of different degree elementwise and sum them up (the 500 is for normalization)...</p> <pre><code>for i in range(degrees): print("0vs{}: {:+.6e}".format(i, sum(lp_array[0]*lp_array[i])/500)) </code></pre> <p>... I get the following values as output:</p> <pre><code>0vs0: +1.000000e+00 0vs1: -5.906386e-17 0vs2: +2.004008e-03 0vs3: -9.903189e-17 0vs4: +2.013360e-03 0vs5: -1.367795e-16 </code></pre> <p>The scalar product of the first polynomial with itself is (as to be expected) equal one, and half of the other results are almost zero, but there are some values in the order of <code>10e-3</code> and I have no idea why. I also tried the <code>scipy.special.eval_legendre(n, x)</code> function – same result :-\</p> <p>Is this a bug in the <code>scipy.special.legendre()</code> function? Or do I do something wrong? I am looking for constructive responds :-)</p> <p>cheers, Markus</p>
2
2016-09-16T18:19:03Z
39,541,581
<p>As others have commented, you're going to get some error, since you're performing an in-exact integral.</p> <p>But you can reduce the error by doing the integral as best you can. In your case, you can still improve your sampling points to make the integral more exact. When sampling, use the "midpoint" of the intervals instead of the edges:</p> <pre><code>x = np.linspace(-1, 1, nx, endpoint=False) x += 1 / nx # I'm adding half a sampling interval # Equivalent to x += (x[1] - x[0]) / 2 </code></pre> <p>This gives quite a lot of improvement! If I use the old sampling method:</p> <pre><code>nx = 500 x = np.linspace(-1, 1, nx) degrees = 7 lp_array = np.empty((degrees, len(x))) for n in np.arange(degrees): LP = special.eval_legendre(n, x) lp_array[n, :] = LP np.set_printoptions(linewidth=120, precision=1) prod = np.dot(lp_array, lp_array.T) / x.size print(prod) </code></pre> <p>This gives:</p> <pre><code>[[ 1.0e+00 -5.7e-17 2.0e-03 -8.5e-17 2.0e-03 -1.5e-16 2.0e-03] [ -5.7e-17 3.3e-01 -4.3e-17 2.0e-03 -1.0e-16 2.0e-03 -1.1e-16] [ 2.0e-03 -4.3e-17 2.0e-01 -1.3e-16 2.0e-03 -1.0e-16 2.0e-03] [ -8.5e-17 2.0e-03 -1.3e-16 1.4e-01 -1.2e-16 2.0e-03 -1.0e-16] [ 2.0e-03 -1.0e-16 2.0e-03 -1.2e-16 1.1e-01 -9.6e-17 2.0e-03] [ -1.5e-16 2.0e-03 -1.0e-16 2.0e-03 -9.6e-17 9.3e-02 -1.1e-16] [ 2.0e-03 -1.1e-16 2.0e-03 -1.0e-16 2.0e-03 -1.1e-16 7.9e-02]] </code></pre> <p>Error terms are ~10^-3.</p> <p>But using the "midpoint sampling scheme", I get:</p> <pre><code>[[ 1.0e+00 -2.8e-17 -2.0e-06 -3.6e-18 -6.7e-06 -8.2e-17 -1.4e-05] [ -2.8e-17 3.3e-01 -2.8e-17 -4.7e-06 -2.7e-17 -1.1e-05 -4.1e-17] [ -2.0e-06 -2.8e-17 2.0e-01 -5.7e-17 -8.7e-06 -2.3e-17 -1.6e-05] [ -3.6e-18 -4.7e-06 -5.7e-17 1.4e-01 -2.1e-17 -1.4e-05 -5.3e-18] [ -6.7e-06 -2.7e-17 -8.7e-06 -2.1e-17 1.1e-01 1.1e-17 -2.1e-05] [ -8.2e-17 -1.1e-05 -2.3e-17 -1.4e-05 1.1e-17 9.1e-02 7.1e-18] [ -1.4e-05 -4.1e-17 -1.6e-05 -5.3e-18 -2.1e-05 7.1e-18 7.7e-02]] </code></pre> <p>Errors are now ~10^-5 or even 10^-6, which is much better!</p>
0
2016-09-17T00:02:52Z
[ "python", "scipy", "polynomials", "orthogonal" ]
A more pythonic way of doing the following?
39,537,837
<p>A more pythonic way of doing the following? In this example, I'm trying to build comments (a dict) to be key-value pairs where the key is the unmodified-version, and the value is the return value from a function where the key was passed as an arg.</p> <pre><code>def func(word): return word[-1:-6:-1].upper() subs = { 'ALLOWED': ['one', 'two'], 'DISALLOWED': ['three', 'four'] } comments = {} for sub in subs['ALLOWED']: # reverse and uppercase comments[sub] = func(sub) print(comments) </code></pre> <p>Anyone have recommendation? It's not exactly important to have this done, but I love learning python idioms and ways to make my code more pythonic. Thanks!</p>
0
2016-09-16T18:20:56Z
39,537,912
<p>Use a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a> instead of building your dictionary in a <code>for</code> loop:</p> <pre><code>comments = {key: func(key) for key in subs['ALLOWED']} </code></pre>
4
2016-09-16T18:25:00Z
[ "python", "python-3.x" ]
A more pythonic way of doing the following?
39,537,837
<p>A more pythonic way of doing the following? In this example, I'm trying to build comments (a dict) to be key-value pairs where the key is the unmodified-version, and the value is the return value from a function where the key was passed as an arg.</p> <pre><code>def func(word): return word[-1:-6:-1].upper() subs = { 'ALLOWED': ['one', 'two'], 'DISALLOWED': ['three', 'four'] } comments = {} for sub in subs['ALLOWED']: # reverse and uppercase comments[sub] = func(sub) print(comments) </code></pre> <p>Anyone have recommendation? It's not exactly important to have this done, but I love learning python idioms and ways to make my code more pythonic. Thanks!</p>
0
2016-09-16T18:20:56Z
39,537,920
<p>Remove the loop and replace it inside the function with a dictionary comprehension. Then, you can simply return it. </p> <p>Also, you can reverse the string <code>word</code> with <code>[::-1]</code>, not the complex <code>[-1:-6:-1]</code> slice you're using:</p> <pre><code>def func(words): return {word: word[::-1].upper() for word in words} </code></pre> <p>This yields the same thing:</p> <pre><code>comments = func(subs['ALLOWED']) print(comments) # {'two': 'OWT', 'one': 'ENO'} </code></pre>
0
2016-09-16T18:25:32Z
[ "python", "python-3.x" ]
Python random.random - chance of rolling 0
39,537,843
<p>As described in the <a href="https://docs.python.org/3.4/library/random.html#random.random" rel="nofollow">documentation</a>, random.random will "return the next random floating point number in the range [0.0, 1.0)"</p> <p>So what is the chance of it returning a 0?</p>
3
2016-09-16T18:21:09Z
39,537,894
<p>As per the documentation, it </p> <blockquote> <p>It produces 53-bit precision </p> </blockquote> <p>And the Mersenne Twister it is based on has a huge state space, many times large than this. It also routinely passes statistical tests of bit independence (in programs designed to spot patterns in RNG output). The distribution is essentially uniform with equal probability that any bit will be 0 or 1.</p> <p>The probability of getting precisely 0.0 will be 1 in 2^53 (assuming an unknown internal state)</p>
8
2016-09-16T18:24:02Z
[ "python", "random" ]
Python 3 + NTLM + Sharepoint
39,537,888
<p>I am attempting to create a tool for interfacing with Sharepoint to start transitioning a number of old processes away from using Sharepoint as a relational database and move that data into an actual database and automate several manual tasks among other things.</p> <p>The environment I am working with is a Sharepoint 2013 server using NTLM authentication. I need to use python3 to be able to use a set of libraries that will later be used to consume the data. Python is running via Anaconda 64 bit. I have no administrative power over the sharepoint server at all, just the ability to read and change information of certain pages.</p> <p>The problem I am running into is authenticating using NTLM and the Sharepoint module together. The following snippet works just fine for pulling the HTML from the site as if it were a browser:</p> <pre><code>from &lt;&lt;password management library&gt;&gt; import KEY from requests_ntlm import HttpNtlmAuth import requests,getpass #Configuration domain='domain' srv="sharepoint.company.com" creds=KEY(srv,getpass.getuser()) #Secure credential retrieval user='{0}\\{1}'.format(domain,creds.USERNAME).upper() srvaddr='https://{0}'.format(srv) site='/sites/path/to/site/' site_url='{0}{1}'.format(srvaddr,site) #Auth via Requests_NTLM opener=HttpNtlmAuth(user,creds.getpass()) #Interface via Requests s = sharepoint.SharePointSite(site_url, opener) r = requests.get(srvaddr, auth=opener) </code></pre> <p>Using the documentation, source code provided in the sharepoint library's documentation and a few Stackoverflow posts (that refer to python 2 libraries), I attempted to replicate this using the sharepoint module. While the above is able to successfully authenticate, the following snippet gets a 401 Unauthorized Error:</p> <pre><code>import sharepoint,requests,getpass,urllib from ntlm3.HTTPNtlmAuthHandler import HTTPNtlmAuthHandler from &lt;&lt;password management library&gt;&gt; import KEY from requests_ntlm import HttpNtlmAuth from urllib.request import BaseHandler, HTTPPasswordMgrWithDefaultRealm, build_opener #Configuration domain='domain' srv="sharepoint.company.com" creds=KEY(srv,getpass.getuser()) #Secure credential retrieval user='{0}\\{1}'.format(domain,creds.USERNAME).upper() srvaddr='https://{0}'.format(srv) site='/sites/path/to/site/' site_url='{0}{1}'.format(srvaddr,site) #Auth via urllib Opener def basic_auth_opener(url, username, password): password_manager = HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, url, username, password) auth_handler = HTTPNtlmAuthHandler(password_manager) #PreemptiveBasicAuthHandler(password_manager) opener = build_opener(auth_handler) return opener print('Auth as {0}@{1}'.format(user,srvaddr)) opener = basic_auth_opener(srvaddr, user, creds.getpass()) #urllib.request.install_opener(opener) print('Open {0}'.format(site_url)) #Interface via Sharepoint module s = sharepoint.SharePointSite(site_url, opener) for sp_list in s.lists: print (sp_list.id, sp_list.meta['Title']) </code></pre> <p>I know that the credentials work and are authorized to access the site since the first snippet works just fine. The second simply gets a 401 error and I have been diving into the inner workings of urllib, requests, python-ntlm, and requests-ntlm all day trying to understand why one works but the other does not.</p> <p>Error stack for reference:</p> <pre><code>HTTPErrorTraceback (most recent call last) &lt;ipython-input-41-af721d5620e7&gt; in &lt;module&gt;() 31 #Interface via Sharepoint module 32 s = sharepoint.SharePointSite(site_url, opener) ---&gt; 33 for sp_list in s.lists: 34 print (sp_list.id, sp_list.meta['Title']) C:\Anaconda3\lib\site-packages\sharepoint\lists\__init__.py in __iter__(self) 78 79 def __iter__(self): ---&gt; 80 return iter(self.all_lists) 81 82 def __getitem__(self, key): C:\Anaconda3\lib\site-packages\sharepoint\lists\__init__.py in all_lists(self) 34 if not hasattr(self, '_all_lists'): 35 xml = SP.GetListCollection() ---&gt; 36 result = self.opener.post_soap(LIST_WEBSERVICE, xml) 37 38 self._all_lists = [] C:\Anaconda3\lib\site-packages\sharepoint\site.py in post_soap(self, url, xml, soapaction) 30 if soapaction: 31 request.add_header('Soapaction', soapaction) ---&gt; 32 response = self.opener.open(request, timeout=self.timeout) 33 return etree.parse(response).xpath('/soap:Envelope/soap:Body/*', namespaces=namespaces)[0] 34 C:\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout) 470 for processor in self.process_response.get(protocol, []): 471 meth = getattr(processor, meth_name) --&gt; 472 response = meth(req, response) 473 474 return response C:\Anaconda3\lib\urllib\request.py in http_response(self, request, response) 580 if not (200 &lt;= code &lt; 300): 581 response = self.parent.error( --&gt; 582 'http', request, response, code, msg, hdrs) 583 584 return response C:\Anaconda3\lib\urllib\request.py in error(self, proto, *args) 508 if http_err: 509 args = (dict, 'default', 'http_error_default') + orig_args --&gt; 510 return self._call_chain(*args) 511 512 # XXX probably also want an abstract factory that knows when it makes C:\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args) 442 for handler in handlers: 443 func = getattr(handler, meth_name) --&gt; 444 result = func(*args) 445 if result is not None: 446 return result C:\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs) 588 class HTTPDefaultErrorHandler(BaseHandler): 589 def http_error_default(self, req, fp, code, msg, hdrs): --&gt; 590 raise HTTPError(req.full_url, code, msg, hdrs, fp) 591 592 class HTTPRedirectHandler(BaseHandler): HTTPError: HTTP Error 401: Unauthorized </code></pre>
0
2016-09-16T18:23:43Z
39,622,563
<p>Shareplum ended up working great, with some exceptions due to the way it imported some data. Here's some rough code I ended up using to test it and later expand, censored, but enough to get someone started if they stumble across this:</p> <pre><code>from &lt;&lt;DATABASE LIBRARY&gt;&gt; import KEY,ORACLESQL from requests_ntlm import HttpNtlmAuth import requests,getpass,datetime,re,json import shareplum def date_handler(obj): return obj.isoformat() if hasattr(obj, 'isoformat') else obj def ppJSON(inDict): return (json.dumps(inDict,sort_keys=True, indent=4, default=date_handler)) ####### BEGIN: Monkey Patch to Shareplum ################### def _python_type(self, key, value): """Returns proper type from the schema""" try: field_type = self._sp_cols[key]['type'] if field_type in ['Number', 'Currency']: return float(value) elif field_type == 'DateTime': # Need to round datetime object return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')#.date() elif field_type == 'Boolean': if value == '1': return 'Y' elif value == '0': return 'N' else: return '' elif field_type == 'User': # Sometimes the User no longer exists or # has a diffrent ID number so we just remove the "123;#" # from the beginning of their name if value in self.users['sp']: return self.users['sp'][value] else: return value.split('#')[1] else: return value.encode('ascii','replace').decode('ascii') except AttributeError as e: print(e) return value #Monkey Patching the datetime import to avoid truncation of data shareplum.shareplum._List._python_type=_python_type ####### END: Monkey Patch to Shareplum ################### class SPSite(object): def __init__(self,username,password,server,site,listname=None,viewname=None,domain='sensenet'): self.domain=domain self.server=server self.site=site self.listname=listname self.viewname=viewname self.user='{0}\\{1}'.format(self.domain,username).upper() self.opener=HttpNtlmAuth(self.user,password) self.s=None self.l=None self.sql=None self.updateMetaData() def updateMetaData(self): self.srvaddr='https://{0}'.format(self.server) self.site_url='{0}{1}'.format(self.srvaddr,self.site) self.s=shareplum.Site(self.site_url,self.opener) if self.listname: self.l=self.s.List(self.listname) def showSampleData(self,view=None,*args,**kwargs): s=self.s #theview=view #if not theview and not fields: theview=self.viewname #Display Data print('Lists in {0}'.format(self.site_url)) for i in s.GetListCollection(): print(i['Title']) if self.listname: l=s.List(self.listname) print('\nViews in List {0}'.format(self.listname)) for i in l.views: print(i) if self.viewname: print('\nView Fields for {0}'.format(viewname)) for i in l.GetView(viewname)['fields']: print (i) print('\nData in View {0}'.format(self.viewname)) for i in l.GetListItems(rowlimit=10,*args,**kwargs): print(ppJSON(i)) </code></pre> <p>Example:</p> <pre><code>#Configuration domain='DomainName' srv="sharepoint.site.com" creds=KEY(srv,getpass.getuser()) #Secure credential retrieval site='/sites/path/to/site' listname='Some List' viewname='Some View I Want to ETL' tablename='SP_{0}_STG'.format(to_oracle(listname)) #Show Sample Data s=SPSite(creds.USERNAME,creds.getpass(),srv,site,listname,viewname) s.showSampleData(viewname) </code></pre>
0
2016-09-21T17:06:25Z
[ "python", "sharepoint", "sharepoint-2013", "ntlm" ]
Start infinite python script in new thread within Flask
39,537,892
<p>I'd like to start my never ending Python script from within Flask request:</p> <pre><code>def start_process(): exec(open("./process/main.py").read(), globals()) print("Started") return </code></pre> <p>and with the request:</p> <pre><code>@app.route("/start") def start(): from threading import Thread thread = Thread(target=start_process, args=()) thread.setDaemon(True) thread.start() return redirect(url_for('main')) </code></pre> <p>The <code>main.py</code> process is a little test server that waits for some messages, but it simply hangs the entire flask script (in fact, through gunicorn, if I send CTRL-C, I can see the output of the subprocess).</p> <p>How can I make the <code>main.py</code> script start separately?</p>
0
2016-09-16T18:23:51Z
39,563,991
<p>I've not successfully started long-running thread from within Flask, but gone the other way, starting Flask in thread and providing it a way to communicate with other threads.</p> <p>The trick is to something along the lines of</p> <pre><code>def webserver(coordinator): app.config['COORDINATOR'] = coordinator app.run(use_reloader=False) # use_reloader=False is needed to keep Flask happy in a thread def main(): coordinator = Coordinator() ui = threading.Thread(target=webserver, args=(coordinator,)) ui.start() # start other threads, passing them coordinator # start long-running tasks in main thread, passing it coordinator </code></pre> <p>Where <code>Coordinator</code> uses <code>threading</code> facilities (e.g., <code>Lock</code>, <code>Queue</code>) to protect access to shared data or resources. You can fairly easily set up the coordinator to support have worker threads block until signaled (from a handler), then start long-running tasks.</p>
0
2016-09-19T00:51:19Z
[ "python", "multithreading", "flask", "process", "daemon" ]
Update/Append to dictionary
39,537,896
<p>Let's say I have a dictionary like so:</p> <pre><code>x = {'age': 23, 'channel': ['a'], 'name': 'Test', 'source': {'data': [1, 2]}} </code></pre> <p>and a similar one like:</p> <pre><code>y = {'age': 23, 'channel': ['c'], 'name': 'Test', 'source': {'data': [3, 4], 'no': 'xyz'}} </code></pre> <p>if I used this <code>x.update(y)</code> I would lose <code>'channel'</code> previous info for example.. How can I append the values when they are different and add keys/values when they are not already in the dictionary?</p> <p>End result should be:</p> <pre><code>{'age': 23, 'channel': ['a', 'c'], 'name': 'Test', 'source': {'data': [1, 2, 3, 4], 'no': 'xyz'}} </code></pre> <p>I came close with this:</p> <pre><code>for a,b in y.iteritems(): try: x[a] = x[a] + y[a] except: x[a] = y[a] </code></pre> <p>but it failed when it found a dictionary inside of the dictionary.</p>
-1
2016-09-16T18:24:09Z
39,538,072
<p>You can access the value associated to the key and make the changes. Lets take the dict example you have taken in your question:</p> <pre><code>x = {'name': 'Test', 'age': 23, 'channel': ['a'], 'source': {'data': [1,2]}} x['channel']=['a'] </code></pre> <p>The value is of type list[]. you can append or add values to a list by list.append()</p> <p>So, <code>x['channel'].append('c')</code> will give you:</p> <pre><code>{'age': 23, 'channel': ['a', 'c'], 'name': 'Test', 'source': {'data': [1, 2]}} </code></pre>
0
2016-09-16T18:34:40Z
[ "python", "dictionary" ]
Update/Append to dictionary
39,537,896
<p>Let's say I have a dictionary like so:</p> <pre><code>x = {'age': 23, 'channel': ['a'], 'name': 'Test', 'source': {'data': [1, 2]}} </code></pre> <p>and a similar one like:</p> <pre><code>y = {'age': 23, 'channel': ['c'], 'name': 'Test', 'source': {'data': [3, 4], 'no': 'xyz'}} </code></pre> <p>if I used this <code>x.update(y)</code> I would lose <code>'channel'</code> previous info for example.. How can I append the values when they are different and add keys/values when they are not already in the dictionary?</p> <p>End result should be:</p> <pre><code>{'age': 23, 'channel': ['a', 'c'], 'name': 'Test', 'source': {'data': [1, 2, 3, 4], 'no': 'xyz'}} </code></pre> <p>I came close with this:</p> <pre><code>for a,b in y.iteritems(): try: x[a] = x[a] + y[a] except: x[a] = y[a] </code></pre> <p>but it failed when it found a dictionary inside of the dictionary.</p>
-1
2016-09-16T18:24:09Z
39,538,357
<p>Your requirement seems a bit vague, but you can do what you want with a recursive function like the following. (To the point I understood your requirements, you can't append <em>sets</em> to <em>dicts</em> right ? or the likes of these cases)</p> <pre><code>x = {'age': 23, 'channel': ['a'], 'name': 'Test', 'source': {'data': [1, 2], 'no': 'jj'}} y = {'age': 23, 'channel': ['c'], 'name': 'Test', 'source': {'data': [3, 4], 'no': 'xyz'}} def deep_update(x, y): for key in y.keys(): if key not in x: x.update({key: y[key]}) elif x[key] != y[key]: if isinstance(x[key], dict): x.update({key: deep_update(x[key], y[key])}) else: x.update({key: list(set(x[key] + y[key]))}) return x print deep_update(x, y) </code></pre> <blockquote> <p>{'source': {'data': [1, 2, 3, 4], 'no': 'jjxyz'}, 'age': 23, 'name': 'Test', 'channel': ['a', 'c']}</p> </blockquote>
2
2016-09-16T18:51:45Z
[ "python", "dictionary" ]
How do I download the entire pypi Python Package Index
39,537,938
<p>I'm trying to find a way to download the entire PyPi index - and only the index - no code files. I'm wanting to analyze license types to be able to rule out libraries that have too restrictive license types. I've looked online and through the user's guide, but if the answer is there, it eludes me.</p>
1
2016-09-16T18:26:44Z
39,538,181
<p>Well, you can use <a href="https://pypi.python.org/simple" rel="nofollow">PyPi's Simple Index</a> to get a simple list of packages without overhead. And then send a GET request to</p> <pre><code>https://pypi.python.org/pypi/&lt;package-name&gt;/json </code></pre> <p>This will return a JSON response containing all the metadata information regarding the package (including the license).</p>
1
2016-09-16T18:40:50Z
[ "python", "pypi" ]
How can I execute Python code in a virtualenv from Matlab
39,538,010
<p>I am creating a Matlab toolbox for research and I need to execute Matlab code but also Python code. </p> <p>I want to allow the user to execute Python code from Matlab. The problem is that if I do it right away, I would have to install everything on the Python's environment and I want to avoid this using virtualenv. The problem is that I don't know how to tell Matlab to user the virtual enviornment created.</p>
3
2016-09-16T18:30:22Z
39,538,066
<p>You can either modify the <code>PATH</code> environment variable in MATLAB prior to calling python from MATLAB</p> <pre class="lang-matlab prettyprint-override"><code>% Modify the system PATH so it finds the python executable in your venv first setenv('PATH', ['/path/to/my/venv/bin', pathsep, getenv('PATH')]) % Call your python script system('python myscript.py') </code></pre> <p>Or the better way would be to specify the full path to the python binary</p> <pre><code>system('/path/to/my/venv/bin/python myscript.py') </code></pre>
5
2016-09-16T18:34:22Z
[ "python", "matlab", "virtualenv" ]
ipython runs older version of script first before running new version
39,538,051
<p>I edited <em>oldscript.py</em> and then saved it in the same directory as <em>newscript.py</em>. After this, when I do <em>%run newscript.py</em> in ipython it seems to run <em>oldscript.py</em> before running <em>newscript.py</em>. I know this because it gives an output from <em>oldscript.py</em> before giving the outputs for <em>newscript.py</em>. It looks something like this:</p> <pre><code>%run newscript.py output from oldscript.py outputs from newscript.py </code></pre> <p>Why is it doing this? I've deleted the .pyc files, but that didn't help. I restarted ipython, my terminal, and my computer and nothing has changed. As far as I know, I don't have anything pointing to <em>oldsript.py</em> in <em>newscript.py</em>. I'm in the correct directory. I also tried running it in spyder and the terminal. Both give the same outputs. I feel like I've tried everything. </p> <p>Also, I should mention that I'm new to python so there may be an obvious solution I haven't tried. Please advise :)</p>
0
2016-09-16T18:33:22Z
39,538,325
<p>I'm pretty sure I just figured it out. I removed <em>oldscript.py</em> from the directory and it worked! Who knew Python could be so particular?! Okay, probably a lot of you, but give me a break I'm a noob ;)</p>
0
2016-09-16T18:49:57Z
[ "python", "ipython" ]
How best to use pandas.DataFrame.pivot?
39,538,109
<p>I am trying to translate a dataframe from rows of key, value to a table with keys as the columns and values as cells. For example:</p> <p>Input dataframe with key, value:</p> <pre><code>&gt;&gt;&gt;df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3', 'TIME', 'VAL1', 'VAL2', 'VAL3'], ["00:00:01",1,2,3,"00:00:02", 1,2,3]]).T 0 1 0 TIME 00:00:01 1 VAL1 1 2 VAL2 2 3 VAL3 3 4 TIME 00:00:02 5 VAL1 1 6 VAL2 2 7 VAL3 3 </code></pre> <p>I want it to look like:</p> <pre><code>TIME VAL1 VAL2 VAL3 00:00:01 1 2 3 00:00:02 1 2 3 </code></pre> <p>I can almost get what I want with pivot:</p> <pre><code>&gt;&gt;&gt;df.pivot(columns=0, values=1) TIME VAL1 VAL2 VAL3 0 00:00:01 None None None 1 None 1 None None 2 None None 2 None 3 None None None 3 4 00:00:02 None None None 5 None 1 None None 6 None None 2 None 7 None None None 3 </code></pre> <p>And I can merge the rows to get what I want:</p> <pre><code>&gt;&gt;&gt; df.pivot(columns=0, values=1).ffill().drop_duplicates(subset='TIME', keep='last').set_index('TIME') TIME VAL1 VAL2 VAL3 00:00:01 1 2 3 00:00:02 1 2 3 </code></pre> <p>But this seems like a rather awkward way to do it that would waste a lot of memory for a large data set. Is there a simpler method?</p> <p>I tired looking at <code>pd.DataFrame.from_items()</code> and <code>pd.DataFrame.from_records()</code> but was not having success.</p>
4
2016-09-16T18:37:07Z
39,538,298
<p>You need an "ID" variable that indicates which rows go together. In your desired output, you are implicitly assuming that every block of 4 rows should become a single row, but pandas won't assume that, because in general pivoting should be able to group together nonconsecutive rows. Each set of rows that you want to become a single row in the new DataFrame must have some shared value.</p> <p>If your data really is just chunks of four rows, you can create the ID variable like this:</p> <pre><code>df['ID'] = np.arange(len(df))//4 </code></pre> <p>You can see that the ID variable now marks which rows should be grouped:</p> <pre><code>&gt;&gt;&gt; df 0 1 ID 0 TIME 00:00:01 0 1 VAL1 1 0 2 VAL2 2 0 3 VAL3 3 0 4 TIME 00:00:02 1 5 VAL1 1 1 6 VAL2 2 1 7 VAL3 3 1 </code></pre> <p>Then use this new column as the "index" of the pivot.</p> <pre><code>&gt;&gt;&gt; df.pivot(index="ID", columns=0, values=1) 0 TIME VAL1 VAL2 VAL3 ID 0 00:00:01 1 2 3 1 00:00:02 1 2 3 </code></pre>
3
2016-09-16T18:47:59Z
[ "python", "pandas" ]
How best to use pandas.DataFrame.pivot?
39,538,109
<p>I am trying to translate a dataframe from rows of key, value to a table with keys as the columns and values as cells. For example:</p> <p>Input dataframe with key, value:</p> <pre><code>&gt;&gt;&gt;df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3', 'TIME', 'VAL1', 'VAL2', 'VAL3'], ["00:00:01",1,2,3,"00:00:02", 1,2,3]]).T 0 1 0 TIME 00:00:01 1 VAL1 1 2 VAL2 2 3 VAL3 3 4 TIME 00:00:02 5 VAL1 1 6 VAL2 2 7 VAL3 3 </code></pre> <p>I want it to look like:</p> <pre><code>TIME VAL1 VAL2 VAL3 00:00:01 1 2 3 00:00:02 1 2 3 </code></pre> <p>I can almost get what I want with pivot:</p> <pre><code>&gt;&gt;&gt;df.pivot(columns=0, values=1) TIME VAL1 VAL2 VAL3 0 00:00:01 None None None 1 None 1 None None 2 None None 2 None 3 None None None 3 4 00:00:02 None None None 5 None 1 None None 6 None None 2 None 7 None None None 3 </code></pre> <p>And I can merge the rows to get what I want:</p> <pre><code>&gt;&gt;&gt; df.pivot(columns=0, values=1).ffill().drop_duplicates(subset='TIME', keep='last').set_index('TIME') TIME VAL1 VAL2 VAL3 00:00:01 1 2 3 00:00:02 1 2 3 </code></pre> <p>But this seems like a rather awkward way to do it that would waste a lot of memory for a large data set. Is there a simpler method?</p> <p>I tired looking at <code>pd.DataFrame.from_items()</code> and <code>pd.DataFrame.from_records()</code> but was not having success.</p>
4
2016-09-16T18:37:07Z
39,538,524
<p>Another way to do this:</p> <pre><code>In [65]: df Out[65]: 0 1 0 TIME 00:00:01 1 VAL1 1 2 VAL2 2 3 VAL3 3 4 TIME 00:00:02 5 VAL1 1 6 VAL2 2 7 VAL3 3 In [66]: newdf = pd.concat([df[df[0] == x].reset_index()[1] for x in df[0].unique()], axis=1) In [67]: newdf.columns = df[0].unique() In [68]: newdf Out[68]: TIME VAL1 VAL2 VAL3 0 00:00:01 1 2 3 1 00:00:02 1 2 3 </code></pre>
1
2016-09-16T19:03:40Z
[ "python", "pandas" ]
How best to use pandas.DataFrame.pivot?
39,538,109
<p>I am trying to translate a dataframe from rows of key, value to a table with keys as the columns and values as cells. For example:</p> <p>Input dataframe with key, value:</p> <pre><code>&gt;&gt;&gt;df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3', 'TIME', 'VAL1', 'VAL2', 'VAL3'], ["00:00:01",1,2,3,"00:00:02", 1,2,3]]).T 0 1 0 TIME 00:00:01 1 VAL1 1 2 VAL2 2 3 VAL3 3 4 TIME 00:00:02 5 VAL1 1 6 VAL2 2 7 VAL3 3 </code></pre> <p>I want it to look like:</p> <pre><code>TIME VAL1 VAL2 VAL3 00:00:01 1 2 3 00:00:02 1 2 3 </code></pre> <p>I can almost get what I want with pivot:</p> <pre><code>&gt;&gt;&gt;df.pivot(columns=0, values=1) TIME VAL1 VAL2 VAL3 0 00:00:01 None None None 1 None 1 None None 2 None None 2 None 3 None None None 3 4 00:00:02 None None None 5 None 1 None None 6 None None 2 None 7 None None None 3 </code></pre> <p>And I can merge the rows to get what I want:</p> <pre><code>&gt;&gt;&gt; df.pivot(columns=0, values=1).ffill().drop_duplicates(subset='TIME', keep='last').set_index('TIME') TIME VAL1 VAL2 VAL3 00:00:01 1 2 3 00:00:02 1 2 3 </code></pre> <p>But this seems like a rather awkward way to do it that would waste a lot of memory for a large data set. Is there a simpler method?</p> <p>I tired looking at <code>pd.DataFrame.from_items()</code> and <code>pd.DataFrame.from_records()</code> but was not having success.</p>
4
2016-09-16T18:37:07Z
39,538,604
<p>You can use a defaultdict that would work fine in the DataFrame constructor:</p> <pre><code>import collections keys = ['TIME', 'VAL1', 'VAL2', 'VAL3', 'TIME', 'VAL1', 'VAL2', 'VAL3'] values = ["00:00:01",1,2,3,"00:00:02", 1,2,3] d = collections.defaultdict(list) for k, v in zip(keys, values): d[k].append(v) ''' d looks like this: defaultdict(list, {'TIME': ['00:00:01', '00:00:02'], 'VAL1': [1, 1], 'VAL2': [2, 2], 'VAL3': [3, 3]})''' df = pd.DataFrame(d) df Out: TIME VAL1 VAL2 VAL3 0 00:00:01 1 2 3 1 00:00:02 1 2 3 </code></pre> <p>An alternative from Nehal J Wani, if you don't have access to those lists:</p> <pre><code>df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3', 'TIME', 'VAL1', 'VAL2', 'VAL3'], ["00:00:01",1,2,3,"00:00:02", 1,2,3]]).T d = collections.defaultdict(list) for k, v in zip(df[0], df[1]): d[k].append(v) </code></pre>
0
2016-09-16T19:08:58Z
[ "python", "pandas" ]
Load CSV to search for match in array/dictionary/list
39,538,166
<p>Very new to Python and I'm now learning by trying to write a program to process data from first few lines from multiple text files. so far so good - getting the data in and reformatting it for output.</p> <p>Now I'd like to change the format of one output field based on what row it sits in in the csv file. The file is 15 rows with variable number of columns.</p> <p>The idea is that:</p> <ol> <li>I preload the CSV file - I'd like to hardcode it into a list or dictionary - not sure what works better for the next step.</li> <li>Go thru the 15 rows in the list/dictionary and if a match is found - set the output to column 1 in the same row.</li> </ol> <p>Example Data:</p> <pre class="lang-none prettyprint-override"><code>BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM CAL, ID27, CALP, HCALI, IECY, CLLO, RD2, RAD3QI, ID4 DEN, RHO8[1], RHOZ1, RHOZ2, RHOB_HR, RHOB_ME, LDENX DENC, CRHO, DRHO1, ZCOR2, HDRH2, ZCORQK DEPT, DEPTH, DEPT,MD DPL, PDL, PORZLS1, PORDLSH_Y, DPRL, HDPH_LIM, PZLS DPS, HDPH_SAN1, DPHI_SAN2, DPUS, DPOR, PZSS1 DTC, DTCO_MFM[1], DT4PT2, DTCO_MUM[1], DTC DTS, DT1R[1], DTSH, DT22, DTSM[1], DT24S GR, GCGR, GR_R3, HGR3, GR5, GR6, GR_R1, MGSGR NPL, NEU, NPOR_LIM, HTNP_LIM, NPOR, HNPO_LIM1 NPS, NPRS, CNC, NPHILS, NPOR_SS, NPRS1, CNCS, PORS PE, PEFZ_2, HPEF, PEQK, PEF81, PEF83, PEDN, PEF8MBT RD, AST90, ASF60, RD, RLLD, RTCH, LLDC, M2R9, LLHD RS, IESN, FOC, ASO10, MSFR, AO20, RS, SFE, LL8, MLL </code></pre> <p>For example:</p> <pre><code>BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM </code></pre> <p>returns <code>BIT</code></p> <p>Questions:</p> <ul> <li>Is a list or dictionary a better for search speed?</li> <li>If I use the csv module to load the data does it matter that number of columns aren't same for every row?</li> <li>Is there a way to search either list or dictionary without using a loop?</li> </ul> <p>My attempt to load into list and search:</p> <pre><code>import csv with open('lookup.csv', 'rb') as f: reader = csv.reader(f) codelist = list(reader) </code></pre> <p>Would this work for searching for matching code <code>searchcode</code>?</p> <pre><code>for subcodes in codelist: if searchcode in subcodes: print "Found it!", subcodes[0] break </code></pre>
0
2016-09-16T18:40:14Z
39,538,405
<p>I think that you should try with two-dimensional dictionary</p> <pre><code>new_dic = {} new_dic[0] = {BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM} new_dic[1] = {CAL, ID27, CALP, HCALI, IECY, CLLO, RD2, RAD3QI, ID4} </code></pre> <p>Then you can search for the element and print it.</p>
0
2016-09-16T18:55:43Z
[ "python", "list", "python-2.7", "csv", "dictionary" ]
Load CSV to search for match in array/dictionary/list
39,538,166
<p>Very new to Python and I'm now learning by trying to write a program to process data from first few lines from multiple text files. so far so good - getting the data in and reformatting it for output.</p> <p>Now I'd like to change the format of one output field based on what row it sits in in the csv file. The file is 15 rows with variable number of columns.</p> <p>The idea is that:</p> <ol> <li>I preload the CSV file - I'd like to hardcode it into a list or dictionary - not sure what works better for the next step.</li> <li>Go thru the 15 rows in the list/dictionary and if a match is found - set the output to column 1 in the same row.</li> </ol> <p>Example Data:</p> <pre class="lang-none prettyprint-override"><code>BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM CAL, ID27, CALP, HCALI, IECY, CLLO, RD2, RAD3QI, ID4 DEN, RHO8[1], RHOZ1, RHOZ2, RHOB_HR, RHOB_ME, LDENX DENC, CRHO, DRHO1, ZCOR2, HDRH2, ZCORQK DEPT, DEPTH, DEPT,MD DPL, PDL, PORZLS1, PORDLSH_Y, DPRL, HDPH_LIM, PZLS DPS, HDPH_SAN1, DPHI_SAN2, DPUS, DPOR, PZSS1 DTC, DTCO_MFM[1], DT4PT2, DTCO_MUM[1], DTC DTS, DT1R[1], DTSH, DT22, DTSM[1], DT24S GR, GCGR, GR_R3, HGR3, GR5, GR6, GR_R1, MGSGR NPL, NEU, NPOR_LIM, HTNP_LIM, NPOR, HNPO_LIM1 NPS, NPRS, CNC, NPHILS, NPOR_SS, NPRS1, CNCS, PORS PE, PEFZ_2, HPEF, PEQK, PEF81, PEF83, PEDN, PEF8MBT RD, AST90, ASF60, RD, RLLD, RTCH, LLDC, M2R9, LLHD RS, IESN, FOC, ASO10, MSFR, AO20, RS, SFE, LL8, MLL </code></pre> <p>For example:</p> <pre><code>BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM </code></pre> <p>returns <code>BIT</code></p> <p>Questions:</p> <ul> <li>Is a list or dictionary a better for search speed?</li> <li>If I use the csv module to load the data does it matter that number of columns aren't same for every row?</li> <li>Is there a way to search either list or dictionary without using a loop?</li> </ul> <p>My attempt to load into list and search:</p> <pre><code>import csv with open('lookup.csv', 'rb') as f: reader = csv.reader(f) codelist = list(reader) </code></pre> <p>Would this work for searching for matching code <code>searchcode</code>?</p> <pre><code>for subcodes in codelist: if searchcode in subcodes: print "Found it!", subcodes[0] break </code></pre>
0
2016-09-16T18:40:14Z
39,538,760
<p>you can use "index" to search for an item in a list. if there that item in the list it will return the location of the first occurrence of it.</p> <pre><code>my_list = ['a','b','c','d','e','c'] # defines the list copy_at = my_list.index('b') # checks if 'b' is in the list copy_at # prints the location in the list where 'b' was at 1 copy_at = my_list.index('c') copy_at 2 copy_at = my_list.index('f') Traceback (most recent call last): File "&lt;pyshell#25&gt;", line 1, in &lt;module&gt; my_list.index('f') ValueError: 'f' is not in list </code></pre> <p>you can catch the error with a "try" "except" and keep searching.</p>
0
2016-09-16T19:21:10Z
[ "python", "list", "python-2.7", "csv", "dictionary" ]
How to debug Pygame application with Visual Studio during runtime
39,538,259
<p>I've been making a small game for a homework assignment using Pygame with Livewires. I've been trying to debug it, but to no success; I can't get a look at the variables I want to look at before the main loop is executed. Though I can press F10 to skip over the main loop, that just stops the Autos and Watches window from working; apparently they can only records vars when the game is paused by the debugger. </p> <p>Is there a way for me to use the debugger to look at the vars in runtime? Because no matter what I do while the debugger is paused, I can't look at the data inside the game objects I want to take a look in</p>
0
2016-09-16T18:45:59Z
39,582,747
<p>Thanks to Jack Zhai's suggestion, I figured it out. </p> <ol> <li><p>When the breakpoint is hit, unpause the debugger (shortcut: F5)</p></li> <li><p>Play to the point in the game you want to debug.</p></li> <li><p>Repause the debugger using Break All (shortcut: Ctrl-Alt-Break)</p></li> <li><p>Press F10 a few times; this makes it go a few more steps in the main livewires loop.</p></li> <li><p>In the autos window, there is an entry that contains the a list of the game's objects. Look through it, until you find the one(s) you're looking for. In my case, the list of the objects was self._objects. The object I was looking for was the second, which in other words, was self._objects[1].</p></li> <li><p>The dropdown arrows of the object(s) you're looking for show the object's members. If you want to look at the object's properties in a less cumbersome way, use the Interactive Debugger to assign that object to a variable. That way, you can look at its values through typing objectNameHere.objectValueHere into the interactive debug console.</p></li> </ol> <p>In my case, I had to type in player = self._objects[1] to get it assigned, then could see the player's x position by then entering player.x into the debug console.</p> <p>--</p> <p>I know this answer might only work for my specific problem, so if anyone else has a better one, please post it for others' sake.</p>
0
2016-09-19T21:57:17Z
[ "python", "visual-studio", "debugging", "pygame", "livewires" ]
Given an acyclic directed graph, return a collection of collections of nodes "at the same level"?
39,538,363
<p>Firstly I am not sure what such an algorithm is called, which is the primary problem - so first part of the question is what is this algorithm called?</p> <p>Basically I have a <code>DiGraph()</code> into which I insert the nodes <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and the edges <code>([1,3],[2,3],[3,5],[4,5],[5,7],[6,7],[7,8],[7,9],[7,10])</code></p> <p>From this I'm wondering if it's possible to get a collection as follows: <code>[[1, 2, 4, 6], [3], [5], [7], [8, 9, 10]]</code></p> <p>EDIT: Let me add some constraints if it helps. - There are no cycles, this is guaranteed - There is no one start point for the graph</p> <p>What I'm trying to do is to collect the nodes at the same level such that their processing can be parallelized, but within the outer collection, the processing is serial.</p> <p>EDIT2: So clearly I hadn't thought about this enough, so the easiest way to describe "level" is interms of <em>deepest predecessor</em>, all nodes that have the same depth of predecessors. So the first entry in the above list are all nodes that have 0 as the deepest predecessor, the second has one, third has two and so on. Within each list, the order of the <em>siblings</em> is irrelevant as they will be parallelly processed.</p>
4
2016-09-16T18:52:21Z
39,538,477
<p>Why would bfs not solve it? A bfs algorithm is breadth traversal algorithm, i.e. it traverses the tree level wise. This also means, all nodes at same level are traversed at once, which is your desired output. As pointed out in comment, this will however, assume a starting point in the graph.</p>
0
2016-09-16T19:00:19Z
[ "python", "algorithm", "graph", "graph-theory", "networkx" ]
Given an acyclic directed graph, return a collection of collections of nodes "at the same level"?
39,538,363
<p>Firstly I am not sure what such an algorithm is called, which is the primary problem - so first part of the question is what is this algorithm called?</p> <p>Basically I have a <code>DiGraph()</code> into which I insert the nodes <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and the edges <code>([1,3],[2,3],[3,5],[4,5],[5,7],[6,7],[7,8],[7,9],[7,10])</code></p> <p>From this I'm wondering if it's possible to get a collection as follows: <code>[[1, 2, 4, 6], [3], [5], [7], [8, 9, 10]]</code></p> <p>EDIT: Let me add some constraints if it helps. - There are no cycles, this is guaranteed - There is no one start point for the graph</p> <p>What I'm trying to do is to collect the nodes at the same level such that their processing can be parallelized, but within the outer collection, the processing is serial.</p> <p>EDIT2: So clearly I hadn't thought about this enough, so the easiest way to describe "level" is interms of <em>deepest predecessor</em>, all nodes that have the same depth of predecessors. So the first entry in the above list are all nodes that have 0 as the deepest predecessor, the second has one, third has two and so on. Within each list, the order of the <em>siblings</em> is irrelevant as they will be parallelly processed.</p>
4
2016-09-16T18:52:21Z
39,538,705
<p>Your question states that you would like the output, for this graph, to be <code>[[1, 2, 4, 6], [3], [5], [7], [8, 9, 10]]</code>. IIUC, the pattern is as follows:</p> <ul> <li><p><code>[1, 2, 4, 6]</code> are the nodes that have no in edges.</p></li> <li><p><code>[3]</code> are the nodes that have no in edges, assuming all previous nodes were erased.</p></li> <li><p><code>[4]</code> are the nodes that have no in edges, assuming all previous nodes were erased.</p></li> <li><p>Etc. (until all nodes have been erased)</p></li> </ul> <p>Say we start with</p> <pre><code>g = networkx.DiGraph() g.add_edges_from([[1,3],[2,3],[3,5],[4,5],[5,7],[6,7],[7,8],[7,9],[7,10]]) </code></pre> <p>Then we can just code this as</p> <pre><code>def find_levels(g): levels = [] while g.nodes(): no_in_nodes = [n for (n, d) in g.in_degree(g.nodes()).items() if d == 0] levels.append(no_in_nodes) for n in no_in_nodes: g.remove_node(n) return levels </code></pre> <p>If we run this, we get the result:</p> <pre><code>&gt;&gt;&gt; find_levels(g) [[1, 2, 4, 6], [3], [5], [7], [8, 9, 10]] </code></pre> <p>The complexity here is <em>&Theta;(|V|<sup>2</sup> + |E|)</em>. A somewhat more complicated version can be built using a <a href="https://en.wikipedia.org/wiki/Fibonacci_heap#Summary_of_running_times" rel="nofollow">Fibonnacci Heap</a>. Basically, all vertices need to be placed into a heap, with each level consisting of the vertices with 0 in degree. Each time one is popped, and the edges to other vertices are removed, we can translate this to a heap decrease-key operation (the in-degrees of remaining vertices are reduced). This would reduce the running time to <em>&Theta;(|V| log(|V|) + |E|)</em>.</p>
4
2016-09-16T19:16:40Z
[ "python", "algorithm", "graph", "graph-theory", "networkx" ]
Given an acyclic directed graph, return a collection of collections of nodes "at the same level"?
39,538,363
<p>Firstly I am not sure what such an algorithm is called, which is the primary problem - so first part of the question is what is this algorithm called?</p> <p>Basically I have a <code>DiGraph()</code> into which I insert the nodes <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and the edges <code>([1,3],[2,3],[3,5],[4,5],[5,7],[6,7],[7,8],[7,9],[7,10])</code></p> <p>From this I'm wondering if it's possible to get a collection as follows: <code>[[1, 2, 4, 6], [3], [5], [7], [8, 9, 10]]</code></p> <p>EDIT: Let me add some constraints if it helps. - There are no cycles, this is guaranteed - There is no one start point for the graph</p> <p>What I'm trying to do is to collect the nodes at the same level such that their processing can be parallelized, but within the outer collection, the processing is serial.</p> <p>EDIT2: So clearly I hadn't thought about this enough, so the easiest way to describe "level" is interms of <em>deepest predecessor</em>, all nodes that have the same depth of predecessors. So the first entry in the above list are all nodes that have 0 as the deepest predecessor, the second has one, third has two and so on. Within each list, the order of the <em>siblings</em> is irrelevant as they will be parallelly processed.</p>
4
2016-09-16T18:52:21Z
39,542,360
<p>A topological sort will achieve this, as Ami states. The following is a Boost Graph Library implementation, with no context, but the pseudocode can be extracted. The <code>toporder</code> object just provides the iterator to a topological ordering. I can extract the general algorithm if desired. </p> <pre><code>template&lt;typename F&gt; void scheduler&lt;F&gt;::set_run_levels() { run_levels = std::vector&lt;int&gt;(tasks.size(), 0); Vertexcont toporder; try { topological_sort(g, std::front_inserter(toporder)); } catch(std::exception &amp;e) { std::cerr &lt;&lt; e.what() &lt;&lt; "\n"; std::cerr &lt;&lt; "You most likely have a cycle...\n"; exit(1); } vContIt i = toporder.begin(); for(; i != toporder.end(); ++i) { if (in_degree(*i,g) &gt; 0) { inIt j, j_end; int maxdist = 0; for(boost::tie(j,j_end) = in_edges(*i,g); j != j_end; ++j) { maxdist = (std::max)(run_levels[source(*j,g)], maxdist); run_levels[*i] = maxdist+1; } } } } </code></pre> <p>I think I once applied this to the same problem, then realized it was unnecessary. Just set up the tasks on a hair-trigger, with all tasks signaling completion to their dependents (by a condition_variable, promise). So all I needed was to know the dependencies of each task, find the initial task, then fire. Is a full specification of <code>run_level</code> needed in your case?</p>
2
2016-09-17T02:35:59Z
[ "python", "algorithm", "graph", "graph-theory", "networkx" ]
Scraping table information
39,538,366
<p>I would like to extract the odds information from the website <a href="http://www.footballlocks.com/nfl_odds.shtml" rel="nofollow">http://www.footballlocks.com/nfl_odds.shtml</a> using Python.</p> <p>I have been trying to do it with BeautifulSoup.</p> <p>The optimal result would be to obtain the odds information in dictionary or list format, as the values will be fed into a mathematical formula.</p> <p>the HTML code for the odds information is:</p> <pre><code> &lt;TABLE COLS="6" WIDTH="650" BORDER="0" CELLSPACING="5" CELLPADDING="2"&gt; &lt;TR&gt; &lt;TD WIDTH="19%"&gt;&lt;span title="Date and Time of Game."&gt;&lt;B&gt;Date &amp; Time&lt;/B&gt;&lt;/span&gt;&lt;/TD&gt; &lt;TD WIDTH="21%"&gt;&lt;span title="Team Spotting Points in a Bet Against the Point Spread."&gt;&lt;B&gt;Favorite&lt;/B&gt;&lt;/span&gt;&lt;/TD&gt; &lt;TD WIDTH="14%"&gt;&lt;span title="Short for Point Spread. Number of Points Subtracted from Final Score of Favorite to Determine Winner of a Point Spread Based Wager."&gt;&lt;B&gt;Spread&lt;/B&gt;&lt;/span&gt;&lt;/TD&gt; &lt;TD WIDTH="21%"&gt;&lt;span title="Team Receiving Points in a Bet With the Point Spread."&gt;&lt;B&gt;Underdog&lt;/B&gt;&lt;/span&gt;&lt;/TD&gt; &lt;TD WIDTH="6%"&gt;&lt;span title="Line for Betting Over or Under the Total number of Points Scored by Both Teams Combined. Synonymous With Over/Under."&gt;&lt;B&gt;Total&lt;/B&gt;&lt;/span&gt;&lt;/TD&gt; &lt;TD WIDTH="19%"&gt;&lt;span title="Money odds to Win the Game Outright, Without any Point Spread. Minus (-) is Amount Bettors Risk for Each $100 on the Favorite to Win the Game Outright. Plus (+) is Amount Bettors Win for Each $100 Risked on the Underdog to Win the Game Outright."&gt;&lt;B&gt;Money Odds&lt;/B&gt;&lt;/span&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At Detroit&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-6&lt;/TD&gt; &lt;TD&gt;Tennessee&lt;/TD&gt; &lt;TD&gt;47&lt;/TD&gt; &lt;TD&gt;-$255 +$215&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At Houston&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-2.5&lt;/TD&gt; &lt;TD&gt;Kansas City&lt;/TD&gt; &lt;TD&gt;43&lt;/TD&gt; &lt;TD&gt;-$140 +$120&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At New England&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-6.5&lt;/TD&gt; &lt;TD&gt;Miami&lt;/TD&gt; &lt;TD&gt;42&lt;/TD&gt; &lt;TD&gt;-$290 +$240&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;Baltimore&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-6.5&lt;/TD&gt; &lt;TD&gt;At Cleveland&lt;/TD&gt; &lt;TD&gt;42.5&lt;/TD&gt; &lt;TD&gt;-$300 +$250&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At Pittsburgh&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-3.5&lt;/TD&gt; &lt;TD&gt;Cincinnati&lt;/TD&gt; &lt;TD&gt;48.5&lt;/TD&gt; &lt;TD&gt;-$180 +$160&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At Washington&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-2.5&lt;/TD&gt; &lt;TD&gt;Dallas&lt;/TD&gt; &lt;TD&gt;45.5&lt;/TD&gt; &lt;TD&gt;-$145 +$125&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At NY Giants&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-4.5&lt;/TD&gt; &lt;TD&gt;New Orleans&lt;/TD&gt; &lt;TD&gt;53.5&lt;/TD&gt; &lt;TD&gt;-$225 +$185&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 1:00 ET&lt;/TD&gt; &lt;TD&gt;At Carolina&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-13.5&lt;/TD&gt; &lt;TD&gt;San Francisco&lt;/TD&gt; &lt;TD&gt;45&lt;/TD&gt; &lt;TD&gt;-$900 +$600&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 4:05 ET&lt;/TD&gt; &lt;TD&gt;At Arizona&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-7&lt;/TD&gt; &lt;TD&gt;Tampa Bay&lt;/TD&gt; &lt;TD&gt;50&lt;/TD&gt; &lt;TD&gt;-$310 +$260&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 4:05 ET&lt;/TD&gt; &lt;TD&gt;Seattle&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-6.5&lt;/TD&gt; &lt;TD&gt;At Los Angeles&lt;/TD&gt; &lt;TD&gt;38&lt;/TD&gt; &lt;TD&gt;-$290 +$240&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 4:25 ET&lt;/TD&gt; &lt;TD&gt;At Denver&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-6.5&lt;/TD&gt; &lt;TD&gt;Indianapolis&lt;/TD&gt; &lt;TD&gt;46.5&lt;/TD&gt; &lt;TD&gt;-$280 +$240&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 4:25 ET&lt;/TD&gt; &lt;TD&gt;At Oakland&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-4.5&lt;/TD&gt; &lt;TD&gt;Atlanta&lt;/TD&gt; &lt;TD&gt;49&lt;/TD&gt; &lt;TD&gt;-$210 +$180&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 4:25 ET&lt;/TD&gt; &lt;TD&gt;At San Diego&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-3&lt;/TD&gt; &lt;TD&gt;Jacksonville&lt;/TD&gt; &lt;TD&gt;47&lt;/TD&gt; &lt;TD&gt;-$165 +$145&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;9/18 8:30 ET&lt;/TD&gt; &lt;TD&gt;Green Bay&lt;/TD&gt; &lt;TD&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;-2.5&lt;/TD&gt; &lt;TD&gt;At Minnesota&lt;/TD&gt; &lt;TD&gt;43.5&lt;/TD&gt; &lt;TD&gt;-$140 +$120&lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; </code></pre> <p>The Python code thus far.</p> <pre><code>from bs4 import BeautifulSoup import urllib url = "http://www.footballlocks.com/nfl_odds.shtml" html = urllib.urlopen(url) soup = BeautifulSoup(html, 'html.parser') for record in soup.find_all('tr'): for data in record.find_all('td'): print data.text </code></pre> <p>PS. My background is economics and my programming experience is limited.</p>
1
2016-09-16T18:53:02Z
39,552,858
<p>It is not the nicest html to parse as there are no classes we can use but this will put all the rows into a list of dicts:</p> <pre><code>from bs4 import BeautifulSoup import requests url = "http://www.footballlocks.com/nfl_odds.shtml" soup = BeautifulSoup(requests.get(url).content) # Use the text of one of the headers to find the correct table table = soup.find("span", text="Date &amp; Time").find_previous("table") data = [] # start from second tr for row in table.select("tr + tr"): # index to get the tds we need tds = [td.text for td in row.find_all("td")] fav, under, odds = tds[1], tds[2], tds[-1] # split money odds into fav/under odds f_odds,u_odds = odds.split() data.append({fav: f_odds.replace(u"$", ""), under : u_odds.replace(u"$", "")}) from pprint import pprint as pp pp(data) </code></pre> <p>Output:</p> <pre><code>[{u'At Detroit': u'-255', u'Tennessee': u'+215'}, {u'At Houston': u'-130', u'Kansas City': u'+110'}, {u'At New England': u'-290', u'Miami': u'+240'}, {u'At Cleveland': u'+225', u'Baltimore': u'-265'}, {u'At Pittsburgh': u'-175', u'Cincinnati': u'+155'}, {u'At Washington': u'-150', u'Dallas': u'+130'}, {u'At NY Giants': u'-215', u'New Orleans': u'+180'}, {u'At Carolina': u'-900', u'San Francisco': u'+600'}, {u'At Arizona': u'-330', u'Tampa Bay': u'+270'}, {u'At Los Angeles': u'+250', u'Seattle': u'-300'}, {u'At Denver': u'-275', u'Indianapolis': u'+235'}, {u'At Oakland': u'-210', u'Atlanta': u'+180'}, {u'At San Diego': u'-160', u'Jacksonville': u'+140'}, {u'At Minnesota': u'+115', u'Green Bay': u'-135'}] </code></pre>
1
2016-09-18T00:00:57Z
[ "python", "html", "web-scraping" ]
How to display images in html?
39,538,368
<p>I have a working app using the imgur API with python.</p> <pre><code>from imgurpython import ImgurClient client_id = '5b786edf274c63c' client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f' client = ImgurClient(client_id, client_secret) items = client.subreddit_gallery('rarepuppers') for item in items: print(item.link) </code></pre> <p>It outputs a set of imgur links. I want to display all those pictures on a webpage.</p> <p>Does anyone know how I can integrate python to do that in an HTML page?</p>
-1
2016-09-16T18:53:09Z
39,539,035
<p>OK, I haven't tested this, but it should work. The HTML is really basic (but you never mentioned anything about formatting) so give this a shot:</p> <pre><code>from imgurpython import ImgurClient client_id = '5b786edf274c63c' client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f' client = ImgurClient(client_id, client_secret) items = client.subreddit_gallery('rarepuppers') htmloutput = open('somename.html', 'w') htmloutput.write("[html headers here]") htmloutput.write("&lt;body&gt;") for item in items: print(item.link) htmloutput.write('&lt;a href="' + item.link + '"&gt;SOME DESCRIPTION&lt;/a&gt;&lt;br&gt;') htmloutput.write("&lt;/body&lt;/html&gt;") htmloutput.close </code></pre> <p>You can remove the print(item.link) statement in the code above - it's there to give you some comfort that stuff is happening.</p> <p>I've made a few assumptions:</p> <ol> <li>The item.link returns a string with only the unformatted link. If it's already in html format, then remove the HTML around item.link in the example above.</li> <li>You know how to add an HTML header. Let me know if you do not.</li> <li>This script will create the html file in the folder it's run from. This is probably not the greatest of ideas. So adjust the path of the created file appropriately.</li> </ol> <p><strong>Once again, though, if that is a real client secret, you probably want to change it ASAP.</strong></p>
0
2016-09-16T19:41:14Z
[ "python", "html", "api", "imgur" ]
read bash array from property file into a script
39,538,371
<ol> <li><p>I've a property file abc.prop that contains the following.</p> <pre><code>x=(A B) y=(C D) </code></pre></li> <li><p>I've a python script abc.py which is able to load the property file abc.prop. But I'm not able to iterate and convert both the arrays from abc.prop as follows,</p> <pre><code>x_array=['A','B'] y_array=['C','D'] </code></pre> <ol start="3"> <li>I tried the following, but I want to know if there's a better way of doing it, instead of using replace() and stripping off braces.</li> </ol> <p><code>importConfigFile = "abc.prop" propInputStream = FileInputStream(importConfigFile) configProps = Properties() configProps.load(propInputStream) x_str=configProps.get("x") x_str=x_str.replace("(","") x_str=x_str.replace(")","") x_array=x_str.split(' ')</code></p></li> </ol> <p>Please suggest a way to achieve this.</p>
0
2016-09-16T18:53:16Z
39,539,479
<p>I'm not aware of any special bash to python data structure converters. And I doubt there are any. The only thing I may suggest is a little bit cleaner and dynamic way of doing this.</p> <pre><code>data = {} with open('abc.prop', 'r') as f: for line in f: parts = line.split('=') key = parts[0].strip() value = parts[1].strip('()\n') values = value.split() data[key] = [x.strip() for x in values] print(data) </code></pre>
1
2016-09-16T20:16:20Z
[ "python" ]
Dynamic entries in a settings module
39,538,409
<p>I'm writing a package that imports audio files, processes them, plots them etc., for research purposes. At each stage of the pipeline, settings are pulled from a settings module as shown below. </p> <p>I want to be able to update a global setting like <code>MODEL_NAME</code> and have it update in any dicts containing it too.</p> <h2>settings.py</h2> <pre><code>MODEL_NAME = 'Test1' DAT_DIR = 'dir1/dir2/' PROCESSING = { "key1":{ "subkey2":0, "subkey3":1 }, "key2":{ "subkey3":MODEL_NAME } } </code></pre> <h2>run.py</h2> <pre><code>import settings as s wavs = import_wavs(s.DAT_DIR) proc_wavs = proc_wavs(wavs,s.PROCESSING) </code></pre> <p>Some of the settings dicts I would like to contain <code>MODEL_NAME</code>, which works fine. The problem arises when I want to change <code>MODEL_NAME</code> during runtime. So if I do:</p> <pre><code>import settings as s wavs = import_wavs(s.DAT_DIR) s.MODEL_NAME='test1' proc_wavs1 = proc_wavs(wavs,s.PROCESSING) s.MODEL_NAME='test2' proc_wavs2 = proc_wavs(wavs,s.PROCESSING) </code></pre> <p>But obviously both the calls so <code>s.PROCESSING</code> will contain the <code>MODEL_NAME</code> originally assigned in the settings file. What is the best way to have it update?</p> <p>Possible solutions I've thought of:</p> <ul> <li><p>Store the variables as a mutable type, then update it e.g.:</p> <pre><code>s.MODEL_NAME[0] = ["test1"] # do processing things s.MODEL_NAME[0] = ["test2"] </code></pre></li> <li><p>Define each setting category as a function instead, so it is rerun on each call e.g.: </p> <pre><code>MODEL_NAME = 'test1' .. def PROCESSING(): return { "key1":{ "subkey2":0, "subkey3":1 }, "key2":{ "subkey3":MODEL_NAME } } </code></pre> <p>Then</p> <pre><code>s.MODEL_NAME='test1' proc_wavs1 = proc_wavs(wavs,s.PROCESSING()) s.MODEL_NAME='test2' proc_wavs1 = proc_wavs(wavs,s.PROCESSING()) </code></pre> <p>I thought this would work great, but then it's very difficult to change any entries of the functions during runtime eg if I wanted to update the value of subkey2 and run something else.</p></li> </ul> <p>Other thoughts maybe a class with an update method or something, does anyone have any better ideas?</p>
0
2016-09-16T18:55:54Z
39,540,660
<p>You want to configure generic and specific settings structured in dictionaries for functions that perform waves analysis.</p> <p>Start by defining a settings class, like :</p> <pre><code>class Settings : data_directory = 'path/to/waves' def __init__(self, model): self.parameters= { "key1":{ "subkey1":0, "subkey2":0 }, "key2":{ "subkey1":model } } # create a new class based on model1 s1 = Settings('model1') # attribute values to specific keys s1.parameters["key1"]["subkey1"] = 3.1415926 s1.parameters["key1"]["subkey2"] = 42 # an other based on model2 s2 = Settings('model2') s2.parameters["key1"]["subkey1"] = 360 s2.parameters["key1"]["subkey2"] = 1,618033989 # load the audio wavs = openWaves(Settings.data_directory) # process with the given parameters results1 = processWaves(wavs,s1) results2 = processWaves(wavs,s2) </code></pre>
1
2016-09-16T21:59:01Z
[ "python", "dictionary", "configuration", "python-module" ]
My search in MySQL it's not working (Python)
39,538,456
<p>I'm trying to get information from a database I have. But everytime I search it says there is nothing that follows the query. This is what I have.</p> <pre><code>import datetime import MySQLdb db = MySQLdb.connect(user='root', passwd='', host='localhost', db = 'data') or die ('Error while connecting') cursor = db.cursor() sqlread = "SELECT * FROM humidity WHERE Date_Hour BETWEEN %s AND %s" ts1 = ('%s/%s/%s 07:00:00') % (now.year, now.month, now.day) ts2 = ('%s/%s/%s 03:00:00') % (now.year, now.month, now.day+1) tsdata = (ts1,ts2) cursor.excecute(sqlread,tsdata) db.commit() result = cursor.fetchall() print result </code></pre> <p>Therefore, the results is 0. But I made the same search on phpMyAdmin and it worked. What I'm doing wrong?</p> <p><strong>UPDATE:</strong></p> <p>Here is my result as Jason commented. <a href="http://i.stack.imgur.com/vx5P2.png" rel="nofollow"><img src="http://i.stack.imgur.com/vx5P2.png" alt="enter image description here"></a> However, I think Jason is right. I'm doing a GUI that make some charts. And I have 2 windows. One is making a graph with an animation using matplotlib, the program make the graphics with new data that is recolected from the database, so it is always asking. The other window just make one query but it doesn't work, so it could be possible because I'm asking "twice"?.</p>
2
2016-09-16T18:58:59Z
39,538,538
<p>Your <code>db.commit()</code> might be throwing it off. However, lots of factors could play a part in this. You might also consider printing out your SQL query to see what is being put so like this:</p> <p>Try setting up your code like this, it should lead you in the right direction:</p> <pre><code>import MySQLdb as mdb conn = mdb.connect('localhost', 'user', 'password', 'database_name') try: cur = conn.cursor() ts1 = ('%s/%s/%s 07:00:00') % (now.year, now.month, now.day) ts2 = ('%s/%s/%s 03:00:00') % (now.year, now.month, now.day + 1) sqlread = "SELECT * FROM my_table where blah between {} and {}".format(ts1, ts2) print(sqlread) cur.execute(sqlread) res = cur.fetchall() except mdb.Error as e: pass finally: if conn: conn.close() </code></pre>
1
2016-09-16T19:04:32Z
[ "python", "mysql", "datetime" ]
How to access preexisting table with Sqlalchemy
39,538,531
<p>I'm working with scrapy. I want to get access to a sqlalchemy session for a table with a table named 'contacts' according to the docs (<a href="http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session</a> ) I have created the following: </p> <pre><code>engine = create_engine('sqlite:///data.db') # create a configured "Session" class Session = sessionmaker(bind=engine) # create a Session session = Session() class ContactSpider(Spider): ....... def parse(self, response): print('hello') session.query(contacts).filter_by(name='ed').all() </code></pre> <p>However I am not seeing a way to connect to a preexisting table. How is this done?</p>
1
2016-09-16T19:04:08Z
39,543,773
<p>You can connect to pre-existing tables via reflection. Unfortunately your question lacks some of the code setup, so below is a general pseudocode example (assuming your table name is <code>contacts</code>)</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # Look up the existing tables from database Base.metadata.reflect(engine) # Create class that maps via ORM to the database table Contact = type('Contact', (Base,), {'__tablename__': 'contacts'}) </code></pre>
1
2016-09-17T06:54:11Z
[ "python", "sqlalchemy" ]
Python using lxml to write an xml file with system performance data
39,538,576
<p>I am using the python modules <code>lxml</code> and <code>psutil</code> to record some system metrics to be placed in an XML file and copied to a remote server for parsing by php and displayed to a user. </p> <p>However, lxml is giving me some trouble on pushing some variables, objects and such to the various parts of my XML.</p> <p>For example:</p> <pre><code>import psutil, os, time, sys, platform from lxml import etree # This creates &lt;metrics&gt; root = etree.Element('metrics') # and &lt;basic&gt;, to display basic information about the server child1 = etree.SubElement(root, 'basic') # First system/hostname, so we know what machine this is etree.SubElement(child1, "name").text = socket.gethostname() # Then boot time, to get the time the system was booted. etree.SubElement(child1, "boottime").text = psutil.boot_time() # and process count, see how many processes are running. etree.SubElement(child1, "proccount").text = len(psutil.pids()) </code></pre> <p>The line to get the system hostname works.</p> <p>However the next two lines to get boot time and process count error out, with:</p> <pre><code>&gt;&gt;&gt; etree.SubElement(child1, "boottime").text = psutil.boot_time() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "lxml.etree.pyx", line 921, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:41344) File "apihelpers.pxi", line 660, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:18894) File "apihelpers.pxi", line 1333, in lxml.etree._utf8 (src/lxml/lxml.etree.c:24601) TypeError: Argument must be bytes or unicode, got 'float' &gt;&gt;&gt; etree.SubElement(child1, "proccount").text = len(psutil.pids()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "lxml.etree.pyx", line 921, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:41344) File "apihelpers.pxi", line 660, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:18894) File "apihelpers.pxi", line 1333, in lxml.etree._utf8 (src/lxml/lxml.etree.c:24601) TypeError: Argument must be bytes or unicode, got 'int' </code></pre> <p>So, here's what my XML looks like as printed:</p> <pre><code>&gt;&gt;&gt; print(etree.tostring(root, pretty_print=True)) &lt;metrics&gt; &lt;basic&gt; &lt;name&gt;mercury&lt;/name&gt; &lt;boottime/&gt; &lt;proccount/&gt; &lt;/basic&gt; &lt;/metrics&gt; </code></pre> <p>So, is there anyway to push floats and ints to xml text like I need? Or am I doing this completely wrong?</p> <p>Thanks for any help you can provide.</p>
0
2016-09-16T19:07:19Z
39,538,627
<p>The <code>text</code> field is expected to be unicode or str, not any other type (<code>boot_time</code> is <code>float</code>, and <code>len()</code> is int). So just convert to string the non-string compliant elements:</p> <pre><code># First system/hostname, so we know what machine this is etree.SubElement(child1, "name").text = socket.gethostname() # nothing to do # Then boot time, to get the time the system was booted. etree.SubElement(child1, "boottime").text = str(psutil.boot_time()) # and process count, see how many processes are running. etree.SubElement(child1, "proccount").text = str(len(psutil.pids())) </code></pre> <p>result:</p> <pre><code>b'&lt;metrics&gt;\n &lt;basic&gt;\n &lt;name&gt;JOTD64&lt;/name&gt;\n &lt;boottime&gt;1473903558.0&lt;/boottime&gt;\n &lt;proccount&gt;121&lt;/proccount&gt;\n &lt;/basic&gt;\n&lt;/metrics&gt;\n' </code></pre> <p>I suppose the library could do the <code>isinstance(str,x)</code> test or <code>str</code> conversion, but it was not designed that way (what if you want to display your floats with leading zeroes, truncated decimals...). It operates faster if the lib assumes that everything is <code>str</code>, which it is most of the time.</p>
2
2016-09-16T19:11:08Z
[ "python", "lxml", "psutil" ]
Generate data with normally distributed noise and mean function
39,538,610
<p>I created a numpy array with n values from 0 to 2pi. Now, I want to generate n test data points deviating from sin(x) normally distributed. </p> <p>So i figured I need to do something like this: <code>t = sin(x) + noise</code>. Where the noise must be something like this: <code>noise = np.random.randn(mean, std)</code>.</p> <p>However, I do not know how I can calculate the noise when my mean is sin(x) (and not a constant).</p>
1
2016-09-16T19:09:46Z
39,538,803
<p>The arguments to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html" rel="nofollow"><code>numpy.random.randn</code></a> are not the mean and standard deviation. For that, you want <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html" rel="nofollow"><code>numpy.random.normal</code></a>. Its signature is</p> <pre><code>normal(loc=0.0, scale=1.0, size=None) </code></pre> <p>To add noise to your sin function, simply use a mean of 0 in the call of <code>normal()</code>. The mean corresponds to the <code>loc</code> argument (i.e. "location"), which by default is 0. So, given that <code>x</code> is something like <code>np.linspace(0, 2*np.pi, n)</code>, you can do this:</p> <pre><code>t = np.sin(x) + np.random.normal(scale=std, size=n) </code></pre> <hr> <p>You <em>could</em> use <code>numpy.random.randn</code>, but you have to scale it by <code>std</code>, because <code>randn</code> returns samples from the standard normal distribution, with mean 0 and standard deviation 1. To use <code>randn</code>, you would write:</p> <pre><code>t = np.sin(x) + std * np.random.randn(n) </code></pre>
2
2016-09-16T19:24:16Z
[ "python", "numpy", "scipy", "normal-distribution" ]
Generate data with normally distributed noise and mean function
39,538,610
<p>I created a numpy array with n values from 0 to 2pi. Now, I want to generate n test data points deviating from sin(x) normally distributed. </p> <p>So i figured I need to do something like this: <code>t = sin(x) + noise</code>. Where the noise must be something like this: <code>noise = np.random.randn(mean, std)</code>.</p> <p>However, I do not know how I can calculate the noise when my mean is sin(x) (and not a constant).</p>
1
2016-09-16T19:09:46Z
39,539,184
<p>If you add the noise to the <code>y</code> coordinate, some of the test data points may have values outside the normal range of the sine function, that is, not from -1 to 1, but from -(1+noise) to +(1+noise). I suggest to add the noise to the <code>x</code> coordinate: </p> <pre><code>t = np.sin(x + np.random.uniform(-noise, noise, x.shape)) </code></pre> <p>where <code>noise</code> must be a suitable value to your problem.</p>
1
2016-09-16T19:53:04Z
[ "python", "numpy", "scipy", "normal-distribution" ]
Get color of individual pixels of images in pygame
39,538,642
<p>How can I get the colour values of pixels of an image that is blitted onto a pygame surface? Using Surface.get_at() only returns the color of the surface layer, not the image that has been blitted over it.</p>
1
2016-09-16T19:11:53Z
39,550,937
<p>The method <code>surface.get_at</code> is fine. Here is an example showing the difference when blitting an image without alpha channel.</p> <pre><code>import sys, pygame pygame.init() size = width, height = 320, 240 screen = pygame.display.set_mode(size) image = pygame.image.load("./img.bmp") image_rect = image.get_rect() screen.fill((0,0,0)) screen.blit(image, image_rect) screensurf = pygame.display.get_surface() while 1: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN : mouse = pygame.mouse.get_pos() pxarray = pygame.PixelArray(screensurf) pixel = pygame.Color(pxarray[mouse[0],mouse[1]]) print pixel print screensurf.get_at(mouse) pygame.display.flip() </code></pre> <p>Here, clicking on a red pixel will give :</p> <pre><code>(0, 254, 0, 0) (254, 0, 0, 255) </code></pre> <p>The PixelArray returns a 0xAARRGGBB color component, while Color expect 0xRRGGBBAA. Also notice that the alpha channel of the screen surface is 255.</p>
3
2016-09-17T19:34:14Z
[ "python", "image", "image-processing", "pygame" ]
correct way to inherit method with 1 correction
39,538,665
<p>I experimented a little bit OOP in python, while doing homework on data structures and I have some troubles with understanding how to correct inherit some method with corrections. </p> <p>So, I have:</p> <pre><code>class BinarySearchTree(object): # snipped def _insert(self, key, val): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>And: </p> <pre><code>class RBTree(BinarySearchTree): # snipped def _insert(self, key, val): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode prevNode.size += 1 # The only difference is in this line if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>And there is my question: is there smart way to inherit this method and realise this 1 difference(<code>prevNode.size += 1</code>) without copying whole inherited function code?</p> <p><em>P.S.: sorry for my bad english.</em></p> <p>UPD: Now I cannot choose between Scott's and CAB's solutions...</p>
1
2016-09-16T19:13:35Z
39,538,742
<p>Assuming that <code>prevNode</code> is also a <code>BTree</code> or <code>RBTree</code>, you could add another method, say 'updateSize`, and include the line </p> <pre><code>prevNode.updateSize() </code></pre> <p>In <code>BTree</code>, this would do nothing. But if you make <code>RBTree</code> a subclass of <code>BTRee</code>, you could override this method to add 1 to the node's size.</p>
1
2016-09-16T19:19:33Z
[ "python", "python-2.7", "inheritance" ]
correct way to inherit method with 1 correction
39,538,665
<p>I experimented a little bit OOP in python, while doing homework on data structures and I have some troubles with understanding how to correct inherit some method with corrections. </p> <p>So, I have:</p> <pre><code>class BinarySearchTree(object): # snipped def _insert(self, key, val): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>And: </p> <pre><code>class RBTree(BinarySearchTree): # snipped def _insert(self, key, val): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode prevNode.size += 1 # The only difference is in this line if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>And there is my question: is there smart way to inherit this method and realise this 1 difference(<code>prevNode.size += 1</code>) without copying whole inherited function code?</p> <p><em>P.S.: sorry for my bad english.</em></p> <p>UPD: Now I cannot choose between Scott's and CAB's solutions...</p>
1
2016-09-16T19:13:35Z
39,538,944
<p>Here's a suggestion using the Visitor design pattern.</p> <p>In this pattern, you're writing a visitor method than knows specifically what needs to be done with each node visited.</p> <p>We'll change the base class to add a visitor capability;</p> <pre><code>class BinarySearchTree(object): # snipped def _insert(self, key, val, visitor=None): # Change here prevNode = None currentNode = self.root while currentNode: prevNode = currentNode if visitor: visitor(prevNode) # Change here if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>Now your second class;</p> <pre><code>class RBTree(BinarySearchTree): # snipped def _insert(self, key, val): visitor = lambda node: node.size += 1 super(RBTree, self)._insert(self, key, val, visitor) # snipped </code></pre>
1
2016-09-16T19:34:54Z
[ "python", "python-2.7", "inheritance" ]
correct way to inherit method with 1 correction
39,538,665
<p>I experimented a little bit OOP in python, while doing homework on data structures and I have some troubles with understanding how to correct inherit some method with corrections. </p> <p>So, I have:</p> <pre><code>class BinarySearchTree(object): # snipped def _insert(self, key, val): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>And: </p> <pre><code>class RBTree(BinarySearchTree): # snipped def _insert(self, key, val): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode prevNode.size += 1 # The only difference is in this line if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped </code></pre> <p>And there is my question: is there smart way to inherit this method and realise this 1 difference(<code>prevNode.size += 1</code>) without copying whole inherited function code?</p> <p><em>P.S.: sorry for my bad english.</em></p> <p>UPD: Now I cannot choose between Scott's and CAB's solutions...</p>
1
2016-09-16T19:13:35Z
39,539,060
<p>It's not exactly elegant, but you could do something like this:</p> <pre><code>class BinarySearchTree(object): def _insert(self, key, val, update=False): prevNode = None currentNode = self.root while currentNode: prevNode = currentNode if update: prevNode.size += 1 if key &lt; currentNode.key: currentNode = currentNode.leftChild else: currentNode = currentNode.rightChild if key &lt; prevNode.key: prevNode.leftChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.leftChild) else: prevNode.rightChild = self.Node(key, val, parent=prevNode) self.updateNodeProperties(prevNode.rightChild) # snipped class RBTree(BinarySearchTree): # snipped def _insert(self, key, val): super(RBTree, self)._insert(self, key, val, update=True) </code></pre> <p>I don't really like that, because it has code in your <code>BinarySearchTree</code> class to update an instance variable that doesn't exist except in the derived <code>RBTree</code> class, but since that part of the code shouldn't ever get executed for a <code>BinarySearchTree</code> instance, you shouldn't encounter a <code>NameError</code>...</p>
2
2016-09-16T19:43:28Z
[ "python", "python-2.7", "inheritance" ]
Relative Python Modules
39,538,721
<p>I am having a lot of trouble understanding the python module import system.</p> <p>I am trying to create a simple folder structure as follows.</p> <pre><code>SomeModule __init__.py AnotherModule AnotherModule.py __init__.py Utils Utils.py __init__.py </code></pre> <p>To use SomeModule i can do:</p> <pre><code>SomeModule.Foo() </code></pre> <p>Now inside AnotherModule.py I would like to import my Utils directory.</p> <p>How come I have to do</p> <pre><code>import SomeModule.AnotherModule.Utils.Foo </code></pre> <p>why cannot I just do</p> <pre><code>import Utils.Foo </code></pre>
1
2016-09-16T19:18:16Z
39,538,866
<p>To shorten up the actual function name that you'll have to call in your code, you can always do:</p> <pre><code>from SomeModule.AnotherModule.Utils import * </code></pre> <p>While this still won't allow you to get away with a shorter import statement at the top of your script, you'll be able to access all of the functions within <code>.Utils</code> just by calling their function name (i.e. <code>foo(x)</code> instead of <code>SomeModule.AnotherModule.Utils.foo(x)</code>. </p> <p>Part of the reason for the lengthy import statement goes to the comment from @wim . Have a look by typing <code>import this</code> in a python interpreter. </p>
0
2016-09-16T19:29:22Z
[ "python", "python-2.7" ]
Relative Python Modules
39,538,721
<p>I am having a lot of trouble understanding the python module import system.</p> <p>I am trying to create a simple folder structure as follows.</p> <pre><code>SomeModule __init__.py AnotherModule AnotherModule.py __init__.py Utils Utils.py __init__.py </code></pre> <p>To use SomeModule i can do:</p> <pre><code>SomeModule.Foo() </code></pre> <p>Now inside AnotherModule.py I would like to import my Utils directory.</p> <p>How come I have to do</p> <pre><code>import SomeModule.AnotherModule.Utils.Foo </code></pre> <p>why cannot I just do</p> <pre><code>import Utils.Foo </code></pre>
1
2016-09-16T19:18:16Z
39,539,157
<p>put</p> <pre><code>import sys import SomeModule.AnotherModule sys.modules['AnotherModule'] = SomeModule.AnotherModule </code></pre> <p>in SomeModules <code>__init__.py</code></p>
0
2016-09-16T19:51:06Z
[ "python", "python-2.7" ]
Is file automatically closed if read in same line as opening?
39,538,802
<p>If I do (in Python):</p> <pre><code>text = open("filename").read() </code></pre> <p>is the file automatically closed?</p>
4
2016-09-16T19:24:14Z
39,538,833
<p>The garbage collector would be activated at some point, but you cannot be certain of when unless you force it.</p> <p>The best way to ensure that the file is closed when you go out of scope just do this:</p> <pre><code>with open("filename") as f: text = f.read() </code></pre> <p>also one-liner but safer.</p>
6
2016-09-16T19:26:47Z
[ "python", "file", "io" ]
Is file automatically closed if read in same line as opening?
39,538,802
<p>If I do (in Python):</p> <pre><code>text = open("filename").read() </code></pre> <p>is the file automatically closed?</p>
4
2016-09-16T19:24:14Z
39,538,837
<p>In CPython (the reference Python implementation) the file will be automatically closed. CPython destroys objects as soon as they have no references, which happens at the end of the statement at the very latest.</p> <p>In other Python implementations this may not happen right away since they may rely on the memory management of an underlying virtual machine, or use some other memory management strategy entirely (see PyParallel for an interesting example).</p> <p>Python, the language, does not specify any particular form of memory management, so you can't rely on the file being closed in the general case. Use the <code>with</code> statement to explicitly specify when it will be closed if you need to rely on it.</p> <p>In practice, I often use this approach in short-lived scripts where it doesn't really matter when the file gets closed.</p>
3
2016-09-16T19:27:15Z
[ "python", "file", "io" ]
Is file automatically closed if read in same line as opening?
39,538,802
<p>If I do (in Python):</p> <pre><code>text = open("filename").read() </code></pre> <p>is the file automatically closed?</p>
4
2016-09-16T19:24:14Z
39,538,839
<p>Since you have no reference on the open file handle, CPython will close it automatically either during garbage collection or at program exit. The problem here is that you don't have any guarantees about when that will occur, which is why the <code>with open(...)</code> construct is preferred. </p>
2
2016-09-16T19:27:21Z
[ "python", "file", "io" ]
Django - Why are variables declared in Model Classes Static
39,538,841
<p>I have been reading and working with Django for a bit now. One of the things that I am still confused with is why the model classes that we create in Django are made up of static variables and not member variables. For instance</p> <pre><code>class Album(models.Model): artist = models.CharField(max_length=128, unique=True) title = models.CharField(max_length=128, unique=True) genre = models.CharField(max_length=128, unique=True) def __unicode__(self): return self.name </code></pre> <p>I read <a href="http://stackoverflow.com/questions/68645/static-class-variables-in-python">this</a> page here which explains static and instance variables in python however i am still confused as to why Django wants the field variables in models be static ?</p>
1
2016-09-16T19:27:32Z
39,540,205
<p>Django uses a <a href="https://docs.python.org/3/reference/datamodel.html#customizing-class-creation" rel="nofollow">metaclass</a> to create the model class. Just as a class's <code>__init__()</code> method creates a new instance, the metaclass's <code>__new__()</code> method creates the class itself. All variables, functions, properties, etc. defined in the class body are passed to the <code>__new__()</code> function. Strictly speaking, just defining a variable in the class body does not create a static/class variable -- only when the <code>__new__()</code> function receives the variable and sets it on the class, will it be a class/static variable. </p> <p>Django overrides this behavior when it comes to fields and the special <code>Meta</code> inner class, by providing a custom <code>__new__()</code> method. The options in the inner <code>Meta</code> class are converted to an <code>Options</code> instance, and that instance is stored as <code>Model._meta</code> rather than <code>Model.Meta</code>. Similarly, any fields you define are stored in <code>Model._meta.fields</code> rather than as class/static variables. </p> <p>You will notice that in your example, the class <code>Album</code> does not have a <code>artist</code> attribute: <code>Album.artist</code> will simply raise an <code>AttributeError</code>. This is because the metaclass moves the field from the class to <code>Album._meta.fields</code>. Instances of <code>Album</code> do have an <code>artists</code> attribute, but <em>this is not the field</em>. Instead, it's the database value related to the field. The <code>__init__</code> method of a model uses <code>self._meta.fields</code> to populate any attributes with either the value that is passed to <code>__init__</code>, or with the default value, to assure that the instance variable exists.</p> <p>Only class variables are passed to the <code>__new__</code> method. If you were to define a field as an instance variable inside <code>__init__</code>, the field would never be passed to <code>Model._meta.fields</code>, and Django simply doesn't know about the field. You will be able to access <code>Album.artist</code>, but this will be the actual field instance, not the related database value. Basically you would be missing the magic that makes a model into a model. </p>
1
2016-09-16T21:17:42Z
[ "python", "django" ]
Parsing text fields into excel columns
39,538,943
<p>I've attempted to parse out data that's over 20,000 records. Each record has 4 fields that's prefixed with 2 alphanumeric values. Below is an example with 2 records. I currently have a bloated solution that uses Java based on the link here: <a href="http://stackoverflow.com/questions/25491424/parsing-html-data-using-java-dom-parse">Parsing HTML Data using Java (DOM parse)</a>. But I'm not looking to use that solution as it is overkill for just seperating the records. Is there a solution that uses VBS, Python or any other language that can separate out the fields based on the logic I've used already? Or another logical approach?</p> <pre><code> 100000000 SMP008483 |--- Category Western |--- Model Ford |--- Asset Delivered Date ? |--- Scheduled ? 100000001 SMP008484 |--- Category Eastern |--- Model Chevrolet |--- Asset Delivered Date ? |--- Scheduled ? </code></pre> <p>Expected output is here:</p> <pre><code>ID1 ID2 Category Model Asset Delivered Date Scheduled 100000000 SMP008483 Western Ford ? ? 100000001 SMP008484 Eastern Chevrolet ? ? </code></pre>
1
2016-09-16T19:34:54Z
39,540,858
<p>This one is kinda crappy but it works. here you go:</p> <pre><code>#!/bin/bash i=0 while IFS= read -r line;do echo $line | egrep -q '^[0-9]+' if test $? -eq 0; then id1=$(echo $line | cut -d' ' -f1) id2=$(echo $line | cut -d' ' -f2) ((i++)) fi echo $line | egrep -q 'Category' if test $? -eq 0; then cat=$(echo $line | sed -e 's/^.*Category//') ((i++)) fi echo $line | egrep -q 'Model' if test $? -eq 0; then model=$(echo $line | sed -e 's/^.*Model//') ((i++)) fi echo $line | egrep -q 'Asset Delivered Date' if test $? -eq 0; then date=$(echo $line | sed -e 's/^.*Asset Delivered Date//') ((i++)) fi echo $line | egrep -q 'Scheduled' if test $? -eq 0; then sch=$(echo $line | sed -e 's/^.*Scheduled//') ((i++)) fi if test $i -eq 5; then echo -e "${id1}\t${id2}\t${cat}\t${model}\t${date}\t${sch}" i=0 fi done &lt;&lt;&lt; "$(cat ${1})" </code></pre> <p>*Do not forget of adding all fields, because it will break if you do.</p>
0
2016-09-16T22:18:44Z
[ "python", "excel", "parsing", "text", "vbscript" ]
What files are required for Py_Initialize to run?
39,539,089
<p>I am working on a simple piece of code that runs a Python function from a C/C++ application. In order to do this I set the PYTHONPATH and run initialize as follows:</p> <pre class="lang-c++ prettyprint-override"><code>Py_SetPythonHome("../Python27"); Py_InitializeEx(0); </code></pre> <p>Then I import my module and run my function. It works great.</p> <p>I am now attempting to build an installer for my colleagues to run my code. I want to minimize the number of files I need to include in this installer, for obvious reasons.</p> <p>Googling around the subject tells me that I should be able to include the files "Python27.lib" and "Python27.dll", then zip the "DLLs" and "Lib" folders and include them. However, when I attempt this, Py_Initialize fails. </p> <p>A quick examination of what is causing this failure shows that Py_Initialize appears to depend upon a number of .pyc files in the Lib folder including (but not limited to <em>warnings.pyc</em>, <em>_abcoll.pyc</em>, <em>_future_.pyc</em> and the contents of the "encodings" folder.</p> <p>I cannot understand why this would be. Any advice?</p>
3
2016-09-16T19:45:42Z
39,541,474
<p>At the beginning I wanted to say that there's no module required (at least no <em>non-builtin</em> one) for <code>Py_InitializeEx</code>, so the only requirement was <em>python27.dll</em> (btw: <em>python27.lib</em> is <strong>not</strong> required, unless your colleagues want to link something against it - but that wouldn't be very easy w/o <em>Python</em>'s <em>Include</em> dir). I had this code (<strong>BTW</strong>: I am using <em>Python 2.7.10</em> that I built using <em>Visual Studio 10.0</em>):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;conio.h&gt; #include &lt;Python.h&gt; int main() { int i = 0; char *pyCode = "s = \"abc\"\n" "print s, 1234"; Py_InitializeEx(0); i = PyRun_SimpleString(pyCode); Py_Finalize(); printf("PyRun_SimpleString returned: %d\nPress a key to exit...\n", i); _getch(); return 0; } </code></pre> <p>It built fine, it ran OK from <em>Visual Studio</em>, and from the command line (after copying the <em>.dll</em> in its folder). But then I copied the <em>.exe</em> and <em>.dll</em> to another computer and when running, <em>bang!!!</em></p> <blockquote> <p>ImportError: No module named site</p> </blockquote> <p>Considering that:</p> <ul> <li>I have no <em>PYTHON*</em> env vars set in neither of the consoles on the 2 machines where I ran the <em>.exe</em> (with different results)</li> <li>On both machines the <em>Python</em> installation is on the same path (I modified it on the machine that doesn't work)</li> </ul> <p>I don't know why it doesn't behave the same (one thing that I haven't check is that there might be some registry key on the machine that works?).</p> <p><em>Note</em>: <code>site</code> is a (<em>.py(c)</em>) module located under <em>%PYTHON_INSTALL_DIR%\Lib</em>.</p> <p>Then, I browsed <em>Python</em>'s source code and I came across this (file: <em>pythonrun.c</em>, line: <em>269</em>, function <code>Py_InitializeEx</code> or <em>pythonrun.c:269:<code>Py_InitializeEx</code></em> - this is how I'm going to refer a point in the source code):</p> <pre><code> if (!Py_NoSiteFlag) initsite(); /* Module site */ </code></pre> <p>while in <em>pythonrun.c:727:<code>initsite</code></em>:</p> <pre><code> m = PyImport_ImportModule("site"); </code></pre> <p>which is pretty obvious (<code>Py_NoSiteFlag</code> is 0).</p> <p>Then I noticed that <code>Py_NoSiteFlag</code> is declared as <a href="https://msdn.microsoft.com/en-us/library/aa299338(v=vs.60).aspx" rel="nofollow"><code>extern</code></a> <a href="https://msdn.microsoft.com/en-us/library/3y1sfaz2(v=vs.100).aspx" rel="nofollow"><code>__declspec(dllexport)</code></a>, so I modified my code to:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;conio.h&gt; #include &lt;Python.h&gt; extern __declspec(dllimport) int Py_NoSiteFlag; int main() { int i = 0; char *pyCode = "s = \"abc\"\n" "print s, 1234"; Py_NoSiteFlag = 1; Py_InitializeEx(0); i = PyRun_SimpleString(pyCode); Py_Finalize(); printf("PyRun_SimpleString returned: %d\nPress a key to exit...\n", i); _getch(); return 0; } </code></pre> <p>and it works! Yay!</p> <p>So, at this point only the <em>.dll</em> is required in order to run a piece of code. But I imagine that your code is "a little bit" more complex than that (it has <a href="https://docs.python.org/2.0/ref/import.html" rel="nofollow"><code>import</code></a>s). To solve the <em>import</em> problem, you can use this nice module called <a href="https://docs.python.org/2/library/modulefinder.html?highlight=modulefinder#module-modulefinder" rel="nofollow"><code>modulefinder</code></a> (part of <em>Python 2.7</em>'s standard modules). To make use of it:</p> <ul> <li>save the code that you execute from <em>C</em> in a <em>.py</em> file</li> <li>run <code>modulefinder</code> against it</li> </ul> <p>Here's an example for my code (<code>pyCode</code> contents in my <em>C</em> program, saved in a file called <em>a.py</em>):</p> <pre><code>s = "abc" print s, 1234 </code></pre> <p>Running <code>%PYTHON_INSTALL_DIR%\python %PYTHON_INSTALL_DIR%\Lib\modulefinder.py a.py</code> yields:</p> <blockquote> <p><code>Name File</code><BR> <code>---- ----</code><BR> <code>m __main__ a.py</code></p> </blockquote> <p><strong>But</strong>, if I add an <code>import os</code> (which is a pretty common module) statement in the file, the above command yields:</p> <blockquote> <p><code>Name File</code><BR> <code>---- ----</code><BR> <code>m StringIO %PYTHON_INSTALL_DIR%\lib\StringIO.py</code><BR> <code>m UserDict %PYTHON_INSTALL_DIR%\lib\UserDict.py</code><BR> <code>m __builtin__</code><BR> <code>m __future__ %PYTHON_INSTALL_DIR%\lib\__future__.py</code><BR> <code>m __main__ a.py</code><BR> <code>m _abcoll %PYTHON_INSTALL_DIR%\lib\_abcoll.py</code><BR> <code>m _codecs</code><BR> <code>m _collections</code><BR> <code>m _functools</code><BR> <code>m _hashlib %PYTHON_INSTALL_DIR%\DLLs\_hashlib.pyd</code><BR> <code>m _heapq</code><BR> <code>m _io</code><BR> <code>m _locale</code><BR> <code>m _random</code><BR> <code>m _sre</code><BR> <code>m _struct</code><BR> <code>m _subprocess</code><BR> <code>m _threading_local %PYTHON_INSTALL_DIR%\lib\_threading_local.py</code><BR> <code>m _warnings</code><BR> <code>m _weakref</code><BR> <code>m _weakrefset %PYTHON_INSTALL_DIR%\lib\_weakrefset.py</code><BR> <code>m abc %PYTHON_INSTALL_DIR%\lib\abc.py</code><BR> <code>m array</code><BR> <code>m atexit %PYTHON_INSTALL_DIR%\lib\atexit.py</code><BR> <code>m bdb %PYTHON_INSTALL_DIR%\lib\bdb.py</code><BR> <code>m binascii</code><BR> <code>m cPickle</code><BR> <code>m cStringIO</code><BR> <code>m cmd %PYTHON_INSTALL_DIR%\lib\cmd.py</code><BR> <code>m codecs %PYTHON_INSTALL_DIR%\lib\codecs.py</code><BR> <code>m collections %PYTHON_INSTALL_DIR%\lib\collections.py</code><BR> <code>m copy %PYTHON_INSTALL_DIR%\lib\copy.py</code><BR> <code>m copy_reg %PYTHON_INSTALL_DIR%\lib\copy_reg.py</code><BR> <code>m difflib %PYTHON_INSTALL_DIR%\lib\difflib.py</code><BR> <code>m dis %PYTHON_INSTALL_DIR%\lib\dis.py</code><BR> <code>m doctest %PYTHON_INSTALL_DIR%\lib\doctest.py</code><BR> <code>m dummy_thread %PYTHON_INSTALL_DIR%\lib\dummy_thread.py</code><BR> <code>P encodings %PYTHON_INSTALL_DIR%\lib\encodings\__init__.py</code><BR> <code>m encodings.aliases %PYTHON_INSTALL_DIR%\lib\encodings\aliases.py</code><BR> <code>m errno</code><BR> <code>m exceptions</code><BR> <code>m fnmatch %PYTHON_INSTALL_DIR%\lib\fnmatch.py</code><BR> <code>m functools %PYTHON_INSTALL_DIR%\lib\functools.py</code><BR> <code>m gc</code><BR> <code>m genericpath %PYTHON_INSTALL_DIR%\lib\genericpath.py</code><BR> <code>m getopt %PYTHON_INSTALL_DIR%\lib\getopt.py</code><BR> <code>m gettext %PYTHON_INSTALL_DIR%\lib\gettext.py</code><BR> <code>m hashlib %PYTHON_INSTALL_DIR%\lib\hashlib.py</code><BR> <code>m heapq %PYTHON_INSTALL_DIR%\lib\heapq.py</code><BR> <code>m imp</code><BR> <code>m inspect %PYTHON_INSTALL_DIR%\lib\inspect.py</code><BR> <code>m io %PYTHON_INSTALL_DIR%\lib\io.py</code><BR> <code>m itertools</code><BR> <code>m keyword %PYTHON_INSTALL_DIR%\lib\keyword.py</code><BR> <code>m linecache %PYTHON_INSTALL_DIR%\lib\linecache.py</code><BR> <code>m locale %PYTHON_INSTALL_DIR%\lib\locale.py</code><BR> <code>P logging %PYTHON_INSTALL_DIR%\lib\logging\__init__.py</code><BR> <code>m marshal</code><BR> <code>m math</code><BR> <code>m msvcrt</code><BR> <code>m nt</code><BR> <code>m ntpath %PYTHON_INSTALL_DIR%\lib\ntpath.py</code><BR> <code>m opcode %PYTHON_INSTALL_DIR%\lib\opcode.py</code><BR> <code>m operator</code><BR> <code>m optparse %PYTHON_INSTALL_DIR%\lib\optparse.py</code><BR> <code>m os %PYTHON_INSTALL_DIR%\lib\os.py</code><BR> <code>m os2emxpath %PYTHON_INSTALL_DIR%\lib\os2emxpath.py</code><BR> <code>m pdb %PYTHON_INSTALL_DIR%\lib\pdb.py</code><BR> <code>m pickle %PYTHON_INSTALL_DIR%\lib\pickle.py</code><BR> <code>m posixpath %PYTHON_INSTALL_DIR%\lib\posixpath.py</code><BR> <code>m pprint %PYTHON_INSTALL_DIR%\lib\pprint.py</code><BR> <code>m random %PYTHON_INSTALL_DIR%\lib\random.py</code><BR> <code>m re %PYTHON_INSTALL_DIR%\lib\re.py</code><BR> <code>m repr %PYTHON_INSTALL_DIR%\lib\repr.py</code><BR> <code>m select %PYTHON_INSTALL_DIR%\DLLs\select.pyd</code><BR> <code>m shlex %PYTHON_INSTALL_DIR%\lib\shlex.py</code><BR> <code>m signal</code><BR> <code>m sre_compile %PYTHON_INSTALL_DIR%\lib\sre_compile.py</code><BR> <code>m sre_constants %PYTHON_INSTALL_DIR%\lib\sre_constants.py</code><BR> <code>m sre_parse %PYTHON_INSTALL_DIR%\lib\sre_parse.py</code><BR> <code>m stat %PYTHON_INSTALL_DIR%\lib\stat.py</code><BR> <code>m string %PYTHON_INSTALL_DIR%\lib\string.py</code><BR> <code>m strop</code><BR> <code>m struct %PYTHON_INSTALL_DIR%\lib\struct.py</code><BR> <code>m subprocess %PYTHON_INSTALL_DIR%\lib\subprocess.py</code><BR> <code>m sys</code><BR> <code>m tempfile %PYTHON_INSTALL_DIR%\lib\tempfile.py</code><BR> <code>m textwrap %PYTHON_INSTALL_DIR%\lib\textwrap.py</code><BR> <code>m thread</code><BR> <code>m threading %PYTHON_INSTALL_DIR%\lib\threading.py</code><BR> <code>m time</code><BR> <code>m token %PYTHON_INSTALL_DIR%\lib\token.py</code><BR> <code>m tokenize %PYTHON_INSTALL_DIR%\lib\tokenize.py</code><BR> <code>m traceback %PYTHON_INSTALL_DIR%\lib\traceback.py</code><BR> <code>m types %PYTHON_INSTALL_DIR%\lib\types.py</code><BR> <code>P unittest %PYTHON_INSTALL_DIR%\lib\unittest\__init__.py</code><BR> <code>m unittest.case %PYTHON_INSTALL_DIR%\lib\unittest\case.py</code><BR> <code>m unittest.loader %PYTHON_INSTALL_DIR%\lib\unittest\loader.py</code><BR> <code>m unittest.main %PYTHON_INSTALL_DIR%\lib\unittest\main.py</code><BR> <code>m unittest.result %PYTHON_INSTALL_DIR%\lib\unittest\result.py</code><BR> <code>m unittest.runner %PYTHON_INSTALL_DIR%\lib\unittest\runner.py</code><BR> <code>m unittest.signals %PYTHON_INSTALL_DIR%\lib\unittest\signals.py</code><BR> <code>m unittest.suite %PYTHON_INSTALL_DIR%\lib\unittest\suite.py</code><BR> <code>m unittest.util %PYTHON_INSTALL_DIR%\lib\unittest\util.py</code><BR> <code>m warnings %PYTHON_INSTALL_DIR%\lib\warnings.py</code><BR> <code>m weakref %PYTHON_INSTALL_DIR%\lib\weakref.py</code><BR></p> <p><code>Missing modules:</code><BR> <code>? _emx_link imported from os</code><BR> <code>? ce imported from os</code><BR> <code>? fcntl imported from subprocess, tempfile</code><BR> <code>? org.python.core imported from copy, pickle</code><BR> <code>? os.path imported from os, shlex</code><BR> <code>? os2 imported from os</code><BR> <code>? posix imported from os</code><BR> <code>? pwd imported from posixpath</code><BR> <code>? readline imported from cmd, pdb</code><BR> <code>? riscos imported from os</code><BR> <code>? riscosenviron imported from os</code><BR> <code>? riscospath imported from os</code><BR></p> </blockquote> <p>As you can see, there is an awfully lot of modules (I modified the output a little bit, instead of the actual path I placed the <em>%PYTHON_INSTALL_DIR%</em> env var). In order for the <em>Python</em> code to work, you'll have to include all of those modules/packages in the installer.</p> <p>Notes about <code>modulefinder</code>'s output (that I've noticed while playing with it):</p> <ul> <li>It searches for modules recursively, so here is the whole module dependency tree</li> <li>It searches for <em>import</em> statements located in functions (so, not only the ones at module level)</li> <li>It <strong>doesn't</strong> search for dynamic imports (e.g. <a href="https://docs.python.org/2/library/functions.html#__import__" rel="nofollow">__import__</a>)</li> </ul> <p>So, looking at the modules that are required by <code>os</code>, I'm not sure that taking out the <code>site</code> import from <em>C</em> makes much of a difference.</p> <p><strong>IMPORTANT NOTE</strong>: To make sure your <em>.exe</em> works on any computer, you might consider including <em>Visual Studio C runtime library</em> (<a href="https://msdn.microsoft.com/en-us/library/59ey50w6(v=vs.100).aspx" rel="nofollow">msvcr##(#).dll</a>) (where <em>#</em> s are placeholders for digits - representing <em>Visual Studio</em> version) in your installer.</p>
0
2016-09-16T23:45:30Z
[ "python", "c++", "ctypes", "embedding" ]
Beginning Python: For Loop- what do to afterwards
39,539,090
<p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p> <p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and <em>root</em> such that 0 &lt; pwr &lt; 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print "No such integers exist."</p> <p>How can I test to see if any #s meet the criteria and if none do, say that?</p> <pre><code>u_i = int(input("input a #:")) root = u_i**.5 for pwr in range(1,6): ans = root**pwr if ans == u_i: print(pwr) print(int(root)) #here is where the problem comes in as it will do this every time and I'm\ failing to discover what I should do instead. if ans!= u_i: print("No such integer exists") </code></pre> <p>Full disclosure: Its been a long time since my last math class so I'm not convinced my "solution" is even correct for what the question is asking. I'm more interested in solving the dilemma I'm facing however as I'm trying to wrap my head around using loops properly.</p>
2
2016-09-16T19:45:51Z
39,539,279
<p>You want to check if there is an integer <code>root</code> such that <code>root ** pwr == user_input</code>. With a little math we can re-write the above statement as <code>root = user_input ** (1. / pwr)</code>. You've got a pretty small number of <code>pwr</code> values to choose from, so you can simply loop over those values (it looks like you've already got that part figured out). The last thing you need to do is (for each <code>pwr</code>) check to see if <code>root</code> is an integer, you could use <code>root % 1 == 0</code> or <code>int(root) == root</code>.</p> <p>If you want to look "fancy" you could use python's for ... else syntax. The <code>else</code> block in a for loop only gets executed if the loop finishes without a break. For example:</p> <pre><code>def has_dogs(pets): # This functions check to see if "dog" is one of the pets for p in pets: if p == "dog": print "found a dog!" break else: # This block only gets run if the loop finishes # without hitting "break" print "did not find any dogs :(" </code></pre> <p>The for ... else syntax is basically a fancy way to do this:</p> <pre><code>def has_dogs(pets): # This functions check to see if "dog" is one of the pets dog_found = False for p in pets: if p == "dog": print "found a dog!" dog_found = True break if not dog_found: print "did not find any dogs :(" </code></pre>
3
2016-09-16T20:00:37Z
[ "python", "if-statement", "for-loop" ]
Beginning Python: For Loop- what do to afterwards
39,539,090
<p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p> <p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and <em>root</em> such that 0 &lt; pwr &lt; 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print "No such integers exist."</p> <p>How can I test to see if any #s meet the criteria and if none do, say that?</p> <pre><code>u_i = int(input("input a #:")) root = u_i**.5 for pwr in range(1,6): ans = root**pwr if ans == u_i: print(pwr) print(int(root)) #here is where the problem comes in as it will do this every time and I'm\ failing to discover what I should do instead. if ans!= u_i: print("No such integer exists") </code></pre> <p>Full disclosure: Its been a long time since my last math class so I'm not convinced my "solution" is even correct for what the question is asking. I'm more interested in solving the dilemma I'm facing however as I'm trying to wrap my head around using loops properly.</p>
2
2016-09-16T19:45:51Z
39,539,343
<p>How about this?</p> <pre><code>userNum = int(input("Choose a number: ")) for i in range(1,6): for j in range(userNum): if j ** i == userNum: pwr = i root = j if pwr: print('pwr = {}, root = {}'.format(pwr, root)) print("No such integers exist.") </code></pre>
-1
2016-09-16T20:06:55Z
[ "python", "if-statement", "for-loop" ]
Beginning Python: For Loop- what do to afterwards
39,539,090
<p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p> <p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and <em>root</em> such that 0 &lt; pwr &lt; 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print "No such integers exist."</p> <p>How can I test to see if any #s meet the criteria and if none do, say that?</p> <pre><code>u_i = int(input("input a #:")) root = u_i**.5 for pwr in range(1,6): ans = root**pwr if ans == u_i: print(pwr) print(int(root)) #here is where the problem comes in as it will do this every time and I'm\ failing to discover what I should do instead. if ans!= u_i: print("No such integer exists") </code></pre> <p>Full disclosure: Its been a long time since my last math class so I'm not convinced my "solution" is even correct for what the question is asking. I'm more interested in solving the dilemma I'm facing however as I'm trying to wrap my head around using loops properly.</p>
2
2016-09-16T19:45:51Z
39,539,677
<p>Here's my solution using @BiRico's <code>for..else</code> strategy and an inner <code>while</code> loop to make it more efficient. Of course, because there is no bounds on <code>root</code> and we're only looking for one solution, it only finds the trivial case (<code>root = number, pwr = 1</code>).</p> <pre><code>number = int(input("Choose a number: ")) for pwr in range(1,6): root = 1 guess = root ** pwr # We can stop guessing once it's too big while guess &lt; number: root += 1 guess = root ** pwr if guess == number: print('root = {}, pwr = {}'.format(root, pwr)) break else: # nobreak print('No such integers exist') </code></pre>
0
2016-09-16T20:31:31Z
[ "python", "if-statement", "for-loop" ]
Django Password Resest Via Email
39,539,102
<p>I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. </p> <p>I took by example <a href="http://stackoverflow.com/questions/18928144/django-user-registration-password-reset-via-email">this question</a> and <a href="http://ruddra.com/2015/09/18/implementation-of-forgot-reset-password-feature-in-django/" rel="nofollow">this site</a>.</p> <p>But my problem is a bit different. I don't have a local database containing the users, so I cannot perform operations over their attributes. I receive user data via an API (user id, user email, user password).</p> <p>So, which is the best way to <strong>generate a unique link</strong> to send via email to user so that this link would <strong>tell me who the user is</strong> and allow me to <strong>reset his/her password</strong>? And also, how could I redirect it in <strong>urls.py</strong>? I wish that this link could be used only a single time.</p> <p>My views.py is like this:</p> <pre><code>def password_reset_form(request): if request.method == 'GET': form = PasswordResetForm() else: form = PasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] content_dict = { 'email': email, 'domain': temp_data.DOMAIN, 'site_name': temp_data.SITE_NAME, 'protocol': temp_data.PROTOCOL, } subject = content_dict.get('site_name')+ ' - Password Reset' content = render_to_string('portal/password_reset_email.html', content_dict) send_mail(subject, content, temp_data.FIBRE_CONTACT_EMAIL, [email]) return render(request, 'portal/password_reset_done.html', {'form': form,}) return render(request, 'portal/password_reset_form.html', {'form': form,}) </code></pre> <p>And the template the e-mail I'm sending is:</p> <pre><code>{% autoescape off %} You're receiving this e-mail because we got a request to reset the password for your user account at {{ site_name }}. Please go to the following page and choose a new password: {% block reset_link %} {{ protocol }}://{{ domain }}/[***some unique link***] {% endblock %} If you didn't request a password reset, let us know. Thank you. The {{ site_name }} team. {% endautoescape %} </code></pre> <p>Thanks, guys.</p>
1
2016-09-16T19:46:43Z
39,539,379
<p>I’d suggest to borrow the general logic from Django and adapt it to your specific conditions:</p> <ul> <li><a href="https://github.com/django/django/blob/master/django/contrib/auth/tokens.py" rel="nofollow"><strong><code>PasswordResetTokenGenerator</code> code</strong></a> — pretty well-documented, very useful</li> <li><a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.views.password_reset" rel="nofollow">password reset docs</a> (probably known information, though)</li> <li><a href="https://github.com/django/django/blob/master/django/contrib/auth/views.py#L378" rel="nofollow">password reset view implementation</a></li> </ul> <p>As you can see from <code>PasswordResetTokenGenerator._make_token_with_timestamp()</code>, its algo relies on user’s last login timestamp, so the APIs you consume would need to accommodate that.</p> <p>You could import the same utility functions used by the above—where cryptography is concerned it’s better to rely on well-tested solutions. Deep internals are prone to change without a release note though when you update to newer Django versions, so take care.</p> <p>You could also look into simply storing some carefully randomly generated reset codes along with usernames in your local DB and deleting them when user accesses the reset form, but that is less elegant while being more brittle and infosec-issue prone.</p>
1
2016-09-16T20:09:52Z
[ "python", "django", "django-forms" ]
Django Password Resest Via Email
39,539,102
<p>I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. </p> <p>I took by example <a href="http://stackoverflow.com/questions/18928144/django-user-registration-password-reset-via-email">this question</a> and <a href="http://ruddra.com/2015/09/18/implementation-of-forgot-reset-password-feature-in-django/" rel="nofollow">this site</a>.</p> <p>But my problem is a bit different. I don't have a local database containing the users, so I cannot perform operations over their attributes. I receive user data via an API (user id, user email, user password).</p> <p>So, which is the best way to <strong>generate a unique link</strong> to send via email to user so that this link would <strong>tell me who the user is</strong> and allow me to <strong>reset his/her password</strong>? And also, how could I redirect it in <strong>urls.py</strong>? I wish that this link could be used only a single time.</p> <p>My views.py is like this:</p> <pre><code>def password_reset_form(request): if request.method == 'GET': form = PasswordResetForm() else: form = PasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] content_dict = { 'email': email, 'domain': temp_data.DOMAIN, 'site_name': temp_data.SITE_NAME, 'protocol': temp_data.PROTOCOL, } subject = content_dict.get('site_name')+ ' - Password Reset' content = render_to_string('portal/password_reset_email.html', content_dict) send_mail(subject, content, temp_data.FIBRE_CONTACT_EMAIL, [email]) return render(request, 'portal/password_reset_done.html', {'form': form,}) return render(request, 'portal/password_reset_form.html', {'form': form,}) </code></pre> <p>And the template the e-mail I'm sending is:</p> <pre><code>{% autoescape off %} You're receiving this e-mail because we got a request to reset the password for your user account at {{ site_name }}. Please go to the following page and choose a new password: {% block reset_link %} {{ protocol }}://{{ domain }}/[***some unique link***] {% endblock %} If you didn't request a password reset, let us know. Thank you. The {{ site_name }} team. {% endautoescape %} </code></pre> <p>Thanks, guys.</p>
1
2016-09-16T19:46:43Z
39,539,861
<p>The problem is not to generate unique link, you need to store somewhere info about user id or email, and generated token. Otherwise you will not know which user should use which token. After user resets his password you can delete his record (his token). </p> <p>You can write the most simple model even in sqlite, which basically could look like this:</p> <pre><code>class UserTokens(model.Models): email = models.EmailField(max_length=50) token = models.CharField(max_length=50) </code></pre> <p>Afterwards when you send mail make something like this:</p> <pre><code>def password_reset_form(request): #your logic here # form post usr, created = UserToken.objects.get_or_create(email=form.email) if usr.token: #send this token to him else: usr.token = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(50)) usr.save() #also send this token to him </code></pre> <p>Then you create a new view or api view which searches for that token, if found, let him reset the password. If not, raise a 404 error, or just let him know that there is no such link to reset password.</p> <p>Please not that, this was written from my phone so care for typos. </p> <p>PS. you also asked about urls</p> <p>just make something like this:</p> <pre><code>url(r'unsubscribe/(?P&lt;quit_hash&gt;[\w\d]+)/$', 'quit_newsletter_or_somethin', name='quit_newsletter_or_somethin') </code></pre>
1
2016-09-16T20:47:30Z
[ "python", "django", "django-forms" ]
Django Password Resest Via Email
39,539,102
<p>I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. </p> <p>I took by example <a href="http://stackoverflow.com/questions/18928144/django-user-registration-password-reset-via-email">this question</a> and <a href="http://ruddra.com/2015/09/18/implementation-of-forgot-reset-password-feature-in-django/" rel="nofollow">this site</a>.</p> <p>But my problem is a bit different. I don't have a local database containing the users, so I cannot perform operations over their attributes. I receive user data via an API (user id, user email, user password).</p> <p>So, which is the best way to <strong>generate a unique link</strong> to send via email to user so that this link would <strong>tell me who the user is</strong> and allow me to <strong>reset his/her password</strong>? And also, how could I redirect it in <strong>urls.py</strong>? I wish that this link could be used only a single time.</p> <p>My views.py is like this:</p> <pre><code>def password_reset_form(request): if request.method == 'GET': form = PasswordResetForm() else: form = PasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] content_dict = { 'email': email, 'domain': temp_data.DOMAIN, 'site_name': temp_data.SITE_NAME, 'protocol': temp_data.PROTOCOL, } subject = content_dict.get('site_name')+ ' - Password Reset' content = render_to_string('portal/password_reset_email.html', content_dict) send_mail(subject, content, temp_data.FIBRE_CONTACT_EMAIL, [email]) return render(request, 'portal/password_reset_done.html', {'form': form,}) return render(request, 'portal/password_reset_form.html', {'form': form,}) </code></pre> <p>And the template the e-mail I'm sending is:</p> <pre><code>{% autoescape off %} You're receiving this e-mail because we got a request to reset the password for your user account at {{ site_name }}. Please go to the following page and choose a new password: {% block reset_link %} {{ protocol }}://{{ domain }}/[***some unique link***] {% endblock %} If you didn't request a password reset, let us know. Thank you. The {{ site_name }} team. {% endautoescape %} </code></pre> <p>Thanks, guys.</p>
1
2016-09-16T19:46:43Z
39,540,032
<p><strong>Don't reinvent the wheel.</strong> You should use <a href="https://github.com/pennersr/django-allauth" rel="nofollow">django-allauth</a> for this kind of stuff. The library is well maintained and under active development.</p>
0
2016-09-16T21:02:32Z
[ "python", "django", "django-forms" ]
Separating/accessing a triple tuple list like [[[x,y],z],p]?
39,539,142
<p>I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, &amp; p from each tuple. How would I do that? </p> <pre><code>MovesList = [ [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2] ] </code></pre>
0
2016-09-16T19:49:48Z
39,539,182
<p>You can unpack tuples as you iterate over them:</p> <p>Python 2:</p> <pre><code>&gt;&gt;&gt; for ((x,y),z),p in MovesList: ... print x, y, z, p </code></pre> <p>Python 3:</p> <pre><code>&gt;&gt;&gt; for ((x,y),z),p in MovesList: ... print(x,y,z,p) </code></pre> <p>Both of which result in:</p> <pre><code>1 2 3 1 2 5 3 1 1 3 0 2 </code></pre>
3
2016-09-16T19:52:54Z
[ "python" ]
Separating/accessing a triple tuple list like [[[x,y],z],p]?
39,539,142
<p>I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, &amp; p from each tuple. How would I do that? </p> <pre><code>MovesList = [ [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2] ] </code></pre>
0
2016-09-16T19:49:48Z
39,539,275
<p>same unpacking with list comprehension</p> <pre><code>In [202]: [[x,y,z,p] for ([[x,y],z],p) in MovesList] Out[202]: [[1, 2, 3, 1], [2, 5, 3, 1], [1, 3, 0, 2]] </code></pre>
0
2016-09-16T20:00:20Z
[ "python" ]
Separating/accessing a triple tuple list like [[[x,y],z],p]?
39,539,142
<p>I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, &amp; p from each tuple. How would I do that? </p> <pre><code>MovesList = [ [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2] ] </code></pre>
0
2016-09-16T19:49:48Z
39,819,791
<p>I also found you can unpack a list of tuples that doesn't have a finite space by putting it through a while loop like so:</p> <pre><code>Mylist = list() MyOtherList = list() //list is packed my tuples of four {(a,b,c,d),(a,b,c,d),(a,b,c,d),...} While MyList[0] != Null: var w = MyList[0][0] var x = MyList[0][1] var y = MyList[0][2] var z = MyList[0][3] MyList.Remove(w,x,y,z) //do something with w,x,y,z based upon use MyOtherList = getMoreListItems(w,x,y,z) MyList.extend(MyOtherList) </code></pre> <p>This can be used when the list you would like to iterate through is full of tuples of all the same size </p>
0
2016-10-02T17:41:34Z
[ "python" ]
pd.rolling_max and min with groupby or similar
39,539,151
<p>Using the following code I am able to capture the rolling high and low of my data in the <code>H1_high</code>and <code>H1_low</code> columns. </p> <pre><code>data["H1_high"] = pd.rolling_max(data.High, window=60, min_periods=1) data["H1_low"] = pd.rolling_min(data.Low, window=60, min_periods=1) </code></pre> <p>This gives the following output:</p> <pre><code> Open High Low Last Volume H1_high H1_low Timestamp 2014-03-04 09:30:00 1783.50 1784.50 1783.50 1784.50 171 1784.50 1783.5 2014-03-04 09:31:00 1784.75 1785.75 1784.50 1785.25 28 1785.75 1783.5 2014-03-04 09:32:00 1785.00 1786.50 1785.00 1786.50 81 1786.50 1783.5 2014-03-04 09:33:00 1786.00 1786.00 1785.25 1785.25 41 1786.50 1783.5 2014-03-04 09:34:00 1785.00 1785.25 1784.75 1785.25 11 1786.50 1783.5 2014-03-04 09:35:00 1785.50 1786.75 1785.50 1785.75 49 1786.75 1783.5 2014-03-04 09:36:00 1786.00 1786.00 1785.25 1785.75 12 1786.75 1783.5 2014-03-04 09:37:00 1786.00 1786.25 1785.25 1785.25 15 1786.75 1783.5 </code></pre> <p>What I would like to do is only capture the <code>H1_high</code>and <code>H1_low</code> between the following times:</p> <pre><code>daystart = '9:30' IB_end = '10:29:59' IB_session = data.between_time(daystart,IB_end, include_start=True, include_end=True) </code></pre> <p>and do this on a daily basis showing the <code>H1_high</code>and <code>H1_low</code> then carrying forward (FFill) the last value from <code>IB_end = '10:29:59'</code> to the end of the day (16:14:00).</p> <p>So here is desired output for <code>H1_high</code> <code>H1_low</code> columns: </p> <pre><code> H1_high H1_low 2014-03-04 10:29:00 1786.75 1783.5 2014-03-04 10:30:00 1786.75 1783.5 2014-03-04 10:31:00 1786.75 1783.5 </code></pre> <p>final value from <code>10:29:59</code> fills forward until end of day:</p> <pre><code> H1_high H1_low 2014-03-04 16:14:00 1786.75 1783.5 </code></pre> <p>then new day starts again with fresh values:</p> <pre><code> H1_high H1_low 2014-03-05 09:30:00 1788.00 1783.00 </code></pre>
2
2016-09-16T19:50:29Z
39,539,484
<p>use <code>datetime.time</code> and filter your index</p> <pre><code>import datetime high_low_xt = lambda df: pd.concat([df.High.cummax(), df.Low.cummin()], axis=1) tidx = pd.date_range('2016-09-14', '2016-09-16', freq='T') start = datetime.time(9, 30) end = datetime.time(10, 30) eod = datetime.time(18, 14) bidx = tidx[(tidx.time &gt;= start) &amp; (tidx.time &lt; end)] didx = tidx[(tidx.time &gt;= start) &amp; (tidx.time &lt;= eod)] df = pd.DataFrame(np.random.rand(len(tidx), 2), tidx, ['High', 'Low']) df1 = df.ix[bidx].groupby(pd.TimeGrouper('D')).apply(high_low_xt) df1.reindex(didx, method='ffill') </code></pre> <p><a href="http://i.stack.imgur.com/eyQk7.png" rel="nofollow"><img src="http://i.stack.imgur.com/eyQk7.png" alt="enter image description here"></a></p>
0
2016-09-16T20:16:38Z
[ "python", "pandas" ]
How to create an rray of composites strings
39,539,230
<p>Hi everyone: I have a collection of 50 strings that represent comments in a text file where each line represents a separate comment with different sentences . </p> <p>Each string is a user review of a product, and each string or review has several several sentences. </p> <p>How could I to create an array with these strings using Python?</p> <p>Example of reviews: Review 1. "I was disapointed with the product. The quality was reality bad and the price was not fair. Never in my life I'll buy again this brand.</p> <p>Review 2. "I'm really happy with this product. It's all what i desired. Thanks brand J" .... and so far.</p> <p>Desired Results: </p> <ol> <li><p>[('disappointed', 'product'), ('quality', 'really', 'bad', 'price', 'fair')] </p></li> <li><p>[('happy', 'product'), ('all', 'desired'), ('thanks', 'brand')] </p></li> <li>... </li> </ol> <p>I want each processed comment in a separate line to save it in a csv file</p>
1
2016-09-16T19:56:22Z
39,540,860
<p>One of my first projects was similar to this. I believe your asking for help in getting the text file lines as an array.</p> <p>To open the file for reading: </p> <p><code>file = open("/path/to/file", "r")</code></p> <p>I would then split on spaces so: </p> <pre><code>for line in file: print line.split(' ') </code></pre> <p>this would give you an array of words from each line in the txt file. Then use the <code>csv</code> module in python to input into a csv file. </p> <p>References: </p> <ul> <li><p><a href="http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python" rel="nofollow">Python the Hard Way - Opening and Closting Files</a></p></li> <li><p><a href="https://www.dotnetperls.com/split-python" rel="nofollow">split() function</a></p></li> <li><p><a href="http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/" rel="nofollow">CSV Module</a></p></li> </ul>
0
2016-09-16T22:19:11Z
[ "python", "arrays", "string" ]
Python for loop over two lists for all the pairs
39,539,287
<p>I have a dataframe with date, id - I need to pull out each date and id combination and create a new dataframe.</p> <pre><code> date id 2016-05-13 abc 2016-05-13 pqr 2016-05-14 abc 2016-05-14 pqr ids = list(sorted(set(df['id']))) Out: ['abc','pqr'] dates = list(sorted(set(df[df.id == ids[i]]['date']))) Out: ['2016-05-13','2016-05-14'] for i in range(0,len(ids)): df2 = df[(df.date == dates[i]) &amp; (df.id == id[i])] </code></pre> <p>The above code is resulting the output (<code>df2</code>) for relative index values only (First date, First Id &amp; Second date, Second Id), but I need the output for all the pairs. Please let me know what to change in the loop?</p>
2
2016-09-16T20:01:11Z
39,539,342
<p>to get all the pairs <code>ids</code> vs. <code>dates</code>, you could use <code>itertools</code> as</p> <pre><code>import itertools for iid, ddate in itertools.product(ids, dates): df2 = df[(df.date == ddate) &amp; (df.id == iid)] </code></pre>
-2
2016-09-16T20:06:42Z
[ "python", "pandas", "for-loop", "iteration" ]
Python for loop over two lists for all the pairs
39,539,287
<p>I have a dataframe with date, id - I need to pull out each date and id combination and create a new dataframe.</p> <pre><code> date id 2016-05-13 abc 2016-05-13 pqr 2016-05-14 abc 2016-05-14 pqr ids = list(sorted(set(df['id']))) Out: ['abc','pqr'] dates = list(sorted(set(df[df.id == ids[i]]['date']))) Out: ['2016-05-13','2016-05-14'] for i in range(0,len(ids)): df2 = df[(df.date == dates[i]) &amp; (df.id == id[i])] </code></pre> <p>The above code is resulting the output (<code>df2</code>) for relative index values only (First date, First Id &amp; Second date, Second Id), but I need the output for all the pairs. Please let me know what to change in the loop?</p>
2
2016-09-16T20:01:11Z
39,540,243
<p>Create a new dataframe with each <code>id</code> in columns and each <code>date</code> in rows. You can fill it in later.</p> <pre><code>pd.DataFrame([], set(df.date), set(df.id)) </code></pre> <p><a href="http://i.stack.imgur.com/ig5Xe.png" rel="nofollow"><img src="http://i.stack.imgur.com/ig5Xe.png" alt="enter image description here"></a></p> <hr> <p>if you just want the list of combinations</p> <pre><code>pd.MultiIndex.from_product([set(df.id), set(df.date)]).tolist() [('pqr', '2016-05-14'), ('pqr', '2016-05-13'), ('abc', '2016-05-14'), ('abc', '2016-05-13')] </code></pre>
0
2016-09-16T21:20:32Z
[ "python", "pandas", "for-loop", "iteration" ]
Specialized @property decorators in python
39,539,292
<p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</p> <pre><code>class Junk(object): def __init__(self, var): self._var = var @property def var(self): """A numeric variable""" return self._var @var.setter def size(self, value): # need to make sure var is an integer if not isinstance(value, int): raise ValueError("var must be an integer, var = {}".format(value)) self._var = value @var.deleter def size(self): raise RuntimeError("You can't delete var") </code></pre> <p>It seems to me that it should be possible to write a decorator that does everything so that the above can be transformed into:</p> <pre><code>def numeric_property(*args, **kwargs): ... class Junk(object): def __init__(self, var): self._var = var @numeric_property def var(self): """A numeric variable""" return self._var </code></pre> <p>That way the new <code>numeric_property</code> decorator can be used in many classes.</p>
4
2016-09-16T20:01:31Z
39,539,523
<p>A <code>@property</code> is just a special case of Python's <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptor protocol</a>, so you can certainly build your own custom versions. For your case:</p> <pre><code>class NumericProperty: """A property that must be numeric. Args: attr (str): The name of the backing attribute. """ def __init__(self, attr): self.attr = attr def __get__(self, obj, type=None): return getattr(obj, self.attr) def __set__(self, obj, value): if not isinstance(value, int): raise ValueError("{} must be an integer, var = {!r}".format(self.attr, value)) setattr(obj, self.attr, value) def __delete__(self, obj): raise RuntimeError("You can't delete {}".format(self.attr)) class Junk: var = NumericProperty('_var') def __init__(self, var): self.var = var </code></pre> <p>In use:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; j = Junk('hi') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/jonrsharpe/test.py", line 29, in __init__ self.var = var File "/Users/jonrsharpe/test.py", line 17, in __set__ raise ValueError("{} must be an integer, var = {!r}".format(self.attr, value)) ValueError: _var must be an integer, var = 'hi' &gt;&gt;&gt; j = Junk(1) &gt;&gt;&gt; del j.var Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/jonrsharpe/test.py", line 21, in __delete__ raise RuntimeError("You can't delete {}".format(self.attr)) RuntimeError: You can't delete _var &gt;&gt;&gt; j.var = 'hello' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/jonrsharpe/test.py", line 17, in __set__ raise ValueError("{} must be an integer, var = {!r}".format(self.attr, value)) ValueError: _var must be an integer, var = 'hello' &gt;&gt;&gt; j.var = 2 &gt;&gt;&gt; j.var 2 </code></pre>
2
2016-09-16T20:19:03Z
[ "python", "python-3.x", "decorator", "python-decorators" ]
Specialized @property decorators in python
39,539,292
<p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</p> <pre><code>class Junk(object): def __init__(self, var): self._var = var @property def var(self): """A numeric variable""" return self._var @var.setter def size(self, value): # need to make sure var is an integer if not isinstance(value, int): raise ValueError("var must be an integer, var = {}".format(value)) self._var = value @var.deleter def size(self): raise RuntimeError("You can't delete var") </code></pre> <p>It seems to me that it should be possible to write a decorator that does everything so that the above can be transformed into:</p> <pre><code>def numeric_property(*args, **kwargs): ... class Junk(object): def __init__(self, var): self._var = var @numeric_property def var(self): """A numeric variable""" return self._var </code></pre> <p>That way the new <code>numeric_property</code> decorator can be used in many classes.</p>
4
2016-09-16T20:01:31Z
39,539,588
<p>You may just create a function that does it for you . As simple as it can get, no need to create a custom descriptor:</p> <pre><code>def numprop(name, privname): @property def _numprop(self): return getattr(self, privname) @_numprop.setter def _numprop(self, value): if not isinstance(value, int): raise ValueError("{name} must be an integer, {name} = {}".format(value, name=name)) setattr(self, privname, value) @_numprop.deleter def _numprop(self): raise RuntimeError("You can't delete var") return _numprop class Junk(object): def __init__(self, var): self._var = var var = numprop("var", "_var") </code></pre>
0
2016-09-16T20:23:48Z
[ "python", "python-3.x", "decorator", "python-decorators" ]
Specialized @property decorators in python
39,539,292
<p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</p> <pre><code>class Junk(object): def __init__(self, var): self._var = var @property def var(self): """A numeric variable""" return self._var @var.setter def size(self, value): # need to make sure var is an integer if not isinstance(value, int): raise ValueError("var must be an integer, var = {}".format(value)) self._var = value @var.deleter def size(self): raise RuntimeError("You can't delete var") </code></pre> <p>It seems to me that it should be possible to write a decorator that does everything so that the above can be transformed into:</p> <pre><code>def numeric_property(*args, **kwargs): ... class Junk(object): def __init__(self, var): self._var = var @numeric_property def var(self): """A numeric variable""" return self._var </code></pre> <p>That way the new <code>numeric_property</code> decorator can be used in many classes.</p>
4
2016-09-16T20:01:31Z
39,539,771
<h2>Option 1: inherit from <code>property</code></h2> <p><code>property</code> is a descriptor. See <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">Descriptor HowTo on python.org</a>.</p> <p>So, can inherit from <code>property</code> and override the relevant methods.</p> <p>For example, to enforce int on setter:</p> <pre><code>class numeric_property(property): def __set__(self, obj, value): assert isinstance(value, int), "numeric_property requires an int" super(numeric_property, self).__set__(obj, value) class A(object): @numeric_property def x(self): return self._x @x.setter def x(self, value): self._x = value </code></pre> <p>And now you have integers enforced:</p> <pre><code>&gt;&gt;&gt; a = A() &gt;&gt;&gt; a.x = 'aaa' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in __set__ AssertionError: numeric_property requires an int </code></pre> <hr> <h2>Option 2: Create a better descriptor</h2> <p>On the other hand, it may be even better to implement a brand new descriptor which does not inherit from property, which would enable you to define the property in one go.</p> <p>It would be nicer to have this kind of interface:</p> <pre><code>class A(object): x = numeric_property('_x') </code></pre> <p>For that you would implement a descriptor which takes the attribute name:</p> <pre><code>class numeric_property(object): def __init__(self, private_attribute_name, default=0): self.private_attribute_name = private_attribute_name self.default = default def __get__(self, obj, typ): if not obj: return self return getattr(obj, self.private_attribute_name, self.default) def __set__(self, obj, value): assert isinstance(value, int), "numeric_property requires an int" setattr(obj, self.private_attribute_name, value) </code></pre> <hr> <p><strong>Disclaimer :)</strong></p> <p>I would rather not enforce strict typing in Pyhon, because Python is much more powerful without it.</p>
1
2016-09-16T20:39:52Z
[ "python", "python-3.x", "decorator", "python-decorators" ]
Use variables as keywords for functions with pre-defined keywords (Python)
39,539,316
<p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword. This can easily be done a different way, but I figured it'd be useful to know how to replace pre-set keywords.</p> <p>The datetime object has a .replace() method that takes any time value as a keyword:</p> <blockquote> <p>datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])</p> </blockquote> <p>But I want to allow the user to specify how much of which kind of time (e.g., 2 days; 4 hours; 1 month).</p> <p>I'm trying to replace any of the above keywords up to "minute" with whatever the user inputs, which is stored in the <em>time_type</em> variable, but I get "<strong>TypeError: 'time_type' is an invalid keyword argument for this function</strong>".</p> <pre><code> start_time = datetime.datetime(2016, 09, 16, 15, 30) def change_time(integer, time_string): time_type = time_string.replace("s","") # de-pluralizes input new_time = getattr(start_time, time_type) + integer print(start_time.replace(time_type=new_time)) change_time(2, "days") </code></pre> <p>This should print the new start_time, which is (2016, 09, 18, 15, 30), but I just get an error.</p>
0
2016-09-16T20:04:10Z
39,539,444
<p>Python allows you to store data in a dictionary and finally unpack them as keyword arguments to different functions.</p> <p>For the thing that you want to do, best way to accomplish this is to use kwargs.</p> <pre><code>replacement_info = {'day': 2, 'month': 9, ...} new_time = start_time.replace(**replacement_info) </code></pre> <p>Note the difference with what you've done. Passing <code>time_type</code> directly to <code>replace</code>, would result in <code>replace</code> being called with the <code>time_type</code> parameter, set to 2, which is undefined (since it's not in the list of accepted arguments for replace)</p> <p>Instead you have to pass it like <code>**{time_type: 2}</code> to the replace function, this way, replace will receive the interpreted value for time_type, namely day, as the input.</p> <p>So you need to change </p> <pre><code>print(start_time.replace(time_type=new_time)) </code></pre> <p>to </p> <pre><code>print(start_time.replace(**{time_type:new_time}) </code></pre>
0
2016-09-16T20:14:16Z
[ "python", "datetime" ]
Use variables as keywords for functions with pre-defined keywords (Python)
39,539,316
<p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword. This can easily be done a different way, but I figured it'd be useful to know how to replace pre-set keywords.</p> <p>The datetime object has a .replace() method that takes any time value as a keyword:</p> <blockquote> <p>datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])</p> </blockquote> <p>But I want to allow the user to specify how much of which kind of time (e.g., 2 days; 4 hours; 1 month).</p> <p>I'm trying to replace any of the above keywords up to "minute" with whatever the user inputs, which is stored in the <em>time_type</em> variable, but I get "<strong>TypeError: 'time_type' is an invalid keyword argument for this function</strong>".</p> <pre><code> start_time = datetime.datetime(2016, 09, 16, 15, 30) def change_time(integer, time_string): time_type = time_string.replace("s","") # de-pluralizes input new_time = getattr(start_time, time_type) + integer print(start_time.replace(time_type=new_time)) change_time(2, "days") </code></pre> <p>This should print the new start_time, which is (2016, 09, 18, 15, 30), but I just get an error.</p>
0
2016-09-16T20:04:10Z
39,539,449
<p>You cannot replace keyword arguments on a function you did not write. When calling a function like:</p> <pre><code>f(a=b) </code></pre> <p>The value of <code>a</code> is not sent as an argument to <code>f</code>. Instead, the value of <code>b</code> is sent and that value is set to the argument <code>a</code> in <code>f's</code> argument list definition. If <code>f</code> does not have an argument <code>a</code> defined (as <code>datetime.replace</code> does not have a <code>time_type</code> argument defined), you will get an <code>invalid keyword argument</code> exception.</p> <p>As others have said, to pass dynamic keyword arguments to a function use the <code>**kwargs</code> notation.</p>
1
2016-09-16T20:14:27Z
[ "python", "datetime" ]
Use variables as keywords for functions with pre-defined keywords (Python)
39,539,316
<p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword. This can easily be done a different way, but I figured it'd be useful to know how to replace pre-set keywords.</p> <p>The datetime object has a .replace() method that takes any time value as a keyword:</p> <blockquote> <p>datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])</p> </blockquote> <p>But I want to allow the user to specify how much of which kind of time (e.g., 2 days; 4 hours; 1 month).</p> <p>I'm trying to replace any of the above keywords up to "minute" with whatever the user inputs, which is stored in the <em>time_type</em> variable, but I get "<strong>TypeError: 'time_type' is an invalid keyword argument for this function</strong>".</p> <pre><code> start_time = datetime.datetime(2016, 09, 16, 15, 30) def change_time(integer, time_string): time_type = time_string.replace("s","") # de-pluralizes input new_time = getattr(start_time, time_type) + integer print(start_time.replace(time_type=new_time)) change_time(2, "days") </code></pre> <p>This should print the new start_time, which is (2016, 09, 18, 15, 30), but I just get an error.</p>
0
2016-09-16T20:04:10Z
39,539,465
<p>Change your last line to something like this:</p> <pre><code>year = start_time.year month = start_time.month day = start_time.day hour = start_time.hour minute = start_time.minute second = start_time.second microsecond = start_time.microsecond exec(time_type + '='+str(new_time)) print(start_time.replace(year, month, day, hour, minute, second, microsecond) </code></pre>
0
2016-09-16T20:15:42Z
[ "python", "datetime" ]
python socket server and java android socket - freezes app
39,539,356
<p>I'm making a python server running on my computer and java socket client running on my phone. the minute the java tries to connect, the app freezes. Not saying anything in the logcat. I have no idea why...</p> <p>python 3.5.1:</p> <pre><code>PORT = 8888 import socket sock = socket.socket() sock.bind(("0.0.0.0", PORT)) sock.listen(1) client = None while not client: try: client = sock.accept() except: pass print(client[1]) </code></pre> <p>java:</p> <pre><code>static String get_leaderboard() { Socket sock; OutputStream out; InputStream in; try { System.out.println("now trying to connect"); sock = new Socket("192.168.1.29", 8888); System.out.println("connected successfuly"); out = sock.getOutputStream(); in = sock.getInputStream(); return Integer.toString(in.read()); } catch (IOException e) { e.printStackTrace(); } return "Error in connection"; </code></pre> <p>but actually, logcat never prints "connected successfuly". just "trying to connect".</p>
0
2016-09-16T20:08:23Z
39,539,885
<p>This line is wrong:</p> <pre><code>client = sock.connect() </code></pre> <p>Servers don't call <code>connect()</code>. Servers call <code>listen()</code> and <code>accept()</code>. Only clients call <code>connect()</code>.</p> <p>Since your server calls <code>bind()</code> and <code>listen()</code>, but not <code>accept()</code>, any client will hang trying to connect to it.</p> <p>Resources:</p> <ul> <li><a href="https://wiki.python.org/moin/TcpCommunication" rel="nofollow">https://wiki.python.org/moin/TcpCommunication</a></li> <li><a href="https://docs.python.org/3/howto/sockets.html" rel="nofollow">https://docs.python.org/3/howto/sockets.html</a></li> <li><a href="http://beej.us/guide/bgnet/" rel="nofollow">http://beej.us/guide/bgnet/</a></li> </ul>
0
2016-09-16T20:49:42Z
[ "java", "android", "python", "sockets" ]
Python Split data into multiple files with a rule
39,539,358
<p>I need some idea to solve my problem in python to split a file.</p> <p>I more than 1.000.000 rows in a file with 2 columns: "accountid" and a "property". One "accountid" can have multiple properties, but each property is one row. Looks something like this: <a href="http://i.stack.imgur.com/d2aVJ.png" rel="nofollow">Example</a></p> <p>I need to split this data into 50.000 rows per file (which is not an issue). However, I one file also only allows 50 "properties" per "accountid". And a lot have more than 50 properties.</p> <p>Do you have any <strong>idea</strong> how to technically solve this best? I do not require any code ;)</p> <p>Thanks</p> <p>Flo</p>
0
2016-09-16T20:08:32Z
39,561,775
<p>Here is one solution that comes to my mind:</p> <p>First you have to determine how many partitions you will need, based on two parameters X and Y. X is determined by the accountid with the maximum number of properties. Let's assume accountid=7 has the maximum number of properties equal to 270 properties. That means you will need at least 6 partitions to ensure a solution exists where none of the partitions will have more than 50 of the acountid=7 rows (based on pigeonhole principle). Y is determined by the total number of rows you have and how big each partition is (in your example Y is 1000,000/50,000 = 20). We take the maximum of X and Y as the number of partitions we need. In this scenario: Number of Partitions = max(6, 20) = 20.</p> <p>Now, you sort the entire table using accountid. Let's assume we know the row number for each row. We will then define Partition k as:</p> <pre><code>P_k = {row | row_number % 20 = k} </code></pre> <p>That should satisfy both of your requirements.</p> <p>Note that if max(X, Y) = X, you will have to allow some partitions with less than 50K rows. Otherwise there is no solution to this problem.</p>
0
2016-09-18T19:29:25Z
[ "python", "split" ]
Tkinter intvar causing process to live on
39,539,462
<p>I realize there are many <a href="http://stackoverflow.com/questions/110923/close-a-tkinter-window">examples</a> of how to properly close a Tkinter GUI by calling the root.destroy() function. They work with my setup except I've determined that including a variable of type tkinter.intvar causes the gui process to live on even after I close the window. Here's a working example:</p> <pre><code>import mtTkinter as Tkinter #special threadsafe version of Tkinter module, required for message windows. You can use regular Tkinter if needed root = Tkinter.Tk() root.wm_title("KillmePlz") nexusvar = Tkinter.IntVar() def ClosebyX(): root.destroy() closebutton = Tkinter.Button(root,text='Quit',command=ClosebyX) closebutton.pack() root.protocol('WM_DELETE_WINDOW', ClosebyX) root.mainloop() </code></pre> <p>On my machine if I remove the creation of "nexusvar", the Tkinter.IntVar, when I close the GUI the process also stops. If this variable is included as shown above, I see the process linger after the gui is closed. I don't think mtTkinter makes any difference.</p> <p>Does anyone know why this might be happening?</p> <p>Windows 7 64 bit, Python 2.7.12</p> <p>UPDATE 9/20/16: mtTkinter is the source of this problem. The solution below is for regular Tkinter module use. For solving this problem using mtTkinter see the following <a href="http://stackoverflow.com/questions/14073463/mttkinter-doesnt-terminate-threads">post</a> </p>
0
2016-09-16T20:15:30Z
39,540,567
<p><code>nexusvar</code> isn't a child of <code>root</code>, so when you destroy <code>root</code> it doesn't know to destroy <code>nexusvar</code> as well - the two things are separate. You can set an <code>IntVar</code> to have <code>root</code> as a parent by supplying <code>root</code> to the constructor. <code>nexusvar</code> should then be able to destroy itself when <code>root</code> dies.</p>
1
2016-09-16T21:50:04Z
[ "python", "tkinter", "process" ]
How to sharex and sharey axis in for loop
39,539,476
<p>I'm trying to share the x-axis and y-axis of my sumplots, I've tried using the sharey and sharex several different ways but haven't gotten the correct result.</p> <pre><code>ax0 = plt.subplot(4,1,1) for i in range(4): plt.subplot(4,1,i+1,sharex = ax0) plt.plot(wavelength[i],flux) plt.xlim([-1000,1000]) plt.ylim([0,1.5]) plt.subplots_adjust(wspace=0, hspace=0) plt.show() </code></pre>
0
2016-09-16T20:16:15Z
39,539,785
<p>If I understood you correctly, want to have four stacked plots, sharing the x-axis and the y-axis. This you can do with <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots" rel="nofollow">plt.subplots</a> and the keywords <code>sharex=True</code> and <code>sharey=True</code>. See example below:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig, axlist = plt.subplots(4, 1, sharex=True, sharey=True) for ax in axlist: ax.plot(np.random.random(100)) plt.show() </code></pre>
0
2016-09-16T20:40:41Z
[ "python", "matplotlib" ]
Control robot by using keyboard
39,539,561
<p>I am new to Python and raspberry pi, I have created a wheeled robot and codes for forwards, backward, turn left and turn right! However every time I want to execute a differant script I have to open a new code and run it(eg open the file for forwards, then open the file for left etc etc.) </p> <p>How do I use the the keyboard arrows to execute parts of the script? </p> <p>I want to be able to press the up button and the robot move forward, then release the up button and the robot stop, then press the left arrow key and the robot turn left until I release the key etc.</p> <p>Iv tried tons of forums and threads but they all relate to differant codes (iv found how to use keyboard events for turtle but they don't work on i2c or gpio)</p> <p>Can anybody help me I bet there's a real simple command code but I don't know what it is or where to find it! </p> <p>I'm using adafruit motor hat with raspberry pi to power the motors if this makes a difference </p>
0
2016-09-16T20:21:51Z
39,551,299
<p>You only need one file for this. Make a new file.</p> <p>You will need a infinite loop, I will suggest using a <code>while(true)</code> loop. You then need</p> <pre><code>if(/*key was UP ARROW*/){ /*CODE TO MAKE MOVE FORWARD HERE*/ }else if(/*KEY WAS DOWN ARROW*/{ /*CODE TO MAKE MOVE DOWN HERE*/ } etc... </code></pre> <p>inside of that <code>while(true)</code> loop. This way, you will be able to use ONE file to capture all keyboard data. So, it would look something similar to this</p> <pre><code>while(true){ //read key input if(/*key was UP ARROW*/){ /*CODE TO MAKE MOVE FORWARD HERE*/ }else if(/*KEY WAS DOWN ARROW*/{ /*CODE TO MAKE MOVE DOWN HERE*/ } etc... } </code></pre> <p>This should do what you need. You already said you have the code to move it, so this shouldn't take long to transfer over.</p> <p>Try reading more about it here <a href="https://learn.pimoroni.com/tutorial/robots/controlling-your-robot-wireless-keyboard" rel="nofollow">https://learn.pimoroni.com/tutorial/robots/controlling-your-robot-wireless-keyboard</a> This should help you immensely</p>
0
2016-09-17T20:17:09Z
[ "python", "keyboard", "raspberry-pi", "control", "keyboard-events" ]
Are for-loop name list expressions legal?
39,539,606
<p>In CPython 2.7.10 and 3.4.3, and PyPy 2.6.0 (Python 2.7.9), it is apparently legal to use expressions (or some subset of them) for the name list in a for-loop. Here's a typical for-loop:</p> <pre><code>&gt;&gt;&gt; for a in [1]: pass ... &gt;&gt;&gt; a 1 </code></pre> <p>But you can also use attributes from objects:</p> <pre><code>&gt;&gt;&gt; class Obj(object): pass ... &gt;&gt;&gt; obj = Obj() &gt;&gt;&gt; for obj.b in [1]: pass ... &gt;&gt;&gt; obj.b 1 </code></pre> <p>And you can even use attributes from expressions:</p> <pre><code>&gt;&gt;&gt; for Obj().c in [1]: pass ... </code></pre> <p>But not all expressions appear to work:</p> <pre><code>&gt;&gt;&gt; for (True and obj.d) in [1]: pass ... File "&lt;stdin&gt;", line 1 SyntaxError: can't assign to operator </code></pre> <p>But they do so long as the attribute is on the outside?</p> <pre><code>&gt;&gt;&gt; for (True and obj).e in [1]: pass ... &gt;&gt;&gt; obj.e 1 </code></pre> <p>Or something is assignable?</p> <pre><code>&gt;&gt;&gt; for {}['f'] in [1]: pass ... </code></pre> <p>I'm surprised any of these are legal syntax in Python. I expected only names to be allowed. Are these even supposed to work? Is this an oversight? Is this an implementation detail of CPython that PyPy happens to also implement?</p>
3
2016-09-16T20:25:32Z
39,539,675
<p>As <a href="https://docs.python.org/3/reference/compound_stmts.html#the-for-statement" rel="nofollow">documented</a>, the "variable" in the <code>for</code> syntax can be any <code>target_list</code>, which, as <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-target_list" rel="nofollow">also documented</a> means anything that can be on the left-hand side of an assignment statement. You obviously can't use something like <code>(True and obj.d)</code>, because there's no way to assign a value to that.</p>
1
2016-09-16T20:31:22Z
[ "python", "language-lawyer" ]
Are for-loop name list expressions legal?
39,539,606
<p>In CPython 2.7.10 and 3.4.3, and PyPy 2.6.0 (Python 2.7.9), it is apparently legal to use expressions (or some subset of them) for the name list in a for-loop. Here's a typical for-loop:</p> <pre><code>&gt;&gt;&gt; for a in [1]: pass ... &gt;&gt;&gt; a 1 </code></pre> <p>But you can also use attributes from objects:</p> <pre><code>&gt;&gt;&gt; class Obj(object): pass ... &gt;&gt;&gt; obj = Obj() &gt;&gt;&gt; for obj.b in [1]: pass ... &gt;&gt;&gt; obj.b 1 </code></pre> <p>And you can even use attributes from expressions:</p> <pre><code>&gt;&gt;&gt; for Obj().c in [1]: pass ... </code></pre> <p>But not all expressions appear to work:</p> <pre><code>&gt;&gt;&gt; for (True and obj.d) in [1]: pass ... File "&lt;stdin&gt;", line 1 SyntaxError: can't assign to operator </code></pre> <p>But they do so long as the attribute is on the outside?</p> <pre><code>&gt;&gt;&gt; for (True and obj).e in [1]: pass ... &gt;&gt;&gt; obj.e 1 </code></pre> <p>Or something is assignable?</p> <pre><code>&gt;&gt;&gt; for {}['f'] in [1]: pass ... </code></pre> <p>I'm surprised any of these are legal syntax in Python. I expected only names to be allowed. Are these even supposed to work? Is this an oversight? Is this an implementation detail of CPython that PyPy happens to also implement?</p>
3
2016-09-16T20:25:32Z
39,539,697
<blockquote> <p>Are these even supposed to work? </p> </blockquote> <p>Yes</p> <blockquote> <p>Is this an oversight? </p> </blockquote> <p>No</p> <blockquote> <p>Is this an implementation detail of CPython that PyPy happens to also implement?</p> </blockquote> <p>No</p> <hr> <p>If you can assign to it, you can use it as the free variable in the for loop.</p> <p>For questions like this, it's worth going straight to the <a href="https://docs.python.org/3/reference/compound_stmts.html#the-for-statement" rel="nofollow">grammar</a>:</p> <pre><code>for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] </code></pre> <p>A <code>target_list</code> is just a bunch of <code>target</code>:</p> <pre><code>target_list ::= target ("," target)* [","] target ::= identifier | "(" target_list ")" | "[" [target_list] "]" | attributeref | subscription | slicing | "*" target </code></pre> <p>If you look at that closely, you'll see that none of the working examples you've given is a counter-example. Mind you, bugs in the parser are not unheard of (<a href="http://stackoverflow.com/questions/23998026/why-isnt-this-a-syntax-error-in-python#comment36983617_23998128">even I found one once</a>), so if you find a legitimate syntax anomaly then by means submit a ticket - these tend to get fixed quickly. </p> <p>The most interesting pair you gave is <code>(True and obj.d)</code> and <code>(True and obj).d</code>, which seem to be the same logically but are parsed differently:</p> <pre><code>&gt;&gt;&gt; ast.dump(ast.parse('(True and obj.d)'), annotate_fields=False) "Module([Expr(BoolOp(And(), [Name('True', Load()), Attribute(Name('obj', Load()), 'd', Load())]))])" &gt;&gt;&gt; ast.dump(ast.parse('(True and obj).d'), annotate_fields=False) "Module([Expr(Attribute(BoolOp(And(), [Name('True', Load()), Name('obj', Load())]), 'd', Load()))])" </code></pre> <p><em>Note:</em> <code>(True and obj).d</code> is an <a href="https://docs.python.org/3/reference/expressions.html#attribute-references" rel="nofollow"><code>attributeref</code></a> in the grammar. </p>
5
2016-09-16T20:32:57Z
[ "python", "language-lawyer" ]
google-app-engine fails to run Cron job and gives an ImportError: No module named gcloud
39,539,611
<p>app-engine fails to import gcloud used gcloud app deploy app.yaml \cron.yaml to deploy on google app engine</p> <p>opened on browser and get:</p> <pre><code>Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/base/data/home/apps/s~gcp-project-01/20160916t160552.395688991947248655/main.py", line 18, in &lt;module&gt; import update_datastore as ud File "/base/data/home/apps/s~vehicle-monitors-api/20160916t160552.395688991947248655/update_datastore.py", line 20, in &lt;module&gt; from gcloud import datastore, logging ImportError: No module named gcloud </code></pre> <p>The app.yaml file:</p> <pre><code> runtime: python27 api_version: 1 threadsafe: true handlers: - url: / script: main login: admin </code></pre> <p>The cron.yaml file:</p> <pre><code> cron: - description: run main app url: / target: main schedule: every 2 minutes </code></pre> <p>the requirements.txt file:</p> <pre><code> gcloud==0.14.0 </code></pre>
0
2016-09-16T20:25:49Z
39,715,633
<p>All 3rd party packages need to be installed in the same directory as your app. Run this from the root directory of your application to install it.</p> <pre><code>pip install gcloud -t . </code></pre>
0
2016-09-27T03:46:28Z
[ "python", "google-app-engine", "cron", "gcloud-python", "google-cloud-python" ]
Scipy/numpy: two dense, one sparse dot product
39,539,640
<p>Let's say we have a matrix <code>A</code> of size <code>NxN</code>, and <code>A</code> is sparse and <code>N</code> is very large. So we naturally want to store is as as scipy sparse matrix.</p> <p>We also have a dense numpy array <code>q</code> of size <code>NxK</code>, where <code>K</code> is relatively smaller.</p> <p>How do we most efficiently perform <code>q.T * A * q</code>, where <code>*</code> is matrix multiplication, to obtain a <code>KxK</code> result?</p> <p>One part of what we want can be done efficiently, that is just <code>A * q</code>, but once you do that you materialize a dense array that you then need to multiply with another dense array.</p> <p>Any way to do it faster than <code>q.T.dot(A.dot(q))</code>?</p>
0
2016-09-16T20:28:06Z
39,540,895
<p>So you have</p> <pre><code>(k,N) * (N,N) * (N,k) =&gt; (k,k) </code></pre> <p>One of those dot product results in a dense array; that times another dense is also dense. With a multiplication like this you quickly loose the sparsity.</p> <p>If <code>q</code> has a lot of 0s, and you want to preserve the sparse matrix nature of the problem, make <code>q</code> sparse before doing this multiplication.</p>
0
2016-09-16T22:23:24Z
[ "python", "arrays", "numpy", "matrix", "scipy" ]
Python Web-scraping Solution
39,539,646
<p>So, I'm new to python and am trying to develop an exercise in which I scrape the page numbers from a list on this url, which is a list of various published papers. </p> <p>When I go into the HTML element for the page I want to scrape, I inspect the element and find this HTML code to match up:</p> <pre><code>&lt;div class="src"&gt; Foreign Affairs, Vol. 79, No. 4 (Jul. - Aug., 2000), pp. 53-63 &lt;/div&gt; </code></pre> <p>The part that I want to churn out what is in between the class brackets. This is what I attempted to write in order to do the job. </p> <pre><code>import requests from bs4 import BeautifulSoup url = "http://www.jstor.org/action/doAdvancedSearch?c4=AND&amp;c5=AND&amp;q2=&amp;pt=&amp;q1=nuclear&amp;f3=all&amp;f1=all&amp;c3=AND&amp;c6=AND&amp;q6=&amp;f4=all&amp;q4=&amp;f0=all&amp;c2=AND&amp;q3=&amp;acc=off&amp;c1=AND&amp;isbn=&amp;q0=china+&amp;f6=all&amp;la=&amp;f2=all&amp;ed=2001&amp;q5=&amp;f5=all&amp;group=none&amp;sd=2000" r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all("div class='src'") for link in links: print </code></pre> <p>I know that this code is unfinished and that's because I don't know where to go from here :/. Can anyone help me here?</p>
1
2016-09-16T20:28:31Z
39,539,709
<p>If I understand you correctly, you want the pages inside all divs with class="src"</p> <p>If so, then you need to do:</p> <pre><code>import requests import re from bs4 import BeautifulSoup url = "http://www.jstor.org/action/doAdvancedSearch?c4=AND&amp;c5=AND&amp;q2=&amp;pt=&amp;q1=nuclear&amp;f3=all&amp;f1=all&amp;c3=AND&amp;c6=AND&amp;q6=&amp;f4=all&amp;q4=&amp;f0=all&amp;c2=AND&amp;q3=&amp;acc=off&amp;c1=AND&amp;isbn=&amp;q0=china+&amp;f6=all&amp;la=&amp;f2=all&amp;ed=2001&amp;q5=&amp;f5=all&amp;group=none&amp;sd=2000" r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all('div', {'class':'src'}) for link in links: pages = re.search('(pp.\s*\d*-\d*)', link.text) print pages.group(1) </code></pre> <p>Note that I have used regex to get the page numbers. This may sound strange for people unfamiliar with regular expressions, but I think its more elegant than using string operations like <code>strip</code> and <code>split</code></p>
1
2016-09-16T20:33:48Z
[ "python", "web-scraping", "beautifulsoup" ]
Python Web-scraping Solution
39,539,646
<p>So, I'm new to python and am trying to develop an exercise in which I scrape the page numbers from a list on this url, which is a list of various published papers. </p> <p>When I go into the HTML element for the page I want to scrape, I inspect the element and find this HTML code to match up:</p> <pre><code>&lt;div class="src"&gt; Foreign Affairs, Vol. 79, No. 4 (Jul. - Aug., 2000), pp. 53-63 &lt;/div&gt; </code></pre> <p>The part that I want to churn out what is in between the class brackets. This is what I attempted to write in order to do the job. </p> <pre><code>import requests from bs4 import BeautifulSoup url = "http://www.jstor.org/action/doAdvancedSearch?c4=AND&amp;c5=AND&amp;q2=&amp;pt=&amp;q1=nuclear&amp;f3=all&amp;f1=all&amp;c3=AND&amp;c6=AND&amp;q6=&amp;f4=all&amp;q4=&amp;f0=all&amp;c2=AND&amp;q3=&amp;acc=off&amp;c1=AND&amp;isbn=&amp;q0=china+&amp;f6=all&amp;la=&amp;f2=all&amp;ed=2001&amp;q5=&amp;f5=all&amp;group=none&amp;sd=2000" r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all("div class='src'") for link in links: print </code></pre> <p>I know that this code is unfinished and that's because I don't know where to go from here :/. Can anyone help me here?</p>
1
2016-09-16T20:28:31Z
39,539,820
<p>An alternative to Tales Pádua's <a href="http://stackoverflow.com/a/39539709/189134">answer</a> is this:</p> <pre><code>from bs4 import BeautifulSoup html = """&lt;div class="src"&gt; Foreign Affairs, Vol. 79, No. 4 (Jul. - Aug., 2000), pp. 53-63 &lt;/div&gt; &lt;div class="src"&gt; Other Book, Vol. 1, No. 1 (Jul. - Aug., 2000), pp. 1-23 &lt;/div&gt;""" soup = BeautifulSoup(html) links = soup.find_all("div", class_ = "src") for link in links: print link.text.strip() </code></pre> <p>This outputs: </p> <pre><code>Foreign Affairs, Vol. 79, No. 4 (Jul. - Aug., 2000), pp. 53-63 Other Book, Vol. 1, No. 1 (Jul. - Aug., 2000), pp. 1-23 </code></pre> <p>This answer uses the <code>class_</code> parameter, which is <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class" rel="nofollow">recommended</a> in the documentation. </p> <hr> <p>If you are looking to get the page number, and everything follows the format above (comma separated), you can change the for loop to grab the last element of the string:</p> <pre><code>print link.text.split(",")[-1].strip() </code></pre> <p>This outputs:</p> <pre><code>pp. 53-63 pp. 1-23 </code></pre>
2
2016-09-16T20:44:00Z
[ "python", "web-scraping", "beautifulsoup" ]
Random numbers- only length-1 arrays can be converted to Python scalars
39,539,672
<pre><code>from math import sin, cos, pi import numpy as np N=10 a=np.random.randint(0, 360+1, N) print (a) theta=a*pi/180 print(theta) x=[cos(theta)] print(x) y=[sin(theta)] print(y) </code></pre> <hr> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-47-632b45c2aba1&gt; in &lt;module&gt;() 9 theta=a*pi/180 10 print(theta) ---&gt; 11 x=[cos(theta)] 12 print(x) 13 y=[sin(theta)] TypeError: only length-1 arrays can be converted to Python scalars </code></pre>
-2
2016-09-16T20:31:03Z
39,539,723
<p>Try using <code>np.cos(theta)</code> instead of <code>cos(theta)</code>. Same goes for <code>sin</code>.</p> <p>Only NumPy functions can be applied both to scalars and arrays. The regular <code>cos()</code> and <code>sin()</code> instead expect only scalar arguments, and fail in the example, as you try to apply them on a NumPy array of size 10.</p> <p>NumPy <code>cos</code> documentation: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html</a> <code>cos</code> documentation: <a href="https://docs.python.org/2/library/math.html" rel="nofollow">https://docs.python.org/2/library/math.html</a></p>
1
2016-09-16T20:35:16Z
[ "python", "arrays", "numpy", "random", "polar-coordinates" ]
Get image width from HTML code
39,539,733
<p>I can get the <code>width</code> attribute of an image using <code>BeautifulSoup</code> as follows:</p> <pre><code>img = soup.find("img") width = img["width"] </code></pre> <p>The problem is that <code>width</code> can be set in <code>CSS</code> file or not set at all.</p> <p>I would like to extract the value without downloading the image from <code>img["src"]</code> How can I do it in Python to extract the value if it's set somewhere (HTML or CSS) or get the default value the browser will render (if not set)?</p>
1
2016-09-16T20:36:23Z
39,539,776
<p>The quick answer is: you can't - the resultant size of an image is based on evaluation of CSS, and indeed JS. You'd need to do all that work in order to find your answer.</p> <p>Another approach might be to use a real browser to do that work for you, and then ask it what the width is. See <a href="http://phantomjs.org/" rel="nofollow">PhantomJS</a>, and <a href="http://www.seleniumhq.org/" rel="nofollow">Selenium</a>.</p>
2
2016-09-16T20:40:11Z
[ "python", "selenium", "web-scraping", "beautifulsoup", "phantomjs" ]
Get image width from HTML code
39,539,733
<p>I can get the <code>width</code> attribute of an image using <code>BeautifulSoup</code> as follows:</p> <pre><code>img = soup.find("img") width = img["width"] </code></pre> <p>The problem is that <code>width</code> can be set in <code>CSS</code> file or not set at all.</p> <p>I would like to extract the value without downloading the image from <code>img["src"]</code> How can I do it in Python to extract the value if it's set somewhere (HTML or CSS) or get the default value the browser will render (if not set)?</p>
1
2016-09-16T20:36:23Z
39,558,983
<p>You can partially download image, only enough to get width/height through setting Range in requests headers and use somehow variant of getimageinfo.py</p> <p>Example usage:</p> <pre><code>def check_is_small_pic(url, pic_size): is_small = False r_check = requests.get(url, headers={"Range": "50"}) image_info = getimageinfo.getImageInfo(r_check.content) if image_info[1] &lt; pic_size or image_info[2] &lt; pic_size: is_small = True return is_small </code></pre> <p>Some getimageinfo.py, quickly adjusted for python 3.5:</p> <pre><code>import io import struct # import urllib.request as urllib2 def getImageInfo(data): data = data size = len(data) #print(size) height = -1 width = -1 content_type = '' # handle GIFs if (size &gt;= 10) and data[:6] in (b'GIF87a', b'GIF89a'): # Check to see if content_type is correct content_type = 'image/gif' w, h = struct.unpack(b"&lt;HH", data[6:10]) width = int(w) height = int(h) # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/) # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR' # and finally the 4-byte width, height elif ((size &gt;= 24) and data.startswith(b'\211PNG\r\n\032\n') and (data[12:16] == b'IHDR')): content_type = 'image/png' w, h = struct.unpack(b"&gt;LL", data[16:24]) width = int(w) height = int(h) # Maybe this is for an older PNG version. elif (size &gt;= 16) and data.startswith(b'\211PNG\r\n\032\n'): # Check to see if we have the right content type content_type = 'image/png' w, h = struct.unpack(b"&gt;LL", data[8:16]) width = int(w) height = int(h) # handle JPEGs elif (size &gt;= 2) and data.startswith(b'\377\330'): content_type = 'image/jpeg' jpeg = io.BytesIO(data) jpeg.read(2) b = jpeg.read(1) try: while (b and ord(b) != 0xDA): while (ord(b) != 0xFF): b = jpeg.read(1) while (ord(b) == 0xFF): b = jpeg.read(1) if (ord(b) &gt;= 0xC0 and ord(b) &lt;= 0xC3): jpeg.read(3) h, w = struct.unpack(b"&gt;HH", jpeg.read(4)) break else: jpeg.read(int(struct.unpack(b"&gt;H", jpeg.read(2))[0])-2) b = jpeg.read(1) width = int(w) height = int(h) except struct.error: pass except ValueError: pass return content_type, width, height # from PIL import Image # import requests # hrefs = ['http://farm4.staticflickr.com/3894/15008518202_b016d7d289_m.jpg','https://farm4.staticflickr.com/3920/15008465772_383e697089_m.jpg','https://farm4.staticflickr.com/3902/14985871946_86abb8c56f_m.jpg'] # RANGE = 5000 # for href in hrefs: # req = requests.get(href,headers={'User-Agent':'Mozilla5.0(Google spider)','Range':'bytes=0-{}'.format(RANGE)}) # im = getImageInfo(req.content) # # print(im) # req = urllib2.Request("http://vn-sharing.net/forum/images/smilies/onion/ngai.gif", headers={"Range": "5000"}) # r = urllib2.urlopen(req) # # f = open("D:\\Pictures\\1.jpg", "rb") # print(getImageInfo(r.read())) # Output: &gt;&gt; ('image/gif', 50, 50) # print(getImageInfo(f.read())) </code></pre>
2
2016-09-18T14:51:58Z
[ "python", "selenium", "web-scraping", "beautifulsoup", "phantomjs" ]
defining a function without using ":"
39,539,803
<p>I have been asked to define a function which is called <code>avg</code>. <code>avg</code> should calculate the average of two lists with the same amount of numbers - take all the numbers from both lists and calculate their average.<br> However, it is not allowed to use <code>:</code> nor more than one line (except <code>import</code> lines).</p> <p>My closest try was:</p> <pre><code>//import line does not count as a line import numpy //the code line (only one is allowed) avg=lambda lst1,lst2: numpy.mean(lst1+lst2) </code></pre> <p>My function properly calculates the average of the lists but it contains <code>:</code>, so it is not good enough. </p>
1
2016-09-16T20:42:34Z
39,539,964
<p>If someone asked you a pointless question, I would just give him a pointless answer. He deserves it.</p> <pre><code>import numpy # You said it doesn't count as a line # Take the : from dict's docstring. exec("avg = lambda lst1, lst2{} numpy.mean(lst1+lst2)".format(dict.__doc__[213])) &gt;&gt;&gt; avg([1,2,3], [1,2,3]) 2 </code></pre>
7
2016-09-16T20:56:54Z
[ "python" ]
defining a function without using ":"
39,539,803
<p>I have been asked to define a function which is called <code>avg</code>. <code>avg</code> should calculate the average of two lists with the same amount of numbers - take all the numbers from both lists and calculate their average.<br> However, it is not allowed to use <code>:</code> nor more than one line (except <code>import</code> lines).</p> <p>My closest try was:</p> <pre><code>//import line does not count as a line import numpy //the code line (only one is allowed) avg=lambda lst1,lst2: numpy.mean(lst1+lst2) </code></pre> <p>My function properly calculates the average of the lists but it contains <code>:</code>, so it is not good enough. </p>
1
2016-09-16T20:42:34Z
39,540,361
<p>You could use exec like in Bharel's answer but use the <code>chr(58)</code>:</p> <pre><code>exec("avg = lambda lst1, lst2 " + chr(58) + " sum(lst1 + lst2, 0.) / (len(lst1) + len(lst2))") print(avg([1,2,3], [4,5,6])) </code></pre> <p>Or if you really want to use numpy.mean:</p> <pre><code>exec("avg = lambda lst1, lst2 " + chr(58) + "numpy.mean(lst1+lst2)") </code></pre>
1
2016-09-16T21:31:12Z
[ "python" ]
defining a function without using ":"
39,539,803
<p>I have been asked to define a function which is called <code>avg</code>. <code>avg</code> should calculate the average of two lists with the same amount of numbers - take all the numbers from both lists and calculate their average.<br> However, it is not allowed to use <code>:</code> nor more than one line (except <code>import</code> lines).</p> <p>My closest try was:</p> <pre><code>//import line does not count as a line import numpy //the code line (only one is allowed) avg=lambda lst1,lst2: numpy.mean(lst1+lst2) </code></pre> <p>My function properly calculates the average of the lists but it contains <code>:</code>, so it is not good enough. </p>
1
2016-09-16T20:42:34Z
39,540,519
<p>Speaking of ridiculous, I suggest:</p> <pre><code>&gt;&gt;&gt; exec(''.join(map(chr, [100, 101, 102, 32, 97, 118, 103, 40, 108, 115, 116, 49, 44, 32, 108, 115, 116, 50, 41, 58, 32, 114, 101,116, 117, 114, 110, 32, 48, 46, 53, 32, 42, 32, 115, 117, 109, 40, 108, 115, 116, 49, 32, 43, 32, 108, 115, 116, 50, 41, 32, 47, 32, 108, 101, 110, 40, 108, 115, 116, 49, 41]))) &gt;&gt;&gt; &gt;&gt;&gt; avg([1,2,3,4],[5,6,7,8]) 4.5 </code></pre>
3
2016-09-16T21:46:28Z
[ "python" ]
Read CSV and replace a column based on keyword list
39,539,868
<p>I'm new to Python and would appreciate some help on how to approach this problem. Here's what I'm trying to do:</p> <ol> <li>Read a CSV file with a list of transactions. Each row has 6 columns.</li> <li><p>For each row, compare the <code>DESCRIPTION</code> column to a list of keywords to see if any word matches one in the keyword list.<br> <code>|Col0 | Col1 | Col2 | Col3 "DESCRIPTION" | Col4 | Col5 "CATEGORY"|</code></p></li> <li><p>If any word matches something from the keyword list, replace the <code>CATEGORY</code> column with a new entry that corresponds to that particular keyword list (e.g. <code>"Groceries"</code>).</p></li> <li>Continue through each row, comparing it to several keyword lists. If it matches, replace Column 5 (<code>CATEGORY</code>) in each row with the corresponding value.</li> <li>Save to a new CSV file.</li> </ol> <p>Here's what I have so far:</p> <pre><code>import csv grocery_keyword = ['GIANT', 'SAFEWAY', 'KROGER'] with open('Trans.csv') as csvFile: reader = csv.reader(csvFile, delimiter=",") my_list = list(reader) for row in my_list: for index, item in enumerate(row): if any grocery_keyword in row: row[index] = item.replace("", "Grocery") newCSVFile = 'newCSVFile.csv' with open(newCSVFile, "w") as output: writer = csv.writer(output, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') writer.writerows(my_list) csvFile.close() </code></pre> <p>Is a list the right thing to use here? How should I do the comparison between the column and the keyword list?</p>
2
2016-09-16T20:47:52Z
39,540,147
<p>i find that the <strong>pandas</strong> library works great for this type of stuff. i'm sure that the find_cat def could be sped up a bit, but wanted to get the idea of the search &amp; substitution applied to a column communicated.</p> <pre><code>import pandas as pd def find_cat(desc, cat_dict): cat_list = [] for cat in cat_dict: for w in cat_dict[cat]: if w in desc: cat_list.append(cat) return cat_list cat_d = { "cat1": ["1_word_1", "1_word_2"], "cat2": ["2_word_1", "2_word_2"], "cat3": ["3_word_1", "3_word_2"] } df = pd.read_csv('in.csv') df["category"] = df[["description"]].apply(lambda row: find_cat(row["description"], cat_d), axis=1) df.to_csv('out.csv') </code></pre> <p>where in.csv contains:</p> <pre><code>col1,col2,col3,col4,description,category 0,0,0,0,1_word_1, 0,0,0,0,1_word_2, 0,0,0,0,1_word_1, 0,0,0,0,3_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_2, 0,0,0,0,1_word_1, 0,0,0,0,2_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_2, 0,0,0,0,1_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_1, 0,0,0,0,2_word_2, 0,0,0,0,1_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_1, 0,0,0,0,1_word_2, 0,0,0,0,1_word_1, 0,0,0,0,2_word_1, </code></pre> <p>and produces out.csv:</p> <pre><code>,col1,col2,col3,col4,description,category 0,0,0,0,0,1_word_1,cat1 1,0,0,0,0,1_word_2,cat1 2,0,0,0,0,1_word_1,cat1 3,0,0,0,0,3_word_1,cat3 4,0,0,0,0,1_word_1,cat1 5,0,0,0,0,1_word_1,cat1 6,0,0,0,0,1_word_2,cat1 7,0,0,0,0,1_word_1,cat1 8,0,0,0,0,2_word_1,cat2 9,0,0,0,0,1_word_1,cat1 10,0,0,0,0,1_word_2,cat1 11,0,0,0,0,1_word_1,cat1 12,0,0,0,0,1_word_1,cat1 13,0,0,0,0,1_word_1,cat1 14,0,0,0,0,2_word_2,cat2 15,0,0,0,0,1_word_1,cat1 16,0,0,0,0,1_word_1,cat1 17,0,0,0,0,1_word_1,cat1 18,0,0,0,0,1_word_1,cat1 19,0,0,0,0,1_word_2,cat1 20,0,0,0,0,1_word_1,cat1 21,0,0,0,0,2_word_1,cat2 </code></pre>
0
2016-09-16T21:12:43Z
[ "python", "csv" ]
Are user defined functions callable?
39,539,914
<p>I am not a very experience programmer. Please can you tell me why this code gives me the error message:</p> <p>error: quad: first argument is not callable</p> <p>code:</p> <pre><code>from matplotlib import pyplot as plt import numpy as np import scipy.integrate as integrate def parabola(x, a): return a+x**2 x=np.arange(-10, 10, 1) plt.plot(x, parabola(x,2)) plt.show() int1=integrate.quad(parabola(x,2), -5, 5) print int1 </code></pre> <p>Should all user defined functions be callable? </p>
0
2016-09-16T20:52:04Z
39,539,948
<p>There are two problems in your code:</p> <p>1) you call the function <code>parabola()</code>. Instead, pass it as an argument to <code>integrate</code>.</p> <p>2) <code>parabola()</code> is a two argument function. <code>integrate</code> expects a single-argument function.</p> <p>To solve the second problem, you need to convert the two-argument function to a single-argument function. This is a general technique known as <em>partial application</em> of functions.</p> <p>Try this:</p> <pre><code>def parabola1(x): return parabola(x, 2) int1 = integrate.quad(parabola1, -5, 5) print int1 </code></pre>
3
2016-09-16T20:55:27Z
[ "python", "numpy" ]
Are user defined functions callable?
39,539,914
<p>I am not a very experience programmer. Please can you tell me why this code gives me the error message:</p> <p>error: quad: first argument is not callable</p> <p>code:</p> <pre><code>from matplotlib import pyplot as plt import numpy as np import scipy.integrate as integrate def parabola(x, a): return a+x**2 x=np.arange(-10, 10, 1) plt.plot(x, parabola(x,2)) plt.show() int1=integrate.quad(parabola(x,2), -5, 5) print int1 </code></pre> <p>Should all user defined functions be callable? </p>
0
2016-09-16T20:52:04Z
39,540,508
<p>Try:</p> <pre><code>int1=integrate.quad(parabola, -5, 5, args=(2,)) </code></pre> <p>The <code>quad</code> signature is:</p> <pre><code>quad(func, a, b, args=(), ...) </code></pre> <p>the function, lower range, upper range, args_to_pass through, etc.</p>
1
2016-09-16T21:44:37Z
[ "python", "numpy" ]
What's the difference between True and False in python grammar?
39,540,014
<p>I'm reading <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow">the python language specification</a> and found there's a <code>None</code>, <code>True</code>, and <code>False</code> token. I can understand the difference between <code>None</code> and <code>False</code> since <code>None</code> is not a boolan. But, about <code>True</code> and <code>False</code>, why not just <code>BOOLEAN</code> there? Is there any case where <code>True</code> and <code>False</code> behave differently? Or is there any semantical difference?</p> <p>Note that I'm asking about the difference in grammar not the boolean value which is obviously different.</p>
0
2016-09-16T21:01:20Z
39,540,098
<p>This is a formalization of the fact that <code>True</code> and <code>False</code> are special names in python3: you can't assign to them. </p> <p>The reason that they aren't BOOLEAN is simply that boolean isn't a <a href="https://docs.python.org/3/library/token.html" rel="nofollow">valid token</a> for the parser. </p> <p><em>Note:</em> You will find this detail missing in the python2 grammar, where you <em>can</em> actually assign to the names True and False (...if you want to watch the world burn). </p>
2
2016-09-16T21:08:51Z
[ "python" ]
What's the difference between True and False in python grammar?
39,540,014
<p>I'm reading <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow">the python language specification</a> and found there's a <code>None</code>, <code>True</code>, and <code>False</code> token. I can understand the difference between <code>None</code> and <code>False</code> since <code>None</code> is not a boolan. But, about <code>True</code> and <code>False</code>, why not just <code>BOOLEAN</code> there? Is there any case where <code>True</code> and <code>False</code> behave differently? Or is there any semantical difference?</p> <p>Note that I'm asking about the difference in grammar not the boolean value which is obviously different.</p>
0
2016-09-16T21:01:20Z
39,540,115
<pre><code>atom: ('(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictorsetmaker] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') </code></pre> <p><code>NAME</code>, <code>NUMBER</code>, and <code>STRING</code> are tokens representing three classes of tokens. Each of them represents an unlimited set of possible tokens. There are many number literals that can be classified as <code>NUMBER</code>, many string literals that can be <code>STRING</code>s, etc.</p> <p>There are only two boolean literals, <code>True</code> and <code>False</code>. The tokenizer could have been written to classify them both as <code>BOOLEAN</code>. Could have, but wasn't. They're only referred to once in the entire grammar, so writing <code>'True' | 'False'</code> is no big deal.</p>
3
2016-09-16T21:10:09Z
[ "python" ]
What's the difference between True and False in python grammar?
39,540,014
<p>I'm reading <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow">the python language specification</a> and found there's a <code>None</code>, <code>True</code>, and <code>False</code> token. I can understand the difference between <code>None</code> and <code>False</code> since <code>None</code> is not a boolan. But, about <code>True</code> and <code>False</code>, why not just <code>BOOLEAN</code> there? Is there any case where <code>True</code> and <code>False</code> behave differently? Or is there any semantical difference?</p> <p>Note that I'm asking about the difference in grammar not the boolean value which is obviously different.</p>
0
2016-09-16T21:01:20Z
39,540,127
<p>Presumably from the reference to which you linked you are referring to the grammatical production</p> <pre><code>atom: ('(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictorsetmaker] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') </code></pre> <p>This simply gives the strings <code>None</code>, <code>True</code>, and <code>False</code> the same status as certain other language elements. While it would have been possible to create a definition of a Boolean atom which could either be <code>True</code> or <code>False</code> and use that in the grammar, what purpose would that have served?</p> <p>In point of fact, even in 2.7 you can try to delete the <code>True</code> and <code>False</code> definitions from the <code>__builtins__</code> namespace:</p> <pre><code>&gt;&gt;&gt; del __builtins__.True &gt;&gt;&gt; del __builtins__.False Traceback (most recent call last): File "/Users/sholden/.virtualenvs/jlab/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) NameError: global name 'True' is not defined </code></pre> <p>Interestingly, if you delete <code>False</code> first there is no complaint about the deletion of <code>True</code> :-)</p> <p>However, this makes even quite standard Python make no sense at all:</p> <pre><code>&gt;&gt;&gt; 1 == 1 Traceback (most recent call last): File "/Users/sholden/.virtualenvs/jlab/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) NameError: global name 'True' is not defined </code></pre> <p>This underlines that Python was produced as "a programming language for consenting adults." Ultimately it gives you enough rope to hang yourself if you are determined to do that.</p>
1
2016-09-16T21:10:54Z
[ "python" ]
How to add a subject to an email being sent with gmail?
39,540,043
<p>I am trying to send an email using GMAIL with a subject and a message. I have succeeded in sending an email using GMAIL without the implementation of <code>subject</code> and have also been able to receieve the email. However whenever I try to add a subject the program simply does not work.</p> <pre><code>import smtplib fromx = '[email protected]' to = '[email protected]' subject = 'subject' #Line that causes trouble msg = 'example' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('[email protected]', 'password') server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble server.quit() </code></pre> <p>error line:</p> <pre><code>server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble </code></pre>
0
2016-09-16T21:03:32Z
39,540,105
<p>The call to <code>smtplib.SMTP.sendmail()</code> does not take a <code>subject</code> parameter. See <a href="https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail" rel="nofollow">the doc</a> for instructions on how to call it.</p> <p>Subject lines, along with all other headers, are included as part of the message in a format called RFC822 format, after the now-obsolete document that originally defined the format. Make your message conform to that format, like so:</p> <pre><code>import smtplib fromx = '[email protected]' to = '[email protected]' subject = 'subject' #Line that causes trouble msg = 'Subject:{}\n\nexample'.format(subject) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('[email protected]', 'xxx') server.sendmail(fromx, to, msg) server.quit() </code></pre> <p>Of course, the easier way to conform your message to all appropriate standards is to use the Python <a href="https://docs.python.org/2/library/email.message.html" rel="nofollow"><code>email.message</code></a> standard library, like so:</p> <pre><code>import smtplib from email.mime.text import MIMEText fromx = '[email protected]' to = '[email protected]' msg = MIMEText('example') msg['Subject'] = 'subject' msg['From'] = fromx msg['To'] = to server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('[email protected]', 'xxx') server.sendmail(fromx, to, msg.as_string()) server.quit() </code></pre> <p><a href="https://docs.python.org/2/library/email-examples.html#email-examples" rel="nofollow">Other examples</a> are also available. </p>
3
2016-09-16T21:09:36Z
[ "python", "python-2.7", "email", "gmail", "subject" ]
How to add a subject to an email being sent with gmail?
39,540,043
<p>I am trying to send an email using GMAIL with a subject and a message. I have succeeded in sending an email using GMAIL without the implementation of <code>subject</code> and have also been able to receieve the email. However whenever I try to add a subject the program simply does not work.</p> <pre><code>import smtplib fromx = '[email protected]' to = '[email protected]' subject = 'subject' #Line that causes trouble msg = 'example' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('[email protected]', 'password') server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble server.quit() </code></pre> <p>error line:</p> <pre><code>server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble </code></pre>
0
2016-09-16T21:03:32Z
39,546,304
<p>Or just use a package like <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a>. Disclaimer: I'm the maintainer.</p> <pre><code>import yagmail yag = yagmail.SMTP("email.gmail.com", "password") yag.send("email1.gmail.com", "subject", "contents") </code></pre> <p>Install with <code>pip install yagmail</code></p>
0
2016-09-17T11:28:02Z
[ "python", "python-2.7", "email", "gmail", "subject" ]
MySQLdb Executemany error
39,540,086
<p>I'm having issues with executemany returning the following error</p> <pre><code>(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IBM'',''1998-01-02 09:30:00'',''104.5'',''104.5'',''104.5'',''104.5'',''67000'')' at line 2") </code></pre> <p>Whats interesting is I'm using the EXACT same syntax successfully with just plain execute command. To demonstrate, this code will successfully add a record using execute, however using the SAME syntax with execute many is returning the above error. Any insight?</p> <pre><code>import MySQLdb from MySQLdb import * import datetime db1 = MySQLdb.connect(host="127.0.0.1",user="root",passwd="password") c = db1.cursor() c.execute("use securities_master") testdata = [('IBM', datetime.datetime(1998, 1, 2, 9, 30), '104.5', '104.5', '104.5', '104.5', '67000'), ('IBM', datetime.datetime(1998, 1, 2, 9, 31), '104.375', '104.5', '104.375', '104.375', '10800'), ('IBM', datetime.datetime(1998, 1, 2, 9, 32), '104.4375', '104.5', '104.375', '104.5', '13300'), ('IBM', datetime.datetime(1998, 1, 2, 9, 33), '104.4375', '104.5', '104.375', '104.375', '16800'), ('IBM', datetime.datetime(1998, 1, 2, 9, 34), '104.375', '104.5', '104.375', '104.375', '4801'), ('IBM', datetime.datetime(1998, 1, 2, 9, 35), '104.4375', '104.5', '104.375', '104.375', '23300'), ('IBM', datetime.datetime(1998, 1, 2, 9, 36), '104.4375', '104.4375', '104.375', '104.4375', '2600'), ('IBM', datetime.datetime(1998, 1, 2, 9, 37), '104.375', '104.375', '104.375', '104.375', '2800'), ('IBM', datetime.datetime(1998, 1, 2, 9, 38), '104.375', '104.4375', '104.375', '104.4375', '11101')] sql = """INSERT IGNORE INTO stocks_datamine (symbol_id,price_date,open_price,high_price,low_price,close_price,volume) VALUES('%s','%s','%s','%s','%s','%s','%s')""" for record in testdata[:1]:#test insert on one record sql_statement = sql%record c.execute(sql_statement) db1.commit() print 'success!' #same sql statement just for multiple records - returns error :( c.executemany(sql, testdata) db1.commit() </code></pre>
0
2016-09-16T21:08:01Z
39,540,295
<p>What you do in the for loop is wrong. You are formatting query as string with <code>sql_statement = sql%record</code>, this is not the correct way. You are constructing a query, this is what you are using MySQLdb for.</p> <p>What you need to do is the following:</p> <pre><code># remove quotes from the query sql = """INSERT IGNORE INTO stocks_datamine (symbol_id,price_date,open_price,high_price,low_price,close_price,volume) VALUES(%s, %s, %s, %s, %s, %s, %s)""" for record in testdata: # let MySQLdb to handle parameters. c.execute(sql_statement, record) db1.commit() </code></pre>
0
2016-09-16T21:25:10Z
[ "python", "mysql-python" ]
MySQLdb Executemany error
39,540,086
<p>I'm having issues with executemany returning the following error</p> <pre><code>(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IBM'',''1998-01-02 09:30:00'',''104.5'',''104.5'',''104.5'',''104.5'',''67000'')' at line 2") </code></pre> <p>Whats interesting is I'm using the EXACT same syntax successfully with just plain execute command. To demonstrate, this code will successfully add a record using execute, however using the SAME syntax with execute many is returning the above error. Any insight?</p> <pre><code>import MySQLdb from MySQLdb import * import datetime db1 = MySQLdb.connect(host="127.0.0.1",user="root",passwd="password") c = db1.cursor() c.execute("use securities_master") testdata = [('IBM', datetime.datetime(1998, 1, 2, 9, 30), '104.5', '104.5', '104.5', '104.5', '67000'), ('IBM', datetime.datetime(1998, 1, 2, 9, 31), '104.375', '104.5', '104.375', '104.375', '10800'), ('IBM', datetime.datetime(1998, 1, 2, 9, 32), '104.4375', '104.5', '104.375', '104.5', '13300'), ('IBM', datetime.datetime(1998, 1, 2, 9, 33), '104.4375', '104.5', '104.375', '104.375', '16800'), ('IBM', datetime.datetime(1998, 1, 2, 9, 34), '104.375', '104.5', '104.375', '104.375', '4801'), ('IBM', datetime.datetime(1998, 1, 2, 9, 35), '104.4375', '104.5', '104.375', '104.375', '23300'), ('IBM', datetime.datetime(1998, 1, 2, 9, 36), '104.4375', '104.4375', '104.375', '104.4375', '2600'), ('IBM', datetime.datetime(1998, 1, 2, 9, 37), '104.375', '104.375', '104.375', '104.375', '2800'), ('IBM', datetime.datetime(1998, 1, 2, 9, 38), '104.375', '104.4375', '104.375', '104.4375', '11101')] sql = """INSERT IGNORE INTO stocks_datamine (symbol_id,price_date,open_price,high_price,low_price,close_price,volume) VALUES('%s','%s','%s','%s','%s','%s','%s')""" for record in testdata[:1]:#test insert on one record sql_statement = sql%record c.execute(sql_statement) db1.commit() print 'success!' #same sql statement just for multiple records - returns error :( c.executemany(sql, testdata) db1.commit() </code></pre>
0
2016-09-16T21:08:01Z
39,540,446
<p>The problem is in <code>sql</code> query, you added quotes to <code>%s</code> (remove them): </p> <pre><code>sql = """INSERT ... VALUES(%s, %s, %s, %s, %s, %s, %s) </code></pre>
0
2016-09-16T21:39:04Z
[ "python", "mysql-python" ]
checking non-ambiguity of strides in numpy array
39,540,102
<p>For a numpy array <code>X</code>, the location of its element <code>X[k[0], ..., k[d-1]]</code> is offset from the location of <code>X[0,..., 0]</code> by <code>k[0]*s[0] + ... + k[d-1]*s[d-1]</code>, where <code>(s[0],...,s[d-1])</code> is the tuple representing <code>X.strides</code>.</p> <p>As far as I understand nothing in numpy array specs requires that distinct indexes of array <code>X</code> correspond to distinct addresses in memory, the simplest instance of this being a zero value of the stride, e.g. see <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/index.html#broadcasting" rel="nofollow">advanced NumPy</a> section of scipy lectures.</p> <p>Does the numpy have a built-in predicate to test if the strides and the shape are such that distinct indexes map to distinct memory addresses? </p> <p>If not, how does one write one, preferably so as to avoid sorting of the strides?</p>
2
2016-09-16T21:09:09Z
39,540,641
<p>edit: It took me a bit to figure what you are asking about. With striding tricks it's possible to index the same element in a databuffer in different ways, and broadcasting actually does this under the covers. Normally we don't worry about it because it is either hidden or intentional.</p> <p>Recreating in the strided mapping and looking for duplicates may be the only way to test this. I'm not aware of any existing function that checks it.</p> <p>==================</p> <p>I'm not quite sure what you concerned with. But let me illustrate how shape and strides work</p> <p>Define a 3x4 array:</p> <pre><code>In [453]: X=np.arange(12).reshape(3,4) In [454]: X.shape Out[454]: (3, 4) In [455]: X.strides Out[455]: (16, 4) </code></pre> <p>Index an item</p> <pre><code>In [456]: X[1,2] Out[456]: 6 </code></pre> <p>I can get it's index in a flattened version of the array (e.g. the original <code>arange</code>) with <code>ravel_multi_index</code>:</p> <pre><code>In [457]: np.ravel_multi_index((1,2),X.shape) Out[457]: 6 </code></pre> <p>I can also get this location using strides - keeping mind that strides are in bytes (here 4 bytes per item)</p> <pre><code>In [458]: 1*16+2*4 Out[458]: 24 In [459]: (1*16+2*4)/4 Out[459]: 6.0 </code></pre> <p>All these numbers are relative to the start of the data buffer. We can get the data buffer address from <code>X.data</code> or <code>X.__array_interface__['data']</code>, but usually don't need to.</p> <p>So this strides tells us that to go from entry to the next, step 4 bytes, and to go from one row to the next step 16. <code>6</code> is located at one row down, 2 over, or 24 bytes into the buffer.</p> <p>In the <code>as_strided</code> example of your link, <code>strides=(1*2, 0)</code> produces repeated indexing of specific values.</p> <p>With my <code>X</code>:</p> <pre><code>In [460]: y=np.lib.stride_tricks.as_strided(X,strides=(16,0), shape=(3,4)) In [461]: y Out[461]: array([[0, 0, 0, 0], [4, 4, 4, 4], [8, 8, 8, 8]]) </code></pre> <p><code>y</code> is a 3x4 that repeatedly indexes the 1st column of <code>X</code>.</p> <p>Changing one item in <code>y</code> ends up changing one value in <code>X</code> but a whole row in <code>y</code>:</p> <pre><code>In [462]: y[1,2]=10 In [463]: y Out[463]: array([[ 0, 0, 0, 0], [10, 10, 10, 10], [ 8, 8, 8, 8]]) In [464]: X Out[464]: array([[ 0, 1, 2, 3], [10, 5, 6, 7], [ 8, 9, 10, 11]]) </code></pre> <p><code>as_strided</code> can produce some weird effects if you aren't careful.</p> <p>OK, maybe I've figured out what's bothering you - can I identify a situation like this where two different indexing tuples end up pointing to the same location in the data buffer? Not that I'm aware of. That <code>y</code> strides contains a 0 is a pretty good indicator. </p> <p><code>as_strided</code>is often used to create overlapping windows:</p> <pre><code>In [465]: y=np.lib.stride_tricks.as_strided(X,strides=(8,4), shape=(3,4)) In [466]: y Out[466]: array([[ 0, 1, 2, 3], [ 2, 3, 10, 5], [10, 5, 6, 7]]) In [467]: y[1,2]=20 In [469]: y Out[469]: array([[ 0, 1, 2, 3], [ 2, 3, 20, 5], [20, 5, 6, 7]]) </code></pre> <p>Again changing 1 item in <code>y</code> ends up changing 2 values in y, but only 1 in <code>X</code>.</p> <p>Ordinary array creation and indexing does not have this duplicate indexing issue. Broadcasting may do something like, under the cover, where a (4,) array is changed to (1,4) and then to (3,4), effectively replicating rows. I think there's another <code>stride_tricks</code> function that does this explicitly.</p> <pre><code>In [475]: x,y=np.lib.stride_tricks.broadcast_arrays(X,np.array([.1,.2,.3,.4])) In [476]: x Out[476]: array([[ 0, 1, 2, 3], [20, 5, 6, 7], [ 8, 9, 10, 11]]) In [477]: y Out[477]: array([[ 0.1, 0.2, 0.3, 0.4], [ 0.1, 0.2, 0.3, 0.4], [ 0.1, 0.2, 0.3, 0.4]]) In [478]: y.strides Out[478]: (0, 8) </code></pre> <p>In any case, in normal array use we don't have to worry about this ambiguity. We get it only with intentional actions, not accidental ones.</p> <p>==============</p> <p>How about this for a test:</p> <pre><code>def dupstrides(x): uniq={sum(s*j for s,j in zip(x.strides,i)) for i in np.ndindex(x.shape)} print(uniq) print(len(uniq)) print(x.size) return len(uniq)&lt;x.size In [508]: dupstrides(X) {0, 32, 4, 36, 8, 40, 12, 44, 16, 20, 24, 28} 12 12 Out[508]: False In [509]: dupstrides(y) {0, 4, 8, 12, 16, 20, 24, 28} 8 12 Out[509]: True </code></pre>
2
2016-09-16T21:57:17Z
[ "python", "numpy" ]
checking non-ambiguity of strides in numpy array
39,540,102
<p>For a numpy array <code>X</code>, the location of its element <code>X[k[0], ..., k[d-1]]</code> is offset from the location of <code>X[0,..., 0]</code> by <code>k[0]*s[0] + ... + k[d-1]*s[d-1]</code>, where <code>(s[0],...,s[d-1])</code> is the tuple representing <code>X.strides</code>.</p> <p>As far as I understand nothing in numpy array specs requires that distinct indexes of array <code>X</code> correspond to distinct addresses in memory, the simplest instance of this being a zero value of the stride, e.g. see <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/index.html#broadcasting" rel="nofollow">advanced NumPy</a> section of scipy lectures.</p> <p>Does the numpy have a built-in predicate to test if the strides and the shape are such that distinct indexes map to distinct memory addresses? </p> <p>If not, how does one write one, preferably so as to avoid sorting of the strides?</p>
2
2016-09-16T21:09:09Z
39,752,690
<p>It turns out this test is already implemented in numpy, see <a href="https://github.com/numpy/numpy/blob/master/numpy/core/src/private/mem_overlap.c#L842" rel="nofollow">mem_overlap.c:842</a>.</p> <p>The test is exposed as <code>numpy.core.multiarray_tests.internal_overlap(x)</code>. </p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from numpy.core.multiarray_tests import internal_overlap &gt;&gt;&gt; from numpy.lib.stride_tricks import as_strided </code></pre> <p>Now, create a contiguous array, and use <code>as_strided</code> to create an array with internal overlapping, and confirm this with the testing:</p> <pre><code>&gt;&gt;&gt; x = np.arange(3*4, dtype=np.float64).reshape((3,4)) &gt;&gt;&gt; y = as_strided(x, shape=(5,4), strides=(16, 8)) &gt;&gt;&gt; y array([[ 0., 1., 2., 3.], [ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 8., 9., 10., 11.]]) &gt;&gt;&gt; internal_overlap(x) False &gt;&gt;&gt; internal_overlap(y) True </code></pre> <p>The function is optimized to quickly returns <code>False</code> for Fortran- or C- contiguous arrays. </p>
2
2016-09-28T16:12:48Z
[ "python", "numpy" ]
What does dis.findlabels() do?
39,540,128
<p>I was playing around with the <code>dis</code> library to gather information about a function (like what other functions it called). The documentation for <a href="https://docs.python.org/2/library/dis.html#dis.findlabels" rel="nofollow"><code>dis.findlabels</code></a> sounds like it would return other function calls, but I've tried it with a handful of functions and it always returns an empty list.</p> <blockquote> <pre><code>dis.findlabels(code) Detect all offsets in the code object code which are jump targets, and return a list of these offsets. </code></pre> </blockquote> <p>What is this function <em>supposed</em> to do and <em>how</em> would you use it?</p>
0
2016-09-16T21:10:57Z
39,540,245
<p>The jump targets are annotated by <code>&gt;&gt;</code> in disassembly output.</p> <p>For example, in:</p> <pre><code>def f(i): if i == 1: return 1 elif i == 2: return 2 </code></pre> <p><code>dis.dis(f)</code> shows:</p> <pre><code> 2 0 LOAD_FAST 0 (i) 3 LOAD_CONST 1 (1) 6 COMPARE_OP 2 (==) 9 POP_JUMP_IF_FALSE 16 3 12 LOAD_CONST 1 (1) 15 RETURN_VALUE 4 &gt;&gt; 16 LOAD_FAST 0 (i) 19 LOAD_CONST 2 (2) 22 COMPARE_OP 2 (==) 25 POP_JUMP_IF_FALSE 32 5 28 LOAD_CONST 2 (2) 31 RETURN_VALUE &gt;&gt; 32 LOAD_CONST 0 (None) 35 RETURN_VALUE </code></pre> <p>And <code>dis.findlabels(f.__code__.co_code)</code> returns <code>[16, 32]</code>.</p>
1
2016-09-16T21:20:45Z
[ "python" ]
What does dis.findlabels() do?
39,540,128
<p>I was playing around with the <code>dis</code> library to gather information about a function (like what other functions it called). The documentation for <a href="https://docs.python.org/2/library/dis.html#dis.findlabels" rel="nofollow"><code>dis.findlabels</code></a> sounds like it would return other function calls, but I've tried it with a handful of functions and it always returns an empty list.</p> <blockquote> <pre><code>dis.findlabels(code) Detect all offsets in the code object code which are jump targets, and return a list of these offsets. </code></pre> </blockquote> <p>What is this function <em>supposed</em> to do and <em>how</em> would you use it?</p>
0
2016-09-16T21:10:57Z
39,540,261
<p>For example, this function has one jump:</p> <pre><code>def f(x): if x &gt; 0: # This will jump to "return 2" if not x &gt; 0 return 1 else: return 2 </code></pre> <p>See it here:</p> <pre><code>&gt;&gt;&gt; dis.disco(f.__code__) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (0) 6 COMPARE_OP 4 (&gt;) 9 POP_JUMP_IF_FALSE 16 3 12 LOAD_CONST 2 (1) 15 RETURN_VALUE 5 &gt;&gt; 16 LOAD_CONST 3 (2) 19 RETURN_VALUE 20 LOAD_CONST 0 (None) 23 RETURN_VALUE </code></pre> <p>There is one jump to 16 in <code>9 POP_JUMP_IF_FALSE 16</code></p> <p>Therefore, <code>findlabels</code> finds that jump target:</p> <pre><code>&gt;&gt;&gt; dis.findlabels(f.__code__.co_code) [16] </code></pre>
2
2016-09-16T21:22:21Z
[ "python" ]
Selenium Python StaleElementReferenceException
39,540,160
<p>I'm trying to download all the pdf on a webpage using Selenium Python with Chrome as browser but every time the session ends with this message:</p> <pre><code>StaleElementReferenceException: stale element reference: element is not attached to the page document (Session info: chrome=52.0.2743.116) (Driver info: chromedriver=2.22.397933 </code></pre> <p>This is the code:</p> <pre><code>def download_pdf(self): current = self.driver.current_url lista_link_temp = self.driver.find_elements_by_xpath("//*[@href]") for link in lista_link_temp: if "pdf+html" in str(link.get_attribute("href")): tutor = link.get_attribute("href") self.driver.get(str(tutor)) self.driver.get(current) </code></pre> <p>Please help me.. I've just tried lambda, implicit and explicit wait </p> <p>Thanks</p>
1
2016-09-16T21:14:10Z
39,540,710
<p>You get stale element when you search for an element and before doing any action on it the page has changed/reloaded.</p> <p>Make sure the page is fully loaded before doing any actions in the page.</p> <p>So you need to add first a condition to wait for the page to be loaded an maybe check all requests are done.</p>
0
2016-09-16T22:02:46Z
[ "python", "google-chrome", "selenium" ]
Selenium Python StaleElementReferenceException
39,540,160
<p>I'm trying to download all the pdf on a webpage using Selenium Python with Chrome as browser but every time the session ends with this message:</p> <pre><code>StaleElementReferenceException: stale element reference: element is not attached to the page document (Session info: chrome=52.0.2743.116) (Driver info: chromedriver=2.22.397933 </code></pre> <p>This is the code:</p> <pre><code>def download_pdf(self): current = self.driver.current_url lista_link_temp = self.driver.find_elements_by_xpath("//*[@href]") for link in lista_link_temp: if "pdf+html" in str(link.get_attribute("href")): tutor = link.get_attribute("href") self.driver.get(str(tutor)) self.driver.get(current) </code></pre> <p>Please help me.. I've just tried lambda, implicit and explicit wait </p> <p>Thanks</p>
1
2016-09-16T21:14:10Z
39,542,565
<p>As soon as you call <code>self.driver.get()</code> in your loop, all the other elements in the list of elements will become stale. Try collecting the <code>href</code> attributes from the elements first, and then visiting them:</p> <pre><code>def download_pdf(self): current = self.driver.current_url lista_link_temp = self.driver.find_elements_by_xpath("//*[@href]") pdf_hrefs = [] # You could do this part with a single line list comprehension too, but would be really long... for link in lista_link_temp: href = str(link.get_attribute("href")) if "pdf+html" in href: pdf_hrefs.append(href) for h in pdf_hrefs: self.driver.get(h) self.driver.get(current) </code></pre>
0
2016-09-17T03:28:26Z
[ "python", "google-chrome", "selenium" ]
How can I create unique non-repeating pair combinations from a list
39,540,161
<p>I am new to computer programming. </p> <p>I want to create successive 2-person teams from an even numbered list of players (32 max) but with no repeats until all possible teams have been formed. </p> <p>For example for 6 players (a thru f) I can generate with itertools.combinations 15 distinct teams. Then I can manually, on paper, in a matrix create 5 sets of 3 unique teams(i.e. [['a','b'],['c','d'], ['e','f']], and similarly ac,bf,de; ae,bc,df; af,bd,ce and ad,be,cf). But I've been unable to write a program (many varied attempts) in python 3.5 to do this. After 5 or fewer iterations I get repeats and some possible teams are not created at all.</p> <p>I did a search but cannot quite discern which solution applies in my specific case.</p>
-3
2016-09-16T21:14:26Z
39,540,410
<p>If all you need is <em>some</em> complete round-robin pairing, then look up solutions with "round-robin tournament schedule". You can likely just use the long-known solution illustrated well on <a href="https://en.wikipedia.org/wiki/Round-robin_tournament" rel="nofollow">Wikipedia</a>.</p> <p>List the players in two rows, half of them in each row, like so:</p> <pre><code>A B C D E F </code></pre> <p>You first pairings are AD, BE, CF. Next, nail <strong>A</strong> in place, and consider the others as a ring:</p> <pre><code>A B C D F E </code></pre> <p>Rotate the ring clockwise one position ...</p> <pre><code>A D B E C F </code></pre> <p>... flatten the lower three into one row again:</p> <pre><code>A D B E F C </code></pre> <p>Your second round pairings are AE, DF, BC. Continue this for a total of five rotations; the last one recovers the original pairings.</p>
0
2016-09-16T21:35:25Z
[ "python", "itertools" ]
How can I create unique non-repeating pair combinations from a list
39,540,161
<p>I am new to computer programming. </p> <p>I want to create successive 2-person teams from an even numbered list of players (32 max) but with no repeats until all possible teams have been formed. </p> <p>For example for 6 players (a thru f) I can generate with itertools.combinations 15 distinct teams. Then I can manually, on paper, in a matrix create 5 sets of 3 unique teams(i.e. [['a','b'],['c','d'], ['e','f']], and similarly ac,bf,de; ae,bc,df; af,bd,ce and ad,be,cf). But I've been unable to write a program (many varied attempts) in python 3.5 to do this. After 5 or fewer iterations I get repeats and some possible teams are not created at all.</p> <p>I did a search but cannot quite discern which solution applies in my specific case.</p>
-3
2016-09-16T21:14:26Z
39,622,880
<p>Here's a typical scenario of what I'm trying to accomplish: Roster of about 26 players Week 1: 18 of 26 show up. I form 9 teams Week 2: 22 of 26 show up. I form 11 teams but no repeats from Week 1 Week 3: 10 of 26 show up. I form 5 teams but no repeats from Week 1 or Week 2, etc.</p> <p>The following works, albeit without the past__teams filter applied (yet), with up to 12 players (takes 25 secs) but beyond 12 is unbearably long, and I expect about 24 players. The program selects the first valid set of teams then ends. With the additional past__teams filter applied - the whole point of the program - it will have to run even longer. Is there an alternate approach to this problem or a way to speed it up considerably?</p> <pre><code>from itertools import combinations, chain import pickle, random '''the'past__teams.py' file was previously created as follows: output = open('past__teams.pkl', 'wb') pickle.dump(past__teams, output) output.close()''' players = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] random.shuffle(players) #load the past__teams file into the program pkl_file = open('past__teams.pkl', 'rb') past__teams = pickle.load(pkl_file) pkl_file.close() all_pair_combinations= [] tonights_teams = [] for c in combinations(players, 2): c = list(c) all_pair_combinations.append(c) def dupe_test(L): if len(L) != len(set(L)): return True return False y = 0 for t in combinations(all_pair_combinations, int(len(players)/2)): t = list(t) tt =list(chain(*t)) y = y +1 if dupe_test(tt) == False: tonights_teams =t break print () print ("Tonights_teams: ",y,tonights_teams) </code></pre>
0
2016-09-21T17:23:00Z
[ "python", "itertools" ]
django runserver can't find django
39,540,328
<p>I'm creating a Django application and I've compiled my own Python then used buildout to manage my dependencies.</p> <p>I'm at the point where I want to run manage.py runserver but I can get an ImportError for django</p> <p>Digging a little deeper it appears that actually it can find django - if I just run manage.py it lists all available commands (so obviously it imported django), but it appears that manage.py runserver calls manage.py again, and I guess this must be calling Python without the overloaded path that buildout provides.</p> <p>So, how can I get manage.py runserver to work with my given setup? Other tutorials I see all say to use virtualenv but I've gone down the path of compiling my own Python so I'd like to stick with that. I've also seen similar questions but they seem to assume the use of system Python, which I am not using. Possibly Django should be installed into my compiled Python but I thought the point of buildout was to avoid the need to do that.</p>
0
2016-09-16T21:27:34Z
39,553,888
<p>So, I think I figured it out. I found a file called django-admin.py in my buildout's bin directory, which eventually led me to add a django section to my buildout.cfg (see <a href="https://pypi.python.org/pypi/djangorecipe" rel="nofollow">https://pypi.python.org/pypi/djangorecipe</a> for details).</p> <p>This created a file called django in my buildout's bin directory, and now running bin/django runserver allows me to view my site locally.</p>
0
2016-09-18T03:48:21Z
[ "python", "django", "buildout" ]
python absolute import of submodule fails
39,540,417
<p>I have seen other posts but did not find answer that worked!</p> <p>File structure</p> <pre><code>my_package/ __init__.py -- empty test/ __init__.py -- empty test1.py </code></pre> <p>Fail</p> <pre><code>from my_package import test test.test1 </code></pre> <p>gives </p> <pre><code>AttributeError: 'module' object has no attribute test </code></pre> <p>Following Passes</p> <pre><code>from my_package.test import test1 # or import my_package.test.test1 from my_package import test # now this works test.tes1 &lt;module 'my_package.test.test1' from ... </code></pre> <p>I have </p> <pre><code> from __future__ import absolute_import </code></pre> <p>in all files, and using python2.7</p>
1
2016-09-16T21:35:53Z
39,541,206
<p>When you import a package (like <code>test</code>), the modules (like <code>test1</code>) are not automatically imported (unless perhaps you put some special code to do so in <code>__init__.py</code>). This is different from importing a module, where the contents of the module are available in the modules namespace. Compare with the Python standard library's <code>xml.etree.ElementTree</code> module:</p> <pre><code>&gt;&gt;&gt; import xml &gt;&gt;&gt; xml.etree Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'etree' &gt;&gt;&gt; from xml import etree &gt;&gt;&gt; etree.ElementTree Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'ElementTree' &gt;&gt;&gt; from xml.etree import ElementTree &gt;&gt;&gt; ElementTree.ElementTree &lt;class 'xml.etree.ElementTree.ElementTree'&gt; </code></pre>
0
2016-09-16T23:05:33Z
[ "python", "python-2.7", "import", "package", "python-import" ]
approximate summation of exponential function in python
39,540,442
<p>I wish to find the approximate sum of exponential function , my code looks like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import math N = input ("Please enter an integer at which term you want to turncate your summation") x = input ("please enter a number for which you want to run the exponential summation e^{x}") exp_sum =0.0 for n in range (0, N): factorial = math.factorial(n) power = x**n nth_term = power/factorial exp_sum = exp_sum + nth_term print exp_sum </code></pre> <p>Now I tested it for a pair of (x, N) = (1,20) and it returns 2.0, I was wondering if my code is right in this context, if it is, then to get e = 2.71..., how many terms should I consider as N? if my code is wrong please help me fix this. </p>
0
2016-09-16T21:38:30Z
39,540,556
<p>Which version of python are you using? The division that finds <code>nth_term</code> gives different results in python 2.x and in version 3.x.</p> <p>It seems like you are using version 2.x. The division you use gives only integer results, so after the first two lines loops (1/factorial(0) + 1/factorial(1)) you are only adding zeros.</p> <p>So either use version 3.x, or replace that line with</p> <pre><code>nth_term = float(power)/factorial </code></pre> <p>Or, as a comment suggests, make python 2.x do division like 3.x by adding the line</p> <pre><code>from __future__ import division </code></pre> <p>at or very near the beginning of the module.</p>
1
2016-09-16T21:48:54Z
[ "python", "exp" ]