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
wtforms: dropdown selector with values defined in model class
38,134,701
<p>I would like to create a model for flask-wtforms where the values of the dropdown selectors are defined in the model already, as they are always the same. I tried the following:</p> <pre><code>class DroppdownForm(Form): fields = {} df = pd.read_excel(open('formfile.xlsx', 'rb'), sheetname='Sheet1') df....
0
2016-06-30T23:13:13Z
38,160,098
<p>This is the basic way you can get a dropdown form. You can process you data into a list of tuples with <code>value</code> and <code>label</code>.</p> <pre><code>class DropDown(Form): fields = [(value, label), (value, label), (value, label)...] dropdown = SelectField('Mydropdown', choices = fields) </code></...
0
2016-07-02T12:21:48Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
wtforms: dropdown selector with values defined in model class
38,134,701
<p>I would like to create a model for flask-wtforms where the values of the dropdown selectors are defined in the model already, as they are always the same. I tried the following:</p> <pre><code>class DroppdownForm(Form): fields = {} df = pd.read_excel(open('formfile.xlsx', 'rb'), sheetname='Sheet1') df....
0
2016-06-30T23:13:13Z
38,163,460
<p>try this:</p> <p>the view:</p> <pre><code>from wtforms import Form, SelectField import pandas as pd def DroppdownFormGen(**kwargs): class DroppdownForm(Form): pass df = pd.read_excel(open('MOCK_DATA.xlsx', 'rb'), sheetname='data') df.fillna(value='NA', inplace=True) form_fields = ['COLUM...
1
2016-07-02T18:50:47Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
STARTTLS extension not supported by server - Getting this error when trying to send an email through Django and a private email address
38,134,714
<p>I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.</p> <p>In my settings.py, I have these settings:</p> <pre><code>EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'contact@mysite.com' EMAIL_HOST_PASSWORD...
0
2016-06-30T23:14:36Z
38,134,738
<p>Either setup TLS on your mail server or use <code>EMAIL_USE_TLS = False</code>.</p>
1
2016-06-30T23:17:21Z
[ "python", "django", "django-email" ]
STARTTLS extension not supported by server - Getting this error when trying to send an email through Django and a private email address
38,134,714
<p>I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.</p> <p>In my settings.py, I have these settings:</p> <pre><code>EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'contact@mysite.com' EMAIL_HOST_PASSWORD...
0
2016-06-30T23:14:36Z
38,138,965
<p>your server 'mail.privateemail.com' does not know what is <code>STARTTLS</code> SMTP Commnad is</p> <p>this may happen in two cases: 1. your server (mail.privateemail.com) do not support secure communication at all and you need to use plain, non-encrypted communication 2. you are trying to connect to the port that ...
2
2016-07-01T06:58:09Z
[ "python", "django", "django-email" ]
I am trying to Scrap reviews from Amazon using Python 3.x but getting nothing
38,134,722
<p>I am trying to scrap all reviews from amazon. When I ran my code below it returns empty list without any error. I couldn't figure out why. Can you please help me.</p> <pre><code>from __future__ import unicode_literals import requests from scrapy.selector import Selector def fetch_page(url): r = requests.get(u...
1
2016-06-30T23:15:44Z
38,134,743
<p>You should not have spaces in your CSS selector between classes. Instead, use <code>.</code> to separate the classes:</p> <pre><code>.css('.a-section.review').extract() </code></pre> <p>Once you fix that, your selector will work fine:</p> <pre><code>In [6]: rev = response.css('.a-section.review').extract() In [7...
1
2016-06-30T23:17:46Z
[ "python", "scrapy", "amazon", "screen-scraping", "review" ]
difference between numpy randint and floor of rand
38,134,811
<pre><code>num_draws = int(1e6) arr1 = np.random.randint(0, 10, num_draws) arr2 = np.floor(10*np.random.rand(num_draws)) </code></pre> <p>Could someone with expertise in the internals of numpy.random comment on whether arr2 obeys formally equivalent statistics to arr1? In experiments I have done, the distributions app...
3
2016-06-30T23:26:52Z
38,135,907
<p><strong>Yes, they're equivalent</strong> <code>[1]</code></p> <p>Looking at the source code, they both are defined in auxiliary functions (<a href="https://github.com/numpy/numpy/blob/master/numpy/random/mtrand/mtrand.pyx#L1181" rel="nofollow">1</a>,<a href="https://github.com/numpy/numpy/blob/master/numpy/random/m...
1
2016-07-01T02:06:08Z
[ "python", "arrays", "numpy", "random", "scientific-computing" ]
Autoscaling the y axis when using rangeslider in Plotly
38,134,900
<p>I'm following the <code>rangeslider</code> example on the Plotly website: <a href="https://plot.ly/python/range-slider/" rel="nofollow">https://plot.ly/python/range-slider/</a></p> <p>Is there a way to automatically (or even manually) rescale the y axis as the x range changes? For example, if the date range in the ...
0
2016-06-30T23:39:44Z
38,447,038
<p>The answer to this is no according to this answer from the devs <a href="http://community.plot.ly/t/autoscaling-the-y-axis-when-using-rangeslider/1456" rel="nofollow">http://community.plot.ly/t/autoscaling-the-y-axis-when-using-rangeslider/1456</a></p>
0
2016-07-18T22:41:14Z
[ "python", "plot", "plotly" ]
Theano for GPU without use of CUDA or using a CUDA workaround
38,134,951
<p>I have an Intel Graphics Card (Intel(R) HD Graphics 520, also am on Windows 10) and as far as I know I can't use CUDA unless I have a NVIDIA GPU. The purpose is to use Theano's GPU capabilities (for deep learning which is why I need GPU power). </p> <ol> <li><p>Is there a workaround that somehow allows me to use CU...
0
2016-06-30T23:47:02Z
38,167,755
<p>In order:</p> <ol> <li>No. You must have a supported NVIDIA GPU to use CUDA.</li> <li>As pointed out in comments, there is an <a href="http://deeplearning.net/software/theano/tutorial/using_gpu.html#gpuarray-backend" rel="nofollow">alternative backend</a> for Theano which uses OpenCL and which might work on your GP...
0
2016-07-03T07:40:15Z
[ "python", "cuda", "gpu", "theano", "theano-cuda" ]
Converting String into Integer and matching to an integer
38,134,964
<p>been trying this with no luck </p> <pre><code>y = ("586MB Available") x= re.findall (r'\d+',(y)) &gt;&gt;&gt; x ['586'] if x == 586: print ('yes') else : print ("No") </code></pre> <p>No</p>
-1
2016-06-30T23:48:23Z
38,134,989
<p>You have to convert the match, which will always be a string (or bytes, if you're working with bytes) to an integer. Alternatively, compare it to a string (or bytes, again). You also have to actually look within the <code>list</code>. The following is probably the easiest way:</p> <pre><code>&gt;&gt;&gt; x = ['586'...
1
2016-06-30T23:50:58Z
[ "python", "string", "int" ]
Converting String into Integer and matching to an integer
38,134,964
<p>been trying this with no luck </p> <pre><code>y = ("586MB Available") x= re.findall (r'\d+',(y)) &gt;&gt;&gt; x ['586'] if x == 586: print ('yes') else : print ("No") </code></pre> <p>No</p>
-1
2016-06-30T23:48:23Z
38,135,094
<p>x is a list of string. You must convert the first element to an int:</p> <pre><code>int(x[0]) == 586 </code></pre> <p>or if you want to have an inequality:</p> <pre><code>int(x[0]) &lt; y </code></pre>
1
2016-07-01T00:05:01Z
[ "python", "string", "int" ]
Numpy array vs. C++ vector in memory efficiency
38,134,980
<p>Which object is generally smaller in memory given the exact same data: a numpy array with dtype int64 or a C++ vector of type int? For example:</p> <pre><code>v = np.array([34, 23]) std::vector&lt;int&gt; v { 34,23 }; </code></pre>
2
2016-06-30T23:49:51Z
38,135,092
<p>There effectively 2 parts to an <code>np.array</code> - the object overhead plus attributes like shape and strides, and a data buffer. The first has roughly the same size for all arrays, the second scales with the number of elements (and the size of each element). In <code>numpy</code> the data buffer is 1d, regar...
2
2016-07-01T00:04:34Z
[ "python", "c++", "numpy" ]
Tkinter click event does not trigger; keyboard does
38,135,076
<p>I found this neat code <a href="http://spider.wadsworth.org/spider_doc/spider/docs/python/spipylib/examples/viewseries.py" rel="nofollow">here</a> that uses Tkinter to display a series of images. I extended the code to use the 'z' and 'x' keys to browse through the images and 'q' to quit. Also, I would like to be ab...
1
2016-07-01T00:02:23Z
38,153,325
<p>It seems like I found the answer myself: </p> <p>If I replace the <code>Frame</code> with a <code>Canvas</code>, I am able to trigger a mouse click event. I am not sure why that is the case, but it works.</p>
0
2016-07-01T20:16:22Z
[ "python", "tkinter" ]
What are the differences between two of these?
38,135,117
<pre><code>find = re.compile(r'die\ area \s+ = \s+ (%d)') </code></pre> <p>What's the difference between <code>'\ '</code> and <code>' '</code>?</p>
1
2016-07-01T00:08:06Z
38,136,954
<p>RegEx101.com agrees. Both match a literal ' '</p>
-1
2016-07-01T04:15:30Z
[ "python", "regex" ]
Python can't find local module
38,135,119
<p>I have a folder structure like this:</p> <pre><code>setup.py core/ __init__.py interpreter.py tests/ __init__.py test_ingest.py </code></pre> <p>If I try to import <code>core</code> in <code>test_ingest.py</code> and run it, I get an <code>ImportError</code> saying that the <code>core</code> module...
2
2016-07-01T00:08:10Z
38,135,519
<p>When you <code>import</code> your package, Python searches the directories on <code>sys.path</code> until it finds one of these: a file called "core.py", or a directory called "core" containing a file called <code>__init__.py</code>. Python then <a href="https://docs.python.org/3/reference/import.html" rel="nofollow...
2
2016-07-01T01:01:58Z
[ "python", "importerror" ]
Class variable initialization?
38,135,121
<p>Is there a <strong>init</strong>() method for the class (not for the instance). What I want is to set class variable value (it is expensive operation) the first time an instance is created. Something like :</p> <pre><code>class Blah: abc = None def __init__(self): if Blah.abc is None : Blah.abc = [1,2,3] <...
0
2016-07-01T00:08:14Z
38,135,202
<pre><code>&gt;&gt;&gt; class Blah: ... abc = None ... def __init__(self): ... if Blah.abc is None: ... Blah.abc = [1,2,3] ... &gt;&gt;&gt; print(Blah.abc) None &gt;&gt;&gt; foo = Blah() &gt;&gt;&gt; print(Blah.abc) [1, 2, 3] </code></pre>
0
2016-07-01T00:18:23Z
[ "python", "initialization", "class-variables" ]
How does one read TensorBoard histograms for a 1D example in TensorFlow?
38,135,122
<p>I made the simplest 1D example for TensorBoard (tracking the minimization of a quadratic) but I get plots that don't make sense to me and I can't figure out why. Is it my own implementation or is TensorBoard buggy?</p> <p>Here are the plots:</p> <p>HISTOGRAM:</p> <p><a href="http://i.stack.imgur.com/IIAn6.png" re...
0
2016-07-01T00:08:36Z
38,780,248
<p>I also met the same problem where multiple lines occurred in the Instance tab in tensor board (even I tried your codes and Board service shows the duplicated warning and only present one curve, better than me)</p> <pre><code>WARNING:tensorflow:Found more than one graph event per run. Overwriting the graph with the ...
0
2016-08-05T02:37:04Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
pandas: group by custom categories, then pivot?
38,135,177
<p>I have a dataframe that looks like this:</p> <pre><code> Company Name Category Amount 0 Teva Limited Consultancy 650.000 1 Teva Limited Consultancy 5.300 2 Eli &amp; Company Ltd Events ...
2
2016-07-01T00:14:13Z
38,135,267
<p>this should do it:</p> <pre><code>cdf = df.groupby([df['Company Name'], df.Category == 'Consultancy']).Amount.sum().unstack().fillna(0) cdf.set_axis(1, ['Other', 'Consultancy']) print cdf Other Consultancy Company Name Eli &amp; Company Ltd 15.00 0.0 Meda ...
0
2016-07-01T00:28:26Z
[ "python", "pandas" ]
pandas: group by custom categories, then pivot?
38,135,177
<p>I have a dataframe that looks like this:</p> <pre><code> Company Name Category Amount 0 Teva Limited Consultancy 650.000 1 Teva Limited Consultancy 5.300 2 Eli &amp; Company Ltd Events ...
2
2016-07-01T00:14:13Z
38,137,589
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">assign()</a> for creating a new <code>cat</code> column containing only <code>['Consultancy', 'Other']</code> categories and then use this new column in <code>pivot_table()</code> function :</p> ...
1
2016-07-01T05:21:34Z
[ "python", "pandas" ]
How does numpy's equality operator between arrays result in more arrays?
38,135,179
<p>Consider the following:</p> <pre><code>&gt;&gt;&gt; (np.arange(10) == [[0], [5], [4]]).astype(float) array([[ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]]) </code></pre> <p>I understand the ef...
1
2016-07-01T00:14:25Z
38,135,233
<p>The magic word here is <em>broadcasting</em>. Rather than explain it here myself, let me refer you to <a href="http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc" rel="nofollow">this article</a> with nice illustrations (linked to from the <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html...
1
2016-07-01T00:23:40Z
[ "python", "arrays", "numpy" ]
How does numpy's equality operator between arrays result in more arrays?
38,135,179
<p>Consider the following:</p> <pre><code>&gt;&gt;&gt; (np.arange(10) == [[0], [5], [4]]).astype(float) array([[ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]]) </code></pre> <p>I understand the ef...
1
2016-07-01T00:14:25Z
38,135,409
<pre><code>np.arange(10) == [[0], [5], [4]] </code></pre> <p><code>np.array([[0], [5], [4]])</code> is (3,1) shape; <code>np.arange(10)</code> is <code>(10,)</code> which can expand to (1,10). The result is (3,10)</p> <p><code>np.array([[0, 2], [5], [4]])</code> is a (3,) object array, because the sublists differ in...
1
2016-07-01T00:48:34Z
[ "python", "arrays", "numpy" ]
How do i insert data into HTML from python script?
38,135,208
<p>I have a html and python script.</p> <p>I am calling html inside python script and e-mailing them.</p> <p>This is my code:</p> <pre><code># Build email message import time currentTime = time.ctime(); reportmessage = urllib.urlopen(Report.reportHTMLPath + "reporturl.html").read() //Code to send e-mail ...
0
2016-07-01T00:19:30Z
38,136,332
<p>The simplest and <em>not secure</em> way is to use <code>str.format</code>:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; currentTime = time.ctime() &gt;&gt;&gt; &gt;&gt;&gt; currentTime 'Fri Jul 1 06:50:37 2016' &gt;&gt;&gt; s = ''' &lt;div&gt; &lt;b&gt; Time is {}&lt;/b&gt; &lt;/div&gt;'''.format(current...
1
2016-07-01T02:57:48Z
[ "python", "html" ]
How do i insert data into HTML from python script?
38,135,208
<p>I have a html and python script.</p> <p>I am calling html inside python script and e-mailing them.</p> <p>This is my code:</p> <pre><code># Build email message import time currentTime = time.ctime(); reportmessage = urllib.urlopen(Report.reportHTMLPath + "reporturl.html").read() //Code to send e-mail ...
0
2016-07-01T00:19:30Z
38,136,456
<p>If you have large quantities of data to be inserted, template will be a good choice. If you really mind of using a template engine, <code>re</code> will be a lightweight solution.</p> <p>Here is a simple example:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; html = ''' ... &lt;div&gt; ... &lt;b&gt; Time is...
1
2016-07-01T03:14:05Z
[ "python", "html" ]
Updating pip package in virutal env via cron
38,135,223
<p>I'm not sure why this is happening, I currently have this set up in my <code>crontab -e</code></p> <pre><code>*/30 * * * * cd /home/www/ &amp;&amp; source env/bin/activate &amp;&amp; pip install --upgrade youtube_dl &gt;/dev/null 2&gt;&amp;1 </code></pre> <p>The problem is this is not actually updating the script....
0
2016-07-01T00:22:32Z
38,135,504
<p>cron uses <code>/bin/sh</code> as its shell, not bash. you are calling <code>source</code>, which is a bash command.</p> <p>note: you can replace <code>source</code> with <code>.</code>, and both shells will recognize the command.</p>
1
2016-07-01T01:00:47Z
[ "python", "ubuntu-14.04", "virtualenv", "crontab" ]
Python reshaping a list of strings based on delimiter
38,135,286
<p>I have pipe delimited data being returned from a Rest API call:</p> <pre><code>data = ['Bob|37', 'Eric|40'] </code></pre> <p>I extracted the header info from the first "line" and split it into a list:</p> <pre><code>column_list = ['Name','Age'] </code></pre> <p>I am trying to read this into a pandas dataframe:</...
3
2016-07-01T00:31:14Z
38,135,369
<p>Try this:</p> <pre><code>data = ['Bob|37', 'Eric|40'] df = pd.Series(data).str.split('|', expand=True) df.columns = ['Name', 'Age'] print df Name Age 0 Bob 37 1 Eric 40 </code></pre>
1
2016-07-01T00:42:16Z
[ "python", "list", "pandas" ]
Python reshaping a list of strings based on delimiter
38,135,286
<p>I have pipe delimited data being returned from a Rest API call:</p> <pre><code>data = ['Bob|37', 'Eric|40'] </code></pre> <p>I extracted the header info from the first "line" and split it into a list:</p> <pre><code>column_list = ['Name','Age'] </code></pre> <p>I am trying to read this into a pandas dataframe:</...
3
2016-07-01T00:31:14Z
38,137,827
<p>Here is an alternative one-liner solution (using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow">.str.extract()</a>) function:</p> <pre><code>In [20]: df = pd.Series(data).str.extract(r'(?P&lt;Name&gt;.*?)\|(?P&lt;Age&gt;.*)', expand=True) In [21]: df O...
1
2016-07-01T05:42:53Z
[ "python", "list", "pandas" ]
How can I sort a DataFrame by date ddMMMyyyy?
38,135,297
<p>I have a sample dataframe as follows. </p> <p><strong>How can I sort it by the index by year instead of by month?</strong></p> <pre><code>test=DataFrame([1,2,3],index=['28FEB1993','28FEB1994','30MAR1993'],columns=['value']) </code></pre> <p>I would like to have the following dataFrame as the result</p> <pre><cod...
0
2016-07-01T00:32:03Z
38,135,400
<p>You can use <code>strptime</code>:</p> <pre><code>from datetime import datetime test.index = np.array([datetime.strptime(s, "%d%b%Y") for s in test.index.values]) test.sort_index() # value # 1993-02-28 1 # 1993-03-30 3 # 1994-02-28 2 </code></pre> <p>Or as suggested by @chrisb:</p> <pre><code>...
0
2016-07-01T00:46:50Z
[ "python", "sorting", "datetime" ]
How to install PyRTF with Python3?
38,135,344
<p>I tried to install <code>PyRTF</code> from PyPi but this doesn't work.</p> <p>The package itself can be found:</p> <pre><code>$ pip3 search PyRTF PyRTF (0.45) - PyRTF - Rich Text Format Document Generation </code></pre> <p>But installing it fails:</p> <pre><code>$ sudo -H pip3 install PyRTF Collecting PyRTF C...
1
2016-07-01T00:38:57Z
38,135,555
<p>You could use the raw url from the sourceforge page in order to get it:</p> <pre><code>pip install https://sourceforge.net/projects/pyrtf/files/pyrtf/0.45/PyRTF-0.45.tar.gz/download </code></pre> <p>But, to be honest, I don't think this library is maintained on the project website the last update was from <code>2...
2
2016-07-01T01:07:48Z
[ "python", "python-3.x", "rtf" ]
New to Python- How do I store a biased number generator as function?
38,135,346
<p>This isn't for any project or anything, just messing around. (Was doing this in a python shell)</p> <pre><code>import random def rand1(): random.gauss(0, 0.1) * 0.3 + random.gauss(0, 3) * 0.7 rand1() + 1 </code></pre> <p>It comes up with</p> <pre><code>TypeError: unsupported operand type(s) for +: 'NoneType'...
0
2016-07-01T00:39:04Z
38,135,363
<p>The syntax for a function is</p> <pre><code>def functionname(): # function operations - this is just a comment, noted by the #! &lt;tab&gt;x = 2 + 2 &lt;tab&gt;return x </code></pre> <p>This "returns <code>x</code>" to the caller. Tabs <code>&lt;tab&gt;</code> are necessary to let the interpreter know it is part o...
0
2016-07-01T00:41:49Z
[ "python", "function", "nonetype" ]
regular expression in python about or
38,135,354
<p>I know <code>p=re.compile('aaa|bbb')</code> can work, but I want to rewrite <code>p = re.compile('aaa|bbb')</code> using variables, something like</p> <pre><code>A = 'aaa' B = 'bbb' p = re.compile(A|B) </code></pre> <p>but this doesn't work. How can I rewrite this so that variables are used (and it works)?</p>
2
2016-07-01T00:40:34Z
38,135,376
<blockquote> <p><code>p=re.compile(A|B)</code></p> </blockquote> <p><em>You are not doing the string concatenation correctly</em>. What you are doing is applying the <a href="http://stackoverflow.com/questions/5988665/pipe-character-in-python">"bitwise or" (the pipe) operator</a> to strings, which, of course, fails:...
4
2016-07-01T00:43:06Z
[ "python", "regex", "python-2.7" ]
Use unicode strings instead of regular strings? (Python 2.7)
38,135,467
<p>As far as I know there is a difference between strings and unicode strings in Python. But is it possible to instruct Python to use unicode strings instead of regular ones whenever a string object is created?</p> <p>So when I get a text input, I don't need to use <code>unicode()</code>?</p> <p>I might sound lazy bu...
0
2016-07-01T00:55:33Z
38,136,165
<p>In Python 2.6+ you can use <code>from __future__ import unicode_literals</code>, but that only makes string literals Unicode. All functions that returned byte strings still return byte strings.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; s = 'abc' &gt;&gt;&gt; type(s) &lt;type 'str'&gt; &gt;&gt;&gt; from __future...
1
2016-07-01T02:35:42Z
[ "python", "string", "unicode", "character-encoding" ]
Use unicode strings instead of regular strings? (Python 2.7)
38,135,467
<p>As far as I know there is a difference between strings and unicode strings in Python. But is it possible to instruct Python to use unicode strings instead of regular ones whenever a string object is created?</p> <p>So when I get a text input, I don't need to use <code>unicode()</code>?</p> <p>I might sound lazy bu...
0
2016-07-01T00:55:33Z
38,136,167
<p>For Example(In pyhon interactive,diff in GUI Shell) :</p> <pre><code>&gt;&gt;&gt; s = '你好' &gt;&gt;&gt; s '\xe4\xbd\xa0\xe5\xa5\xbd' &gt;&gt;&gt; us = u'你好' &gt;&gt;&gt; us u'\u4f60\u597d' &gt;&gt;&gt; print type(s) &lt;type 'str'&gt; &gt;&gt;&gt; print type(us) &lt;type 'unicode'&gt; &gt;&gt;&gt; len(s) 6 ...
1
2016-07-01T02:35:59Z
[ "python", "string", "unicode", "character-encoding" ]
Use unicode strings instead of regular strings? (Python 2.7)
38,135,467
<p>As far as I know there is a difference between strings and unicode strings in Python. But is it possible to instruct Python to use unicode strings instead of regular ones whenever a string object is created?</p> <p>So when I get a text input, I don't need to use <code>unicode()</code>?</p> <p>I might sound lazy bu...
0
2016-07-01T00:55:33Z
38,145,440
<blockquote> <p>But is it possible to instruct Python to use unicode strings instead of regular ones whenever a string object is created?</p> </blockquote> <p>There are two type of strings in Python (on both Python 2 and 3): a bytestring (a sequence of bytes) and a Unicode string (a sequence of Unicode codepoints).<...
0
2016-07-01T12:26:00Z
[ "python", "string", "unicode", "character-encoding" ]
convert a python code with function structure to class structure with generator and calculate time and space complexity
38,135,708
<p>I wrote this simple python code but now I have to convert this into a <code>class</code> structure which accepts an iterator and act as a generator to yield the tuples(instead of return it should yield). I am unable to convert it:</p> <pre><code> def func(str,size): size1 = size list1 = [] ...
-1
2016-07-01T01:31:03Z
38,135,937
<p>Currently the <code>continue</code> statements which follow the <code>return</code> statements make no sense - <code>continue</code> will never be reached. However, you can <em>yield</em> each tuple with <code>yield</code> instead of <code>return</code>, e.g., replace</p> <pre><code>return (None,None,None,None) </c...
0
2016-07-01T02:10:22Z
[ "python", "generator" ]
convert a python code with function structure to class structure with generator and calculate time and space complexity
38,135,708
<p>I wrote this simple python code but now I have to convert this into a <code>class</code> structure which accepts an iterator and act as a generator to yield the tuples(instead of return it should yield). I am unable to convert it:</p> <pre><code> def func(str,size): size1 = size list1 = [] ...
-1
2016-07-01T01:31:03Z
38,136,097
<p>only the window1 and window2 will ask for extra space, so I think the space complexity will be O(n).</p>
0
2016-07-01T02:27:13Z
[ "python", "generator" ]
How to parse not-well formed XML from web to ElementTree
38,135,744
<p>I am having difficulties working with an XML file from the web. It isn't my XML so I can't modify the format. </p> <pre><code>import urllib import xml.etree.ElementTree as ET xmls = urllib.request.urlopen('http://odds.smarkets.com/oddsfeed.xml') tree = ET.ElementTree(ET.fromstring(xmls.read()) </code></pre> <p...
0
2016-07-01T01:35:28Z
38,135,768
<p><em>Don't reinvent the wheel</em> and use a special library for parsing XML feeds - <a href="http://pythonhosted.org/feedparser/introduction.html" rel="nofollow"><code>feedparser</code></a>:</p> <pre><code>from pprint import pprint import feedparser d = feedparser.parse('http://odds.smarkets.com/oddsfeed.xml') pp...
1
2016-07-01T01:40:02Z
[ "python", "xml", "elementtree" ]
How to parse not-well formed XML from web to ElementTree
38,135,744
<p>I am having difficulties working with an XML file from the web. It isn't my XML so I can't modify the format. </p> <pre><code>import urllib import xml.etree.ElementTree as ET xmls = urllib.request.urlopen('http://odds.smarkets.com/oddsfeed.xml') tree = ET.ElementTree(ET.fromstring(xmls.read()) </code></pre> <p...
0
2016-07-01T01:35:28Z
38,147,922
<p>Turns out using the <code>lxml</code> version of ElementTree parses my file just fine. So I'm using that now.</p>
0
2016-07-01T14:26:50Z
[ "python", "xml", "elementtree" ]
Why can't I add a found prime, to a list of primes?
38,135,819
<p>I'm trying to just print out the found primes. I want to add to the prime[], but I get a TypeError</p> <pre><code>line 63, in isprime primes += n TypeError: 'int' object is not iterable </code></pre> <p>The code:</p> <pre><code>def isprime(n): primes = [] if n == 1: print '1 is special' ...
-1
2016-07-01T01:51:10Z
38,135,830
<p><code>primes</code> is a list, so to add <code>n</code>, which is an <code>int</code>, to it, you have to use the <code>append</code> method. Replace <code>primes += n</code> with <code>primes.append(n)</code>.</p>
1
2016-07-01T01:53:58Z
[ "python" ]
Why can't I add a found prime, to a list of primes?
38,135,819
<p>I'm trying to just print out the found primes. I want to add to the prime[], but I get a TypeError</p> <pre><code>line 63, in isprime primes += n TypeError: 'int' object is not iterable </code></pre> <p>The code:</p> <pre><code>def isprime(n): primes = [] if n == 1: print '1 is special' ...
-1
2016-07-01T01:51:10Z
38,135,832
<p><code>+=</code> on a <code>list</code> is intended to concatenate one <code>list</code> to another. If you want to add a single element onto the end of the <code>list</code>, you can either do the straightforward:</p> <pre><code>primes.append(n) </code></pre> <p>or make a temporary <code>list</code> to allow the l...
4
2016-07-01T01:54:06Z
[ "python" ]
How to print input through texts (Python)
38,135,835
<p>I want my program to print the value of the variable 'sob' when I write: write("sob")</p> <p>Code:</p> <pre><code>str = input("&gt;") sob = input(".") if str == ('write("' + sob + '")'): print(sob) else: print("SYNTAX ERROR") </code></pre>
1
2016-07-01T01:54:44Z
38,135,934
<p>Instead of using <code>input()</code> use <code>raw_intput()</code>:</p> <pre><code>str = raw_input('&gt;') sob = raw_input(".") if str == ('write("' + sob + '")'): print(sob) else: print("SYNTAX ERROR") </code></pre> <p><code>input()</code> interprets the input you enter as python commands, where...
0
2016-07-01T02:10:11Z
[ "python" ]
How to print input through texts (Python)
38,135,835
<p>I want my program to print the value of the variable 'sob' when I write: write("sob")</p> <p>Code:</p> <pre><code>str = input("&gt;") sob = input(".") if str == ('write("' + sob + '")'): print(sob) else: print("SYNTAX ERROR") </code></pre>
1
2016-07-01T01:54:44Z
38,135,959
<p>Try this</p> <p><strong>CODE</strong></p> <pre><code>sob = raw_input('Type write("sob"): ') sob = sob.lower() if sob == 'write("sob")': print(sob.lstrip('Type write("').rstrip('")')) else: print("Error") </code></pre> <p><strong>RESULT</strong></p> <pre><code>sob </code></pre>
0
2016-07-01T02:12:52Z
[ "python" ]
Python last line of for loop executed twice
38,136,016
<p>Why is "no" printed an additional time? How can the problem be fixed without writing the loop in a separate function?</p> <pre><code>for i in range(2): if i == 1: print("yes") print("no") </code></pre> <p>Result: </p> <pre><code>no yes no </code></pre>
-1
2016-07-01T02:18:11Z
38,136,031
<p>The other <code>print</code> statement happens <em>unconditionally</em>; that is, there's no <code>else</code> to prevent it from firing again.</p> <p>You can prevent it by using <code>else</code>:</p> <pre><code>for i in range(2): if i == 1: print("yes") else: print("no") </code></pre>
1
2016-07-01T02:20:00Z
[ "python", "for-loop" ]
Python last line of for loop executed twice
38,136,016
<p>Why is "no" printed an additional time? How can the problem be fixed without writing the loop in a separate function?</p> <pre><code>for i in range(2): if i == 1: print("yes") print("no") </code></pre> <p>Result: </p> <pre><code>no yes no </code></pre>
-1
2016-07-01T02:18:11Z
38,136,039
<p>Let see what happened:</p> <p>when <code>i=0</code>, it print <code>no</code> when <code>i=</code>, it firstly print <code>yes</code>, after that printing <code>no</code>.</p> <p>EDIT: to fix it, you can</p> <pre><code>for i in range(2): if i == 1: print("yes") else: print("no") </code></pr...
3
2016-07-01T02:20:27Z
[ "python", "for-loop" ]
Python last line of for loop executed twice
38,136,016
<p>Why is "no" printed an additional time? How can the problem be fixed without writing the loop in a separate function?</p> <pre><code>for i in range(2): if i == 1: print("yes") print("no") </code></pre> <p>Result: </p> <pre><code>no yes no </code></pre>
-1
2016-07-01T02:18:11Z
38,136,300
<p>u can also use keyword <code>break</code> to fix it,like below:</p> <pre><code>for i in range(2): if i==1: print('yes') break print('no') </code></pre> <p>when i==1 break out the for func,maybe this is better understanded</p>
1
2016-07-01T02:54:04Z
[ "python", "for-loop" ]
Networkx read ordnance survey - ITN Integrated Transport Network?/Reading GML file
38,136,044
<p>I met some problems.</p> <p>I want to import ordnance survey - ITN Integrated Transport Network into networkx to do some network analysis. </p> <p>Since the ITN is in a <strong>GML 2.1.2</strong> format, I tried to use </p> <pre><code>nx.read_gml </code></pre> <p>However it warned me that </p> <pre><code>ParseE...
1
2016-07-01T02:21:22Z
38,151,251
<p>It looks like the GML you are citing is the Geography Markup Language <a href="https://en.wikipedia.org/wiki/Geography_Markup_Language" rel="nofollow">https://en.wikipedia.org/wiki/Geography_Markup_Language</a> and the GML referred to in NetworkX is the Graph Modeling Language <a href="https://en.wikipedia.org/wiki/...
0
2016-07-01T17:46:25Z
[ "python", "dictionary", "gis", "networkx", "gml" ]
Tweaking the seaborn graph from pandas dataFrame
38,136,143
<p>I am trying to plot the timeseries graph of internet traffic from 11 cities in Europe.</p> <p>I got access to the data set from <a href="https://datamarket.com/data/set/232i/internet-traffic-data-in-bits-from-a-private-isp-with-centres-in-11-european-cities-the-data-corresponds-to-a-transatlantic-link-and-was-colle...
1
2016-07-01T02:32:31Z
38,641,936
<p>Here is how I would do it in two different ways, depending on how you want to format your y-ticks. </p> <p>I don't have your dataset so I created one myself.</p> <p><strong>Imports:</strong></p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Ticker module import matplotlib....
0
2016-07-28T16:26:37Z
[ "python", "pandas", "matplotlib", "seaborn", "data-analysis" ]
How to trouble-shoot install python-requests module
38,136,217
<p>Using <code>python3</code> On OSX I installed requests using <code>pip3 install requests</code> When I run <code>&gt;&gt;&gt;python -c "import requests"</code>, no errors, but when I run a file started with <code>import requests</code>, I get the following error:</p> <pre><code> Traceback (most recent call last): ...
0
2016-07-01T02:43:37Z
38,149,731
<p>It turns out I was running the file with python 2, but had installed requests under python 3(pip3).</p>
0
2016-07-01T16:05:04Z
[ "python", "module", "python-requests" ]
Combining data and header to create dta
38,136,239
<p>I have tab-delimited txt data without header</p> <pre><code>1990 1 3 1991 0 2 1990 1 1 </code></pre> <p>And I have headers information like this.</p> <pre><code> VARIABLE LABELS C1 'Year' C2 'Sex' C3 'Region' </code></pre> <p>How can I combine them (put the header to tab-delim...
0
2016-07-01T02:46:55Z
38,138,208
<p>I am puzzled by the interest in roundabout ways to do this. A direct way to do this in Stata is </p> <pre><code>import delimited Year Sex Region using mydata.txt save mydata </code></pre> <p>Your real problem could be more complicated, but if so, you will need to give a better explanation. In particular, </p> <...
3
2016-07-01T06:10:34Z
[ "python", "stata" ]
embedding Matplotlib in PyQt5 using anaconda3
38,136,277
<p>I'm trying to make a simple program with matplotlib embedded in a PyQt5 gui. I am using pycharm with anaconda as the interpreter. I installed PyQt5 using the binary installers <a href="https://riverbankcomputing.com/software/pyqt/download5" rel="nofollow">here</a>. My imports are</p> <pre><code>import sys from PyQt...
0
2016-07-01T02:51:28Z
38,150,580
<p>What's the system you used in both your laptop and desktop? And maybe you can try install pyqt4 before install pyqt5.</p>
0
2016-07-01T17:00:28Z
[ "python", "matplotlib", "pyqt5" ]
Reason for No Print Output
38,136,299
<pre><code>a = 1 b = [] while a &lt;= 600851475143: if 600851475143 % a == 0: b.append(a) a += 1 print b </code></pre> <p>I'm trying to print the factors of 600851475143 as a list by using this loop, but nothing gets printed. Any explanation?</p>
-3
2016-07-01T02:53:56Z
38,136,491
<p>The loop takes too much time. A PC can operate about 100000000 instructions per second. So your loop need about 4 hours or more to print the result.</p>
0
2016-07-01T03:17:41Z
[ "python" ]
Python BeautifulSoup && Request to scrape search engines
38,136,424
<p>I'm a little confused on how to do this. I'm not sure if this is correct but I'm trying to query a search via a url. I've tried doing this:</p> <pre><code>url = 'https://duckduckgo.com/dogs?ia=meanings' session = requests.session() r = session.get(url) soup = bs(r.content, 'html.parser') </code></pre> <p>I get som...
0
2016-07-01T03:11:03Z
38,136,472
<p>The problem is that the search results and most of the page are <em>dynamically loaded</em> with the help of JavaScript code being executed by the browser. <code>requests</code> would only download the initial static HTML page, it has no JS engine since it is not a browser.</p> <p>You have basically 3 main options:...
2
2016-07-01T03:15:56Z
[ "python", "web-scraping", "beautifulsoup", "python-requests" ]
numpy: broadcasting into multiple inner products and inverses
38,136,461
<p>I have arrays <code>e</code>, (shape <code>q</code> by <code>l</code>) <code>f</code> (shape <code>n</code> by <code>l</code>), and <code>w</code> (shape <code>n</code> by <code>l</code>), and I want to create an array <code>M</code> where <code>M[s,i,j] = np.sum(w[s, :] * e[i, :] * e[j, :])</code>, and an array <co...
2
2016-07-01T03:14:42Z
38,137,374
<pre><code>M[s,i,j] = np.sum(w[s, :] * e[i, :] * e[j, :]) </code></pre> <p>translates to</p> <pre><code>M = np.einsum('sk,ik,jk-&gt;sij',w,e,e) </code></pre> <p>and</p> <pre><code>F[s,j] = np.sum(w[s, :] * f[s, :] * e[j, :]) F = np.einsum('sk,sk,jk-&gt;sj', w, f, e) </code></pre> <p>I haven't tested these with you...
3
2016-07-01T05:00:56Z
[ "python", "numpy", "matrix-inverse", "broadcasting", "inner-product" ]
Dividing a file by byte count
38,136,475
<p>I am making a file-sharing program, and when I send a file I want to only send 1024 bytes, and then send the next 1024 bytes and so on. I am using scapy and not sockets, so I need to do this manually. How can I divide a file into chunks of 1024 bytes each?</p>
1
2016-07-01T03:16:30Z
38,136,939
<p>You can just write a simple loop:</p> <pre><code>while True: block = f.read(1024) if not block: break ... do stuff with block ... </code></pre> <p>Each call to <code>read</code> reads data and advances the file position, so you get a new block each time. Alternatively, you can be a little more ...
1
2016-07-01T04:13:49Z
[ "python", "python-2.7", "file", "file-io" ]
what is the difference between ['[a,a,a]','[b,b,b]'] and [[a,a,a],[b,b,b]] in python?
38,136,504
<p>In my program, when I debug my code, it seems somewhere in my code I generate </p> <pre><code>X1=['[a,a,a]','[b,b,b]'] </code></pre> <p>and somewhere else I generate </p> <pre><code>X2=[[a,a,a],[b,b,b]] </code></pre> <p>and when I want to add this two lists and then use <code>numpy.array(X1+X2)</code> I get er...
2
2016-07-01T03:19:09Z
38,136,576
<p>X1 is a list that contains two strings</p> <p>X2 is a list that contains two lists that each contain three variables.</p> <p>About converting the strings to a list you would have to make an empty list and then remove the square brackets from the strings and then look for "," and add what was found before it to the...
2
2016-07-01T03:27:29Z
[ "python", "list", "numpy" ]
what is the difference between ['[a,a,a]','[b,b,b]'] and [[a,a,a],[b,b,b]] in python?
38,136,504
<p>In my program, when I debug my code, it seems somewhere in my code I generate </p> <pre><code>X1=['[a,a,a]','[b,b,b]'] </code></pre> <p>and somewhere else I generate </p> <pre><code>X2=[[a,a,a],[b,b,b]] </code></pre> <p>and when I want to add this two lists and then use <code>numpy.array(X1+X2)</code> I get er...
2
2016-07-01T03:19:09Z
38,136,682
<p>Just to riff off of @JoshuaWierenga's answer:</p> <pre><code>&gt;&gt;&gt; a, b = 1, 2 &gt;&gt;&gt; X1=['[a,a,a]','[b,b,b]'] &gt;&gt;&gt; X2=[[a,a,a],[b,b,b]] &gt;&gt;&gt; [eval(i) for i in X1] == X2 True &gt;&gt;&gt; [str(i) for i in X2] == X1 False &gt;&gt;&gt; [str(i) for i in X2] ['[1, 1, 1]', '[2, 2, 2]'] &gt;&...
1
2016-07-01T03:39:55Z
[ "python", "list", "numpy" ]
Python codecademy digit_sum
38,136,544
<p>the task was discussed in <a href="http://stackoverflow.com/questions/37948737/codecademy-practice-makes-perfect-digit-sum">codecademy Practice Makes Perfect digit_sum</a></p> <p>Where you need to sum the digits of a positive number. I use the string way to decide the task (not the floor dividing).</p> <p>My code...
1
2016-07-01T03:22:55Z
38,136,687
<p>you did not convert n to string, so when you call n[i] it will raise exception</p> <pre><code>def digit_sum(n): return sum( int(i) for i in str(n) ) </code></pre>
1
2016-07-01T03:40:48Z
[ "python" ]
Python codecademy digit_sum
38,136,544
<p>the task was discussed in <a href="http://stackoverflow.com/questions/37948737/codecademy-practice-makes-perfect-digit-sum">codecademy Practice Makes Perfect digit_sum</a></p> <p>Where you need to sum the digits of a positive number. I use the string way to decide the task (not the floor dividing).</p> <p>My code...
1
2016-07-01T03:22:55Z
38,161,770
<p>Evert, Jerzyk, Galaxian, thanks for the comments. Thanks for you I saw it: I casted n to str only in one place (3rd line) and thought that this was enough since the 4th line is inside the for loop. I edited the code to </p> <pre><code>def digit_sum (n): total = 0 n = str(n) for digit in range(len(n)): ...
0
2016-07-02T15:37:29Z
[ "python" ]
Creating empty 3-layer nested list
38,136,668
<p>If I want to create a 3-layer nested list like <code>list = [[[],[]],[[],[]]]</code>, what's the appropriate way to do this? I saw someone else posted solution for the 2-layer nested list as <code>lst = [[] for _ in xrange(a)]</code>. Is there a more generalized way to create this nested list without establishing ho...
1
2016-07-01T03:38:28Z
38,136,848
<p>There is a way if you know the lengths of the third layer lists beforehand.</p> <pre><code>&gt;&gt;&gt; length = [1,2,3,4] # indicates the lengths of the third layer lists &gt;&gt;&gt; res = [ [ [] for i in range(j) ] for j in length ] &gt;&gt;&gt; res [[[]], [[], []], [[], [], []], [[], [], [], []]] </code></pre>
0
2016-07-01T04:00:57Z
[ "python", "list", "nested" ]
Creating empty 3-layer nested list
38,136,668
<p>If I want to create a 3-layer nested list like <code>list = [[[],[]],[[],[]]]</code>, what's the appropriate way to do this? I saw someone else posted solution for the 2-layer nested list as <code>lst = [[] for _ in xrange(a)]</code>. Is there a more generalized way to create this nested list without establishing ho...
1
2016-07-01T03:38:28Z
38,138,200
<p>You could use Python's arithmetic operators to generate your nested lists (this method is more performant than iterating with nested <code>for</code> loops):</p> <pre><code>def listmaker(n, m): # n = number of lists in the 3rd layer # m = number of lists in the 2nd layer return [[[]] * n] * m listmak...
2
2016-07-01T06:10:04Z
[ "python", "list", "nested" ]
redirect to other page when I download via download link
38,136,826
<p>For example, I can only download thr srt file on mouse click in this page: <a href="http://www.addic7ed.com/show/95" rel="nofollow">http://www.addic7ed.com/show/95</a></p> <p>When I type the download link <a href="http://www.addic7ed.com/updated/1/1792/0" rel="nofollow">http://www.addic7ed.com/updated/1/1792/0</a> ...
0
2016-07-01T03:58:37Z
38,141,440
<p>The server looks at the <code>Referer</code> HTTP header to check that the request for the <code>srt</code> file came from the page that links to it. You can use <a href="https://en.wikipedia.org/wiki/Referer_spoofing" rel="nofollow">Referer spoofing</a> to get around this:</p> <p>If you run this cURL command, you ...
0
2016-07-01T09:09:29Z
[ "python", "http", "web" ]
Inserting element into arbitrary position of an n-dimensional array
38,136,912
<p>I am using Python 2.7 to create a complex-valued (m x n)-dimensional array without an initially known fixed size (i.e. m and n are not known ahead of time) which will have particular elements assigned different values. Thus, I will be changing existing elements or adding new elements to this array at arbitrary posit...
2
2016-07-01T04:10:47Z
38,137,248
<p>Try this:</p> <pre><code>np.concatenate((T, np.zeros((1,T.shape[1]), dtype=np.complex_)), axis=0) </code></pre> <p>and</p> <pre><code>np.concatenate((T, np.zeros((T.shape[0],1), dtype=np.complex_)), axis=1) </code></pre>
0
2016-07-01T04:45:55Z
[ "python", "numpy", "multidimensional-array", "scipy", "append" ]
Inserting element into arbitrary position of an n-dimensional array
38,136,912
<p>I am using Python 2.7 to create a complex-valued (m x n)-dimensional array without an initially known fixed size (i.e. m and n are not known ahead of time) which will have particular elements assigned different values. Thus, I will be changing existing elements or adding new elements to this array at arbitrary posit...
2
2016-07-01T04:10:47Z
38,137,301
<p>I'd suggest studying the code for <code>np.insert</code>. It is Python. If it is complex it is simply because it is trying to be general, handling rows or cols etc.</p> <p>The basic idea is to make a new result array of the correct size, and then copy blocks of values from the original to the result. In 1d that ...
0
2016-07-01T04:53:15Z
[ "python", "numpy", "multidimensional-array", "scipy", "append" ]
How to create 2-layers neural network using TensorFlow and python on MNIST data
38,136,961
<p>I'm a newbie in machine learning and I am following tensorflow's tutorial to create some simple Neural Networks which learn the MNIST data.</p> <p>I have built a single layer network (following the tutotial), accuracy was about 0.92 which is ok for me. But then I added one more layer, the accuracy reduced to 0.113,...
1
2016-07-01T04:16:05Z
38,139,788
<p>The input of the 2nd layer is the <code>softmax</code> of the output of the first layer. You don't want to do that.</p> <p>You're forcing the sum of these values to be 1. If some value of <code>tf.matmul(x, W1) + b1</code> is about 0 (and some certainly are) the softmax operation is lowering this value to be 0. Res...
1
2016-07-01T07:43:56Z
[ "python", "tensorflow", "mnist" ]
django-pipeline crashes python social auth
38,136,962
<p>Currently I'm working in a little project that is contemplating social authentication (so python-social-auth is great). Also, I wanna to integrate django-pipeline to handle my assets (css principally).</p> <p>JS to perform a social sign up: </p> <pre><code>vm.doSocialAuth = function(provider) { var authURL = '/a...
1
2016-07-01T04:16:09Z
38,149,989
<p>The credit for the next answer is all for <a href="https://github.com/webjunkie" rel="nofollow">Julian Bez</a>, he posted <a href="https://github.com/omab/python-social-auth/pull/888#issuecomment-215690158" rel="nofollow">this</a> comment.</p> <p>And he is basically suggesting to define a <code>SOCIAL_AUTH_PIPELINE...
0
2016-07-01T16:20:48Z
[ "python", "django", "python-social-auth", "django-pipeline" ]
Catching a (specific) generic Exception raised by an external library
38,137,275
<p>I am using an external library which raises a generic <code>Exception</code> in one of it's modules under certain circumstances:</p> <pre><code>if some_condition: raise Exception('DSSP failed to produce an output') </code></pre> <p>This only occurs in a few edge-cases, but is still something I want to catch an...
1
2016-07-01T04:49:58Z
38,137,308
<p>Catch <code>Exception</code> and reraise if it's not the exception you're looking for:</p> <pre><code>try: do_thing() except Exception as e: if type(e) is not Exception: # Not what we're looking for. Let it pass. raise handle(e) </code></pre> <p>You can add some other checks if you want...
2
2016-07-01T04:53:48Z
[ "python" ]
Removing wireframe without gaps in matplotlib plot_trisurf
38,137,316
<p>I want to create a smooth cylinder using matplotlib/pyplot. I've adapted a tutorial online and produced the following minimal example: </p> <pre><code>from numpy import meshgrid,linspace,pi,sin,cos,shape from matplotlib import pyplot import matplotlib.tri as mtri from mpl_toolkits.mplot3d import Axes3D u,v = meshg...
0
2016-07-01T04:54:28Z
38,137,688
<pre><code>ax.plot_trisurf(x,y,z,triangles=tri.triangles,linewidth=0, antialiased=False) </code></pre>
-1
2016-07-01T05:31:02Z
[ "python", "matplotlib" ]
Sage (Python) Math Programming, Writing an Algorithm to check for Primality
38,137,320
<p>I need to write a code in Sage for a homework problem that checks whether a random number generated between 10^7 and 10^8 is prime by dividing it by all the known primes less than or equal to 10^4. I have never programmed in Sage prior to this as a warning. This is what I have so far.</p> <pre><code># This creates ...
1
2016-07-01T04:54:51Z
38,137,649
<p>You're <code>check_if_prime</code> function could use some work. I've re-written below.</p> <pre><code>def check_if_prime(): # there's no parameter for this method since we're checking against the global var list_of_primes for n in list_of_primes: if random_between(10^7,10^8) % n == 0: # if a random num...
0
2016-07-01T05:26:34Z
[ "python", "primes", "sage", "number-theory" ]
Access SeqIO.index returned dict in multiprocess shared memory
38,137,331
<p>I have a large file (40G) in FASTA format. To speed up the process, I have a parallel step using <code>pool.map</code>. First, <code>SeqIO.index</code> is used to load the large file's index info to a shared memory (using multiprocessing's Manager). </p> <p>But when I run the following code, the program crashes som...
0
2016-07-01T04:55:58Z
38,240,893
<p>I could reproduce your problem with a smaller data set (all proteins from E. Coli) and it really does occur randomly. It seems that the problem is the use of <code>manager.dict()</code> on <code>SeqIO.index</code> which is a different type.</p> <pre><code>&gt;&gt;&gt; print(type(m_records)) &lt;class 'Bio.File._Ind...
0
2016-07-07T08:34:29Z
[ "python", "indexing", "multiprocessing", "biopython" ]
Why bother quantize() a floating-point number given that we have round() function?
38,137,451
<p>I read in a Python book saying that in financial world, sometimes it'd be better using quantize() and decimal module to round off floating-point numbers. An example is given in the book as below, </p> <pre><code>from decimal import Decimal price = Decimal('19.99') tax = Decimal('0.06') total = price + (price * tax)...
0
2016-07-01T05:08:00Z
38,137,883
<p>I don't think that the main reason for using Decimal (and quantize) is speed: it's accuracy. From the docs:</p> <blockquote> <p>Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2...
0
2016-07-01T05:45:50Z
[ "python", "floating-point", "decimal" ]
How to delete attribute of user in ldap3?
38,137,478
<p>I know how to modify an attribute.</p> <pre><code>c.modify('cn=user1,ou=users,o=company', {'userWorkstations': [(MODIFY_REPLACE, ['Win-7'])]}) </code></pre> <p>This <a href="http://ldap3.readthedocs.io/delete.html" rel="nofollow">link</a> shows how to delete an entry.</p> <p>But How to delete an attribut...
0
2016-07-01T05:10:02Z
38,155,806
<p>An LDAP Modify Request has various "<a href="https://www.ldap.com/the-ldap-modify-operation" rel="nofollow">Modification Types</a>" that may be performed.</p> <p>You can "ADD" a value of an attribute. You can "DELETE" a value of an attribute. You can "REPLACE" a value of an attribute. You can "INCREMENT" a value of...
1
2016-07-02T01:58:16Z
[ "python", "active-directory", "ldap", "ldap-query" ]
Error while calculating time diff
38,137,480
<p>I am running into following error while calculating time diff?how to fix it?</p> <pre><code>from datetime import datetime, date import time print "Start : %s" % time.ctime() start_time = time.ctime() #do something print "How to calculate time diff?" end_time = time.ctime() total_elapsed_time = datetime.combine(date...
-1
2016-07-01T05:10:10Z
38,137,562
<p>time.ctime() returns a string, that is the source of your error.</p> <p><a href="http://www.tutorialspoint.com/python/time_ctime.htm" rel="nofollow">See Python time.ctime</a></p> <p>time.time() is probably what you are looking for:</p> <p><a href="http://www.tutorialspoint.com/python/python_date_time.htm" rel="no...
0
2016-07-01T05:17:33Z
[ "python" ]
Error while calculating time diff
38,137,480
<p>I am running into following error while calculating time diff?how to fix it?</p> <pre><code>from datetime import datetime, date import time print "Start : %s" % time.ctime() start_time = time.ctime() #do something print "How to calculate time diff?" end_time = time.ctime() total_elapsed_time = datetime.combine(date...
-1
2016-07-01T05:10:10Z
38,137,620
<p>The error clearly states that argument 2 of combine() must be datetime.time.</p> <p>You should have an instance of <code>datetime.time</code> which is something like:</p> <pre><code>d = datetime.now() timepart = d.time() datepart = d.date() datetime.combine(datepart, timepart) </code></pre>
1
2016-07-01T05:24:06Z
[ "python" ]
Error while calculating time diff
38,137,480
<p>I am running into following error while calculating time diff?how to fix it?</p> <pre><code>from datetime import datetime, date import time print "Start : %s" % time.ctime() start_time = time.ctime() #do something print "How to calculate time diff?" end_time = time.ctime() total_elapsed_time = datetime.combine(date...
-1
2016-07-01T05:10:10Z
38,137,621
<p>Your start_time and end_time are strings. Also your datetime.combine should have the 2nd argument as a datetime.time object. Your time.ctime returns the date and year information as well. So first extract only the time information and then convert it to a datetime.time object.</p> <p>You can store the start and end...
0
2016-07-01T05:24:11Z
[ "python" ]
Error while calculating time diff
38,137,480
<p>I am running into following error while calculating time diff?how to fix it?</p> <pre><code>from datetime import datetime, date import time print "Start : %s" % time.ctime() start_time = time.ctime() #do something print "How to calculate time diff?" end_time = time.ctime() total_elapsed_time = datetime.combine(date...
-1
2016-07-01T05:10:10Z
38,137,794
<pre><code>from datetime import datetime, timedelta def calc(): s = datetime.now() e = datetime(day=21, month=7, year=2016, hour=12, minute=0) diff = e - s </code></pre> <p><strong>diff</strong> is datetime.timedelta instance now. On this instance you have properties such as days, seconds, microseconds a...
1
2016-07-01T05:40:03Z
[ "python" ]
Error while calculating time diff
38,137,480
<p>I am running into following error while calculating time diff?how to fix it?</p> <pre><code>from datetime import datetime, date import time print "Start : %s" % time.ctime() start_time = time.ctime() #do something print "How to calculate time diff?" end_time = time.ctime() total_elapsed_time = datetime.combine(date...
-1
2016-07-01T05:10:10Z
38,138,347
<p>First of all you are mixin 3 data types, so your approach is fundamentally wrong.</p> <p>There are two (basic) ways, how to get and store time in python (two from std lib):</p> <ol> <li>timestamp - you import <code>time</code> module, then <code>time.time()</code> will return a <code>float</code> - a number of sec...
1
2016-07-01T06:18:46Z
[ "python" ]
selenium (Firefox in background), sendkeys works but does not focus
38,137,586
<p>I am trying to run selenium for Firefox as a background process. I have to send text to an input box and then send Tab key to select a dynamically visible drop-down.</p> <p>Selenium is able to enter the text correctly but it is not able to send the tab key in the desired manner, i.e. when I try to send tab after te...
-1
2016-07-01T05:21:21Z
38,138,683
<p>Try with click in input box before sendkeys. So click -> sendkeys -> tab</p>
0
2016-07-01T06:40:41Z
[ "javascript", "python", "selenium" ]
Not able to start the instance since instance object variable not being updated , boto3
38,137,708
<p>I am trying to STOP and then START a list of instances, i need to check also if the instance is stopped or not and similarly for the start part.</p> <p>The code looks like</p> <pre><code>client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=region, ) response = cl...
0
2016-07-01T05:32:31Z
38,138,104
<p>This is a very busy loop, you might want to add a <code>sleep</code> in there.<br> You aren't updating the status but just referring the same status each time, you need to get the up-to-date status. Given you are just stopping a single <code>instance_id</code> then you can do:</p> <pre><code>ec2 = boto3.resource('e...
1
2016-07-01T06:03:17Z
[ "python" ]
SQLite Date type Error when querying a database for a website
38,137,782
<p>I have been stuck on this error for the longest and it is getting very annoying. I've checked my code countless times and like I said I'm annoyed as to why this SQLAlchemy error is coming up. </p> <p>What am I doing: I'm trying to send data to a Database in the format as a Date time i.e. "MM/DD/YYYY" through the us...
1
2016-07-01T05:38:59Z
38,138,360
<p>Looks like you are passing the <code>user_id</code> from the form as the <code>posted_date</code> in the <code>Task</code> constructor</p> <p><strong>Creating a new task from your view</strong></p> <pre><code>new_task = Task( form.name.data, form.due_date.data, form....
1
2016-07-01T06:19:58Z
[ "python", "sqlite", "date", "datetime" ]
filter DataFrame using dictionary
38,137,821
<p>I am new to pandas and python. I want to use dictionary to filter DataFrame</p> <pre><code>import pandas as pd from pandas import DataFrame df = DataFrame({'A': [1, 2, 3, 3, 3, 3], 'B': ['a', 'b', 'f', 'c', 'e', 'c'], 'D':[0,0,0,0,0,0]}) my_filter = {'A':[3], 'B':['c']} </code></pre> <p>When I call</p> <pre><cod...
1
2016-07-01T05:42:07Z
38,137,875
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> of <code>True</code> by columns and then compare with <code>2</code>:</p> <pre><code>print (df.isin(my_filter).sum(1) == 2) 0 False 1 False 2 False 3 True 4 False 5 ...
1
2016-07-01T05:45:34Z
[ "python", "pandas", "dataframe" ]
not standard splitting
38,137,882
<p>I have string value like:</p> <p><strong>a='[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]'</strong></p> <p>I want to transform "a" into dictionary: the strings with preceding "-" character should be keys and what goes after the space should be values of the key preceding it. If we are working with "a", then wh...
0
2016-07-01T05:45:43Z
38,137,981
<p>You can split the string by '-' and then add the '-' back.</p> <pre><code>a = '[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]' a = a[1:-1] # get ride of the start and end [] sections = a.split('-') dict_a = {} for s in sections: s = s.strip() if len(s) == 0: continue key_value = s.split(' ...
1
2016-07-01T05:54:09Z
[ "python" ]
not standard splitting
38,137,882
<p>I have string value like:</p> <p><strong>a='[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]'</strong></p> <p>I want to transform "a" into dictionary: the strings with preceding "-" character should be keys and what goes after the space should be values of the key preceding it. If we are working with "a", then wh...
0
2016-07-01T05:45:43Z
38,138,014
<p>I can tell you a way to go about it. Strip the quotes and the outer brackets. Then split the string using spaces. Iterate over the list obtained and check for any opening brackets. Keep a count of the number of opening brackets, join all the list items as a string with spaces between each such item until you encount...
0
2016-07-01T05:57:01Z
[ "python" ]
not standard splitting
38,137,882
<p>I have string value like:</p> <p><strong>a='[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]'</strong></p> <p>I want to transform "a" into dictionary: the strings with preceding "-" character should be keys and what goes after the space should be values of the key preceding it. If we are working with "a", then wh...
0
2016-07-01T05:45:43Z
38,138,269
<p>Using a regular expression:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dict(re.findall('(-\S+) ([^-]+)', a[:-1].replace(' -', '-'))) {'-sfdfj': 'aidjf', '-dugs': 'jfdsif', '-usda': '[[s dfdsf sdf]]'} </code></pre> <p>Using @ChongTang's idea:</p> <pre><code>&gt;&gt;&gt; dict(('-' + b).strip().split(maxspli...
0
2016-07-01T06:13:59Z
[ "python" ]
not standard splitting
38,137,882
<p>I have string value like:</p> <p><strong>a='[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]'</strong></p> <p>I want to transform "a" into dictionary: the strings with preceding "-" character should be keys and what goes after the space should be values of the key preceding it. If we are working with "a", then wh...
0
2016-07-01T05:45:43Z
38,138,920
<p>You can try this:</p> <pre><code>import re a='[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]' pattern_key=re.compile(r'(?P&lt;key&gt;-\S+)\s+') pattern_val=re.compile(r' (?P&lt;val&gt;[^-].*?)( -|\Z)') d={} matches=pattern_key.finditer(a) matches1=pattern_val.finditer(a) for m,n in zip(matches, matches1): ...
0
2016-07-01T06:56:01Z
[ "python" ]
I don't understand this error: TypeError: 'float' object cannot be interpreted as an integer
38,137,904
<p>I'm trying to run this code from <a href="https://abhishekds.com/2016/04/19/retrieve-all-stock-symbols-from-yahoo-finance-using-python/" rel="nofollow">here</a>:</p> <pre><code>import re, sys, time, string from bs4 import BeautifulSoup import urllib2 import logging class FetchAllSybols(object): def __init__(s...
1
2016-07-01T05:47:46Z
38,137,974
<p><code>final_search_page_count = total_search_qty/20</code></p> <p>I dont know python but the problem seems to be that in the line above should round up to the nearest integer.</p> <p>This is a smaller case with the same problem:</p> <p><code>range(1, 3.33, 1)</code></p>
1
2016-07-01T05:53:41Z
[ "python", "python-3.x" ]
I don't understand this error: TypeError: 'float' object cannot be interpreted as an integer
38,137,904
<p>I'm trying to run this code from <a href="https://abhishekds.com/2016/04/19/retrieve-all-stock-symbols-from-yahoo-finance-using-python/" rel="nofollow">here</a>:</p> <pre><code>import re, sys, time, string from bs4 import BeautifulSoup import urllib2 import logging class FetchAllSybols(object): def __init__(s...
1
2016-07-01T05:47:46Z
38,137,990
<p>The <code>range()</code> function is expecting an integer, while <code>total_page_to_scan</code> is a float value. You should find a way to return an int in your <code>get_total_page_to_scan_for_alphabet()</code>:</p> <pre><code>def get_total_page_to_scan_for_alphabet(self, alphabet): ... return int(final_s...
1
2016-07-01T05:55:17Z
[ "python", "python-3.x" ]
I don't understand this error: TypeError: 'float' object cannot be interpreted as an integer
38,137,904
<p>I'm trying to run this code from <a href="https://abhishekds.com/2016/04/19/retrieve-all-stock-symbols-from-yahoo-finance-using-python/" rel="nofollow">here</a>:</p> <pre><code>import re, sys, time, string from bs4 import BeautifulSoup import urllib2 import logging class FetchAllSybols(object): def __init__(s...
1
2016-07-01T05:47:46Z
38,138,007
<p>You're using a script that was written for <code>Python 2</code> in <code>Python 3</code>. In <code>Python 2</code> the division operator yields an integer, in <code>3</code> it yields a <code>float</code>:</p> <p><em>Python 2</em>:</p> <pre><code>&gt;&gt;&gt; 20 / 10 2 &gt;&gt;&gt; range(0, 20/10) [0, 1] </code><...
1
2016-07-01T05:56:37Z
[ "python", "python-3.x" ]
I don't understand this error: TypeError: 'float' object cannot be interpreted as an integer
38,137,904
<p>I'm trying to run this code from <a href="https://abhishekds.com/2016/04/19/retrieve-all-stock-symbols-from-yahoo-finance-using-python/" rel="nofollow">here</a>:</p> <pre><code>import re, sys, time, string from bs4 import BeautifulSoup import urllib2 import logging class FetchAllSybols(object): def __init__(s...
1
2016-07-01T05:47:46Z
38,138,970
<p>As stated by Jim, you can use the following to ensure an integer result. </p> <pre><code>final_search_page_count = total_search_qty // 20 </code></pre> <p>Alternatively, you can use</p> <pre><code>final_search_page_count = int(total_search_qty / 20) </code></pre> <p>This is important because <code>range()</code>...
1
2016-07-01T06:58:11Z
[ "python", "python-3.x" ]
Animate image ( left to right ) opencv python
38,138,043
<p>I've a task to move an image ( file.jpg ) from left to right side using openCV and python. </p> <p>i've tried </p> <pre><code>import cv2 img=cv2.imread('C:/Python27/03323_HD.jpg') cv2.imshow('ImageWindow',img) cv2.waitKey() </code></pre> <p>but its simply opening the image . instead of that just vibrate/shake ani...
0
2016-07-01T05:59:16Z
38,139,018
<p>From what I understand we need to open piece-wise. While <code>imshow</code> only opens the whole image at one go, we can first chose a region of an image and then increase it slowly with time and show it using <code>imshow</code>.</p> <p>I am showing left to right, you can try other variants also.</p> <pre><code...
1
2016-07-01T07:00:40Z
[ "python", "opencv" ]
Using LLDB Commands in Python Script
38,138,060
<p>I'm writing a Python script to use in Xcode's LLDB. I have this simple script up and running:</p> <pre><code>import lldb def say_hello(debugger, command, result, dict): print command def __lldb_init_module (debugger, dict): debugger.HandleCommand('command script add -f sayhello.say_hello hello') </code></pre>...
0
2016-07-01T06:00:32Z
38,152,048
<p>IIRC XCUIApplication is a function provided by the XCTest framework, so it is a function in the program you are debugging. So you would call it the same way you call any other function, using the "EvaluateExpression" API either on SBTarget or on SBFrame. The result of evaluating the expression will be returned to ...
1
2016-07-01T18:39:59Z
[ "python", "objective-c", "xcode", "swift", "lldb" ]
ValueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: 1.0
38,138,067
<p>I have a training dataset of 8670 trials and each trial has a length of 125-time samples while my test set consists of 578 trials. When I apply SVM algorithm from scikit-learn, I get pretty good results. </p> <p>However, when I apply logistic regression, this error occurs:</p> <blockquote> <p>"ValueError: This s...
1
2016-07-01T06:00:55Z
38,660,281
<p>I read this in the following issue on a similar linear module:<a href="https://github.com/lensacom/sparkit-learn/issues/49" rel="nofollow">https://github.com/lensacom/sparkit-learn/issues/49</a></p> <p>"Sadly this is a bug indeed. Sparkit trains sklearn's linear models in parallel, then averages them in a reduce st...
0
2016-07-29T13:35:05Z
[ "python", "scikit-learn", "svm", "logistic-regression" ]
Send JSON object via POST from JavaScript to Python
38,138,142
<p>There is a client-side JavaScript and server-side Python, powered by Django. There is a data object: <code>foo_data = {"foo":1, "bar":2}</code>.</p> <p>Now, I would like to send a post-request using <code>dojo/request/xhr</code>, and send <code>foo_data</code> along with another variable:</p> <pre><code>xhr.post(d...
1
2016-07-01T06:05:51Z
38,138,386
<p>dojo.xhr has been deprecated, please consider using <code>dojo/request</code> more info here:</p> <p><a href="https://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html#dojo-request-xhr" rel="nofollow">https://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html#dojo-request-xhr</a> </p> <p>For a liv...
2
2016-07-01T06:21:46Z
[ "javascript", "python", "json", "django", "dojo" ]
how do I match an element with a list?
38,138,143
<p>I am trying to match <code>id</code> with <code>id_list</code> using a one-liner,following doesnt seem to work,how do I fix it?</p> <pre><code>id = 77bb1b03 id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', ''] if id in id_list: print "id present" else: print "id not present...
1
2016-07-01T06:05:51Z
38,138,176
<p>You aren't matching on equality but on a substring of the values in the list, assuming you just want to match the start:<br> Note: assuming <code>id</code> is actually a string because it isn't a valid literal.</p> <pre><code>id = '77bb1b03' id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tde...
2
2016-07-01T06:08:20Z
[ "python" ]
how do I match an element with a list?
38,138,143
<p>I am trying to match <code>id</code> with <code>id_list</code> using a one-liner,following doesnt seem to work,how do I fix it?</p> <pre><code>id = 77bb1b03 id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', ''] if id in id_list: print "id present" else: print "id not present...
1
2016-07-01T06:05:51Z
38,138,247
<p>First, fix your code:</p> <pre><code>id = "77bb1b03" # needs to be a string id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', ''] </code></pre> <p>Then loop over the list and compare each string individually:</p> <pre><code>for s in id_list: if id in s: print "id %s pres...
0
2016-07-01T06:12:23Z
[ "python" ]
how do I match an element with a list?
38,138,143
<p>I am trying to match <code>id</code> with <code>id_list</code> using a one-liner,following doesnt seem to work,how do I fix it?</p> <pre><code>id = 77bb1b03 id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', ''] if id in id_list: print "id present" else: print "id not present...
1
2016-07-01T06:05:51Z
38,138,299
<p>Check this out:<br> Single liner as you demanded and id is a string!</p> <pre><code>&gt;&gt;&gt; from __future__ import print_function ... id = '77bb1b03' ... id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', ''] ... [print(item, 'ID present') for item in id_list if item and item.find...
0
2016-07-01T06:15:34Z
[ "python" ]
how do I match an element with a list?
38,138,143
<p>I am trying to match <code>id</code> with <code>id_list</code> using a one-liner,following doesnt seem to work,how do I fix it?</p> <pre><code>id = 77bb1b03 id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', ''] if id in id_list: print "id present" else: print "id not present...
1
2016-07-01T06:05:51Z
38,141,146
<p>A nasty, obscure, slower alternative to those that will/are shown. The <code>id</code> var seems to prefix list items, but not sure if you would ever have need to find the <code>id</code> "somewhere" inside a list element.</p> <pre><code>id = 77bb1b03 id_list = ['List of devices attached ', '572ea01e\tdevice', '77...
0
2016-07-01T08:55:27Z
[ "python" ]
When store data including foreign key, errors occur in Django?
38,138,159
<p>I'm developing django web service with Python3.5 and Django1.9.</p> <p>I define models like belows:</p> <pre><code>from django.db import models from django.utils import timezone class URLCategory(models.Model): url = models.CharField(max_length=200, null=True) class Post(models.Model): title = models.Cha...
0
2016-07-01T06:06:48Z
38,138,174
<p>It should be</p> <pre><code>url_category = URLCategory.objects.create(url="http://example.org") post = Post(title="Title", created_date="06/29/2016", site=url_category) post.save() </code></pre>
0
2016-07-01T06:08:18Z
[ "python", "django", "model" ]
insert string at beginning of regex in python
38,138,276
<p>In below code, the string "Graph" is replacing the matched regex:</p> <pre><code>htmlText = re.sub("[0-9]*/index.html", 'Graph', htmlText, re.MULTILINE|re.DOTALL) </code></pre> <p>But the problem is, I want to prepend 'Graph' to the beginning of the matched <code>'[0-9]*/index.html'</code> expression, not replace ...
0
2016-07-01T06:14:28Z
38,138,377
<p>You want to capture the match (by surrounding your regex with parens), then backreference it (via <code>\1</code>), using a <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">raw string</a> (via <code>r</code> before the replacement string) to prevent the backslash fro...
2
2016-07-01T06:21:18Z
[ "python", "regex" ]
Trying to plot a defined function
38,138,417
<p>I have a problem. I'm trying to plot a function for different values of <code>d</code>. I have defined <code>d</code> as: </p> <pre><code>d = np.arange(0.0, 100.0, 0.01) </code></pre> <p>But I still get the same error:</p> <blockquote> <p>TypeError: only length-1 arrays can be converted to Python scalars</p> </...
3
2016-07-01T06:23:35Z
38,138,543
<p>You have to vectorize your function <code>teo_function</code> to work with an array:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import math def teo_function(d): return 2*math.pi*math.sqrt(((1**2)/(12+d**2))/9.81*d) vecfunc = np.vectorize(teo_function) d = np.arange(0.0, 100.0, 0.01) T =...
2
2016-07-01T06:32:12Z
[ "python", "numpy", "matplotlib" ]
Trying to plot a defined function
38,138,417
<p>I have a problem. I'm trying to plot a function for different values of <code>d</code>. I have defined <code>d</code> as: </p> <pre><code>d = np.arange(0.0, 100.0, 0.01) </code></pre> <p>But I still get the same error:</p> <blockquote> <p>TypeError: only length-1 arrays can be converted to Python scalars</p> </...
3
2016-07-01T06:23:35Z
38,138,638
<p>the function <code>teo_function</code> uses <code>math.sqrt</code> which works on scalars, not on arrays. If you ever use numpy arrays, use the math operations which are included in <code>numpy</code>, eg. <code>numpy.sqrt</code>. Numpy has equivalent to all functions i know in the <code>math.module</code> optimized...
1
2016-07-01T06:37:55Z
[ "python", "numpy", "matplotlib" ]
Trying to plot a defined function
38,138,417
<p>I have a problem. I'm trying to plot a function for different values of <code>d</code>. I have defined <code>d</code> as: </p> <pre><code>d = np.arange(0.0, 100.0, 0.01) </code></pre> <p>But I still get the same error:</p> <blockquote> <p>TypeError: only length-1 arrays can be converted to Python scalars</p> </...
3
2016-07-01T06:23:35Z
38,141,882
<p>Another way. If you want your function to return a list</p> <pre><code>def teo_function(ds): return [2*math.pi*math.sqrt(((1**2)/(12+d**2))/9.81*d) for d in ds] </code></pre>
1
2016-07-01T09:30:56Z
[ "python", "numpy", "matplotlib" ]
Sqlite version for Firefox 40.0
38,138,533
<p>I am trying to access cookies.sqlite of a firefox profile using embedded sqlite3 in python.</p> <pre><code>&gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; conn = sqlite3.connect(COOKIES_FILEPATH) </code></pre> <p>*COOKIES_FILEPATH is replaced with actual file path.</p> <p>On running the above script, I am facing the fol...
1
2016-07-01T06:31:36Z
38,138,745
<p>SQLite has an excellent track record of maintaining backwards compatibility, and the error message would reflect it if there was an issue with the database file.</p> <p>The error indicates that you have your path wrong. Make sure you have an absolute path to the file that you have verified to exist. You could use P...
1
2016-07-01T06:44:36Z
[ "python", "sqlite", "firefox", "cookies", "sqlite3" ]