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
Can we integrate Hadoop with Python?
37,936,958
<p>I have my project requirement in which one python script is used for analyzing the data. Previously, I used the txt files as an input to that python script. But as data grows, I have to switch my storage platform to Hadoop HDFS. How can I HDFS data to my python script? Is there any way of doing that? Thanks in advan...
1
2016-06-21T06:25:10Z
37,950,359
<p>In addition to other approaches, you can also embed Pig Latin statements and Pig commands in Python script using a JDBC-like compile, bind, run model. For Python, make sure the Jython jar is included in your class path. Refer apache pig documentation here for more details: <a href="https://pig.apache.org/docs/r0.9.1...
0
2016-06-21T16:56:36Z
[ "python", "hadoop", "hdfs", "bigdata" ]
iPython not responding while program is running. Will respond when program quits
37,937,007
<p>I'm fairly new to programming, so please bear with me. I have som difficulty explaining my problem, so i posted som pictures to help. This is a general problem i'm having</p> <p>I made an interactive program that prompts the user for some data. The user can do some operations on the data, including visualizing it. ...
-2
2016-06-21T06:28:39Z
37,942,522
<p>This should work:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt plt.ion() data = np.array([1,2,3,4,5]) timeline = np.arange(5) while True: choice = int(input("Please choose a number, 0 or 1: ")) if choice == 1: plt.plot(timeline, data) plt.pause(0.001) plt.draw()...
0
2016-06-21T10:55:27Z
[ "python", "matplotlib" ]
Download a file from a Flask-based Python server
37,937,091
<p>I'm trying to make work a code that I found at this URL: <a href="http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python" rel="nofollow">http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python</a></p> <p>My goal is ...
1
2016-06-21T06:34:21Z
37,937,923
<p>The best way to solve this issue is to use the already predefined helper function <a href="http://flask.pocoo.org/docs/0.11/api/#flask.send_file" rel="nofollow"><code>send_file()</code></a> in flask:</p> <pre><code>@app.route("/api/downloadlogfile/&lt;path&gt;") def DownloadLogFile (path = None): if path is Non...
0
2016-06-21T07:20:06Z
[ "python", "flask", "werkzeug", "webclient-download" ]
Python 3 & GTK3: crossplatform tray icon
37,937,212
<p>It's <a href="https://github.com/afiskon/py-gtk-example/blob/master/gtk-example.py" rel="nofollow">possible</a> to create a tray icon with a menu using AppIndicator3. But this solution is not portable. For instance <a href="https://lists.freebsd.org/pipermail/freebsd-questions/2016-June/272287.html" rel="nofollow">i...
1
2016-06-21T06:41:47Z
37,983,084
<p>Ok, I think I figured it out. The idea is to fallback to Gtk.StatusIcon if AppIndicator3 is unavailable:</p> <pre><code>class TrayIcon: def __init__(self, appid, icon, menu): self.menu = menu APPIND_SUPPORT = 1 try: from gi.repository import AppIndicator3 except: ...
1
2016-06-23T05:33:27Z
[ "python", "python-3.x", "gtk", "gtk3" ]
I have written two separate files, one containing classes and the other calling them but calling one makes object of all. Why?
37,937,231
<p>separate.py </p> <pre><code> class foo(): print 'a bunch of time consuming work' class tryme(): print 'try me'* </code></pre> <p>main.py</p> <pre><code>from separate import * foo() </code></pre> <p>It however printed both:</p> <pre><code>a bunch of time consuming work try me </code></p...
3
2016-06-21T06:42:57Z
37,937,532
<p>You should write an init for your classes then it wont happen anymore!</p> <pre><code>class foo(): def __init__(self): print('a bunch of time consuming work') class tryme(): def __init__(self): print ('try me') </code></pre>
1
2016-06-21T07:00:56Z
[ "python", "python-2.7" ]
I have written two separate files, one containing classes and the other calling them but calling one makes object of all. Why?
37,937,231
<p>separate.py </p> <pre><code> class foo(): print 'a bunch of time consuming work' class tryme(): print 'try me'* </code></pre> <p>main.py</p> <pre><code>from separate import * foo() </code></pre> <p>It however printed both:</p> <pre><code>a bunch of time consuming work try me </code></p...
3
2016-06-21T06:42:57Z
37,937,596
<p>When you call <code>from separate import *</code> you execute the print command ! If you want to just make an instance do something like : </p> <pre><code>class foo(): def my_print(self): print 'a bunch of time consuming work' </code></pre> <p>and call my print from main !</p> <pre><code>f = foo() f.my_prin...
1
2016-06-21T07:03:45Z
[ "python", "python-2.7" ]
I have written two separate files, one containing classes and the other calling them but calling one makes object of all. Why?
37,937,231
<p>separate.py </p> <pre><code> class foo(): print 'a bunch of time consuming work' class tryme(): print 'try me'* </code></pre> <p>main.py</p> <pre><code>from separate import * foo() </code></pre> <p>It however printed both:</p> <pre><code>a bunch of time consuming work try me </code></p...
3
2016-06-21T06:42:57Z
37,937,757
<p>Because commands in the scope of the class are statically defined, when importing a module it also initiate the static fields when binding everything. @Tino A gave a nice solution for you, but if you want to read some more material regarding <strong>imports</strong> in python try <a href="https://docs.python.org/3/r...
0
2016-06-21T07:11:33Z
[ "python", "python-2.7" ]
Graphite install error 0.10.0-alpha
37,937,232
<p>I get the following error when starting Graphite-web using DJango. 0.9.15 works ok, but I am looking to use the new "mapSeries" function available in 0.10.x</p> <p>Seems to be a missing import -</p> <blockquote> <pre><code>Exception occurred processing WSGI script '/opt/graphite/conf/graphite.wsgi'. Traceback (mos...
0
2016-06-21T06:43:00Z
37,937,447
<p>I solved the issue by updating <code>/opt/graphite/conf/graphite.wsgi</code> to the latest example version.<br> The 0.9.x version is not compatible with 0.10.x</p>
0
2016-06-21T06:56:22Z
[ "python", "django", "graphite" ]
can't get rid of 1e-5 while formatting in python 3 programming
37,937,270
<p>I am creating a length calculator and need to format it so it doesn't show <code>1e-5</code> from going to <code>mm</code> to <code>km</code>. i have tried <code>'{:.6}'.format()</code> but doesn't seem to work as still outputs it as 1e-5. </p> <p>Any help on what to do to get rid of this?</p>
-2
2016-06-21T06:45:11Z
37,937,330
<p>Use the <code>f</code> presentation type insteaf of the default (<code>g</code> with a small modification):</p> <pre><code>'{:.6f}'.format(floating_point_number) </code></pre> <p>See the <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow"><em>Format Specificati...
0
2016-06-21T06:48:48Z
[ "python", "python-3.x", "formatting", "format" ]
alternate of spsolve and spdiag in matlab/octave
37,937,326
<p>I have a python code which I am trying to convert to Matlab code. The code is for baseline correction for a wave.</p> <pre><code>def baseline_als(y, lam, p, niter=20): L = len(y) D = sparse.csc_matrix(np.diff(np.eye(L), 2)) w = np.ones(L) for i in xrange(niter): W = sparse.spdiags(w, 0, L, L...
0
2016-06-21T06:48:29Z
37,945,105
<p>Its quite easy <em>if you know what spsolve does</em>. Lets focus on that, <a href="https://uk.mathworks.com/help/matlab/ref/spdiags.html" rel="nofollow">as <code>spidiag</code> seems easier to solve</a>, doesn't it? </p> <p><code>spsolve</code> "Solve the sparse linear system Ax=b, where b may be a vector or a ma...
3
2016-06-21T12:56:24Z
[ "python", "matlab", "scikit-learn", "octave" ]
rounding 1 to have two floating digits
37,937,337
<pre><code>''' Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... ''' </code></pre> <p>Kind of non-trivial but I tried to use <code>round(1,2)</code> to show <code>1.00</code> but it shows <code>1.0</code>, what can I us...
0
2016-06-21T06:49:16Z
37,937,377
<p>For numerical calculation, the digits after the decimals should not matter. I believe you want a string representation with 2 decimal places.</p> <p>In Python 2.x, you'd do:</p> <pre><code>&gt;&gt;&gt; "%.2f"%1.0 '1.00' </code></pre> <p>In Python3.x, you'd do:</p> <pre><code>&gt;&gt;&gt; "{:.2f}".format(1.0) '1....
2
2016-06-21T06:52:04Z
[ "python", "floating-point", "integer", "rounding" ]
rounding 1 to have two floating digits
37,937,337
<pre><code>''' Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... ''' </code></pre> <p>Kind of non-trivial but I tried to use <code>round(1,2)</code> to show <code>1.00</code> but it shows <code>1.0</code>, what can I us...
0
2016-06-21T06:49:16Z
37,937,438
<p>Use <a href="https://docs.python.org/3.5/library/functions.html#format" rel="nofollow"><code>format</code></a> function:</p> <pre><code>return format(sum, '.2f') </code></pre>
0
2016-06-21T06:55:57Z
[ "python", "floating-point", "integer", "rounding" ]
django.db.migrations.exceptions.NodeNotFoundError
37,937,343
<p>When i run <code>makemigrations</code> command, i got this error:</p> <pre><code>Traceback (most recent call last): ... django.db.migrations.exceptions.NodeNotFoundError: Migration products.0002_auto_20160618_1143 dependencies reference nonexistent parent node (u'products', u'0001_initial') </code></pre>
0
2016-06-21T06:49:37Z
37,937,503
<p>If you open the file migration file <code>products.0002_auto_20160618_1143</code> you will see a section called dependencies:</p> <pre><code>dependencies = [("products", "0001_initial")] </code></pre> <p>Which will look like that. This line tell Django that the current file depends on that file. A file that given ...
1
2016-06-21T06:59:36Z
[ "python", "django" ]
Python - How do I put results of strings in an if else in a variable?
37,937,571
<p>let's say <code>rand_word</code> is string = <code>'petite'</code> and <code>guess</code> is a user input of a single char</p> <pre><code>for char in rand_word: if char in guess: print(char,end='') else: print('_',end="") </code></pre> <p>in the code above if I typed the letter 'e' as my in...
2
2016-06-21T07:02:30Z
37,937,619
<p>Put your characters in a list and join it with <code>str.join()</code>:</p> <pre><code>result = [] for char in rand_word: if char in guess: result.append(char) else: result.append('_') result = ''.join(result) </code></pre> <p>Using a conditional expression and a list comprehension, you can...
1
2016-06-21T07:05:01Z
[ "python", "python-3.x" ]
Python - How do I put results of strings in an if else in a variable?
37,937,571
<p>let's say <code>rand_word</code> is string = <code>'petite'</code> and <code>guess</code> is a user input of a single char</p> <pre><code>for char in rand_word: if char in guess: print(char,end='') else: print('_',end="") </code></pre> <p>in the code above if I typed the letter 'e' as my in...
2
2016-06-21T07:02:30Z
37,937,752
<p>Another way to do it:</p> <pre><code>result = [char if char in guess else "_" for char in rand_word] str_result = "".join(result) </code></pre>
0
2016-06-21T07:11:27Z
[ "python", "python-3.x" ]
Python - How do I put results of strings in an if else in a variable?
37,937,571
<p>let's say <code>rand_word</code> is string = <code>'petite'</code> and <code>guess</code> is a user input of a single char</p> <pre><code>for char in rand_word: if char in guess: print(char,end='') else: print('_',end="") </code></pre> <p>in the code above if I typed the letter 'e' as my in...
2
2016-06-21T07:02:30Z
37,939,921
<p>Simpler, maybe</p> <pre><code>to_print = "" for char in rand_word: if char in guess: to_print += char else: to_print += '_' print(to_print) </code></pre> <p>The million dollar question being why might this not be a good idea...</p>
0
2016-06-21T09:02:01Z
[ "python", "python-3.x" ]
How to add related field in following cases in odoo?
37,937,602
<p>In my following module I have two classes .When I select <strong>date_of1</strong> field from <strong>feeder_data</strong> class .Same selected date should auto-populate in tree view <strong>data_value</strong> at <strong>time_read</strong>.Now there are two fields are auto-populating using <strong>def get_feeder_ca...
1
2016-06-21T07:04:05Z
37,947,959
<pre class="lang-py prettyprint-override"><code>class feeder_data(osv.Model): _name="feeder.data" _columns = { 'date_of1':fields.datetime('Date',), } class data_value(osv.Model): _name = "data.value" _rec_name = "mega_wat" _columns = { 'time_read':fields.datetime('Time'), ...
2
2016-06-21T14:59:56Z
[ "python", "xml", "openerp" ]
patching multiple module variables in all tests
37,937,632
<p>I have a module with two module variables. I want to path them out for all tests in my file. Initially I did monkey patching but this turned out to be a problem for tests in other files, that require those variables to be intact. This is something I came up with currently. It's horrible but it works. I'd like to do ...
1
2016-06-21T07:05:47Z
37,938,060
<blockquote> <p>but I feel like the proper way to do that would be something that keeps a single indent.</p> </blockquote> <p><strong>With statement with multiple contexts</strong></p> <p>You can put several statements into a single <code>with</code></p> <pre><code>with patch.object(my_module, 'old_first_variable'...
0
2016-06-21T07:27:23Z
[ "python", "python-2.7", "py.test" ]
How do I use (or convert, or view) inline Python objects in Perl?
37,937,897
<p>I'm resurrecting some orphaned code, which is written in Perl but uses inline Python. A call to the Python module returns an array of dicts or Python objects. I'm really struggling with how to access the data structures within - if I try to straight out log (print) the data structure, it appears to give the the data...
2
2016-06-21T07:18:40Z
37,958,490
<p>I've got this working through a 'useless' list comprehension inside a <code>py_eval()</code>. It seems that Perl's Inline Python doesn't handle lists of the type <code>future.types.newlist.newlist</code> that are returned from the python code. So this code converts those into plain old lists, which Perl can then han...
1
2016-06-22T04:20:20Z
[ "python", "perl" ]
Python import fails Openpyxl
37,938,131
<p>I know many questions speak about this problem, but i tried a lot and didn't fin any solution to my "very classical" issue : Python import fails altough package installed:</p> <pre><code>MacBook-Pro-de-Stephanie:scripts user$ sudo -H pip install openpyxl Collecting openpyxl Requirement already satisfied (use --upgr...
1
2016-06-21T07:30:59Z
37,938,668
<p>I am not getting that error. Just now i installed. All i am getting is </p> <p>" /usr/local/lib/python2.7/dist-packages/openpyxl/xml/<strong>init</strong>.py:15: UserWarning: The installed version of lxml is too old to be used with openpyxl warnings.warn("The installed version of lxml is too old to be used with o...
-1
2016-06-21T07:58:40Z
[ "python", "import", "pip", "openpyxl" ]
Python import fails Openpyxl
37,938,131
<p>I know many questions speak about this problem, but i tried a lot and didn't fin any solution to my "very classical" issue : Python import fails altough package installed:</p> <pre><code>MacBook-Pro-de-Stephanie:scripts user$ sudo -H pip install openpyxl Collecting openpyxl Requirement already satisfied (use --upgr...
1
2016-06-21T07:30:59Z
37,940,443
<p>Here was the solution for me (linked to Mac OS clearly) : <a href="http://stackoverflow.com/questions/25276329/cant-load-python-modules-installed-via-pip-from-site-packages-directory">Can&#39;t load Python modules installed via pip from site-packages directory</a></p> <blockquote> <p><code>/usr/bin/python</code> ...
0
2016-06-21T09:23:34Z
[ "python", "import", "pip", "openpyxl" ]
Can we get request parameters from Django settings or other variables?
37,938,159
<p>I see that the request parameters can be obtained in a viewset function using request variable. eg:</p> <pre><code>@detail_route(methods=['get']) def mysampleviewsetfunction(self, request): print request </code></pre> <p>But, I want to be able to access request from some common variable. The purpose of that ...
0
2016-06-21T07:32:01Z
37,939,085
<blockquote> <p>it'd save me the trouble of modifying all the functions.</p> </blockquote> <p>You wouldn't have to if you provide a default.</p> <pre><code>def commonfunction(request=None): </code></pre> <p>This of course means that any existing function calls won't be able to use the request until you update them...
1
2016-06-21T08:19:38Z
[ "python", "django", "django-rest-framework" ]
reformat date to YYYY/MM/DD and replace column data in CSV
37,938,206
<p>I'm a newbie python programmer and I have a CSV that is simple, looks like this:</p> <pre><code>FROM_ID,JOIN_DATE,FAV_SPORT 100004,06/08/2016,Football 100006,06/08/2016,Tennis 100007,06/08/2016,Football 100009,06/08/2016,Basketball </code></pre> <p>I am trying to rewrite the date to YYYY/MM/DD. So far I have gotte...
-1
2016-06-21T07:34:09Z
37,938,403
<p>You're pretty close. All you need is:</p> <pre><code>print parts[2] + "/" + parts[0] + "/" + parts[1] </code></pre>
1
2016-06-21T07:45:31Z
[ "python", "python-2.7" ]
reformat date to YYYY/MM/DD and replace column data in CSV
37,938,206
<p>I'm a newbie python programmer and I have a CSV that is simple, looks like this:</p> <pre><code>FROM_ID,JOIN_DATE,FAV_SPORT 100004,06/08/2016,Football 100006,06/08/2016,Tennis 100007,06/08/2016,Football 100009,06/08/2016,Basketball </code></pre> <p>I am trying to rewrite the date to YYYY/MM/DD. So far I have gotte...
-1
2016-06-21T07:34:09Z
37,938,528
<pre><code>import csv f = open('reg.csv') csv_f = csv.reader(f) for row in csv_f: if "JOIN_DATE" in row: continue parts = row[1].split('/') data = "{}/{}/{}".format(parts[2],parts[1],parts[0]) print data </code></pre>
1
2016-06-21T07:51:46Z
[ "python", "python-2.7" ]
reformat date to YYYY/MM/DD and replace column data in CSV
37,938,206
<p>I'm a newbie python programmer and I have a CSV that is simple, looks like this:</p> <pre><code>FROM_ID,JOIN_DATE,FAV_SPORT 100004,06/08/2016,Football 100006,06/08/2016,Tennis 100007,06/08/2016,Football 100009,06/08/2016,Basketball </code></pre> <p>I am trying to rewrite the date to YYYY/MM/DD. So far I have gotte...
-1
2016-06-21T07:34:09Z
37,938,565
<p>As to your second point, you should probably have a look at <a href="http://pandas.pydata.org/pandas-docs/stable/" rel="nofollow">pandas</a>, which is a Python library for data analysis, especially of tabular data sets.</p> <p>You could read in your data using </p> <pre><code>df = pd.read_csv("path_to_your_file") ...
1
2016-06-21T07:53:21Z
[ "python", "python-2.7" ]
reformat date to YYYY/MM/DD and replace column data in CSV
37,938,206
<p>I'm a newbie python programmer and I have a CSV that is simple, looks like this:</p> <pre><code>FROM_ID,JOIN_DATE,FAV_SPORT 100004,06/08/2016,Football 100006,06/08/2016,Tennis 100007,06/08/2016,Football 100009,06/08/2016,Basketball </code></pre> <p>I am trying to rewrite the date to YYYY/MM/DD. So far I have gotte...
-1
2016-06-21T07:34:09Z
37,938,569
<p>Try this one:</p> <pre><code>import datetime . . datetime.datetime.strptime(row[1],'%d/%m/%Y').strftime('%Y/%m/%d') </code></pre>
0
2016-06-21T07:53:32Z
[ "python", "python-2.7" ]
reformat date to YYYY/MM/DD and replace column data in CSV
37,938,206
<p>I'm a newbie python programmer and I have a CSV that is simple, looks like this:</p> <pre><code>FROM_ID,JOIN_DATE,FAV_SPORT 100004,06/08/2016,Football 100006,06/08/2016,Tennis 100007,06/08/2016,Football 100009,06/08/2016,Basketball </code></pre> <p>I am trying to rewrite the date to YYYY/MM/DD. So far I have gotte...
-1
2016-06-21T07:34:09Z
37,939,027
<p>I reccommend using pandas:</p> <pre><code>import pandas as pd df = pd.read_csv("path_to_your_file") def change_date_format(date): # create a list of the substrings separated by '/', # so in your case ['DD', 'MM', 'YYYY'] split_dt = date.split("/") return split_dt[2] + '/' + split_dt[1] + '/' + ...
0
2016-06-21T08:16:31Z
[ "python", "python-2.7" ]
exec with ';' in python
37,938,236
<p>I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )</p> <pre><code>list = ["abc","xyz","pqr"] str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated exec (str) </code></pre> <p>My problem...
-2
2016-06-21T07:35:50Z
37,938,314
<p>Try this:</p> <pre><code>str = "print" + "list[0]" + "';'" + "list[2]" </code></pre> <p>or</p> <pre><code>str = "print" + "list[0]" + "/;" + "list[2]" </code></pre>
0
2016-06-21T07:40:37Z
[ "python", "printing", "exec", "semicolon" ]
exec with ';' in python
37,938,236
<p>I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )</p> <pre><code>list = ["abc","xyz","pqr"] str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated exec (str) </code></pre> <p>My problem...
-2
2016-06-21T07:35:50Z
37,938,320
<p>You are generating the following code:</p> <pre><code>print list[0];list[2] </code></pre> <p>Note that the <code>;</code> is <strong>not quoted</strong>. Since a <code>;</code> is used by Python to separate multiple simple statements on a line, Python executes the <code>print list[0]</code> first, then <code>list[...
4
2016-06-21T07:40:48Z
[ "python", "printing", "exec", "semicolon" ]
exec with ';' in python
37,938,236
<p>I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )</p> <pre><code>list = ["abc","xyz","pqr"] str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated exec (str) </code></pre> <p>My problem...
-2
2016-06-21T07:35:50Z
37,938,420
<p>The problem here is that Python optionally allows semicolons to delimit two separate statements (<a href="https://docs.python.org/2/reference/compound_stmts.html" rel="nofollow">Compound statements</a>). So when you use <code>exec</code> on the evaluated statement <code>print "abc";"xyz"</code>, Python thinks they a...
0
2016-06-21T07:46:21Z
[ "python", "printing", "exec", "semicolon" ]
Why Cant I Click an Element in Selenium using python and Chrome Webdriver?
37,938,287
<p>I use Selenium-python to scrape <a href="http://www.ooshop.com/courses-en-ligne/ContentNavigation.aspx?TO_NOEUD_IDMO=N000000013081&amp;FROM_NOEUD_IDMO=N000000013056&amp;TO_NOEUD_IDFO=81018&amp;NOEUD_NIVEAU=2&amp;UNIVERS_INDEX=2" rel="nofollow">this page</a> and click on Pagination numbers.</p> <p>i try this one:</p...
1
2016-06-21T07:39:05Z
37,941,585
<p><code>cssSelec = 'ctl00_cphC_pn3T1_ctl01_rptPaginationH_ctl0%s_lbPage' %number</code> and <code>cssSelec = 'ctl00_cphC_pn3T1_ctl01_rptPaginationH_ctl%s_lbPage' %number</code> refer to the id's for the elements you're trying to click and are not applicable CSS selectors by themselves - you <em>can</em> use them in a...
0
2016-06-21T10:11:39Z
[ "python", "selenium", "selenium-webdriver", "web-scraping", "selenium-chromedriver" ]
Why Cant I Click an Element in Selenium using python and Chrome Webdriver?
37,938,287
<p>I use Selenium-python to scrape <a href="http://www.ooshop.com/courses-en-ligne/ContentNavigation.aspx?TO_NOEUD_IDMO=N000000013081&amp;FROM_NOEUD_IDMO=N000000013056&amp;TO_NOEUD_IDFO=81018&amp;NOEUD_NIVEAU=2&amp;UNIVERS_INDEX=2" rel="nofollow">this page</a> and click on Pagination numbers.</p> <p>i try this one:</p...
1
2016-06-21T07:39:05Z
37,943,288
<p>You should try <code>.execute_script</code> to perform click as below :- </p> <pre><code>try:driver.execute_script("document.getElementById(arguments[0]).click();", cssSelec) </code></pre> <p>You can also try as below :-</p> <pre><code>try: element = WebDriverWait(driver, 10).until( EC.presence_of_elemen...
1
2016-06-21T11:32:45Z
[ "python", "selenium", "selenium-webdriver", "web-scraping", "selenium-chromedriver" ]
Numpy faster at sorting than Pandas
37,938,502
<p>this is a basic question about sorting arrays in numpy and pandas:</p> <p>I realized that when I used pandas for sorting and selecting specific columns of a data frame, that it took almost twice as long when I changed the code to use numpy arrays.</p> <p>What is the reason for this change in speed?</p> <p>Thanks,...
2
2016-06-21T07:50:29Z
37,938,822
<p><a href="https://penandpants.com/2014/09/05/performance-of-pandas-series-vs-numpy-arrays/" rel="nofollow">https://penandpants.com/2014/09/05/performance-of-pandas-series-vs-numpy-arrays/</a> explains it quite nicely. <code>pandas</code> as a lot of overhead, compared to <code>numpy</code></p> <p>quote from that sit...
1
2016-06-21T08:06:15Z
[ "python", "arrays", "sorting", "numpy", "pandas" ]
Test case Django command PyCharm
37,938,515
<p>I'm a new Pycharm's user, and in my project I created a Django command that needs two parameters. I know that to run it correctly I must add additional options and it works fine. </p> <p>Now i would like create a test case for it, but i don't know how add additional option in test case. </p> <p>I should add in Run...
0
2016-06-21T07:51:21Z
37,939,006
<p>The best way to do this is to put all of the command logic into a separate function that can be tested independently. Then the command simply calls that function.</p> <p>If that's not feasible for some reason you can test a command directly with </p> <pre><code>from django.core.management import call_command call...
1
2016-06-21T08:15:36Z
[ "python", "django", "pycharm", "testcase" ]
Constructor failing in inherited class python
37,938,792
<p>What is the correct way of calling a constructor in an inherited class in python?</p> <p>For example,</p> <pre><code>class A: def __init__(self, x, y): self.x = x self.y = y class B(A): def __init__(self, x, y, z): self.z = z # super().__init__(x, y) # &lt;== works ...
-2
2016-06-21T08:04:39Z
37,938,816
<p>Do this:</p> <pre><code>super(B, self).__init__(x, y) </code></pre>
2
2016-06-21T08:06:01Z
[ "python", "python-2.7" ]
Constructor failing in inherited class python
37,938,792
<p>What is the correct way of calling a constructor in an inherited class in python?</p> <p>For example,</p> <pre><code>class A: def __init__(self, x, y): self.x = x self.y = y class B(A): def __init__(self, x, y, z): self.z = z # super().__init__(x, y) # &lt;== works ...
-2
2016-06-21T08:04:39Z
37,938,817
<p>You are using <code>super()</code> wrong; you need to create the object passing in the current class and <code>self</code>, then reference an inherited attribute on that:</p> <pre><code>super(B, self).__init__(x, y) </code></pre> <p><code>super()</code> then uses <code>type(self).__mro__</code> to search the full ...
3
2016-06-21T08:06:03Z
[ "python", "python-2.7" ]
Python regex to find specific word in the middle of a text file
37,938,996
<p>I have a text file basically and I want to search for the middle word of a sentence. I get an error saying <code>found_state not defined</code> when I run my <code>.py</code> script. </p> <p>Consider this file:</p> <pre><code>file.conf hostname(config)#aaa new-model fdfsfd b kthik pooooo shh </code></pre> <p>My p...
0
2016-06-21T08:14:59Z
37,939,270
<p>If your condition <code>if re.search('(?&lt;=#)\w+',data):</code> fails, then found_state is not declared. Do that before the for loop.</p>
0
2016-06-21T08:30:26Z
[ "python", "regex", "grouping" ]
Python regex to find specific word in the middle of a text file
37,938,996
<p>I have a text file basically and I want to search for the middle word of a sentence. I get an error saying <code>found_state not defined</code> when I run my <code>.py</code> script. </p> <p>Consider this file:</p> <pre><code>file.conf hostname(config)#aaa new-model fdfsfd b kthik pooooo shh </code></pre> <p>My p...
0
2016-06-21T08:14:59Z
37,940,645
<p>Since you say you need to get the "middle word" I understand you need to <em>extract</em> that word. Right now, you get the whole line if there is a match.</p> <p>Here is <a href="https://ideone.com/HdPCEt" rel="nofollow">a piece of code</a> that should work for you (it prints <code>aaa is Found</code>):</p> <pre>...
0
2016-06-21T09:32:26Z
[ "python", "regex", "grouping" ]
How to use color scale to the whole column in xlsxwriter
37,939,095
<p>According to this example (<a href="http://xlsxwriter.readthedocs.io/working_with_conditional_formats.html" rel="nofollow">http://xlsxwriter.readthedocs.io/working_with_conditional_formats.html</a>) you can use color scales on columns. </p> <p>The example from the docs:</p> <pre><code>caption = 'Examples of color ...
1
2016-06-21T08:20:21Z
37,941,172
<p>In general in XlsxWriter you can set a 2D range to the maximum column values to get a <code>Col:Col</code> style range. This is also (generally) what happens internally in Excel.</p> <p>So the following should work in your case:</p> <pre><code>worksheet7.conditional_format('B1:B1048576', {'type': '3_color_scale'})...
1
2016-06-21T09:55:29Z
[ "python", "excel", "xlsxwriter" ]
Getting 404 with Flask ,Nginx and uwsgi
37,939,111
<p>I hava a flask application in /find_bili_user/app.py with the virtualenv in /python_envs/env1/,</p> <p>app.py:</p> <pre><code>from flask import Flask, jsonify, request, make_response from biliuser import getdanmu app = Flask('__name__') @app.route('/find_bili_user.json', methods=['GET']) def get_user(): av...
1
2016-06-21T08:21:18Z
37,962,765
<p>Solved. Turns out that I didn't delete in <code>/etc/nginx/sites-enabled/default</code>. </p>
0
2016-06-22T08:39:43Z
[ "python", "nginx", "uwsgi" ]
exporting Python model results
37,939,120
<p>Hi I’ve launched a random forest over a dataset imported as df. Now I would like to export both results (0-1 prediction) and predicted probabilities ( a two dimensions array) and match them to my dataset df. Is that possible? Until now I figured out how to export in a separate way to csv. And yes, I am not a panda...
0
2016-06-21T08:21:58Z
37,942,472
<p>You should be able to </p> <pre><code>df['results] = results df = pd.concat([df, pd.DataFrame(predicted_probs, columns=['Col_1', 'Col_2'])], axis=1) </code></pre>
0
2016-06-21T10:53:25Z
[ "python", "pandas", "export", "scikit-learn" ]
Python: Compare strings with 'or' operator
37,939,293
<p>In the Python3 tutorials, it is stated that "It is possible to assign the result of a comparison or other Boolean expression to a variable." The example given is:</p> <pre><code>&gt;&gt;&gt; string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' &gt;&gt;&gt; non_null = string1 or string2 or string3 &gt;&gt;&gt...
0
2016-06-21T08:31:35Z
37,939,365
<p><code>or</code> returns the value on the left of it if that is true-ish, and the one on the right otherwise.</p> <p>For strings, only <code>""</code> (the empty string) is not true-ish, and all others are.</p> <p>So</p> <pre><code>&gt;&gt;&gt; "" or "Test" "Test" </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt;...
1
2016-06-21T08:35:02Z
[ "python", "string", "python-3.x", "boolean", "boolean-logic" ]
Python: Compare strings with 'or' operator
37,939,293
<p>In the Python3 tutorials, it is stated that "It is possible to assign the result of a comparison or other Boolean expression to a variable." The example given is:</p> <pre><code>&gt;&gt;&gt; string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' &gt;&gt;&gt; non_null = string1 or string2 or string3 &gt;&gt;&gt...
0
2016-06-21T08:31:35Z
37,939,369
<p>Inclusive <code>or</code> selects the first non-falsy string (checking from left to right), which in this case is <code>'Trondheim'</code></p> <pre><code>&gt;&gt;&gt; bool('') False &gt;&gt;&gt; bool('Trondheim') True </code></pre> <p>It is sometimes preferable when performing this type of check to <code>strip</co...
2
2016-06-21T08:35:09Z
[ "python", "string", "python-3.x", "boolean", "boolean-logic" ]
Python: Compare strings with 'or' operator
37,939,293
<p>In the Python3 tutorials, it is stated that "It is possible to assign the result of a comparison or other Boolean expression to a variable." The example given is:</p> <pre><code>&gt;&gt;&gt; string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' &gt;&gt;&gt; non_null = string1 or string2 or string3 &gt;&gt;&gt...
0
2016-06-21T08:31:35Z
37,939,459
<p>When treated as boolean, an empty string will return <code>False</code> and a non empty string will return <code>True</code>.</p> <p>Since Python supports short circuiting, in the expression <code>a or b</code>, <code>b</code> won't be evaluated if <code>a</code> is True.</p> <p>In your example, we have <code>'' o...
1
2016-06-21T08:39:08Z
[ "python", "string", "python-3.x", "boolean", "boolean-logic" ]
Python: Compare strings with 'or' operator
37,939,293
<p>In the Python3 tutorials, it is stated that "It is possible to assign the result of a comparison or other Boolean expression to a variable." The example given is:</p> <pre><code>&gt;&gt;&gt; string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' &gt;&gt;&gt; non_null = string1 or string2 or string3 &gt;&gt;&gt...
0
2016-06-21T08:31:35Z
37,939,525
<p>In the assignment of <code>non_null</code>, the <code>or</code> comparisons are evaluated sequentially, which translates to this :</p> <pre><code>if string1: non_null = string1 elif string2: non_null = string2 elif string3: non_null = string3 else: non_null = False </code></pre> <p>However, in your...
1
2016-06-21T08:42:26Z
[ "python", "string", "python-3.x", "boolean", "boolean-logic" ]
Python Bot How to Retry after network failure
37,939,304
<p>I have this Twitter App, i am running it locally sometimes it fails due to Slow internet connection. once it fails i have to restart the app from Cmd. is it possible to make the bot sleep if network fails and retry the code </p> <pre><code>import tweepy, time, sys argfile = str(sys.argv[1]) #APP #CONSUMER_KE...
0
2016-06-21T08:32:07Z
37,939,544
<p>I would do something like this:</p> <pre><code>import requests import socket def get_json(url): """Fetches JSON response from specified URL""" fetched_data = dict() try: request = requests.get(url, timeout=2) try: fetched_data = request.json() print("JSON respo...
0
2016-06-21T08:43:32Z
[ "python", "for-loop", "tweepy" ]
How to export 3D files from python(pygame)
37,939,412
<p>I have created a pygame based environment. In that I am importing a spherical ball blender based obj file. Using pykinect, I am trying to mould the object with inputs from a kinect for Xbox 360 camera.</p> <p>All is working ok.</p> <p>However I wish to export the end product 3D moulded object and save it in a .dae...
0
2016-06-21T08:37:32Z
37,956,343
<p>If you are 'just' moving the locations of vertices (which is what moulding sounds like) then you can 'just' replace that block of the .obj etc file. You should be able to figure out where to cut and insert by looking at some files (I've done this with .obj but not the others so this may be harder than I suggest!) </...
0
2016-06-21T23:47:16Z
[ "python", "numpy", "pygame", "blender", "pykinect" ]
Python: How to get Exception OSError 's third arguments?
37,939,508
<p>From <a href="https://docs.python.org/3/library/exceptions.html#OSError" rel="nofollow">Python document</a>:</p> <blockquote> <p>For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.</p> </blockquote> <p>So How do we I the t...
1
2016-06-21T08:41:47Z
37,939,596
<p>In your example, <code>error.args</code> contains <code>(2, 'No such file or directory')</code>.</p> <p>In order to get the path, you should access <code>error.filename</code>:</p> <pre><code>try: open('some/invalid path') except OSError as e: print(e.filename) &gt;&gt; 'some/invalid path' </code></pre...
1
2016-06-21T08:45:52Z
[ "python" ]
Python: How to get Exception OSError 's third arguments?
37,939,508
<p>From <a href="https://docs.python.org/3/library/exceptions.html#OSError" rel="nofollow">Python document</a>:</p> <blockquote> <p>For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.</p> </blockquote> <p>So How do we I the t...
1
2016-06-21T08:41:47Z
37,939,598
<p>From the same docs:</p> <blockquote> <p>For exceptions that involve a file system path (such as open() or os.unlink()), <strong>filename</strong> is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name pas...
1
2016-06-21T08:46:00Z
[ "python" ]
differences between for...in and for... , .. in
37,939,583
<p>can anyone help me to figure out difference between</p> <pre><code>for abc in xyz </code></pre> <p>and</p> <pre><code>for abc, n in xyz </code></pre> <p>I know in first case each letter is assigned to abc in every iteration. How is it different from 2nd case</p>
-10
2016-06-21T08:45:21Z
37,939,671
<pre><code>xyz=[(3,8),(23,13),(89,34)] for abc, n in xyz: print( abc, " ## ",n) </code></pre> <p>Result:</p> <pre><code>3 ## 8 23 ## 13 89 ## 34 </code></pre>
2
2016-06-21T08:49:17Z
[ "python" ]
differences between for...in and for... , .. in
37,939,583
<p>can anyone help me to figure out difference between</p> <pre><code>for abc in xyz </code></pre> <p>and</p> <pre><code>for abc, n in xyz </code></pre> <p>I know in first case each letter is assigned to abc in every iteration. How is it different from 2nd case</p>
-10
2016-06-21T08:45:21Z
37,939,719
<p>At first both lines are missing the <code>:</code> at the end.</p> <p>The first iterates over the string <code>'xyz'</code>. This will do one iteration per character. The second iterates over the variable <code>xyz</code>. This could be anything, so nothing can be said about the resulting iteration.</p> <p>The fir...
1
2016-06-21T08:52:02Z
[ "python" ]
differences between for...in and for... , .. in
37,939,583
<p>can anyone help me to figure out difference between</p> <pre><code>for abc in xyz </code></pre> <p>and</p> <pre><code>for abc, n in xyz </code></pre> <p>I know in first case each letter is assigned to abc in every iteration. How is it different from 2nd case</p>
-10
2016-06-21T08:45:21Z
37,939,789
<p>This is doing "tuple-unpacking" in a loop. What is tuple unpacking?</p> <pre><code>&gt;&gt;&gt; t = ("foo", "bar") &gt;&gt;&gt; a, b = t &gt;&gt;&gt; a 'foo' &gt;&gt;&gt; b 'bar' </code></pre> <p>This will only work if the tuple has the same number of elements as there are variables you are unpacking it into. If y...
0
2016-06-21T08:55:05Z
[ "python" ]
differences between for...in and for... , .. in
37,939,583
<p>can anyone help me to figure out difference between</p> <pre><code>for abc in xyz </code></pre> <p>and</p> <pre><code>for abc, n in xyz </code></pre> <p>I know in first case each letter is assigned to abc in every iteration. How is it different from 2nd case</p>
-10
2016-06-21T08:45:21Z
37,939,862
<p>The difference is that <code>for abc, n in xyz</code> will unpack two elements from xyz, for example if you have a list of lists such as <code>xyz=[[1,2],[3,4]]</code> for each iteration you will get the elements from the inner list. However, if you had <code>xyz[[1,2,3],[4,5,6]]</code> and you try to do <code>for a...
0
2016-06-21T08:58:50Z
[ "python" ]
Numpy indexing reorders array
37,939,602
<p>I have just stumbled over a numpy index behavior which I do not quite understand. It seems like numpy is changing the order of my axes depending on the indexing schema. Unfortunately, I cannot find an explanation for the following in the documentation. Could somebody explain to me what is going on?</p> <pre><code>#...
3
2016-06-21T08:46:12Z
37,940,712
<p>It is expected behavior... NumPy treats axes indexed with slices and axes indexed with arrays differently. The default behavior is that the resulting shape will have the resulting shape of axes indexed with arrays before the resulting shape of axes indexed with slices. Which means that the odd one out is the first...
4
2016-06-21T09:35:15Z
[ "python", "numpy", "slice" ]
Python string in exception converted to tuple
37,939,701
<p>Python 2.7.10 appears to be converting my string into a tuple when thrown in an exception. Here's my example:</p> <pre><code>class MyError(RuntimeError): def __init__(self, arg): self.args = arg def raiseMyError(): errorCode = 29 errorText = 'Port not ready yet' exitCodeMessage = 'ERROR {0}: {...
2
2016-06-21T08:50:47Z
37,939,808
<p>Actually you don't need to override the <code>__init__</code> method at all, it's sufficient enough to:</p> <pre><code>class MyError(RuntimeError): pass </code></pre> <p>Regarding the behaviour - <a href="https://docs.python.org/2/library/exceptions.html#exceptions.BaseException.args" rel="nofollow">docs</a> st...
2
2016-06-21T08:56:16Z
[ "python", "string", "exception", "tuples" ]
Python string in exception converted to tuple
37,939,701
<p>Python 2.7.10 appears to be converting my string into a tuple when thrown in an exception. Here's my example:</p> <pre><code>class MyError(RuntimeError): def __init__(self, arg): self.args = arg def raiseMyError(): errorCode = 29 errorText = 'Port not ready yet' exitCodeMessage = 'ERROR {0}: {...
2
2016-06-21T08:50:47Z
37,940,084
<p>This is because args is a property that is defined in the <code>BaseException</code> class.</p> <p>Check out exceptions.py:70:</p> <p><code>args = property(lambda self: tuple())</code></p> <p>Try this:</p> <pre><code>class MyError(RuntimeError): def __init__(self, errorString): self._errorString = error...
2
2016-06-21T09:09:37Z
[ "python", "string", "exception", "tuples" ]
Assign color to points (x,y)
37,939,716
<p>I have a list of points (r1,r2) which I am plotting. For these points I have a certain error value 's' associated with each one of them. I want to assign a color with respect to what the error for each point is. For example red for highest error and blue for lowest error and also get a legend showing the range of co...
0
2016-06-21T08:51:47Z
37,940,103
<p>How about this,</p> <p><a href="http://i.stack.imgur.com/2iPzj.png" rel="nofollow"><img src="http://i.stack.imgur.com/2iPzj.png" alt="enter image description here"></a></p> <hr> <p>The source code is as follows. Refer to <a href="http://matplotlib.org/users/colormaps.html" rel="nofollow">colormaps</a> for more ab...
0
2016-06-21T09:10:20Z
[ "python", "plot", "colors" ]
How to fetch the Response object of a Request synchronously on Scrapy?
37,939,736
<p>I believe using "callback" method is asynchronous, please correct me if I'm wrong. I'm still new with Python so please bear with me.</p> <p>Anyway, I'm trying to make a method to check if a file exists and here is my code:</p> <pre><code>def file_exists(self, url): res = False; response = Request(url, meth...
0
2016-06-21T08:52:27Z
37,939,877
<p>Scrapy uses Request and Response objects for crawling web sites.</p> <p>Typically, Request objects are generated in the spiders and pass across the system until they reach the Downloader, which executes the request and returns a Response object which travels back to the spider that issued the request.</p> <p>Unles...
0
2016-06-21T09:00:00Z
[ "python", "scrapy" ]
How to fetch the Response object of a Request synchronously on Scrapy?
37,939,736
<p>I believe using "callback" method is asynchronous, please correct me if I'm wrong. I'm still new with Python so please bear with me.</p> <p>Anyway, I'm trying to make a method to check if a file exists and here is my code:</p> <pre><code>def file_exists(self, url): res = False; response = Request(url, meth...
0
2016-06-21T08:52:27Z
37,945,188
<p><code>Request</code> objects don't generate anything. </p> <p>Scrapy uses asynchronous Downloader engine which takes these <code>Request</code> objects and generate <code>Response</code> objects. </p> <p>if any method in your spider returns a Request object it is automatically scheduled in the downloader and retur...
0
2016-06-21T13:01:04Z
[ "python", "scrapy" ]
Does arr = [val] * N have liner or constant time?
37,939,814
<p>I am trying to solve some problem at codility. And I am wondering whether <code>answ = [max] * N</code> has linear or constant time ?</p> <pre><code>def solution(N, A): answ = [0] * N max = 0 for item in A: if item &gt; N: answ = [max] * N # this line here. Linear or constant time ...
1
2016-06-21T08:56:23Z
37,939,934
<p>Since you're populating an array sized <code>N</code> with the value <code>max</code>, that means you're doing <code>N</code> writes - hence it is linear in complexity.</p> <p>There are some data structures that can receive a "default" value for all items that aren't explicitly declared with a value, in a bound arr...
1
2016-06-21T09:02:41Z
[ "python", "algorithm", "asymptotic-complexity" ]
Does arr = [val] * N have liner or constant time?
37,939,814
<p>I am trying to solve some problem at codility. And I am wondering whether <code>answ = [max] * N</code> has linear or constant time ?</p> <pre><code>def solution(N, A): answ = [0] * N max = 0 for item in A: if item &gt; N: answ = [max] * N # this line here. Linear or constant time ...
1
2016-06-21T08:56:23Z
37,940,652
<p>Yes. CPython lists are merely arrays of pointers. Check out struct definition in listobject.h:</p> <p><a href="https://hg.python.org/cpython/file/tip/Include/listobject.h#l22" rel="nofollow">https://hg.python.org/cpython/file/tip/Include/listobject.h#l22</a></p> <pre><code>typedef struct { PyObject_VAR_HEAD ...
1
2016-06-21T09:32:34Z
[ "python", "algorithm", "asymptotic-complexity" ]
Shifting origin in plots using pandas python
37,939,843
<p>I have a data frame in pandas and I am plotting a scatter plot between two columns of the data frame,Now I want to transform the origin from (0,0) to say (1300,50) in this scatter plot.I am using Jupyter IPython notebook on ubuntu</p>
0
2016-06-21T08:57:49Z
37,942,754
<p>You can use <code>xlim</code> and <code>ylim</code>, and provide either a <code>tuple</code> as <code>(lower, upper)</code> or an <code>int</code> as lower limit only:</p> <pre><code>import pandas as pd import numpy as np plt.style.use('ggplot') df = pd.DataFrame(data={'X': np.random.random(100) * 50 + 100, 'Y': np...
1
2016-06-21T11:06:47Z
[ "python", "pandas", "data-visualization", "jupyter-notebook" ]
Google Bigquery API: How to add result query to Table?
37,939,975
<p>I have already read some introduction about this topic but this code didn't run. I created table 'product_flat_index' in project and this function add query result to that table. But it didn't run .</p> <pre><code>def insertValues(service): project_id = "598330041668" dataset_id = 'recommendation_001' t...
0
2016-06-21T09:04:38Z
37,980,419
<p>You should specify your <code>destinationTable</code>, <code>createDisposition,</code> and <code>writeDisposition</code> properties within your query configuration object, not the top-level configuration. They are properties of configuration.query, not the top-level configuration. For example, <a href="https://clo...
0
2016-06-23T00:35:34Z
[ "python", "bigdata", "google-bigquery" ]
How to get multiple tk.text widgets to adjust to content height?
37,940,002
<p>I'm working on a gui with tcl/tk 8.5.9 and python 3.5.1 on Mac OS X 10.11.5.</p> <p>I'm trying to create a sort of list of tk.text widgets that have a fixed width and adjust height to fit their content whenever it is changed (by the user or programmatically). This should take into account real as well as wrapped di...
1
2016-06-21T09:05:47Z
38,016,721
<p>I solved this by configuring the bindtags and resetting the event binding on Key-events every time the text widget gets the focus (event binding on FocusIn).</p> <p>Probably not a clean solution, but it seems to work fine:</p> <pre><code>from tkinter import * class ResizingText(Text): def __init__(self, paren...
0
2016-06-24T15:15:06Z
[ "python", "tkinter" ]
Replace Specific field values in fabric
37,940,004
<p>i have file with below content i want to change only some values in below code.how can i do it in fabric.</p> <pre><code> totem { version: 2 cluster_name: lbcluster transport: udpu interface { ringnumber: 0 bindnetaddr: server_private_IP_address broadcast: yes mcastport: 5405 } } quorum { provider: coro...
0
2016-06-21T09:05:54Z
37,963,521
<p>You could use sed, an example:</p> <pre><code>def sed_ip(): sed('/home/user/test/file', 'primary_private_IP_address', '192.168.0.0') </code></pre>
1
2016-06-22T09:12:32Z
[ "python", "fabric" ]
Signal Comparison method
37,940,005
<p>I have 2 raw signals having same sampling rate and they start at different time. I am interested in trying to do a match making(i.e. both to be similar without any deviations) of these signals in python 3.5. Can anyone give me inputs on what is the best method to compare such signals and say there is no change in ...
0
2016-06-21T09:06:00Z
37,940,134
<p>I'd find the moment with peak amplitude in both signal stream, and sync the signals there. Then I'd go over the signal, sample by sample, normalize the values based on the peak amplitude and compare the trend. </p> <p>I don't think this question should be here, by the way, try to ask in a more relevant StackExchang...
0
2016-06-21T09:12:05Z
[ "python", "matlab" ]
Signal Comparison method
37,940,005
<p>I have 2 raw signals having same sampling rate and they start at different time. I am interested in trying to do a match making(i.e. both to be similar without any deviations) of these signals in python 3.5. Can anyone give me inputs on what is the best method to compare such signals and say there is no change in ...
0
2016-06-21T09:06:00Z
37,941,568
<p>What i can recommend is:<br></p> <ol> <li><strong>Fast-Fourier-Transform</strong>: you get all the different frequencies within your two signals and then you can see if there are any different peaks between the two spectrum of the signals.</li> <li><strong>Wavelet Transform</strong>: kind of same working principle ...
0
2016-06-21T10:11:04Z
[ "python", "matlab" ]
Dynamic boolean mask on same values certain columns pandas
37,940,026
<p>I have a Pandas DataFrame where certain rows have the same values in similar columns. I want to create a boolean mask that is True when all these columns have the same values for the specific row. I want to dynamically pass a list of columns to check. Example:</p> <pre><code>A | B | C | Mask 1 | 1 | 1 | True 2 | 2 ...
2
2016-06-21T09:07:00Z
37,940,510
<p>You can compare all <code>df</code> with first column by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow"><code>eq</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a> :</p>...
1
2016-06-21T09:26:10Z
[ "python", "pandas" ]
Dynamic boolean mask on same values certain columns pandas
37,940,026
<p>I have a Pandas DataFrame where certain rows have the same values in similar columns. I want to create a boolean mask that is True when all these columns have the same values for the specific row. I want to dynamically pass a list of columns to check. Example:</p> <pre><code>A | B | C | Mask 1 | 1 | 1 | True 2 | 2 ...
2
2016-06-21T09:07:00Z
37,940,599
<p>After discussing with a colleague he pointed me to this post:</p> <p><a href="http://stackoverflow.com/questions/21231478/get-rows-that-have-the-same-value-across-its-columns-in-pandas">Get rows that have the same value across its columns in pandas</a></p> <p>I have tried both methods mentioned here and on the lin...
1
2016-06-21T09:30:23Z
[ "python", "pandas" ]
Dynamic boolean mask on same values certain columns pandas
37,940,026
<p>I have a Pandas DataFrame where certain rows have the same values in similar columns. I want to create a boolean mask that is True when all these columns have the same values for the specific row. I want to dynamically pass a list of columns to check. Example:</p> <pre><code>A | B | C | Mask 1 | 1 | 1 | True 2 | 2 ...
2
2016-06-21T09:07:00Z
37,940,624
<p>You can try this:</p> <pre><code>data = pd.DataFrame({'a': [1, 2, 4], 'b': [1, 2, 4], 'c': [1, 3, 4]}) data.apply(lambda x: len(set(x)) == 1, axis=1) </code></pre>
1
2016-06-21T09:31:35Z
[ "python", "pandas" ]
Dynamic boolean mask on same values certain columns pandas
37,940,026
<p>I have a Pandas DataFrame where certain rows have the same values in similar columns. I want to create a boolean mask that is True when all these columns have the same values for the specific row. I want to dynamically pass a list of columns to check. Example:</p> <pre><code>A | B | C | Mask 1 | 1 | 1 | True 2 | 2 ...
2
2016-06-21T09:07:00Z
37,940,740
<p>How bad is this:</p> <pre><code>list_a = [1, 2, 4] list_b = [1, 2, 4] list_c = [1, 3, 4] longshot = [True if not x % 111 else False for x in list(map(lambda x: int(str(x[0])+str(x[1])+str(x[2])), list(zip(list_a, list_b, list_c))))] print(longshot) # [True, False, True] </code></pre>
0
2016-06-21T09:36:39Z
[ "python", "pandas" ]
Negating `operator.attrgetter`
37,940,094
<p>I would like to use <code>operator.attrgetter</code> and <code>itertool.groupby</code> to split a string of text by spaces, preserving the number of spaces between the text. This is the expected behaviour:</p> <pre><code>result = process('Am G C') assert result == [(2, 'Am'), (20, ' '), ...
0
2016-06-21T09:09:51Z
37,941,090
<p><a href="https://docs.python.org/3.5/library/operator.html#operator.attrgetter" rel="nofollow"><code>operator.attrgetter</code></a> won't directly work as a key function here. <code>attrgetter("isspace")(x)</code> will just fetch the <code>"isspace"</code> attribute of <code>x</code>, while you also need to call it:...
4
2016-06-21T09:51:26Z
[ "python", "list-comprehension", "itertools" ]
Negating `operator.attrgetter`
37,940,094
<p>I would like to use <code>operator.attrgetter</code> and <code>itertool.groupby</code> to split a string of text by spaces, preserving the number of spaces between the text. This is the expected behaviour:</p> <pre><code>result = process('Am G C') assert result == [(2, 'Am'), (20, ' '), ...
0
2016-06-21T09:09:51Z
37,944,450
<p>No, you cannot make an inverted function of the the <code>attrgetter</code>, or any other function with the <code>neg</code> operator. First of all, <code>neg</code> stands for <em>negation</em>; e.g. <code>neg(x)</code> &lt;=> <code>-x</code>. And this applied to <code>False</code> results in <code>0</code>; <code>...
2
2016-06-21T12:27:54Z
[ "python", "list-comprehension", "itertools" ]
How to draw points with bright colors in an image with Pillow/PIL library
37,940,390
<p>I'm implementing a basic crowd dynamic software. At each timestep, all people inside a rectangular area with exits is evolved in the direction pointed by the model. The output at each timestep shall be printed to an image. I did not have big issues in drawing the area as a rectangle and the people as points, but now...
0
2016-06-21T09:21:29Z
37,986,548
<p>It seems that the anti-aliasing or smoothing makes the colors less vibrant. One path to try is to output to a lossless PNG rather than a JPEG, or even a higher quality JPEG. Another is to use a 9x9 pixel square, that'll be less affected by the smoothing. </p>
1
2016-06-23T08:47:47Z
[ "python", "pillow" ]
pandas interchangeable dual indexing?
37,940,518
<p>I have a DataFrame and I build a dual index. 'start' values don't exist in 'end' index values and versa.</p> <pre><code>c_weights.rename(columns={0:'start',1:'end',2:'metric',3:'angular',4:'special',5:'cos_pi'}, inplace=True) c_weights.set_index(['start','end'],inplace=True) c_weights.head() </code></pre> <p><img ...
0
2016-06-21T09:26:29Z
37,941,426
<p>Anyways, for the first case, you can just index using <code>ix</code> and passing a tuple on the row index</p> <pre><code>c_weights.ix[(1,638)] </code></pre> <p>For the second case, I guess it'll depend whether you know off hand or not if you're trying to pass the end first, in which case I'd just construct a tupl...
0
2016-06-21T10:05:37Z
[ "python", "pandas", "dataframe" ]
pandas interchangeable dual indexing?
37,940,518
<p>I have a DataFrame and I build a dual index. 'start' values don't exist in 'end' index values and versa.</p> <pre><code>c_weights.rename(columns={0:'start',1:'end',2:'metric',3:'angular',4:'special',5:'cos_pi'}, inplace=True) c_weights.set_index(['start','end'],inplace=True) c_weights.head() </code></pre> <p><img ...
0
2016-06-21T09:26:29Z
37,941,910
<p>A dataframe is a wrapper around an numpy ndarray in which a row and column index are assigned. We can define a second dataframe with different row or column indices and access the same ndarray. For example, let's first define <code>df1</code>, then define <code>df2</code> with the same data, but swap the levels in...
0
2016-06-21T10:27:16Z
[ "python", "pandas", "dataframe" ]
how to divide information after extracting data from multiple tags using BS4
37,940,521
<p>I am new in Python. I have problem when extracting list from documents. My sources file is not really html but it has a tag to extract data needed.</p> <p><a href="https://i.stack.imgur.com/Y5nSI.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/Y5nSI.jpg" alt="enter image description here"></a></p> <p>I man...
0
2016-06-21T09:26:38Z
37,941,000
<p>You can group in a dict, using the tag name to do the grouping so you can do it in a single pass:</p> <pre><code>soup = BeautifulSoup(page.read(),"xml") d = {"review_text":[], "product_name": []} for review in soup.find_all(['review_text','product_name']): d[review.name].append(review.get_text()) </code></pre> ...
-1
2016-06-21T09:47:56Z
[ "python", "beautifulsoup" ]
Django rest framework add dict to serializer
37,940,524
<p>This is my serializers.py:</p> <pre><code>class SysUserSerializer(serializers.ModelSerializer): pk = serializers.IntegerField(read_only=True) login_id = serializers.CharField(required=False) name = serializers.CharField(required=False) class Meta: model = SysUser fields = ('pk','log...
0
2016-06-21T09:26:42Z
37,941,579
<p>Problem here that <code>serializer.data</code> is not instance argument, but <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L225" rel="nofollow"><code>property</code></a> which returns it. So you can fix this by assigning <code>serializer.data</code> to variab...
0
2016-06-21T10:11:27Z
[ "python", "django", "django-rest-framework", "response", "django-serializer" ]
What is it qd in scapy?
37,940,607
<p>I found a code that do a DNS request. I understand almost everything there except for this part: <code>qd=DNSQR(qname="www.facebook.com")</code>. Can someone tell me what it means?</p> <p>Here is the whole code:</p> <pre><code> my_packet = sr1(IP(dst="8.8.8.8")/UDP(dport = 53)/DNS(rd=1,qd=DNSQR(qname=URL))) </code...
0
2016-06-21T09:30:49Z
37,982,471
<p>Let's open the source code:</p> <pre><code>class DNSQR(Packet): name = "DNS Question Record" fields_desc = [ DNSStrField("qname",""), ShortEnumField("qtype", 1, dnsqtypes), ShortEnumField("qclass", 1, dnsclasses) ] </code></pre> <p>where <code>ShortEnumField</code> a...
0
2016-06-23T04:39:34Z
[ "python", "python-2.7", "scapy" ]
Python Pandas: Get 2 set of random samples per group
37,940,654
<p>I have a pandas DataFrame say this:</p> <pre><code> user value 0 a 1 1 a 2 2 a 3 3 a 4 4 a 5 5 b 6 6 b 7 7 b 8 8 b 9 9 b 10 10 c 11 11 c 12 12 c 13 13 c 14 14 c 15 </code></pre> <p>Now I w...
1
2016-06-21T09:32:36Z
37,941,076
<p>There is likely a better solution but what about just randomizing your data before grouping and then taking the tail and head per group? You could take a set of your indices, take a random permutation of it and use that to create a new scrambled dataframe, then do your current procedure.</p>
1
2016-06-21T09:51:05Z
[ "python", "pandas" ]
Python Pandas: Get 2 set of random samples per group
37,940,654
<p>I have a pandas DataFrame say this:</p> <pre><code> user value 0 a 1 1 a 2 2 a 3 3 a 4 4 a 5 5 b 6 6 b 7 7 b 8 8 b 9 9 b 10 10 c 11 11 c 12 12 c 13 13 c 14 14 c 15 </code></pre> <p>Now I w...
1
2016-06-21T09:32:36Z
37,941,171
<p>This maybe a bit naive but all I did was reindex the DataFrame with a random permutation of the length of the DataFrame and reset the index. After that I take the head and tail as you did with your original code, seems to work. This could probably be made into a function:</p> <pre><code>a = np.arange(len(df)) np.ra...
2
2016-06-21T09:55:27Z
[ "python", "pandas" ]
Python Pandas: Get 2 set of random samples per group
37,940,654
<p>I have a pandas DataFrame say this:</p> <pre><code> user value 0 a 1 1 a 2 2 a 3 3 a 4 4 a 5 5 b 6 6 b 7 7 b 8 8 b 9 9 b 10 10 c 11 11 c 12 12 c 13 13 c 14 14 c 15 </code></pre> <p>Now I w...
1
2016-06-21T09:32:36Z
37,941,505
<p>You can randomly select 3 records for each user:</p> <pre><code>a = df.groupby("user")["value"].apply(lambda x: x.sample(3)) a Out[27]: user a 3 4 0 1 2 3 b 5 6 7 8 6 7 c 14 15 10 11 13 14 dtype: int64 </code></pre> <p>And...
3
2016-06-21T10:08:25Z
[ "python", "pandas" ]
Blank page apply.cgi during selenium webdriver automation
37,940,667
<p>I am trying to automate a router configuration using selenium webdriver. Below is the html of the router page:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:v=""&gt; ...
0
2016-06-21T09:33:13Z
37,947,289
<p>I was prepending router credentials to the base_url in python script which was causing issue on page refresh. Page refresh was happening after option was getting selected from drop down menu and script was not able to open the authentication url again. Now I open base_url(without credentials) after logging into the ...
0
2016-06-21T14:32:16Z
[ "python", "selenium", "selenium-webdriver" ]
line_profiler and kernprof does not work installed from pip and repro
37,940,860
<p>I have tried what has been suggested. On the simplest of code, I get the familiar error that others have mentioned. The error is:</p> <pre><code>@profile NameError: name 'profile' is not defined </code></pre> <p>on the minimal code:</p> <pre><code>@profile def hello(): print('Testing') hello() </code></pre> <...
0
2016-06-21T09:42:07Z
37,943,069
<p>I fixed this my cloning the code from <a href="https://github.com/rkern/line_profiler" rel="nofollow">https://github.com/rkern/line_profiler</a> and rebuilding and then calling the kernprof from the binary install location.</p>
0
2016-06-21T11:22:39Z
[ "python", "line-profiler" ]
PyQt transparent background image partially black
37,941,039
<p>Strangely, while I have successfully added a background containing transparency in a PyQt application, much of the image remains black.</p> <pre><code>from PyQt4.QtGui import * import sys class BackgroundIssue(QMainWindow): def __init__(self): super(BackgroundIssue, self).__init__() def resizeEven...
0
2016-06-21T09:49:39Z
37,956,012
<p>I've finally resolved this issue: the answer actually lies in overlaying. By setting <code>QtGui.Qt.WA_TranslucentBackground</code> to True and then setting the background in a widget contained within, the main window draws the desktop background and then the transparent image within the widget draws from the parent...
0
2016-06-21T23:08:35Z
[ "python", "qt", "pyqt" ]
How to separate the dart board from the background with OpenCV?
37,941,304
<p>I use python and openCV. I would like to separate the dart board from the background. I tried it with findContours and Canny edge detection but I couldn't make it.</p> <p>Example image:</p> <p><a href="http://i.stack.imgur.com/MVwYt.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/MVwYt.jpg" alt="enter image...
1
2016-06-21T10:00:59Z
37,942,163
<p>You can use <code>grab-cut</code> algorithm -</p> <p>What you have to do is to specify the area of the image which'll act as a foreground as a rectangle. The algorithm will take a lil bit of time, and will throw out your required image... Code here requires a lil bit of tweaking though.</p> <pre><code>import numpy...
0
2016-06-21T10:38:49Z
[ "python", "opencv", "image-segmentation" ]
flatten arrays in a list in python
37,941,462
<p>I have multiple numpy masked arrays <code>arr0, arr1, ..., arrn</code>. </p> <p>I put them in a list <code>arrs = [arr0, ..., arrn]</code>.</p> <p>I want to flatten these arrays et put a mask on them. I did something like:</p> <pre><code>for arr in arrs: arr = np.ravel(arr) arr[mask] = ma.masked </code></...
-1
2016-06-21T10:07:00Z
37,949,501
<pre><code>In [1032]: arr0 = np.ma.masked_array(data=[[1,2],[3,4]], mask=False) In [1033]: arr1 = np.ma.masked_array(data=[[5,6],[7,8]], mask=False) </code></pre> <p>This is the basic way of iterating over a list, applying some action to each element, and collecting the results in another list:</p> <pre><code>In ...
0
2016-06-21T16:10:45Z
[ "python", "arrays", "numpy", "view", "flatten" ]
Get all documents of a collection using Pymongo
37,941,610
<p>I want to return all document of my collection in mongodb</p> <pre><code>import pymongo import json from pymongo import MongoClient if __name__ == '__main__': client = MongoClient("localhost", 27017, maxPoolSize=50) db=client.mydatabase collection=db['mycollection'] cursor = collection.find({}) ...
2
2016-06-21T10:12:41Z
37,942,641
<p>Here is the sample code which works fine when you run from command prompt.</p> <pre><code>import pymongo import json from pymongo import MongoClient if __name__ == '__main__': client = MongoClient("localhost", 27017, maxPoolSize=50) db=client.localhost collection=db['chain'] cursor = collection.fin...
1
2016-06-21T11:00:39Z
[ "python", "mongodb", "pymongo" ]
Unable to crop away transparency, Neither PIL getbbox() nor Numpy are working
37,941,648
<p>I've very much a noob when it comes to image processing :( I have a bunch of PNG files (300 of them) that have large areas of transparency that I wish to crop. I want to automate the process obviously, hence why i tried using python and PIL. </p> <p>Now I have a look at the following link, <a href="http://stackove...
0
2016-06-21T10:15:00Z
37,942,933
<p>The issue you're having is that your images contain transparent white pixels, and your code is only going to crop pixels that are both transparent <em>and</em> black. The RGBA values for most of the pixels in your example image are <code>(255, 255, 255, 0)</code>. </p> <p>In <code>autocrop_image2</code>, you're tak...
1
2016-06-21T11:16:20Z
[ "python", "image", "numpy", "python-imaging-library" ]
Pandas: solve a crosstab issue
37,941,670
<p>I have a situation where a user belongs to multiple categories:</p> <pre><code>UserID Category 1 A 1 B 2 A 3 A 4 C 2 C 4 A A = 1,2,3,4 B = 1 C = 2,4 </code></pre> <p>I want the crosstab which shows data like this using pandas:</p> <pre><code> A B C A...
3
2016-06-21T10:15:54Z
37,942,081
<p>You can first create <code>DataFrame</code> from lists <code>a</code>, <code>b</code>, <code>c</code>. Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge...
2
2016-06-21T10:34:52Z
[ "python", "pandas", "dataframe", "group-by", "pivot" ]
Python hacking around read only property
37,941,718
<p>I am using some third party code that has some read only properties. I obviously want to alter them regardless.</p> <p>I tried using <code>del</code> but I keep getting: <code>AttributeError: can't delete attribute</code></p> <p>Here is my code:</p> <pre><code>for page in suggested_pages: url = page.url + '?s...
-1
2016-06-21T10:17:43Z
37,942,118
<p>In Python, read only properties are generally implemented through the <code>property</code> function.</p> <p>Example:</p> <pre><code>class A(object): def __init__(self, val): self._val = val @property def val(self): return self._val </code></pre> <p>That means that the read only proper...
0
2016-06-21T10:36:33Z
[ "python" ]
How to Interpret roc_curve(Test,Predictions) in scikit-learn
37,941,753
<p>I am working with scikit-learn for classification problem to predict Win or Loss of an opportunity.<br> I used the piece of code:</p> <pre><code>fpr, tpr, thresholds =roc_curve(yTest,predictions) </code></pre> <p>And the result is:</p> <pre><code> (array([ 0. , 0.2628946, 1. ]), array([ 0. ...
1
2016-06-21T10:19:20Z
38,015,850
<p>Thresholds are not confined to [0;1].</p> <p>Only TPR and FPR are rates, i.e. 0 to 1.</p> <p>If you see the <strong>documentation</strong>, it will tell you how it arrived at the value 2:</p> <blockquote> <p>Decreasing thresholds on the decision function used to compute fpr and tpr. <code>thresholds[0]</code> r...
0
2016-06-24T14:30:05Z
[ "python", "machine-learning", "scikit-learn", "data-mining" ]
How to add tag and region name while printing the result
37,941,774
<p>This is basically a effort to learn mapping for dictionary, basically i have a function which prints the change in a port , the code is as follows :</p> <pre><code> def comp_ports(self,filename,mapping): try: #print "HEYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY" f = open(filename) se...
0
2016-06-21T10:20:22Z
37,942,232
<p>Since the IP is your key in the dictionaries <code>old_port_dict</code>, <code>new_port_dict</code> and <code>mapping</code> and in <code>mapping</code> each IP maps to a list with tag at index 0 and region at index 1, the way to access those will be. </p> <pre><code>for key in diff_key: print "For %s with ta...
1
2016-06-21T10:41:42Z
[ "python" ]
Want to run a curl command either through python's subprocess or pycurl
37,941,853
<p>I have the following command which adds a user to the administrator group of a <code>gerrit</code> instance,</p> <pre><code> curl -X POST -H "Content-Type:application/json;charset=UTF-8" -u nidhi:pswd http://host_ip:port/a/groups/Administrators/members.add -d '{"members":["user@example.com"]}' </code></pre> <p>Whe...
0
2016-06-21T10:24:47Z
37,942,910
<ul> <li>you should try [<code>urllib2</code>] (<code>python2</code>) or <a href="https://docs.python.org/3/library/urllib.html" rel="nofollow"><code>urllib</code></a>(<code>python3</code>) to post json data ;</li> <li>for <code>subprocess.Popen</code> : <code>subprocess.Popen.communicate</code>(<a href="https://docs.p...
0
2016-06-21T11:14:58Z
[ "python", "curl", "subprocess", "pycurl" ]
Want to run a curl command either through python's subprocess or pycurl
37,941,853
<p>I have the following command which adds a user to the administrator group of a <code>gerrit</code> instance,</p> <pre><code> curl -X POST -H "Content-Type:application/json;charset=UTF-8" -u nidhi:pswd http://host_ip:port/a/groups/Administrators/members.add -d '{"members":["user@example.com"]}' </code></pre> <p>Whe...
0
2016-06-21T10:24:47Z
37,943,126
<h2>a) string escaping</h2> <p>For the subprocess/curl usage, you should be escaping your string tokens rather than manually adding extra <code>'</code>:</p> <p><code>...stuff'+"'"+'more.stuff...</code></p> <p>Escape using <code>\</code> before the character i.e. using</p> <p><code>"curl -X POST -H \"Content-Type:a...
1
2016-06-21T11:25:06Z
[ "python", "curl", "subprocess", "pycurl" ]
How to implement Poisson Regression?
37,941,881
<p>There are 2 types of Generalized Linear Models: <br>1. Log-Linear Regression, also known as Poisson Regression <br>2. Logistic Regression</p> <p>How to implement the Poisson Regression in Python for Price Elasticity prediction?</p>
0
2016-06-21T10:26:01Z
37,942,077
<p>Have a look at the <a href="https://pypi.python.org/pypi/statsmodels" rel="nofollow">statmodels</a> package in python.</p> <p>Here is an <a href="http://nbviewer.jupyter.org/urls/umich.box.com/shared/static/ir0bnkup9rywmqd54zvm.ipynb" rel="nofollow">example</a></p> <p>A bit more of input to avoid the <strong><em>l...
1
2016-06-21T10:34:42Z
[ "python", "statistics", "regression" ]
Website scraping script works in Linux but not in Windows 7?
37,941,982
<p>I have written a script that scrapes a URL. It works fine on Linux OS. But i am getting http 503 error when running on Windows 7. The URL has some issue. I am using python 2.7.11 . Please help. Below is the script:</p> <pre><code>import sys # Used to add the BeautifulSoup folder the import path import urllib2 # Us...
1
2016-06-21T10:30:20Z
37,942,204
<p>Apparently with Python 2.7.2 on Windows, any time you send a custom User-agent header, urllib2 doesn't send that header. (source: <a href="http://stackoverflow.com/a/8994498/6479294">http://stackoverflow.com/a/8994498/6479294</a>).</p> <p>So you might want to consider using requests instead of urllib2 in Windows:</...
0
2016-06-21T10:40:39Z
[ "python", "web", "screen-scraping" ]
How to write a proper unit test for file transformation
37,941,986
<p>I'm not very familiar with unit testing, I just start with learning how to do it. Maybe I haven't really understood the principles of unit testing and TDD and that's the reason why I'm feeling stuck.</p> <p>The code to test looks like this:</p> <pre><code>class DevelopingMyClass: def __init__(self): se...
0
2016-06-21T10:30:40Z
37,943,122
<p>One of the reasons why unit tests help during development is that they reveal if your interfaces are designed correctly. Think about unit test as about a program of someone else who wants to use the functionality designed by you.</p> <p>In your case, I can see the problem in using the <code>print</code> inside the ...
0
2016-06-21T11:25:00Z
[ "python", "unit-testing", "python-3.x", "mocking" ]
returncode of Popen object is None after the process is terminated
37,942,022
<p>I'm running a process with the use of <code>Popen</code>. I need to wait for the process to terminate. I'm checking that the process have terminated through the <code>returncode</code>. When <code>returncode</code> is different from <code>None</code> the process must have terminated. The problem is that when <code>p...
0
2016-06-21T10:32:29Z
37,946,438
<p>I'm not sure why it did not work, but I think it has something to do with not closing the streams. The following code works:</p> <pre><code>def run(command, print_output=True): from subprocess import Popen, PIPE, STDOUT from io import StringIO popen = Popen(command, stdout=PIPE, stderr=STDOUT, universa...
0
2016-06-21T13:55:35Z
[ "python", "subprocess" ]
Replace value in array with condition
37,942,039
<p>I have this simplified program to replace values in array which fulfill the conditions:</p> <pre><code>formula1=2*2 formula2=5*2 formula3=4*4 array = np.random.rand(2,4,10) for n,i in enumerate(array): if i&gt;0.5: #find value in array with this condition formula = formula1 array[n] = array[n]*...
1
2016-06-21T10:33:24Z
37,942,229
<p>To enumerate an array, you can use <code>np.ndenumerate</code> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html" rel="nofollow">documentation here</a>):</p> <pre><code>for n, i in np.ndenumerate(array): ... </code></pre>
2
2016-06-21T10:41:33Z
[ "python", "arrays", "if-statement", "numpy" ]