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
Jinja2 include & extends not working as expected
39,555,769
<p>I used <code>include</code> and <code>extends</code> in the <code>base.html</code> file and expect them to be included in order. But the <code>extends</code> template is appended to the end of the file.</p> <p>I expect my template to give me the output of:</p> <pre class="lang-html prettyprint-override"><code>&lt;...
2
2016-09-18T08:47:49Z
39,556,662
<p>I would suggest structuring slightly differently. I used a structure like this just recently and got the proper results.</p> <p>index.html:</p> <pre><code>{% extends "base.html" %} {% block head %} &lt;!-- if you want to change the &lt;head&gt; somehow, you can do that here --&gt; {% endblock head %} {% blo...
1
2016-09-18T10:30:21Z
[ "python", "flask", "jinja2" ]
How to populate a dropdown in Django?
39,555,782
<p>I want to build a simple view using Django. There will be a dropdown of 'customer site's and then, after one customer site is selected the view will populate a dropdown of competitors of previously selected customer. My trouble is with the second part: when I select the customer from the first dropdown and press 'ch...
0
2016-09-18T08:49:21Z
39,556,075
<p>In your form, <code>self.competitors_site_ids</code> isn't anything relevant. You need to assign to <code>self.fields['competitors_site_ids']</code>.</p> <p>Also this code should probably be in <code>__init__</code>, not a separate method.</p>
0
2016-09-18T09:25:52Z
[ "python", "django" ]
Return the different child object depending on the condition using the same method
39,555,914
<p>I have a two child classes which are inherited from the base class. I have one method in the different script which will actually return one of the child class object depending on some condition, is it the correct way in python to return the different child object using the same method. I think yes as their type is ...
-1
2016-09-18T09:07:10Z
39,556,215
<p>Python is a dynamically typed language. One does not declare types. So, from that side, it is perfectly fine to pass arguments and return values of any type.</p> <p>On the other hand, you want your objects to be usable, so some interface has to be adhered to. For example, you can often pass any object with <code>re...
0
2016-09-18T09:40:35Z
[ "python" ]
How can I update a Gtk.TextView from events from a different thread?
39,556,006
<p>In a separate thread, I check for information in the pySerial Buffer (Infinite Loop). If new information is available, I'd like to show that Input in a <code>Gtk.TextView</code>. After Googling on the subject it turns out doing Gtk -Stuff inside threads is a killer. Random errors will appear and so on, which was als...
1
2016-09-18T09:17:26Z
39,558,636
<p>Found a Solution:</p> <blockquote> <p>GObject.timeout_add</p> </blockquote> <p><a href="http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add" rel="nofollow">http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add</a></p> <p>This GObject Func...
1
2016-09-18T14:19:46Z
[ "python", "user-interface", "queue", "gtk3", "python-multithreading" ]
How can I update a Gtk.TextView from events from a different thread?
39,556,006
<p>In a separate thread, I check for information in the pySerial Buffer (Infinite Loop). If new information is available, I'd like to show that Input in a <code>Gtk.TextView</code>. After Googling on the subject it turns out doing Gtk -Stuff inside threads is a killer. Random errors will appear and so on, which was als...
1
2016-09-18T09:17:26Z
39,558,651
<p>To successfully periodically update the GUI from events in a thread, we cannot simply use <code>threading</code> to start a second process. Like you mention, it will lead to conflicts.</p> <p>Here is where <code>GObject</code> comes in, to, as it is put in <a href="http://faq.pygtk.org/index.py?req=edit&amp;file=fa...
2
2016-09-18T14:22:04Z
[ "python", "user-interface", "queue", "gtk3", "python-multithreading" ]
Django migrations in subfolders
39,556,018
<p>I have the following project structure:</p> <pre><code>bm_app_1 | contents here bm_app_2 | contents here bm_common | __init__.py | deletable | | __init__.py | | behaviors.py | | models.py | timestampable | | __init__.py | | behaviors.py </code></pre> <p>The files in app <code>bm_common</code> define...
0
2016-09-18T09:18:38Z
39,556,055
<p>The models need to be imported in some way when the app registry is populating all models, otherwise they are not registered and Django doesn't know about them. The easiest solution is to create a <code>bm_common/models.py</code> file and import all models in there:</p> <pre><code>from .deletable.models import Mode...
1
2016-09-18T09:24:01Z
[ "python", "django", "django-models", "django-migrations" ]
How to keep variable in for loop and others'conditional statement wouldn't change it
39,556,032
<p>when program executed the second <code>if</code> and change <code>P = 0</code>, it will execute the next <code>if</code>. I know it's wrong, but I curiously wonder how to hold variables(<code>P</code>) constant and don't impact other in the if statement.</p> <pre><code> """ :type a: str :type b: str ...
1
2016-09-18T09:20:45Z
39,556,067
<p>Use <code>elif</code> (else if).</p> <p>Instead of:</p> <pre><code>if something: change_something() if something_else: change_something_else() </code></pre> <p>Do:</p> <pre><code>if something: change_something() elif something_else: change_something_else() </code></pre>
2
2016-09-18T09:25:09Z
[ "python", "if-statement", "condition" ]
How to keep variable in for loop and others'conditional statement wouldn't change it
39,556,032
<p>when program executed the second <code>if</code> and change <code>P = 0</code>, it will execute the next <code>if</code>. I know it's wrong, but I curiously wonder how to hold variables(<code>P</code>) constant and don't impact other in the if statement.</p> <pre><code> """ :type a: str :type b: str ...
1
2016-09-18T09:20:45Z
39,556,079
<p>Don't you want to use <code>elif</code>?</p> <pre><code>if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 1: c = c + '0' P = 0 elif a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 0: c = c + '1' elif a[i] + b[j] == '00' and P == 1: c = c + '1' P =0 elif a[i] + b[j] == '00' and P == ...
1
2016-09-18T09:26:11Z
[ "python", "if-statement", "condition" ]
Running pdflatex from a python script (3.5.2)
39,556,116
<p>I am trying to run pdflatex from a python script using the subprocess module but for some reason python cannot find the pdflatex module. I can call pdflatex from a command prompt and it works without any issues. I have verified that the path to pdflatex exists under environment variables. I have a MikTex 2.9 install...
0
2016-09-18T09:30:17Z
39,556,191
<p>You should try <a href="https://github.com/aclements/latexrun" rel="nofollow">latexrun</a>. This takes care of running all latex related commands.</p>
0
2016-09-18T09:37:24Z
[ "python", "subprocess", "pdflatex" ]
Bokeh is behaving in mysterious way
39,556,175
<pre><code>import numpy as np from bokeh.plotting import * from bokeh.models import ColumnDataSource </code></pre> <h1>prepare data</h1> <pre><code>N = 300 x = np.linspace(0,4*np.pi, N) y0 = np.sin(x) y1 = np.cos(x) output_notebook() #create a column data source for the plots to share source = ColumnDataSource(data...
0
2016-09-18T09:36:24Z
39,562,869
<p>If you want to configure multiple glyphs to share data from a single <code>ColumnDataSource</code>, then you always need to configure the glyph properties with the <em>names</em> of the columns, and <strong><em>not</em></strong> with the actual data literals, as you have done. In other words:</p> <pre><code>left.ci...
0
2016-09-18T21:29:55Z
[ "python", "python-3.x", "debugging", "data-visualization", "bokeh" ]
Computer guessing game
39,556,504
<pre><code>import random def start(): print "\t\t***-- Please enter Y for Yes and N for No --***" answer = raw_input("\t\t Would you like to play a Guessing Game?: ") if answer == "Y" or answer == "y": game() elif answer == "N" or answer == "n": end() def end(): print("\t\t\t **Goodbye** ") raw...
-2
2016-09-18T10:12:59Z
39,557,100
<p>If you want the computer to guess your number, you could use a function like this:</p> <pre><code>import random my_number = int(raw_input("Please enter a number between 1 and 20: ")) guesses = [] def make_guess(): guess = random.randint(1, 20) while guess in guesses: guess = random.randint(1, 20) ...
0
2016-09-18T11:22:33Z
[ "python" ]
Connecting to MySQL over SSH using Python
39,556,553
<p>I need some help adding tables from a desktop PC to an existing MySQL database (db name DB2639162) on a webserver using a python script. I have written the following script (create_db.py):</p> <pre><code>import MySQLdb from sshtunnel import SSHTunnelForwarder ssh_pwd='' ssh_usr='' mysql_pwd='' mysql_usr='' with SSH...
0
2016-09-18T10:18:56Z
39,558,723
<p>The answer is right there in the error message:</p> <blockquote> <p>2016-09-18 11:02:19,291| ERROR | Secsh channel 0 open FAILED: open failed: Administratively prohibited</p> </blockquote> <p>Running the MySQL command-line client in a shell session on a server and setting up port forwarding/tunneling are compl...
1
2016-09-18T14:28:39Z
[ "python", "mysql", "linux", "ssh" ]
Convert &#xxxx; to normal character?
39,556,554
<p>lxml.etree.parse() have generate string in utf-16 file as &amp;#xxxx; How can I convert it back?</p> <p>Opening output file in web browser is fine. However I still need regular string in output file, too.</p> <p>Example file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-16"?&gt; &lt;?xml-stylesheet type="t...
0
2016-09-18T10:19:02Z
39,557,045
<p>You need to specify the encoding when you use <em>tostring</em>:</p> <pre><code>dIn [2]: !cat "test.xml" ��&lt;?xml version="1.0" encoding="UTF-16"?&gt; &lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt; &lt;TEI.2&gt; &lt;teiHeader&gt;&lt;/teiHeader&gt; &lt;text&gt; &lt;front&gt;&lt;/front...
1
2016-09-18T11:15:27Z
[ "python", "html", "xml", "character-encoding", "lxml" ]
Generate MATLAB code from python
39,556,602
<p>I have a problem when using the <a href="http://se.mathworks.com/help/matlab/matlab-engine-for-python.html" rel="nofollow">MATLAB python engine</a>.</p> <p>I want to get approximated solutions to ODEs (using something like the <code>ode45</code> function in MATLAB) from Python, but the problem is that ODE approxima...
3
2016-09-18T10:24:05Z
39,559,459
<p><a href="https://www.mathworks.com/help/matlab/ref/ode45.html" rel="nofollow"><code>odefun</code> passed to <code>ode45</code>, according to docs, has to be a function handle</a>.</p> <blockquote> <p>Solve the ODE</p> <p>y' = 2t</p> <p>Use a time interval of [0,5] and the initial condition y0 = 0.</p> <...
1
2016-09-18T15:39:40Z
[ "python", "matlab", "python-3.x" ]
Django Test: error creating the test database: permission denied to copy database "template_postgis"
39,556,719
<p>I am am working on setting up Django Project for <code>running tests</code>. But I am getting below error:</p> <pre><code>Got an error creating the test database: permission denied to copy database "template_postgis" </code></pre> <p><strong>Note</strong>: My default application's database is working fine. The <co...
0
2016-09-18T10:36:40Z
39,556,765
<p>I finally found how to fix this issue. The problem is that when I created <code>template_postgis</code>, I didn’t set it to be a <code>template</code>.</p> <p>You can check it doing:</p> <pre><code>SELECT * FROM pg_database; </code></pre> <p>You can fix it doing:</p> <pre><code>update pg_database set datistemp...
0
2016-09-18T10:42:28Z
[ "python", "django", "postgis", "django-testing", "geodjango" ]
Django Test: error creating the test database: permission denied to copy database "template_postgis"
39,556,719
<p>I am am working on setting up Django Project for <code>running tests</code>. But I am getting below error:</p> <pre><code>Got an error creating the test database: permission denied to copy database "template_postgis" </code></pre> <p><strong>Note</strong>: My default application's database is working fine. The <co...
0
2016-09-18T10:36:40Z
39,556,812
<p>Install packages first correctly.</p> <pre><code>sudo apt-get update sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib </code></pre> <p>During installation postgres user is created automatically. </p> <pre><code> sudo su - postgres </code></pre> <p>You should now be in a shell se...
0
2016-09-18T10:48:07Z
[ "python", "django", "postgis", "django-testing", "geodjango" ]
Python: Does 'kron' create sparse matrix when I use ' from scipy.sparse import * '?
39,556,910
<p>For the code below, Mat is a array-type matrix,</p> <pre><code>a = kron(Mat,ones((8,1))) b = a.flatten() </code></pre> <p>If I don't import scipy.sparse package, <code>a</code> is an <strong>array-type matrix</strong>, <code>b</code> can also be executed. If I use 'from scipy.sparse import *', <code>a</code> is a ...
0
2016-09-18T10:59:33Z
39,557,562
<p><code>from module import *</code> is generally considered bad form in application code, for the reason you're seeing - it makes it very hard to tell which modules functions are coming from, especially if you do this for more than one module</p> <p>Right now, you have:</p> <pre><code>from numpy import * # from scip...
2
2016-09-18T12:17:05Z
[ "python", "numpy", "matrix", "scipy", "sparse-matrix" ]
How do I override django admin's default file upload behavior?
39,556,939
<p>I need to change default file upload behavior in django and the documentation on the django site is rather confusing. </p> <p>I have a model with a field as follows:</p> <pre><code>class document (models.Model): name = models.CharField(max_length=200) file = models.FileField(null=True, upload_to='uploads/'...
0
2016-09-18T11:03:04Z
39,560,147
<p>One option could be to do the <code>.json</code> file generation on the (model) form used to initially upload the file. Override the <code>save()</code> method of the <code>ModelForm</code> to generate the file immediately after the model has been saved.</p> <pre><code>class DocumentForm(forms.ModelForm): class...
1
2016-09-18T16:42:54Z
[ "python", "django" ]
Export the list of file name from CSV file and copy to another directory with python
39,557,016
<p>i have one csv file that include the list of file: nome Desert Hydrangeas Jellyfish Koala Lighthouse Penguins Tulips I would like to create one script with python for copy this list of file from one directory to another directory, i can do this :</p> <pre><code>import csv import os import shutil source = os.listdir...
-1
2016-09-18T11:11:59Z
39,561,009
<p>The issue is that <code>os.listdir()</code> returns a <em>list</em> of files contained in the directory that you give it - in this case "C:\test".</p> <p>Later on, when you then try and concatenate <code>source</code> with the individual files, you are therefor attempting to combine a list with a str. This is why y...
0
2016-09-18T18:10:38Z
[ "python", "csv" ]
Export the list of file name from CSV file and copy to another directory with python
39,557,016
<p>i have one csv file that include the list of file: nome Desert Hydrangeas Jellyfish Koala Lighthouse Penguins Tulips I would like to create one script with python for copy this list of file from one directory to another directory, i can do this :</p> <pre><code>import csv import os import shutil source = os.listdir...
-1
2016-09-18T11:11:59Z
39,562,623
<p>I resolve my problem with this code:</p> <pre><code>import csv import os import shutil source = "C:\Test" destination = "C:\Test1" with open('semplice1.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['nome']) shutil.copyfile(os.path.join(source, ...
0
2016-09-18T20:58:50Z
[ "python", "csv" ]
Creating lmdb file in the right way
39,557,118
<p>I'm trying to create an lmdb file that contains all of my database images (in order to train CNN).</p> <p>This is my 'test code', that I took from <a href="http://deepdish.io/2015/04/28/creating-lmdb-in-python/" rel="nofollow">here</a>:</p> <pre><code>import numpy as np import lmdb import caffe import cv2 import g...
0
2016-09-18T11:24:25Z
39,582,450
<p>str_id is the internal name of the data set (e.g. one JPG image) used inside the LMDB. It's derived from the path and sequence number <strong>i</strong>.</p> <p><strong>tobytes</strong> ... here, let me <a href="https://docs.python.org/3/library/array.html?highlight=tobytes#array.array.tobytes" rel="nofollow">sear...
1
2016-09-19T21:31:27Z
[ "python", "database", "neural-network", "caffe", "lmdb" ]
Creating lmdb file in the right way
39,557,118
<p>I'm trying to create an lmdb file that contains all of my database images (in order to train CNN).</p> <p>This is my 'test code', that I took from <a href="http://deepdish.io/2015/04/28/creating-lmdb-in-python/" rel="nofollow">here</a>:</p> <pre><code>import numpy as np import lmdb import caffe import cv2 import g...
0
2016-09-18T11:24:25Z
39,627,172
<p>You can use the <a href="https://github.com/LMDB/lmdb/blob/mdb.master/libraries/liblmdb/mdb_dump.c" rel="nofollow">mdb_dump</a> tool to inspect the contents of the database.</p>
1
2016-09-21T21:54:04Z
[ "python", "database", "neural-network", "caffe", "lmdb" ]
save some variables in tensorflow
39,557,122
<p>I am trying to save some variable ( weights and biases) to use them later but i have detected error, i don't know if my steps is right or not :</p> <pre><code>graph = tf.Graph() with graph.as_default(): weights = { 'wc1_0': tf.Variable(tf.random_normal([patch_size_1, patch_size_1, num_channels, depth],stdd...
0
2016-09-18T11:24:54Z
39,558,932
<p>You defined two dictionaries: 1 for weights and 1 for biases. You have filled the dictionaries with Tensorflow variables objects.. So, why don't you use them?</p> <pre><code> conv_1 = tf.nn.conv2d(data, weights['wc1_0'] , [1, 2, 2, 1], padding='SAME') hidden_1 = tf.nn.relu(conv_1 + biases['bc1_0']) pool_1 ...
1
2016-09-18T14:48:23Z
[ "python", "tensorflow", "convolution" ]
Python 2.7 conversion to 3
39,557,125
<p>I found a code snippet online, that would be able to display sensor readings from an android phone, but I need this to run on Python 3. And I have no idea how to fix it:</p> <pre><code># ------------------------------------------------------- import socket, traceback, string from sys import stderr host = '' port =...
0
2016-09-18T11:25:21Z
39,557,216
<p>you're trying to split <code>bytes</code> object</p> <p>convert it back to a string like this, by decoding the bytes back to a string</p> <pre><code>data = data.decode() # you can also specify the encoding of the string if it's not unicode data = message.split(",") </code></pre> <p>this is a demonstration of what...
1
2016-09-18T11:35:31Z
[ "python", "python-2.7" ]
Vim huge delay when inserting newline after complex strings
39,557,163
<p>Vim takes an annoyingly noticeable long time to insert a newline (<code>o</code> in normal mode or return key in insert mode) when inserted at the end of a specific code block that could be considered complex.</p> <p>How would I go about identifying the cause and fixing the problem?</p> <h1>Case-specific informati...
1
2016-09-18T11:29:49Z
39,571,883
<p>It's likely related to syntax highlighting; check whether the delay is gone after <code>:syntax off</code>.</p> <p>If your Vim version (recent ones with "huge" features) supports the <code>:syntime</code> command, you can dive deeper; cp. <code>:help :syntime</code>.</p> <p>This may turn up a pattern that is respo...
1
2016-09-19T11:16:34Z
[ "python", "vim", "archlinux" ]
The newest file after unpacking file [python]
39,557,187
<p>When I'm unpack file, it is not the newest. Is there any chance to upack file and change its name so it is the newest file in the directory?</p> <pre><code>print newest() #prints myFile.rar if newest().endswith('.rar') or newest().endswith('.zip') : patoolib.extract_archive(newest(), outdir=".") #myFile.r...
0
2016-09-18T11:32:15Z
39,588,482
<p>It is really easy. After I unpack the file I just use function os.utime so unpacked file is the newest one in a directory :) ts = time.time() os.utime("/home/es/ajo/files/all")), (ts, ts)) It changes modified date. </p>
0
2016-09-20T07:48:29Z
[ "python", "python-2.7", "file" ]
Set limit feature_importances_ in DataFrame Pandas
39,557,194
<p>I want to set a limit for my feature_importances_ output using DataFrame. Below is my code (refer from this <a href="https://statcompute.wordpress.com/2012/12/05/learning-decision-tree-in-scikit-learn-package/" rel="nofollow">blog</a>):</p> <pre><code>train = df_visualization.sample(frac=0.9,random_state=639) test...
1
2016-09-18T11:32:49Z
39,559,040
<p>Try this: </p> <pre><code>indices = np.argsort(dt.feature_importances_)[::-1] for i in range(5): print " %s = %s" % (feature_cols[indices[i]], dt.feature_importances_[indices[i]]) </code></pre>
0
2016-09-18T14:58:53Z
[ "python", "dataframe" ]
remove a contour from image using skimage
39,557,205
<p>I want to remove some contour from an image but I don't know how to achieve it using <code>skimage</code>? I do something like this in <code>OpenCV</code> using <code>drawContour</code> but I can't find the equivalent in <code>skimage</code>.</p> <p>Assume I have a simple image like:</p> <pre><code>0 0 0 0 0 0 0 0...
0
2016-09-18T11:34:01Z
39,558,221
<p>skimage have equivalent function: </p> <pre><code>contours=skimage.measure.find_contours(array, level, fully_connected='low', positive_orientation='low') </code></pre> <p>find_countours return value is an array of numpy arrays each of which contain specific contour. Then you can just select specific contour by ind...
0
2016-09-18T13:36:52Z
[ "python", "image-processing", "skimage" ]
Is there a debugger tool that shows the value of a variable?
39,557,207
<p>I am looking for a debugger tool that helps me find what causes the error in my program?</p> <p>Usually to debug I use the <strong>print(variable) function</strong> to see what the value of a certain variable is at a given time. Hence I can see where and when something goes wrong. However, this takes way too long i...
0
2016-09-18T11:34:16Z
39,557,347
<p>Yes, Pycharm has built-in debugging capabilities. First, set the breakpoint at the point (line) you would like to see the variable. In your case that would have to be after the <code>del y[2]</code> line, as this is the point that the <code>del</code> would have effect:</p> <p>y = "otito" y = list(y) del y[2] y ...
0
2016-09-18T11:51:03Z
[ "python", "debugging", "pycharm" ]
Scrapy SgmlLinkExtractor how to define rule with regex
39,557,231
<p>I have a link like <code>http://www.example.com/kaufen/105975478</code></p> <p>I only want to allow links that have "/kaufen/" in the url and which contain a 9 digit integer number at the end of the url. </p> <p>I managed to allow only links containing "/kaufen/" with the following allow statement:</p> <pre><code...
1
2016-09-18T11:36:46Z
39,557,379
<p>You can use <code>\/kaufen\/[0-9]{9}</code></p> <ul> <li><code>\/kaufen\/</code> means /kaufen/ litteraly</li> <li><code>[0-9]{9}</code> means 9 number chars</li> </ul> <p><a href="https://regex101.com/r/tH5pC7/1" rel="nofollow">https://regex101.com/r/tH5pC7/1</a></p> <p><div class="snippet" data-lang="js" data-h...
2
2016-09-18T11:54:04Z
[ "python", "regex", "scrapy" ]
Scrapy SgmlLinkExtractor how to define rule with regex
39,557,231
<p>I have a link like <code>http://www.example.com/kaufen/105975478</code></p> <p>I only want to allow links that have "/kaufen/" in the url and which contain a 9 digit integer number at the end of the url. </p> <p>I managed to allow only links containing "/kaufen/" with the following allow statement:</p> <pre><code...
1
2016-09-18T11:36:46Z
39,557,544
<p>You can use:</p> <pre><code>allow=(r'kaufen/\d+$') </code></pre>
1
2016-09-18T12:14:57Z
[ "python", "regex", "scrapy" ]
how can I best translate this java method to python
39,557,242
<p>how can i write less python2 code to achieve the same thing,need encryption results are the same.</p> <p><code>b[i++] = (byte) 172;</code> In what way cast int to byte in python2....</p> <pre><code>public static String encryptPassword(String content) { String resultString = ""; String appkey = "ftj...
1
2016-09-18T11:37:51Z
39,566,552
<p>Use <code>chr</code> to get the char of a byte in python.</p> <pre><code>from Crypto.Hash import MD5 key = 'ftjf,ckdfkl' src= '123' b = src+chr(172)+chr(163)+chr(161)+chr(163)+key md5 = MD5.new() md5.update(b) text = md5.hexdigest() print text </code></pre> <p>Given the src '123',output is:</p> <pre><code>eedb36...
0
2016-09-19T06:21:10Z
[ "java", "python", "python-2.7", "python-3.x" ]
rolling apply in pandas shows "TypeError: only length-1 arrays can be converted to Python scalars"
39,557,313
<p>Dataframe <code>df_implied_full</code> has several columns, one of them is called <code>'USDZARV1Y Curncy'</code>, and it has only <code>floats</code>.</p> <p>This code works:</p> <pre><code>mad = lambda x: np.median(np.fabs(x - np.median(x))) df_implied_full['madtest'] = df_implied_full...
1
2016-09-18T11:46:45Z
39,557,459
<p>There is problem output of <code>x</code> in <code>lambda x: (x ...</code> is <code>numpy array</code>, so if use only <code>test = lambda x: x</code> numpy array cannot be converted to scalar values per each row. I think you need return scalar value only e.g. use <code>x[0]</code> or <code>np.median(x)</code>. The ...
1
2016-09-18T12:04:50Z
[ "python", "arrays", "function", "pandas", "median" ]
How can i read the text between xml tags using xml.etree.Elementree ?If the xml is complex
39,557,384
<pre><code>&lt;GeocodeResponse&gt; &lt;status&gt;OK&lt;/status&gt; &lt;result&gt; &lt;type&gt;locality&lt;/type&gt; &lt;type&gt;political&lt;/type&gt; &lt;formatted_address&gt;Chengam, Tamil Nadu 606701, India&lt;/formatted_address&gt; &lt;address_component&gt; &lt;long_name&gt;Chengam&lt;/long_name&gt; &lt;short_name&...
0
2016-09-18T11:54:51Z
39,557,421
<p>You almost got it. Change <code>root.find(".//geometry/location")</code> to <code>root.find(".//geometry/location/lat")</code>:</p> <pre><code>lat = root.find(".//geometry/location/lat") print(lat.text) &gt;&gt; 12.3067864 </code></pre> <p>Same goes for <code>lng</code> of course:</p> <pre><code>lng = root.find("...
1
2016-09-18T12:00:21Z
[ "python", "xml.etree" ]
Output not showing entirely in Python
39,557,405
<p>The output when running a simple code breaks and is not entirely shown. What are the options to avoid the breaks?</p> <pre><code>22 December 23, 1989, Saturday, Late Edition - Final 23 December 22, 1989, Friday, Late Edition - Final 24 December 21, 1989, Thursday, Late Edition - Final 25 December ...
1
2016-09-18T11:57:13Z
39,557,507
<p>You need to change the display width for pandas. The option you are looking for is <code>pd.set_option('display.width', 2000)</code>, but you may also find some other pandas options helpful which I use regularily:</p> <pre><code>pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.s...
2
2016-09-18T12:10:55Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>ye...
0
2016-09-18T12:02:15Z
39,557,451
<p>For slicing to work (<code>year[-2:]</code>) you should not convert <code>year</code> to <code>int</code> (ie <code>year</code> needs to be a string):</p> <pre><code>year = '2016' year[-2:] &gt;&gt; '16' </code></pre>
1
2016-09-18T12:04:08Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>ye...
0
2016-09-18T12:02:15Z
39,557,481
<p>you can use <code>year%100</code> to only get the digits within a century:</p> <pre><code>&gt;&gt;&gt; 2000%100 0 &gt;&gt;&gt; 2013%100 13 &gt;&gt;&gt; 1985%100 85 &gt;&gt;&gt; 1997%100 97 </code></pre>
2
2016-09-18T12:07:20Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>ye...
0
2016-09-18T12:02:15Z
39,557,656
<p>You want a function which takes the year as input and returns the last two digits as output.</p> <p>Since the last two digits may start with a <code>0</code>, you need to return the output as a string.</p> <hr> <p>Assuming that the input is an integer, here is one way for implementing it:</p> <pre><code>def Trun...
0
2016-09-18T12:30:22Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>ye...
0
2016-09-18T12:02:15Z
39,557,818
<p>You don't validate the input so using slicing or modulo could give you nonsensical output, you should use a while loop and verify the user enters a year in some realistic range which if you go by the <a href="https://en.wikipedia.org/wiki/List_of_the_verified_oldest_people" rel="nofollow">verified oldest person in t...
0
2016-09-18T12:50:40Z
[ "python" ]
How to have a conversation with a bot?
39,557,488
<p>I want to send a <a href="https://python-telegram-bot.org" rel="nofollow">python telegram bot</a> a specific command that causes the bot to respond with a request for more information and listen for another message containing that extra information.</p> <p>For instance:</p> <ul> <li>I send <code>/add</code> the bo...
-3
2016-09-18T12:07:49Z
39,566,732
<p>You can make a list of those things. So, when you say your torrent link he adds it to the list using yourlistname.append(yourtorrentlinkinput)</p>
-1
2016-09-19T06:34:18Z
[ "python", "bots", "python-telegram-bot" ]
How to have a conversation with a bot?
39,557,488
<p>I want to send a <a href="https://python-telegram-bot.org" rel="nofollow">python telegram bot</a> a specific command that causes the bot to respond with a request for more information and listen for another message containing that extra information.</p> <p>For instance:</p> <ul> <li>I send <code>/add</code> the bo...
-3
2016-09-18T12:07:49Z
39,567,979
<p>In this case I would look into <a href="https://pythonhosted.org/python-telegram-bot/telegram.ext.conversationhandler.html?module-telegram.ext.conversationhandler" rel="nofollow">ConversationHandler</a></p>
0
2016-09-19T07:53:08Z
[ "python", "bots", "python-telegram-bot" ]
Extract data from multiple bracket string in Pandas and create new table
39,557,680
<p>I am trying to build a 2 x 24 table in pandas with the following data below: </p> <pre><code>d.iloc[0:2] = [[0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L], [0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 0L, 0L, 0L]] </code></pre...
0
2016-09-18T12:34:05Z
39,557,783
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code></a> with apply <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></...
1
2016-09-18T12:47:28Z
[ "python", "pandas", "data-structures", "extract", "reshape" ]
Using findall and clickall without getting an error if image doesn't exit
39,557,746
<p>I can't figure out what I'm doing wrong. The code works great as long as there is an image displayed for the <code>findall</code>, but if <code>x</code> doesn't appear, then I get an error: </p> <p><code>[error] FindFailed ( can not find P(1474201252795.png) S: 0.99 in R[0,0 1920x1080]@S(0) )</code></p> <p>Not qui...
1
2016-09-18T12:43:31Z
39,558,830
<p>As per documentation <code>findAll</code> throws an Exception on failed search. (<a href="https://github.com/sikuli/sikuli/blob/develop/sikuli-script/src/main/java/org/sikuli/script/Region.java#L434" rel="nofollow">docs</a>). Try to use <code>hasNext()</code> method along with context manager, e.g.</p> <pre><code>w...
0
2016-09-18T14:37:48Z
[ "python", "jython", "sikuli" ]
Using findall and clickall without getting an error if image doesn't exit
39,557,746
<p>I can't figure out what I'm doing wrong. The code works great as long as there is an image displayed for the <code>findall</code>, but if <code>x</code> doesn't appear, then I get an error: </p> <p><code>[error] FindFailed ( can not find P(1474201252795.png) S: 0.99 in R[0,0 1920x1080]@S(0) )</code></p> <p>Not qui...
1
2016-09-18T12:43:31Z
39,568,944
<p>Use try/catch</p> <pre><code>private boolean exists(Pattern img, int sec) { try { window.wait(img, sec); return true; } catch (FindFailed exception) { return false; } } </code></pre>
0
2016-09-19T08:48:32Z
[ "python", "jython", "sikuli" ]
Using findall and clickall without getting an error if image doesn't exit
39,557,746
<p>I can't figure out what I'm doing wrong. The code works great as long as there is an image displayed for the <code>findall</code>, but if <code>x</code> doesn't appear, then I get an error: </p> <p><code>[error] FindFailed ( can not find P(1474201252795.png) S: 0.99 in R[0,0 1920x1080]@S(0) )</code></p> <p>Not qui...
1
2016-09-18T12:43:31Z
39,800,821
<p>Another way to avoid the error is to check if the image exist before using findAll:</p> <pre><code>if exists("image_in_findAll.png"): for x in findAll("image.png"): ... </code></pre>
0
2016-09-30T22:14:45Z
[ "python", "jython", "sikuli" ]
Transforming visualization from Seaborn to Bokeh
39,557,758
<p>I want the similar visualization as shown below using <strong>Bokeh</strong>. As I am new to <strong>Bokeh</strong> , I might be wondering is there any code that is as concise as the below one using <strong>Seaborn</strong> ?</p> <p><strong><em>My main focus is how to write code for same visualization in Bokeh</em>...
3
2016-09-18T12:45:05Z
39,562,767
<p>The above charts are certainly <em>possible</em> with Bokeh, in the sense that Bokeh could draw them, without any question. But it would take some work, and require more code, than with Seaborn. Basically you'd have to compute all the coordinates and set up all the glyphs "by hand". As of Bokeh <code>0.12.2</code>, ...
2
2016-09-18T21:17:34Z
[ "python", "data-visualization", "linear-regression", "seaborn", "bokeh" ]
How to write a binary file filled with zeros as binary digits?
39,557,788
<p>How can I write a binary file filled with zeros as binary digits? </p> <p>For example I have 8 bits of zeros like 00000000 which will be saved as one byte.</p>
-1
2016-09-18T12:47:43Z
39,557,807
<p>Files are sequences of bytes, and Python trivially lets you write bytes. Just write <code>\x00</code> characters to produce byes that consist of nothing but <code>0</code> bits.</p> <p>Open the file as binary and just write as many such bytes as you need:</p> <pre><code>with open(filename, 'wb') as binfile: bi...
0
2016-09-18T12:49:38Z
[ "python", "binary" ]
NameError:my function has not be defined
39,557,798
<p>This is my python code in ipython notebook</p> <pre><code>import sys sys.path.append('C:/Users/dell/.ipynb_checkpoints/bsm_functions.py') tol=0.5 for option in options_data.index: forward=futures_data[futures_data['MATURITY']==\ options_data.loc[option]['MATURITY']]['PRICE'].values[0] if(forward*...
-1
2016-09-18T12:48:42Z
39,557,825
<p>You need to <strong>import</strong> your module. You add the <em>parent directory</em> of a module to your <code>sys.path</code>, then import names from the module:</p> <pre><code>sys.path.append('C:/Users/dell/.ipynb_checkpoints') from bsm_functions import bsm_call_imp_vol </code></pre> <p>Adding the path to a <c...
2
2016-09-18T12:51:21Z
[ "python" ]
Python recursion variable state
39,557,886
<p>I'm trying to write a Python function to take a string and a number and return a list containing repetitions of the string. For example</p> <pre><code>print func(3, 'aaa') </code></pre> <p>returns</p> <pre><code>['aaa', 'aaa', 'aaa'] </code></pre> <p>This is what I've done so far:</p> <pre><code>def func(times,...
2
2016-09-18T12:59:39Z
39,557,917
<p>You need a base case where times is 0, there you can just return an empty list:</p> <pre><code>def func(times, data): if times == 0: return [] # no need for split, just wrap data in a list. return [data] + func(times-1, data) </code></pre> <p>In your code when times == 0, your function implici...
5
2016-09-18T13:02:52Z
[ "python" ]
Python recursion variable state
39,557,886
<p>I'm trying to write a Python function to take a string and a number and return a list containing repetitions of the string. For example</p> <pre><code>print func(3, 'aaa') </code></pre> <p>returns</p> <pre><code>['aaa', 'aaa', 'aaa'] </code></pre> <p>This is what I've done so far:</p> <pre><code>def func(times,...
2
2016-09-18T12:59:39Z
39,558,373
<p>While @Padraic Cunningham has a good answer, here is a simple way to do it:</p> <pre><code>def func(number, content): return [content] * number </code></pre> <p>Or list comprehension:</p> <pre><code>def func(number, content): return [content for _ in range(number)] </code></pre>
0
2016-09-18T13:54:12Z
[ "python" ]
Is it possible to run just through the item pipeline without crawling with Scrapy?
39,557,896
<p>I have a <code>.jl</code> file with items I've scraped. I have another pipeline now which was not present when I was doing the scraping. Is it possible to run just the pipeline, and have it apply the new pipeline without doing the crawl/scrape again?</p>
0
2016-09-18T13:00:35Z
39,558,345
<p>Quick answer: Yes.</p> <p>To bypass the downloader while having other components of scrapy working, you could use a customized downloader middleware which returns <code>Response</code> objects in its <code>process_request</code> method. Check the details: <a href="http://doc.scrapy.org/en/latest/topics/downloader-m...
2
2016-09-18T13:50:12Z
[ "python", "scrapy" ]
Print in getter of a property not working?
39,558,027
<p>I am new to python, currently trying to learn properties. </p> <pre><code>class Car(object): def set_speed(self, speed): self._speed = speed print("set speed to {}".format(self.speed)) def get_speed(self): return self._speed print("the speed is {}".format(self.speed)) ...
0
2016-09-18T13:15:08Z
39,558,038
<p>You used a <code>return</code> statement <em>before</em> the <code>print()</code> call. The function execution <em>ends</em> at that point, the <code>print()</code> is never reached:</p> <pre><code>def get_speed(self): # return ends a function return self._speed # anything beyond this point is ignored ...
7
2016-09-18T13:16:20Z
[ "python", "properties" ]
How to add each element in two vectors with Theano?
39,558,303
<p>I would like to know how to add each element in two vectors with Theano?</p> <p>Assume that we have two vector <em>vector_1</em> and <em>vecotr_2</em>, and we would like to construct a matrix <em>A</em>, where</p> <blockquote> <p><em>A[i][j]</em> = <em>vector_1[i]</em> + <em>vecotr_2[j]</em></p> </blockquote> <...
1
2016-09-18T13:46:21Z
39,559,410
<p>You can make use of broadcasting. Here is an example in NumPy, you can do the same in Theano:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x1 = np.array([1,1,9]).reshape((3,1)) &gt;&gt;&gt; x2 = np.array([0,3,4]).reshape((1,3)) &gt;&gt;&gt; np.add(x1, x2) array([[ 1, 4, 5], [ 1, 4, 5], ...
0
2016-09-18T15:34:08Z
[ "python", "theano", "theano.scan" ]
How can I remove a URL channel from Anaconda?
39,558,316
<p>Recently I needed to install PyPdf2 to one of my programs using Anaconda. Unfortunately, I failed, but the URLs that was added to Anaconda environment prohibit the updates of all the Conda libraries. Every time I tried to update anaconda it gives the following </p> <pre><code>conda update conda Using Anaconda Cloud...
2
2016-09-18T13:47:26Z
39,566,207
<p>Fortunately, I found the answer (Thanks to @cel as well).</p> <p>I navigated to <code>C:\Users\{MyUserName}\</code> Then I found a file with no name but has a strange extension (<code>.condarc</code>) I opened it with Notepad++, I found the files as below></p> <p><a href="http://i.stack.imgur.com/dPbWh.png" rel="n...
1
2016-09-19T05:55:30Z
[ "python", "anaconda", "channel", "pypdf2" ]
How can I remove a URL channel from Anaconda?
39,558,316
<p>Recently I needed to install PyPdf2 to one of my programs using Anaconda. Unfortunately, I failed, but the URLs that was added to Anaconda environment prohibit the updates of all the Conda libraries. Every time I tried to update anaconda it gives the following </p> <pre><code>conda update conda Using Anaconda Cloud...
2
2016-09-18T13:47:26Z
39,596,897
<p>Expanding upon Mohammed's <a href="http://stackoverflow.com/a/39566207/1193874">answer</a>.</p> <p>All those URLs that you see in your <code>conda info</code> are your channel URLs. These are where conda will look for packages. As noted by @cel, these channels can be found in the <code>.condarc</code> file in your ...
0
2016-09-20T14:33:26Z
[ "python", "anaconda", "channel", "pypdf2" ]
How to pass error without try catch in Python-Selenium?
39,558,340
<p>In my python-Selenium code, i should use many <strong>try-catch</strong> to pass the errors, and if i don't use it, my script doesn't continue. for example if i don't use try catch, if my script doesn't find <code>desc span</code> i will have an error and i can't continue, </p> <pre><code> try : libelle1...
1
2016-09-18T13:49:57Z
39,558,743
<blockquote> <p>is there an alternative method for passing error?</p> </blockquote> <p>Yes, To avoid <code>try-catch</code> and avoid error as well try using <code>find_elements</code> instead which would return either a list of all elements with matching locator or empty list if nothing is found, you need to just c...
1
2016-09-18T14:29:59Z
[ "python", "selenium", "exception", "web-scraping", "try-catch" ]
How to enter the offset for a Caesar cipher in Python
39,558,372
<p>I have this code which is a basic Caesar cipher, the offset is set to one but I want it so that the user can enter the offset. The user should be able to say by how much the alphabet is moved across by, but it won't work if offset = input</p> <pre><code>#Caesar cipher sentance = input('Enter sentance: ') alphabet =...
0
2016-09-18T13:54:03Z
39,558,753
<p>That is probably because you did not convert the input into an integer, and practically filled <code>offset</code> with a string.</p> <p>Use <code>int(input())</code> to convert the inputted string as an integer (optional- also remember to add the original character in case they are not in the alphabet):</p> <pre>...
1
2016-09-18T14:31:26Z
[ "python", "encryption", "caesar-cipher" ]
remove parentheses created by csv.DictWriter in python
39,558,413
<p>when i'm saving a dictionary representing a graph with the format:</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>and save it with the csv.DictWriter and load it i get:</p> <pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'} </code></pre> ...
0
2016-09-18T13:58:22Z
39,558,518
<p>You have</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>Then</p> <pre><code> edges = graph_dict[vertex] writer.writerow({'vertices': vertex, 'edges': edges}) </code></pre> <p>This writes a list to the file -- it is converted to str.</p> <p>Do, for example</p>...
0
2016-09-18T14:09:11Z
[ "python", "python-3.x" ]
remove parentheses created by csv.DictWriter in python
39,558,413
<p>when i'm saving a dictionary representing a graph with the format:</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>and save it with the csv.DictWriter and load it i get:</p> <pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'} </code></pre> ...
0
2016-09-18T13:58:22Z
39,558,545
<p>CSV is not intended for nested data structures; it has no meaningful way of dealing with them (it's converting your <code>list</code> values to <code>str</code> for output).</p> <p>You either need to use a more appropriate format (e.g. JSON or <code>pickle</code>), or use horrible hacks to convert the <code>repr</c...
0
2016-09-18T14:11:38Z
[ "python", "python-3.x" ]
remove parentheses created by csv.DictWriter in python
39,558,413
<p>when i'm saving a dictionary representing a graph with the format:</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>and save it with the csv.DictWriter and load it i get:</p> <pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'} </code></pre> ...
0
2016-09-18T13:58:22Z
39,558,575
<p>You're trying to "serialize" this data using CSV, which might be appropriate if you want to analyze the file outside of Python. If not, your problem will be solved more easily with the <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle</a> module.</p> <p>If you must use CSV, make sure the...
0
2016-09-18T14:14:42Z
[ "python", "python-3.x" ]
How can I load my Aurelia app from an index.html which is not located in the same folder as the rest of the application?
39,558,580
<p>How can I load my app from an <code>index.html</code> which is not located in the same folder as the rest of the application?</p> <p>I’m currently using <code>jspm</code> (which I’m new to). I’m trying to integrate <code>Aurelia</code> with <code>web2py</code> (Python web framework). </p> <p>My <code>index.h...
0
2016-09-18T14:14:58Z
39,644,621
<p>You need to use the <a href="http://web2py.com/books/default/chapter/29/04/the-core?search=router#Pattern-based-system" rel="nofollow">web2py pattern router</a>, something like this in the router definition should work:</p> <pre><code>routes_in = ( ('/appname/default/index', '/appname/static/aurelia_app/index.htm...
0
2016-09-22T16:45:03Z
[ "javascript", "python", "web2py", "aurelia", "jspm" ]
Using set_index within a custom function
39,558,659
<p>I would like to convert the date observations from a column into the index for my dataframe. I am able to do this with the code below:</p> <p>Sample data:</p> <pre><code>test = pd.DataFrame({'Values':[1,2,3], 'Date':["1/1/2016 17:49","1/2/2016 7:10","1/3/2016 15:19"]}) </code></pre> <p>Indexing code:</p> <pre><c...
0
2016-09-18T14:22:35Z
39,558,726
<p>IIUC <code>return df</code> is missing:</p> <pre><code>df1 = pd.DataFrame({'Values':[1,2,3], 'Exam Completed Date':["1/1/2016 17:49","1/2/2016 7:10","1/3/2016 15:19"]}) def date_index(df): df['Exam Completed Date Index'] = pd.to_datetime(df['Exam Completed Date']) df = df.set_index('Exam Completed Date ...
0
2016-09-18T14:28:53Z
[ "python", "pandas" ]
Regex find whole substring between parenthesis containing exact substring
39,558,667
<p>For example I have string:</p> <pre><code>"one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" </code></pre> <p>and I need only whole substring with parenthesis, containing word <code>"back"</code>, for this string it will be:</p> <pre><code>"(87 back sack)" </code></pre> <p>I've tried:</p> ...
1
2016-09-18T14:23:31Z
39,558,763
<p>You can use this regex based on negated character class:</p> <pre><code>\([^()]*?back[^()]*\) </code></pre> <ul> <li><code>[^()]*</code> matches 0 or more of any character that is not <code>(</code> and <code>)</code>, thus making sure we don't match across the pair of <code>(...)</code>.</li> </ul> <p><a href="h...
3
2016-09-18T14:32:27Z
[ "python", "regex", "string", "substring", "parentheses" ]
Regex find whole substring between parenthesis containing exact substring
39,558,667
<p>For example I have string:</p> <pre><code>"one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" </code></pre> <p>and I need only whole substring with parenthesis, containing word <code>"back"</code>, for this string it will be:</p> <pre><code>"(87 back sack)" </code></pre> <p>I've tried:</p> ...
1
2016-09-18T14:23:31Z
39,559,021
<pre><code>h="one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" l=h.split("(") [x.split(")")[0] for x in l if ")" in x and "back" in x] </code></pre>
0
2016-09-18T14:56:12Z
[ "python", "regex", "string", "substring", "parentheses" ]
Regex find whole substring between parenthesis containing exact substring
39,558,667
<p>For example I have string:</p> <pre><code>"one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" </code></pre> <p>and I need only whole substring with parenthesis, containing word <code>"back"</code>, for this string it will be:</p> <pre><code>"(87 back sack)" </code></pre> <p>I've tried:</p> ...
1
2016-09-18T14:23:31Z
39,614,422
<p>Try the below pattern for reluctant matching</p> <p>pattern="\(.*?\)"</p>
0
2016-09-21T10:47:58Z
[ "python", "regex", "string", "substring", "parentheses" ]
Pivot Table with All the Index
39,558,733
<p>I am using python pandas to create a pivot table from df. The df looks like:</p> <p><a href="http://i.stack.imgur.com/uId4U.png" rel="nofollow"><img src="http://i.stack.imgur.com/uId4U.png" alt="enter image description here"></a></p> <p>The fields that have missing values are: Origin City, Shipment Date, Volume an...
1
2016-09-18T14:29:27Z
39,558,860
<p>You can use <code>ffill</code>, what is same as <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>Series.fillna</code></a> with <code>method='ffill'</code>:</p> <pre><code>print (df) DC Landing date Volume 0 MAR 02-09-16 50.0 1 MAR 03-09-...
0
2016-09-18T14:40:39Z
[ "python", "python-2.7", "pandas", "pivot", "pivot-table" ]
If statement not firing
39,558,770
<p>This code does a recursive bisection search for a character in a string. </p> <p>When the <code>print</code> statements are not commented out, it seems to work well with the recursion and bisection, but the <code>if</code> statement that returns <code>True</code> does not seem to fire.</p> <pre><code>def isIn(cha...
0
2016-09-18T14:32:40Z
39,558,843
<p>You need to return the result of each recursive call.</p> <p>This is a very common mistake, for some reason.</p>
1
2016-09-18T14:39:08Z
[ "python" ]
If statement not firing
39,558,770
<p>This code does a recursive bisection search for a character in a string. </p> <p>When the <code>print</code> statements are not commented out, it seems to work well with the recursion and bisection, but the <code>if</code> statement that returns <code>True</code> does not seem to fire.</p> <pre><code>def isIn(cha...
0
2016-09-18T14:32:40Z
39,559,031
<p>You shouldn't be using <code>round</code> in whatever that calculation is, as then you are using a <code>float</code> instead of an <code>int</code> as the index to the string.<br> use <code>int</code> instead:</p> <pre><code>str(b[int(c/2)])) </code></pre>
0
2016-09-18T14:57:41Z
[ "python" ]
If statement not firing
39,558,770
<p>This code does a recursive bisection search for a character in a string. </p> <p>When the <code>print</code> statements are not commented out, it seems to work well with the recursion and bisection, but the <code>if</code> statement that returns <code>True</code> does not seem to fire.</p> <pre><code>def isIn(cha...
0
2016-09-18T14:32:40Z
39,559,140
<p>This code works, has return before the recursive function calls:</p> <pre><code>def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' b = sorted(aStr) c = len(aStr) # print("string b " + str(b)) # print("c " + str(c)) # print("element ...
0
2016-09-18T15:07:27Z
[ "python" ]
Check if multiple lists contain multiple items
39,558,820
<p>I have a list of lists in my python code, and I want to check if <em>any</em> of those lists contains a certain two items.</p> <pre><code>f1=['a','b'] f2=['c','d'] f3=['e','f'] f4=['g','h'] f5=['i','j'] f6=['k','l'] flist=[f1,f2,f3,f4,f5,f6] </code></pre> <p>I want something like:</p> <pre><code>if 'a' in flist[...
-1
2016-09-18T14:37:10Z
39,558,962
<pre><code>for f in flist: if 'a' not in f: continue if 'b' not in f: continue return True return False </code></pre>
1
2016-09-18T14:50:17Z
[ "python", "list" ]
Check if multiple lists contain multiple items
39,558,820
<p>I have a list of lists in my python code, and I want to check if <em>any</em> of those lists contains a certain two items.</p> <pre><code>f1=['a','b'] f2=['c','d'] f3=['e','f'] f4=['g','h'] f5=['i','j'] f6=['k','l'] flist=[f1,f2,f3,f4,f5,f6] </code></pre> <p>I want something like:</p> <pre><code>if 'a' in flist[...
-1
2016-09-18T14:37:10Z
39,558,967
<p>You can use <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any</code></a> with <code>issubset</code>:</p> <pre><code>if any({'a', 'b'}.issubset(sublist) for sublist in flist): print "a and b were found" </code></pre> <p>By using <code>any</code>, the search is called off as...
3
2016-09-18T14:50:50Z
[ "python", "list" ]
Check if multiple lists contain multiple items
39,558,820
<p>I have a list of lists in my python code, and I want to check if <em>any</em> of those lists contains a certain two items.</p> <pre><code>f1=['a','b'] f2=['c','d'] f3=['e','f'] f4=['g','h'] f5=['i','j'] f6=['k','l'] flist=[f1,f2,f3,f4,f5,f6] </code></pre> <p>I want something like:</p> <pre><code>if 'a' in flist[...
-1
2016-09-18T14:37:10Z
39,558,982
<p>How about you just iterate over it.</p> <pre><code>for i in range(len(flist)): if ['a', 'b'] == sorted(flist[i]): print (i) </code></pre> <p>or you can simply do one-liner, just to know if it exists.</p> <pre><code>print (["a", "b"] in [sorted(x) for x in flist]) </code></pre>
1
2016-09-18T14:51:56Z
[ "python", "list" ]
Removing values from dataframe based on groupby condition
39,558,888
<p>I'm a bit stuck here trying to determine how to slice my dataframe.</p> <pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004], 'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh...
1
2016-09-18T14:43:50Z
39,559,062
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>SeriesGroupBy.nunique</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">boolean indexing</a> where conditi...
0
2016-09-18T15:00:50Z
[ "python", "pandas" ]
Removing values from dataframe based on groupby condition
39,558,888
<p>I'm a bit stuck here trying to determine how to slice my dataframe.</p> <pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004], 'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh...
1
2016-09-18T14:43:50Z
39,559,319
<p>Another solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> in combination with <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow"><code>groupby.filter</code></a> and filtering b...
0
2016-09-18T15:25:05Z
[ "python", "pandas" ]
Python scraping splash javascript click
39,558,904
<p>I'm trying to use Splash to renderer a webpage with javascript content. I'm using lxml to parse the result. I need to expand hidden menus. I've found the method to click on element but I don't know how I can click on each result from an xpath search.</p> <p>Below my xpath filter. </p> <p>//div[contains(@class,'cli...
1
2016-09-18T14:45:47Z
39,610,148
<p>Here I will explain you how to get all submenu.</p> <p><a href="https://angel.co/new_tags/list_children?tag_id=data-tag_id" rel="nofollow">https://angel.co/new_tags/list_children?tag_id=data-tag_id</a> eg. <a href="https://angel.co/new_tags/list_children?tag_id=9217" rel="nofollow">https://angel.co/new_tags/list_ch...
0
2016-09-21T07:31:15Z
[ "javascript", "python", "xpath", "splash" ]
ComboBox not present in TK
39,558,908
<p>According to the docs there should be a <code>ComboBox</code> operation in TK, but I can't find it. <code>dir(tk)</code> shows</p> <blockquote> <p>['ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'At', 'AtEnd', 'AtInsert', 'AtSelFirst', 'AtSelLast', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', 'Bitmap...
0
2016-09-18T14:46:17Z
39,558,955
<p>There is no <code>ComboBox</code> widget in <code>tkinter</code>, what you are looking for is <code>tkinter.ttk</code> (in Python 3, in Python 2 it's just called <code>ttk</code>), which provides themed tk widgets. <a href="https://docs.python.org/3.1/library/tkinter.ttk.html" rel="nofollow">Docs for <code>tkinter.t...
2
2016-09-18T14:49:38Z
[ "python", "tkinter", "combobox" ]
Skip part of superclass __init__?
39,558,956
<p>I have a class which subclass another. I would like to skip a part of the initialization process, for example:</p> <pre><code>class Parent: __init__(self, a, b, c, ...): # part I want to keep: self.a = a self.b = b self.c = c ... # part I want to skip, which is me...
1
2016-09-18T14:49:43Z
39,559,015
<p>What about wrapping creation of <code>Q</code> into private method, and overriding that method in subclass?</p> <pre><code>class Parent: def __init__(self, a, b, c, ...): # part I want to keep: self.a = a self.b = b self.c = c self._init_q() def _init_q(): se...
4
2016-09-18T14:55:51Z
[ "python", "inheritance" ]
Determine why WTForms form didn't validate
39,558,984
<p>I called <code>form.validate_on_submit()</code>, but it returned <code>False</code>. How can I find out why the form didn't validate?</p>
0
2016-09-18T14:52:14Z
39,559,508
<p>For the whole form, <code>form.errors</code> contains a map of fields to lists of errors. If it is not empty, then the form did not validate. For an individual field, <code>field.errors</code> contains a list of errors for that field. The list is the same as the one in <code>form.errors</code>.</p> <p><code>form...
1
2016-09-18T15:45:21Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,559,322
<p>The simplest code to do so, would probably be (in pseudo code):</p> <pre><code>function find_missing(input) sort!(input) # in-place sort, should take most of the time val = 0 for d in input # go over sorted input if d == val val += 1 end if d &gt; val ...
3
2016-09-18T15:25:18Z
[ "python", "algorithm" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,560,512
<p>I am not really sure whether I understand your question fully. However, from what I understand, you have an array of integers and an input (which is also integers).</p> <pre><code>set_of_integers = set(array_of_integers) for input_item in input: if input_item not in set_of_integers: print(input_item) <...
0
2016-09-18T17:19:18Z
[ "python", "algorithm" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,563,838
<p>You haven't specified how you know what the original set of values is, so I'm going to go ahead and just assume that you have two lists of values, <code>set1</code> and <code>set2</code>, which may or may not contain duplicates, may or may not be in the same order, and differ by a single element which you wish to id...
0
2016-09-19T00:21:08Z
[ "python", "algorithm" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,567,381
<p>I go with Dan Getz assumption of the problem. Dan's solution gives you in the worst case O(n log n) runtime. </p> <p>Now the crazy idea: How about skipping the sorting part that is the "heaviest" overhead O(n log n)? Instead of starting with the sorting, just maintain a <code>Hashmap</code> of ALL 4 byte positive i...
0
2016-09-19T07:15:52Z
[ "python", "algorithm" ]
Append row with counts in PANDAS
39,559,054
<p>I have a data frame with categorical data structured in the following way:</p> <pre><code>index A B C D ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 </code></pre> <p>I would like to append a row which sums only the instances of <code>"1"</code>. The desired result would...
1
2016-09-18T15:00:04Z
39,559,101
<p>You can sum boolean mask <code>df == 1</code>:</p> <pre><code>print (df == 1) A B C D index ind1 False False True False ind2 True False False False ind3 False True False False df.loc['count1'] = (df == 1).sum() print (df) A B C D ...
2
2016-09-18T15:03:59Z
[ "python", "pandas", "sum", "append", "condition" ]
Append row with counts in PANDAS
39,559,054
<p>I have a data frame with categorical data structured in the following way:</p> <pre><code>index A B C D ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 </code></pre> <p>I would like to append a row which sums only the instances of <code>"1"</code>. The desired result would...
1
2016-09-18T15:00:04Z
39,559,110
<p>Not sure if you want to sum over the <code>1s</code> or if you want to count the 1s. This assumes that the <code>dtype</code> is not <code>object</code>. If it is only @jezrael's solution will work if you check against <code>'1'</code> rather than <code>1</code>.</p> <p>To sum over the 1s:</p> <pre><code>sr = df.w...
0
2016-09-18T15:04:40Z
[ "python", "pandas", "sum", "append", "condition" ]
SQLite3 query ORDER BY parameter with ? notation
39,559,072
<p>I am trying to make a query with sqlite3 in python, to be ordered by a parameter column "overall_risk" or "latest_risk" (which is double number)</p> <pre><code>param = ('overall_risk',) cur = db.execute("SELECT * FROM users ORDER BY ? DESC", param) </code></pre> <p>However, I doesn't return the data ordered by <co...
0
2016-09-18T15:01:36Z
39,559,103
<p>SQL parameters can't be used for anything other than <em>values</em>. The whole point in using a placeholder is to have the value properly quoted to avoid it from being interpreted as part of a SQL statement or as an object.</p> <p>You are trying to insert an object name, not a value, so you can't use <code>?</code...
3
2016-09-18T15:04:07Z
[ "python", "sqlite3" ]
PySide:QWebView's Mouse move and Mouse press events Freezing html document
39,559,334
<p>I am trying to make a QwebView window move whenever I drag the mouse within the window (not the title bar) while at the same time events in the html documents can trigger.</p> <p>Here is my implementation of it</p> <pre><code>import sys import json import threading from time import sleep from PySide.QtCore import ...
3
2016-09-18T15:26:15Z
39,616,062
<p>You forgot to call super methods of mouse*Event.</p> <p>Reason: Those methods are called event handler. Since you overridden it and didn't call default implementation, QWebView have no chance to know mouse states (But it was not "freezed").</p> <p><a href="https://doc.qt.io/qt-4.8/eventsandfilters.html" rel="nofol...
5
2016-09-21T12:03:04Z
[ "python", "pyqt", "pyside" ]
Append multiple values for a key from a file
39,559,372
<p>I've got a file similar to below:</p> <pre><code>t_air_sens1 laten t_air_sens1 periodic t_air_air laten t_air_air periodic ... ... </code></pre> <p>I want to make a dictionary in order to assign those values of <em>laten</em> and <em>periodic</em> to each key of <em>t_air_sens1</em> and etc. The final result must ...
1
2016-09-18T15:30:27Z
39,559,399
<p><code>line[0]</code> and <code>line[1]</code> are single characters in the string, not the current line and the next.</p> <p>File objects are iterators; the <code>for</code> loop will get new lines from it each iteration, but you can also use the <a href="https://docs.python.org/3/library/functions.html#next" rel="...
3
2016-09-18T15:33:21Z
[ "python", "dictionary", "key-value" ]
Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute
39,559,374
<p>I have a model linked to Django <code>User</code> model but when I try saving to that model using <code>User</code> instance, it says <strong>'User' object has no attribute 'mymodel_set'</strong></p> <p><strong>My models.py:</strong></p> <pre><code>from django.contrib.auth.models import User from django.db import ...
0
2016-09-18T15:30:39Z
39,559,421
<p>If the related object existed, you would use <code>mymodel</code>, but it does not exist and the relationship is void, so it cannot be accessed via the <code>user</code>. Create it first and set the relationship to that user:</p> <pre><code>mymodel = MyModel.objects.create(name=display_name, user=user) # ...
0
2016-09-18T15:35:19Z
[ "python", "django" ]
Xfce Python Dbus
39,559,383
<p>I run Xfce (Arch Linux) and I'm trying to control the power manager. I already declared the power manager but what are the methods to hibernate it and control it? Here's my code so far:</p> <pre><code>from pydbus import SessionBus bus = SessionBus power = bus.get('org.xfce.PowerManager', '/org/xfce/PowerM...
0
2016-09-18T15:31:54Z
39,626,965
<p>As Dartmouth mentioned, you need to find xfce4-power-manager's exposed methods. For that <a href="https://wiki.gnome.org/Apps/DFeet" rel="nofollow">DFeet</a> (a D-Bus debugger) will help you:</p> <p><a href="http://i.stack.imgur.com/UIOz6.png" rel="nofollow"><img src="http://i.stack.imgur.com/UIOz6.png" alt="enter ...
0
2016-09-21T21:37:05Z
[ "python", "dbus" ]
Can't "import urllib.request, urllib.parse, urllib.error"
39,559,384
<p>I trying to convert my project to python3.</p> <p>My server script is server.py:</p> <pre><code>#!/usr/bin/env python #-*-coding:utf8-*- import http.server import os, sys server = http.server.HTTPServer handler = http.server.CGIHTTPRequestHandler server_address = ("", 8080) #handler.cgi_directories = [""] httpd =...
0
2016-09-18T15:31:55Z
39,559,790
<p>Your shebang suggests that code should be run by <code>python</code> binary, which is historically associated with Python 2.x releases.</p> <p>Simply change first line to:</p> <pre><code>#!/usr/bin/env python3 </code></pre>
1
2016-09-18T16:11:09Z
[ "python", "python-3.x", "urllib", "2to3" ]
pyspark: expand a DenseVector to tuple in a RDD
39,559,401
<p>I have the following RDD, each record is a tuple of (bigint, vector):</p> <pre><code>myRDD.take(5) [(1, DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432])), (1, DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432])), (0, DenseVector([5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0])), (1, DenseVector([9....
0
2016-09-18T15:33:32Z
39,559,884
<p>Well, since <code>pyspark.ml.linalg.DenseVector</code> (or <code>mllib</code>) is iterbale (provide <code>__len__</code> and <code>__getitem__</code> methods) you can treat it like any other python collections, for example:</p> <pre><code>def as_tuple(kv): """ &gt;&gt;&gt; as_tuple((1, DenseVector([9.25, 1....
1
2016-09-18T16:19:12Z
[ "python", "apache-spark", "pyspark", "rdd" ]
Way to transfer OpenCV Mat to iPhone
39,559,521
<p>I'm doing a computer vision project on my RaspberryPi 2. The computer vision is done through the well known OpenCV library with Python bindings. I want to show a live stream of what the Raspberry Pi is doing with an iOS app.</p> <p>The images being elaborated by the Raspberry Pi are OpenCV Mats that in Python are n...
1
2016-09-18T15:45:46Z
40,052,651
<p>I solved the problem this way:</p> <ol> <li>Encoded the image Mat with <code>cv2.imencode(extension, mat)</code> function which returns a byte array with the encoded image.</li> <li>Use TCP Socket to send the generated byte array.</li> </ol> <p>Specifically:</p> <p>The function used for conversion is</p> <pre><c...
0
2016-10-14T22:04:52Z
[ "python", "ios", "swift", "opencv", "raspberry-pi" ]
How do I programmatically implement super user privileges in a script?
39,559,568
<p>I've written a python script. One of the functions opens a port to listen on. To open a port to listen on I need to do it as super user. I don't want to run the script with <code>sudo</code> or with root permissions, etc. I saw an answer here regarding sub-process using <code>sudo</code>. It's not a sub-process ...
2
2016-09-18T15:50:59Z
39,559,644
<p>You can't do that. If you could then malicious code would have free access to any system as root at any time! </p> <p>If you want super user privileges you need to run the script from the root account or use sudo and type in the password - this is the whole point of having user accounts.</p> <p>EDIT</p> <p>It is ...
0
2016-09-18T15:57:09Z
[ "python", "permissions" ]
How do I programmatically implement super user privileges in a script?
39,559,568
<p>I've written a python script. One of the functions opens a port to listen on. To open a port to listen on I need to do it as super user. I don't want to run the script with <code>sudo</code> or with root permissions, etc. I saw an answer here regarding sub-process using <code>sudo</code>. It's not a sub-process ...
2
2016-09-18T15:50:59Z
39,559,666
<p>You could use sudo inside your python script like this, so you don't have to run the script with sudo or as root.</p> <pre><code>import subprocess subprocess.call(["sudo", "cat", "/etc/shadow"]) </code></pre>
0
2016-09-18T15:59:22Z
[ "python", "permissions" ]
Reduction the Pandas dataframe to other dataframe
39,559,603
<p>I have two data frames and their shapes are (<code>707</code>,<code>140</code>) and (<code>34</code>,<code>98</code>).</p> <p>I want to minimize the bigger data frame to the small one based on the same index name and column names. </p> <p>So after the removing additional rows and columns from bigger data frame, in...
1
2016-09-18T15:53:41Z
39,559,624
<p>I think you can select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> <code>index</code> and <code>columns</code> of small <code>DataFrame</code>:</p> <pre><code>dfbig.loc[dfsmall.index, dfsmall.columns] </code></pre> <p>Sample:</p> ...
3
2016-09-18T15:55:15Z
[ "python", "pandas", "dataframe", "multiple-columns" ]
Django: ImportError: cannot import name 'User'
39,559,635
<p>I'm new to django and I'm facing some difficulties in creating a user from the AbstractBaseUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my User model</p> <pre><code>from django.db import models from django.contrib.auth.models import AbstractBaseUser class Use...
0
2016-09-18T15:56:18Z
39,559,879
<p>You didn't import from right package.</p> <p>Use:</p> <pre><code>from user_profile.models import User </code></pre>
1
2016-09-18T16:18:45Z
[ "python", "django", "django-models", "model", "django-users" ]
Subtract two lists of tuples from each other
39,559,649
<p>I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^). </p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] </code></pre> <p>Essentially what I want is:</p> <pre><code>B - A = [(0, 0), (0, 2)] </code></pre>
1
2016-09-18T15:57:29Z
39,559,657
<p>You can use list comprehension to solve this problem: </p> <pre><code>[item for item in B if item not in A] </code></pre> <p>More discussion can be found <a href="http://stackoverflow.com/questions/3428536/python-list-subtraction-operation">here</a></p>
2
2016-09-18T15:58:39Z
[ "python", "list", "tuples", "subtraction" ]
Subtract two lists of tuples from each other
39,559,649
<p>I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^). </p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] </code></pre> <p>Essentially what I want is:</p> <pre><code>B - A = [(0, 0), (0, 2)] </code></pre>
1
2016-09-18T15:57:29Z
39,559,676
<p>If there are no duplicate tuples in <code>B</code> and <code>A</code>, might be better to keep them as sets, and use the <a href="https://docs.python.org/2/library/stdtypes.html#set.difference" rel="nofollow"><code>difference</code></a> of sets:</p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] diff = set(B) ...
1
2016-09-18T16:00:17Z
[ "python", "list", "tuples", "subtraction" ]
Subtract two lists of tuples from each other
39,559,649
<p>I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^). </p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] </code></pre> <p>Essentially what I want is:</p> <pre><code>B - A = [(0, 0), (0, 2)] </code></pre>
1
2016-09-18T15:57:29Z
39,559,774
<p>You can do such operations by converting the lists to sets. Set difference:</p> <pre><code>r = set(B)-set(A) </code></pre> <p>Convert to list if necessary: list(r)</p> <p>Working on sets is efficient compared to running "in" operations on lists: <a href="http://stackoverflow.com/questions/25294897/why-is-converti...
0
2016-09-18T16:09:36Z
[ "python", "list", "tuples", "subtraction" ]
Project Euler #4 repeat of numbers generated
39,559,671
<p>I was trying to solve Project Euler Problem #4 and while I have solved it I am not satisfied with my code because it generates repeats.</p> <p>Below is the code:</p> <pre><code>pal = [] for i in range(100 ** 2, 1000 ** 2): if str(i) == str(i)[::-1]: pal.append(i) for n in pal: for x in range(100,...
0
2016-09-18T15:59:42Z
39,559,817
<p>You could you <code>set</code> or to store values just once:</p> <pre><code>pal = set() for i in range(100 ** 2, 1000 ** 2): if str(i) == str(i)[::-1]: pal.add(i) for n in pal: for x in range(100, 1000): if 99 &lt; n / x &lt; 1000 and n % x == 0: print(x, n//x, n) </code></pre>...
1
2016-09-18T16:13:46Z
[ "python", "python-3.x" ]