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
Receiving AssertionError using Flask sqlalchemy and restful
39,845,187
<p>I have been stumped and can't seem to figure out why I am receiving an AssertionError. I am currently working on a rest api using the flask_restful lib. I am querying by:</p> <pre><code>@staticmethod def find_by_id(id, user_id): f = File.query.filter_by(id=id).first() #Error is happening here if f is not ...
0
2016-10-04T06:04:11Z
39,866,856
<p>Although I couldn't figure out why the error occurs, I know how as well as how to prevent it. It is created because the query doesn't pull the live data right after the commit. The way to prevent it is by using <code>db.session.query()</code>. So in my example I would change:</p> <p><code>f = File.query.filter_b...
0
2016-10-05T06:29:40Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy", "flask-restful" ]
sorting json file using python having value as string
39,845,303
<p>i have json file:</p> <pre><code>ll = {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"James", "lastName":"Bond"}, {"firstName":"Celestial", "lastName":"Systems"}, {"firstName":"Peter", "lastName":"Jones"} ]} </code></pre> <p>i want ...
0
2016-10-04T06:13:27Z
39,845,360
<p>You need to give list of objects to <code>sorted</code> and <code>key</code> should be method to get value for single object.</p> <pre><code>In [1]: ll = {"employees": [{"name": "abc"}, {"name": "bcd"}]} In [2]: sorted(ll['employees'], key=lambda x: x['name']) Out[2]: [{'name': 'abc'}, {'name': 'bcd'}] </code></pr...
1
2016-10-04T06:18:32Z
[ "python", "json" ]
sorting json file using python having value as string
39,845,303
<p>i have json file:</p> <pre><code>ll = {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"James", "lastName":"Bond"}, {"firstName":"Celestial", "lastName":"Systems"}, {"firstName":"Peter", "lastName":"Jones"} ]} </code></pre> <p>i want ...
0
2016-10-04T06:13:27Z
39,845,950
<p>You can sort the <code>ll["employees"]</code> list in-place using the <code>list.sort</code> method. And while you can roll your own key function using <code>lambda</code> it's cleaner and more efficient to use <code>operator.itemgetter</code>.</p> <p>In this code, my key function creates a tuple of the <code>last...
1
2016-10-04T06:54:49Z
[ "python", "json" ]
How to use python to fill in dates and values so that every day has the same number of entries?
39,845,417
<p>I have a data set that looks like the table below. Every day has time stamps with 15 minutes interval, so there should be 15*24 = 96 entries per day. It is important that each day has the same number of values, because the np.corrceof() function I will use later to find the correlation of each day requires this. </p...
0
2016-10-04T06:22:29Z
39,847,337
<p>Here an example: </p> <pre><code>import pandas as pd index = pd.date_range('5/1/2015', periods=12, freq='15T') series = pd.Series(range(12), index=index) series = series.drop(series[2:5].index) print(series) print(series.resample('15T').pad()) print(series.resample('15T').bfill()) print(series.resample('15T')...
1
2016-10-04T08:12:44Z
[ "python" ]
pgadmin4 - New install not working
39,845,604
<p>I downloaded the <code>postgresql-9.6.0-1-linux-x64.run</code> package and ran through the installer on <strong>ubuntu 16.04</strong>. <strong>Postgres</strong> is working fine. I am trying to use the <strong>pgadmin4</strong> package that was included with this installer. I created a site in Apache per the instruct...
0
2016-10-04T06:34:18Z
39,848,018
<p>This error message shows that your environment is missing a package called <code>flask_babel</code>. To install it, switch to the virtualenv your webserver uses and install it with this command:</p> <pre><code>pip install flask_babel </code></pre> <p>If you are not using any virtual environment for your python scr...
0
2016-10-04T08:52:21Z
[ "python", "postgresql", "pgadmin-4" ]
pgadmin4 - New install not working
39,845,604
<p>I downloaded the <code>postgresql-9.6.0-1-linux-x64.run</code> package and ran through the installer on <strong>ubuntu 16.04</strong>. <strong>Postgres</strong> is working fine. I am trying to use the <strong>pgadmin4</strong> package that was included with this installer. I created a site in Apache per the instruct...
0
2016-10-04T06:34:18Z
39,871,086
<p>If you are using virtualenv to run pgAdmin4 then you need to activate it first, Refer Apache mine wsgi file.<a href="http://i.stack.imgur.com/8HbKw.png" rel="nofollow"><img src="http://i.stack.imgur.com/8HbKw.png" alt="enter image description here"></a></p>
0
2016-10-05T10:05:48Z
[ "python", "postgresql", "pgadmin-4" ]
The 'pip==7.1.0' distribution was not found and is required by the application
39,845,636
<p>I have the latest version of pip 8.1.1 on my ubuntu 16. But I am not able to install any modules via pip as I get this error all the time.</p> <pre><code>File "/usr/local/bin/pip", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/lib/python3/dist-packages/pkg_resources/__init__....
1
2016-10-04T06:36:03Z
39,953,036
<p>Im repair this with</p> <blockquote> <p>easy_install pip</p> </blockquote>
1
2016-10-10T07:17:41Z
[ "python", "python-2.7", "ubuntu", "pip" ]
Generating shell commands from functions
39,845,724
<p>I wrote a library for manipulating specific files. That library comprises many functions that would be useful to use as command line scripts and piping results.</p> <p>In my library I have a few functions:</p> <pre><code>def do_this(p1, p2=[]): return "something" def do_that(p1, p2, p3={}): return "else" </co...
1
2016-10-04T06:40:37Z
39,847,102
<p>As you use <code>cat</code> in you example, I assume that you use a Linux or other Unix-like system. A common way would be to have several links to your python script, one for each function. Then in the script, you parse the arguments once, and depending on the value of <code>sys.argv[0]</code> call the proper funct...
0
2016-10-04T07:59:05Z
[ "python", "function", "parsing", "command-line" ]
Working on dates with mm-dd-YY & YY-mm-dd format in pandas
39,845,833
<p>I am trying to do a simple test on pandas capabilities to handle dates &amp; format. For that i have created a dataframe with values like below. :</p> <pre><code>df = pd.DataFrame({'date1' : ['10-11-11','12-11-12','10-10-10','12-11-11', '12-12-12','11-12-11','11-11-11']}) </code></pre> <p>Her...
1
2016-10-04T06:48:06Z
39,845,879
<p><code>%Y</code> in the format specifier takes the 4-digit year (i.e. 2016). <code>%y</code> takes the 2-digit year (i.e. 16, meaning 2016). Change the <code>%Y</code> to <code>%y</code> and it should work. </p> <p>Also the dashes in your format specifier are not present. You need to change your format to <code>%y-%...
1
2016-10-04T06:51:20Z
[ "python", "date", "datetime" ]
Sum of difference of squares between each combination of rows of 17,000 by 300 matrix
39,845,960
<p>Ok, so I have a matrix with 17000 rows (examples) and 300 columns (features). I want to compute basically the euclidian distance between each possible combination of rows, so the sum of the squared differences for each possible pair of rows. Obviously it's a lot and iPython, while not completely crashing my laptop, ...
3
2016-10-04T06:55:20Z
39,846,562
<p>You could always divide your computation time by 2, noticing that d(i, i) = 0 and d(i, j) = d(j, i).</p> <p>But have you had a look at <code>sklearn.metrics.pairwise.pairwise_distances()</code> (in v 0.18, see <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html...
2
2016-10-04T07:29:11Z
[ "python", "numpy", "optimization", "matrix" ]
Sum of difference of squares between each combination of rows of 17,000 by 300 matrix
39,845,960
<p>Ok, so I have a matrix with 17000 rows (examples) and 300 columns (features). I want to compute basically the euclidian distance between each possible combination of rows, so the sum of the squared differences for each possible pair of rows. Obviously it's a lot and iPython, while not completely crashing my laptop, ...
3
2016-10-04T06:55:20Z
39,846,761
<p>Forget about numpy, which is only a convenience solution for self expanding arrays. Use python lists instead which have a very fast indexing access and are about 15 times faster. Use it like this:</p> <pre><code>features = list(dataframe) distances = [[None]*17000]*17000 def sum_diff(): for i in range(17000): ...
-3
2016-10-04T07:40:14Z
[ "python", "numpy", "optimization", "matrix" ]
Sum of difference of squares between each combination of rows of 17,000 by 300 matrix
39,845,960
<p>Ok, so I have a matrix with 17000 rows (examples) and 300 columns (features). I want to compute basically the euclidian distance between each possible combination of rows, so the sum of the squared differences for each possible pair of rows. Obviously it's a lot and iPython, while not completely crashing my laptop, ...
3
2016-10-04T06:55:20Z
39,847,037
<p>The big thing with numpy is to avoid using loops and to let it do its magic with the vectorised operations, so there are a few basic improvements that will save you some computation time: </p> <pre><code>import numpy as np import timeit #I reduced the problem size to 1000*300 to keep the timing in reasonable range...
1
2016-10-04T07:55:34Z
[ "python", "numpy", "optimization", "matrix" ]
How to do POST using requests module with Flask server?
39,845,970
<p>I am having trouble uploading a file to my Flask server using the Requests module for Python. </p> <pre><code>import os from flask import Flask, request, redirect, url_for from werkzeug import secure_filename UPLOAD_FOLDER = '/Upload/' app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.rout...
0
2016-10-04T06:56:06Z
39,846,239
<p>You upload the file as the <code>random.txt</code> field:</p> <pre><code>files={'random.txt': open('random.txt', 'rb')} # ^^^^^^^^^^^^ this is the field name </code></pre> <p>but look for a field named <code>file</code> instead:</p> <pre><code>file = request.files['file'] # ^^^^^^ the fiel...
0
2016-10-04T07:11:08Z
[ "python", "post", "flask", "python-requests" ]
How to do POST using requests module with Flask server?
39,845,970
<p>I am having trouble uploading a file to my Flask server using the Requests module for Python. </p> <pre><code>import os from flask import Flask, request, redirect, url_for from werkzeug import secure_filename UPLOAD_FOLDER = '/Upload/' app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.rout...
0
2016-10-04T06:56:06Z
39,846,300
<p>Because you have <code>&lt;input&gt;</code> with <code>name=file</code> so you need</p> <pre><code> files={'file': ('random.txt', open('random.txt', 'rb'))} </code></pre> <p>Examples in requests doc: <a href="http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow">P...
0
2016-10-04T07:14:17Z
[ "python", "post", "flask", "python-requests" ]
customizing django admin ChangeForm template / adding custom content
39,845,982
<p>I'm able to insert (lame) static text onto the change form admin page, but I'd really like it to use the context of the current object being edited! </p> <p>For instance, I want to format on the MyObject change form a URL to include the ID from a ForeignKey connected object (<code>obj</code>) as a link.</p> <p>My ...
1
2016-10-04T06:56:41Z
39,848,376
<p>Add your extra context in <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.change_view" rel="nofollow">change_view</a></p> <pre><code>class MyObjectAdmin(admin.ModelAdmin): # A template for a very customized change view: change_form_template = 'admin/my_change_form....
3
2016-10-04T09:10:35Z
[ "python", "django", "django-admin" ]
Check for duplicates in a randomly generated list and replace them
39,846,207
<p>I am making a minesweeper game with randomly generated bombs. Yet at times I have found that there are duplicates in my list of coordinates of bombs. How do I check for duplicates in a list and replace them with other randomised coordinates.</p> <pre><code>from random import randint def create_bombpos(): globa...
2
2016-10-04T07:09:06Z
39,846,321
<pre><code>from random import randint def create_bombpos(): global BOMBS, NUM_BOMBS, GRID_TILES i = 0 while i&lt;NUM_BOMBS: x = randint(1, GRID_TILES) y = randint(1, GRID_TILES) if (x,y) not in BOMBS BOMBS.append((x, y)) i = i + 1 print(BOMBS) </code></pre> <...
3
2016-10-04T07:15:44Z
[ "python", "python-3.x", "random" ]
Check for duplicates in a randomly generated list and replace them
39,846,207
<p>I am making a minesweeper game with randomly generated bombs. Yet at times I have found that there are duplicates in my list of coordinates of bombs. How do I check for duplicates in a list and replace them with other randomised coordinates.</p> <pre><code>from random import randint def create_bombpos(): globa...
2
2016-10-04T07:09:06Z
39,846,391
<p>Searching each time through your whole BOMBS list would cost you <code>O(n)</code> (linear time). Why don't you use a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">set</a> instead? a Set guarantees that you ll end up with distinct (in terms of hashing) elements.</p> <pre><code>from random imp...
4
2016-10-04T07:19:28Z
[ "python", "python-3.x", "random" ]
Check for duplicates in a randomly generated list and replace them
39,846,207
<p>I am making a minesweeper game with randomly generated bombs. Yet at times I have found that there are duplicates in my list of coordinates of bombs. How do I check for duplicates in a list and replace them with other randomised coordinates.</p> <pre><code>from random import randint def create_bombpos(): globa...
2
2016-10-04T07:09:06Z
39,846,480
<p>Use a python set for this, it will automatically check for duplicates and simply ignore every entry that already is in the list. I also think the runtime is much better than using a list and checking for duplicates manually.</p> <p>Link: <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">https://d...
0
2016-10-04T07:24:41Z
[ "python", "python-3.x", "random" ]
Check for duplicates in a randomly generated list and replace them
39,846,207
<p>I am making a minesweeper game with randomly generated bombs. Yet at times I have found that there are duplicates in my list of coordinates of bombs. How do I check for duplicates in a list and replace them with other randomised coordinates.</p> <pre><code>from random import randint def create_bombpos(): globa...
2
2016-10-04T07:09:06Z
39,846,996
<p>You could also use random.sample to achieve this:</p> <pre><code>from random import sample GRID_TILES = 100 NUM_BOMBS = 5 indexes = sample(range(GRID_TILES * GRID_TILES), NUM_BOMBS) BOMBS = [(i // GRID_TILES, i % GRID_TILES) for i in indexes] </code></pre>
3
2016-10-04T07:53:24Z
[ "python", "python-3.x", "random" ]
library of react components in webpack bundle export to use in on runtime rendering
39,846,223
<p>I am upgrading a legacy web2py (python) application to use react components. I am using webpack to transpile the jsx files to minified js bundle. I want to be able to use:</p> <pre><code>ReactDOM.render( &lt;ComponentA arg1="hello" arg2="world" /&gt;, document.getElementById('react-container') ); </code></pre> ...
0
2016-10-04T07:09:55Z
39,864,896
<p>I solved it after I came across <a href="http://stackoverflow.com/a/32786185/3163075">this StackOverflow answer</a></p> <p>First make sure that your <code>main.jsx</code> file (which would import all the components) also exports them:</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; impo...
0
2016-10-05T03:19:30Z
[ "python", "reactjs", "ecmascript-6", "webpack", "web2py" ]
Binary to hex in Python, low-nibble first encoding
39,846,315
<p>I have a protocol that requires converting binary data to and from a hex-encoded string where the low-nibble (lower 4 bits of each byte) come first - so for example the Python string '\xab\xcd' would be encoded as 'badc'. This odd format comes from the PHP/Perl <code>pack</code> and <code>unpack</code> functions wit...
1
2016-10-04T07:15:03Z
39,848,471
<p>A more efficient way would be to precalculate a translation table and then simply apply it using <a href="https://docs.python.org/2/library/string.html#string.translate" rel="nofollow"><code>str.translate()</code></a></p> <pre><code>_translation = bytearray(((0x0f &amp; c) &lt;&lt; 4 | (0xf0 &amp; c) &gt;&gt; 4) ...
0
2016-10-04T09:15:11Z
[ "python", "encoding", "hex", "binary-data", "packing" ]
Automated transfer of results of computation on ec2 instance to local client using Python
39,846,434
<p>I'm computing smaller things on a AWS EC2 gpu-instance. Currently I have to find the right parameters, so there are shorter computations I have to analyze and then adjust some parameter to compute again.</p> <p>For the analysis, I depend on things, which aren't available on my EC2 instance. So I'm looking for an c...
0
2016-10-04T07:21:51Z
39,846,508
<p>If you have <code>scp</code> access to your systems then the <code>paramiko</code> library can perform the transfers for you, as detailed in <a href="http://stackoverflow.com/questions/250283/how-to-scp-in-python">this answer</a>. There's an <a href="https://pypi.python.org/pypi/scp" rel="nofollow"><code>scp</code> ...
1
2016-10-04T07:26:28Z
[ "python", "amazon-web-services", "amazon-ec2", "file-transfer" ]
Automated transfer of results of computation on ec2 instance to local client using Python
39,846,434
<p>I'm computing smaller things on a AWS EC2 gpu-instance. Currently I have to find the right parameters, so there are shorter computations I have to analyze and then adjust some parameter to compute again.</p> <p>For the analysis, I depend on things, which aren't available on my EC2 instance. So I'm looking for an c...
0
2016-10-04T07:21:51Z
39,846,575
<p>You can use tar for your files.</p> <pre><code>tar cvzf - -T list_of_filenames | ssh -i ec2key.pem ec2-user@hostname tar xzf - </code></pre> <p>You can also use recursive <code>scp</code>.</p>
0
2016-10-04T07:29:44Z
[ "python", "amazon-web-services", "amazon-ec2", "file-transfer" ]
seconds since midnight to datetime (python)
39,846,488
<p>I have a timezone aware datetime date object:</p> <pre><code>Timestamp('2004-03-29 00:00:00-0456', tz='America/New_York') </code></pre> <p>and a number of mili seconds since midnight (midnight in the local timezone):</p> <p>34188542</p> <p>How to combine them to get a valid datetime?</p>
0
2016-10-04T07:25:15Z
39,846,623
<p>Create a <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow"><code>timedelta</code></a> object and add it to you time like this:</p> <pre><code>td = datetime.timedelta(milliseconds=34188542) date_object = datetime.datetime.now() + td # change to your datetime object, I just u...
4
2016-10-04T07:32:20Z
[ "python", "datetime" ]
seconds since midnight to datetime (python)
39,846,488
<p>I have a timezone aware datetime date object:</p> <pre><code>Timestamp('2004-03-29 00:00:00-0456', tz='America/New_York') </code></pre> <p>and a number of mili seconds since midnight (midnight in the local timezone):</p> <p>34188542</p> <p>How to combine them to get a valid datetime?</p>
0
2016-10-04T07:25:15Z
39,846,655
<p>Assuming the datetime object is <code>ts</code>, and by "combine them", you mean "add them":</p> <pre><code>ms = 34188545 new_datetime = ts + datetime.timedelta(milliseconds = ms) </code></pre>
1
2016-10-04T07:34:00Z
[ "python", "datetime" ]
what is foo.__add__ in python means?
39,846,532
<p>i ususally see when we create class in python we use <code>__init__(self)</code> , I just come across this code :</p> <pre><code>&gt;&gt;&gt; foo = 10 &gt;&gt;&gt; print(foo.__add__) &lt;method-wrapper '__add__' of int object at 0x8502c0&gt; </code></pre> <p>so i have two doubts:</p> <p>can someone explain in d...
0
2016-10-04T07:27:43Z
39,847,355
<p>When Python tries to evaluate <code>x + y</code>, it first attempts to call <code>x.__add__(y)</code>. If this fails then it falls back to <code>y.__radd__(x)</code>. In short, <code>__add__()</code> defines the behavior of <code>+</code> operator.</p> <p>For example, <code>1 + 2</code> results in 3, whereas <code>...
1
2016-10-04T08:13:51Z
[ "python", "python-2.7", "python-3.x" ]
Working with GUIs and text files - how do I 'synchronize' them?
39,846,573
<p>I am working on a larger programming project, and since I am a beginner it is not that complex. I will try to keep it straight forward: I want to create a GUI program that reads from a text file with "elements of notes", i.e. as a calendar.</p> <p>The interface should have "text entry box", where you can submit new...
0
2016-10-04T07:29:38Z
39,847,576
<p>You can use it inside <code>Application</code> class: </p> <pre><code>from Tkinter import * class Application(Frame): """ GUI application that creates diary. """ def __init__(self): """ Initialize Frame. """ Frame.__init__(self) self.note_list = [] ...
0
2016-10-04T08:28:39Z
[ "python", "oop", "user-interface", "tkinter", "text-files" ]
Python non-numpy matrixes issue
39,846,646
<p>I have the following issue:</p> <p>I have a list of lists with the following declaration:</p> <pre><code>As = [[0]*3]*3 </code></pre> <p>I then try to change the values of this "matrix" with this:</p> <pre><code>for i in range(3): for j in range(3): As[i][j] = calculate(A, i, j)*((-1)**(i+j)) </code>...
1
2016-10-04T07:33:41Z
39,846,702
<p>When you build a list like this <code>[[0]*3]*3</code> you are creating 3 references to the same list, use a list comprehension instead:</p> <pre><code>[[0 for _ in xrange(3)] for _ in xrange(3)] </code></pre> <p>See how in the comprehension here just the <code>[0][0]</code> is modified:</p> <pre><code>&gt;&gt;&g...
2
2016-10-04T07:36:36Z
[ "python", "list", "matrix" ]
Python non-numpy matrixes issue
39,846,646
<p>I have the following issue:</p> <p>I have a list of lists with the following declaration:</p> <pre><code>As = [[0]*3]*3 </code></pre> <p>I then try to change the values of this "matrix" with this:</p> <pre><code>for i in range(3): for j in range(3): As[i][j] = calculate(A, i, j)*((-1)**(i+j)) </code>...
1
2016-10-04T07:33:41Z
39,846,813
<p>The problem is in your first line:</p> <pre><code>As = [[0]*3]*3 </code></pre> <p>This is equivalent to the following:</p> <pre><code>a = [0] * 3 As = [a] * 3 </code></pre> <p><code>As</code> therefore contains three references to the same list:</p> <pre><code>&gt;&gt;&gt; for a in As: ... print(id(a)) ... ...
1
2016-10-04T07:43:23Z
[ "python", "list", "matrix" ]
Trying to concatenate string with integer but unwanted values is getting added
39,846,653
<p>I have a Dataframe which has 2 columns, I am trying to create a new column <code>column3</code> with a logic of concatenating values of <code>column1</code> (String) and <code>column2</code> (int) with a separator ('_'). </p> <p>Below are the few initial values of the dataframe:</p> <pre><code> column1 column2...
0
2016-10-04T07:33:55Z
39,846,723
<p>you don't need to make it so complicated. dataframe support such operation:</p> <pre><code>df.column1 + "_" + df.column2.astype("str") </code></pre>
1
2016-10-04T07:37:54Z
[ "python", "dataframe" ]
Trying to concatenate string with integer but unwanted values is getting added
39,846,653
<p>I have a Dataframe which has 2 columns, I am trying to create a new column <code>column3</code> with a logic of concatenating values of <code>column1</code> (String) and <code>column2</code> (int) with a separator ('_'). </p> <p>Below are the few initial values of the dataframe:</p> <pre><code> column1 column2...
0
2016-10-04T07:33:55Z
39,846,886
<p>You want this:</p> <pre><code>def concat_cols(row): return "{}_{}".format(row['column1'], row['column2']) df['column3'] = df.apply(concat_cols, axis = 1) </code></pre> <p>The key aspect is <code>axis = 1</code>, which looks at the dataframe row-wise, rather than column-wise. In your code above, <code>df['colu...
0
2016-10-04T07:47:42Z
[ "python", "dataframe" ]
What exactly does iter_content() function do?
39,846,671
<p>just finished learning web scraping from automate the boring stuff book, but i'm still really confused about iter_content function? what does it actually do?</p> <p>try to download web page using normal: </p> <pre><code>note = open('download.txt', 'w') note.write(request) note.close() </code></pre> <p>but the re...
-2
2016-10-04T07:34:35Z
39,846,737
<p><strong><em>iter_content</em></strong>(<em>chunk_size=1, decode_unicode=False</em>)</p> <p>Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not n...
1
2016-10-04T07:38:54Z
[ "python", "python-3.x" ]
Google Foobar Challenge 3 - Find the Access Codes
39,846,735
<h1>Find the Access Codes</h1> <p>Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (lst[i], lst[j], lst[k]) where i &lt; j &lt; k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits wit...
3
2016-10-04T07:38:44Z
39,846,872
<p>Thing is: you let that library method <strong>combinations</strong> do all the "real" work for you. </p> <p>And of course: normally that is exactly the way to go. You do <strong>not</strong> want to re-invent the wheel when there is an existing library function that gives you what you need. Your current code is pre...
1
2016-10-04T07:46:49Z
[ "java", "python", "combinations" ]
Google Foobar Challenge 3 - Find the Access Codes
39,846,735
<h1>Find the Access Codes</h1> <p>Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (lst[i], lst[j], lst[k]) where i &lt; j &lt; k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits wit...
3
2016-10-04T07:38:44Z
39,847,350
<p>Here is a solution off the top of my head that has O(n^2) time and O(n) space complexity. I think there is a better solution (probably using dynamic programming), but this one beats generating all combinations.</p> <pre><code>public static int foobar( int[] arr) { int noOfCombinations = 0; int[] noOfDoubles...
1
2016-10-04T08:13:37Z
[ "java", "python", "combinations" ]
Google Foobar Challenge 3 - Find the Access Codes
39,846,735
<h1>Find the Access Codes</h1> <p>Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (lst[i], lst[j], lst[k]) where i &lt; j &lt; k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits wit...
3
2016-10-04T07:38:44Z
39,929,490
<p>I tried implementing this in python. It isn't quite fast enough to pass the test, but it runs 50x faster then uoyilmaz's solution ported to python. The code for that is below:</p> <pre><code>#!/usr/bin/env python2.7 from bisect import insort_left from itertools import combinations def answer_1(l): """My own ...
0
2016-10-08T06:38:45Z
[ "java", "python", "combinations" ]
seaborn violinplot out of valid range
39,846,760
<p>I am using seaborn to create violin plots. Right now I am creating violin plots out of proportion values (so all values are between 0 and 1), but the resulting violin plot is quite off. Its bottom ranges into negative values and its top ranges into values greater than 1. Below is an example which I ran to test it:<...
0
2016-10-04T07:40:11Z
39,858,667
<p>The link provided by mbatchkarov answers my question. Thanks!</p>
0
2016-10-04T17:46:16Z
[ "python", "plot", "seaborn", "violin-plot" ]
How to parse text from html file
39,846,780
<pre><code>import urllib2 import nltk from HTMLParser import HTMLParser from bs4 import BeautifulSoup l = """&lt;TR&gt;&lt;TD&gt;&lt;small style=font-family:courier&gt; &gt;M. tuberculosis H37Rv|Rv3676|crp&lt;br /&gt;VDEILARAGIFQGVEPSAIAALTKQLQPVDFPRGHTVFAEGEPGDRLYIIISGKVKIGRR&lt;br /&gt;APDGRENLLTIMGPSDMFGELSIFDPG...
1
2016-10-04T07:41:31Z
39,846,897
<p>I notice you import BeautifulSoup, so you can use BeautifulSoup to help you extract these information.</p> <pre><code>soup = BeautifulSoup(l,"html.parser") print soup.get_text() </code></pre> <p>I've tried and it worked, but the sentence in the last tag will also be extracted, you have to cut the result if needed....
1
2016-10-04T07:48:21Z
[ "python" ]
How to parse text from html file
39,846,780
<pre><code>import urllib2 import nltk from HTMLParser import HTMLParser from bs4 import BeautifulSoup l = """&lt;TR&gt;&lt;TD&gt;&lt;small style=font-family:courier&gt; &gt;M. tuberculosis H37Rv|Rv3676|crp&lt;br /&gt;VDEILARAGIFQGVEPSAIAALTKQLQPVDFPRGHTVFAEGEPGDRLYIIISGKVKIGRR&lt;br /&gt;APDGRENLLTIMGPSDMFGELSIFDPG...
1
2016-10-04T07:41:31Z
39,847,186
<pre><code>try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup html = BeautifulSoup(l) small = html.find_all('small') print (small.get_text()) </code></pre> <p>This gets the small tag and prints out all the text in it</p>
1
2016-10-04T08:04:12Z
[ "python" ]
How to parse text from html file
39,846,780
<pre><code>import urllib2 import nltk from HTMLParser import HTMLParser from bs4 import BeautifulSoup l = """&lt;TR&gt;&lt;TD&gt;&lt;small style=font-family:courier&gt; &gt;M. tuberculosis H37Rv|Rv3676|crp&lt;br /&gt;VDEILARAGIFQGVEPSAIAALTKQLQPVDFPRGHTVFAEGEPGDRLYIIISGKVKIGRR&lt;br /&gt;APDGRENLLTIMGPSDMFGELSIFDPG...
1
2016-10-04T07:41:31Z
39,849,162
<p>I have tried with BeautifulSoup which was not working for me because it was producing unformatted version so i have decide to write down code with my self and its working absolutely fine and producing what i want.</p> <pre><code>import urllib2 proxy = urllib2.ProxyHandler({'http': 'http://******************'}) o...
1
2016-10-04T09:48:23Z
[ "python" ]
Python: from vertical line user input to list
39,846,836
<p>I know how to change horizontal user input to became a list.</p> <pre><code>numbers = [int(n) for n in input().split()] </code></pre> <p>but not sure how to do if the user input is vertical(enter after input integer:224, 32, 5)...</p> <p>example input:</p> <blockquote> <p>224 32 5</p> </blockquote> <p>example...
1
2016-10-04T07:44:47Z
39,846,906
<pre><code>number_read = raw_input() number_list = [] while number_read != 'q': number_list.append(int(number_read)) number_read = raw_input() </code></pre> <p>So as soon as a user writes <code>q</code> and presses enter, you will be done collecting input</p>
2
2016-10-04T07:48:52Z
[ "python" ]
Python: from vertical line user input to list
39,846,836
<p>I know how to change horizontal user input to became a list.</p> <pre><code>numbers = [int(n) for n in input().split()] </code></pre> <p>but not sure how to do if the user input is vertical(enter after input integer:224, 32, 5)...</p> <p>example input:</p> <blockquote> <p>224 32 5</p> </blockquote> <p>example...
1
2016-10-04T07:44:47Z
39,850,683
<p>As @vlad-ardelean mentioned you can create a list and by means of "append" comand add its parameter as a single element to the list. However if your given input is going to be a Python list (or any other iterable such as a tuple) you can convert it to a string for display:</p> <pre><code>inputNumbers = input_list()...
1
2016-10-04T11:06:55Z
[ "python" ]
Invalid parameter estimator for estimator MLPClassifier
39,846,864
<p>When I tried to use GridSearchCV for MLPClassifier, I got this message: </p> <blockquote> <p>ValueError: Invalid parameter estimator for estimator <br> MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9, beta_2=0.999, early_stopping=False, epsilon=1e-08,<br> hidden_layer_sizes=(100...
0
2016-10-04T07:46:18Z
39,898,074
<p>You are doing a grid search on <code>paramgrid</code> which contains the parameter <code>estimator__alpha</code>.</p> <p>However <strong>MLPClassifier</strong> does not have this parameter. You should change your <code>paramgrid</code>.</p>
0
2016-10-06T14:01:25Z
[ "python" ]
How does this work: except IOError as e: print("No such file: {0.filename}".format(e))
39,846,889
<p>The code that uses the expression in question:</p> <pre><code>def read_file(self,file_name): try: with open(file_name,'r') as file: data=file.read() return data.split() except IOError as e: print("Could not read file:{0.filename}".format(e)) ...
0
2016-10-04T07:47:50Z
39,846,925
<p>This essentially means takes the positional argument at position <code>0</code> (in <code>format(e)</code>, <code>e</code> is the zero position arg) and grab the <code>filename</code> attribute defined on it:</p> <pre><code>print("No such file: {0.filename}".format(e)) </code></pre> <p>Is similar to:</p> <pre><c...
2
2016-10-04T07:49:49Z
[ "python", "python-3.x" ]
Convert date to ordinal python?
39,846,918
<p>I want to convert 2010-03-01 to 733832</p> <p>I just found this toordinal code</p> <pre><code>d=datetime.date(year=2010, month=3, day=1) d.toordinal() </code></pre> <p>from <a href="http://stackoverflow.com/questions/16542074/what-is-the-inverse-of-date-toordinal-in-python">this</a></p> <p>But i want something m...
0
2016-10-04T07:49:32Z
39,846,998
<p>You'll need to use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow"><code>strptime</code></a> on the date string, specifying the format, then you can call the <code>toordinal</code> method of the <code>date</code> object:</p> <pre><code>&gt;&gt;&gt; from datetime i...
3
2016-10-04T07:53:33Z
[ "python", "datetime" ]
Convert date to ordinal python?
39,846,918
<p>I want to convert 2010-03-01 to 733832</p> <p>I just found this toordinal code</p> <pre><code>d=datetime.date(year=2010, month=3, day=1) d.toordinal() </code></pre> <p>from <a href="http://stackoverflow.com/questions/16542074/what-is-the-inverse-of-date-toordinal-in-python">this</a></p> <p>But i want something m...
0
2016-10-04T07:49:32Z
39,847,003
<p>like this:</p> <pre><code>datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal() </code></pre>
2
2016-10-04T07:53:49Z
[ "python", "datetime" ]
Convert date to ordinal python?
39,846,918
<p>I want to convert 2010-03-01 to 733832</p> <p>I just found this toordinal code</p> <pre><code>d=datetime.date(year=2010, month=3, day=1) d.toordinal() </code></pre> <p>from <a href="http://stackoverflow.com/questions/16542074/what-is-the-inverse-of-date-toordinal-in-python">this</a></p> <p>But i want something m...
0
2016-10-04T07:49:32Z
39,847,069
<p>You need to firstly convert the time string to <code>datetime</code> object using <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow">strptime()</a>. Then call <code>.toordinal()</code> on the <code>datetime</code> object</p> <pre><code>&gt;&gt;&gt; from datetime impo...
1
2016-10-04T07:57:02Z
[ "python", "datetime" ]
python DataFrame comparison using == operator
39,846,946
<p>I have two python dataframes of same structure and same number of rows when I perform '==' operation on them they gives wrong answers</p> <p>df1:</p> <pre><code> 0 61561899 1 56598947 2 52231204 3 10069030 4 19900179 5 52892001 6 50015534 7...
0
2016-10-04T07:51:00Z
39,846,979
<p>Try cast to <code>str</code> and then compare:</p> <pre><code>df1.spn.astype(str) == df2.spn.astype(str) </code></pre> <p>Or maybe need compare columns only:</p> <pre><code>df1.spn == df2.spn </code></pre>
0
2016-10-04T07:52:34Z
[ "python", "dataframe", "comparison" ]
urllib.error.HTTPError: HTTP Error 400: Bad Request (bottlenose)
39,847,007
<p>After installing bottlenose and getting my API keys and associate tags I tried following the instructions in this guide: <a href="https://github.com/lionheart/bottlenose" rel="nofollow">https://github.com/lionheart/bottlenose</a></p> <p>(I have removed my api keys)</p> <p>This is the error I am getting:</p> <pre>...
0
2016-10-04T07:53:59Z
39,849,015
<p>You have to provide the value for keys</p> <ul> <li><strong>AWS_ACCESS_KEY_ID</strong></li> <li><strong>AWS_SECRET_ACCESS_KEY</strong></li> <li><strong>AWS_ASSOCIATE_TAG</strong></li> </ul> <p>In order to get the keys you have to register on AWS</p>
0
2016-10-04T09:41:11Z
[ "python", "api", "amazon-web-services" ]
Pythonic superclass with classmethod constructor: override, inherit, ...?
39,847,154
<p>What is the neatest and most pythonic way to solve this:</p> <p>Given a class with a <code>@classmethod</code> constructor such as in code sample 1. But now subclass it with two classes which both require a totally different additional argument, such as in code sample 2. Should this be solved by using <code>*args, ...
-1
2016-10-04T08:02:15Z
39,847,610
<p>I think you could avoid defining a new <em>subclass</em> (and <em>subclassing</em> altogether) each time you have a new attribute for the <code>Car</code> class by setting up the attributes of each instance from the <code>kwargs</code> passed to the <code>__init__</code> method of the class:</p> <pre><code>class Ca...
1
2016-10-04T08:30:50Z
[ "python", "inheritance", "class-method" ]
How could I call a User defined function from spark sql queries in pyspark?
39,847,547
<p>I need to call a function from my spark sql queries. I have tried udf but I don't know how to manipulate it. Here is the scenario:</p> <pre><code># my python function example def sum(effdate, trandate): sum=effdate+trandate return sum </code></pre> <p>and my spark sql query is like:</p> <pre><code>spark.sql(...
0
2016-10-04T08:26:36Z
39,848,223
<p>Check this</p> <pre><code> &gt;&gt;&gt; from pyspark.sql.types import IntegerType &gt;&gt;&gt; sqlContext.udf.register("stringLengthInt", lambda x: len(x), IntegerType()) &gt;&gt;&gt; sqlContext.sql("SELECT stringLengthInt('test')").collect() [Row(_c0=4)] </code></pre>
0
2016-10-04T09:01:41Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Is it possible to use cassandra cqlsh copy command inside the python programme?
39,847,605
<p>Is it possible to execute Cassandra CQLSH copy command through a Python program. If yes, how?</p> <p>Thanks in Advance.</p>
-3
2016-10-04T08:30:36Z
39,866,720
<p>Yes, it is possible. I'm providing you a sample code about how we use cqlsh inside python. I guess, you'll can get some help from it but not interested to write the entire copy script for you.</p> <pre><code> import subprocess host = "xxx.xxx.xxx.xxx" user = "cassandra" password = "cassandra" process = subpro...
0
2016-10-05T06:20:37Z
[ "python", "cassandra" ]
Access to django template variable from js block
39,847,663
<p>I have js code in my django template but project use Grunt js, so code must be in js block {% block extrajs %}.</p> <p>This is my code in template:</p> <pre><code>&lt;script type="text/javascript"&gt; var pub_date = {{ obj.pub_date|date:'YmdHi' }}; var hour = moment().startOf('hour').fromNow(); var tim...
0
2016-10-04T08:33:44Z
39,848,265
<p>In order to this work you have to have your js code inside your html template. Also when trying to do this add <code>|safe</code> behind your statement. For example :</p> <pre><code>$(document).ready(function(){ var pub_date = '{{ obj.pub_date|date:'YmdHi'|safe }}'; alert(pub_date); }); </code></pre>
0
2016-10-04T09:04:22Z
[ "javascript", "python", "django", "gruntjs", "django-templates" ]
Python Regular Expression for a paragraph
39,847,681
<p>Hi i have this as my testing string:</p> <pre><code>&lt;image&gt; &lt;title&gt;CNN.com - Technology&lt;/title&gt; &lt;link&gt;http://www.cnn.com/TECH/index.html?eref=rss_tech&lt;/link&gt; </code></pre> <p>and i want to select 'Technology' from it using a python regular expression, however i need it specific so tha...
2
2016-10-04T08:34:48Z
39,848,100
<p>How about something like this :</p> <pre><code>(&lt;image&gt;\n&lt;title&gt;CNN.com - )(.*?)(&lt;\/title&gt;\n.*) </code></pre> <p>Group number 2 would be <code>Technology</code>.</p>
0
2016-10-04T08:56:05Z
[ "python", "regex" ]
Python Regular Expression for a paragraph
39,847,681
<p>Hi i have this as my testing string:</p> <pre><code>&lt;image&gt; &lt;title&gt;CNN.com - Technology&lt;/title&gt; &lt;link&gt;http://www.cnn.com/TECH/index.html?eref=rss_tech&lt;/link&gt; </code></pre> <p>and i want to select 'Technology' from it using a python regular expression, however i need it specific so tha...
2
2016-10-04T08:34:48Z
39,848,174
<p>Your regexp is not bad but you need to escape the slash in <code>&lt;/title&gt;</code> with a backslash and it does not match because of the newlines in your string.</p> <p>Newlines are whitespaces (like space, tabulation... \s is equivalent to [ \t\n\r\f\v] when the UNICODE flag is not set), so you can use \s to m...
1
2016-10-04T08:59:13Z
[ "python", "regex" ]
Python Regular Expression for a paragraph
39,847,681
<p>Hi i have this as my testing string:</p> <pre><code>&lt;image&gt; &lt;title&gt;CNN.com - Technology&lt;/title&gt; &lt;link&gt;http://www.cnn.com/TECH/index.html?eref=rss_tech&lt;/link&gt; </code></pre> <p>and i want to select 'Technology' from it using a python regular expression, however i need it specific so tha...
2
2016-10-04T08:34:48Z
39,848,201
<p>If you use the 'single line' option for regex, you name newlines with <code>.</code>. So, you can do:</p> <pre><code>&lt;image&gt;.&lt;title[^&gt;]*&gt;CNN.com - (.*?)&lt;/title&gt;.&lt;link&gt; </code></pre>
0
2016-10-04T09:00:28Z
[ "python", "regex" ]
How to select all the rows with the same name and not only the first one?
39,847,727
<p>This is the xls file : </p> <pre><code>moto 5 2 45 moto 2 4 43 coche 8 54 12 coche 43 21 6 coche 22 14 18 </code></pre> <p>And this is the code working with pyexcel library:</p> <pre><code>import pyexcel as pe data = pe.get_sheet(file_name="vehiculo.xls") sheet = pe.Sheet(data, name_...
0
2016-10-04T08:37:16Z
39,848,048
<p>Just iterate over the data:</p> <pre><code>import pyexcel from collections import defaultdict results = defaultdict(list) data = pe.get_sheet(file_name="vehiculo.xls") for row in data.rows(): results[row[0]] += row[1:] </code></pre> <p>You'll get the following:</p> <pre><code>&gt;&gt;&gt; results['moto'] [5L,...
0
2016-10-04T08:53:48Z
[ "python", "python-2.7", "pyexcel" ]
Can I get PyCharm to suppress a particular warning on a single line?
39,847,884
<p>PyCharm provides some helpful warnings on code style, conventions and logical gotchas. It also provides a notification if I try to commit code with warnings (or errors).</p> <p>Sometimes I consciously ignore these warnings for particular lines of code (for various reasons, typically to account for implementation de...
1
2016-10-04T08:45:31Z
39,847,910
<p>Essentially, for the file in which you want to suppress the warning, run it through code inspection, post which PyCharm will give you warnings in that particular file. You can then review the warnings and tell PyCharm to suppress warning for a particular statement.</p> <p>Code Inspection can be accessed from Code--...
1
2016-10-04T08:47:09Z
[ "python", "pycharm", "compiler-warnings", "suppress-warnings" ]
Find max and min RGB values of a pixel using PIL
39,847,891
<p>I have a basic algorithm for desaturating an image using the pillow library and Python 3: - find max of a pixel's RGB values - find min of a pixel's RGB values - calc average: (max + min) / 2</p> <p>How do I find the min and max red, green and blue values for each pixel? I'm completely confused! I tried this code a...
0
2016-10-04T08:46:11Z
39,847,965
<p><code>img.getextrema()</code> returns the tuple of <code>(min_value, max_value)</code>. In order to get the average value, you have to do:</p> <pre><code>value = img.getextrema() avg = sum(value)/len(value) # OR, sum(value)/2, as len will always be 2 </code></pre>
0
2016-10-04T08:50:08Z
[ "python" ]
Pandas: improve algorithm with find substring in column
39,847,973
<p>I have dataframe and I try to get only string, where some column contain some strings.</p> <p>I use:</p> <pre><code>df_res = pd.DataFrame() for i in substr: res = df[df['event_address'].str.contains(i)] </code></pre> <p><code>df</code> looks like:</p> <pre><code>member_id,event_address,event_time,event_durat...
1
2016-10-04T08:50:41Z
39,848,010
<p>I think you need add <code>join</code> by <code>|</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow">str.<code>contains</code></a> if need faster solution:</p> <pre><code>res = df[df['event_address'].str.contains('|'.join(urls.url))] print (res) ...
1
2016-10-04T08:52:01Z
[ "python", "string", "pandas", "indexing", "substring" ]
Pandas: improve algorithm with find substring in column
39,847,973
<p>I have dataframe and I try to get only string, where some column contain some strings.</p> <p>I use:</p> <pre><code>df_res = pd.DataFrame() for i in substr: res = df[df['event_address'].str.contains(i)] </code></pre> <p><code>df</code> looks like:</p> <pre><code>member_id,event_address,event_time,event_durat...
1
2016-10-04T08:50:41Z
39,848,317
<p>do like this:</p> <pre><code>def check_exists(x): for i in substr: if i in x: return True return False df2 = df.ix[df.event_address.map(check_exists)] </code></pre> <p>or if you like write it in one-line:</p> <pre><code>df.ix[df.event_address.map(lambda x: any([True for i in substr if...
2
2016-10-04T09:07:06Z
[ "python", "string", "pandas", "indexing", "substring" ]
Mykrobe predictor JSON to TSV Converter
39,847,995
<p>I wanted to ask a question regarding file conversion.</p> <p>I have a JSON file (after AMR prediction execution) that I want to covert to a TSV file based on Mykrobe-predictor scripts (json_to_tsv.py) and this is my JSON output (<a href="http://bioinfo.cs.ccu.edu.tw/result_TB.json" rel="nofollow">result_TB.json</a>...
2
2016-10-04T08:51:40Z
39,872,732
<p>Looking at the code I guess they expect to call the converter with something like:</p> <pre><code>python json_to_tsv.py plate/sample1/sample1.json </code></pre> <p>Try copying your JSON file to a directory called <code>sample1</code> inside a directory called <code>plate</code> and see if you get the same error wh...
0
2016-10-05T11:27:22Z
[ "python", "json", "linux", "bioinformatics" ]
Memory error python computing permutations of list
39,848,084
<p>I want to compute all possible ways of constructing a binary list of length n with the following line</p> <pre><code>combinations = map(list, itertools.product([0, 1], repeat=n)) </code></pre> <p>This works fine with low n's but I want to compute this for big n's (i.e. values between 25-35). Is there a better and ...
0
2016-10-04T08:55:23Z
39,848,454
<p>Just create the list "lazily", so as to not store the entire thing in memory at once:</p> <pre><code>n = some-largish-value for i in itertools.product([0, 1], repeat=n): result = do_something_with(list(i)) </code></pre>
2
2016-10-04T09:14:04Z
[ "python", "python-2.7", "permutation", "combinatorics" ]
Memory error python computing permutations of list
39,848,084
<p>I want to compute all possible ways of constructing a binary list of length n with the following line</p> <pre><code>combinations = map(list, itertools.product([0, 1], repeat=n)) </code></pre> <p>This works fine with low n's but I want to compute this for big n's (i.e. values between 25-35). Is there a better and ...
0
2016-10-04T08:55:23Z
39,849,515
<p>Your are trying to find all the combinations of 0 and 1 for n term. Total number of such combination will be <code>2**n</code>. For <code>n=30</code>, total such combinations are <code>1073741824</code>. Huge isn't? </p> <p>In order to get rid of the memory error, you should be using <a href="https://wiki.python.or...
1
2016-10-04T10:05:43Z
[ "python", "python-2.7", "permutation", "combinatorics" ]
Memory error python computing permutations of list
39,848,084
<p>I want to compute all possible ways of constructing a binary list of length n with the following line</p> <pre><code>combinations = map(list, itertools.product([0, 1], repeat=n)) </code></pre> <p>This works fine with low n's but I want to compute this for big n's (i.e. values between 25-35). Is there a better and ...
0
2016-10-04T08:55:23Z
39,849,706
<p>No, if you really want a list of lists then your code is almost as memory efficient as it could be. Your issue is the size of the list, not the way you are computing it.</p> <p>Do you realize that for n=35 you will have 1,202,590,842,880 elements? Most (if not all) desktop computers can't hold so many python intege...
0
2016-10-04T10:15:39Z
[ "python", "python-2.7", "permutation", "combinatorics" ]
convert foreach to foreachpartition in spark
39,848,127
<p>I am working with foreach on spark RDD. Now I wanted to convert the same logic to foreachpartition.</p> <p><strong>Here is my logic:</strong> </p> <pre><code>batch = [] max = rdd.count() processed = 0 def writeBatch(b): ///Push this batch to a database def collect(row): dict={'name':row[0],'age':row[1} ...
0
2016-10-04T08:57:28Z
39,853,563
<p>Problem is it is not a valid logic. It may work in some special cases but in general you'll loose data.</p> <p>Inside <code>foreach</code> you mutate two objects <code>batch</code>, <code>processed</code> where neither one is truly global (for a whole cluster) or isolated per partition (unless you configured Spark ...
0
2016-10-04T13:24:27Z
[ "python", "apache-spark", "pyspark" ]
Change the underlying data representation with the descriptor protocol
39,848,164
<p>Suppose I have an existing class, for example doing some mathematical stuff:</p> <pre><code>class Vector: def __init__(self, x, y): self.x = y self.y = y def norm(self): return math.sqrt(math.pow(self.x, 2) + math.pow(self.y, 2)) </code></pre> <p>Now, for some reason, I'd like to ...
2
2016-10-04T08:58:53Z
39,848,393
<p>If you need a generic convertor('convert') like you did, this is the way to go.</p> <p>The biggest downside will be <strong>performance</strong> when you will need to create a lot of instances( I assumed you might, since the class called <code>Vector</code>). This will be slow since python class initiation is slow....
0
2016-10-04T09:11:22Z
[ "python" ]
Change the underlying data representation with the descriptor protocol
39,848,164
<p>Suppose I have an existing class, for example doing some mathematical stuff:</p> <pre><code>class Vector: def __init__(self, x, y): self.x = y self.y = y def norm(self): return math.sqrt(math.pow(self.x, 2) + math.pow(self.y, 2)) </code></pre> <p>Now, for some reason, I'd like to ...
2
2016-10-04T08:58:53Z
39,854,068
<p>There is one pitfall regarding python descriptors.</p> <p>Using your code, you will reference the same value, stored in StringVector.x.prop and StringVector.y.prop respectively:</p> <pre><code>v1 = StringVector(1, 2) print('current StringVector "x": ', StringVector.__dict__['x'].prop) v2 = StringVector(3, 4) print...
1
2016-10-04T13:48:46Z
[ "python" ]
Django: Store many forms into one table
39,848,235
<p>I'm using django v1.8.</p> <p>A have one table split into four forms.</p> <p>Example from my <code>views.py</code></p> <pre><code>ext_cent = ExternalCentersForm(request.POST, prefix='extcent') ext_cent_diagnostic = ExternalCentersDiagnosticForm(request.POST,prefix='extcentDiagn') ext_cent_outcomes = ExternalCente...
0
2016-10-04T09:02:06Z
39,848,573
<p>In the place of save You need "update"</p> <p>Here is an example :</p> <pre><code> ext_cent_stored = Ext_centers.objects.get(center_id=ext_cent_object.center_id) form = ExternalCentersForm(request.POST, instance=ext_cent_stored) if form.is_valid(): form.save() for...
1
2016-10-04T09:20:14Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
How to dump a dictionary into an .xlsx file with proper column alignment?
39,848,392
<p>I have a dictionary with 2000 items which looks like this:</p> <pre><code>d = {'10071353': (0, 0), '06030011': (6, 0), '06030016': (2, 10), ...} </code></pre> <p>Given that I want to write it to an <code>.xlsx</code> file, I use this code (taken from <a href="http://stackoverflow.com/questions/23113231/python-writ...
1
2016-10-04T09:11:21Z
39,848,529
<p>This is what I think should help:</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook('myfile.xlsx') worksheet = workbook.add_worksheet() row = 0 col = 0 order=sorted(d.keys()) for key in order: row += 1 worksheet.write(row, col, key) i =1 for item in d[key]: worksheet.write...
2
2016-10-04T09:18:17Z
[ "python", "excel", "dictionary", "xlsxwriter" ]
How to dump a dictionary into an .xlsx file with proper column alignment?
39,848,392
<p>I have a dictionary with 2000 items which looks like this:</p> <pre><code>d = {'10071353': (0, 0), '06030011': (6, 0), '06030016': (2, 10), ...} </code></pre> <p>Given that I want to write it to an <code>.xlsx</code> file, I use this code (taken from <a href="http://stackoverflow.com/questions/23113231/python-writ...
1
2016-10-04T09:11:21Z
39,849,006
<p>The best way is to use <code>pandas</code> for this task. Some documentation is available here (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html</a> )</p> <pre><code>impo...
1
2016-10-04T09:40:46Z
[ "python", "excel", "dictionary", "xlsxwriter" ]
How to dump a dictionary into an .xlsx file with proper column alignment?
39,848,392
<p>I have a dictionary with 2000 items which looks like this:</p> <pre><code>d = {'10071353': (0, 0), '06030011': (6, 0), '06030016': (2, 10), ...} </code></pre> <p>Given that I want to write it to an <code>.xlsx</code> file, I use this code (taken from <a href="http://stackoverflow.com/questions/23113231/python-writ...
1
2016-10-04T09:11:21Z
39,849,172
<p>I think you just misplaced a variable.</p> <pre><code>worksheet.write(row, col + 1, item) row += 1 </code></pre> <p>this is wrong, <code>row +=1</code> should be replaced with <code>col +=1</code></p> <p>This is correct way, You can use the same variable.</p> <pre><code>import xlsxwriter workbook = xlsxw...
2
2016-10-04T09:48:45Z
[ "python", "excel", "dictionary", "xlsxwriter" ]
Scipy minimize a scalar with Brent method throws an Overflow 34
39,848,410
<p>I'd like to find a local minimum of the function <code>f(x) = x^3 + x^2 + x - 2</code> where <code>x</code> is between <code>&lt;-10; 10&gt;</code>. I use Anaconda 3 on Windows 64bit.</p> <p>My scipy python code throws an error:</p> <pre><code>from scipy import optimize def f(x): return (x**3)+(x**2)+x-2 x_min...
0
2016-10-04T09:12:05Z
39,849,390
<p>When using local boundaries, changing <code>method</code> to <code>'bounded'</code> is required</p> <pre><code>from scipy import optimize def f(x): return (x**3)+(x**2)+x-2 x_min = optimize.minimize_scalar(f, bounds=[-10, 10], method='bounded') print(x_min) </code></pre>
1
2016-10-04T09:59:36Z
[ "python", "scipy" ]
Selenium Webdriver failed when use window_handles
39,848,485
<p>I am trying to handle Two Tab in Python Selenium webdriver with Chrome as browser.</p> <p>I am getting result for find element by link text on first tab as well as second tab if I keep the <strong>Chrome Browser as selected window</strong>.[i.e Front Screen Process ]</p> <p>When I change the control to new tab usi...
0
2016-10-04T09:15:53Z
39,865,480
<p>you can manage tab using following code.</p> <pre><code>driver.execute_script("window.open('"+url+"', '_blank');") driver.switch_to_window(driver.window_handles[1]) </code></pre>
0
2016-10-05T04:31:45Z
[ "python", "google-chrome", "selenium", "selenium-webdriver", "windows-7" ]
How to insert NaN array into a numpy 2D array
39,848,700
<p>I'm trying to insert an arbitrary number of rows of NaN values within a 2D array at specific places. I'm logging some data from a microcontroller in a .csv file and parsing with python.</p> <p>The data is stored in a 3 column 2D array like this</p> <pre><code>[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (125.0, 1.0, -...
0
2016-10-04T09:25:42Z
39,848,762
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html" rel="nofollow">doc of <code>np.insert()</code></a>:</p> <pre><code>import numpy as np a = np.arrray([(122.0, 1.0, -47.0), (123.0, 1.0, -47.0), (125.0, 1.0, -44.0)])) np.insert(a, 2, np.nan, axis=0) array([[ 122., 1., -47.],...
1
2016-10-04T09:29:19Z
[ "python", "arrays", "numpy" ]
How to insert NaN array into a numpy 2D array
39,848,700
<p>I'm trying to insert an arbitrary number of rows of NaN values within a 2D array at specific places. I'm logging some data from a microcontroller in a .csv file and parsing with python.</p> <p>The data is stored in a 3 column 2D array like this</p> <pre><code>[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (125.0, 1.0, -...
0
2016-10-04T09:25:42Z
39,848,990
<p><strong>Approach #1</strong></p> <p>We can use an initialization based approach to handle multiple gaps and gaps of any lengths -</p> <pre><code># Pre-processing step to create monotonically increasing array for first col id_arr = np.zeros(arr.shape[0]) id_arr[np.flatnonzero(np.diff(arr[:,0])&lt;0)+1] = 256 a0 = i...
1
2016-10-04T09:39:44Z
[ "python", "arrays", "numpy" ]
Filtering and displaying mySQL Data on Webpage via Python? PHP?
39,848,809
<p>I'd like to build a website that reads data from a database, lets me filter that data with different Frontend dropdown-filters and presents me the filtered data in a table shown on the Webpage.</p> <p>In addition I'd like to have the possibility to use that data further to store it into some file, or use it in a py...
-2
2016-10-04T09:31:22Z
39,849,072
<p>It depends on how familiar you are with PHP or Python. If you are new to both, I recommend you to start with <a href="http://www.w3schools.com/php/" rel="nofollow">PHP</a>. If you are familiar with Python, I recommend you to use <a href="http://flask.pocoo.org/docs/0.11/tutorial/" rel="nofollow">Flask</a> or <a href...
1
2016-10-04T09:43:55Z
[ "php", "python", "mysql" ]
Remote MySQL connection works from cmdline, but not with Apache (Webpy, Mod-WSGI)
39,848,813
<ul> <li>Server OS: Red Hat Enterprise Linux Server release 5.11 </li> <li>Apache: 2.2.3</li> <li>Python: 2.7.6</li> <li>Mod_WSGI 4.5.3, Web.Py, MySQLdb</li> </ul> <p>Hey! I have created a Web.Py site that queries data from a remote Oracle database which works perfectly, but I have now run into a problem when trying t...
0
2016-10-04T09:31:26Z
39,855,544
<p>As has been commented, check to see if there is a file within the same directory as the file you're trying to run, that has the name MySQLdb.py</p>
0
2016-10-04T14:55:16Z
[ "python", "apache", "mod-wsgi", "mysql-python", "web.py" ]
Replace the column into designed format
39,848,869
<p>I have a column like that </p> <pre><code>Hei-3_ctg7180000009945 pan gene 1 13249 . . . ID=Hei-3_ctg7180000009945;Name=Hei-3_ctg7180000009945 Hei-3_ctg7180000009946 pan gene 1 587 . . . ID=Hei-3_ctg7180000009946;Name=Hei-3_ctg7180000009946 </code></pre> <p>And I want to make it like:</p> ...
0
2016-10-04T09:34:15Z
39,849,118
<p>Very vague question, but to print with a fixed length (5 in this case) you can use</p> <pre><code>print("{:5}".format(123)) print("{:5}".format(12345)) </code></pre> <p>yields</p> <pre><code> 123 12345 </code></pre>
0
2016-10-04T09:46:06Z
[ "python", "shell", "unix" ]
Problems while importing h5py package
39,848,991
<p>I am coding in python and trying to <code>import h5py</code>. I have installed this package before. When I try to do this, it gives this error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/dist-p...
0
2016-10-04T09:39:44Z
39,849,311
<p>The fact that it works in one place and not another points to a possible conflict between several installs.</p> <p>I suggest that you make sure to have only one install of NumPy and of h5py.</p> <p>To diagnose the problem, issue the commands</p> <pre><code>python -c 'import h5py; print h5py.__file__' python -c 'i...
0
2016-10-04T09:56:08Z
[ "python", "numpy", "h5py" ]
Skipping long entries for history search in IPython 5.x
39,849,137
<p>I use <code>ipython</code> console quite heavily for python workflow. As happy as I am with the new 5.x series <a href="http://ipython.readthedocs.io/en/stable/whatsnew/version5.html" rel="nofollow">released</a>, I find the ability to freely navigate inside the long code blocks a double-edged sword when it comes to ...
0
2016-10-04T09:47:14Z
39,849,333
<p><code>&lt;Up&gt;</code>/<code>&lt;C-P&gt;</code> and <code>&lt;Down&gt;</code>/<code>&lt;C-N&gt;</code> iterate over every line in your history.</p> <p>Use <code>&lt;PageDown&gt;</code> and <code>&lt;PageUp&gt;</code> keys to iterate over entries instead.</p> <p>Here's a full list of shortcuts: <a href="http://ipy...
1
2016-10-04T09:57:04Z
[ "python", "ipython", "keyboard-shortcuts" ]
Regular expression tags on multiple lines
39,849,145
<p>How to extract the contents between these tags when they're on multiple/ different lines? </p> <pre><code>&lt;link&gt; https://widget.websta.me/rss/n/bleh &lt;/link&gt; </code></pre> <p>I tried: content = findall('(.*)', web_page_contents, re.DOTALL) But I get the next mention of instead of this one^</p>
-1
2016-10-04T09:47:41Z
39,849,397
<p>You can use <code>BeautifulSoup</code> to do that. It has a very good <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">documentation</a> and is very easy.</p> <p>The following code will work:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get(webpage_url) soup = B...
0
2016-10-04T09:59:49Z
[ "python", "html", "regex" ]
Translate lists to a 2D numpy matrix
39,849,208
<p>I have a list of lists in python. The lists is the following:</p> <pre><code>[[196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3], .... ] </code></pre> <p>The first column correspond to users (1:943) and the second to items(1:1682) and their votes to items. I want to try the matrix factorization <a hr...
0
2016-10-04T09:50:26Z
39,849,268
<p>Sure.</p> <p>You can create a 2-dimensional numpy array (which you can treat as a matrix), using the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html" rel="nofollow"><code>np.array</code></a> function:</p> <pre><code>mat = np.array(list_of_lists) </code></pre>
1
2016-10-04T09:54:21Z
[ "python", "numpy", "matrix" ]
Translate lists to a 2D numpy matrix
39,849,208
<p>I have a list of lists in python. The lists is the following:</p> <pre><code>[[196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3], .... ] </code></pre> <p>The first column correspond to users (1:943) and the second to items(1:1682) and their votes to items. I want to try the matrix factorization <a hr...
0
2016-10-04T09:50:26Z
39,849,412
<p>Here is how you can create a sparse matrix from the list of set items:</p> <pre><code>data = [ [196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3], .... ] user_count = max(i[0] for i in data) + 1 item_count = max(i[1] for i in data) + 1 data_mx = scipy.sparse.dok_matrix((user_count, it...
1
2016-10-04T10:00:14Z
[ "python", "numpy", "matrix" ]
Translate lists to a 2D numpy matrix
39,849,208
<p>I have a list of lists in python. The lists is the following:</p> <pre><code>[[196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3], .... ] </code></pre> <p>The first column correspond to users (1:943) and the second to items(1:1682) and their votes to items. I want to try the matrix factorization <a hr...
0
2016-10-04T09:50:26Z
39,858,030
<p>You data looks like a list of lists:</p> <pre><code>In [168]: ll = [[196, 242, 3], ...: [186, 302, 3], ...: [22, 377, 1], ...: [196, 377, 3]] </code></pre> <p>Make an array from it - for convenience in the following operations</p> <pre><code>In [169]: A = np.array(ll) In [170]: ll Out[170]: [[...
1
2016-10-04T17:06:13Z
[ "python", "numpy", "matrix" ]
Override ModelViewSet's queryset with filter backends applied
39,849,292
<p>Is it possible to take into account <code>MyModelViewSet</code>'s <code>filter_backends</code> when creating custom queryset?</p> <pre><code>class MyModelViewSet(viewsets.ModelViewSet): filter_backends = (CustomFilter, ) serializer_class = MySerializer def get_queryset(self): # It should not re...
0
2016-10-04T09:55:19Z
39,849,686
<p>Yes you can. Just extend <code>filter_queryset</code> method of ViewSet</p> <pre><code>class MyModelViewSet(viewsets.ModelViewSet): filter_backends = (CustomFilter, ) serializer_class = MySerializer def filter_queryset(self, queryset): # super needs to be called to filter backends to be applied...
1
2016-10-04T10:14:07Z
[ "python", "django", "python-3.x", "django-rest-framework" ]
Get visible content of a page using selenium and BeautifulSoup
39,849,497
<p>I want to retrieve all visible content of a web page. Let say for example <a href="https://dukescript.com/best/practices/2015/11/23/dynamic-templates.html" rel="nofollow">this</a> webpage. I am using a headless firefox browser remotely with selenium.</p> <p>The script I am using looks like this</p> <pre><code>driv...
2
2016-10-04T10:04:34Z
39,849,658
<p>Sounds like the dom elements are not yet loaded when your code try to reach them. </p> <p>Try to <a href="http://stackoverflow.com/questions/7781792/selenium-waitforelement">wait</a> for the elements to be fully loaded and just then replace.</p> <p>This works for your when you run it command by command because the...
1
2016-10-04T10:12:59Z
[ "python", "html", "selenium", "beautifulsoup" ]
Get visible content of a page using selenium and BeautifulSoup
39,849,497
<p>I want to retrieve all visible content of a web page. Let say for example <a href="https://dukescript.com/best/practices/2015/11/23/dynamic-templates.html" rel="nofollow">this</a> webpage. I am using a headless firefox browser remotely with selenium.</p> <p>The script I am using looks like this</p> <pre><code>driv...
2
2016-10-04T10:04:34Z
39,854,093
<p>Try to get the Page Source after detecting the required ID/CSS_SELECTOR/CLASS or LINK.</p> <p>You can always use explicit wait of Selenium WebDriver.</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.commo...
1
2016-10-04T13:50:00Z
[ "python", "html", "selenium", "beautifulsoup" ]
Get visible content of a page using selenium and BeautifulSoup
39,849,497
<p>I want to retrieve all visible content of a web page. Let say for example <a href="https://dukescript.com/best/practices/2015/11/23/dynamic-templates.html" rel="nofollow">this</a> webpage. I am using a headless firefox browser remotely with selenium.</p> <p>The script I am using looks like this</p> <pre><code>driv...
2
2016-10-04T10:04:34Z
39,854,349
<p>To add to Or Duan's answer I provide what I ended up doing. The problem of finding whether a page or parts of a page have loaded completely is an intricate one. I tried to use implicit and explicit waits but again I ended up receiving half-loaded frames. My workaround is to check the <code>readyState</code> of the o...
1
2016-10-04T14:01:39Z
[ "python", "html", "selenium", "beautifulsoup" ]
Unicoded string key error in python dict
39,849,584
<p>I have such a code:</p> <pre><code>corpus_file = codecs.open("corpus_en-tr.txt", encoding="utf-8").readlines() corpus = [] for a in range(0, len(corpus_file), 2): corpus.append({'src': corpus_file[a].rstrip(), 'tgt': corpus_file[a+1].rstrip()}) params = {} for sentencePair in corpus: for tgtWord in sen...
0
2016-10-04T10:09:25Z
39,849,671
<p>Your <code>params</code> dict is empty.</p> <p>You can use tree for that:</p> <pre><code>from collections import defaultdict def tree(): return defaultdict(tree) params = tree() params['any']['keys']['you']['want'] = 1.0 </code></pre> <p>Or a simpler <a href="https://docs.python.org/3/library/collections.ht...
1
2016-10-04T10:13:23Z
[ "python", "dictionary", "unicode" ]
Unicoded string key error in python dict
39,849,584
<p>I have such a code:</p> <pre><code>corpus_file = codecs.open("corpus_en-tr.txt", encoding="utf-8").readlines() corpus = [] for a in range(0, len(corpus_file), 2): corpus.append({'src': corpus_file[a].rstrip(), 'tgt': corpus_file[a+1].rstrip()}) params = {} for sentencePair in corpus: for tgtWord in sen...
0
2016-10-04T10:09:25Z
39,850,144
<p>You can just use <code>setdefault</code>:</p> <p>Replace </p> <pre class="lang-python prettyprint-override"><code>params[srcWord][tgtWord] = 1.0 </code></pre> <p>with</p> <pre class="lang-python prettyprint-override"><code>params.setdefault(srcWord, {})[tgtWord] = 1.0 </code></pre>
1
2016-10-04T10:39:07Z
[ "python", "dictionary", "unicode" ]
Unable to extract zip in python to destination folder(server) from my local host
39,849,766
<p>I'm unable to extract zip file in python to destination folder(server) from my local host. While extracting using <code>z.extract(name,"/destination/")</code>, it's unable to find destination folder as it is trying to search destination folder locally instead of the server.</p> <pre><code> transport = paramiko.T...
0
2016-10-04T10:18:35Z
39,850,327
<p>It appears you would like the extracted files to appear on the server, even though you are extracting them on the client machine. Unfortunately that isn't going to fly, as the <code>zipfile.extract</code> method assumes that its second argument is a local path.</p> <p>You <em>could</em> consider creating a local te...
1
2016-10-04T10:49:06Z
[ "python", "ssh", "sftp", "paramiko" ]
New project in scrapy
39,849,778
<p>I am new to scrapy. I found the error when I create new project.</p> <p>So please tell me How to create new project in scrapy. I am trying as following-</p> <pre><code>scrapy start project </code></pre>
0
2016-10-04T10:19:36Z
39,849,896
<p>Simply go to directory where you want to create project using-</p> <pre><code>cd path/to/directory </code></pre> <p>in the command prompt. Then run the command-</p> <pre><code>scrapy startproject project_name </code></pre> <p>you are using space between start and project which is incorrect.</p>
0
2016-10-04T10:25:59Z
[ "python", "scrapy" ]
Get index/position of the tag using text in Selenium WebDriver
39,849,823
<p>Here is html chunk:</p> <pre><code>&lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;td&gt; &lt;td&gt; &lt;img src="../imgs.gif"&gt; &lt;td&gt; &lt;td&gt;&lt;td&gt; &lt;td&gt;&lt;td&gt; &lt;td&gt;&lt;td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>I want to iterate over <strong>&lt; td ></strong> attribu...
0
2016-10-04T10:21:50Z
39,850,593
<p>How about identifying the image and counting the preceding td sibling and adding one to it.</p> <pre><code>$x("count(//img/parent::td/preceding-sibling::td) + 1") </code></pre>
1
2016-10-04T11:01:58Z
[ "python", "html", "selenium", "xpath" ]
Get index/position of the tag using text in Selenium WebDriver
39,849,823
<p>Here is html chunk:</p> <pre><code>&lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;td&gt; &lt;td&gt; &lt;img src="../imgs.gif"&gt; &lt;td&gt; &lt;td&gt;&lt;td&gt; &lt;td&gt;&lt;td&gt; &lt;td&gt;&lt;td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>I want to iterate over <strong>&lt; td ></strong> attribu...
0
2016-10-04T10:21:50Z
39,854,573
<p>Tried a bit different approach that works.</p> <pre><code> html = browser.page_source tree = lxml.html.fromstring(html) re = tree.xpath("//tbody//tr//td") for i in range(0, len(re)): res = re[i].xpath(".//img//@src") for img in res: print repr(img) print "img n...
0
2016-10-04T14:11:51Z
[ "python", "html", "selenium", "xpath" ]
I am getting following error.i download oracle client and provide neccesary path to env varibles
39,849,837
<blockquote> <blockquote> <blockquote> <p>import cx_Oracle Traceback (most recent call last): File "", line 1, in ImportError: DLL load failed: %1 is not a valid Win32 application.</p> </blockquote> </blockquote> </blockquote>
0
2016-10-04T10:23:10Z
39,852,993
<p>I'll list the things that you need to check.</p> <p>1) An Oracle client is required. The easiest to use is the Oracle instant client which you can get from this location: <a href="http://www.oracle.com/technetwork/database/features/instant-client/index.html" rel="nofollow">http://www.oracle.com/technetwork/database...
0
2016-10-04T12:58:51Z
[ "python", "django", "oracle10g", "cx-oracle", "instantclient" ]
Disappearing {% csrf_token %} on website file
39,849,875
<p>When I wanted use my registration form in my site, I get ERROR 403: "CSRF verification failed. Request aborted." In source of this website I realised that is missing. This is part of view-source from my site:</p> <pre><code>&lt;div style="margin-left:35%;margin-right:35%;"&gt; &lt;fieldset&gt; &lt;legend&gt; Wszys...
3
2016-10-04T10:25:15Z
39,850,114
<p>CSRF token gets included in HTML form by calling <code>hidden_tag</code> function on your form object.</p> <p>For example check this <a href="https://gist.github.com/srahul07/6507758" rel="nofollow">gist</a>, line number 6. This is how you add form and it's elements in jinja.</p>
-2
2016-10-04T10:37:15Z
[ "python", "html", "django", "django-templates", "pythonanywhere" ]
Disappearing {% csrf_token %} on website file
39,849,875
<p>When I wanted use my registration form in my site, I get ERROR 403: "CSRF verification failed. Request aborted." In source of this website I realised that is missing. This is part of view-source from my site:</p> <pre><code>&lt;div style="margin-left:35%;margin-right:35%;"&gt; &lt;fieldset&gt; &lt;legend&gt; Wszys...
3
2016-10-04T10:25:15Z
39,850,762
<p>You should pass a plain dict and the request object to <code>template.render()</code>, not a <code>RequestContext</code>. The template engine will convert it to a <code>RequestContext</code> for you:</p> <pre><code>template = get_template("osnowa_app/register.html") context = {'form': form} output = template.render...
4
2016-10-04T11:10:20Z
[ "python", "html", "django", "django-templates", "pythonanywhere" ]
Selectively feeding python csv class with lines
39,850,173
<p>I have a csv file with a few patterns. I only want to selectively load lines into the csv reader class of python. Currently, csv only takes a file object. Is there a way to get around this?<br> In other words, what I need is:</p> <pre><code>with open('filename') as f: for line in f: if condition(line): ...
0
2016-10-04T10:40:59Z
39,850,257
<pre><code>import shlex lex = shlex.shlex('"sreeraag","100,ABC,XYZ",112',',', posix=True) lex.whitespace += ',' lex.whitespace_split = True print list(lex) </code></pre> <p>yields</p> <pre><code>['sreeraag', '100,ABC,XYZ', '112'] </code></pre>
1
2016-10-04T10:44:59Z
[ "python", "csv" ]
Selectively feeding python csv class with lines
39,850,173
<p>I have a csv file with a few patterns. I only want to selectively load lines into the csv reader class of python. Currently, csv only takes a file object. Is there a way to get around this?<br> In other words, what I need is:</p> <pre><code>with open('filename') as f: for line in f: if condition(line): ...
0
2016-10-04T10:40:59Z
39,851,685
<p>To read file as stream you can use this.</p> <pre><code>io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True) </code></pre>
1
2016-10-04T11:57:28Z
[ "python", "csv" ]
Selectively feeding python csv class with lines
39,850,173
<p>I have a csv file with a few patterns. I only want to selectively load lines into the csv reader class of python. Currently, csv only takes a file object. Is there a way to get around this?<br> In other words, what I need is:</p> <pre><code>with open('filename') as f: for line in f: if condition(line): ...
0
2016-10-04T10:40:59Z
39,852,797
<p>From the <code>csv.reader</code> docstring:</p> <blockquote> <p><em>csvfile</em> can be any object which supports the iterator protocol and returns a string each time its <code>__next__()</code> method is called</p> </blockquote> <p>You can feed <code>csv.reader</code> with a generator iterator that yields only ...
3
2016-10-04T12:49:26Z
[ "python", "csv" ]