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
Log into Google account using Python?
39,540,479
<p>I want to Sign into my Google account using Python but when I print the html results it doesn't show my username. That's how I know it isn't logged in.</p> <p>How do I sign into google using Python? I have seen two popular modules so far for this urllib.request or Requests but none have helped me with logging into the giant Google.</p> <p>Code:</p> <pre><code>import requests # Fill in your details here to be posted to the login form. payload = { 'Email': 'accountemail@gmail.com', 'Passwd': 'accountemailpassword' } # Use 'with' to ensure the session context is closed after use. with requests.Session() as s: p = s.post('https://accounts.google.com/signin/challenge/sl/password', data=payload) # print the html returned or something more intelligent to see if it's a successful login page. print(p.text) </code></pre> <p>Login form info:</p> <pre><code>&lt;input id="Email" name="Email" placeholder="Enter your email" type="email" value="" spellcheck="false" autofocus=""&gt; &lt;input id="Passwd" name="Passwd" type="password" placeholder="Password" class=""&gt; &lt;input id="signIn" name="signIn" class="rc-button rc-button-submit" type="submit" value="Sign in"&gt; </code></pre> <p>When I login the console will give me 4 link to request so I'm not sure if I'm even using the right URL.</p> <pre><code>Request URL:https://accounts.google.com/signin/challenge/sl/password Request Method:POST Status Code:302 Request URL:https://accounts.google.com/CheckCookie?hl=en&amp;checkedDomains=youtube&amp;checkConnection=youtube%3A503%3A1&amp;pstMsg=1&amp;chtml=LoginDoneHtml&amp;service=youtube&amp;continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dsign_in_button%26app%3Ddesktop%26action_handle_signin%3Dtrue%26next%3D%252F&amp;gidl=CAASAggA Request Method:GET Status Code:302 Request URL:https://accounts.google.com/CheckCookie?hl=en&amp;checkedDomains=youtube&amp;checkConnection=youtube%3A503%3A1&amp;pstMsg=1&amp;chtml=LoginDoneHtml&amp;service=youtube&amp;continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dsign_in_button%26app%3Ddesktop%26action_handle_signin%3Dtrue%26next%3D%252F&amp;gidl=CAASAggA Request Method:GET Status Code:302 request URL:https://www.youtube.com/signin?hl=en&amp;feature=sign_in_button&amp;app=desktop&amp;action_handle_signin=true&amp;next=%2F&amp;auth=xAMUT-baNWvXgWyGYfiQEoYLmGv4RL0ZTB-KgGa8uacdJeruODeKVoxZWwyfd-NezfxB6g. Request Method:GET Status Code:303 </code></pre> <p>I am currently using Python 3.4.2 &amp; don't plan on using google's API.</p>
2
2016-09-16T21:42:16Z
39,540,549
<p>Except by using <a href="http://stackoverflow.com/q/10271110/1658617">oAuth</a> or their API, google has things like captcha and so to prevent bots from brute-forcing and guessing passwords.</p> <p>You can try and trick the user-agent but I still believe it's to vein.</p>
0
2016-09-16T21:48:34Z
[ "python", "python-3.x" ]
Log into Google account using Python?
39,540,479
<p>I want to Sign into my Google account using Python but when I print the html results it doesn't show my username. That's how I know it isn't logged in.</p> <p>How do I sign into google using Python? I have seen two popular modules so far for this urllib.request or Requests but none have helped me with logging into the giant Google.</p> <p>Code:</p> <pre><code>import requests # Fill in your details here to be posted to the login form. payload = { 'Email': 'accountemail@gmail.com', 'Passwd': 'accountemailpassword' } # Use 'with' to ensure the session context is closed after use. with requests.Session() as s: p = s.post('https://accounts.google.com/signin/challenge/sl/password', data=payload) # print the html returned or something more intelligent to see if it's a successful login page. print(p.text) </code></pre> <p>Login form info:</p> <pre><code>&lt;input id="Email" name="Email" placeholder="Enter your email" type="email" value="" spellcheck="false" autofocus=""&gt; &lt;input id="Passwd" name="Passwd" type="password" placeholder="Password" class=""&gt; &lt;input id="signIn" name="signIn" class="rc-button rc-button-submit" type="submit" value="Sign in"&gt; </code></pre> <p>When I login the console will give me 4 link to request so I'm not sure if I'm even using the right URL.</p> <pre><code>Request URL:https://accounts.google.com/signin/challenge/sl/password Request Method:POST Status Code:302 Request URL:https://accounts.google.com/CheckCookie?hl=en&amp;checkedDomains=youtube&amp;checkConnection=youtube%3A503%3A1&amp;pstMsg=1&amp;chtml=LoginDoneHtml&amp;service=youtube&amp;continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dsign_in_button%26app%3Ddesktop%26action_handle_signin%3Dtrue%26next%3D%252F&amp;gidl=CAASAggA Request Method:GET Status Code:302 Request URL:https://accounts.google.com/CheckCookie?hl=en&amp;checkedDomains=youtube&amp;checkConnection=youtube%3A503%3A1&amp;pstMsg=1&amp;chtml=LoginDoneHtml&amp;service=youtube&amp;continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dsign_in_button%26app%3Ddesktop%26action_handle_signin%3Dtrue%26next%3D%252F&amp;gidl=CAASAggA Request Method:GET Status Code:302 request URL:https://www.youtube.com/signin?hl=en&amp;feature=sign_in_button&amp;app=desktop&amp;action_handle_signin=true&amp;next=%2F&amp;auth=xAMUT-baNWvXgWyGYfiQEoYLmGv4RL0ZTB-KgGa8uacdJeruODeKVoxZWwyfd-NezfxB6g. Request Method:GET Status Code:303 </code></pre> <p>I am currently using Python 3.4.2 &amp; don't plan on using google's API.</p>
2
2016-09-16T21:42:16Z
39,541,371
<p>This will get you logged in:</p> <pre><code>from bs4 import BeautifulSoup import requests form_data={'Email': 'you@gmail.com', 'Passwd': 'your_password'} post = "https://accounts.google.com/signin/challenge/sl/password" with requests.Session() as s: soup = BeautifulSoup(s.get("https://mail.google.com").text) for inp in soup.select("#gaia_loginform input[name]"): if inp["name"] not in form_data: form_data[inp["name"]] = inp["value"] s.post(post, form_data) html = s.get("https://mail.google.com/mail/u/0/#inbox").content </code></pre> <p>If you save and open the html in a browser, you will see the <code>Loading you@gmail.com…</code>, you would need Javascript to actually load the page. You can further verify by putting in a bad password, if you do you will see the html of the login page again.</p> <p>You can see in your browser a lot more gets posted than you have provided, the values are contained in the <code>gaia_loginform</code>.</p> <pre><code>&lt;form novalidate method="post" action="https://accounts.google.com/signin/challenge/sl/password" id="gaia_loginform"&gt; &lt;input name="Page" type="hidden" value="RememberedSignIn"&gt; &lt;input type="hidden" name="GALX" value="5r_aVZgnIGo"&gt; &lt;input type="hidden" name="gxf" value="AFoagUUk33ARYpIRJqwrADAIgtChEXMHUA:33244249"&gt; &lt;input type="hidden" id="_utf8" name="_utf8" value="&amp;#9731;"/&gt; &lt;input type="hidden" name="bgresponse" id="bgresponse" value="js_disabled"&gt; &lt;input type="hidden" id="pstMsg" name="pstMsg" value="0"&gt; &lt;input type="hidden" id="dnConn" name="dnConn" value=""&gt; &lt;input type="hidden" id="checkConnection" name="checkConnection" value=""&gt; &lt;input type="hidden" id="checkedDomains" name="checkedDomains" value="youtube"&gt; </code></pre> <p>I am obviously not going to share my email or password but you can I have my email stored in a variable <em>my_mail</em> below, you can see when we test for it that it is there:</p> <pre><code>In [3]: from bs4 import BeautifulSoup In [4]: import requests In [5]: post = "https://accounts.google.com/signin/challenge/sl/password" In [6]: with requests.Session() as s: ...: soup = BeautifulSoup(s.get("https://accounts.google.com/ServiceLogin?elo=1").text, "html.parser") ...: for inp in soup.select("#gaia_loginform input[name]"): ...: if inp["name"] not in form_data: ...: form_data[inp["name"]] = inp["value"] ...: s.post(post, form_data) ...: In [7]: my_mail in s.get("https://mail.google.com/mail/u/0/#inbox").text Out[7]: True </code></pre>
1
2016-09-16T23:27:31Z
[ "python", "python-3.x" ]
How to return result from a function in Django html form?
39,540,522
<p>Basically I have this form right here</p> <pre><code>&lt;form method="POST" action="."&gt; &lt;input type="text" name="fcal" value="{{F}}" /&gt; &lt;p&gt; &lt;input type="submit" name="fibo" value="Fibonacci" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>I would like the user to input a number and after that this number to be calculated and printed in a Fibonacci sequence.</p> <p>This is my Fibonacci function</p> <pre><code>def fibo(n): if n == 0: return 0 elif n == 1: return 1 else: result = fibo(n - 1) + fibo(n - 2) return result </code></pre> <p>I believe my problem is coming from the views.py file because I am not sure how to create the result to be rendered back.</p> <pre><code>from django.template import Context, loader, RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.forms import ModelForm from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseNotFound import fibonacci def fibocal(request): if request.method == 'POST': fb = request.POST['fcal'] cal = fibonacci.fibo(fb) return render_to_response('fibb/fibb.html', context_instance=RequestContext(request, cal)) else: print('Wrond input type') </code></pre> <p>I would highly appreciate if someone can at least explain how to get the result from a function and print it out on the same page.</p>
0
2016-09-16T21:46:34Z
39,540,582
<p>your html file</p> <pre><code> &lt;form method="POST" action="."&gt; &lt;input type="text" name="fcal" value="{{F}}" /&gt; &lt;p&gt; &lt;input type="submit" name="fibo" value="Fibonacci" /&gt; &lt;/p&gt; &lt;/form&gt; {% if cal %} Your Fibonacci answer is {{cal}} {% endif %} </code></pre> <p>Your view:</p> <pre><code>def fibocal(request): if request.method == 'POST': fb = request.POST['fcal'] cal = fibonacci.fibo(fb) return render(request, 'fibb/fibb.html', {'cal': cal}) else: return render(request, 'fibb/fibb.html', {}) </code></pre> <p>This will do the trick</p>
0
2016-09-16T21:51:31Z
[ "python", "django" ]
Self delete page in wx.Notebook
39,540,563
<p>I want to dynamically create and delete pages in a notebook. In the main class I successfully create and add pages with a button. The pages are a separate class of course, and have a button inside. I know I can put the button outside the notebook and delete them from the main class but I want to use page's own button to self destruct the whole page as it won't be needed any more.</p> <p>Sorry I don't post any code but I'm posting from my cellphone. Also it seems to be a question not so specific to need a minimal working example.</p>
0
2016-09-16T21:49:48Z
39,541,649
<p>As you've guessed, care needs to be taken when destroying UI objects from their own event handlers. Not only is the current event handler still active, but there may be other pending events that are still in the queue, and if the target object has been destroyed when they are delivered then you can get a crash.</p> <p>The best thing to do is to defer the destruction until after the current and possible pending event handlers have been completed and there is nothing waiting to be done on the UI object except for the destruction that you want to do. And the best way to do that is to use <code>wx.CallAfter</code>. It will call a function with parameters that you give it the next time the the event loop empties, so implicitly there is not anything else waiting to be done or sent to the UI object in question.</p> <p>In your case it would be safe to do things like immediately remove the page from the notebook, and hide the page window. Then use <code>wx.CallAfter</code> to call some function (perhaps in the notebook class) which calls the page window's <code>Destroy</code> method and does any other cleanup that is necessary. The reason I suggest splitting these two sets of tasks is not because it will take a long time for the function to be called, but in some cases it may be long enough to flicker momentarily in a transitory state, so the appearance is less smooth for the users.</p>
0
2016-09-17T00:14:34Z
[ "python", "wxpython", "wxnotebook" ]
Django get info in the same web without showing pk in url
39,540,566
<p>I'm trying to get info from a model but without moving the url, let me explain by myself when I access to for example:</p> <p>/list It shows the info and if I just make a click in there i can access to the complete info of this user, or book or something and the url change to detail/8/</p> <p>Is there any way to get the information without show the id of the database in the url?</p> <p>for example list/</p> <p>I have some code but I d no have any idea how to do it, I hope you guys can help me.</p> <p>urls:</p> <pre><code>url(r'^detalle/(?P&lt;pk&gt;[0-9]+)/$', views.detalle_id, name="detalle_id"), url(r'^detalle/(?P&lt;nombre&gt;.*)/$', views.detalle_nombre), </code></pre> <p>views:</p> <pre><code>def detalle_id(request, pk): detalle = Pregunta.objects.get(pk=pk) Pregunta.objects.filter(id=pk).update(comentario='1') return render(request, 'detalle.html', {'detalle': detalle}) def detalle_nombre(request, nombre): detalle = Pregunta.objects.get(nombre=nombre) return render(request, 'detalle.html', {'detalle': detalle}) def lista(request): listadb = Pregunta.objects.all() return render(request, 'lista.html', {'listadb':listadb}) </code></pre> <p><strong>Edit: from comments:</strong></p> <p>The reason of this is because I'm trying to make a client database and the users who will use the database will have access to some of them but not of all the data base so if a user set for example domain.com/89 will see the information or can edit of client No 89, this I have a lot reasons why I'm trying to do it like this. Believe me I need o get information on click but accessing without change the url just by click. is it possible ? do you have any idea </p>
0
2016-09-16T21:50:04Z
39,541,831
<p>If you are trying to create an 'unguessable' url for each book or other item in your database to stop unauthorized access, you are on the wrong track. Unguessable URLs can and will be guessed and people who shouldn't see or edit them, will edit them.</p> <p>At the very least you should check if the user is authenticated.</p> <pre><code>if request.user.is_authenticated(): </code></pre> <p>But this only tells you if the user is logged in or an anonymous user. To find out if the user is authorized to edit, you will need to add some information to the models.</p> <pre><code>class Pregunta(models.Model): .... owner = models.ForiegnKey(User) </code></pre> <p>then do an additional test to find out if the ownership is correct.</p> <p>getting back to unguessable URLS, if you don't want to use slugs, you can use a non sequential primary key: <a href="http://stackoverflow.com/a/37605582/267540">http://stackoverflow.com/a/37605582/267540</a></p> <p>This is usefull if you don't want to reveal to the user how many items exists in your database and which item came first.</p>
2
2016-09-17T00:46:43Z
[ "python", "django", "django-views" ]
Rename CSV File Headers using Dynamic String in Python
39,540,579
<p>Below is the CSV file structure that I have,</p> <pre><code>ITEM | ID | SET | COUNT | ------ | ------ |------ | ------ | Value | 44000001005 | 0 | 24 | Value | 10000000019659 | 0 | 29 | Value | 10000000019659 | 1 | 5 | </code></pre> <p>I want to Dynamically take an input from the user to edit the header, So if I assume that I have taken "Edit_" as input from the user, my resultant CSV file would look like below,</p> <pre><code>EDIT_ITEM | EDIT_ID | EDIT_SET | EDIT_COUNT | ------------| ---------------|----------- | ------------| Value | 44000001005 | 0 | 24 | Value | 10000000019659 | 0 | 29 | Value | 10000000019659 | 1 | 5 | </code></pre> <p>So each header value is to be appended by the user input "Edit_". I could manually do this using "w.writerow", but not sure how to dynamically append the user input. </p> <p>I am relatively new to Python, tried to go through a lot of answers here on Stack Overflow but couldn't get anything that could work for me. I would appreciate any guidance for this issue. </p> <p>Thank you!</p>
0
2016-09-16T21:51:22Z
39,540,835
<p>Use the csv module to read and edit the header then write all the rows back to the new file</p> <pre><code>import csv with open("input.csv") as f, open("output.csv", "wb") as o: ui = raw_input("Enter user input: ") reader = csv.reader(f) header = reader.next() writer = csv.writer(o) new_header = map(lambda x:"{}{}".format(ui,x) ,header) writer.writerow(new_header) writer.writerows(reader) </code></pre>
0
2016-09-16T22:16:19Z
[ "python", "csv" ]
How to apply decorators to Cython cpdef functions
39,540,599
<p>I've been playing around with Cython lately and I came across this error when applying a decorator to a Cython function</p> <p><code>Cdef functions/classes cannot take arbitrary decorators</code></p> <p>Here is the code I was tinkering with:</p> <pre><code>import functools def memoize(f): computed = {} @functools.wraps(f) def memoized_f(main_arg, *args, **kwargs): if computed.get(main_arg): return computed[main_arg] computed[main_arg] = f(main_arg, *args, **kwargs) return computed[main_arg] return memoized_f @memoize cpdef int fib(int n): return 1 if n &lt; 2 else fib(n - 1) + fib(n - 2) </code></pre> <p>The error suggests that cdef functions can only take <em>certain</em> decorators. Is it possible to write your own decorators that you can apply to cdef functions?</p> <hr> <p>EDIT: For future readers:</p> <p>The <code>g = plus_one(_g)</code> trick mentioned in @DavidW's answer <em>sort of</em> works. It does not work with recursion. e.g. doing <code>fib = memoize(fib)</code> in my example code does not memoize the recursive calls to fib, although it does memoize the top-level call. i.e. calling <code>fib(5)</code> will memoize the result of the <code>fib(5)</code> call, but it will <em>not</em> memoize the recursive calls (i.e. <code>fib(4), fib(3), fib(2), fib(1)</code>)</p> <p>As @DavidW points out, <code>cdef, cpdef</code> functions are fully determined at compile time; the decoration is a runtime thing and does not update the actual function.</p>
3
2016-09-16T21:53:14Z
39,544,561
<p><strong>No</strong> - you can't easily write decorators for <code>cdef</code> functions. The decorators <code>cdef</code> functions take are things like <code>cython.boundscheck</code> which control the Cython code generation rather than user generated functions.</p> <p>The main difference between a <code>cdef</code> function and a <code>def</code> function is that a <code>cdef</code> function has a C interface while a <code>def</code> function becomes a Python callable so can be used from Python (but calling it is slightly less efficient because the arguments have to be passed in terms of PyObjects). [The inside of <em>both</em> a <code>cdef</code> and <code>def</code> function is compiled by Python so the only performance difference comes from the calling overhead] </p> <p>The usual use of a decorator is to take an arbitrary Python callable and make some modification to it. For example</p> <pre><code>def plus_one(f): def wrapper(*args,**kwargs): return f(*args,**kwargs) + 1 return wrapper </code></pre> <p>now try to use it on a cdef function</p> <pre><code>cdef int g(double x, double y): # some implementation... </code></pre> <p>The first problem is that g is translated to C code like <code>int g(double x, double y)</code> which can be represented by a function pointer but not as an arbitrary Python callable like <code>plus_one</code> expects. Second, <code>wrapper</code> has no way of knowing (from a C function pointer) what <code>g</code>s arguments are called (can't do <code>**kwargs</code>) or any easy way of doing the <code>*args</code> expansion.</p> <p>You can make something like a decorator by taking a specific function pointer type and returning a Python callable:</p> <pre><code>cdef plus_one(int (*f)(double, double): def wrapper(double x, double y): return f(x, y) + 1 return wrapper cdef int _g(double x, double y): # some implementation g = plus_one(_g) # kind of like a decorator </code></pre> <p><em>However,</em> you've lost the whole benefit of using a <code>cdef</code> function since <code>g</code> is now a generic Python callable with all the overhead that goes with it.</p> <hr> <p>Addendum: an alternative way of putting it is that decorators are a runtime Python feature (usually run at module import). <code>cdef</code> functions are a compile-time C feature. While it probably wouldn't be impossible to implement something like "compile-time decorators" it would be a pretty significant change to Cython.</p>
2
2016-09-17T08:18:31Z
[ "python", "cython", "cythonize" ]
Python sqlite3 'executemany' not successfully updating my database
39,540,600
<p>I'm trying to extract a column from my database, apply a transformation, and create a new column with the results. </p> <p>I ultimately want to save the local variable 'new_proba' (which has a length of 740, the same length as my database) as a new column called 'predict_proba_tplus1'. From reading <a href="http://stackoverflow.com/questions/15688462/how-to-update-entire-column-with-values-in-list-using-sqlite3">this thread</a>, I've learned that the UPDATE function expects a tuple. </p> <p>I created an 'IDs' list which matches the indexID column in the database and then zipped it with 'new_proba' to create the tuple which outputs '(0.56298709097028454, 0), (0.54392926856501334, 1),' etc.</p> <p>The function below doesn't actually throw any error, but it only creates the column 'predict_proba_tplus1' and doesn't fill in any values which I'd expect c.executemany() to do - I'm left with a new column filled with NULL values. It makes me think there's something wrong with the WHERE statement - i.e. it's not matching the indexID column to the IDs variable for some reason, despite the numbers being the same.</p> <p>Any insight would be hugely appreciated. </p> <pre><code>def update_class_proba(path): conn = sqlite3.connect(path) c = conn.cursor() cursor = c.execute('SELECT text, indexID FROM reuters_test_X') all_rows = cursor.fetchall() X = vect.transform(x[0] for x in all_rows) new_proba = list(clf.predict_proba(X)[:,1]) IDs = list(np.arange(0, 740, 1)) new_proba_tuple = list(zip(new_proba,IDs)) c.execute('ALTER TABLE reuters_test_X ADD COLUMN predict_proba_tplus1 REAL') c.executemany('UPDATE reuters_test_X SET predict_proba_tplus1=? WHERE indexID=?', new_proba_tuple) conn.commit() conn.close() </code></pre>
0
2016-09-16T21:53:33Z
39,598,087
<p>Those values aren't plain <code>float</code>; they're <code>numpy.float64</code>, which the database can't handle.</p> <p>Convert your values to plain <code>float</code> and <code>int</code> like this:</p> <pre><code>new_proba = list(float(z) for z in clf.predict_proba(X)[:,1]) IDs = list(int(zz) for zz in np.arange(0, 740, 1)) </code></pre>
0
2016-09-20T15:26:48Z
[ "python", "sqlite3", "sql-update", "executemany" ]
Django - TypeError: 'genre' is an invalid keyword argument for this function
39,540,634
<p>I’m using Django and I'm having a problem running a Python script that uses Django models</p> <p>The script that I'm using takes data from an api and loads it into my database, however, I'm getting a TypeError while trying to run it:</p> <pre><code>&gt;&gt;&gt; exec(open('load_from_api.py').read()) Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\commands\shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\commands\shell.py", line 61, in run_shell raise ImportError ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 465, in get_or_create return self.get(**lookup), False File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 387, in get self.model._meta.object_name movies.models.DoesNotExist: Movie matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "&lt;string&gt;", line 24, in &lt;module&gt; File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\ma nager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 467, in get_or_create return self._create_object_from_params(lookup, params) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 499, in _create_object_from_params obj = self.create(**params) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 399, in create obj = self.model(**kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\ba se.py", line 443, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % li st(kwargs)[0]) TypeError: 'genre' is an invalid keyword argument for this function </code></pre> <p><strong>Movie model:</strong></p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=511) tmdb_id = models.IntegerField(null=True, blank=True) release = models.DateField(null=True, blank=True) poster = models.TextField(max_length=500) backdrop = models.TextField(max_length=500, null=True, blank=True) rating = models.FloatField(null=True, blank=True) description = models.TextField() director = models.ManyToManyField(Person, related_name="directed_movies") actors = models.ManyToManyField(Person, related_name="acted_movies") genre = models.ManyToManyField(Genre) </code></pre> <p>and a snippet from the script i'm using:</p> <pre><code>for movie in results: data = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], genre=movie['genre_ids'], description=movie['overview'], backdrop=movie['backdrop_path'], poster=movie['poster_path']) </code></pre> <p>movie['genre_ids'] come in a list form: [42, 67, 80] or [12, 109] for example.</p> <p>I'm not quiet sure where I'm wrong, any help would be appreciated!</p> <p><strong>Edit:</strong></p> <p>When i changed my script to this:</p> <pre><code>for movie in results: data = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], description=movie['overview'], backdrop=movie['backdrop_path'], poster=movie['poster_path']) genres = [] genres = movie['genre_ids'] for gnre in genres: data.genre.add(gnre) </code></pre> <p>It gave me the following error:</p> <pre><code>AttributeError: 'tuple' object has no attribute 'genre' </code></pre>
0
2016-09-16T21:56:55Z
39,541,140
<p>try this:</p> <pre><code>for movie in results: obj, data = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], description=movie['overview'], backdrop=movie['backdrop_path'], poster=movie['poster_path']) genre_ids = movie['genre_ids'] genres = Genre.objects.filter(id__in=genre_ids) obj.genre.add(*genres) </code></pre>
0
2016-09-16T22:56:22Z
[ "python", "django" ]
Django - TypeError: 'genre' is an invalid keyword argument for this function
39,540,634
<p>I’m using Django and I'm having a problem running a Python script that uses Django models</p> <p>The script that I'm using takes data from an api and loads it into my database, however, I'm getting a TypeError while trying to run it:</p> <pre><code>&gt;&gt;&gt; exec(open('load_from_api.py').read()) Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\commands\shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\commands\shell.py", line 61, in run_shell raise ImportError ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 465, in get_or_create return self.get(**lookup), False File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 387, in get self.model._meta.object_name movies.models.DoesNotExist: Movie matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "&lt;string&gt;", line 24, in &lt;module&gt; File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\ma nager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 467, in get_or_create return self._create_object_from_params(lookup, params) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 499, in _create_object_from_params obj = self.create(**params) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\qu ery.py", line 399, in create obj = self.model(**kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\ba se.py", line 443, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % li st(kwargs)[0]) TypeError: 'genre' is an invalid keyword argument for this function </code></pre> <p><strong>Movie model:</strong></p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=511) tmdb_id = models.IntegerField(null=True, blank=True) release = models.DateField(null=True, blank=True) poster = models.TextField(max_length=500) backdrop = models.TextField(max_length=500, null=True, blank=True) rating = models.FloatField(null=True, blank=True) description = models.TextField() director = models.ManyToManyField(Person, related_name="directed_movies") actors = models.ManyToManyField(Person, related_name="acted_movies") genre = models.ManyToManyField(Genre) </code></pre> <p>and a snippet from the script i'm using:</p> <pre><code>for movie in results: data = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], genre=movie['genre_ids'], description=movie['overview'], backdrop=movie['backdrop_path'], poster=movie['poster_path']) </code></pre> <p>movie['genre_ids'] come in a list form: [42, 67, 80] or [12, 109] for example.</p> <p>I'm not quiet sure where I'm wrong, any help would be appreciated!</p> <p><strong>Edit:</strong></p> <p>When i changed my script to this:</p> <pre><code>for movie in results: data = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], description=movie['overview'], backdrop=movie['backdrop_path'], poster=movie['poster_path']) genres = [] genres = movie['genre_ids'] for gnre in genres: data.genre.add(gnre) </code></pre> <p>It gave me the following error:</p> <pre><code>AttributeError: 'tuple' object has no attribute 'genre' </code></pre>
0
2016-09-16T21:56:55Z
39,541,172
<blockquote> <p>get_or_create()</p> <p>Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.</p> </blockquote> <p>so instead of:</p> <pre><code>data = Movie.objects.get_or_create(title=movie['title'], ....) </code></pre> <p>it should be:</p> <pre><code>data, created = Movie.objects.get_or_create(title=movie['title'], ....) </code></pre>
0
2016-09-16T22:59:33Z
[ "python", "django" ]
Remove edges from a graph using networkx
39,540,705
<p>I am trying to convert a <code>DiGraph</code> into n-ary tree and displaying the nodes in level order or BFS. My tree is similar to this, but much larger, for simplicity using this example: </p> <pre><code>G = networkx.DiGraph() G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')]) G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')]) G.add_edges_from([('n2', 'n21'), ('n2', 'n22'), ('n', 'n22')]) G.add_edges_from([('n13', 'n131'), ('n22', 'n221'), ('n', 'n131'), ('n', 'n221')]) </code></pre> <p>Tree: borrowed the data from this <a href="http://stackoverflow.com/questions/21866902/networkx-graph-searches-dfs-successors-vs-dfs-predecessors">question</a> and modified it appropriately:</p> <pre><code>n----&gt;n1---&gt;n11 | |---&gt;n12 | |---&gt;n13 |-----------|---&gt;n131 |---&gt;n2 | |----&gt;n21 | |----&gt;n22 |------------|---&gt;n221 |---&gt;n3 </code></pre> <p>Now my real data set is much more complicated with hundreds of node, to keep it simple I have used the above diagram.</p> <p>I want remove the unnecessary edges from the tree, such that if a parent has an edge to the child, which has another edge to a grandchild AND the parent also has an edge to the grandchild. I simple want to remove the edge between the grandchild and the parent (root), since this is complicating my graph. ex: I want to remove <code>('n', 'n131')</code> and <code>('n', 'n221')</code> from the above graph. What is the best way to achieve this. </p>
1
2016-09-16T22:02:28Z
39,541,027
<p>Looks like you want to find the minimum spanning tree of the graph G, you can use Prim's or Kruskal's algorithm's implementation: here is one from scipy: <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree.html" rel="nofollow">http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree.html</a></p>
0
2016-09-16T22:42:14Z
[ "python", "algorithm", "networkx" ]
How to make xticks evenly spaced despite their value?
39,540,730
<p>I am trying to generate a plot with x-axis being a geometric sequence while the y axis is a number between 0.0 and 1.0. My code looks like this:</p> <pre><code>form matplotlib import pyplot as plt plt.xticks(X) plt.plot(X,Y) plt.show() </code></pre> <p>which generates a plot like this:</p> <p><a href="http://i.stack.imgur.com/Ia6Wf.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Ia6Wf.jpg" alt="My plot"></a></p> <p>As you can see, I am explicitly setting the x-axis ticks to the ones belonging to the geometric sequence. </p> <p>My question:Is it possible to make x-ticks evenly spaced despite their value, as the initial terms of the sequence are small, and crowded together. Kind of like logarithmic scale, which would be ideal if dealing with powers of a base, but not for a geometric sequence, I think, as is the case here.</p>
0
2016-09-16T22:04:50Z
39,545,860
<p>You can do it by plotting your variable as a function of the "natural" variable that parametrizes your curve. For example:</p> <pre><code>n = 12 a = np.arange(n) x = 2**a y = np.random.rand(n) fig = plt.figure(1, figsize=(7,7)) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) ax1.plot(x,y) ax1.xaxis.set_ticks(x) ax2.plot(a, y) #we plot y as a function of a, which parametrizes x ax2.xaxis.set_ticks(a) #set the ticks to be a ax2.xaxis.set_ticklabels(x) # change the ticks' names to x </code></pre> <p>which produces:</p> <p><a href="http://i.stack.imgur.com/LP3UM.png" rel="nofollow"><img src="http://i.stack.imgur.com/LP3UM.png" alt="enter image description here"></a></p>
0
2016-09-17T10:41:20Z
[ "python", "matplotlib", "plot" ]
How do I use JWT with grpc?
39,540,731
<p>I am trying to get my head wrapped around <a href="http://www.grpc.io/docs/guides/auth.html#using-client-side-ssltls" rel="nofollow">grpc authentication</a>. From the looks of the examples, it looks like grpc supports ssl/tls and google tokens...</p> <p>I've also looked at <a href="https://jwt.io/" rel="nofollow">json web tokens</a> as a means of authentication.</p> <p>I'm not sure if this is even the correct way of thinking about this, but how would I use JWT in conjunction with grpc?</p> <p>Is the JWT the "token" that gets used with the oauth2 example?</p> <p>Does it relate to the 'roots.pem' file that is being opened?</p> <p>I feel like I know very little about authentication/tokens. I've tried searching for python examples that involve grpc and JWT, and it has been a mostly fruitless search.</p> <p>Am I thinking about this the wrong way?</p>
0
2016-09-16T22:04:55Z
39,541,040
<p>The normal JWT approach uses service account credentials which are provided by the environment in a well-known location. This is what "Google Default Credentials" are in the examples. These are by far the easiest to get working, and have the best security and performance characteristics.</p> <p>OAuth2 is also supported, by using a OAuth token. This is useful for things like 3-legged OAuth or integrating into a pre-existing application that is using tokens directly.</p> <p><code>roots.pem</code> is something different. That's for TLS-based authentication with custom Certificate Authorities.</p> <p>That said, there is currently no JWT example in Python. Please follow <a href="https://github.com/grpc/grpc/issues/6860" rel="nofollow">the open issue</a>. The example today uses service account credentials, but then converts it to a normal OAuth token.</p>
1
2016-09-16T22:44:06Z
[ "python", "authentication", "token", "jwt", "grpc" ]
Google Cloud Vision - Numbers and Numerals OCR
39,540,741
<p>I've been trying to implement an OCR program with Python that reads numbers with a specific format, XXX-XXX. I used Google's Cloud Vision API Text Recognition, but the results were unreliable. Out of 30 high-contrast 1280 x 1024 bmp images, only a handful resulted in the correct output, or at least included the correct output in the results. The program tends to omit some numbers, output in non-English languages or sneak in a few special characters.</p> <p>The goal is to at least output the correct numbers consecutively, doesn't matter if the results are sprinkled with other junk. Is there a way to help the program recognize numbers better, for example limit the results to a specific format, or to numbers only?</p>
11
2016-09-16T22:06:03Z
39,680,724
<p>At this moment it is not possible to add constraints or to give a specific expected number format to Vision API requests, as mentioned <a href="http://stackoverflow.com/questions/36125830/google-cloud-vision-text-detection-only-on-digits">here</a> (by the Project Manager of Cloud Vision API).</p> <p>You can also check all the possible request parameters (in the <a href="https://cloud.google.com/vision/reference/rest/v1/images/annotate#AnnotateImageRequest" rel="nofollow">API reference</a>), none indicating anything to specify number format. Currently only options to:</p> <ul> <li>latLongRect: specify location of the image</li> <li>languageHints: indicating the expected language for <code>text_detection</code> (list of supported languages <a href="https://cloud.google.com/translate/v2/translate-reference#supported_languages" rel="nofollow">here</a>)</li> </ul> <p>I assume you already checked out the multiple responses (with different included image regions) to see if you could reconstruct the text using the location of different digits? </p> <p>Note that the Vision API and <code>text_detection</code> is not optimized for your data specifically, if you would have a lot of annotated data, it is also an option to actually build your own model using Tensorflow. <a href="https://matthewearl.github.io/2016/05/06/cnn-anpr/" rel="nofollow">This blogpost</a> explains a system setup to detect number plates (with a specific number format). All the code is available on <a href="https://github.com/matthewearl/deep-anpr" rel="nofollow">Github</a> and the problem seems very related to yours.</p>
3
2016-09-24T20:33:40Z
[ "python", "ocr", "google-cloud-platform", "google-cloud-vision", "text-recognition" ]
Google Cloud Vision - Numbers and Numerals OCR
39,540,741
<p>I've been trying to implement an OCR program with Python that reads numbers with a specific format, XXX-XXX. I used Google's Cloud Vision API Text Recognition, but the results were unreliable. Out of 30 high-contrast 1280 x 1024 bmp images, only a handful resulted in the correct output, or at least included the correct output in the results. The program tends to omit some numbers, output in non-English languages or sneak in a few special characters.</p> <p>The goal is to at least output the correct numbers consecutively, doesn't matter if the results are sprinkled with other junk. Is there a way to help the program recognize numbers better, for example limit the results to a specific format, or to numbers only?</p>
11
2016-09-16T22:06:03Z
39,809,660
<p>I am unable to tell you why this works, perhaps it has to do with how the language is read, o vs 0, l vs 1, etc. But whenever I use OCR and I am specifically looking for numbers, I have read to set the detection language to "Korean". It works exceptionally well for me and has influenced the accuracy greatly. </p>
1
2016-10-01T17:43:03Z
[ "python", "ocr", "google-cloud-platform", "google-cloud-vision", "text-recognition" ]
How to rename the sheet name in the spread-sheet using Python?
39,540,789
<p>Have a scenario where I wanted to change the name of the "Sheet" in the spread-sheet.</p> <p>a. I tried created a spread-sheet saying <code>ss = Workbook()</code>. Think, this is creating the spread-sheet with a sheet named "Sheet"</p> <p>b. I tried changing the name of the sheet using the below format, </p> <pre><code>ss_sheet = ss.get_sheet_by_name('Sheet') ss_sheet.Name = 'Fruit' </code></pre> <p>But then the above step is not changing the sheet name as required. Is there anything wrong in the above step ? Kindly comment on the same.</p> <p>Thanks</p>
1
2016-09-16T22:10:44Z
39,552,011
<p>You can do this by doing the following:</p> <pre><code>import openpyxl ss=openpyxl.load_workbook("file.xlsx") #printing the sheet names ss_sheet = ss.get_sheet_by_name('Sheet') ss_sheet.title = 'Fruit' ss.save("file.xlsx") </code></pre> <p>This works for me. Hope this helps.</p>
0
2016-09-17T21:40:49Z
[ "python", "python-2.7" ]
I am trying to make a lcd program so that all the numbers are printed side by side and its not working
39,540,902
<p>I am trying to print out ascii numbers side by side in python after the previous number is printed. If I put a comma after the last line in the function only the top part of the next number is printed.</p> <pre><code>def zero(): print " __ " print "| |" print "|__|" def one(): print " " print " |" print " |" def two(): print " __ " print " __|" print "|__ " def three(): print " __ " print " __|" print " __|" def four(): print "|_|" print " |" def five(): print " __ " print "|__ " print " __|" def six(): print " __ " print "|__ " print "|__|" def seven(): print " __ " print " |" print " |" def eight(): print " __ " print "|__|" print "|__|" def nine(): print " __ " print "|__|" print " |" x = raw_input("Type the number you would like printed: ") a = list(x) for x in a: if x == '1': one(), elif x == '2': two(), elif x == '3': three(), elif x == '4': four(), elif x == '5': five(), elif x == '6': six(), elif x == '7': seven(), elif x == '8': eight(), elif x == '9': nine(), elif x == '0': zero(), elif x == 'Quit': break else: print "Number not entered" </code></pre>
1
2016-09-16T22:24:27Z
39,540,967
<p>This code prints three lines of output:</p> <pre><code>print " __ " print "|__|" print " |" </code></pre> <p>One that is printed, there is no good way to go back up and print the next number. </p> <p>The solution is to print the first line of each character, then the second line of each character etc...</p> <p>So, to print 98, instead of:</p> <pre><code>print " __ " # 9, row 1 print "|__|" # 9, row 2 print " |" # 9, row 3 print " __ " # 8, row 1 print "|__|" # 8, row 2 print "|__|" # 8, row 3 </code></pre> <p>You have to:</p> <pre><code>print " __ ", # 9, row 1 print " __ ", # 8, row 1 print print "|__|", # 9, row 2 print "|__|", # 8, row 2 print print " |", # 9, row 3 print "|__|", # 8, row 3 print </code></pre> <p>Note that I added a comma after each line, so it does not make a line break. Then I added a line break (empty print) once for each line, after all characters.</p> <p>Now, to print any number, you'll have to go through all characters three times: once for each line...</p>
1
2016-09-16T22:33:06Z
[ "python", "python-2.7" ]
I am trying to make a lcd program so that all the numbers are printed side by side and its not working
39,540,902
<p>I am trying to print out ascii numbers side by side in python after the previous number is printed. If I put a comma after the last line in the function only the top part of the next number is printed.</p> <pre><code>def zero(): print " __ " print "| |" print "|__|" def one(): print " " print " |" print " |" def two(): print " __ " print " __|" print "|__ " def three(): print " __ " print " __|" print " __|" def four(): print "|_|" print " |" def five(): print " __ " print "|__ " print " __|" def six(): print " __ " print "|__ " print "|__|" def seven(): print " __ " print " |" print " |" def eight(): print " __ " print "|__|" print "|__|" def nine(): print " __ " print "|__|" print " |" x = raw_input("Type the number you would like printed: ") a = list(x) for x in a: if x == '1': one(), elif x == '2': two(), elif x == '3': three(), elif x == '4': four(), elif x == '5': five(), elif x == '6': six(), elif x == '7': seven(), elif x == '8': eight(), elif x == '9': nine(), elif x == '0': zero(), elif x == 'Quit': break else: print "Number not entered" </code></pre>
1
2016-09-16T22:24:27Z
39,541,178
<p>funny exercice :)</p> <p>following the comments of @zvone perhaps something like this:</p> <pre><code>def zero(): chars = [" __ "] chars += ["| |"] chars += ["|__|"] return chars def one(): chars = [" "] chars += [" |"] chars += [" |"] return chars def two(): chars = [" __ "] chars += [" __|"] chars += ["|__ "] return chars def three(): chars = [" __ "] chars += [" __|"] chars += [" __|"] return chars def four(): chars = [" "] chars += ["|_|"] chars += [" |"] return chars def five(): chars = [" __ "] chars += ["|__ "] chars += [" __|"] return chars def six(): chars = [" __ "] chars += ["|__ "] chars += ["|__|"] return chars def seven(): chars = [" __ "] chars += [" |"] chars += [" |"] return chars def eight(): chars = [" __ "] chars += ["|__|"] chars += ["|__|"] return chars def nine(): chars = [" __ "] chars += ["|__|"] chars += [" |"] return chars numbers = {'0': zero, '1': one, '2': two, '3': three, '4': four, '5': five, '6': six, '7': seven, '8': eight, '9': nine} def print_lcd(a): for line in zip(*[numbers[num]() for num in a]): print ' '.join(line) else: print "Number not entered" x = raw_input("Type the number you would like printed: ") a = list(x) print_lcd(a) </code></pre>
0
2016-09-16T23:00:20Z
[ "python", "python-2.7" ]
I am trying to make a lcd program so that all the numbers are printed side by side and its not working
39,540,902
<p>I am trying to print out ascii numbers side by side in python after the previous number is printed. If I put a comma after the last line in the function only the top part of the next number is printed.</p> <pre><code>def zero(): print " __ " print "| |" print "|__|" def one(): print " " print " |" print " |" def two(): print " __ " print " __|" print "|__ " def three(): print " __ " print " __|" print " __|" def four(): print "|_|" print " |" def five(): print " __ " print "|__ " print " __|" def six(): print " __ " print "|__ " print "|__|" def seven(): print " __ " print " |" print " |" def eight(): print " __ " print "|__|" print "|__|" def nine(): print " __ " print "|__|" print " |" x = raw_input("Type the number you would like printed: ") a = list(x) for x in a: if x == '1': one(), elif x == '2': two(), elif x == '3': three(), elif x == '4': four(), elif x == '5': five(), elif x == '6': six(), elif x == '7': seven(), elif x == '8': eight(), elif x == '9': nine(), elif x == '0': zero(), elif x == 'Quit': break else: print "Number not entered" </code></pre>
1
2016-09-16T22:24:27Z
39,541,372
<p>As said before, your approach was a bit off. I implemented one that takes your list numbers and then builds the result line by line (i.e., top, middle, then bottom).</p> <pre><code>class zero: top = " __ " mid = "| |" bot = "|__|" class one: top = " " mid = " |" bot = " |" class two: top = " __ " mid = " __|" bot = "|__ " class three: top = " __ " mid = " __|" bot = " __|" class four: top = " " mid = "|_|" bot = " |" class five: top = " __ " mid = "|__ " bot = " __|" class six: top = " __ " mid = "|__ " bot = "|__|" class seven: top = " __ " mid = " |" bot = " |" class eight: top = " __ " mid = "|__|" bot = "|__|" class nine: top = " __ " mid = "|__|" bot = " |" def printnum(list): chunks = ['top','mid','bot'] for section in chunks: string = '' for x in list: if x == '1': string += getattr(one, section) elif x == '2': string += getattr(two, section) elif x == '3': string += getattr(three, section) elif x == '4': string += getattr(four, section) elif x == '5': string += getattr(five, section) elif x == '6': string += getattr(six, section) elif x == '7': string += getattr(seven, section) elif x == '8': string += getattr(eight, section) elif x == '9': string += getattr(nine, section) elif x == '0': string += getattr(zero, section) elif x == 'Quit': break else: print "Number not entered" print string x = raw_input("Type the number you would like printed: ") a = list(x) printnum(a) </code></pre>
0
2016-09-16T23:27:46Z
[ "python", "python-2.7" ]
Extracting Adam update rates in Tensorflow
39,540,977
<p>I want to find out and keep track of Adam update rate of</p> <pre><code>lr_t &lt;- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t) </code></pre> <p>I followed another post and got the nodes of a graph by </p> <pre><code>[n.name for n in tf.get_default_graph().as_graph_def().node] </code></pre> <p>In which I found </p> <pre><code>u'Adam/update', u'Adam/value', u'Adam', </code></pre> <p>I am assume that either of these three could be the updated learning rate I'm looking for but I don't know how to extract it. Please help </p>
1
2016-09-16T22:34:30Z
39,550,537
<p>Suppose you've defined an optimizer:</p> <pre><code>optm = tf.train.AdamOptimizer(learning_rate = 0.01) train_step = optm.minimize(L) </code></pre> <p>Now you could reach v_t and m_t with the following code:</p> <pre><code>optm.get_slot(W, 'v') optm.get_slot(W, 'm') </code></pre> <p>These values are tensors so they are to be evaluated by running a session.</p> <p>W is some previously defined variable. </p> <p>Explore more by examing <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py" rel="nofollow">the source</a>.</p>
-1
2016-09-17T18:50:47Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
How to set a variable to the result of command function of a tkinter Button?
39,540,999
<p>So here is my problem that I just can't figure out and can't seem to find information to help me understand what is happening. So I set <code>source</code> equal to the button that calls a function called <code>openDirectory</code> which is really just a short-cut to call <code>os.path.join()</code> and <code>os.path.normalize()</code> on the <code>askopendirectory</code> function from <code>tkinter.filedialog</code>. </p> <p>The problem is that the <code>source</code> is always a number and I can't figure out why it is not the path I have chosen in the <code>openDirectory</code> function. I have also tried placing the code inside <code>openDirectory</code> directly in the command of the button, and it still does the same thing.</p> <p>Steps to reproduce:</p> <ol> <li>Run this code (written using python 3.5)</li> <li>Select a path using the source button</li> <li>Hit the button at the bottom right corner which should show the path in a <code>messagebox</code></li> <li>Notice that the <code>messagebox</code> shows a big number instead of the path.</li> </ol> <p>How can I get the path stored in the source variable so I can access it at any time?</p> <pre><code>#!/usr/bin/python import os from functions import * from tkinter import * from tkinter import messagebox from tkinter import filedialog class FileMover(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def openDirectory(listfiles, recursive): destination = os.path.join(os.path.normpath(filedialog.askdirectory()), "") return destination def initUI(self): self.parent.title("File Mover") self.pack() recursiveCheck = bool previewCheck = bool # source button and label. source should equal the path selected in openDirecotry source = Button(self, text="Source Directory", command=lambda:openDirectory(recursiveCheck)) sourceLabel = Label(self, text="Select a Source Directory...") sourcemsg = Button(self, text="Source Variable", command=lambda:messagebox.askokcancel(self, source)) # check box used to tell open directory either true or false to recurse the source dir recursiveLabel = Label(self, text="Recursive ") recursive = Checkbutton(self, onvalue=True, offvalue=False, variable=recursiveCheck) # destination button and label. source should equal the path selected in openDirecotry destination = Button(self, text="Target Directory ", command=lambda:openDirectory(False)) destinationLabel = Label(self, text="Select a Target Directory...") # not implemented yet previewLabel = Label(self, text="Preview ") preview = Checkbutton(self, onvalue=True, offvalue=False, variable=previewCheck) source.grid(row=0, column=0, columnspan=2) sourceLabel.grid(row=0, column=2) recursiveLabel.grid(row=1, column=1) recursive.grid(row=1, column=2, sticky=W) destination.grid(row=2, column=0, columnspan=2) destinationLabel.grid(row=2, column=2) previewLabel.grid(row=4, column=6) preview.grid(row=4, column=7, sticky=W) # just for debugging to show source directory on demand sourcemsg.grid(row=5, column=8) def main(): root = Tk() ex = FileMover(root) root.mainloop() if __name__ == '__main__': main() </code></pre>
0
2016-09-16T22:38:43Z
39,541,092
<p>Buttons do not work that way. When a function serves as a button's callback and the function is called by using the button, there's nowhere to return to. There isn't really a sensible way to make that work. If it worked the way you are guessing it does, you would lose the reference to the button! You don't want that.</p> <p>Instead, simply save it as an instance variable:</p> <pre><code>def openDirectory(self, recursive): self.destination = os.path.join(os.path.normpath(filedialog.askdirectory()), "") </code></pre> <p>Note that your <code>openDirectory</code> method had <code>listfiles</code> referring to the instance itself, while the other methods use the traditional <code>self</code> - I've changed it to use <code>self</code> so you don't have to deal with <code>listfiles.destination = ...</code>.</p> <pre><code>sourcemsg = Button(self, text="Source Variable", command=lambda:messagebox.askokcancel('Window Title', self.destination)) </code></pre> <p>Note that I've changed the arguments to <code>messagebox.askokcancel</code> to the string <code>'Window Title'</code> and the reference <code>self.destination</code>, so instead of the window's title being a reference to the frame (it's supposed to be a string for the window's title) it's an actual string, and instead of the message's text being a reference to a button (it's supposed to be a string for the message's text) it's the string you saved in <code>openDirectory</code>.</p>
1
2016-09-16T22:50:48Z
[ "python", "python-3.x", "button", "tkinter" ]
requests.exceptions.MissingSchema: Invalid URL (with bs4)
39,541,071
<p>I am getting this error: requests.exceptions.MissingSchema: Invalid URL 'http:/1525/bg.png': No schema supplied. Perhaps you meant <a href="http://http:/1525/bg.png" rel="nofollow">http://http:/1525/bg.png</a>?</p> <p>I don't really care why the error happened, I want to be able to capture any Invalid URL errors, issue a message and proceed with the rest of the code. </p> <p>Below is my code, where I'm trying to use try/except for that specific error but its not working...</p> <pre><code># load xkcd page # save comic image on that page # follow &lt;previous&gt; comic link # repeat until last comic is reached import webbrowser, bs4, os, requests url = 'http://xkcd.com/1526/' os.makedirs('xkcd', exist_ok=True) while not url.endswith('#'): # - last page # download the page print('Dowloading page %s...' % (url)) res = requests.get(url) res.raise_for_status() soup = bs4.BeautifulSoup(res.text, "html.parser") # find url of the comic image (&lt;div id ="comic"&gt;&lt;img src="........" &lt;/div comicElem = soup.select('#comic img') if comicElem == []: print('Could not find any images') else: comicUrl = 'http:' + comicElem[0].get('src') #download the image print('Downloading image... %s' % (comicUrl)) res = requests.get(comicUrl) try: res.raise_for_status() except requests.exceptions.MissingSchema as err: print(err) continue # save image to folder imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') for chunk in res.iter_content(1000000): imageFile.write(chunk) imageFile.close() #get &lt;previous&gt; button url prevLink = soup.select('a[rel="prev"]')[0] url = 'http://xkcd.com' + prevLink.get('href') print('Done') </code></pre> <p>What a my not doing? (I'm on python 3.5) Thanks allot in advance...</p>
0
2016-09-16T22:47:21Z
39,541,226
<p>if you don't care about the error (which i see as bad programming), just use a blank except statement that catches all exceptions.</p> <pre><code>#download the image print('Downloading image... %s' % (comicUrl)) try: res = requests.get(comicUrl) # moved inside the try block res.raise_for_status() except: continue </code></pre> <p>but on the other hand if your except block isn't catching the exception then it's because the exception actually happens outside your try block, so move <code>requests.get</code> into the try block and the exception handling should work (that's if you still need it).</p>
0
2016-09-16T23:09:10Z
[ "python" ]
How to check if multiple items from a list appear in a string?
39,541,076
<p>Let's say I have a list of keywords:</p> <pre><code>keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] </code></pre> <p>And a list of main terms:</p> <pre><code>`main_terms = ["terms","words","vocab","list"]` </code></pre> <p>UPDATED to more clearly state the problem:</p> <p>The script I'm making is to remove near-duplicates from a long list of keywords. I've managed to remove misspellings and slight variants (ex. "hitsory terms", "history term").</p> <p><strong>My problem</strong> is that I have multiple terms that I'm looking for in this list of keywords, but after I've found one of these terms in a keyword (ex. "history terms") all keywords that are identical except with a different term or combination of terms (ex. "history vocab", "history words", "history words terms", etc.) should be considered duplicates.</p> <ul> <li>It is OK to have multiple terms in the keyword (ex. "math terms words vocab") <strong>as long as</strong> there is not a keyword that is identical save for having a lower number of the terms (ex. "math terms words" or ideally a single term like "math vocab").</li> </ul>
2
2016-09-16T22:47:38Z
39,541,224
<p>I'm sure there's a more elegant solution, but this seems to be the solution for which you're looking, at least for part 1):</p> <pre><code>&gt;&gt;&gt; def remove_main_terms(keyword): words = keyword.split() count = 0 to_keep = [] for word in words: if word in main_terms: count += 1 if count &lt; 2: to_keep.append(word) else: pass return " ".join(to_keep) &gt;&gt;&gt; keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] &gt;&gt;&gt; main_terms = ["terms","words","vocab","list"] &gt;&gt;&gt; new_list = [] &gt;&gt;&gt; for w in keywords: new_list.append(remove_main_terms(w)) &gt;&gt;&gt; new_list ['history terms', 'history words', 'history vocab', 'history words', 'history vocab', 'science list', 'science terms', 'math terms'] </code></pre>
0
2016-09-16T23:09:00Z
[ "python" ]
How to check if multiple items from a list appear in a string?
39,541,076
<p>Let's say I have a list of keywords:</p> <pre><code>keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] </code></pre> <p>And a list of main terms:</p> <pre><code>`main_terms = ["terms","words","vocab","list"]` </code></pre> <p>UPDATED to more clearly state the problem:</p> <p>The script I'm making is to remove near-duplicates from a long list of keywords. I've managed to remove misspellings and slight variants (ex. "hitsory terms", "history term").</p> <p><strong>My problem</strong> is that I have multiple terms that I'm looking for in this list of keywords, but after I've found one of these terms in a keyword (ex. "history terms") all keywords that are identical except with a different term or combination of terms (ex. "history vocab", "history words", "history words terms", etc.) should be considered duplicates.</p> <ul> <li>It is OK to have multiple terms in the keyword (ex. "math terms words vocab") <strong>as long as</strong> there is not a keyword that is identical save for having a lower number of the terms (ex. "math terms words" or ideally a single term like "math vocab").</li> </ul>
2
2016-09-16T22:47:38Z
39,541,246
<p>EDIT: I'm increasingly thinking you're asking an <a href="http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY Question</a> and you want unique subjects.</p> <p>If that is the case, the following works even better:</p> <pre><code>result = [] found = [] for word in keywords: for term in main_terms: if term in word: word = word.replace(term, "") result.append(word.strip()) print set(result) </code></pre> <p>Which outputs <code>set(['science', 'math', 'history'])</code></p> <hr> <p>This solves your original problem with the same results, but does it by ignoring terms after the first and only passing unique first words.</p> <pre><code>result = [] found = [] for word in keywords: found = False for res in result: if word.split()[0] in res: found = True if not found: result.append(word) print result </code></pre> <p>See the demo on <a href="https://repl.it/Dbb1/0" rel="nofollow">repl.it</a></p>
0
2016-09-16T23:11:17Z
[ "python" ]
How to check if multiple items from a list appear in a string?
39,541,076
<p>Let's say I have a list of keywords:</p> <pre><code>keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] </code></pre> <p>And a list of main terms:</p> <pre><code>`main_terms = ["terms","words","vocab","list"]` </code></pre> <p>UPDATED to more clearly state the problem:</p> <p>The script I'm making is to remove near-duplicates from a long list of keywords. I've managed to remove misspellings and slight variants (ex. "hitsory terms", "history term").</p> <p><strong>My problem</strong> is that I have multiple terms that I'm looking for in this list of keywords, but after I've found one of these terms in a keyword (ex. "history terms") all keywords that are identical except with a different term or combination of terms (ex. "history vocab", "history words", "history words terms", etc.) should be considered duplicates.</p> <ul> <li>It is OK to have multiple terms in the keyword (ex. "math terms words vocab") <strong>as long as</strong> there is not a keyword that is identical save for having a lower number of the terms (ex. "math terms words" or ideally a single term like "math vocab").</li> </ul>
2
2016-09-16T22:47:38Z
39,541,251
<p>Loop through the <code>keywords</code> and check each one against the <code>main_terms</code>:</p> <pre><code>keywords = ["history terms", "history words", "history vocab", "history words terms", "history vocab words", "science list", "science terms vocab", "math terms words vocab"] main_terms = {"terms","words","vocab","list"} result = {} for words in keywords: s = set(words.split()) s_subject = s - main_terms subject = s_subject and next(iter(s_subject)) if s | main_terms and subject and subject not in result: result[subject] = words </code></pre> <p>The turn the result values into a list:</p> <pre><code>&gt;&gt;&gt; list(result.values()) ['math terms words vocab', 'history terms', 'science list'] </code></pre>
1
2016-09-16T23:11:52Z
[ "python" ]
Need a way to test SSH with a timeout
39,541,080
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we need to keep the Python version to 2.6 for now. So I need a way to get this function to work and with a timeout of 1-2s.</p> <pre><code>import commands def test_ssh(host): output = commands.getstatusoutput("ssh " + host + " hostname") if output[0] == 0: return True else: print(host + " not accessible via SSH!") return False </code></pre>
0
2016-09-16T22:48:46Z
39,541,189
<p>You need to determine if it is actually a connect timeout, or if it can connect, but the server is accepting the connection and doesn't send anything.</p> <p>If you were to use telnet to manually test, telnet 22 and see if you get a response from the server at all, you should see something like this if it connects:</p> <pre> $ telnet localhost 22 Connected to localhost. Escape character is '^]'. SSH-2.0-OpenSSH_7.2 </pre> <p>If it connects and you don't get any response, then I think you will have to try a test using sockets in python. </p> <p>You can find info here: <a href="https://docs.python.org/3/library/socket.html" rel="nofollow">https://docs.python.org/3/library/socket.html</a></p>
0
2016-09-16T23:03:12Z
[ "python", "ssh" ]
Need a way to test SSH with a timeout
39,541,080
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we need to keep the Python version to 2.6 for now. So I need a way to get this function to work and with a timeout of 1-2s.</p> <pre><code>import commands def test_ssh(host): output = commands.getstatusoutput("ssh " + host + " hostname") if output[0] == 0: return True else: print(host + " not accessible via SSH!") return False </code></pre>
0
2016-09-16T22:48:46Z
39,543,654
<p>If you want to be sure that an SSH connection (including authentication) can be established correctly, the best way probably is to connect in batch mode with a small timeout (<code>-o BatchMode=yes -o ConnectTimeout=2</code>).</p>
0
2016-09-17T06:39:18Z
[ "python", "ssh" ]
Need a way to test SSH with a timeout
39,541,080
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we need to keep the Python version to 2.6 for now. So I need a way to get this function to work and with a timeout of 1-2s.</p> <pre><code>import commands def test_ssh(host): output = commands.getstatusoutput("ssh " + host + " hostname") if output[0] == 0: return True else: print(host + " not accessible via SSH!") return False </code></pre>
0
2016-09-16T22:48:46Z
39,561,302
<p>you could wrap your call to <code>ssh</code> into <code>timelimit</code> so it gets cancelled after a certain timeout if it does not finish on time.</p> <ul> <li>homepage: <a href="http://devel.ringlet.net/sysutils/timelimit/" rel="nofollow">http://devel.ringlet.net/sysutils/timelimit/</a></li> <li>manpage: <a href="http://manpages.ubuntu.com/manpages/xenial/man1/timelimit.1.html" rel="nofollow">http://manpages.ubuntu.com/manpages/xenial/man1/timelimit.1.html</a></li> </ul>
0
2016-09-18T18:40:58Z
[ "python", "ssh" ]
Package for multiple correlation?
39,541,144
<p>Is there any easy to use python package that helps in calculating multiple correlation? Its definition is as follows:</p> <p><a href="https://en.wikipedia.org/wiki/Multiple_correlation" rel="nofollow">https://en.wikipedia.org/wiki/Multiple_correlation</a></p>
0
2016-09-16T22:56:47Z
39,541,336
<p>Very similar question here: <a href="http://stackoverflow.com/questions/13452353/multiple-correlation-in-python">multiple correlation in python</a></p> <p>The answer given is an implementation using pandas. </p> <p>Alternatively you could look at Numpy/Scipy, they likely have something you could use. <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html" rel="nofollow">numpy.corrcoef</a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html" rel="nofollow">numpy.correlate</a> might get you started.</p>
0
2016-09-16T23:21:57Z
[ "python", "correlation" ]
Understanding threading synchronization
39,541,212
<p>The Fredrik Lundh article titled <a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow"><em>Thread Synchronization Mechanisms in Python</em></a> gives the example below to show that multiple threads operating can result in an inaccurate value.</p> <pre><code>counter = 0 def process_item(item): global counter ... do something with item ... counter += 1 </code></pre> <p>Then it goes on saying these things are thread-safe:</p> <pre class="lang-none prettyprint-override"><code>reading or replacing a single instance attribute reading or replacing a single global variable fetching an item from a list modifying a list in place (e.g. adding an item using append) fetching an item from a dictionary modifying a dictionary in place (e.g. adding an item, or calling the clear method) </code></pre> <p>But isn't the code example just updating a single global variable, and hence would be thread-safe anyway?</p> <p>What am I missing here?</p>
0
2016-09-16T23:06:28Z
39,541,254
<p>In Python the code:</p> <pre><code>counter += 1 </code></pre> <p>is the same as saying:</p> <pre><code>counter = counter + 1 </code></pre> <p>Thus the lookup of the value is separate to the update.</p>
3
2016-09-16T23:12:03Z
[ "python", "multithreading" ]
I need to make py to exe. I'm using python 3.5.2
39,541,220
<p>I need to make py to exe. I'm using python 3.5.2. Try to install pyinstaller for it. But didnt understand how it install it properly or how to use it? I'm a beginner of python. Could someone please explaine in in very basic manner? Thank you for your time.</p>
-2
2016-09-16T23:08:03Z
39,761,244
<p>First install pyinstaller with pip: <strong>pip install pyinstaller</strong></p> <p>If the installation is successful, try to create an exe with the following command:</p> <pre><code>pyinstaller --onefile [your_script].py </code></pre> <p>Update your question with the errors, if you get any.</p>
0
2016-09-29T04:07:58Z
[ "python", "python-3.x", "exe", "pyinstaller" ]
How to write a recursive function to print a string a certain number of times?
39,541,240
<p>I have been trying to write a python function which will receive two arguments: <code>x</code> which is the number of times to repeat and <code>y</code> which is the number or string to be repeated.</p> <p>So far this is what I have been able to come up with, but I can't seem to be able to determine how to do it recursively.</p> <pre><code>def recurse(x, y): final = [] if x == 0: return ("") else: x = x - 1 final.append(recurse(x,y)) return final </code></pre> <p>If <code>recurse(3,"Cat")</code> is called, the output is meant to look like this:</p> <pre><code>print recurse(3, 'cat') ['cat','cat','cat'] </code></pre> <p>How would I go about doing this?</p>
0
2016-09-16T23:10:24Z
39,541,314
<p>True functional recursion should have <em>no</em> assignments (i.e. state). This can be achieved using what's called an <em>accumulator</em>, i.e. an array that is built up successively and passed to each recursive step, until the base case occurs, causing the accumulator's final form to be returned directely, and indirectly <em>all the way back</em> to the initial calling instance.</p> <pre><code>&gt;&gt;&gt; def recurse(Iters, text, Accumulator=[]): ... if Iters == 0: return Accumulator # base case ... return recurse(Iters-1, text, Accumulator + [text]) # recursive step ... &gt;&gt;&gt; recurse(3, 'helle') ['helle', 'helle', 'helle'] </code></pre> <p>Note that there is no change of <em>state</em> at any point; all "updates" occur at the point of calling the next recursive step with updated arguments.</p>
1
2016-09-16T23:19:30Z
[ "python", "recursion" ]
How to write a recursive function to print a string a certain number of times?
39,541,240
<p>I have been trying to write a python function which will receive two arguments: <code>x</code> which is the number of times to repeat and <code>y</code> which is the number or string to be repeated.</p> <p>So far this is what I have been able to come up with, but I can't seem to be able to determine how to do it recursively.</p> <pre><code>def recurse(x, y): final = [] if x == 0: return ("") else: x = x - 1 final.append(recurse(x,y)) return final </code></pre> <p>If <code>recurse(3,"Cat")</code> is called, the output is meant to look like this:</p> <pre><code>print recurse(3, 'cat') ['cat','cat','cat'] </code></pre> <p>How would I go about doing this?</p>
0
2016-09-16T23:10:24Z
39,541,319
<pre><code>def recurse(x, y): final = [] if times == 0: </code></pre> <p>You can't just reference "times" as if it's some kind of magic floaty variable available anywhere and everywhere. The first time in here, <code>times</code> will have no value. And the next time through, you're hoping you can just pick the value of <code>times</code> out of thin air and it will magically be what it was somewhere else, during some previous run.</p> <p>The only variables you can work with are the ones completely inside your function - or ones which are passed in from outside, and returned out at the end.</p> <pre><code>def recurse(times, word): if times == 1: return [word] else: return [word] + recurse(times-1, word) print(recurse(3, 'cat')) </code></pre> <p><a href="https://repl.it/Dbbl" rel="nofollow">Try it online at repl.it</a></p> <p>It takes a number of times as an input, it returns <code>[word]</code> plus ( It takes a number of times - 1 as an input, it returns <code>[word]</code> plus ( It takes a number of times - 1 as an input, it returns <code>[word]</code> ).</p> <p>Note there's no accumulator list like <code>final = []</code> because each time through the function it will be empty again. The accumulation happens implicitly in the way the programming language calls functions and returns values. Python will hold <code>[word]</code> in memory itself while it calculates the next recurse() output.</p>
0
2016-09-16T23:19:47Z
[ "python", "recursion" ]
Unable to successfully call a class string in a for loop
39,541,260
<p>I have a class</p> <pre><code>class zero: top = " __ " mid = "| |" bot = "|__|" </code></pre> <p>And I want to use a loop to call the different sections. E.g.:</p> <pre><code>def printnum(list): chunks = ['top','mid','bot'] print section # prints "top" print zero.top # prints " __ " print zero.section # fails for section in chunks: string = '' for x in list: if x == '1': string += getattr(one, section) elif x == '2': string += getattr(two, section) etc.... </code></pre> <p>I must be missing something pretty basic here. Can I use my loop to call the different parts of my class?</p> <p>Here's a snippet of intended functionality:</p> <pre><code>&gt;&gt;Enter the number you would like printed: 21 __ __ __||__ __| __| </code></pre>
0
2016-09-16T23:12:42Z
39,541,340
<p>Your <code>zero</code> class doesn't have an attribute called <code>section</code>, what you can do instead is to use <code>getattr</code> which accepts a string (second argument) as the object property to get, like this:</p> <pre><code>class zero: top = " __ " mid = "| |" bot = "|__|" chunks = ['top','mid','bot'] for section in chunks: print section # prints "top" print zero.top # prints " __ " print getattr(zero, section) </code></pre> <p>Which tells python that you want to get the attribute (all the items in your list when you're looping through it) your object <code>zero</code>.</p> <p><code>getattr</code> also takes a third argument that would be returned if the object doesn't have that property.</p> <pre><code>getattr(zero, section, 'Not Found') </code></pre>
1
2016-09-16T23:22:20Z
[ "python" ]
Take Unique of numpy array according to 2 column values.
39,541,276
<p>I have Numpy array in python with two columns as follows : </p> <pre><code>time,id 1,a 2,b 3,a 1,a 5,c 6,b 3,a </code></pre> <p>i want to take unique time of each user. For above data i want below output. </p> <pre><code>time,id 1,a 2,b 3,a 5,c 6,b </code></pre> <p>That is, I want to take only unique rows. so, 1,a and 3,a will not repeat in the result. I have both the column as string datatype and have a very large 2-D array. one solution may be, i can iterate over all the rows and make a set. But that will be very slow. Please suggest an efficient way to implement it. </p>
0
2016-09-16T23:14:19Z
39,541,480
<p>Given:</p> <pre><code>&gt;&gt;&gt; b [['1' 'a'] ['2' 'b'] ['3' 'a'] ['1' 'a'] ['5' 'c'] ['6' 'b'] ['3' 'a']] </code></pre> <p>You can do:</p> <pre><code>&gt;&gt;&gt; np.vstack({tuple(e) for e in b}) [['3' 'a'] ['1' 'a'] ['2' 'b'] ['6' 'b'] ['5' 'c']] </code></pre> <p>Since that is a set comprehension, you loose the order of the original. </p> <p>Or, to maintain order, you can do: </p> <pre><code>&gt;&gt;&gt; c = np.ascontiguousarray(b).view(np.dtype((np.void, b.dtype.itemsize * b.shape[1]))) &gt;&gt;&gt; b[np.unique(c, return_index=True)[1]] [['1' 'a'] ['2' 'b'] ['3' 'a'] ['5' 'c'] ['6' 'b']] </code></pre> <p>Or, if you can use Pandas, this is really easy. Given the following DataFrame:</p> <pre><code>&gt;&gt;&gt; df id time 0 a 1 1 b 2 2 a 3 3 a 1 4 c 5 5 b 6 6 a 3 </code></pre> <p>Just use <code>drop_duplicates()</code>:</p> <pre><code>&gt;&gt;&gt; df.drop_duplicates() id time 0 a 1 1 b 2 2 a 3 4 c 5 5 b 6 </code></pre>
1
2016-09-16T23:45:41Z
[ "python", "arrays", "numpy" ]
Take Unique of numpy array according to 2 column values.
39,541,276
<p>I have Numpy array in python with two columns as follows : </p> <pre><code>time,id 1,a 2,b 3,a 1,a 5,c 6,b 3,a </code></pre> <p>i want to take unique time of each user. For above data i want below output. </p> <pre><code>time,id 1,a 2,b 3,a 5,c 6,b </code></pre> <p>That is, I want to take only unique rows. so, 1,a and 3,a will not repeat in the result. I have both the column as string datatype and have a very large 2-D array. one solution may be, i can iterate over all the rows and make a set. But that will be very slow. Please suggest an efficient way to implement it. </p>
0
2016-09-16T23:14:19Z
39,541,690
<p>If you go back to your original list format data and create a structured array, then determining the unique values is much easier.</p> <pre><code>a = [['1', 'a'], ['2', 'b'], ['3', 'a'],['1', 'a'],['5', 'c'], ['6', 'b'], ['3', 'a']] tup = [tuple(i) for i in a] # you need a list of tuples, a kludge for now dt = [('f1', '&lt;U5'), ('f2', '&lt;U5')] # specify a dtype with two columns b = np.array(tup, dtype=dt) # create the array with the dtype np.unique(b) # get the unique values array([('1', 'a'), ('2', 'b'), ('3', 'a'), ('5', 'c'), ('6', 'b')], dtype=[('f1', '&lt;U5'), ('f2', '&lt;U5')]) np.unique(b).tolist() # and if you need a list, just change the array [('1', 'a'), ('2', 'b'), ('3', 'a'), ('5', 'c'), ('6', 'b')] </code></pre> <p>Reference: <a href="http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array">Find unique rows in numpy.array</a></p> <p>A combination of Joe Kingston and Jaime recommendations deal with views and the above can be simplified to the following. Nicely, this option relies on view, a change of dtype to a structured array and a slice into the original array using the indices of the unique values in the structured view.</p> <pre><code>&gt;&gt;&gt; dt = a.dtype.descr * a.shape[1] &gt;&gt;&gt; a_view = a.view(dt) &gt;&gt;&gt; a_uniq, a_idx = np.unique(a_view, return_index=True) &gt;&gt;&gt; a[a_idx] array([['1', 'a'], ['2', 'b'], ['3', 'a'], ['5', 'c'], ['6', 'b']], dtype='&lt;U1') </code></pre>
0
2016-09-17T00:23:32Z
[ "python", "arrays", "numpy" ]
Which kind of of data handling, internal or external, is commonly used?
39,541,277
<p>I'm writing a program in Python3.5 that reads a data set and does some stuff (it's DICOM data if you are familiar with it). It uses:</p> <ul> <li>Large arrays of size (512,512,141) or bigger.</li> <li>Alot of small metadata (many single data entries).</li> </ul> <p>Now my program has many different components that will all use the same set of data. My question is what is the best practice of handling this data? Do I:</p> <ul> <li><strong>Pass the data through internal variables?</strong> I feel this is an inefficient use of memory/space as each time I have to pass data down a line (without destroying where it came from) that it is unnecessarily adding resources?</li> <li><strong>Use a file storage system?</strong> When I say this I refer to something such as SQL, HDF5 or even a dictionary of values inside python.</li> <li><strong>Read the data in every time I need it?</strong> So for instance I would have to import the library, load the file, search the file for the var, store the var and close the file again. Seems quite tedious.</li> </ul> <p>Which is the best method? I'm not accessing this data once or twice but in the order of 20+ times. Is there a method I don't know about that I should be using?</p> <p>Thanks in advance, I value your help (and criticism where necessary) to always improve myself as a programmer and, a human being.</p>
1
2016-09-16T23:14:34Z
39,542,069
<p>Seems like you're actually asking multiple questions here. Let me try to tease them apart:</p> <h3>Should I store all my data in-memory?</h3> <p>Can you? Do you have enough memory to do so comfortably? Then do it. Load it once and pass it around, or pass around some interface to the data, as necessary. How you interface with it is your choice (see below). Otherwise you have no choice but to make multiple calls to disk I/O. But I think it's generally a bad decision to read the same data from disk redundantly, since disk I/O tends to be a bottleneck resource.</p> <h3>Should I pass loads of data to lots of functions? Won't this create unnecessary copies of the data?</h3> <p>Python function arguments are passed "by assignment" so to speak. To use C terminology, although not technically precise, it's more like pass-by-reference than pass-by-value. You usually don't see this behavior because 1) lots of things in python are immutable, and 2) assignment statements in python just reassign the name to a different value. Examples where you can see this behavior are mutable objects like a <code>list</code>, <code>dict</code> or any kind of object with mutable member properties. Try passing a list to a function and modifying it inside. It will also be modified in the passing context after the function returns.</p> <h3>How should I interface with my data?</h3> <p>This depends on several things that I can think of. First, did you decide to store the data in memory or on disk (see first question)? Second, from where do you need to access the data? Third, if you're storing it in memory, do you need the data to persist between runs of the program?</p> <p>If you can store the data in memory, just need to access it locally, and don't need it to persist, I would go with just some sort of nested python <code>dict</code>, maybe making one or more custom <code>class</code>es to simplify the interface to the data.</p> <p>If you can store the data in memory, but either need to access it over a network or need it to persist between runs of the program, I would use <strong>redis</strong> or a similar key-value store to manage the data. <a href="https://try.redis.io/" rel="nofollow">redis is really easy to learn</a> and <a href="https://pypi.python.org/pypi/redis" rel="nofollow">there's good python library support</a>.</p> <p>If you can't store the data in memory, but don't want to parse it over and over again, you should at least index it before you write it back to disk. You might come up with your own indexing scheme just using the file system if you only need local access. If this becomes too complicated or you need network access, you should probably use a database system.</p>
1
2016-09-17T01:35:12Z
[ "python", "external", "dicom", "internal", "datahandler" ]
No module named "xxx" in my project root folder
39,541,295
<p>My project is organized this way:</p> <pre><code>ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>There are empties <strong>init</strong>.py files in ezrename, base and shell folders. Images is just a resource folder and don't have anything.</p> <p>I have a module named ezrename/base/colors.py file, which implements the Colors class.</p> <p>I have a module named ezrename/shell/baseshell.py, which implements the BaseShell class and imports Colors.</p> <blockquote> <p>from ezrename.base import Colors</p> </blockquote> <p>But I get the following error:</p> <pre><code>Traceback (most recent call last): File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in &lt;module&gt; from ezrename.base import Colors ImportError: No module named 'ezrename' </code></pre> <p>So I decided to try</p> <pre><code>from ..base import Colors </code></pre> <p>And gets</p> <pre><code>Traceback (most recent call last): File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in &lt;module&gt; from ..base import Colors SystemError: Parent module '' not loaded, cannot perform relative import </code></pre> <p>I have no idea what am I doing wrong. Can somebody explain how the imports works and what am I not doing right?</p>
1
2016-09-16T23:16:05Z
39,541,353
<p>Python imports will work form the root of your project, so any imports in modules in subdirectories should import relative to that</p> <p>So if you're running from a main module in ezrename/ then the import in baseshell.py should be:</p> <p><code>from base import colors</code></p>
0
2016-09-16T23:25:01Z
[ "python", "python-3.x", "import" ]
No module named "xxx" in my project root folder
39,541,295
<p>My project is organized this way:</p> <pre><code>ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>There are empties <strong>init</strong>.py files in ezrename, base and shell folders. Images is just a resource folder and don't have anything.</p> <p>I have a module named ezrename/base/colors.py file, which implements the Colors class.</p> <p>I have a module named ezrename/shell/baseshell.py, which implements the BaseShell class and imports Colors.</p> <blockquote> <p>from ezrename.base import Colors</p> </blockquote> <p>But I get the following error:</p> <pre><code>Traceback (most recent call last): File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in &lt;module&gt; from ezrename.base import Colors ImportError: No module named 'ezrename' </code></pre> <p>So I decided to try</p> <pre><code>from ..base import Colors </code></pre> <p>And gets</p> <pre><code>Traceback (most recent call last): File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in &lt;module&gt; from ..base import Colors SystemError: Parent module '' not loaded, cannot perform relative import </code></pre> <p>I have no idea what am I doing wrong. Can somebody explain how the imports works and what am I not doing right?</p>
1
2016-09-16T23:16:05Z
39,541,400
<p>You can add ezrename/base to the python path and then just import Colors </p> <p>e.g. from ezrename/shell/baseshell.py</p> <pre><code>import os import sys shell_dir = os.path.dirname(os.path.realpath(__file__)) ezrename_dir = os.path.dirname(shell_dir) base_dir = os.path.join(ezrename_dir, "base") sys.path.append(base_dir) import Colors </code></pre>
0
2016-09-16T23:32:11Z
[ "python", "python-3.x", "import" ]
No module named "xxx" in my project root folder
39,541,295
<p>My project is organized this way:</p> <pre><code>ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>There are empties <strong>init</strong>.py files in ezrename, base and shell folders. Images is just a resource folder and don't have anything.</p> <p>I have a module named ezrename/base/colors.py file, which implements the Colors class.</p> <p>I have a module named ezrename/shell/baseshell.py, which implements the BaseShell class and imports Colors.</p> <blockquote> <p>from ezrename.base import Colors</p> </blockquote> <p>But I get the following error:</p> <pre><code>Traceback (most recent call last): File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in &lt;module&gt; from ezrename.base import Colors ImportError: No module named 'ezrename' </code></pre> <p>So I decided to try</p> <pre><code>from ..base import Colors </code></pre> <p>And gets</p> <pre><code>Traceback (most recent call last): File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in &lt;module&gt; from ..base import Colors SystemError: Parent module '' not loaded, cannot perform relative import </code></pre> <p>I have no idea what am I doing wrong. Can somebody explain how the imports works and what am I not doing right?</p>
1
2016-09-16T23:16:05Z
39,571,780
<p>By the pythonic way, I think my idea was wrong. You can't import from two modules as I wanted to because imports will only work if the module itself was not imported do what I wanted is not possible.</p> <p>The pythonic way would be create an application folder without an <strong>init</strong>.py file, import the package in the application entrance script and the the relative imports will work:</p> <pre><code>EzRename └──ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>In EzRename, add a application.py:</p> <blockquote> <p>import ezrename</p> </blockquote> <p>If you do that, the relative imports from the classes in shell and base will work. That was the missing piece</p>
0
2016-09-19T11:11:07Z
[ "python", "python-3.x", "import" ]
How to do type verification in python?
39,541,393
<p>(Maybe b/c I'm from a C++ world) I want to verify some python variable is</p> <p><code>list(string)</code> or <code>list(dict(int, string))</code> or <code>SomethingIterable(string)</code></p> <p>Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)</p> <p>I emphasize that I understand in Python <code>list</code> can have elements of different types, which is exactly the reason why I ask how to verify a <code>list</code> which are composed by just a certain type e.g. <code>string</code>.</p>
2
2016-09-16T23:31:35Z
39,541,428
<p>In Python lists can be composed of mixed types, there is no way to do something like setting the "type" of a list. Also, even if you could, this "type" is not enforced and could change at any time.</p>
4
2016-09-16T23:38:00Z
[ "python" ]
How to do type verification in python?
39,541,393
<p>(Maybe b/c I'm from a C++ world) I want to verify some python variable is</p> <p><code>list(string)</code> or <code>list(dict(int, string))</code> or <code>SomethingIterable(string)</code></p> <p>Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)</p> <p>I emphasize that I understand in Python <code>list</code> can have elements of different types, which is exactly the reason why I ask how to verify a <code>list</code> which are composed by just a certain type e.g. <code>string</code>.</p>
2
2016-09-16T23:31:35Z
39,541,442
<p>Use the <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">typing</a> module</p> <p>Typically: </p> <pre><code>from typing import List def method(value: List[str]): pass </code></pre>
-3
2016-09-16T23:40:24Z
[ "python" ]
How to do type verification in python?
39,541,393
<p>(Maybe b/c I'm from a C++ world) I want to verify some python variable is</p> <p><code>list(string)</code> or <code>list(dict(int, string))</code> or <code>SomethingIterable(string)</code></p> <p>Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)</p> <p>I emphasize that I understand in Python <code>list</code> can have elements of different types, which is exactly the reason why I ask how to verify a <code>list</code> which are composed by just a certain type e.g. <code>string</code>.</p>
2
2016-09-16T23:31:35Z
39,541,470
<p>It seems that you are looking for an array (<a href="https://docs.python.org/3/library/array.html" rel="nofollow"><code>array.array</code></a>), not a list:</p> <pre><code>&gt;&gt;&gt; l = [1] &gt;&gt;&gt; l.append('a') &gt;&gt;&gt; import array &gt;&gt;&gt; a = array.array('l') &gt;&gt;&gt; a.append(3) &gt;&gt;&gt; a.append('a') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: an integer is required (got type str) &gt;&gt;&gt; a array('l', [3]) </code></pre> <p>As you get more and more comfortable with Python, though, you will gradually learn how to structure your code in such a way that type-checking becomes unnecessary. Personally, I've never had to use an <code>array.array</code> in Python (except in cases like this, where I'm specifically working with that module).</p>
1
2016-09-16T23:44:56Z
[ "python" ]
Why am I getting the error: No module named 'email.MIMEMultipart'?
39,541,394
<p>I'm trying to experiment with simple code to send an email from a Python script. I keep getting an error that the module 'email.MIMEMultipart' does not exist. To simplify the question/answer process, I can narrow it down even further. From the Python environment prompt I can enter</p> <h1>>>>import email</h1> <h1>>>> dir(email)</h1> <p>It will list a bunch of modules in the email module, but none of the MIME modules are there. I can see them from WindowsExplorer in the same lib folder as all the other modules. After searching other questions I did see that I had named my test program 'email.py' which I see now is a big no-no. I deleted it and verified there isn't also an 'email.pyc'.</p> <p>I'm using Windows 10, Python 3.5.2. I've also already reinstalled Python with no improvement.</p> <p>Can anyone tell me what else I should check? This is the actual code:</p> <pre><code> import smtplib from email.MIMEMultipart import MIMEMultipart </code></pre>
0
2016-09-16T23:31:36Z
39,541,559
<p>According to the examples in <a href="https://docs.python.org/3/library/email-examples.html" rel="nofollow">the documentation</a>, you need:</p> <pre><code>from email.mime.multipart import MIMEMultipar </code></pre>
0
2016-09-16T23:59:18Z
[ "python", "email", "module" ]
why does MaxAbsScaler() not set the column range to [-1,1]?
39,541,476
<p>From scikit learn documentation (<a href="http://scikit-learn.org/stable/modules/preprocessing.html" rel="nofollow">http://scikit-learn.org/stable/modules/preprocessing.html</a>), I understand that MaxAbsScaler works by dividing each column by its maximum value. This should set the maximum to be exactly one, i.e equivalent to the transformation df=df/df.max().</p> <p>This gives me the result I expect:</p> <pre><code>from sklearn import preprocessing import numpy as np import pandas as pd max_abs_scaler = preprocessing.MaxAbsScaler() df = pd.DataFrame(np.random.randn(100,50), columns=np.arange(50)) dfdividebymax = df/df.max() dfdividebymax.max(axis=0) </code></pre> <p>is an array of 1s, since every column maximum occurs at least once. However,</p> <pre><code>dftransformed = max_abs_scaler.fit_transform(df) dftransformed.max(axis=0) array([ 0.9542721 , 0.95156696, 0.98142822, 0.86959599, 0.82640483, 1. , 0.71766434, 0.97071355, 1. , 1. , 1. , 1. , 0.96306546, 1. , 1. , 0.96927375, 1. , 1. , 1. , 0.90660616, 1. , 0.93072587, 0.90154812, 0.81959713, 0.83557895, 1. , 1. , 0.988002 , 0.89144342, 0.74270055, 0.66322889, 0.93516648, 0.84134716, 1. , 1. , 1. , 1. , 1. , 1. , 0.63151867, 0.86357431, 0.71128973, 1. , 1. , 1. , 0.69890436, 1. , 1. , 0.95098563, 0.73306342]) </code></pre> <p>outputs now several columns whose maximum is strictly less than 1. What is the reason that some maxima are missed?</p>
1
2016-09-16T23:45:33Z
39,557,133
<p>The missing part lies in the fact that the transformer finds the maximum of the absolute values of your dataframe. As a result, if the absolute value is a negative in your original dataframe, you notice the "inconsistency" you pointed. In other words, in your random dataframe, the maximum absolute values of your first 5 features for instance, have negative values in df. You can see the transformation in line 784 of <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/preprocessing/data.py#L696" rel="nofollow">source code</a> </p>
1
2016-09-18T11:26:13Z
[ "python", "scikit-learn" ]
strange result from timeit
39,541,528
<p>I tried to repeat the functionality of IPython %time, but for some strange reason, results of testing of some function are horrific.</p> <p>IPython:</p> <pre><code>In [11]: from random import shuffle ....: import numpy as np ....: def numpy_seq_el_rank(seq, el): ....: return sum(seq &lt; el) ....: ....: seq = np.array(xrange(10000)) ....: shuffle(seq) ....: In [12]: %timeit numpy_seq_el_rank(seq, 10000//2) 10000 loops, best of 3: 46.1 µs per loop </code></pre> <p>Python:</p> <pre><code>from timeit import timeit, repeat def my_timeit(code, setup, rep, loops): result = repeat(code, setup=setup, repeat=rep, number=loops) return '%d loops, best of %d: %0.9f sec per loop'%(loops, rep, min(result)) np_setup = ''' from random import shuffle import numpy as np def numpy_seq_el_rank(seq, el): return sum(seq &lt; el) seq = np.array(xrange(10000)) shuffle(seq) ''' np_code = 'numpy_seq_el_rank(seq, 10000//2)' print 'Numpy seq_el_rank:\n\t%s'%my_timeit(code=np_code, setup=np_setup, rep=3, loops=100) </code></pre> <p>And its output:</p> <pre class="lang-none prettyprint-override"><code>Numpy seq_el_rank: 100 loops, best of 3: 1.655324947 sec per loop </code></pre> <p>As you can see, in python i made 100 loops instead 10000 (<em>and get 35000 times slower result</em>) as in ipython, because it takes really long time. Can anybody explain why result in python is so slow?</p> <p>UPD: Here is <code>cProfile.run('my_timeit(code=np_code, setup=np_setup, rep=3, loops=10000)')</code> output:</p> <pre class="lang-none prettyprint-override"><code> 30650 function calls in 4.987 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 4.987 4.987 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 &lt;timeit-src&gt;:2(&lt;module&gt;) 3 0.001 0.000 4.985 1.662 &lt;timeit-src&gt;:2(inner) 300 0.006 0.000 4.961 0.017 &lt;timeit-src&gt;:7(numpy_seq_el_rank) 1 0.000 0.000 4.987 4.987 Lab10.py:47(my_timeit) 3 0.019 0.006 0.021 0.007 random.py:277(shuffle) 1 0.000 0.000 0.002 0.002 timeit.py:121(__init__) 3 0.000 0.000 4.985 1.662 timeit.py:185(timeit) 1 0.000 0.000 4.985 4.985 timeit.py:208(repeat) 1 0.000 0.000 4.987 4.987 timeit.py:239(repeat) 2 0.000 0.000 0.000 0.000 timeit.py:90(reindent) 3 0.002 0.001 0.002 0.001 {compile} 3 0.000 0.000 0.000 0.000 {gc.disable} 3 0.000 0.000 0.000 0.000 {gc.enable} 3 0.000 0.000 0.000 0.000 {gc.isenabled} 1 0.000 0.000 0.000 0.000 {globals} 3 0.000 0.000 0.000 0.000 {isinstance} 3 0.000 0.000 0.000 0.000 {len} 3 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 29997 0.001 0.000 0.001 0.000 {method 'random' of '_random.Random' objects} 2 0.000 0.000 0.000 0.000 {method 'replace' of 'str' objects} 1 0.000 0.000 0.000 0.000 {min} 3 0.003 0.001 0.003 0.001 {numpy.core.multiarray.array} 1 0.000 0.000 0.000 0.000 {range} 300 4.955 0.017 4.955 0.017 {sum} 6 0.000 0.000 0.000 0.000 {time.clock} </code></pre>
0
2016-09-16T23:54:07Z
39,541,639
<p>There could be any number of reasons this code is running slower in one implementation of python than another. One may be optimized differently than another, one may pre-compile certain parts while the other is fully interpreted. The only way to figure out why is to profile your code.</p> <p><a href="https://docs.python.org/2/library/profile.html" rel="nofollow">https://docs.python.org/2/library/profile.html</a></p> <pre><code>import cProfile cProfile.run('repeat(code, setup=setup, repeat=rep, number=loops)') </code></pre> <p>Will give a result similar to</p> <pre class="lang-none prettyprint-override"><code>ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;stdin&gt;:1(testing) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.000 0.000 0.000 0.000 {method 'upper' of 'str' objects} </code></pre> <p>Which shows you when function calls were made, how many times they were made and how long they took.</p>
1
2016-09-17T00:11:59Z
[ "python", "debugging", "time", "ipython" ]
strange result from timeit
39,541,528
<p>I tried to repeat the functionality of IPython %time, but for some strange reason, results of testing of some function are horrific.</p> <p>IPython:</p> <pre><code>In [11]: from random import shuffle ....: import numpy as np ....: def numpy_seq_el_rank(seq, el): ....: return sum(seq &lt; el) ....: ....: seq = np.array(xrange(10000)) ....: shuffle(seq) ....: In [12]: %timeit numpy_seq_el_rank(seq, 10000//2) 10000 loops, best of 3: 46.1 µs per loop </code></pre> <p>Python:</p> <pre><code>from timeit import timeit, repeat def my_timeit(code, setup, rep, loops): result = repeat(code, setup=setup, repeat=rep, number=loops) return '%d loops, best of %d: %0.9f sec per loop'%(loops, rep, min(result)) np_setup = ''' from random import shuffle import numpy as np def numpy_seq_el_rank(seq, el): return sum(seq &lt; el) seq = np.array(xrange(10000)) shuffle(seq) ''' np_code = 'numpy_seq_el_rank(seq, 10000//2)' print 'Numpy seq_el_rank:\n\t%s'%my_timeit(code=np_code, setup=np_setup, rep=3, loops=100) </code></pre> <p>And its output:</p> <pre class="lang-none prettyprint-override"><code>Numpy seq_el_rank: 100 loops, best of 3: 1.655324947 sec per loop </code></pre> <p>As you can see, in python i made 100 loops instead 10000 (<em>and get 35000 times slower result</em>) as in ipython, because it takes really long time. Can anybody explain why result in python is so slow?</p> <p>UPD: Here is <code>cProfile.run('my_timeit(code=np_code, setup=np_setup, rep=3, loops=10000)')</code> output:</p> <pre class="lang-none prettyprint-override"><code> 30650 function calls in 4.987 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 4.987 4.987 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 &lt;timeit-src&gt;:2(&lt;module&gt;) 3 0.001 0.000 4.985 1.662 &lt;timeit-src&gt;:2(inner) 300 0.006 0.000 4.961 0.017 &lt;timeit-src&gt;:7(numpy_seq_el_rank) 1 0.000 0.000 4.987 4.987 Lab10.py:47(my_timeit) 3 0.019 0.006 0.021 0.007 random.py:277(shuffle) 1 0.000 0.000 0.002 0.002 timeit.py:121(__init__) 3 0.000 0.000 4.985 1.662 timeit.py:185(timeit) 1 0.000 0.000 4.985 4.985 timeit.py:208(repeat) 1 0.000 0.000 4.987 4.987 timeit.py:239(repeat) 2 0.000 0.000 0.000 0.000 timeit.py:90(reindent) 3 0.002 0.001 0.002 0.001 {compile} 3 0.000 0.000 0.000 0.000 {gc.disable} 3 0.000 0.000 0.000 0.000 {gc.enable} 3 0.000 0.000 0.000 0.000 {gc.isenabled} 1 0.000 0.000 0.000 0.000 {globals} 3 0.000 0.000 0.000 0.000 {isinstance} 3 0.000 0.000 0.000 0.000 {len} 3 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 29997 0.001 0.000 0.001 0.000 {method 'random' of '_random.Random' objects} 2 0.000 0.000 0.000 0.000 {method 'replace' of 'str' objects} 1 0.000 0.000 0.000 0.000 {min} 3 0.003 0.001 0.003 0.001 {numpy.core.multiarray.array} 1 0.000 0.000 0.000 0.000 {range} 300 4.955 0.017 4.955 0.017 {sum} 6 0.000 0.000 0.000 0.000 {time.clock} </code></pre>
0
2016-09-16T23:54:07Z
39,541,771
<p>Well, one issue is that you're misreading the results. <code>ipython</code> is telling you how long it took each of the 10,000 iterations for the set of 10,000 iterations with the lowest total time. The <code>timeit.repeat</code> module is reporting how long the whole round of 100 iterations took (again, for the shortest of three). So the real discrepancy is 46.1 µs per loop (ipython) vs. 16.5 ms per loop (python), still a factor of ~350x difference, but not 35,000x.</p> <p>You didn't show profiling results for <code>ipython</code>. Is it possible that in your <code>ipython</code> session, you did either <code>from numpy import sum</code> or <code>from numpy import *</code>? If so, you'd have been timing the <code>numpy.sum</code> (which is optimized for <code>numpy</code> arrays and would <a href="http://stackoverflow.com/a/10922744/364696">run several orders of magnitude faster</a>), while your <code>python</code> code (which isolated the globals in a way that <code>ipython</code> does not) ran the normal <code>sum</code> (that has to convert all the values to Python <code>int</code>s and sum them).</p> <p>If you check your profiling output, virtually all of your work is being done in <code>sum</code>; if that part of your code was sped up by several orders of magnitude, the total time would reduce similarly. That would explain the "real" discrepancy; in the test case linked above, it was a 40x difference, and that was for a smaller array (the smaller the array, the less <code>numpy</code> can "show off") with more complex values (vs. summing 0s and 1s here I believe).</p> <p>The remainder (if any) is probably an issue of how the code is being <code>eval</code>ed slightly differently, or possibly weirdness with the <code>random</code> shuffle (for consistent tests, you'd want to seed <code>random</code> with a consistent seed to make the "randomness" repeatable) but I doubt that's a difference of more than a few percent.</p>
3
2016-09-17T00:38:25Z
[ "python", "debugging", "time", "ipython" ]
Creating points subsets in django-models
39,541,554
<p>I am looking for a scalable way to create new user points subsets without migrating each time a new subset is created.</p> <p>For example, say I have a <code>users</code> app with a model where <code>total_points</code> is the sum of <code>pts_1</code>, <code>pts_2</code>, and <code>pts_3</code> for each user.</p> <p>I have also created a <code>campaigns</code> app that enables users to earn points by performing an action (say, clicking a button for simplicity). I can add new campaigns to the platform through the Django admin and set it up so that when users complete the campaigns, they are credited with points such that <code>(campaign, pk=n)</code> credits that user's <code>pts_n</code>.</p> <p>However, in order to do this, I need to manually add <code>pts_n</code> to <code>models.py</code> and migrate to the database. Is there a better solution? The only thing that I can think of is pre-populating <code>pts_n</code> in batches to avoid migrating every time I add a new campaign.</p> <p>Am I thinking about this the wrong way? I am pretty new to this.</p>
0
2016-09-16T23:58:28Z
39,542,693
<p>The easiest solution would be to create a UserPoints model where you record the awarding of points.</p> <pre><code>class UserPoints(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) points_amount = models.IntegerField(default=1) points_category = models.CharField(max_length=50, blank=True, null=True) </code></pre> <p>This model assumes that the category is optional.</p> <p>Now you can dynamically calculate a user's points:</p> <pre><code>user = request.user UserPoints.objects.filter(user=user).aggregate(Sum('points_amount')) </code></pre> <p>If you want just the amount of points from a certain category:</p> <pre><code>category = 'my_category' UserPoints.objects.filter(user=user, category=category).aggregate(Sum('points_amount')) </code></pre> <p>Your solution where you would constantly be adding <code>pts_n</code> columns to the database is clearly not preferable here, since that would be a lot of work and you would be using the <code>total_points</code> column as an aggregate of other columns which is not a recommended practice.</p>
0
2016-09-17T03:55:16Z
[ "python", "django", "django-models", "architecture", "scalability" ]
pyspark: convert RDD[DenseVector] to dataframe
39,541,568
<p>I have the following rdd:</p> <p>rdd.take(5) gives me:</p> <pre><code>[DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]), DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]), DenseVector([5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0, 4.0, 9.0]), DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]), DenseVector([9.2463, 2.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699])] </code></pre> <p>I would like to make it a data frame which should look like:</p> <pre><code>------------------------------------------------------------------- | features | ------------------------------------------------------------------- | [9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] | |-----------------------------------------------------------------| | [9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] | |-----------------------------------------------------------------| | [5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0, 4.0, 9.0] | |-----------------------------------------------------------------| | [9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] | |-----------------------------------------------------------------| | [9.2463, 2.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] | |-----------------------------------------------------------------| </code></pre> <p>Is this possible? I tried to use <code>df_new = sqlContext.createDataFrame(rdd,['features'])</code> , but it didn't work. Does anyone have any suggestion? Thanks!</p>
0
2016-09-17T00:00:30Z
39,548,128
<p>Map to <code>tuples</code> first:</p> <pre><code>rdd.map(lambda x: (x, )).toDF(["features"]) </code></pre> <p>Just keep in mind that as of Spark 2.0 there are two different <code>Vector</code> implementation an <code>ml</code> algorithms require <code>pyspark.ml.Vector</code>.</p>
1
2016-09-17T14:48:37Z
[ "python", "pyspark", "spark-dataframe", "apache-spark-ml" ]
faster and more 'pythonic' list of dictionaries
39,541,577
<p>For simplicity, I've provided 2 lists in a list, but I'm actually dealing with a hundred of lists in a list, each containing a sizable amount of dictionaries. I only want to get the value of 'status' key in the 1st dictionary without checking any other dictionaries in that list (since I know they all contain the same value at that key). Then I will perform some sort of clustering within each big dictionary. I need to efficiently concatenate all 'title' values. Is there a way to make my code more elegant and much faster?</p> <p>I have:</p> <pre><code>nested = [ [ {'id': 287, 'title': 'hungry badger', 'status': 'High'}, {'id': 437, 'title': 'roadtrip to Kansas','status': 'High'} ], [ {'id': 456, 'title': 'happy title here','status': 'Medium'}, {'id': 342,'title': 'soft big bear','status': 'Medium'} ] ] </code></pre> <p>I'd like:</p> <pre><code>result = [ { 'High': [ {'id': 287, 'title': 'hungry badger'}, {'id': 437, 'title': 'roadtrip to Kansas'} ] }, { 'Medium': [ {'id': 456, 'title': 'happy title here'}, {'id': 342, 'title': 'soft big bear'} ] } ] </code></pre> <p>What I tried:</p> <pre><code>for oneList in nested: result= {} for i in oneList: a= list(i.keys()) m= [i[key] for key in a if key not in ['id','title']] result[m[0]]=oneList for key in a: if key not in ['id','title']: del i[key] </code></pre>
3
2016-09-17T00:02:13Z
39,541,622
<pre><code>from itertools import groupby result = groupby(sum(nested,[]), lambda x: x['status']) </code></pre> <p>How it works:</p> <p><code>sum(nested,[])</code> concatenates all your outer lists together into one big list of dictionaries</p> <p><code>groupby(, lambda x: x['status'])</code> groups all your objects by their status property</p> <p>Note itertools.groupby returns a generator (not a list), so if you want to materialize the generator you need to do something like follows.</p> <pre><code>from itertools import groupby result = groupby(sum(nested,[]), lambda x: x['status']) result = {key:list(val) for key,val in result} </code></pre>
2
2016-09-17T00:09:16Z
[ "python", "dictionary" ]
faster and more 'pythonic' list of dictionaries
39,541,577
<p>For simplicity, I've provided 2 lists in a list, but I'm actually dealing with a hundred of lists in a list, each containing a sizable amount of dictionaries. I only want to get the value of 'status' key in the 1st dictionary without checking any other dictionaries in that list (since I know they all contain the same value at that key). Then I will perform some sort of clustering within each big dictionary. I need to efficiently concatenate all 'title' values. Is there a way to make my code more elegant and much faster?</p> <p>I have:</p> <pre><code>nested = [ [ {'id': 287, 'title': 'hungry badger', 'status': 'High'}, {'id': 437, 'title': 'roadtrip to Kansas','status': 'High'} ], [ {'id': 456, 'title': 'happy title here','status': 'Medium'}, {'id': 342,'title': 'soft big bear','status': 'Medium'} ] ] </code></pre> <p>I'd like:</p> <pre><code>result = [ { 'High': [ {'id': 287, 'title': 'hungry badger'}, {'id': 437, 'title': 'roadtrip to Kansas'} ] }, { 'Medium': [ {'id': 456, 'title': 'happy title here'}, {'id': 342, 'title': 'soft big bear'} ] } ] </code></pre> <p>What I tried:</p> <pre><code>for oneList in nested: result= {} for i in oneList: a= list(i.keys()) m= [i[key] for key in a if key not in ['id','title']] result[m[0]]=oneList for key in a: if key not in ['id','title']: del i[key] </code></pre>
3
2016-09-17T00:02:13Z
39,541,667
<p>You could make a <code>defaultdict</code> for each nested list:</p> <pre><code>import collections nested = [ [{'id': 287, 'title': 'hungry badger', 'status': 'High'}, {'id': 437, 'title': 'roadtrip to Kansas','status': 'High'}], [{'id': 456, 'title': 'happy title here','status': 'Medium'}, {'id': 342,'title': 'soft big bear','status': 'Medium'}] ] result = [] for l in nested: r = collections.defaultdict(list) for d in l: name = d.pop('status') r[name].append(d) result.append(r) </code></pre> <p>This gives the following <code>result</code>:</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(result) [{'High': [{'id': 287, 'title': 'hungry badger'}, {'id': 437, 'title': 'roadtrip to Kansas'}]}, {'Medium': [{'id': 456, 'title': 'happy title here'}, {'id': 342, 'title': 'soft big bear'}]}] </code></pre>
2
2016-09-17T00:20:18Z
[ "python", "dictionary" ]
Use assert in normal code
39,541,590
<p>I'm writing a python function to validate a token from an email. In the email, there is a url with the endpoint of it. I have two url parameters, the token and email address. In my endpoint I have to check : </p> <ul> <li>if the parameters are in the URL</li> <li>if there is a associate token in the database</li> <li>if it corresponds to the user email</li> <li>if the token is still valid (expires after 2 days)</li> <li>if it has already been used</li> </ul> <p>I choose to wrap all those checks in a <code>try except</code> block, I will always return the same error "invalid token" so I don't have to precisely check individual error. I used the function <code>assertFalse</code> and <code>assertEqual</code> that will raise an exception if it's not correct.</p> <pre><code>try: # pull from url email = request.GET['email'] value_token = request.GET['token'] # test if valid token = EmailValidationToken.objects.get(token=value_token) assertFalse(token.consumed) assertEqual(email, token.user.email) assertFalse(token.is_expired()) except: pass # return error </code></pre> <p>I like the way I did it because it's super clean. Is it a good practice ? Is there other solution for this problem ?</p>
0
2016-09-17T00:04:31Z
39,541,698
<p>No, using <code>assert</code> for control flow rather than debugging is poor practice, because assertions can be turned off. Just use an ordinary <code>if</code> statement.</p> <pre><code># pull from url email = request.GET['email'] value_token = request.GET['token'] # test if valid token = EmailValidationToken.objects.get(token=value_token) if token.consumed or email != token.user.email or token.is_expired(): pass # return error </code></pre> <p>If you absolutely insist on controlling your program's flow by raising an error (which is a valid thing to do in some cases), do so with <code>raise</code>, e.g. <code>if condition: raise TypeError</code>.</p>
5
2016-09-17T00:25:19Z
[ "python", "assert" ]
Setting default histtype in matplotlib?
39,541,655
<p>Is there a way to configure the default argument for <code>histtype</code> of matplotlib's <code>hist()</code> function? The default behavior is to make bar-chart type histograms, which I basically <em>never</em> want to look at, since it is horrible for comparing multiple distributions that have significant overlap.</p> <p>In case it's somehow relevant, the default behavior I would like to attain is to have <code>histtype='step'</code>.</p>
2
2016-09-17T00:17:10Z
39,543,370
<p>Thank you for prompting me to look at this, as I much prefer <code>'step'</code> style histograms too! I solved this problem by going into the matplotlib source code. I use anaconda, so it was located in <code>anaconda/lib/site-packages/python2.7/matplotlib</code>.</p> <p>To change the histogram style I edited two of the files. Assuming that the current directory is <code>matplotlib/</code>, then open up <code>axes/_axes.py</code> and locate the <code>hist()</code> function there (it's on line 5690 on my machine, matplotlib version 1.5.1). You should see the <code>histtype</code> argument there. Change this to <code>'step'</code>.</p> <p>Now open up <code>pyplot.py</code> and again locate the <code>hist()</code> function and make the same change to the <code>histtype</code> argument (line 2943 in version 1.5.1 and on my machine). There is a comment about not editing this function, but I only found this to be an issue when I didn't also edit <code>axes/_axes.py</code> as well.</p> <p>This worked for me! Another alternative would be just to write a wrapper around <code>hist()</code> yourself that changes the default argument. </p>
1
2016-09-17T06:01:26Z
[ "python", "matplotlib", "data-analysis" ]
Calculate directory path in Python module distribution
39,541,678
<p>I have a Python module distribution (it's an egg) that contains some additional files &amp; directories that I would like to copy during my program's runtime. </p> <pre><code>├── mypkg │ ├── extra_files │ │ ├── layouts/ │ │ ├── scripts/ │ │ └── config.yaml </code></pre> <p>When <code>mypkg</code> is being used, I would like to copy all contents of <code>extra_files</code> directory to somewhere else on disk. Something like:</p> <pre><code>shutil.copytree('mypkg/extra_files', destination) </code></pre> <p>I've taken a look at <code>pkg_resources</code> however it seem like I can't calculate the path to a directory that way.</p> <p>How can I calculate the path to files and directories in my distribution package? Do I need to first list all directories and then call <code>pkg_resources.resource_stream</code> on each file in each directory? </p>
0
2016-09-17T00:22:21Z
39,682,573
<p>I was able to actually do this with <code>__file__</code>, which returns the pathname from which the module was first loaded. I can get the full path to my static directory like this:</p> <pre><code>import os directory = os.path.join(os.path.dirname(__file__), 'templates/index.html') </code></pre>
0
2016-09-25T01:28:59Z
[ "python", "module", "pkg-resources" ]
basic understanding of simple socket server
39,541,706
<p>I am new to socket programming and am trying to understand how sockets work. Presently I am trying to play with python socket library to see how it works. </p> <p>Now there are a few things that I am not able to wrap my head around. Let's take an example as shown <a href="http://www.bogotobogo.com/python/python_network_programming_server_client.php" rel="nofollow">here</a> of a simple echo client and server written in python using the Python socket library. </p> <p>The <strong>echo server</strong> looks like the below # echo_server.py import socket</p> <pre><code>host = '' # Symbolic name meaning all available interfaces port = 12345 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() </code></pre> <p>The <strong>echo client</strong> looks like the below</p> <pre><code># echo_client.py import socket host = socket.gethostname() port = 12345 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.sendall(b'Hello, world') data = s.recv(1024) s.close() print('Received', repr(data)) </code></pre> <p><strong>My Questions</strong></p> <ol> <li>In echo_server.py when I say conn, addr = s.accept(), accept() does two things. 1. it returns the connecting client's address (ip and port), which is stored in addr and 2. It creates a new socket (called client socket) that can be referenced here using conn and is used to interact with the connected client. <blockquote> <p>Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?</p> </blockquote></li> <li>Again in echo_server.py, the s.listen(1) suggests there is a maximum of 1 backlog allowed, which I seem to understand only theoretically that it is the maximum number of clients that the server wants to allow to keep waiting in the queue while the server is busy dealing with the already connected client. <blockquote> <p>Is there some simple practical example to demo this ?</p> </blockquote></li> </ol>
1
2016-09-17T00:27:01Z
39,541,752
<blockquote> <p>Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?</p> </blockquote> <p>In your example, nothing interesting will happen. The attempt to connect will hang. Each client call to <code>connect()</code> must match a server call to <code>accept()</code>. Since you call <code>accept()</code> exactly once, at most one client will ever connect.</p> <p>If you want to be able to accept connections from subsequent clients, serially, try this:</p> <pre><code>import socket host = '' # Symbolic name meaning all available interfaces port = 12345 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) while True: conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() </code></pre> <p>If you want to be able to accept connections from clients in parallel, ie. from multiple clients simultaneously, then you have more work to do. But that isn't really part of your question today.</p>
0
2016-09-17T00:35:14Z
[ "python", "sockets", "networking", "tcp-ip" ]
basic understanding of simple socket server
39,541,706
<p>I am new to socket programming and am trying to understand how sockets work. Presently I am trying to play with python socket library to see how it works. </p> <p>Now there are a few things that I am not able to wrap my head around. Let's take an example as shown <a href="http://www.bogotobogo.com/python/python_network_programming_server_client.php" rel="nofollow">here</a> of a simple echo client and server written in python using the Python socket library. </p> <p>The <strong>echo server</strong> looks like the below # echo_server.py import socket</p> <pre><code>host = '' # Symbolic name meaning all available interfaces port = 12345 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() </code></pre> <p>The <strong>echo client</strong> looks like the below</p> <pre><code># echo_client.py import socket host = socket.gethostname() port = 12345 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.sendall(b'Hello, world') data = s.recv(1024) s.close() print('Received', repr(data)) </code></pre> <p><strong>My Questions</strong></p> <ol> <li>In echo_server.py when I say conn, addr = s.accept(), accept() does two things. 1. it returns the connecting client's address (ip and port), which is stored in addr and 2. It creates a new socket (called client socket) that can be referenced here using conn and is used to interact with the connected client. <blockquote> <p>Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?</p> </blockquote></li> <li>Again in echo_server.py, the s.listen(1) suggests there is a maximum of 1 backlog allowed, which I seem to understand only theoretically that it is the maximum number of clients that the server wants to allow to keep waiting in the queue while the server is busy dealing with the already connected client. <blockquote> <p>Is there some simple practical example to demo this ?</p> </blockquote></li> </ol>
1
2016-09-17T00:27:01Z
39,546,051
<blockquote> <blockquote> <p>Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?</p> </blockquote> </blockquote> <p>As pointed out by Rob in another answer, your code will accept only one client. The <code>accept</code> have to be called for any connect request from client. And code accordingly. Now coming to your question, yes, the (conn,addr) pair will be overwritten. The code should take care of passing them on to some connection thread before calling <code>accept</code> again for new connection.</p> <blockquote> <blockquote> <p>Is there some simple practical example to demo this ?s there some simple practical example to demo this ?</p> </blockquote> </blockquote> <p>In the updated code for accepting multiple clients try not calling <code>accept</code> after few connections and notice the TCP connection status table (with <code>netstat</code> for example) to see the behavior for varying values of backlog.</p>
0
2016-09-17T11:03:24Z
[ "python", "sockets", "networking", "tcp-ip" ]
Django: "cannot import name import_string" while using "rest_framework_docs"
39,541,722
<p>I installed <code>drfdocs</code> by following the steps as mentioned <a href="http://drfdocs.com/installation/" rel="nofollow">here</a>. But I am getting <code>cannot import name import_string</code>.</p> <p>Below is the stacktrace:</p> <pre><code>ImportError at / cannot import name import_string Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.6.5 Exception Type: ImportError Exception Value: cannot import name import_string Exception Location: /usr/local/lib/python2.7/dist-packages/rest_framework_docs/api_docs.py in &lt;module&gt;, line 4 Python Executable: /usr/bin/python </code></pre> <p>I am using <code>Django 1.6.5</code> and <code>django-rest-framework-docs==0.1.7</code></p> <p>Below is the list of <code>pip packages</code> installed on my system:</p> <pre><code>moin@moin-pc:~/workspace/my_project$ pip freeze adium-theme-ubuntu==0.3.4 boto==2.42.0 coreapi==2.0.0 dateutils==0.6.6 Django==1.6.5 django-cors-headers==1.1.0 django-countries==4.0 django-debug-toolbar==1.5 django-rest-framework-docs==0.1.7 django-rest-swagger==2.0.5 django-storages==1.5.1 django-tastypie==0.13.3 django-tastypie-swagger==0.1.4 djangorestframework==2.3.13 drfdocs==0.0.11 itypes==1.1.0 jsonpickle==0.9.3 mysqlclient==1.3.7 openapi-codec==1.0.0 Pillow==3.3.1 psycopg2==2.6.2 pygeocoder==1.2.5 python-dateutil==2.5.3 python-mimeparse==1.5.2 pytz==2016.6.1 PyYAML==3.12 requests==2.11.1 simplejson==3.8.2 six==1.10.0 sqlparse==0.2.1 ua-parser==0.7.1 unity-lens-photos==1.0 uritemplate==3.0.0 user-agents==1.0.1 </code></pre> <p>I am sure it is due to any conflict between package version. Any help will be appreciated.</p>
0
2016-09-17T00:31:35Z
39,542,379
<p>It was due to the conflict in the version of <code>drfdocs</code> with <code>django-rest-framework</code>. Downgrading my version from <code>drfdocs==0.0.11</code> to <code>drfdocs==0.0.6</code> fixed the issue.</p>
0
2016-09-17T02:40:31Z
[ "python", "django", "python-2.7", "django-rest-framework", "django-1.6" ]
Do all models in Django basically have init constructors that assign to object variables
39,541,728
<p>Suppose I have something like this</p> <pre><code>class Album(models.Model): artist = models.CharField(max_length=128, unique=True) title = models.CharField(max_length=128, unique=True) </code></pre> <p>Now I can do this</p> <pre><code>inst = Album(artist="Shania Twain",title="blah") </code></pre> <p>Since I have not studied how model classes are created under the hood , I am curious do all the model classes have an init constructor as well ? 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) def __init__(self,artist): Album.artist = artist .......... .......... </code></pre> <p>Please let me know if this makes sense.</p>
0
2016-09-17T00:31:58Z
39,541,748
<p>Yes it has, but is not recommend to override it.</p> <p>You can do it like this. But It's not recommended.</p> <pre><code> def __init__(self, name, email, password, *args, **kwargs): super(models.Model, self).__init__(*args, **kwargs) self.name = name self.email = email # or whatever you want </code></pre> <p>From Django docs</p> <blockquote> <p>You may be tempted to customize the model by overriding the <strong>init</strong> method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved.</p> </blockquote> <p>If you want add fields or do something else, trying to add a create method in your models</p> <pre><code>from django.db import models class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): book = cls(title=title) # do something with the book return book book = Book.create("Pride and Prejudice") </code></pre>
1
2016-09-17T00:34:53Z
[ "python", "django" ]
Why isn't my Model Query set working properly?
39,541,791
<p>I'm building a Q&amp;A style community with categories containing forums which contain Topics and each topic has posts. On the landing page, I want popular Topics across all categories and when inside a category, I want all popular Topics within that category. I've defined template filters to do this but they aren't displaying anything at the category or home levels. They kind of work at the forum level i.e., inside a particular forum it is able to fetch all the topics in that forum. Inside a category, it is supposed to fetch all Topics from each of the forum in that category, currently, it just returns a list of the forums in that category rather than the list of all topics. At the home level, it is supposed to return a list of topics across all categories and contained forums but I get nothing.</p> <p>Can someone please help me figure out whats happening here:? Thanks</p> <p>My TOPICSFORALL.HTML:</p> <pre><code>{% block card_body %} {% for topic in topic_list %} {% include "subjectcard.html" with topic=topic %} {% endfor %} {% endblock %} </code></pre> <p>My SUBJECTCARD.HTML:</p> <pre><code>{% block card_body %} {% for topic in topic_list %} {% include "subjectcard.html" with topic=topic %} {% endfor %} {% endblock %} </code></pre> <p>My SITE_BASE.HTML:</p> <pre><code>{% extends "theme_bootstrap/base.html" %} {% load i18n pybb_tags topicsbycat topicsbyforum %} {% load static %} {% catindexlist as catindexlisted %} {% topicsbyall as topicsbyallcatnforum %} ... {% block body %} &lt;!-- Main hero unit for a primary marketing message or call to action --&gt; &lt;div class="col-xs-2 col-sm-3 col-md-2 col-lg-2" style="border-right:solid;text-align:right;height:99%;padding:0 0 0 0px;" id="sidebar"&gt;{% include "categoryindex.html" %}&lt;/div&gt; &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" id="homebread"&gt;{% include "breadcrumbbt.html" %}&lt;/div&gt; {% if category %} &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" style="height:auto;padding-bottom:10px;text-align:center;"&gt;{% include "topicstyleforumindex.html" %}&lt;/div&gt; &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" style="height:auto;padding-bottom:10px;text-align:center;"&gt;{% include "topicsforall.html" with topic_list=category|topicsbycat %}&lt;/div&gt; {% elif forum %} &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" style="height:auto;padding-bottom:10px;text-align:center;"&gt;{% include "topicindex.html" %}&lt;/div&gt; &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" style="height:auto;padding-bottom:10px;text-align:center;"&gt;{% include "topicsforall.html" with topic_list=forum|topicsbyforum %}&lt;/div&gt; {% elif topic %} &lt;div class="main-block col-xs-6 col-xs-offset-1 col-sm-6 col-sm-offset-3 col-md-6 col-md-offset-2 col-lg-6 col-lg-offset-2" id="content" style="height:80%;"&gt;{% include 'pybb/topic.html' %}&lt;/div&gt; {% else %} &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" style="height:auto;padding-bottom:10px;text-align:center;"&gt;{% include "topicstyleforumindex.html" %}&lt;/div&gt; &lt;div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 col-lg-10 col-lg-offset-2" style="height:auto;padding-bottom:10px;text-align:center;"&gt;{% include "topicsforall.html" with topic_list=topicsbyallcatnforum %}&lt;/div&gt; {% endif %} {% endblock %} </code></pre> <p>My PYBB_TAGS.PY:</p> <pre><code>@register.assignment_tag def topicsbyall(): topic_list = Topic.objects.all().order_by('-updated', '-created') return topic_list </code></pre> <p>My TOPICSBYFORUM.PY: register = template.Library()</p> <p>@register.filter</p> <pre><code>def topicsbyforum(forum): topic_list = Topic.objects.filter(forum=forum).order_by('post_count','views','-updated') return topic_list </code></pre> <p>My TOPICSBYCAT.PY:</p> <pre><code>register = template.Library() @register.filter def topicsbycat(category): topic_list = [] catforum = Forum.objects.filter(category=category).order_by('topic_count','post_count') for forum in catforum: forumtopics = Topic.objects.filter(forum=forum).order_by('post_count','views','-updated') topic_list.append(forumtopics) return topic_list </code></pre>
0
2016-09-17T00:41:12Z
39,542,079
<p>I'm not sure what exactly the issue was but I kinda got it to work by changing the template filters to do just on queryset each and using more for loops in my templates while calling the filters. I guess filters have some constraints in this area. I'll try finding more specific points that will clarify this issue and update this post but until then, thanks to the 6 people who tried answering my question!</p>
0
2016-09-17T01:36:27Z
[ "python", "django", "django-models", "django-templates", "django-template-filters" ]
opening and manipulating text files with python
39,541,809
<p>So I've done a lot of browsing, but I cant seem to open my text file so I can begin to manipulate it. </p> <p>I saved my program in with the same file: and my first line returns no errors:</p> <pre><code>fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt' with open(fpath) as f_in: dates= f_in.read() f_in.close() </code></pre> <p>But now is my file open? The text file (file_list.txt) is: </p> <p>3B43.20000101.7.tif</p> <p>3B43.20000201.7.tif</p> <p>3B43.20000301.7.tif</p> <p>3B43.20000401.7.tif</p> <p>3B43.20000501.7.tif...</p> <p>and so on, so now I need to assign dates(jan, feb, mar etc) instead of numbers, but I havent used anything without "" so I'm a little lost and while I can find a lot on CSV files I havent been able to find what I need on txt files so any references would be much appreciated. </p> <p>Thanks! </p> <p>ps. If anyone knows how to change my hard drives name to something other than veggiepunk1363 PLEASE let me know! haha</p> <p>my new code:</p> <p>f = open('/Users/veggiepunk1363/Desktop/geoproccessing/file_listmaster3.txt','r') filedata = f.read() f.close()</p> <p>Jan = filedata.replace("20001","2000Jan")</p> <p>Feb = filedata.replace("20002","2000Feb")</p> <p>Mar= filedata.replace("20003","2000Mar")</p> <p>Apr= filedata.replace("20004","2000Apr")</p> <p>May= filedata.replace("20005","2000May")</p> <p>Jun= filedata.replace("20006","2000Jun")</p> <p>Jul= filedata.replace("20007","2000Jul")</p> <p>Aug= filedata.replace("20008","2000Aug")</p> <p>Sep= filedata.replace("20009","2000Sep")</p> <p>Oct= filedata.replace("20010","2000Oct")</p> <p>Nov= filedata.replace("20011","2000Nov")</p> <p>Dec= filedata.replace("20012","2000Dec")</p> <p>f = open('/Users/veggiepunk1363/Desktop/geoproccessing/file_listmaster3.txt','w')</p> <p>f.write(Jan)</p> <p>f.write(Feb)</p> <p>f.write(Mar)</p> <p>f.write(Apr)</p> <p>f.write(May)</p> <p>f.write(Jun)</p> <p>f.write(Jul)</p> <p>f.write(Aug)</p> <p>f.write(Sep)</p> <p>f.write(Oct)</p> <p>f.write(Nov)</p> <p>f.write(Dec)</p> <p>print ('The dates have been reformatted') </p> <p>f.close()</p> <p>I know this is the long way to do what I'm trying to do, but I thought it would still work... it didnt. it tripled the size of my txt file and it looks like everything was duplicated? not quite sure what is going on. </p>
0
2016-09-17T00:43:15Z
39,541,882
<p>You need not use a context manager. This is much simpler and does not require you to explicitly close the file descriptor:</p> <pre><code>for file_name in open(fpath).readlines(): print file_name # 3B43.20000101.7.tif... </code></pre>
-1
2016-09-17T00:56:16Z
[ "python", "file", "text" ]
opening and manipulating text files with python
39,541,809
<p>So I've done a lot of browsing, but I cant seem to open my text file so I can begin to manipulate it. </p> <p>I saved my program in with the same file: and my first line returns no errors:</p> <pre><code>fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt' with open(fpath) as f_in: dates= f_in.read() f_in.close() </code></pre> <p>But now is my file open? The text file (file_list.txt) is: </p> <p>3B43.20000101.7.tif</p> <p>3B43.20000201.7.tif</p> <p>3B43.20000301.7.tif</p> <p>3B43.20000401.7.tif</p> <p>3B43.20000501.7.tif...</p> <p>and so on, so now I need to assign dates(jan, feb, mar etc) instead of numbers, but I havent used anything without "" so I'm a little lost and while I can find a lot on CSV files I havent been able to find what I need on txt files so any references would be much appreciated. </p> <p>Thanks! </p> <p>ps. If anyone knows how to change my hard drives name to something other than veggiepunk1363 PLEASE let me know! haha</p> <p>my new code:</p> <p>f = open('/Users/veggiepunk1363/Desktop/geoproccessing/file_listmaster3.txt','r') filedata = f.read() f.close()</p> <p>Jan = filedata.replace("20001","2000Jan")</p> <p>Feb = filedata.replace("20002","2000Feb")</p> <p>Mar= filedata.replace("20003","2000Mar")</p> <p>Apr= filedata.replace("20004","2000Apr")</p> <p>May= filedata.replace("20005","2000May")</p> <p>Jun= filedata.replace("20006","2000Jun")</p> <p>Jul= filedata.replace("20007","2000Jul")</p> <p>Aug= filedata.replace("20008","2000Aug")</p> <p>Sep= filedata.replace("20009","2000Sep")</p> <p>Oct= filedata.replace("20010","2000Oct")</p> <p>Nov= filedata.replace("20011","2000Nov")</p> <p>Dec= filedata.replace("20012","2000Dec")</p> <p>f = open('/Users/veggiepunk1363/Desktop/geoproccessing/file_listmaster3.txt','w')</p> <p>f.write(Jan)</p> <p>f.write(Feb)</p> <p>f.write(Mar)</p> <p>f.write(Apr)</p> <p>f.write(May)</p> <p>f.write(Jun)</p> <p>f.write(Jul)</p> <p>f.write(Aug)</p> <p>f.write(Sep)</p> <p>f.write(Oct)</p> <p>f.write(Nov)</p> <p>f.write(Dec)</p> <p>print ('The dates have been reformatted') </p> <p>f.close()</p> <p>I know this is the long way to do what I'm trying to do, but I thought it would still work... it didnt. it tripled the size of my txt file and it looks like everything was duplicated? not quite sure what is going on. </p>
0
2016-09-17T00:43:15Z
39,542,595
<p>Try this way. "veggiepunk1363" is not the name of your hard drive is the folder in which your User files resides on Windows.</p> <pre><code>fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt' with open(fpath, 'r') as f_in: #opens the file with read mode dates = f_in.readlines() #returns a list of all the lines in the file into dates </code></pre>
-2
2016-09-17T03:33:53Z
[ "python", "file", "text" ]
Plotting a histogram
39,541,811
<p>I am trying to plot a histogram with mu and sigma. </p> <p>Im trying to use the ec_scores values on the y axis, its supposed to show me 0.1 to 1.0 It gives me 1, 2, 3, 4, 5, 6 on the y axis instead. Im not getting any errors but this is throwing off the graph completely. Please assist me and tell me what I am doing wrong and how can i get the graph to be generated properly. Thanks. </p> <p>This is my code :</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab x = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) ec_scores = np.array([1., 1., 1., 0.95923677, 0.94796184, 1., 0.76669558, 1., 0.99913194, 1.]) mu, sigma = (np.mean(ec_scores), np.std(ec_scores)) fig = plt.figure() ax = fig.add_subplot(111) n, bins, patches = ax.hist(x, 50, normed=1, facecolor='blue', alpha=0.75) bincenters = 0.5*(bins[1:]+bins[:-1]) y = mlab.normpdf( bincenters, mu, sigma) l = ax.plot(bincenters, y, 'r--', linewidth=1) ax.set_xlabel('Parameters') ax.set_ylabel('EC scores ') plt.plot(x, ec_scores) ax.grid(True) plt.show() </code></pre> <p>Currently the graph looks like this: <a href="http://i.stack.imgur.com/Kh2jh.png" rel="nofollow"><img src="http://i.stack.imgur.com/Kh2jh.png" alt="enter image description here"></a></p>
2
2016-09-17T00:43:48Z
39,727,268
<p>As mentioned by @benton in the comments, you can plot the ec_scores as a <a href="http://matplotlib.org/examples/api/barchart_demo.html" rel="nofollow">barchart</a>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) ec_scores = np.array([1., 1., 1., 0.95923677, 0.94796184, 1., 0.76669558, 1., 0.99913194, 1.]) mu, sigma = (np.mean(ec_scores), np.std(ec_scores)) fig = plt.figure() ax = fig.add_subplot(111) rects = ax.bar(x, ec_scores, width=0.1, align='center', facecolor='blue', alpha=0.75) ax.set_xlabel('Parameters') ax.set_ylabel('EC scores ') ax.grid(True) plt.show() </code></pre> <p>Which will look like this: <a href="http://i.stack.imgur.com/KHSO6.png" rel="nofollow"><img src="http://i.stack.imgur.com/KHSO6.png" alt="Plotted as a barplot."></a></p> <p>You can also add error bars by passing an array to the <code>yerr</code> parameter. This is illustrated in the barchart example I linked to above. I am not sure what exactly you are trying to do with normpdf, but the barchart returns a list of rectangles instead of bins, so you might need to adapt this to your code.</p> <p>I hope this helps.</p>
0
2016-09-27T14:23:53Z
[ "python", "matplotlib", "graph", "histogram" ]
Best way to add a form to multiple pages?
39,541,891
<p>I'm working on a project, that has a bunch of views with corresponding templates and forms. Every template contains a link to a login page (inherits it from the main template):</p> <pre><code>&lt;ul class="options"&gt; ... &lt;li id="login"&gt; &lt;a class="button" href="{% url 'forum:login' %}?next={{ request.path }}"&gt;Sign in&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And it leads to a separate login page, that renders standard django login form.</p> <p>I want to use jQuery to create or make visible that form on the same page where login link was clicked. What is the best way to add a form to multiple pages? </p> <p>I've tried to get html and build a form dynamically with ajax:</p> <p><strong>view:</strong></p> <pre><code>class Login(FormView): ... def get(self, request, *args, **kwargs): if request.is_ajax(): form = self.get_form().as_ul() return HttpResponse(form) else: return super(Login, self).get(request, *args, **kwargs) </code></pre> <p><strong>script:</strong></p> <pre><code>$(document).ready(function() { $('#login').on('click', 'a', function(event) { var loginUrl = $(this).attr('href'); $.ajax({ url: loginUrl, type: 'GET'}) .done(function(html) { var newForm = $('&lt;form/&gt;', {action: loginUrl, method: 'post'}); newForm.insertAfter('ul.options'); newForm.append($('&lt;input/&gt;', {type: 'hidden', name: 'csrfmiddlewaretoken', value: csrftoken})); var newList = $('&lt;ul/&gt;'); newForm.append(newList); newList.append(html); newList.append($('&lt;li&gt;&lt;input type="submit" value="Sign in"/&gt;&lt;/li&gt;')); }); event.preventDefault(); }); }); </code></pre> <p>But I wonder, if there any better ways to complete such task?</p> <p>Also I'm new to jQuery, so I'd appreciate any remarks on the code.</p>
0
2016-09-17T00:58:26Z
39,541,990
<p>you can put your form in it's own template loginform.html and then use "include" where you want it with:</p> <pre><code>{% include './path-to/loginform.html' %} </code></pre> <p>edit: This is also a great way to handle things like your css and javascript areas, nav-menu, etc. <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#include" rel="nofollow">The Docs</a></p>
2
2016-09-17T01:19:31Z
[ "jquery", "python", "ajax", "django" ]
Convert Cocoa timestamp in Python
39,541,908
<p>I have a Cocoa timestamp (zero time of January 1st, 2001 00:00:00 UTC) that I need to convert in Python. When I use the following code it assumes a Unix timestamp input. Besides adding 31 years in seconds (Just under a billion seconds...) what's the best way to convert the time?</p> <pre><code>import datetime print(datetime.datetime.fromtimestamp(int("495759456")).strftime('%Y-%m-%d %H:%M:%S')) </code></pre> <p>The output for this line of code is '1985-09-16 16:12:03'</p>
1
2016-09-17T01:01:03Z
39,542,440
<p>Would something like this work for you:</p> <pre><code>from datetime import datetime unix = datetime(1970, 1, 1) # UTC cocoa = datetime(2001, 1, 1) # UTC delta = cocoa - unix # timedelta instance timestamp = datetime.fromtimestamp(int("495759456")) + delta print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) </code></pre> <p>I didn't specify timezone information for the two starts of time as they're in the same zone so I assume it shouldn't matter which is used when computing the difference. For converting the timestamp string, you may need to adjust for your timezone if it's different than the one in which the string was generated.</p> <p>The above code produces <code>2016-09-16 15:57:36</code></p>
1
2016-09-17T02:56:45Z
[ "python", "cocoa", "timestamp" ]
Extract netcdf4 variable slice by dimension name
39,541,950
<p>I have a netCDF file with 4 dimensions. I want to extract a slice from the netCDF file by giving the name of one of the dimensions </p> <p>I know how to do this by position. E.g.</p> <pre><code>from netCDF4 import Dataset hndl_nc = Dataset(path_to_nc) # Access by slice hndl_nc.variables['name_variable'][:,5,:,:] </code></pre> <p>Given that I know the names of the dimensions, say <code>A</code>, <code>B</code>, <code>C</code>, <code>D</code>. How do I access by dimension name instead of position?</p>
0
2016-09-17T01:09:25Z
39,548,112
<p>You can use <a href="http://xarray.pydata.org/en/stable/indexing.html#indexing-with-labeled-dimensions" rel="nofollow">xarray</a>'s indexing capabilities to access netcdf data by dimension name. </p> <pre><code>import xarray as xr ds = xr.open_dataset('./foo.nc') var = ds['name_variable'] # Slice var by Dimension "A" between values 0 and 5 var_slice = var.sel(A=slice(0,5)) </code></pre>
1
2016-09-17T14:47:25Z
[ "python", "netcdf" ]
Python: Performing Mathematical Functions between IP Address Octets
39,541,973
<p>I'm trying to perform the following:</p> <pre><code>firstoctet * 256 + secondoctet = * 256 + thirdoctet = * 256 + fourthoctet = x </code></pre> <p>When I use this as an example :</p> <pre><code>64.233.187.99 (google.com) 64 * 256 + 233 = * 256 + 187 = * 256 + 99 = http://1089059683/ </code></pre> <p>Can someone please provide a method as to how this can be done? The mathematical sequence is no problem, i'm just unsure as to how I can take the octet values out of the decimal points to perform the math functions. </p> <p>Thanks in advance!</p>
0
2016-09-17T01:14:42Z
39,542,090
<p>Convert an IP address string to a list of integers like this:</p> <pre><code>ip_as_string = "64.233.187.99" ip_as_ints = [int(a) for a in ip_as_string.split('.')] </code></pre> <p><code>ip_as_ints</code> will be [64, 233, 187, 99].</p> <p>I will guess that the mathematical expression that you intend to perform is RPN for converting the byte sequence from a base-256 representation to a single number. (Thanks to ShadowRanger for showing this). You can obtain that single number easily as follows:</p> <pre><code>x = functools.reduce(lambda x,y: (x &lt;&lt; 8) | y, ip_as_ints, 0) print(x) </code></pre> <p>x is 1089059683.</p>
0
2016-09-17T01:39:17Z
[ "python", "python-2.7", "python-3.x" ]
Python: Performing Mathematical Functions between IP Address Octets
39,541,973
<p>I'm trying to perform the following:</p> <pre><code>firstoctet * 256 + secondoctet = * 256 + thirdoctet = * 256 + fourthoctet = x </code></pre> <p>When I use this as an example :</p> <pre><code>64.233.187.99 (google.com) 64 * 256 + 233 = * 256 + 187 = * 256 + 99 = http://1089059683/ </code></pre> <p>Can someone please provide a method as to how this can be done? The mathematical sequence is no problem, i'm just unsure as to how I can take the octet values out of the decimal points to perform the math functions. </p> <p>Thanks in advance!</p>
0
2016-09-17T01:14:42Z
39,542,125
<p>If you're on Python 3.3 or higher, you can leverage <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">the <code>ipaddress</code> module</a> to avoid reinventing the wheel, and it even provides a useful view as <code>bytes</code> that <code>int.from_bytes</code> can efficiently convert to a real <code>int</code>:</p> <pre><code>from ipaddress import IPv4Address ip_as_addr = IPv4Address("64.233.187.99") ip_as_int = int.from_bytes(ip_as_addr.packed, 'big') print(ip_as_int, hex(ip_as_int)) </code></pre> <p>gets you output of <code>1089059683 0x40e9bb63</code>.</p> <p>You could do this by hand if you really wanted to, I just like the self-documenting aspect of the above code. If Py 3.3+ isn't an option, you can get the same results with:</p> <pre><code>octets = map(int, "64.233.187.99".split('.')) ip_as_int = sum(octet &lt;&lt; ((3 - i) * 8) for i, octet in enumerate(octets)) </code></pre> <p>That just splits the octets apart, converts them to <code>int</code>, then shifts each of them left by 24, 16, 8 and 0 bits (to align the octets properly), which then allows <code>sum</code> to combine them into a single <code>int</code>.</p>
1
2016-09-17T01:46:45Z
[ "python", "python-2.7", "python-3.x" ]
Why does an empty list become NoneType on return?
39,541,976
<p>I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as <code>[]</code> (which is correct).</p> <pre><code>def path(goal, pathToParentLookup): currentNode = goal result = [] while(currentNode in pathToParentLookup): currentNode = pathToParentLookup[currentNode] result.append(currentNode) return result #bidirectional search from start to goal finds the mid point of "center" start_path = path(center, pathBack_start).reverse() goal_path = path(center, pathBack_goal) return start_path + [center] + goal_path </code></pre> <p>However I'm getting this error:</p> <pre class="lang-none prettyprint-override"><code>&lt;ipython-input-14-ca3cb26b31ce&gt; in bidirectional_search(graph, start, goal, searchMethod) 46 start_path = path(center, pathBack_start).reverse() 47 goal_path = path(center, pathBack_goal) ---&gt; 48 return start_path + [center] + goal_path 49 50 TypeError: can only concatenate list (not "NoneType") to list </code></pre>
1
2016-09-17T01:15:10Z
39,542,018
<p>That's not what is happening. The problem is that on <code>line 46</code> you assign start_path the result of calling reverse() on the list that <code>path()</code> returns. That's OK, but since <code>[].reverse()</code> always returns <code>None</code>, I'm certain it's not what you intended.</p> <p>What I think you want is this:</p> <pre><code>#bidirectional search from start to goal finds the mid point of "center" start_path = path(center, pathBack_start) start_path.reverse() goal_path = path(center, pathBack_goal) return start_path + [center] + goal_path </code></pre>
3
2016-09-17T01:24:28Z
[ "python", "list", "python-2.7", "return", "nonetype" ]
Why does an empty list become NoneType on return?
39,541,976
<p>I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as <code>[]</code> (which is correct).</p> <pre><code>def path(goal, pathToParentLookup): currentNode = goal result = [] while(currentNode in pathToParentLookup): currentNode = pathToParentLookup[currentNode] result.append(currentNode) return result #bidirectional search from start to goal finds the mid point of "center" start_path = path(center, pathBack_start).reverse() goal_path = path(center, pathBack_goal) return start_path + [center] + goal_path </code></pre> <p>However I'm getting this error:</p> <pre class="lang-none prettyprint-override"><code>&lt;ipython-input-14-ca3cb26b31ce&gt; in bidirectional_search(graph, start, goal, searchMethod) 46 start_path = path(center, pathBack_start).reverse() 47 goal_path = path(center, pathBack_goal) ---&gt; 48 return start_path + [center] + goal_path 49 50 TypeError: can only concatenate list (not "NoneType") to list </code></pre>
1
2016-09-17T01:15:10Z
39,542,019
<p>Because reverse is an inplace operation with a None return type. </p> <pre><code>x = [1, 2] print(x) [1, 2] a = x.reverse() print(a) None print(x) [2, 1] </code></pre> <p>Don't assign <code>start_path</code> to the result of reverse. Assign it to start_path = path(center, pathBack_start) and then call start_path.reverse()</p>
1
2016-09-17T01:24:28Z
[ "python", "list", "python-2.7", "return", "nonetype" ]
Why does an empty list become NoneType on return?
39,541,976
<p>I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as <code>[]</code> (which is correct).</p> <pre><code>def path(goal, pathToParentLookup): currentNode = goal result = [] while(currentNode in pathToParentLookup): currentNode = pathToParentLookup[currentNode] result.append(currentNode) return result #bidirectional search from start to goal finds the mid point of "center" start_path = path(center, pathBack_start).reverse() goal_path = path(center, pathBack_goal) return start_path + [center] + goal_path </code></pre> <p>However I'm getting this error:</p> <pre class="lang-none prettyprint-override"><code>&lt;ipython-input-14-ca3cb26b31ce&gt; in bidirectional_search(graph, start, goal, searchMethod) 46 start_path = path(center, pathBack_start).reverse() 47 goal_path = path(center, pathBack_goal) ---&gt; 48 return start_path + [center] + goal_path 49 50 TypeError: can only concatenate list (not "NoneType") to list </code></pre>
1
2016-09-17T01:15:10Z
39,542,021
<p><code>[].reverse()</code> returns <code>None</code>, you should not assign the return value, because it modifies the list in-place.</p> <p>See below:</p> <pre><code>Python 2.7.11 (default, Dec 5 2015, 14:44:53) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; print [].reverse() None &gt;&gt;&gt; </code></pre>
0
2016-09-17T01:24:38Z
[ "python", "list", "python-2.7", "return", "nonetype" ]
Scipy's RectBivariateSpline returns wrong value?
39,541,991
<p>Trying to interpolate data from a regular input grid, and came across this in the documentation for <code>scipy.interpolate.interp2d</code>:</p> <blockquote> <p>See also RectBivariateSpline Much faster 2D interpolation if your input data is on a grid</p> </blockquote> <p>So I tried using <code>scipy.interpolate.RectBivariateSpline</code> instead of <code>interp2d</code>. Docs for both functions seem very similar, so I expected this to produce similar results:</p> <pre><code>import numpy as np from scipy.interpolate import RectBivariateSpline, interp2d from .constants import data x_coords = y_coords = np.arange(data.shape[0]) # Square array interp_fun = interp2d(x_coords, y_coords, data) bivar_fun = RectBivariateSpline(x_coords, y_coords, data) data[250, 60] # 76.1451873779 interp_fun(60, 250) # 76.14518738 bivar_fun(60, 250, grid=False) # 345.24444 </code></pre> <p>Am I calling this wrong? I have no idea why the interpolation based on <code>RectBivariateSpline</code> is so far off?</p> <p>I did suspect that maybe <code>RectBivariateSpline</code> operates on a cartesian grid and inverted the y-Axis of input data, but still no luck.</p>
1
2016-09-17T01:19:35Z
39,541,992
<p>Right, just before submitting this I thought I should try calling <code>bivar_fun(y, x)</code> instead of <code>bivar_fun(x, y)</code> and things suddenly work:</p> <pre><code>data[250, 60] # 76.1451873779 interp_fun(60, 250) # 76.14518738 bivar_fun(250, 60, grid=False) # [ 76.14518738] </code></pre> <p>Still not quite sure why, because the first arguments to <code>interp_fun</code> and <code>bivar_fun</code> should be the same:</p> <blockquote> <p><code>RectBivariateSpline.__call__(x, y, mth=None, dx=0, dy=0, grid=True)</code></p> </blockquote> <p><a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.RectBivariateSpline.__call__.html#scipy.interpolate.RectBivariateSpline.__call__" rel="nofollow">RectBivariateSpline Docs</a></p> <blockquote> <p><code>interp2d.__call__(x, y, dx=0, dy=0)</code></p> </blockquote> <p><a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.interp2d.__call__.html#scipy.interpolate.interp2d.__call__" rel="nofollow">Interp2d Docs</a></p> <p>There's also a related issue on Github: <a href="https://github.com/scipy/scipy/issues/3164" rel="nofollow">https://github.com/scipy/scipy/issues/3164</a></p>
1
2016-09-17T01:19:35Z
[ "python", "numpy", "scipy" ]
what does socket.connect() do internally?
39,542,026
<p>So I am trying to understand networking in general and especially sockets at this point in time. I am using the Python socket library to play with things. </p> <p>I came across many examples on the internet that demonstrate TCP and UDP sockets via simple ECHO servers as examples. </p> <p>For the TCP counterparts the resources suggest that the TCP echo client uses </p> <blockquote> <p>socket_object.connect() to connect to the server and exchange data over it. Similarly, the TCP echo server uses listen() and accept() to handle connections and interactions with the client. </p> </blockquote> <p><strong>Questions</strong></p> <ol> <li>Now these resources mention that it is a TCP connection and hence connection oriented (which I understand conceptually). Please help me understand what does it actually mean to say connection oriented implementation wise? And how does the connect(), listen() and accept() APIs help achieve this?</li> <li><p>Similarly, for the UDP counterparts, the <a href="https://pymotw.com/2/socket/udp.html" rel="nofollow">resources</a> suggest that the UDP echo client does not use any connect() and nor does the UDP echo server use any listen() or accept(). This helps it achieve connectionless behavior. Please help me understand how exactly ? Or may be the answer the question 1 above would help me understand this as well.</p></li> <li><p>Also, in case of UDP echo client in our case, why would it not need to bind to a socket. Even to be able to send data to a remote server, will it still not need a socket endpoint to actually send the data and also receive data when the server sends it back ? Or essentially, I guess, an understanding of what bind() really does internally will help me understand this.</p></li> </ol>
2
2016-09-17T01:25:21Z
39,542,109
<blockquote> <p>Please help me understand what does it actually mean to say connection oriented implementation wise?</p> </blockquote> <p>It means that the TCP protocol relies on an open connection to work. In other words, there <em>must</em> be an open connection through which the packages of a message sent via socket go.</p> <blockquote> <p>And how does the connect(), listen() and accept() APIs help achieve this?</p> </blockquote> <p>I have never used this Python socket library but I think my fairly basic knowledge regarding sockets will suffice to explain this. The <code>connect</code> method is used to open this very same connection I mentioned in the previous answer. The other two methods are used by the server to receive messages sent from the client through this open connection.</p> <blockquote> <p>Similarly, for the UDP counterparts, the resources suggest that the UDP echo client does not use any connect() and nor does the UDP echo server use any listen() or accept(). This helps it achieve connectionless behavior. Please help me understand how exactly ?</p> </blockquote> <p>You probably know that the UDP protocol, different from the TCP protocol, does not rely on an open connection to work. This means that message packages are sent "atomically" (independent from each other), which would make the previous methods useless. As stated in the docs you linked in your question:</p> <p><em>Since there is no connection, per se, the server does not need to listen for and accept connections. It only needs to use bind() to associate its socket with a port, and then wait for individual messages.</em></p> <p>This means that all that a server using UDP for sockets communication must do is register the port from which it will expect socket messages, which will be sent from the client and received through the <code>recvfrom</code> method. The client uses this method as well to receive messages from the server.</p> <blockquote> <p>Even to be able to send data to a remote server, will it still not need a socket endpoint to actually send the data and also receive data when the server sends it back ?</p> </blockquote> <p>The API probably does not expose a method to do that client-side because clients pick the port dynamically and prevent other programs from being a server in that port, or at least they should.</p>
1
2016-09-17T01:42:48Z
[ "python", "sockets", "tcp", "udp" ]
Adding returned tuples to a list of lists
39,542,060
<p>I am trying to add the returned tuples to a list of lists or list of arrays.</p> <pre><code> dim = 10 for key, figure in sorted(problem.figures.iteritems(), reverse=True): dim -= 1 # print key, dim (img_arr[dim], images[dim]) = vectorize(figure) </code></pre> <p>The function returns an array and an image. I am trying to create a list of arrays and a list of images. Can I do this without initializing a list of images outside of the loop?</p>
1
2016-09-17T01:33:11Z
39,542,210
<pre><code>img_arr[dim], images[dim] = vectorize(figure) </code></pre>
0
2016-09-17T02:01:36Z
[ "python", "list" ]
Adding returned tuples to a list of lists
39,542,060
<p>I am trying to add the returned tuples to a list of lists or list of arrays.</p> <pre><code> dim = 10 for key, figure in sorted(problem.figures.iteritems(), reverse=True): dim -= 1 # print key, dim (img_arr[dim], images[dim]) = vectorize(figure) </code></pre> <p>The function returns an array and an image. I am trying to create a list of arrays and a list of images. Can I do this without initializing a list of images outside of the loop?</p>
1
2016-09-17T01:33:11Z
39,543,274
<p>Try using <code>append()</code> attribute of list like this:</p> <pre><code>img_arr, images = [],[] # assuming you already declared the list for key, figure in sorted(problem.figures.iteritems(), reverse=True): tup = vectorize(figure) img_arr.append(tup[0]) images.append(tup[1]) </code></pre> <blockquote> <p>The method append() appends a passed obj into the existing list.</p> </blockquote>
0
2016-09-17T05:44:43Z
[ "python", "list" ]
Pillow does not seem to work inside a function, but works fine on interpreter
39,542,061
<p>The function below, part of a bigger class works fine on all the images except this one -> <a href="http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png" rel="nofollow">http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png</a></p> <pre><code>def _fetch_image_size(self, image_url): size = None if '.svg' not in image_url: response = requests.get(image_url, headers=self._headers) if response.status_code == 200: response.raw.decode_content = True try: image = Image.open(io.BytesIO(response.content)) size = image.size except (IOError, OSError) as error: print error print image_url response.close() return size </code></pre> <p>when the above function is called as part of the class object, it raises me this error.</p> <blockquote> <p>cannot identify image file &lt;_io.BytesIO object at 0x1062e1b30></p> </blockquote> <p>however on the command line interpreter, when i do this</p> <pre><code>import io, requests from PIL import Image response = requests.get('http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png') response.raw.decode_content = True image = Image.open(io.BytesIO(response.content)) print image.size </code></pre> <p>the output is, </p> <pre><code>(220, 220) </code></pre> <p>i am unable to figure out why is it happening?</p>
0
2016-09-17T01:33:22Z
39,551,025
<p>sorry to bother you all. it appears that i need to sanitize my url in my class and look for blankspaces. Nothing wrong with PIL here.</p> <p>here is how i pin pointed the faulty code, if anybody is interested.</p> <p>thankyou for your response. I have diagnosed the problem. pasting the problematic code from my class here.</p> <pre><code>def _extract_image_urls(self, soup): """ extracts all the &lt;img src=''&gt; tags Args: soup (obj): the BeautifulSoup object Returns: url (str): string for url """ for img in soup.findAll("img", src=True): yield urlparse.urljoin(self._url, img["src"]) </code></pre> <p>```</p> <p>this above code gets me all the urls i need to pass onto my <code>_fetch_image_size()</code> function.</p> <p>i modified my <code>_fetch_image_size</code> function to have this</p> <pre><code>..... response = requests.get(image_url, headers=self._headers) print 'Request URL: {url}'.format(url=image_url) print 'Response URL: {url}'.format(url=response.url) ..... </code></pre> <p>and here is the response.</p> <blockquote> <p>s = LinkScraper('<a href="http://www.worldbank.org/en/about/president/about-the-office/bio" rel="nofollow">http://www.worldbank.org/en/about/president/about-the-office/bio</a>') Request URL: <a href="http://www.worldbank.org/content/dam/wbr/img/mobile-menu-lines.png" rel="nofollow">http://www.worldbank.org/content/dam/wbr/img/mobile-menu-lines.png</a> Response URL: <a href="http://www.worldbank.org/content/dam/wbr/img/mobile-menu-lines.png" rel="nofollow">http://www.worldbank.org/content/dam/wbr/img/mobile-menu-lines.png</a></p> <p>Request URL: <a href="http://www.worldbank.org/etc/designs/wbr/clientlibs/img/icon-search-black.png" rel="nofollow">http://www.worldbank.org/etc/designs/wbr/clientlibs/img/icon-search-black.png</a> Response URL: <a href="http://www.worldbank.org/etc/designs/wbr/clientlibs/img/icon-search-black.png" rel="nofollow">http://www.worldbank.org/etc/designs/wbr/clientlibs/img/icon-search-black.png</a></p> <p>Request URL: <a href="http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png" rel="nofollow">http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png</a> Response URL: <a href="http://www.worldbank.org/404_response.htm" rel="nofollow">http://www.worldbank.org/404_response.htm</a> Error: cannot identify image file &lt;_io.BytesIO object at 0x112414830></p> </blockquote> <p>the response that is being passed into the PIL.Image function is an http response and not an image at all!. Nothing wrong with PIL here. I need to sanitize my urls to look for blank spaces here maybe. </p> <p>thank you @martineau for taking the time. Much appreciated.</p> <p>//mouse.</p>
0
2016-09-17T19:44:45Z
[ "python", "pillow" ]
Intermittent "ORA-01458: invalid length inside variable character string" error when inserting data into Oracle DB using SQLAlchemy
39,542,204
<p>I am working on a Python 3.5 server project and using SQLAlchemy 1.0.12 with cx_Oracle 5.2.1 to insert data into Oracle 11g. I noticed that many of my multi-row table insertions are failing intermittently with "ORA-01458: invalid length inside variable character string" error. </p> <p>I generally insert a few thousand to a few tens of thousands of rows at a time, and the data is mostly composed of strings, Pandas timestamps, and floating point numbers. I have made the following observations:</p> <ol> <li>The error occurs on both Windows and Linux host OS for the Python server </li> <li>The error always occurs intermittently, even when the data doesn't change</li> <li>If I don't insert floating point numbers, or if I round them, the error happens less often but still happens</li> <li>If I insert the rows one at a time I don't encounter the error (but this is unacceptable for me performance-wise)</li> </ol> <p>Additionally, I have tried to insert again if I encountered the error. The first thing I tried was to was put a try-except block around where I call execute on the <strong>sqlalchemy.engine.base.Connection</strong> object like the following:</p> <pre><code>try: connection.execute(my_table.insert(), records) except DatabaseError as e: connection.execute(my_table.insert(), records) </code></pre> <p>I noticed that using this method the second insertion still often fails. The second thing I tried was to try the same in the implementation of <strong>do_executemany</strong> of <strong>OracleDialect_cx_oracle</strong> in the sqlalchemy package (sqlalchemy\dialects\oracle\cx_oracle.py):</p> <pre><code>def do_executemany(self, cursor, statement, parameters, context=None): if isinstance(parameters, tuple): parameters = list(parameters) # original code # cursor.executemany(statement, parameters) # new code try: cursor.executemany(statement, parameters) except Exception as e: print('trying again') cursor.executemany(statement, parameters) </code></pre> <p>Strangely, when I do it this way the second <strong>executemany</strong> call will always work if the first one fails. I'm not certain what this means but I believe this points to the cx_Oracle driver being the cause of the issue instead of sqlalchemy. </p> <p>I have searched everywhere online and have not seen any reports of the same problem. Any help would be greatly appreciated!</p>
1
2016-09-17T01:59:49Z
39,668,650
<p>We found out that if we replace all the float.nan objects with None before we do the insertion the error disappears completely. Very weird indeed!</p>
0
2016-09-23T19:59:05Z
[ "python", "oracle", "oracle11g", "sqlalchemy", "cx-oracle" ]
Why isn't this element visible (Selenium + Python/Django 1.9)
39,542,380
<p>I am using webdriver to fill out a form in Django. The first field, name, is found and filled out. But the second field is somehow not being found. Here's the script I'm using...</p> <pre><code>name = browser.find_element_by_id("name") value = browser.find_element_by_id("value") submit = browser.find_element_by_id("offer-submit") name.send_keys(address) name.send_keys(Keys.TAB) # I tried having the browser press tab to see if it becomes visible. no luck. value.send_keys(random.randrange(1, 100, 2)) </code></pre> <p>Here's the error traceback: </p> <pre><code>Traceback (most recent call last): File "populate_map.py", line 71, in &lt;module&gt; value.send_keys(random.randrange(1, 100, 2)) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 320, in send_keys self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)}) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 461, in _execute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///c:/users/owner/appdata/local/temp/tmprd4j_t/extensions/fxdriver@googlecode.com/components/command-processor.js:10092) at DelayedCommand.prototype.checkPreconditions_ (file:///c:/users/owner/appdata/local/temp/tmprd4j_t/extensions/fxdriver@googlecode.com/components/command-processor.js:12644) at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/owner/appdata/local/temp/tmprd4j_t/extensions/fxdriver@googlecode.com/components/command-processor.js:12661) at fxdriver.Timer.prototype.setTimeout/&lt;.notify (file:///c:/users/owner/appdata/local/temp/tmprd4j_t/extensions/fxdriver@googlecode.com/components/command-processor.js:625) </code></pre> <p>The fields are being created with this form:</p> <pre><code>class OfferForm(forms.ModelForm): service = forms.BooleanField() class Meta: model = Offer fields = [ "name", "value", "description", "tags", "location", "code", "service", # "duration" "icon", ] widgets = { 'name': forms.TextInput( attrs={'id': 'name', 'class': 'data', 'style': 'font-family: VT323; font-size: 60%', 'required': True, 'placeholder': 'name'} ), 'value': forms.TextInput( attrs={'id': 'value', 'class': 'data', 'style': 'font-family: VT323; font-size: 60%', 'required': True, 'placeholder': 'value'} ), } </code></pre> <p>Reading <a href="http://stackoverflow.com/questions/6101461/how-to-force-selenium-webdriver-to-click-on-element-which-is-not-currently-visib">this question</a>, I see that there should be a good reason that the value isn't visible -- i.e. it is being made invisible with a style attribute. But when I bring up firebug, I can't see anything to indicate that it's invisible.</p> <p>Here's my template code: (I should mention that #offer is clicked earlier in the script, which activates the display -- it's not none by the time the webdriver is looking for it.)</p> <pre><code> &lt;script&gt; $("#offer").click(function(){ $("#find-offer").css("display", "none"); $("#make-offer").css("display", "block"); $("#popular-offers").css("display", "block") $(".welcome").css("display", "none"); }); &lt;/script&gt; &lt;div id="make-offer" style="display: none"&gt; &lt;p&gt;Make an offer&lt;/p&gt; &lt;form name="offer-form" action="" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} {{ form.as_p }} &lt;input type="submit" id="offer-submit" class="data" style="font-family: Fira Mono; font-size: 70%; padding: 10px; position: absolute" value="Submit" /&gt; &lt;/form&gt; </code></pre> <p>Any other ideas?</p>
2
2016-09-17T02:40:43Z
39,542,433
<p>In my experience, <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains" rel="nofollow"><code>ActionChains</code></a> are often the answer when I have an issue like this in selenium. It is worth a try in this case:</p> <pre><code>from selenium.webdriver.common.action_chains import ActionChains ActionChains(browser).move_to_element(value).click().send_keys(random.randrange(1, 100, 2)).perform() </code></pre> <p>This will first move to the element, click to focus the input, and then send the keys. If the element is not being seen as visible this might raise the same exception, but it is worth a shot. </p>
1
2016-09-17T02:54:26Z
[ "python", "django", "selenium", "webdriver" ]
Kivy Update Widget
39,542,463
<p>I read in a text file called data.txt containing the usernames and passwords. The format of the text file is:</p> <p>username1<br> password1<br> username2<br> password2<br> username3<br> username3<br> etc.</p> <p>I read in the usernames and make a corresponding button for each username. When I first start the program, it shows everything in data.txt and works. However, when I add a user using the program, it does not update the list of users on the main screen. How would I update the list?</p> <pre><code>import kivy from kivy.app import App from kivy.uix.screenmanager import Screen, ScreenManager, NoTransition from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.core.window import Window from kivy.config import Config from kivy.properties import ObjectProperty from kivy.uix.textinput import TextInput from kivy.uix.popup import Popup from numpy import loadtxt from kivy.uix.widget import Widget from os.path import sep, expanduser, isdir, dirname from kivy.uix.stacklayout import StackLayout from functools import partial from kivy.uix.scrollview import ScrollView from kivy.uix.gridlayout import GridLayout class AddUserWindow(Screen): def __init__(self,**kwargs): super (AddUserWindow,self).__init__(**kwargs) addNewUserLayout = FloatLayout() newUserLabel = Label(text="User Name:", font_size='15dp', size_hint = (.5, .05), pos = (500, 450), halign = 'right') passwordLabel = Label(text="Password:", font_size='15dp', size_hint = (.5, .05), pos = (500, 400), halign = 'right') confirmPasswordLabel = Label(text="Confirm Password:", font_size='15dp', size_hint = (.5, .05), pos = (500, 350), halign = 'right') self.newUserInput = TextInput(text = "", size_hint = (.25, .05), pos = (875, 450), font_size='15dp', multiline = False, write_tab = False) self.passwordInput = TextInput(text = "", password = True, size_hint = (.25, .05), pos = (875, 400), font_size='15dp', multiline = False, write_tab = False) self.confirmPasswordInput = TextInput(text = "", password = True, size_hint = (.25, .05), pos = (875, 350), font_size='15dp', multiline = False, write_tab = False) cancelButton = Button(text="Cancel",size_hint = (.2, .05), pos = (650,0)) cancelButton.bind(on_press = self.changeToMainWindow) okButton = Button(text="Ok",size_hint = (.2, .05), pos = (350,0)) okButton.bind(on_press=self.newUserCheck) addNewUserLayout.add_widget(cancelButton) addNewUserLayout.add_widget(okButton) addNewUserLayout.add_widget(newUserLabel) addNewUserLayout.add_widget(passwordLabel) addNewUserLayout.add_widget(confirmPasswordLabel) addNewUserLayout.add_widget(self.newUserInput) addNewUserLayout.add_widget(self.passwordInput) addNewUserLayout.add_widget(self.confirmPasswordInput) self.add_widget(addNewUserLayout) def newUserCheck(self, *args): if self.newUserInput.text == "": content = Button(text = 'Close') popup = Popup(title = 'Please enter user name', size_hint = (.4, .15), content = content, auto_dismiss = False) content.bind(on_press = popup.dismiss) popup.open() return if self.passwordInput.text == "": content = Button(text = 'Close') popup = Popup(title = 'Please enter password', size_hint = (.4, .15), content = content, auto_dismiss = False) content.bind(on_press = popup.dismiss) popup.open() return if self.confirmPasswordInput.text == "": content = Button(text = 'Close') popup = Popup(title = 'Please confirm password', size_hint = (.4, .15), content = content, auto_dismiss = False) content.bind(on_press = popup.dismiss) popup.open() return if self.passwordInput.text != self.confirmPasswordInput.text: content = Button(text = 'Close') popup = Popup(title = 'Passwords must match', size_hint = (.4, .15), content = content, auto_dismiss = False) content.bind(on_press = popup.dismiss) popup.open() return file = open('data.txt', 'r') initial = file.readlines() databaselines = sum(1 for line in open('data.txt')) file.close() users = databaselines / 2 data = [[0 for x in range(2)] for y in range(users)] currLine = 0 range(users) for i in range(users): data[i][0] = initial[currLine].rstrip() data[i][1] = initial[currLine + 1].rstrip() currLine += 2 inDatabase = 0 for i in range(users): if data[i][0] == self.newUserInput.text: inDatabase = 1 break if inDatabase == 1: content = Button(text = 'Close') popup = Popup(title = 'Already in database', size_hint = (.4, .15), content = content, auto_dismiss = False) content.bind(on_press = popup.dismiss) popup.open() return with open("data.txt", "a") as dataFile: dataFile.write(self.newUserInput.text + "\n") dataFile.write(self.passwordInput.text + "\n") self.changeToMainWindow def changeToMainWindow(self, *args): self.newUserInput.text = "" self.passwordInput.text = "" self.confirmPasswordInput.text = "" self.manager.current = 'mainScreen' class MainWindow(Screen): def __init__(self,**kwargs): super (MainWindow,self).__init__(**kwargs) self.mainLayout = FloatLayout() logoutButton = Button(text="Logout",size_hint = (.2, .1), pos = (650,0)) logoutButton.bind(on_press = exit) addNewUserButton = Button(text="New User",size_hint = (.2, .1), pos = (350,0)) addNewUserButton.bind(on_press=self.changeToAddUser) self.mainLayout.add_widget(logoutButton) self.mainLayout.add_widget(addNewUserButton) file = open('data.txt', 'r') initial = file.readlines() databaselines = sum(1 for line in open('data.txt')) file.close() users = databaselines / 2 data = [[0 for x in range(2)] for y in range(users)] currLine = 0 range(users) for i in range(users): data[i][0] = initial[currLine].rstrip() data[i][1] = initial[currLine + 1].rstrip() currLine += 2 self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None) self.layout.bind(minimum_height=self.layout.setter('height')) for i in range(users): self.btn = Button(text=data[i][0], size_hint_y=None, height=40) self.layout.add_widget(self.btn) self.root = ScrollView(size_hint=(.45, None), pos = (600, 100), size=(Window.width, Window.height)) self.root.add_widget(self.layout) self.mainLayout.add_widget(self.root) self.add_widget(self.mainLayout) def changeToAddUser(self, *args): self.manager.current = 'addUserScreen' class TestApp(App): def build(self): self.my_screenmanager = ScreenManager(transition = NoTransition()) self.mainScreen = MainWindow(name='mainScreen') self.addUserScreen = AddUserWindow(name = 'addUserScreen') self.my_screenmanager.add_widget(self.mainScreen) self.my_screenmanager.add_widget(self.addUserScreen) Window.size = (1200, 800) return self.my_screenmanager if __name__ == '__main__': TestApp().run() </code></pre> <p>Thanks so much in advance!!</p>
0
2016-09-17T03:01:32Z
39,544,988
<p>Either you can define a function which adds the appropriate widgets to the layout or you can "clean" the layout and read every user from the database again. If you have many users this might take a while.</p> <p>To add users via a function:</p> <pre><code>class MainWindow(Screen): def __init__(self,**kwargs): super (MainWindow,self).__init__(**kwargs) [... create initial widgets ...] [... read users from database ...] for i in range(users): self.add_user(data[i][0] self.root = ScrollView(size_hint=(.45, None), pos = (600, 100), size=(Window.width, Window.height)) self.root.add_widget(self.layout) self.mainLayout.add_widget(self.root) self.add_widget(self.mainLayout) def add_user(self, text): button = Button(text=text, size_hint_y=None, height=40) self.layout.add_widget(button) </code></pre> <p>then when adding a new user:</p> <pre><code>def newUserCheck(self, *args): [... do checks ...] [... write to file ...] # replace `text` with whatever text you want to display self.manager.get_screen("mainScreen").add_user(text) # in your shown code you missed the () on this function call self.changeToMainWindow() </code></pre> <p>Also I personally found your code relatively hard to read. You could create some functions and call them e.g. <code>create_initial_widgets</code>, <code>read_users_from_database</code>, <code>write_user_to_database</code> etc. </p>
0
2016-09-17T09:09:05Z
[ "python", "kivy" ]
Backend architecture for SaaS product in django
39,542,509
<p>I'm writing the backend for a SaaS application in django. Need some guidance on the architecture. So the product will have 2 offerings: a general one where all users will share the same database and a premium one with a dedicated database. How I'm planning to translate this to django is the following:</p> <ul> <li>Within the django project, there'll be one app for the general offering.</li> <li>For every premium client, there'll be a separate app.</li> <li>Each app has the same models. </li> <li>Every app communicates with a separate database. Achieved this using: <a href="http://stackoverflow.com/questions/18547468/multiple-databases-and-multiple-models-in-django">stackoverflow post</a> and <a href="https://docs.djangoproject.com/en/dev/topics/db/multi-db/" rel="nofollow">django documentation</a></li> <li>I'll write views for all the APIs in the project's views.py, not inside any app and decide on the basis of a token which app's models to communicate to. </li> </ul> <p>The problems I see right now with this architecture:</p> <ul> <li>In all of the views, I'll have to write a lot of conditional statements once the number of premium clients increases.</li> <li>Onboarding of new premium clients requires quite a bit of code change.</li> <li>Code duplication in models.py of all the different apps. But it's almost similar to writing statements for creating tables in a new database every time a premium client signs up. Comments?</li> </ul> <p>Please advise me on the architecture as a whole. I went through a lot of articles and stack overflow posts before going this way, but none were completely specific to django so I'm not 100% confident. Much thanks in advance.</p>
0
2016-09-17T03:13:03Z
39,542,583
<p>If the functionality of the free and premium offerings will be exactly the same you shouldn't need any code duplication. This is of course a big IF, because it's very conceivable that you'll add extra features to the premium offering.</p> <p>If the functionality will be exactly the same then all you need to do is add any new premium databases to your settings.py and use a middleware to determine which database your models should communicate with (using the <code>using</code> attribute), and for the shared database add an <code>owner</code> column to every table that records who the owner of that row is so you can filter querysets appropriately.</p>
0
2016-09-17T03:31:27Z
[ "python", "django", "saas" ]
Run Kivy app as root user with touch screen on raspberry pi
39,542,539
<p>I want to make a kivy app for the raspberry pi that can use a touch screen. I was able to get the demos to work with the touchscreen with just "python ~/kivy/examples/demo/showcase/main.py". The issue comes when I need to start the app with "sudo python main.py", the touchscreen then ceases to work. </p> <p>The app I am trying to write uses the rpi_ws281x library for controlling addressable leds which HAS to be run as root. Is there a way to run the kivy app as root while still enabling the touchscreen functionality? </p> <p>If there isn't, is there a way to send data from the kivy app to say a script which is running sudo that controls the leds? </p> <p>I've looked a lot of places but no one seems to have had this problem before (or they could work around it by changing the privileges of other directories where they were accessing the sudo protected content). Any help is greatly appreciated! </p>
0
2016-09-17T03:22:23Z
39,542,558
<p>Well apparently I didn't look hard enough. The solution is to copy "~/.kivy/config.ini" to "/root/.kivy/config.ini"</p> <p>So the commands are </p> <p>"sudo cp ~/.kivy/config.ini /root/.kivy/config.ini"</p> <p>And then everything works happily together! </p>
0
2016-09-17T03:26:26Z
[ "python", "raspberry-pi", "kivy", "led" ]
Programatically changing docstring of a class object
39,542,552
<p>I have a function and class decorator that changes them to singletons but the docstrings are kind of dropped. Transforming function returns a class object that has its own docstring which should be overwritten. How can I work around this?</p> <pre><code>def singleton(cls): return cls() def singletonfunction(func): return func() @singletonfunction def Bit(): """A 1-bit BitField; must be enclosed in a BitStruct""" return BitsInteger(1) </code></pre> <p>Inspecting <code>Bit</code> yields the <code>BitInteger</code> docstring, not the function's one.</p>
3
2016-09-17T03:25:11Z
39,542,655
<p>Lets assume the original version is something like this:</p> <pre><code>class BitsInteger: """BitsInteger docstring""" def __init__(self, num): pass def singleton(cls): return cls() def singletonfunction(func): return func() @singletonfunction def Bit(): """A 1-bit BitField; must be enclosed in a BitStruct""" return BitsInteger(1) b = Bit print("b.__doc__ :", b.__doc__) </code></pre> <p>Running this with Python3.5 gives the output:</p> <pre><code>b.__doc_ : BitsInteger docstring </code></pre> <p>This might not be what you expect. When we run with <code>python -i original.py</code> we can have a look around at what is really going on here:</p> <pre><code>&gt;&gt;&gt; vars() {'__name__': '__main__', '__builtins__': &lt;module 'builtins' (built-in)&gt;, 'b': &lt;__main__.BitsInteger object at 0x7ff05d2ae3c8&gt;, '__spec__': None, 'singletonfunction': &lt;function singletonfunction at 0x7ff05d2b40d0&gt;, 'singleton': &lt;function singleton at 0x7ff05d30cd08&gt;, '__cached__': None, 'BitsInteger': &lt;class '__main__.BitsInteger'&gt;, '__loader__': &lt;_frozen_importlib.SourceFileLoader object at 0x7ff05d2eb4a8&gt;, '__package__': None, 'Bit': &lt;__main__.BitsInteger object at 0x7ff05d2ae3c8&gt;, '__doc__': None} &gt;&gt;&gt; </code></pre> <p>As you can see <code>b</code> is actually of type <code>BitsInteger</code></p> <p>The reason is because what's really going on is that when you write:</p> <pre><code>@singleton_function def Bit(): """Bit docstring""" ... return BitsInteger(1) </code></pre> <p>You are really just getting syntactic sugar for this:</p> <pre><code>def Bit(): """Bit docstring""" ... return BitsInteger(1) Bit = singleton_function(Bit) </code></pre> <p>In this case <code>Bit</code> is the return value of <code>singleton_function</code> which is actually a <code>BitsInteger</code>. I find when you strip back the syntactic sugar it's much clearer what's going on here.</p> <p>If you would like to have the convenience of a decorator that doesn't change the docstring I'd recommend using <a href="https://pypi.python.org/pypi/wrapt" rel="nofollow">wrapt</a></p> <pre><code>import wrapt class BitsInteger: """BitsInteger docstring""" def __init__(self, num): pass def singleton(cls): return cls() @wrapt.decorator def singletonfunction(func): return func() @singletonfunction def Bit(): """A 1-bit BitField; must be enclosed in a BitStruct""" return BitsInteger(1) b = Bit print("b.__doc_ :", b.__doc__) </code></pre> <p>This outputs:</p> <pre><code>b.__doc_ : A 1-bit BitField; must be enclosed in a BitStruct </code></pre> <p>Now when you look at <code>Vars()</code> you see that <code>'b': &lt;FunctionWrapper at 0x7f9a9ac42ba8 for function at 0x7f9a9a9e8c80&gt;</code> which is no longer a <code>BitInteger</code> type. Personally I like using wrapt because I get what I want immediately. Implementing that functionality and covering all the edge cases takes effort and I know that wrapt is well tested and works as intended.</p>
1
2016-09-17T03:48:00Z
[ "python", "decorator", "python-decorators", "docstring" ]
Selenium Auto Submits Form with Send_keys?
39,542,586
<p>I'm using Selenium 2.53 with python 3.4 firefox 47 to do automation testing. When using .send_keys (sendKeys in Java) it will auto submit the form when I dont want it to.</p> <p>The form input that I'm sending keys to is:</p> <pre><code>&lt;input tabindex="1" type="text" name="PostingTitle" id="PostingTitle" maxlength="70" &lt;/label&gt; </code></pre> <p>It's strange because it doesnt do this with all the forms. Is there a way to tell selenium not to submit?</p>
1
2016-09-17T03:32:06Z
39,543,218
<blockquote> <p>When using .send_keys (sendKeys in Java) it will auto submit the form when I dont want it to.</p> </blockquote> <p>It might be possible your desired text box is capturing key events during sendKeys which may be call any JavaScript function to submit the form, because <code>sendKeys</code> working normally as user input from keys.</p> <p>From comments :-</p> <blockquote> <p>No new line and no 'enter' or 'return' or related keys. No event occuring during sendKeys on the html.</p> </blockquote> <p>Then it's hard to say why <code>sendKeys</code> submit your form.</p> <p>You can use <code>execute_script()</code> instead which would silently set the value into your textbox without occuring any events as :-</p> <pre><code>driver.execute_script("arguments[0].value = arguments[1]", driver.find_element_by_id("PostingTitle"), "you‌​r value to set") </code></pre>
1
2016-09-17T05:35:39Z
[ "python", "selenium", "selenium-webdriver" ]
While statement and expressions
39,542,616
<p><code>while</code> loop statement gets executed as long as the expression is true. </p> <p>After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list. But, the below code executes fine without any error. Why is it so?</p> <pre><code>a = [x*x for x in range(10)] while a.pop(): print("elements in the list") </code></pre> <p>It might be a very basic question, but I am trying to get comfortable with Python.</p>
1
2016-09-17T03:37:59Z
39,542,668
<p>It is unclear what your issue is. If I execute your code, it does (what I think) you expect. It is likely the <code>0</code> that is causing unexpected behavior:</p> <pre><code>&gt;&gt;&gt; a = [x*x for x in range(10)] &gt;&gt;&gt; while a.pop(): ... print a ... [0, 1, 4, 9, 16, 25, 36, 49, 64] [0, 1, 4, 9, 16, 25, 36, 49] [0, 1, 4, 9, 16, 25, 36] [0, 1, 4, 9, 16, 25] [0, 1, 4, 9, 16] [0, 1, 4, 9] [0, 1, 4] [0, 1] [0] </code></pre> <p>It is more <em>Pythonic</em> to test the list itself only rather than the result of <code>.pop()</code> since that will terminate the loop on any falsy item:</p> <pre><code>&gt;&gt;&gt; li=[1,2,3,False,4,5] &gt;&gt;&gt; while li.pop(): ... print li ... [1, 2, 3, False, 4] [1, 2, 3, False] </code></pre> <p>You can see that the <code>while</code> loop is terminated as it encounters <code>False</code> from pop. </p> <p>It would be more typical to do:</p> <pre><code>&gt;&gt;&gt; li=[1,2,3,False,4,5] &gt;&gt;&gt; while li: ... e=li.pop() ... print e, li ... 5 [1, 2, 3, False, 4] 4 [1, 2, 3, False] False [1, 2, 3] 3 [1, 2] 2 [1] 1 [] </code></pre> <p>which terminates when the list becomes false.</p> <p>Better still (in Python) to use a <code>for</code> loop which is non destructive to the list:</p> <pre><code>&gt;&gt;&gt; li=[1,2,3,False,4,5] &gt;&gt;&gt; for e in li: ... print e, li ... 1 [1, 2, 3, False, 4, 5] 2 [1, 2, 3, False, 4, 5] 3 [1, 2, 3, False, 4, 5] False [1, 2, 3, False, 4, 5] 4 [1, 2, 3, False, 4, 5] 5 [1, 2, 3, False, 4, 5] </code></pre>
2
2016-09-17T03:49:31Z
[ "python", "while-loop" ]
While statement and expressions
39,542,616
<p><code>while</code> loop statement gets executed as long as the expression is true. </p> <p>After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list. But, the below code executes fine without any error. Why is it so?</p> <pre><code>a = [x*x for x in range(10)] while a.pop(): print("elements in the list") </code></pre> <p>It might be a very basic question, but I am trying to get comfortable with Python.</p>
1
2016-09-17T03:37:59Z
39,542,686
<blockquote> <p>After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list.</p> </blockquote> <p>No, the code never tries to do any <code>pop</code>s after the 10th, because the 10th <code>pop</code> returns <code>0</code>. <code>0</code> is considered false in a boolean context, so the loop terminates at that point.</p>
3
2016-09-17T03:53:53Z
[ "python", "while-loop" ]
Python os.walk() method
39,542,635
<p>I am new to stackoverflow. I have taken lot of help from this forum in writing the following code. The code below searches all directories/sub directories on the system drives but while looking into 'D' drive, it looks only those directories and sub directories that are after the folder in which i run this program. </p> <p>I mean if I run this program from <code>D:\Dir1\Dir2\Dir3\myCode.py</code>, it will search directories and sub directories after <code>D:\Dir1\Dir2\Dir3\</code> not the entire 'D' drive. It works good with other drives while running from the same location. This is my code:</p> <pre><code>import os, string total=0 for driveLetter in string.ascii_uppercase: try: if os.path.exists(driveLetter+':'): for root, dirs, docs in os.walk(top=driveLetter+':', topdown=True): for name in docs: try: if (name.endswith(".docx")) or (name.endswith(".doc")): print(os.path.join(root, name)) total+=1 except: continue except: continue print ('You have a total of ' + str(total) + ' word documents in your System') </code></pre>
1
2016-09-17T03:42:45Z
39,543,046
<p>In Windows <a href="http://superuser.com/questions/135214/using-cd-command-in-windows-command-line-cant-navigate-to-d">each process may set a current working directory on each <em>drive</em> separately</a>. <code>D:</code> means the <em>current working directory</em> on drive D. Here the behaviour occurs, because on all other drives the current working directory is set to the root directory, but on <code>D:</code> it is the <code>D:\Dir1\Dir2\Dir3\</code> because the working directory was changed to the location of the script. To refer to the <em>root</em> directory of <code>D:</code> unambiguously, you need to use <code>D:\</code>. Thus</p> <pre><code>drive_root = drive_letter + ':\\' # double \\ because this is a Python string literal if os.path.exists(drive_root): for root, dirs, docs in os.walk(drive_root, topdown=True): </code></pre>
2
2016-09-17T05:09:03Z
[ "python" ]
Reshaping pandas dataframe: New row for every 76 entries
39,542,642
<p>I'm new to Python and Pandas and am playing around with a heart disease data set via UCI. <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data" rel="nofollow">https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data</a></p> <p>There are 76 attributes for each person and 303 people so I'd like to end up with each person as a row and 76 columns. I'm having trouble arranging this into a dataframe because the data seems to be presented in rows of 9. </p> <p>I've tried importing the dataset into a pandas dataframe using a space or a newline as a delimiter, but I am still unable to prevent the data from wanting to split after every 8 values:</p> <pre><code>df = pd.read_table('https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data', sep=' ') </code></pre> <p>df results in a table like this:</p> <pre><code> 1254 0 40 1 1.1 0.1 0.2 -9.0 2 140.0 0.0 289 -9.0 -9.0 -9.0 0.0 -9 -9.0 0.0 12 16.0 84.0 0.0 0.0 0 0.0 0.0 150 18.0 -9.0 7.0 172.0 86 200.0 110.0 140 86.0 0.0 0.0 0.0 -9 26.0 20.0 -9 -9.0 -9.0 -9.0 </code></pre> <p>I'd appreciate any advice you might have on how to split this up and create a new row after ever 76th value. Every 76th value is the string 'name' and this denotes the end of one person's data. Thank you!</p>
1
2016-09-17T03:44:28Z
39,544,990
<p>As <a href="http://stackoverflow.com/questions/39542642/reshaping-pandas-dataframe-new-row-for-every-76-entries#comment66400235_39542642">@Boud has already said</a> it's much easier to pre-process your data instead of massaging "incorrectly built" DF:</p> <pre><code>import io import requests import pandas as pd url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data' r = requests.get(url) if r.status_code != requests.codes.ok: r.raise_for_status() data = r.text.replace('\n', ' ').replace(' name ', ' name\n') df = pd.read_table(io.StringIO(data), sep='\s+', header=None) print(df) </code></pre> <p>Output:</p> <pre><code>In [20]: df Out[20]: 0 1 2 3 4 5 6 7 8 9 ... 66 67 68 69 70 71 72 73 74 75 0 1254 0 40 1 1 0 0 -9 2 140 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 1 1255 0 49 0 1 0 0 -9 3 160 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 2 1256 0 37 1 1 0 0 -9 2 130 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 3 1257 0 48 0 1 1 1 -9 4 138 ... 2 -9 1 1 1 1 1 -9.0 -9.0 name 4 1258 0 54 1 1 0 1 -9 3 150 ... 1 -9 1 1 1 1 1 -9.0 -9.0 name 5 1259 0 39 1 1 0 1 -9 3 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 6 1260 0 45 0 0 1 0 -9 2 130 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 7 1261 0 54 1 1 0 0 -9 2 110 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 8 1262 0 37 1 1 1 1 -9 4 140 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 9 1263 0 48 0 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 10 1264 0 37 0 1 0 1 -9 3 130 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 11 1265 0 58 1 1 0 0 -9 2 136 ... -9 2 1 1 1 7 1 -9.0 -9.0 name 12 1266 0 39 1 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 13 1267 0 49 1 1 1 1 -9 4 140 ... 2 -9 1 1 1 1 1 -9.0 -9.0 name 14 1268 0 42 0 1 0 1 -9 3 115 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 15 1269 0 54 0 1 1 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 16 1270 0 38 1 1 1 1 -9 4 110 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 17 1271 0 43 0 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 18 1272 0 60 1 1 1 1 -9 4 100 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 19 1273 0 36 1 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 20 1274 0 43 0 0 0 0 -9 1 100 ... -9 -9 1 1 1 1 2 -9.0 -9.0 name 21 1275 0 44 1 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 22 1276 0 49 0 1 0 0 -9 2 124 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 23 1277 0 44 1 1 0 0 -9 2 150 ... 2 -9 1 1 1 1 1 67.0 -9.0 name 24 1278 0 40 1 1 0 1 -9 3 130 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name .. ... .. .. .. .. .. .. .. .. ... ... .. .. .. .. .. .. .. ... ... ... 269 1032 0 54 1 1 1 0 -9 4 130 ... -9 2 1 1 1 7 1 66.0 -9.0 name 270 1033 0 47 0 1 0 0 -9 3 130 ... -9 -9 1 1 1 1 1 68.0 -9.0 name 271 1034 0 45 1 1 1 1 -9 4 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 272 1035 0 32 0 1 0 0 -9 2 105 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 273 1036 0 55 1 1 1 1 -9 4 140 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 274 1037 0 55 1 1 0 0 -9 3 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 275 1038 0 45 0 0 0 0 -9 2 180 ... -9 -9 1 1 1 1 1 70.0 -9.0 name 276 1039 0 59 1 1 0 1 -9 3 180 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 277 1041 0 51 1 1 0 0 -9 3 135 ... 2 -9 1 1 3 8 2 -9.0 -9.0 name 278 1042 0 52 1 1 1 1 -9 4 170 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 279 1043 0 57 0 1 1 1 -9 4 180 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 280 1044 0 54 0 1 0 0 -9 2 130 ... -9 -9 1 1 1 1 3 -9.0 -9.0 name 281 1045 0 60 1 1 0 0 -9 3 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 282 1046 0 49 1 1 1 1 -9 4 150 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 283 1047 0 51 0 1 0 1 -9 3 130 ... -9 -9 1 1 1 1 1 61.0 -9.0 name 284 1048 0 55 0 0 0 0 -9 2 110 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 285 1049 0 42 1 1 1 1 -9 4 140 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 286 1050 0 51 0 1 0 1 -9 3 110 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 287 1051 0 59 1 1 1 1 -9 4 140 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 288 1052 0 53 1 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 289 1053 0 48 0 0 0 0 -9 2 -9 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 290 1054 0 36 1 1 0 0 -9 2 120 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 291 5001 0 48 1 0 0 0 -9 3 110 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 292 5000 0 47 0 0 0 0 -9 2 140 ... -9 -9 1 1 1 1 1 -9.0 -9.0 name 293 5002 0 53 1 1 1 1 -9 4 130 ... 1 1 1 1 1 1 1 -9.0 -9.0 name [294 rows x 76 columns] </code></pre>
1
2016-09-17T09:09:15Z
[ "python", "pandas" ]
Error displaying a matplotlib in ipython notebook
39,542,703
<p>I'm going though a ipython notebook tutorial and it says to run this in a cell. import numpy as np import math import matplotlib.pyplot as plt</p> <pre><code>x = np.linspace(0, 2*math.pi) plt.plot(x, np.sin(x), label=r'$\sin(x)$') plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') plt.title(r'Two plots in a graph') plt.legend() </code></pre> <p>and I should get an actual graph. Isntead I get</p> <pre><code>&lt;matplotlib.legend.Legend at 0x1124a2fd0&gt; </code></pre> <p>What should I do instead?</p>
0
2016-09-17T03:56:26Z
39,543,637
<p>Try to add this statement earlier in your notebook, which indicates to matplotlib where to render the plot (i.e. as an html element embedded in the notebook):</p> <p><code> %matplotlib inline </code></p> <p>The story behind that is simply that matplotlib is old enough to be existing since before jupyter and ipython notebooks became popular. Back then the standard way of creating a plot was to write a script, run it, and obtain an image file as result. Currently the same image can be easily and directly visible in the notebook, at the cost of the supplementary "rewiring" statement above. </p> <p>In order to display any plot in the notebook, you can have the <code>plot</code> statement as last line of that block code (i.e. the plot is then the returned value, which get rendered by jupyter automatically), or use plt.show() as described by Abdou in the comment. </p> <p>Also, watch out that you have 2 plots in your code:</p> <pre><code># Put these 2 in two separate notebook blocks to get 2 separate plots. # As-is the first one will never get displayed plt.plot(x, np.sin(x), label=r'$\sin(x)$') plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') </code></pre> <p>If you want to have all plots rendered as one single image (which quickly gets hairy with matplotlib imho), have a look at <a href="http://matplotlib.org/examples/pylab_examples/subplots_demo.html" rel="nofollow">subplot documentation</a></p> <p>To make the result prettier, include a <code>;</code>at the end of the plot to avoid the ugly <code>&lt;matplotlib.legend.Legend at 0x1124a2fd0&gt;</code></p>
1
2016-09-17T06:37:43Z
[ "python", "matplotlib", "ipython" ]
DFS path finding with obstacles
39,542,810
<p>I have the following grid and i'm trying to get to the 1's in that grid, the obstacle is shown by 2. The robot has prioritized movement in this order: up, right, down, left. The starting position has a * next to it.</p> <pre><code> 0 0* 0 0 2 0 1 1 0 </code></pre> <p>What i have done so far is to put the position of that grid into a graph form, and also generated all the possible moves from each position in the prioritized order. But my issue is that the algorithm gets stuck in a loop when it gets to the last section of the second row. I'm trying to implement some sort of a cycle detector so i don't get stuck in that loop.</p> <p>I should also mention that the robot can visit the same position twice as long as it's through different paths. So what I have so far is:</p> <pre><code>def dfs(grid,start): #find the routes in U,R,D,L order height = len(grid) width = len(grid[0]) routes = {(i, j) : [] for j in range(width) for i in range(height)} for row, col in routes.keys(): # Left moves if col &gt; 0: routes[(row, col)].append((row , col - 1)) # Down moves if row &lt; height - 1: routes[(row, col)].append(((row + 1, col))) # Right moves if col &lt; width - 1: routes[(row, col)].append(((row , col + 1))) # Up moves if row &gt; 0: routes[(row, col)].append(((row - 1, col))) #find the blocked ones blocked = {(i,j) for j in range(width) for i in range(height) if grid[i][j] == 2} path = [] stack = [start] while stack: node = stack.pop() if node not in blocked: path.append(node) stack = [] for x in routes[node]: stack.extend([x]) return path </code></pre> <p>Where</p> <pre><code> grid = [[0, 0, 0], [0, 2, 0], [1, 1, 0]] start = (0,1) </code></pre> <p>Doing this by hand shows that the path should go as follows: right, down, down, left, right, up, up, left, left, down, down</p> <p>any suggestions on how i can implement the detector would be great, I'm very new to AI and python and i've been trying to figure this out all day...thank you</p>
-1
2016-09-17T04:19:13Z
39,543,291
<p>Try this:</p> <pre><code>def dfs2(grid,pos,curr,height,width): x = pos[0] y = pos[1] if grid[x][y]==1: print str(curr) return None elif grid[x][y] ==2: return None last = curr[-1] if x-1 &gt;= 0 and last != 'DOWN': curr.append('UP') dfs2(grid,(x-1,y),curr,height,width) curr.pop() if y+1 &lt; width and last != 'LEFT': curr.append('RIGHT') dfs2(grid,(x,y+1),curr,height,width) curr.pop() if x+1 &lt; height and last != 'UP': curr.append('DOWN') dfs2(grid,(x+1,y),curr,height,width) curr.pop() if y-1&gt;=0 and last != 'RIGHT': curr.append('LEFT') dfs2(grid,(x,y-1),curr,height,width) curr.pop() def dfs(grid,pos): dfs2(grid,pos,['START'],len(grid),len(grid[0])) ########MAIN######### #up, right, down, left grid = [[0, 0, 0], [0, 2, 0], [1, 1, 0]] start = (0,1) print str(grid) dfs(grid,start) </code></pre> <p>This is based on recursion. Attemps to move to the next position based on the order specified in the question and stores the movements in a list which gets printed on reaching the destination</p>
0
2016-09-17T05:47:41Z
[ "python", "artificial-intelligence", "depth-first-search" ]
Returning a real-valued, phase-scrambled timeseries using Python
39,543,002
<p>I'm trying to implement "phase scrambling" of a timeseries in Python using Scipy/Numpy. Briefly, I'd like to:</p> <ol> <li>Take a timeseries.</li> <li>Measure the power and phase in the frequency domain using FFT.</li> <li>Scramble the existing phase, randomly reassigning phase to frequency.</li> <li>Return a real-valued (i.e., non-complex) timeseries with scrambled phase using IFFT such that the power spectrum of the timeseries remains constant but the points of the timeseries differ from the original.</li> </ol> <p>I have a script that superficially seems to work (see plots), but I suspect that I'm missing something important. In particular, my returned phase-scrambled timeseries has complex-valued entries instead of real-valued entries, and I'm not sure what to do with that. If any signal-processing folks could weigh in and educate me, I'd greatly appreciate it.</p> <p>Here's a sample script suitable for Jupyter Notebook:</p> <pre><code>%matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft, ifft def phaseScrambleTS(ts): """Returns a TS: original TS power is preserved; TS phase is shuffled.""" fs = fft(ts) pow_fs = np.abs(fs) ** 2. phase_fs = np.angle(fs) phase_fsr = phase_fs.copy() np.random.shuffle(phase_fsr) fsrp = np.sqrt(pow_fs) * (np.cos(phase_fsr) + 1j * np.sin(phase_fsr)) tsr = ifft(fsrp) return tsr ts = np.array([0.02, -1.04, 2.50, 2.21, 1.37, -0.05, 0.06, -0.22, -0.48, -0.31, 0.15, 0.99, 0.39, 0.65, 1.13, 0.77, 1.16, 1.35, 0.92, 1.42, 1.58, 1.33, 0.73, 0.98, 0.66, 0.13, -0.19, 2.05, 1.95, 1.25, 1.37, 0.85, 0.00, 1.37, 2.17, 0.69, 1.38, 0.49, 0.52, 0.62, 1.74, 0.67, 0.61, 1.03, 0.38, 0.64, 0.83, 1.16, 1.10, 1.30, 1.98, 0.92, 1.36, -1.49, -0.80, -0.08, 0.01, -0.04, -0.07, -0.20, 0.82, -0.26, 0.83, 0.09, -0.54, -0.45, 0.82, -0.53, -0.88, -0.54, -0.30, 0.52, 0.54, -0.57, 0.73, -0.04, 0.34, 0.59, -0.67, -0.25, -0.44, 0.07, -1.00, -1.88, -2.55, -0.08, -1.13, -0.94, -0.09, -2.08, -1.56, 0.25, -1.87, 0.52, -0.51, -1.42, -0.80, -1.96, -1.42, -1.27, -1.08, -1.79, -0.73, -2.70, -1.14, -1.71, -0.75, -0.78, -1.87, -0.88, -2.15, -1.92, -2.17, -0.98, -1.52, -1.92], dtype=np.float) N = ts.shape[0] TR = 2. x = np.linspace(0.0, N*TR, N) plt.plot(x, ts) plt.ylabel('% Sig. Change') plt.xlabel('Time') plt.title('RSFC: Time domain') plt.show() ts_ps = phaseScrambleTS(ts) plt.plot(x, ts, x, ts_ps) plt.ylabel('% Sig. Change') plt.xlabel('Time') plt.title('RSFC, Orig. vs. Phase-Scrambled: Time domain') plt.show() fs = fft(ts) fs_ps = fft(ts_ps) xf = np.linspace(0.0, 1.0/(2.0*TR), N/2) plt.plot(xf, 2./N * np.abs(fs[0:N/2]), 'b--', xf, 2./N * np.abs(fs_ps[0:N/2]), 'g:') plt.grid() plt.ylabel('Amplitude') plt.xlabel('Freq.') plt.title('RSFC, Orig. vs. Phase-Scrambled: Freq. domain, Amp.') plt.show() </code></pre> <p>Edit: Following up on one of the solutions below, I generalized from the even case to the odd case as follows. I believe that the conditional for detecting non-negligible imaginary components is now unnecessary, but I'll leave it in for posterity.</p> <pre><code>def phaseScrambleTS(ts): """Returns a TS: original TS power is preserved; TS phase is shuffled.""" fs = fft(ts) pow_fs = np.abs(fs) ** 2. phase_fs = np.angle(fs) phase_fsr = phase_fs.copy() if len(ts) % 2 == 0: phase_fsr_lh = phase_fsr[1:len(phase_fsr)/2] else: phase_fsr_lh = phase_fsr[1:len(phase_fsr)/2 + 1] np.random.shuffle(phase_fsr_lh) if len(ts) % 2 == 0: phase_fsr_rh = -phase_fsr_lh[::-1] phase_fsr = np.concatenate((np.array((phase_fsr[0],)), phase_fsr_lh, np.array((phase_fsr[len(phase_fsr)/2],)), phase_fsr_rh)) else: phase_fsr_rh = -phase_fsr_lh[::-1] phase_fsr = np.concatenate((np.array((phase_fsr[0],)), phase_fsr_lh, phase_fsr_rh)) fsrp = np.sqrt(pow_fs) * (np.cos(phase_fsr) + 1j * np.sin(phase_fsr)) tsrp = ifft(fsrp) if not np.allclose(tsrp.imag, np.zeros(tsrp.shape)): max_imag = (np.abs(tsrp.imag)).max() imag_str = '\nNOTE: a non-negligible imaginary component was discarded.\n\tMax: {}' print imag_str.format(max_imag) return tsrp.real </code></pre>
2
2016-09-17T04:58:25Z
39,543,314
<p><strong>A property of Fourier transform</strong>: a real valued time domain signal has a conjugate symmetric frequency domain signal. See <a href="https://en.wikipedia.org/wiki/Fourier_transform#Functional_relationships" rel="nofollow">110 of Functional relationships of Fourier transform</a>.</p> <h1>Solution (may not be optimal)</h1> <p>Edit a code below in <code>phaseScrambleTs()</code>:</p> <pre><code>np.random.shuffle(phase_fsr) </code></pre> <p>to:</p> <pre><code>phase_fsr_lh = phase_fsr[1:len(phase_fsr)/2] np.random.shuffle(phase_fsr_lh) phase_fsr_rh = -phase_fsr_lh[::-1] phase_fsr = np.append(phase_fsr[0], np.append(phase_fsr_lh, np.append(phase_fsr[len(phase_fsr)/2], phase_fsr_rh))) </code></pre> <p>The left half of frequency domain takes <code>phase_fsr[1:len(phase_fsr)/2]</code>. Note that the starting index is <code>1</code>, not <code>0</code>. And shuffle it. The right half of frequency domain is determined as a sign-inverted of <code>phase_fsr_lh</code> in reverse order (by definition of conjugate). And append all of them, the first element, the left half, the centered element, and the right half.</p>
1
2016-09-17T05:51:28Z
[ "python", "numpy", "scipy", "signal-processing", "ifft" ]
Returning a real-valued, phase-scrambled timeseries using Python
39,543,002
<p>I'm trying to implement "phase scrambling" of a timeseries in Python using Scipy/Numpy. Briefly, I'd like to:</p> <ol> <li>Take a timeseries.</li> <li>Measure the power and phase in the frequency domain using FFT.</li> <li>Scramble the existing phase, randomly reassigning phase to frequency.</li> <li>Return a real-valued (i.e., non-complex) timeseries with scrambled phase using IFFT such that the power spectrum of the timeseries remains constant but the points of the timeseries differ from the original.</li> </ol> <p>I have a script that superficially seems to work (see plots), but I suspect that I'm missing something important. In particular, my returned phase-scrambled timeseries has complex-valued entries instead of real-valued entries, and I'm not sure what to do with that. If any signal-processing folks could weigh in and educate me, I'd greatly appreciate it.</p> <p>Here's a sample script suitable for Jupyter Notebook:</p> <pre><code>%matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft, ifft def phaseScrambleTS(ts): """Returns a TS: original TS power is preserved; TS phase is shuffled.""" fs = fft(ts) pow_fs = np.abs(fs) ** 2. phase_fs = np.angle(fs) phase_fsr = phase_fs.copy() np.random.shuffle(phase_fsr) fsrp = np.sqrt(pow_fs) * (np.cos(phase_fsr) + 1j * np.sin(phase_fsr)) tsr = ifft(fsrp) return tsr ts = np.array([0.02, -1.04, 2.50, 2.21, 1.37, -0.05, 0.06, -0.22, -0.48, -0.31, 0.15, 0.99, 0.39, 0.65, 1.13, 0.77, 1.16, 1.35, 0.92, 1.42, 1.58, 1.33, 0.73, 0.98, 0.66, 0.13, -0.19, 2.05, 1.95, 1.25, 1.37, 0.85, 0.00, 1.37, 2.17, 0.69, 1.38, 0.49, 0.52, 0.62, 1.74, 0.67, 0.61, 1.03, 0.38, 0.64, 0.83, 1.16, 1.10, 1.30, 1.98, 0.92, 1.36, -1.49, -0.80, -0.08, 0.01, -0.04, -0.07, -0.20, 0.82, -0.26, 0.83, 0.09, -0.54, -0.45, 0.82, -0.53, -0.88, -0.54, -0.30, 0.52, 0.54, -0.57, 0.73, -0.04, 0.34, 0.59, -0.67, -0.25, -0.44, 0.07, -1.00, -1.88, -2.55, -0.08, -1.13, -0.94, -0.09, -2.08, -1.56, 0.25, -1.87, 0.52, -0.51, -1.42, -0.80, -1.96, -1.42, -1.27, -1.08, -1.79, -0.73, -2.70, -1.14, -1.71, -0.75, -0.78, -1.87, -0.88, -2.15, -1.92, -2.17, -0.98, -1.52, -1.92], dtype=np.float) N = ts.shape[0] TR = 2. x = np.linspace(0.0, N*TR, N) plt.plot(x, ts) plt.ylabel('% Sig. Change') plt.xlabel('Time') plt.title('RSFC: Time domain') plt.show() ts_ps = phaseScrambleTS(ts) plt.plot(x, ts, x, ts_ps) plt.ylabel('% Sig. Change') plt.xlabel('Time') plt.title('RSFC, Orig. vs. Phase-Scrambled: Time domain') plt.show() fs = fft(ts) fs_ps = fft(ts_ps) xf = np.linspace(0.0, 1.0/(2.0*TR), N/2) plt.plot(xf, 2./N * np.abs(fs[0:N/2]), 'b--', xf, 2./N * np.abs(fs_ps[0:N/2]), 'g:') plt.grid() plt.ylabel('Amplitude') plt.xlabel('Freq.') plt.title('RSFC, Orig. vs. Phase-Scrambled: Freq. domain, Amp.') plt.show() </code></pre> <p>Edit: Following up on one of the solutions below, I generalized from the even case to the odd case as follows. I believe that the conditional for detecting non-negligible imaginary components is now unnecessary, but I'll leave it in for posterity.</p> <pre><code>def phaseScrambleTS(ts): """Returns a TS: original TS power is preserved; TS phase is shuffled.""" fs = fft(ts) pow_fs = np.abs(fs) ** 2. phase_fs = np.angle(fs) phase_fsr = phase_fs.copy() if len(ts) % 2 == 0: phase_fsr_lh = phase_fsr[1:len(phase_fsr)/2] else: phase_fsr_lh = phase_fsr[1:len(phase_fsr)/2 + 1] np.random.shuffle(phase_fsr_lh) if len(ts) % 2 == 0: phase_fsr_rh = -phase_fsr_lh[::-1] phase_fsr = np.concatenate((np.array((phase_fsr[0],)), phase_fsr_lh, np.array((phase_fsr[len(phase_fsr)/2],)), phase_fsr_rh)) else: phase_fsr_rh = -phase_fsr_lh[::-1] phase_fsr = np.concatenate((np.array((phase_fsr[0],)), phase_fsr_lh, phase_fsr_rh)) fsrp = np.sqrt(pow_fs) * (np.cos(phase_fsr) + 1j * np.sin(phase_fsr)) tsrp = ifft(fsrp) if not np.allclose(tsrp.imag, np.zeros(tsrp.shape)): max_imag = (np.abs(tsrp.imag)).max() imag_str = '\nNOTE: a non-negligible imaginary component was discarded.\n\tMax: {}' print imag_str.format(max_imag) return tsrp.real </code></pre>
2
2016-09-17T04:58:25Z
39,544,572
<p>Scipy has <code>rfft</code> and <code>irfft</code> routines to do Fourier transforms of real signals (the <code>r</code> is for real). The function below returns a properly scrambled signal. I should note that the routine as written will only work for even length signals, but fixing it for odd length signals shouldn't be too hard, just check the <code>rfft</code> documentation</p> <pre><code>from scipy.fftpack import rfft, irfft def phaseScrambleTS(ts): """Returns a TS: original TS power is preserved; TS phase is shuffled.""" fs = rfft(ts) # rfft returns real and imaginary components in adjacent elements of a real array pow_fs = fs[1:-1:2]**2 + fs[2::2]**2 phase_fs = np.arctan2(fs[2::2], fs[1:-1:2]) phase_fsr = phase_fs.copy() np.random.shuffle(phase_fsr) # use broadcasting and ravel to interleave the real and imaginary components. # The first and last elements in the fourier array don't have any phase information, and thus don't change fsrp = np.sqrt(pow_fs[:, np.newaxis]) * np.c_[np.cos(phase_fsr), np.sin(phase_fsr)] fsrp = np.r_[fs[0], fsrp.ravel(), fs[-1]] tsr = irfft(fsrp) return tsr </code></pre>
1
2016-09-17T08:19:59Z
[ "python", "numpy", "scipy", "signal-processing", "ifft" ]
How can I code a sample of random numbers from a list, so that each number generated follows some condition depending on the preceding number?
39,543,027
<p>Example: If the first number in the sample is 1, then the next number can only be 2, 4 or 5, and if the second number is 2, then the next number can only be 1, 3, 4, 5 or 6. This continues for all the numbers in the list.</p> <p>I tried using this:</p> <pre><code>import random num_list = [1,2,3,4,5,6,7,8,9] new_sample = random.sample(num_list, 5) print (new_sample) </code></pre> <p>However, I can't seem to manipulate this code so that it follows the conditions I need. Any help would really be appreciated.</p> <p>EDIT: The pattern in the conditions is a bit hard to explain. The numbers 1 to 9 come from a 3 x 3 grid of dots numbered in order from left to right and top to bottom. I'm trying to simulate random patterns such that you can only join adjacent dots. </p> <p>If the preceding number (PN) = 1, then the next number (NN) = 2, 4 or 5, If PN = 2, then NN = 1, 3, 4, 5 or 6, If PN = 3 then NN = 2, 5, 6, If PN = 4 then NN = 1, 2, 5, 7, or 8, If PN = 5 then NN = 1, 2, 3, 4, 6, 7, 8, or 9 and so on. </p>
-1
2016-09-17T05:04:36Z
39,543,777
<p>I think this will work (in Python 3): </p> <pre><code>import random x_arr=[] y_arr=[] def addTolist(m,n): x_arr.append(m) y_arr.append(n) grid = [[1,2,3],[4,5,6],[7,8,9]] new_sample = random.sample(range(1,10), 5) # to generate random list of 5 numbers current = random.choice(new_sample) # take random number from list of 5 numbers for i in range(3): # to position of number in the grid for j in range(3): if current == grid[i][j]: x = i y = j break num = [current] # to store the unique random numbers for i in range(4): # loop till we find the 5 th number print('current:',current) # every time empty the list neighbours = [] x_arr=[] y_arr=[] # to choose the neighbours of current number (maximum 8 neighbours) if y-1 &gt;= 0: neighbours.append(grid[x][y-1]) addTolist(x,y-1) if x+1 &lt; 3: neighbours.append(grid[x+1][y-1]) addTolist(x+1,y-1) if x-1 &gt;= 0: neighbours.append(grid[x-1][y-1]) addTolist(x-1,y-1) if x-1 &gt;= 0: neighbours.append(grid[x-1][y]) addTolist(x-1,y) if y+1 &lt; 3: neighbours.append(grid[x-1][y+1]) addTolist(x-1,y+1) if y+1 &lt; 3: neighbours.append(grid[x][y+1]) addTolist(x,y+1) if x+1 &lt; 3: neighbours.append(grid[x+1][y+1]) addTolist(x+1,y+1) if x+1 &lt; 3: neighbours.append(grid[x+1][y]) addTolist(x+1,y) current = random.choice(neighbours) while current in num: # till unique random number is not generted current = random.choice(neighbours) num.append(current) position = neighbours.index(current) x = x_arr[position] y = y_arr[position] print("x position:",x_arr) print("y position:",y_arr) print("neighbours:",neighbours) print("Final Number : ",current) </code></pre> <p>Output:</p> <pre><code>current: 7 x position: [1, 1, 2] y position: [0, 1, 1] neighbours: [4, 5, 8] current: 4 x position: [0, 0, 1, 2, 2] y position: [0, 1, 1, 1, 0] neighbours: [1, 2, 5, 8, 7] current: 5 x position: [1, 2, 0, 0, 0, 1, 2, 2] y position: [0, 0, 0, 1, 2, 2, 2, 1] neighbours: [4, 7, 1, 2, 3, 6, 9, 8] current: 8 x position: [2, 1, 1, 1, 2] y position: [0, 0, 1, 2, 2] neighbours: [7, 4, 5, 6, 9] Final Number : 9 </code></pre> <blockquote> <p><strong>Assumption :</strong> grid is 3*3 And You have to find the 5th unique random number always.</p> </blockquote> <p>It is bit lengthy but I have to check all neighbours in <code>3*3</code> grid. So I take <code>grid</code> variable which is list of list numbers in grid similar to <em>2D array</em>. I think all the remaining code is self explanatory.</p> <p>Hope this will help you.</p>
0
2016-09-17T06:54:39Z
[ "python" ]
How can I know in Python how many times a line of code is executed per minute?
39,543,081
<p>For example if I have: </p> <pre><code> something=something+1 </code></pre> <p>I want to know how many times in a minute, this line is executed in order to create another variable with this result? </p>
0
2016-09-17T05:13:52Z
39,543,135
<p>I suppose you are trying to do some basic benchmarking, in this case it would go like this:</p> <pre><code>import time start = int(round(time.time() * 1000)) something = 0 while something &lt; 1000000: something = something + 1 delta = int(round(time.time() * 1000)) - start print "loop ran 1000000 times in {0:0d} milliseconds".format(delta) </code></pre>
0
2016-09-17T05:24:26Z
[ "python", "loops", "time" ]
How can I know in Python how many times a line of code is executed per minute?
39,543,081
<p>For example if I have: </p> <pre><code> something=something+1 </code></pre> <p>I want to know how many times in a minute, this line is executed in order to create another variable with this result? </p>
0
2016-09-17T05:13:52Z
39,543,324
<p>If you are willing to wait a full minute (which usually is not the case) you could do something like</p> <pre><code>import time start = time.time() operationsPerMinute = 0 while (time.time() - start &lt; 60): operationsPerMinute = operationsPerMinute + 1 print(operationsPerMinute) </code></pre> <p>In which case operationsPerMinute holds the value you want.</p> <p>Alternatively, you could run in a much smaller time frame and use a bit of math to estimate it in a whole minute time frame. </p>
0
2016-09-17T05:53:01Z
[ "python", "loops", "time" ]
How can I know in Python how many times a line of code is executed per minute?
39,543,081
<p>For example if I have: </p> <pre><code> something=something+1 </code></pre> <p>I want to know how many times in a minute, this line is executed in order to create another variable with this result? </p>
0
2016-09-17T05:13:52Z
39,543,813
<p>For benchmarking you would probably ask for per second timings.</p> <p>To count events in the last minute, here is a class remembering event timestamps for a given period:</p> <pre><code>import bisect import time class TimedCounter: def __init__(self, period=60.0): self._timestamps = [] self._period = period def _cleanup(self, now): del self._timestamps[:bisect.bisect_left(self._timestamps, now - self._period)] def increment(self): now = time.time() self._timestamps.append(now) self._cleanup(now) # optimization: not necessary to call every time def get_count(self): self._cleanup(time.time()) return len(self._timestamps) </code></pre> <p>and an example:</p> <pre><code>tc = TimedCounter(1.0) for i in range(7, 27): tc.increment() print("{} time(s) in the last second".format(tc.get_count())) time.sleep(7/i) </code></pre>
0
2016-09-17T06:58:30Z
[ "python", "loops", "time" ]
PyCharm not detecting interpreter
39,543,093
<p>I am trying to code something in PyCharm (by JetBrains), and it is asking for an interpreter, however, there are no interpreters on the list. I am running 64-bit windows with 64-bit python installed. How can I fix this?</p>
0
2016-09-17T05:16:31Z
39,543,333
<p>Open PyCharm, Open Settings, Go To "Project: YourProjectName" -> Project Interpreter, click the Gear right to the Project Interpreter Field, Click "Add Local", search for your python.exe and click OK.</p>
0
2016-09-17T05:54:47Z
[ "python", "pycharm", "interpreter" ]
Big Binary Code into File in Python
39,543,117
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p> <pre><code>binaryRecieved="11001010101....(Shortened)" f=open(fileName,'wb') m=long(binaryRecieved,2) struct.pack('i',m) f.write(struct.pack('i',m)) f.close() quit() </code></pre> <p>I am left with the error</p> <pre><code>struct.pack('i',x) struct.error: integer out of range for 'i' format code </code></pre> <p>My integer is out of range, so I was wondering if there is a different way of going about with this.</p> <p>Thanks</p>
0
2016-09-17T05:21:55Z
39,543,228
<p>In <code>struct.pack</code> you have used 'i' which represents an integer number, which is limited. As your code states, you have a long output; thus, you may want to use 'd' in stead of 'i', to pack your data up as double. It should work. <br /> <br /> See <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">Python struct</a> for more information.</p>
0
2016-09-17T05:37:18Z
[ "python", "file", "binary" ]
Big Binary Code into File in Python
39,543,117
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p> <pre><code>binaryRecieved="11001010101....(Shortened)" f=open(fileName,'wb') m=long(binaryRecieved,2) struct.pack('i',m) f.write(struct.pack('i',m)) f.close() quit() </code></pre> <p>I am left with the error</p> <pre><code>struct.pack('i',x) struct.error: integer out of range for 'i' format code </code></pre> <p>My integer is out of range, so I was wondering if there is a different way of going about with this.</p> <p>Thanks</p>
0
2016-09-17T05:21:55Z
39,543,388
<p>Convert your bit string to a byte string: see for example this question <a href="http://stackoverflow.com/questions/28370991/converting-bits-to-bytes-in-python">Converting bits to bytes in Python</a>. Then pack the bytes with <code>struct.pack('c', bytestring)</code></p>
1
2016-09-17T06:05:03Z
[ "python", "file", "binary" ]
Big Binary Code into File in Python
39,543,117
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p> <pre><code>binaryRecieved="11001010101....(Shortened)" f=open(fileName,'wb') m=long(binaryRecieved,2) struct.pack('i',m) f.write(struct.pack('i',m)) f.close() quit() </code></pre> <p>I am left with the error</p> <pre><code>struct.pack('i',x) struct.error: integer out of range for 'i' format code </code></pre> <p>My integer is out of range, so I was wondering if there is a different way of going about with this.</p> <p>Thanks</p>
0
2016-09-17T05:21:55Z
39,543,990
<p>For encoding m in big-endian order (like "ten" being written as "10" in normal decimal use) use:</p> <pre><code>def as_big_endian_bytes(i): out=bytearray() while i: out.append(i&amp;0xff) i=i&gt;&gt;8 out.reverse() return out </code></pre> <p>For encoding <code>m</code> in little-endian order (like "ten" being written as "01" in normal decimal use) use:</p> <pre><code>def as_little_endian_bytes(i): out=bytearray() while i: out.append(i&amp;0xff) i=i&gt;&gt;8 return out </code></pre> <p>both functions work on numbers - like you do in your question - so the returned bytearray may be shorter than expected (because for numbers leading zeroes do not matter).</p> <p>For an exact representation of a binary-digit-string (which is only possible if its length is dividable by 8) you would have to do:</p> <pre><code>def as_bytes(s): assert len(s)%8==0 out=bytearray() for i in range(0,len(s)-8,8): out.append(int(s[i:i+8],2)) return out </code></pre>
1
2016-09-17T07:16:56Z
[ "python", "file", "binary" ]
pyplot and python. saving multiple graphs
39,543,196
<p>Well, we were recently given a project to make a natural selection simulator that tracks down the frequency of alleles through generations given particular particular viability of each allele pair. I made a program in python to print the graphs and it's working quite fine.</p> <p>Here it is.</p> <pre><code>#!/usr/bin/env python import matplotlib.pyplot as plt print ("Number of generations:") n=int(input()) genp=[] genq=[] print ("What is p:") p=float(input()) genp.append(p) toap=1-p genq.append(toap) print ("What is w11:") w11=float(input()) print ("What is w12:") w12=float(input()) print ("What is w22:") w22=float(input()) for i in range(1,n): genp.append((genp[i-1]*(genp[i-1]*w11+genq[i-1]*w12))/(genp[i-1]*genp[i-1]*w11+2*genp[i-1]*genq[i-1]*w12+genq[i-1]*genq[i-1]*w22)) genq.append(1-genp[i]) plt.plot(range(0,n),genp,'r-',label='A') plt.plot(range(0,n),genq,'b--',label='a') plt.xlabel('Generations') plt.ylabel('Allele Frequency') plt.legend(loc='upper left') plt.axis([0, n, -0.01, 1.01]) plt.title('p='+str(p)+' w11='+str(w11)+' w12='+str(w12)+' w22='+str(w22)+' for '+str(n)+' generations.', fontsize=14, fontweight='bold') plt.savefig('graphP-'+str(p)+'w11-'+str(w11)+'w12-'+str(w12)+'w22-'+str(w22)+'.png') plt.show() </code></pre> <p>Now,I decided to be a little lazy and make the program do the work of iterating through different values of viabilities. </p> <p>Here's how I modified it.</p> <pre><code>#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np print ("Number of generations:") n=int(input()) genp=[] genq=[] print ("What is p:") p=float(input()) genp.append(p) toap=1-p genq.append(toap) for l in range(1,10): for j in range(1,10): for k in range(1,10): w11=l*0.1 w12=j*0.1 w22=k*0.1 for i in range(1,n): genp.append((genp[i-1]*(genp[i-1]*w11+genq[i-1]*w12))/(genp[i-1]*genp[i-1]*w11+2*genp[i-1]*genq[i-1]*w12+genq[i-1]*genq[i-1]*w22)) genq.append(1-genp[i]) plt.plot(range(0,n),genp,'r-',label='A') plt.plot(range(0,n),genq,'b--',label='a') plt.xlabel('Generations') plt.ylabel('Allele Frequency') plt.legend(loc='upper left') plt.axis([0, n, -0.01, 1.01]) plt.title('p='+str(p)+' w11='+str(w11)+' w12='+str(w12)+' w22='+str(w22)+' for '+str(n)+' generations.', fontsize=14, fontweight='bold') plt.savefig('graphP-'+str(p)+'w11-'+str(w11)+'w12-'+str(w12)+'w22-'+str(w22)+'.png') </code></pre> <p>I don't know why but executing this program is leading to errors.</p> <pre><code>Traceback (most recent call last): File "./iterative.py", line 30, in &lt;module&gt; plt.plot(range(0,n),genp,'r-',label='A') File "/usr/lib/python3.5/site-packages/matplotlib/pyplot.py", line 3153, in plot ret = ax.plot(*args, **kwargs) File "/usr/lib/python3.5/site-packages/matplotlib/__init__.py", line 1819, in inner return func(ax, *args, **kwargs) File "/usr/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 1382, in plot for line in self._get_lines(*args, **kwargs): File "/usr/lib/python3.5/site-packages/matplotlib/axes/_base.py", line 381, in _grab_next_args for seg in self._plot_args(remaining, kwargs): File "/usr/lib/python3.5/site-packages/matplotlib/axes/_base.py", line 359, in _plot_args x, y = self._xy_from_xy(x, y) File "/usr/lib/python3.5/site-packages/matplotlib/axes/_base.py", line 219, in _xy_from_xy raise ValueError("x and y must have same first dimension") ValueError: x and y must have same first dimension </code></pre> <p>I searched stack overflow for the last error and found that it arises when the number of elements in x and y arrays is not same. The first program however is not giving this error.</p>
0
2016-09-17T05:33:04Z
39,554,241
<p>I may not be fully sure what you are trying, and it might have been a good idea to change user inputs against fixed values in your program, since nobody knows the vaules for your input parameters.</p> <p>Nevertheless I think your error is related to not initializing genp and genq properly for each loop cycle.</p> <p>So I have made 2 changes:</p> <ul> <li>I moved the initialization into the loop and </li> <li>I cleared genp and genq after each loop cycle</li> </ul> <p>Hope that solves your issues.</p> <p><strong>Hint:</strong> A way to track down your error would have been to analyze the actual dimensions of x and y at the line where the error occured, using a command like <code>print len(x)</code></p> <pre><code>#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np print ("Number of generations:") n=int(input()) genp=[] genq=[] print ("What is p:") p=float(input()) for l in range(1,10): for j in range(1,10): for k in range(1,10): # Move this part of code into your loop for initialization genp.append(p) toap=1-p genq.append(toap) # end w11=l*0.1 w12=j*0.1 w22=k*0.1 for i in range(1,n): genp.append((genp[i-1]*(genp[i-1]*w11+genq[i-1]*w12))/(genp[i-1]*genp[i-1]*w11+2*genp[i-1]*genq[i-1]*w12+genq[i-1]*genq[i-1]*w22)) genq.append(1-genp[i]) plt.plot(range(0,n),genp,'r-',label='A') plt.plot(range(0,n),genq,'b--',label='a') plt.xlabel('Generations') plt.ylabel('Allele Frequency') plt.legend(loc='upper left') plt.axis([0, n, -0.01, 1.01]) plt.title('p='+str(p)+' w11='+str(w11)+' w12='+str(w12)+' w22='+str(w22)+' for '+str(n)+' generations.', fontsize=14, fontweight='bold') plt.savefig('graphP-'+str(p)+'w11-'+str(w11)+'w12-'+str(w12)+'w22-'+str(w22)+'.png') #clear plot plt.clf() # Empty ypur lists after each run genp=[] genq=[] #end </code></pre>
0
2016-09-18T04:52:40Z
[ "python", "matplotlib", "graph" ]
Apply shift for comparison on multiple columns over groupby pandas
39,543,230
<p>I have a dataframe(raw_data) containing multiple columns:</p> <pre><code>raw_data = {'one': ['A', 'B', 'A', 'C', 'B', 'B', 'A', 'C', 'A', 'B', 'C', 'B'],'two' : [3,4,5,6,2,7,9,12,1,10,11,8],'three': ['bcd','qpv', 'cba','klm','zfv','klm','abc','abc','abc','lmf','fly','zdb'],'four':['cba','klm','tcf','fly','zfb','zdb','pcd','tlm','bcd','klm','mvt','jbm'], 'five':['apple','lemon','banana','water','kiwi','lemon','orange','apple','apple','straw','water','pom']} df = pd.DataFrame(raw_data, columns = ['one', 'two', 'three','four','five']) </code></pre> <p>From this df, I can generate new columns or directly shift by 1 for column three &amp; five.</p> <p>Output:</p> <p>1) Groupby 'one' </p> <p>2) sort by 'two' </p> <p>3) shift 'three' 1 level up, new column 'three_new'</p> <p>4) shift 'five' 1 level, new column 'five_new'</p> <p>5) compare 'four' with 'three_new' &amp; 'five' with 'five_new', if both match remove the first row &amp; continue</p> <p>6) comparison on groupby</p> <p>The output looks like this :</p> <pre><code>one two three four five A 3 bcd cba apple A 5 cba tcf banana A 9 abc pcd orange B 2 zfv zfb kiwi B 7 klm zdb lemon B 8 zdb jbm pom B 10 lmf klm straw C 11 fly mvt water C 12 abc tlm apple </code></pre> <p>Initial df has 12 rows &amp; output df has 9 rows, filtered on the above criteria. Please help.</p> <p>Thanks</p>
0
2016-09-17T05:38:08Z
39,544,657
<p>You could perform those steps as follows:</p> <pre><code># Groupby column one and sort values by column two df_grouped = df.groupby('one').apply(lambda x: x.sort_values('two')) # Shift by one level up and compare comparison_1 = df_grouped['five']==df_grouped['five'].shift(-1) comparison_2 = df_grouped['four']==df_grouped['three'].shift(-1) # Select not of subset df_grouped[~(comparison_1 &amp; comparison_2)].reset_index(drop=True) </code></pre> <p><a href="http://i.stack.imgur.com/C6Tf4.png" rel="nofollow"><img src="http://i.stack.imgur.com/C6Tf4.png" alt="Image"></a></p>
0
2016-09-17T08:32:47Z
[ "python", "pandas", "lambda" ]