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
How to rearrange a multidimensional array
38,673,268
<p>So for various reasons that go outside of this post, I am writing a file that transfers data from one place to another. I have some of the data held in a series of multidimensional arrays</p> <p>lets pretend I have a 4 dimensional array with the following shape/dimensions: [x, y, z, n]</p> <p>How would I rearrange...
0
2016-07-30T11:12:32Z
38,673,357
<p>for the horizontal flipping you only need one loop. you need to go from the first place to the centered place, and replace each one with the same one on the opposite. for example:</p> <pre><code>lets say that we have an int length. and then: for(int i=0;i&lt;length/2;i++) { switch array[i] with array[length-i] }...
0
2016-07-30T11:20:29Z
[ "python", "arrays", "multidimensional-array" ]
Custom JSONField in Django
38,673,401
<p>I am trying to implement a custom JSON Field for my models using Django + MySQL. This is what my <strong>models.py</strong> looks like:</p> <pre><code>from __future__ import unicode_literals from django.db import models from django.db import models from django.core.serializers.json import DjangoJSONEncoder import j...
0
2016-07-30T11:26:03Z
38,673,441
<p>According to exception and <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.Field.get_db_prep_save" rel="nofollow">django docs</a>, your <code>get_db_prep_save</code> method should take one more argument, called <code>connection</code>, so this:</p> <pre><code> def get_db_prep_s...
0
2016-07-30T11:29:14Z
[ "python", "mysql", "json", "django", "django-jsonfield" ]
lxml is not detecting empty div as expected
38,673,474
<p>For the below input, <code>lxml</code> modifies the <code>div</code> as if it understands that <code>div</code> can't be inside <code>p</code>.</p> <p>Can anyone tell me how to just get the <code>&lt;div&gt;&lt;/div&gt;</code> for this type of input? I want to correct the input HTML.</p> <p>Do I need to switch to ...
0
2016-07-30T11:33:12Z
38,674,670
<p>You need to pass some additional arguments to change the behavior of tostring():</p> <pre><code>etree.tostring(d, method="html", with_tail=False) '&lt;div&gt;&lt;/div&gt;' </code></pre>
0
2016-07-30T13:51:20Z
[ "python", "lxml" ]
lxml is not detecting empty div as expected
38,673,474
<p>For the below input, <code>lxml</code> modifies the <code>div</code> as if it understands that <code>div</code> can't be inside <code>p</code>.</p> <p>Can anyone tell me how to just get the <code>&lt;div&gt;&lt;/div&gt;</code> for this type of input? I want to correct the input HTML.</p> <p>Do I need to switch to ...
0
2016-07-30T11:33:12Z
38,678,456
<p>You can use the <a href="http://lxml.de/elementsoup.html" rel="nofollow">soupparser</a> in <em>lxml</em> and still process the data with xpaths etc..:</p> <pre><code>from lxml.html.soupparser import fromstring html_element = fromstring(html_string) </code></pre> <p>That will maintain <code>&lt;div&gt;&lt;/div&gt;...
1
2016-07-30T21:01:09Z
[ "python", "lxml" ]
Dont show me again checkbox
38,673,481
<p>I want a window with "don't show me again" (a toplevel-window). If this box get's checked, I don't want it showing me this window another time.</p> <pre><code>import configparser from tkinter import * config = configparser.RawConfigParser() #my ini file config.add_section('Section1') config.set('Section1', 'a_b...
-1
2016-07-30T11:34:05Z
38,673,937
<p>For the variable of a <code>Checkbutton</code> to work, it should be an <code>IntVar</code> or a <code>BooleanVar</code>. So I replaced the <code>var1</code> in your code by a <code>BooleanVar</code>:</p> <pre><code>def var_states(): #write to ini file global mt print(config.read('a...
0
2016-07-30T12:25:08Z
[ "python", "tkinter", "configparser" ]
Subset in Python output error - HackerRank
38,673,491
<p><strong><em>This is a question from <a href="https://www.hackerrank.com/challenges/py-check-subset" rel="nofollow">HackerRank</a></em></strong></p> <p>You are given two sets <code>A</code> and <code>B</code>.</p> <p>Your job is to find whether set <code>A</code> is a subset of set <code>B</code>.</p> <p>If set <c...
-1
2016-07-30T11:34:41Z
38,673,509
<p>The problem specification says this:</p> <blockquote> <p>Note: More than 4 lines will result in a score of zero. Blank lines won't be counted.</p> </blockquote> <p>Your solution uses 7 lines, so it counts as a failure.</p>
1
2016-07-30T11:36:35Z
[ "python", "python-2.7", "set", "subset" ]
How to store prices for every pair of objects
38,673,512
<p>I'm working on a web app. This app has model <code>Location</code> which can be New York, Wienna, Paris etc. </p> <p>Now I want to have some data structure/table which holds <strong>price</strong> for any tuple from set of <code>Location</code> objects. </p> <p>So if there are 3 objects yet - NY, PA, WI, I have to...
0
2016-07-30T11:36:54Z
38,673,681
<p>What I think would be nice solution is to have each <code>Location</code> model a <code>ManyToManyField</code> field, which links to <code>CityPrice</code> model. That way many <code>Location</code> models will share the same price and you will be able to have multiple prices assigned to a single city.</p> <pre><co...
0
2016-07-30T11:58:41Z
[ "python", "django", "django-models", "django-admin", "django-orm" ]
Multiply numpy int and float arrays
38,673,531
<p>I'd like to multiply an <code>int16</code> array but a <code>float</code> array, with auto rounding, but this fails :</p> <pre><code>import numpy A = numpy.array([1, 2, 3, 4], dtype=numpy.int16) B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64) A *= B </code></pre> <p>I get: </p> <blockquote> <p>TypeErro...
2
2016-07-30T11:39:30Z
38,677,336
<p>You could use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> to multiply the two arrays and take only the integer part as follows:</p> <pre><code>In [2]: (A*B).astype(int) Out[2]: array([ 0, 4, 9, 16]) </code></pre> <p><strong>Timing Constrain...
1
2016-07-30T18:40:33Z
[ "python", "arrays", "numpy", "floating-point", "int" ]
Multiply numpy int and float arrays
38,673,531
<p>I'd like to multiply an <code>int16</code> array but a <code>float</code> array, with auto rounding, but this fails :</p> <pre><code>import numpy A = numpy.array([1, 2, 3, 4], dtype=numpy.int16) B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64) A *= B </code></pre> <p>I get: </p> <blockquote> <p>TypeErro...
2
2016-07-30T11:39:30Z
38,677,658
<pre><code>import numpy as np A = np.float_(A) A *= B </code></pre> <p>try this. I think are different array type you get fail.</p> <p>Cast </p>
1
2016-07-30T19:18:09Z
[ "python", "arrays", "numpy", "floating-point", "int" ]
Can I use Hendrix to run Falcon app?
38,673,550
<p>Hendrix is a WSGI compatible server written in Tornado. I was wondering if it can be used to run an app written in Falcon ? </p>
1
2016-07-30T11:42:18Z
38,676,247
<p>So found the solution. Created a python file according to hendrix's docs. And imported my app's wsgi callable there.</p>
1
2016-07-30T16:44:26Z
[ "python", "tornado", "wsgi", "falcon", "hendrix" ]
How to implement python script to run on "N" number of CPU CORES?
38,673,565
<p>I have made a script to optimize particular part of structure. (scientific terms , you can ignore it) but the main purpose of script is optimization and it takes major time during these two steps optimize () and refine() function where it uses only one CPU out of 4 CPU's in my local system but i want to make this sc...
0
2016-07-30T11:44:07Z
38,677,305
<p>Please check pp module. <a href="http://www.parallelpython.com/" rel="nofollow">Parallelpython.com</a> </p>
0
2016-07-30T18:36:42Z
[ "python", "multithreading", "parallel-processing", "multiprocessing", "multicore" ]
How to implement python script to run on "N" number of CPU CORES?
38,673,565
<p>I have made a script to optimize particular part of structure. (scientific terms , you can ignore it) but the main purpose of script is optimization and it takes major time during these two steps optimize () and refine() function where it uses only one CPU out of 4 CPU's in my local system but i want to make this sc...
0
2016-07-30T11:44:07Z
38,786,046
<p>Finally I have done myself by another method called multiprocessing.pool based on the blog <a href="http://chriskiehl.com/article/parallelism-in-one-line/" rel="nofollow">http://chriskiehl.com/article/parallelism-in-one-line/</a> and <a href="https://pymotw.com/2/multiprocessing/basics.html" rel="nofollow">https://p...
1
2016-08-05T09:37:00Z
[ "python", "multithreading", "parallel-processing", "multiprocessing", "multicore" ]
python: list index out of range error in code
38,673,583
<p>I'm pretty new to python, and really stuck at this.</p> <p>Basically, I'm supposed to make a check code to check the last alphabet of the NRIC. My code works fine so long as there are 7 numbers (like there are supposed to be). However, my teacher just helped me find out that my code doesn't work whenever the number...
-1
2016-07-30T11:46:35Z
38,673,616
<p>When you convert the string input into an <code>int</code>, the leading zero is stripped away (e.g. <code>"0153444"</code> -> <code>153444</code>). When you convert back to a string again in the list comprehension, you won't get the zero back, so you end up with an NRIC list of [1, 5, 3, 4, 4, 4] instead of [0, 1, 5...
2
2016-07-30T11:50:41Z
[ "python" ]
python: list index out of range error in code
38,673,583
<p>I'm pretty new to python, and really stuck at this.</p> <p>Basically, I'm supposed to make a check code to check the last alphabet of the NRIC. My code works fine so long as there are 7 numbers (like there are supposed to be). However, my teacher just helped me find out that my code doesn't work whenever the number...
-1
2016-07-30T11:46:35Z
38,673,856
<p>Edit: This code verifies if the input is made of 7 digits.</p> <pre><code>def check_code(): while True: nricno = input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will restart.") if len(nricno) == 7 and nricno.digits == True: print ("Wo...
0
2016-07-30T12:16:12Z
[ "python" ]
python: list index out of range error in code
38,673,583
<p>I'm pretty new to python, and really stuck at this.</p> <p>Basically, I'm supposed to make a check code to check the last alphabet of the NRIC. My code works fine so long as there are 7 numbers (like there are supposed to be). However, my teacher just helped me find out that my code doesn't work whenever the number...
-1
2016-07-30T11:46:35Z
38,674,235
<p>Here's a compact way to calculate the NRIC check code. If an invalid string is passed to the function a ValueError exception is raised, which will cause the program to crash. And if a non-string is passed TypeError will be raised. You can catch exceptions using the <code>try:... except</code> syntax.</p> <pre><code...
1
2016-07-30T12:59:05Z
[ "python" ]
python: list index out of range error in code
38,673,583
<p>I'm pretty new to python, and really stuck at this.</p> <p>Basically, I'm supposed to make a check code to check the last alphabet of the NRIC. My code works fine so long as there are 7 numbers (like there are supposed to be). However, my teacher just helped me find out that my code doesn't work whenever the number...
-1
2016-07-30T11:46:35Z
39,585,944
<p>When you force your input as an int, the leading 0 will be interpreted as an error in Python 3. For example, <code>int(0351)</code> would not yield either <code>0351</code> or <code>351</code> but would just cause an error stating <code>invalid token</code>.</p> <p>You should not force the input to be an int, but i...
0
2016-09-20T04:54:30Z
[ "python" ]
Why does uploaded image permissions depends on it's size?
38,673,607
<p>Web application build using Django Framework</p> <ul> <li>Server: <code>CentOS Linux release 7.1.1503 (Core)</code></li> <li>Nginx: <code>nginx version: nginx/1.6.3</code></li> <li>Gunicorn: <code>gunicorn==19.3.0</code></li> <li>Django: <code>Django==1.8.4</code></li> </ul> <p>When uploading image which is less t...
0
2016-07-30T11:49:12Z
38,673,672
<p>Django is using 2 upload handlers: <code>MemoryFileUploadHandler</code> and <code>TemporaryFileUploadHandler</code>. First one will keep uploaded file in ram, before deciding what to do with it. Second one will put file in temp directory and move it later to proper location.</p> <p>Problem probably occurs because m...
0
2016-07-30T11:58:15Z
[ "python", "django", "nginx", "centos", "gunicorn" ]
Using subprocess in python with multiple values and same argument
38,673,624
<p>This is my command</p> <pre><code>subprocess.call(["wine","MP4Box.exe","-add",outputdir+"tmp.m4a","-itags",'name=a',"-itags", "artist=b","-itags", "album_artist=c","-itags", "album=d","-itags", "created=2034","-itags", "genre=e","-new", "tmp23.m4a"]) </code></pre> <p>In the output file i can get only genre, subpro...
1
2016-07-30T11:51:51Z
38,673,720
<p>According to their <a href="https://gpac.wp.mines-telecom.fr/mp4box/mp4box-documentation/" rel="nofollow">documentation</a> the parameter should be passed like this </p> <blockquote> <p>-itags tag1[:tag2] </p> </blockquote> <p>So you may try to do it like so </p> <pre><code>subprocess.call(["wine","MP4Box.exe...
0
2016-07-30T12:02:19Z
[ "python", "subprocess", "xargs", "mp4box" ]
Using subprocess in python with multiple values and same argument
38,673,624
<p>This is my command</p> <pre><code>subprocess.call(["wine","MP4Box.exe","-add",outputdir+"tmp.m4a","-itags",'name=a',"-itags", "artist=b","-itags", "album_artist=c","-itags", "album=d","-itags", "created=2034","-itags", "genre=e","-new", "tmp23.m4a"]) </code></pre> <p>In the output file i can get only genre, subpro...
1
2016-07-30T11:51:51Z
38,673,732
<pre><code>outputdir = "output" subprocess.call([ "wine", "MP4Box.exe", "-add", outputdir + "/tmp.m4a", "-itags", "name={name}:artist={artist}:album_artist={album_artist}:album={album}:created={created}:genre={genre}".format( name="a", artist="b", album_artist="c", album="d", ...
1
2016-07-30T12:02:55Z
[ "python", "subprocess", "xargs", "mp4box" ]
Efficient method for matching data in multiple csv files
38,673,647
<p>Here is a snippet of my code:</p> <pre><code>for i,r1 in enumerate(Solution.values): h1=ProjectedRevenue.index[i] District_ID,Instrument_ID,Buy_or_not,Revenue=r1 listSol=[] listSol.append(h1) listSol.append(list(r1)[0]) listSol.append(list(r1)[1]) for j,r2 in enumerate(ProjectedRevenue.v...
-1
2016-07-30T11:54:28Z
38,673,655
<p>use <code>:</code> at the end of <code>if</code> check.</p> <pre><code>if h2 == listSol[0]: </code></pre>
0
2016-07-30T11:55:27Z
[ "python", "python-3.x", "numpy", "pandas" ]
Efficient method for matching data in multiple csv files
38,673,647
<p>Here is a snippet of my code:</p> <pre><code>for i,r1 in enumerate(Solution.values): h1=ProjectedRevenue.index[i] District_ID,Instrument_ID,Buy_or_not,Revenue=r1 listSol=[] listSol.append(h1) listSol.append(list(r1)[0]) listSol.append(list(r1)[1]) for j,r2 in enumerate(ProjectedRevenue.v...
-1
2016-07-30T11:54:28Z
38,675,126
<p>try this vectorized pandas approach:</p> <pre><code>In [22]: fn1 = r'D:\temp\.data\38673647\Solution.csv' In [23]: fn2 = r'D:\temp\.data\38673647\ProjectedRevenue.csv' In [24]: df1 = pd.read_csv(fn1) In [25]: df2 = pd.read_csv(fn2) In [26]: df1 Out[26]: Hospital_ID District_ID Instrument_ID 0 1 ...
1
2016-07-30T14:42:07Z
[ "python", "python-3.x", "numpy", "pandas" ]
How can create Android app using Django REST API
38,673,676
<p>How can create an Android App with Django back-end. I have created REST API but unable to communicate between Android and API. Any luck...Thanks in advance..</p>
-1
2016-07-30T11:58:19Z
38,676,081
<p>Communicating to your REST-API should be made via SSL-encrypted calls to your specified endpoints like <a href="https://myurl.com/api/call_method" rel="nofollow">https://myurl.com/api/call_method</a></p> <p>You can use androids HttpUrlConnection to access your server. Preprocess your user input in a task specific h...
0
2016-07-30T16:27:34Z
[ "android", "python", "django" ]
How can I call Python script from URL and get parameters
38,673,764
<p>I call my script with <a href="http://domain/script.py" rel="nofollow">http://domain/script.py</a> How can I call the script with a parameter and get the parameter in the python script when I call it like <a href="http://domain/script.py?parmameter=value" rel="nofollow">http://domain/script.py?parmameter=value</a> I...
0
2016-07-30T12:07:11Z
38,673,846
<p>Tell us more about your setup and what is working. What is serving your Python script? Are you using a Web server like nginx or Apache?<br> You can not normally run a Python script via a Web browser without some kind of interface - otherwise you would just get the source of the Python file served as text.<br> If you...
0
2016-07-30T12:15:01Z
[ "python", "url", "server" ]
Spark 2.0 Possible Bug on DataFrame Initialization
38,673,826
<p>There is possible bug that is produced by the following code :</p> <pre><code>_struct = [ types.StructField('string_field', types.StringType(), True), types.StructField('long_field', types.LongType(), True), types.StructField('double_field', types.DoubleType(), True) ] _rdd = sc.parallelize([Row(string_field=...
1
2016-07-30T12:13:40Z
38,674,803
<p>This looks like a change of behavior between 1.x and 2.x but I doubt it is a bug. In particular when you create <code>Row</code> object with <code>kwargs</code> (named arguments) <a href="https://github.com/apache/spark/blob/274f3b9ec86e4109c7678eef60f990d41dc3899f/python/pyspark/sql/types.py#L1375-L1376" rel="nofol...
4
2016-07-30T14:06:19Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
Redefine *= operator in numpy
38,673,878
<p>As <a href="http://stackoverflow.com/questions/38673531/multiply-numpy-int-and-float-arrays">mentioned here</a> and <a href="https://github.com/numpy/numpy/pull/6499/files" rel="nofollow">here</a>, this doesn't work anymore in numpy 1.7+ :</p> <pre><code>import numpy A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)...
4
2016-07-30T12:18:32Z
38,673,941
<p>You can create a general function and pass the intended attribute to it:</p> <pre><code>def calX(a,b, attr): try: return getattr(numpy, attr)(a, b, out=a, casting="unsafe") except AttributeError: raise Exception("Please enter a valid attribute") </code></pre> <p>Demo:</p> <pre><code>&gt;&g...
1
2016-07-30T12:25:34Z
[ "python", "arrays", "numpy", "subclass" ]
Redefine *= operator in numpy
38,673,878
<p>As <a href="http://stackoverflow.com/questions/38673531/multiply-numpy-int-and-float-arrays">mentioned here</a> and <a href="https://github.com/numpy/numpy/pull/6499/files" rel="nofollow">here</a>, this doesn't work anymore in numpy 1.7+ :</p> <pre><code>import numpy A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)...
4
2016-07-30T12:18:32Z
38,674,413
<p>You can use <code>np.set_numeric_ops</code> to override array arithmetic methods:</p> <pre><code>import numpy as np def unsafe_multiply(a, b, out=None): return np.multiply(a, b, out=out, casting="unsafe") np.set_numeric_ops(multiply=unsafe_multiply) A = np.array([1, 2, 3, 4], dtype=np.int16) B = np.array([0....
6
2016-07-30T13:22:53Z
[ "python", "arrays", "numpy", "subclass" ]
Find the row indexes of several values in a numpy array
38,674,027
<p>I have an array X:</p> <pre><code>X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) </code></pre> <p>And I wish to find the index of the row of several values in this array:</p> <pre><code>searched_values = np.array([[4, 2], ...
4
2016-07-30T12:34:59Z
38,674,038
<p><strong>Approach #1</strong></p> <p>One approach would be to use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a>, like so -</p> <pre><code>np.where((X==searched_values[:,None]).all(-1))[1] </code></pre> <p><strong>Approach #2</strong></p> ...
5
2016-07-30T12:36:15Z
[ "python", "arrays", "numpy" ]
Find the row indexes of several values in a numpy array
38,674,027
<p>I have an array X:</p> <pre><code>X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) </code></pre> <p>And I wish to find the index of the row of several values in this array:</p> <pre><code>searched_values = np.array([[4, 2], ...
4
2016-07-30T12:34:59Z
38,674,119
<pre><code>X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) S = np.array([[4, 2], [3, 3], [5, 6]]) result = [[i for i,row in enumerate(X) if (s==row).all()] for s in S] </code></pre> <p>or</p> <pre><code>result = [i for s...
2
2016-07-30T12:45:41Z
[ "python", "arrays", "numpy" ]
Find the row indexes of several values in a numpy array
38,674,027
<p>I have an array X:</p> <pre><code>X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) </code></pre> <p>And I wish to find the index of the row of several values in this array:</p> <pre><code>searched_values = np.array([[4, 2], ...
4
2016-07-30T12:34:59Z
38,675,193
<p>Another alternative is to use <code>asvoid</code> (below) to <code>view</code> each row as a <em>single</em> value of <code>void</code> dtype. This reduces a 2D array to a 1D array, thus allowing you to use <code>np.in1d</code> as usual:</p> <pre><code>import numpy as np def asvoid(arr): """ Based on http:...
5
2016-07-30T14:49:06Z
[ "python", "arrays", "numpy" ]
Find the row indexes of several values in a numpy array
38,674,027
<p>I have an array X:</p> <pre><code>X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) </code></pre> <p>And I wish to find the index of the row of several values in this array:</p> <pre><code>searched_values = np.array([[4, 2], ...
4
2016-07-30T12:34:59Z
39,587,388
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains functionality for performing such operations efficiently (also uses searchsorted under the hood). In terms of functionality, it acts as a vectorized equivalent of lis...
0
2016-09-20T06:45:20Z
[ "python", "arrays", "numpy" ]
Find the row indexes of several values in a numpy array
38,674,027
<p>I have an array X:</p> <pre><code>X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) </code></pre> <p>And I wish to find the index of the row of several values in this array:</p> <pre><code>searched_values = np.array([[4, 2], ...
4
2016-07-30T12:34:59Z
39,594,398
<p>Here is a pretty fast solution that scales up well using numpy and hashlib. It can handle large dimensional matrices or images in seconds. I used it on 520000 X (28 X 28) array and 20000 X (28 X 28) in 2 seconds on my CPU</p> <p>Code:</p> <pre><code>import numpy as np import hashlib X = np.array([[4, 2], ...
0
2016-09-20T12:40:41Z
[ "python", "arrays", "numpy" ]
Nested relative imports don't seem to work
38,674,106
<h2>Description</h2> <p>I have a package structure where various modules need to obtain information from different ones and therefore I use relative imports. It happens that those relative imports are nested in some way.<br> I'll just present you the package structure I have:</p> <pre><code>. ├── core │   â...
2
2016-07-30T12:44:26Z
38,675,544
<p>As @Blckknght pointed out, you have an import cycle. you can eliminate this annoying cycle by reorganizing your code.</p> <p>But if you don't have to invoke <code>core.sub2.mod1</code> immediately when importing <code>core.sub1.mod1</code>, there is a simple way to fix it.</p> <p>You can import <code>core.sub2</co...
0
2016-07-30T15:24:40Z
[ "python", "python-2.7", "import" ]
How to write Django class-based view for form displaying and submission from other template?
38,674,150
<p>I have a ModelForm that I’d like to display in multiple places. For instance, in a ListView, underneath the list of articles. I can do this by putting it in <code>get_context_data()</code> in the ListView. I’d also like to display the form in its own template.</p> <p>I’ve created a view for the form, but am n...
0
2016-07-30T12:49:24Z
38,681,482
<p>As it turns out, I don’t need django-betterforms. A regular modelform works just fine. There were some other mistakes as well.</p> <p>This is the code.</p> <p><code>models.py</code></p> <pre><code>class Article(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=20...
0
2016-07-31T06:44:14Z
[ "python", "django", "django-forms", "django-templates", "django-class-based-views" ]
Python 2.7 converting list of strings to dictionary
38,674,163
<p>I am trying to transform a list of the type</p> <pre><code>list = ['a=1','b=2','c=3','d=4'] </code></pre> <p>to a dictionary of the type</p> <pre><code>dictionary = {'a':'1', 'b':'2', 'c':'3', 'd':'4'} </code></pre> <p>How can I do this?</p>
-5
2016-07-30T12:51:14Z
38,674,188
<p>That suppose to work for you:</p> <pre><code>items = ['a=1','b=2','c=3','d=4'] d = {} for item in items: a, b = item.split('=') d.update({a:b}) print d # {'a': '1', 'c': '3', 'b': '2', 'd': '4'} </code></pre> <p>Good Luck!</p>
0
2016-07-30T12:54:07Z
[ "python", "data-type-conversion" ]
Keras VGG extract features
38,674,189
<p>I have loaded a pre-trained VGG face CNN and have run it successfully. I want to extract the hyper-column average from layers 3 and 8. I was following the section about extracting hyper-columns from <a href="http://blog.christianperone.com/2016/01/convolutional-hypercolumns-in-python/">here</a>. However, since the g...
5
2016-07-30T12:54:12Z
38,760,402
<p>It confused me a lot:</p> <ol> <li>After <code>layers = [K.function([model.layers[0].input],[model.layers[li].output])([instance])[0] for li in layer_indexes]</code>, layers is list of extracted feature.</li> <li>And then you send that list into <code>feature_maps = get_features(model,layers,instance)</code>.</li> ...
0
2016-08-04T06:54:35Z
[ "python", "deep-learning", "theano", "keras" ]
Python/Matplotlib: 2d random walk with kde joint density contour in a 3d plot
38,674,204
<p>I'm struggling with creating a quite complex 3d figure in python, specifically using iPython notebook. I can partition the content of the graph into two sections:</p> <p><strong>The (x,y) plane:</strong> Here a two-dimensional random walk is bobbing around, let's call it G(). I would like to plot part of this traje...
2
2016-07-30T12:55:27Z
38,714,154
<p>Final code, </p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt import random import numpy as np import seaborn as sns import scipy from mpl_toolkits.mplot3d import Axes3D from matplotlib.mlab import bivariate_normal %matplotlib inline # Data for random walk def randomwalk(): mpl.rc...
0
2016-08-02T07:22:21Z
[ "python", "matplotlib", "plot", "3d" ]
Python __super black magic failed
38,674,218
<p>I want to add an attribute for every class created by a metaclass. For example, when a class named <code>C</code> is created, I want add an attribute <code>C._C__sup</code> whose value is the descriptor <code>super(C)</code>.</p> <p>Here is what I've tried:</p> <pre><code>class Meta(type): def __init__(cls, na...
0
2016-07-30T12:57:24Z
38,674,382
<p>Use <code>setattr</code> instead of assignment to <code>cls.__dict__</code>:</p> <pre><code>class Meta(type): def __init__(cls, name, bases, clsdict): # Not overriding type.__new__ setattr(cls, '_' + name + '__sup', super(cls)) super(Meta, cls).__init__(name, bases, clsdict) class C(object): ...
2
2016-07-30T13:20:11Z
[ "python", "python-2.7", "attributes", "metaclass", "descriptor" ]
How to get the token with django rest framework and ajax
38,674,266
<p>I want to build a rest api where users can authenticate with tokens. I have included <code>rest_framework.authtoken</code> in the installed apps list. Also added the required configuration in the settings.py:</p> <pre><code>INSTALLED_APPS = ( ... 'rest_framework.authtoken' ) REST_FRAMEWORK = { 'DEFAULT...
1
2016-07-30T13:04:09Z
38,674,510
<p>By default the <code>type</code> or <code>method</code> value is set to 'GET' on jQuery.ajax() method. It lookls like the response you get, allows only 'POST', and 'OPTIONS'.</p> <p>How about you try to set <code>type</code> or <code>method</code> value to 'POST' on your jQuery.ajax() method.</p>
0
2016-07-30T13:34:39Z
[ "python", "ajax", "django", "rest", "django-rest-framework" ]
How to get the token with django rest framework and ajax
38,674,266
<p>I want to build a rest api where users can authenticate with tokens. I have included <code>rest_framework.authtoken</code> in the installed apps list. Also added the required configuration in the settings.py:</p> <pre><code>INSTALLED_APPS = ( ... 'rest_framework.authtoken' ) REST_FRAMEWORK = { 'DEFAULT...
1
2016-07-30T13:04:09Z
38,674,669
<p>This is a cors issue, try with Chromium and start it with chromium-browser --disable-web-security to test it</p>
0
2016-07-30T13:51:19Z
[ "python", "ajax", "django", "rest", "django-rest-framework" ]
How to get the token with django rest framework and ajax
38,674,266
<p>I want to build a rest api where users can authenticate with tokens. I have included <code>rest_framework.authtoken</code> in the installed apps list. Also added the required configuration in the settings.py:</p> <pre><code>INSTALLED_APPS = ( ... 'rest_framework.authtoken' ) REST_FRAMEWORK = { 'DEFAULT...
1
2016-07-30T13:04:09Z
38,681,334
<p>The problem here is because instead of send the data into the request payload, you are passing through URL, like a GET request.</p> <p>The request you generate using <code>httpie</code> works because it correctly generate the request, as you can see:</p> <p><strong>Request:</strong></p> <pre><code>http POST 0.0.0...
0
2016-07-31T06:20:54Z
[ "python", "ajax", "django", "rest", "django-rest-framework" ]
How to properly wrap std::vector<std::size_t> with SWIG for Python? Problems with std::size_t
38,674,268
<p>I'm trying to get <code>std::vector&lt;std::size_t&gt;</code> to work with SWIG. I need to provide a python interface to a c++ library. <code>std::vector</code>s of primitive types and objects are working fine but there is a problem with <code>std::size_t</code>.</p> <p>I provide a MCVE on github <a href="https://g...
6
2016-07-30T13:04:31Z
38,706,357
<p>Instantiate your templates as follows</p> <pre><code>namespace std { %template(VecSize) vector&lt;size_t&gt;; } </code></pre> <p>It works here with this change - out of the box. I am using SWIG 3.0.2, g++ 4.9.2 and Python 2.7.9. </p> <p>I have changed <code>d_swig_vec_std_size.i</code> in your project and the ...
2
2016-08-01T19:08:38Z
[ "python", "c++", "vector", "swig" ]
How to properly wrap std::vector<std::size_t> with SWIG for Python? Problems with std::size_t
38,674,268
<p>I'm trying to get <code>std::vector&lt;std::size_t&gt;</code> to work with SWIG. I need to provide a python interface to a c++ library. <code>std::vector</code>s of primitive types and objects are working fine but there is a problem with <code>std::size_t</code>.</p> <p>I provide a MCVE on github <a href="https://g...
6
2016-07-30T13:04:31Z
38,828,544
<p>Try defining size_t for swig as shown here - <a href="http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn20" rel="nofollow">http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn20</a></p> <pre><code>%inline %{ typedef long unsigned int size_t; %} namespace std { %template(VecSize) vector&lt;size_t&gt;; } </code></pre>
1
2016-08-08T11:53:23Z
[ "python", "c++", "vector", "swig" ]
How to compile kivy and python files to apk
38,674,286
<p>i want to convert my python and kivy files into signed and unsigned apk. i work on windows but for compiling using python for android in ubuntu in vm ware. After installing all necessary modules like kivy, python for android and android studio.</p> <p>when i am compiling it's showing error that sdk not found. is th...
0
2016-07-30T13:08:08Z
38,676,403
<p>I suggest using buildozer instead of p4a - the buildozer uses it internally. It can also automatically download specified android sdk for you.</p> <p>Install it using pip: <code>sudo pip install buildozer</code></p> <p>Once you have it installed, go to your project directory and type:</p> <pre><code>buildozer ini...
1
2016-07-30T17:01:17Z
[ "android", "python", "apk", "kivy" ]
Store plotted data for later use
38,674,287
<p>I do much (practically all) of my data analysis in Jupyter/iPython-notebooks. For convenience, I obviously also plot my data in those notebooks using <code>matplotlib</code>/<code>pyplot</code>. Some of those plots I need to recreate externally later on, for example to use them in <code>latex</code>. For this I save...
0
2016-07-30T13:08:17Z
38,674,397
<p>You could pickle the object (using the <code>cPickle</code> module). See this question <a href="http://stackoverflow.com/questions/7290370/store-and-reload-matplotlib-pyplot-object">here</a>.</p>
0
2016-07-30T13:22:08Z
[ "python", "matplotlib", "ipython", "jupyter-notebook" ]
Missing dll files when using pyinstaller
38,674,400
<p>Good day!</p> <p>I'm using python 3.5.2 with qt5, pyqt5 and sip14.8. I'm also using the latest pyinstaller bracnch (3.3.dev0+g501ad40).</p> <p>I'm trying to create an exe file for a basic hello world program.</p> <pre><code>from PyQt5 import QtWidgets import sys class newPingDialog(QtWidgets.QMainWindow): def _...
1
2016-07-30T13:22:15Z
38,682,416
<p>This may be more like a workaround and Pyinstaller might need fixing.</p> <p>I found out that <code>--paths</code> argument pointing to the directory containing <em>Qt5Core.dll</em>, <em>Qt5Gui.dll</em>, etc. helped</p> <pre><code>pyinstaller --paths C:\Python35\Lib\site-packages\PyQt5\Qt\bin hello.py </code></pre...
3
2016-07-31T09:04:04Z
[ "python", "qt", "dll", "pyinstaller" ]
Problems with python + json vs. curl
38,674,459
<p>so when I run the python code the server (google) give me a different response than when I run curl command. Can someone tell me where I'm wrong please?</p> <p>code:</p> <pre><code>import urllib2, simplejson def MapsWIFI(card): req = urllib2.Request("https://www.googleapis.com/geolocation/v1/geolocate?key=AI....
1
2016-07-30T13:28:25Z
38,674,495
<p>The data is <em>already</em> a JSON encoded string, you don't want to encode it twice.</p> <p>Pass it in <em>without</em> encoding it again:</p> <pre><code>jWifiReport = urllib2.urlopen(req, jWifi).read() </code></pre> <p>You only need to encode if you have a Python data structure (a dictionary in this case).</p>...
2
2016-07-30T13:33:16Z
[ "python", "json", "google-maps", "curl", "google-geolocation" ]
InterfaceError for a custom JSONField for Django
38,674,469
<p>I am trying to build a custom JSON Field for Django projects that support MySQL. This is my <strong>models</strong>:</p> <pre><code>from __future__ import unicode_literals from django.db import models from django.db import models from django.core.serializers.json import DjangoJSONEncoder import json name1 = 'name1...
1
2016-07-30T13:29:23Z
38,674,937
<p>this code will produce an undefined variable error before you call your user method.</p> <pre><code>data = { name1 : { "image_url" : 'https://photosite.com/image1.jpg', "views" : 0 }, name2 : { "image_url" : 'https://photosite.com/image2.jpg', ...
1
2016-07-30T14:19:56Z
[ "python", "json", "django", "django-models", "django-jsonfield" ]
I/O Warning Non ASCII found
38,674,480
<p>This is my first question...</p> <p>I just checked this <a href="http://stackoverflow.com/questions/16270174/how-to-deal-with-non-ascii-warning-when-performing-save-on-python-code-edited-wi">How to deal with Non-ASCII Warning when performing Save on Python code edited with IDLE?</a> but didn't find the solution.</p...
-1
2016-07-30T13:31:35Z
38,676,657
<p>In image its already mentioned what to do. </p> <p>You need to add first line in your code file as "<strong># -*- coding: utf-8 -*-</strong>"</p> <pre><code># -*- coding: utf-8 -*- </code></pre>
0
2016-07-30T17:31:15Z
[ "python", "syntax" ]
Replace leading zeros with spaces
38,674,494
<p>I have a text file of multiple records. Each record has a field which has some number of leading zeros that I need to replace with that number of spaces. A record will look like this:</p> <pre><code>A206 000001204 X4609 </code></pre> <p>I need the record to look like this:</p> <pre><code>A206 1204 X4...
-2
2016-07-30T13:33:06Z
38,674,521
<p>Yes, <code>\b0+</code> would probably work.</p> <p>Here using the <a href="https://msdn.microsoft.com/en-us/library/ht1sxswy(v=vs.110).aspx" rel="nofollow"><code>Regex.Replace()</code> method</a> in <code>C#</code>:</p> <pre><code>using System.Text.RegularExpressions; Regex.Replace(inputString, @"\b0+", m =&gt; "...
6
2016-07-30T13:35:13Z
[ "c#", "python", "regex", "powershell", "notepad++" ]
Replace leading zeros with spaces
38,674,494
<p>I have a text file of multiple records. Each record has a field which has some number of leading zeros that I need to replace with that number of spaces. A record will look like this:</p> <pre><code>A206 000001204 X4609 </code></pre> <p>I need the record to look like this:</p> <pre><code>A206 1204 X4...
-2
2016-07-30T13:33:06Z
38,674,539
<p>Does this suffice?</p> <pre><code>while (dataString.Contains(" 0")) // while data contains a zero after a space dataString = dataString.Replace(" 0", " "); // Replace with two spaces </code></pre> <p>Though this doesn't use regex. </p> <p>I hope this helps.</p>
3
2016-07-30T13:37:39Z
[ "c#", "python", "regex", "powershell", "notepad++" ]
Replace leading zeros with spaces
38,674,494
<p>I have a text file of multiple records. Each record has a field which has some number of leading zeros that I need to replace with that number of spaces. A record will look like this:</p> <pre><code>A206 000001204 X4609 </code></pre> <p>I need the record to look like this:</p> <pre><code>A206 1204 X4...
-2
2016-07-30T13:33:06Z
38,674,859
<p>Using Npp:</p> <ul> <li><kbd>Ctrl</kbd>+<kbd>H</kbd></li> <li>Find what: <code>\b0</code></li> <li>Replace with: <code></code> (a space)</li> <li><kbd>Replace All</kbd></li> </ul>
1
2016-07-30T14:11:56Z
[ "c#", "python", "regex", "powershell", "notepad++" ]
Replace leading zeros with spaces
38,674,494
<p>I have a text file of multiple records. Each record has a field which has some number of leading zeros that I need to replace with that number of spaces. A record will look like this:</p> <pre><code>A206 000001204 X4609 </code></pre> <p>I need the record to look like this:</p> <pre><code>A206 1204 X4...
-2
2016-07-30T13:33:06Z
38,676,466
<p>As an alternative to <a href="http://stackoverflow.com/a/38674521/1630171">Mathias'</a> lambda expression solution you could also use a more "conventional" approach like this:</p> <pre><code>$str = 'A206 000001204 X4609' $re = '\b0+' if ($str -match $re) { $str -replace $re, (' ' * $matches[0].Length) } </c...
0
2016-07-30T17:07:42Z
[ "c#", "python", "regex", "powershell", "notepad++" ]
Select values of one array based on a boolean expression applied to another array
38,674,562
<p>Starting with the following array</p> <pre><code>array([ nan, nan, nan, 1., nan, nan, 0., nan, nan]) </code></pre> <p>which is generated like so:</p> <pre><code>import numpy as np row = np.array([ np.nan, np.nan, np.nan, 1., np.nan, np.nan, 0., np.nan, np.nan]) </code></pre> <p>I'd like to ge...
1
2016-07-30T13:40:00Z
38,674,582
<p>You could do something like this -</p> <pre><code># Store non-NaN indices idx = np.where(~np.isnan(row))[0] # Select non-NaN elements, perform argsort and use those argsort # indices to re-order non-NaN indices as final output out = idx[row[idx].argsort()] </code></pre>
3
2016-07-30T13:41:54Z
[ "python", "arrays", "numpy" ]
Select values of one array based on a boolean expression applied to another array
38,674,562
<p>Starting with the following array</p> <pre><code>array([ nan, nan, nan, 1., nan, nan, 0., nan, nan]) </code></pre> <p>which is generated like so:</p> <pre><code>import numpy as np row = np.array([ np.nan, np.nan, np.nan, 1., np.nan, np.nan, 0., np.nan, np.nan]) </code></pre> <p>I'd like to ge...
1
2016-07-30T13:40:00Z
38,674,628
<p>Another option:</p> <pre><code>row.argsort()[~np.isnan(np.sort(row))] # array([6, 3]) </code></pre>
1
2016-07-30T13:47:02Z
[ "python", "arrays", "numpy" ]
Select values of one array based on a boolean expression applied to another array
38,674,562
<p>Starting with the following array</p> <pre><code>array([ nan, nan, nan, 1., nan, nan, 0., nan, nan]) </code></pre> <p>which is generated like so:</p> <pre><code>import numpy as np row = np.array([ np.nan, np.nan, np.nan, 1., np.nan, np.nan, 0., np.nan, np.nan]) </code></pre> <p>I'd like to ge...
1
2016-07-30T13:40:00Z
38,703,141
<p>There is another faster solution (for OP data). </p> <p>Psidom's Solution</p> <pre><code>%timeit row.argsort()[~np.isnan(np.sort(row))] The slowest run took 31.23 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 8.16 µs per loop </code></pre> <...
0
2016-08-01T15:53:14Z
[ "python", "arrays", "numpy" ]
Can not start elasticsearch as a service in ubuntu 16.04
38,674,711
<p>I have recently upgraded my machine from Ubuntu <code>14.04</code> to <code>16.04</code>. I am facing problem of using the <code>elasticsearch</code> as a service. I <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-repositories.html" rel="nofollow">installed</a> <code>elasticsearch</cod...
3
2016-07-30T13:55:14Z
38,676,036
<p>I found the solution for this issue. The solution comes form this discussion thread- <a href="https://discuss.elastic.co/t/cant-start-elasticsearch-with-ubuntu-16-04/48730/9">Can’t start elasticsearch with Ubuntu 16.04</a> on elastic's website.</p> <blockquote> <p>It seems that to get Elasticsearch to run on <c...
5
2016-07-30T16:23:02Z
[ "java", "python", "elasticsearch", "ubuntu-16.04" ]
Pillow Attribute Error
38,674,729
<p>I want to set up an imagestream from my rbpi to my server.</p> <p>So I would like to setup a network stream discripted in the <a href="http://picamera.readthedocs.io/en/release-1.12/recipes1.html#streaming-capture" rel="nofollow">http://picamera.readthedocs.io/en/release-1.12/recipes1.html#streaming-capture</a>.</p...
3
2016-07-30T13:57:17Z
38,705,927
<p>I don't have a raspberry-pi, but decided to see if I could reproduce the problem anyway. Also, for input I just created an image file on disk to eliminate all the socket stuff. Sure enough I got exactly the same error as you encountered. (<strong>Note:</strong> IMO you should have done this simplification yourself a...
1
2016-08-01T18:42:42Z
[ "python", "raspberry-pi", "pillow" ]
Matplotlib - plot line merging with plot frame
38,674,784
<p>How to avoid plot line merging with plot frame in matplotlib? I attached a screenshot. As you can see the purple line at the bottom is merely visible.</p> <p><a href="http://i.stack.imgur.com/zf67i.png" rel="nofollow">Graph</a></p> <p>I am plotting like this:</p> <pre><code>plt.subplot2grid((4,4), (1, 0), colspan...
0
2016-07-30T14:03:47Z
38,675,289
<p>The easiest thing to do would be to alter the axes. If you move the y-axis down to about -5 or even -1 it will show the whole line. Use the ylim function:</p> <pre><code>ymin, ymax = ylim() # get the current limits ylim( (ymin - 5, ymax) ) # set the ylim to ymin, ymax </code></pre> <p>This will move the y-a...
0
2016-07-30T14:58:24Z
[ "python", "matplotlib" ]
How and when to intialise configuration in Python?
38,674,793
<p>I'm getting pretty confused as to how and where to initialise application configuration in Python 3.</p> <p>I have configuration that consists of application specific config (db connection strings, url endpoints etc.) and logging configuration.</p> <p>Before my application performs its intended function I want to ...
0
2016-07-30T14:05:06Z
38,713,360
<p>I ended up with a cut down version of the Django approach: <a href="https://github.com/django/django/blob/master/django/conf/__init__.py" rel="nofollow">https://github.com/django/django/blob/master/django/conf/<strong>init</strong>.py</a></p> <p>It seems pretty elegant and has the nice benefit of working regardless...
0
2016-08-02T06:40:21Z
[ "python" ]
Python Pandas flattening a calendar with overlapping meetings to get actual time in meetings
38,674,805
<p>I have the details of my weekly calendar (obviously Changed the Subjects to protect the innocent) read into into a pandas dataframe. One of my goals is to get the total time in meetings. I would like to have a dataframe indexed by date_range with hourly frequencies for the week showing how many total minutes I was...
0
2016-07-30T14:06:21Z
38,675,588
<p>One possibility is creating a time series (<code>s</code> below) indexed by minute that keeps tracks of whether you are in a meeting during that minute or not, and then resample that by hour. To match your desired output, you may adjust the start and end time of the index of <code>s</code>.</p> <pre><code>import io...
1
2016-07-30T15:29:50Z
[ "python", "datetime", "pandas", "dataframe" ]
split elements in array using python
38,674,808
<p>I have a big array and a part of that is shown below. in each list, the first number is start and the 2nd number is end (so there is a range). what I want to do is:</p> <p>1: filter out those lists (ranges) which are smaller than 300 (e.g. the 18th list in the following array must be removed) </p> <p>2: get a sm...
2
2016-07-30T14:06:40Z
38,674,887
<pre><code>data = [[ 469, 1300], # ... [ 63, 330], [ 479, 2411]] print( filter(lambda v: v[1] - v[0] &gt;= 300, data) ) print( [[v[0] + 100, v[0] + 200] for v in data] ) </code></pre> <p>Explanation:</p> <p>The first command uses the builtin <a href="https://docs.python.org/3.5/lib...
0
2016-07-30T14:15:10Z
[ "python", "arrays", "numpy" ]
split elements in array using python
38,674,808
<p>I have a big array and a part of that is shown below. in each list, the first number is start and the 2nd number is end (so there is a range). what I want to do is:</p> <p>1: filter out those lists (ranges) which are smaller than 300 (e.g. the 18th list in the following array must be removed) </p> <p>2: get a sm...
2
2016-07-30T14:06:40Z
38,675,005
<p>A general note before: You should use <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">tuples</a> to represnt such ranges, not lists, They are immutable data types with a meaning to the order of items in them.</p> <p>As for 1, it is pretty easy to filter in python...
0
2016-07-30T14:28:32Z
[ "python", "arrays", "numpy" ]
split elements in array using python
38,674,808
<p>I have a big array and a part of that is shown below. in each list, the first number is start and the 2nd number is end (so there is a range). what I want to do is:</p> <p>1: filter out those lists (ranges) which are smaller than 300 (e.g. the 18th list in the following array must be removed) </p> <p>2: get a sm...
2
2016-07-30T14:06:40Z
38,675,113
<p>Assuming your array is called <code>A</code>, then:</p> <pre><code>import numpy as np # Filter out differences not wanted gt300 = A[(np.diff(A) &gt;= 300).flatten()] # Set new value of first column gt300[:,0] += 100 # Set value of second column gt300[:,1] = gt300[:,0] + 100 </code></pre> <p>Or maybe something l...
2
2016-07-30T14:40:46Z
[ "python", "arrays", "numpy" ]
split elements in array using python
38,674,808
<p>I have a big array and a part of that is shown below. in each list, the first number is start and the 2nd number is end (so there is a range). what I want to do is:</p> <p>1: filter out those lists (ranges) which are smaller than 300 (e.g. the 18th list in the following array must be removed) </p> <p>2: get a sm...
2
2016-07-30T14:06:40Z
38,676,451
<p>We can find which rows have the small difference with:</p> <pre><code>In [745]: mask=(x[:,1]-x[:,0])&lt;300 In [746]: mask Out[746]: array([False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, True, False], dtype=bool) </code></pre> <p>We c...
0
2016-07-30T17:05:57Z
[ "python", "arrays", "numpy" ]
Append a series of strings to a Pandas column
38,674,830
<p>I'm a Pandas newbie and have written some code that should append a dictionary to the last column in a row. The last column is named "Holder"</p> <p>Part of my code, which offends the pandas engine is shown below</p> <pre><code>df.loc[df[innercat] == -1, 'Holder'] += str(odata) </code></pre> <p>I get the error me...
0
2016-07-30T14:08:36Z
38,675,477
<p>is that what you want?</p> <pre><code>In [190]: d1 = {"student name": "Peter", "data": {"notes": "Gr8 student", "Course name": "Math1"}} In [191]: d2 = {"student name": "Peter", "data": {"notes": "Foo", "Course name": "Spanish1"}} In [192]: import json In [193]: json.dumps(d1) Out[193]: '{"student name": "Peter"...
1
2016-07-30T15:17:20Z
[ "python", "pandas" ]
How to "promote" an instance to a subclass?
38,674,880
<p>Suppose I have the following classes:</p> <pre><code>class Plain(object): def speak(self): print 'ho-hum' class Fancy(Plain): def exult(self): print 'huzzah!' plain = Plain() plain.speak() # ho-hum plain.exult() # --------------------------------------------------------------------------- ...
0
2016-07-30T14:14:00Z
38,674,928
<p>You could use of course</p> <pre><code>fancy = Fancy(plain) </code></pre> <p>and define in the constructor of Fancy, what should happen if an instance of Plain is given as argument.</p> <p><strong>Example</strong>:</p> <pre><code>class Plain: def __init__(self, foo, bar): self.foo = foo self.bar...
3
2016-07-30T14:19:10Z
[ "python", "class" ]
Ignoring empty arguments for certain flags
38,674,919
<p>I have a command that takes 1 argument and can take several flags.</p> <pre><code>@click.command() @click.argument('item') @click.option('--list-items', help='list items', is_flag=True) def cli(item, list_items): if list_items: click.echo(ITEMS) return </code></pre> <p>currently it returns:</p>...
-1
2016-07-30T14:18:23Z
38,675,052
<p>You'd have to make <code>item</code> optional:</p> <pre><code>@click.argument('item', required=False) </code></pre> <p>then do error handling in the function (e.g. raise a <a href="http://click.pocoo.org/5/api/#click.BadParameter" rel="nofollow"><code>BadParameter()</code> exeception</a>).</p>
1
2016-07-30T14:32:58Z
[ "python", "click", "command-line-interface" ]
Ignoring empty arguments for certain flags
38,674,919
<p>I have a command that takes 1 argument and can take several flags.</p> <pre><code>@click.command() @click.argument('item') @click.option('--list-items', help='list items', is_flag=True) def cli(item, list_items): if list_items: click.echo(ITEMS) return </code></pre> <p>currently it returns:</p>...
-1
2016-07-30T14:18:23Z
38,675,084
<p>You made it mandatory argument, make it optional by either adding required= False or by adding a default value to it</p>
0
2016-07-30T14:36:08Z
[ "python", "click", "command-line-interface" ]
Define a function using string variable
38,674,954
<p>I am trying to create a function "a21" that takes a parameter x and adds 4 to it.</p> <pre><code>eq = 'x+4' b=21 new='a'+str(b)+'(x)' def eval(new): return eval(eq) c=5 print(a21(c)) </code></pre> <p>The desired output is 9 but it's not recognizing a21 as a function. How do I write this to create a the functi...
-3
2016-07-30T14:22:38Z
38,674,997
<p>Write a fully-featured function definition:</p> <pre><code>new = ''' def a21(x): return x + 4 ''' </code></pre> <p>And then <code>exec</code>ute it: <code>exec(new)</code> and run: <code>a21(678)</code>.</p> <p>If you want to construct a function during runtime, use string formatting.</p> <pre><code>new = ''...
2
2016-07-30T14:27:42Z
[ "python" ]
Define a function using string variable
38,674,954
<p>I am trying to create a function "a21" that takes a parameter x and adds 4 to it.</p> <pre><code>eq = 'x+4' b=21 new='a'+str(b)+'(x)' def eval(new): return eval(eq) c=5 print(a21(c)) </code></pre> <p>The desired output is 9 but it's not recognizing a21 as a function. How do I write this to create a the functi...
-3
2016-07-30T14:22:38Z
38,675,437
<p>The following is possible and does almost the same thing: You can bind the function in a function like below.</p> <pre><code>eq = 'x+4' def bindfunc(name): def dynamicfunc(x): return eval(eq) dynamicfunc.__name__ = name return dynamicfunc </code></pre> <p>The way you would use this would be a little diff...
0
2016-07-30T15:12:38Z
[ "python" ]
Python error while attempting to call cocos from the command line
38,675,224
<p>To be clear, this is not an issue about creating a new project. I have a sneaking suspicion that it may have something to do with my initial setup using setup.py.</p> <p><strong>The Problem:</strong></p> <p>Calling "cocos" from the command line generates the following error:</p> <pre><code>*C:\Users\pixelhacker&g...
0
2016-07-30T14:52:06Z
38,687,364
<p>Originally I was running an older version of Python, version 2.5. I upgraded to the latest version but the issue persisted. After some research, I decided to use version 2.7.</p> <p>Problem resolved.</p>
0
2016-07-31T18:52:58Z
[ "python", "cocos2d-x-3.x" ]
Flask HTML forms- UnboundLocalError
38,675,377
<p>I am new to the Flask application development. I want to make a Flask application that receives the details from a user. After the successful registration, then a new page will be displayed showing the entered details. The application is built using HTML forms and not by using WTF.</p> <p><strong>Following is the c...
0
2016-07-30T15:08:01Z
38,676,803
<p><code>result</code> only exists if the <code>request</code> method is <code>POST</code>, so if the request method was <code>GET</code>(which is the default request one), that is when the page is requested before submitting user data form, then <code>result</code> won't be existing, hence the error message. Plus, you...
1
2016-07-30T17:46:55Z
[ "python", "flask" ]
Flask HTML forms- UnboundLocalError
38,675,377
<p>I am new to the Flask application development. I want to make a Flask application that receives the details from a user. After the successful registration, then a new page will be displayed showing the entered details. The application is built using HTML forms and not by using WTF.</p> <p><strong>Following is the c...
0
2016-07-30T15:08:01Z
38,676,930
<p>Try this:<br> app.py</p> <pre><code>from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def form(): return render_template('register.html') @app.route('/success',methods = ['POST', 'GET']) def user(): if request.method == 'POST': results = request.form ret...
0
2016-07-30T18:00:08Z
[ "python", "flask" ]
Python/OpenCV - how to load all images from folder in alphabetical order
38,675,389
<p>how to load all images from given folder in alphabetical order?</p> <p>Code like this:</p> <pre><code>images = [] for img in glob.glob("images/*.jpg"): n= cv2.imread(img) images.append(n) print (img) </code></pre> <p>...return:</p> <pre><code>... images/IMG_9409.jpg images/IMG_9425.jpg images/IMG_941...
1
2016-07-30T15:08:55Z
38,675,461
<p>Luckily, python lists have a built-in sort function that can sort strings using ASCII values. It is as simple as putting this before your loop:</p> <pre><code>filenames = [img for img in glob.glob("images/*.jpg")] filenames.sort() # ADD THIS LINE images = [] for img in filenames: n= cv2.imread(img) images...
0
2016-07-30T15:14:44Z
[ "python", "opencv" ]
fft (fast Fourier transform) to speed up opencv in python?
38,675,473
<p>i have a raspberry pi with opencv and python installed. I want is to do a simple frontal face haarcascade using opencv. It works however i only have about 2 fps. So i searched through the internet and found this: <code>https://www.raspberrypi.org/blog/accelerating-fourier-transforms-using-the-gpu/</code></p> <p>I t...
0
2016-07-30T15:16:57Z
38,927,016
<p>You can highly improve the performance of the classification when you specify the parameters correctly. Just set the min,max frame size to reasonable values and maybe set a scale factor.</p> <p>For the fft there are already some python packages available for that. I would not recommend to write your own fft functio...
0
2016-08-12T21:57:17Z
[ "python", "opencv", "fft" ]
robot framework with pabot : is it possible to pass two different values to a variable in two tests
38,675,475
<p>Example, I have <code>file1.robot</code> and <code>file2.robot</code>and each has <code>${var}</code> as the variable. Can I pass 2 different values to this same <code>${var}</code> in the command line? Something like <code>pabot -v var:one:two file1.robot file2.robot</code> where <code>-v var:one:two</code> would f...
2
2016-07-30T15:17:14Z
38,740,020
<p>This solution is not 100% what you've asked for, but maybe you can make it work.</p> <p>In <a href="https://github.com/mkorpela/pabot/blob/master/README.md" rel="nofollow">pabot readme file</a> is mentioned something about shared set of variables and <a href="https://github.com/mkorpela/pabot/blob/master/README.md#...
1
2016-08-03T09:45:03Z
[ "python", "robotframework" ]
robot framework with pabot : is it possible to pass two different values to a variable in two tests
38,675,475
<p>Example, I have <code>file1.robot</code> and <code>file2.robot</code>and each has <code>${var}</code> as the variable. Can I pass 2 different values to this same <code>${var}</code> in the command line? Something like <code>pabot -v var:one:two file1.robot file2.robot</code> where <code>-v var:one:two</code> would f...
2
2016-07-30T15:17:14Z
39,305,280
<p>Another way is to use multiple argument files. One containing the first value for ${var} and the other containing the other.</p> <p>This will execute the same test suite for both argument files.</p> <pre><code>pabot --agumentfile1 varone.args --argumentfile2 vartwo.args file.robot =&gt; file.robot executed with va...
0
2016-09-03T09:17:47Z
[ "python", "robotframework" ]
Is a break statement required or is the return statement enough?
38,675,529
<p>In my Python 3(.5) script I have a simple <code>for</code> loop, that looks like this:</p> <pre><code>request = "simple string" ignore = ( # Tuple that contains regex's to ignore ) for (i, regex) in enumerate(ignore): if re.search(regex, request): print("Found regex {0}.".format(i)) return False </code>...
2
2016-07-30T15:23:13Z
38,675,546
<p><code>return</code> exits a function immediately.</p> <p>If you are in a loop, that breaks out of the loop and no <code>break</code> is required first.</p> <p>So no, you are not required to use <code>break</code> if <code>return</code> suits your needs.</p>
5
2016-07-30T15:24:55Z
[ "python", "python-3.x", "for-loop", "return", "break" ]
How do i extract values with beautifulsoup?
38,675,693
<p>Hi am using beautiful soup to extract the euro to us value, this is what i got so far: </p> <pre><code>import requests from bs4 import BeautifulSoup def Euro_spider(): url = 'http://fx-rate.net/USD/' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "htm...
-1
2016-07-30T15:43:10Z
38,675,724
<p>Now you need to locate the correct element containing the rate:</p> <pre><code>&lt;a href="/USD/EUR/" class="1rate" title="Dollar to Euro"&gt;0.895&lt;/a&gt; </code></pre> <p>You can locate it, for example, by <code>title</code>:</p> <pre><code>usd_to_euro = soup.find(title="Dollar to Euro").get_text() print(usd_...
0
2016-07-30T15:46:22Z
[ "python", "web-scraping", "beautifulsoup", "web-crawler" ]
** operator TypeError
38,675,717
<p>I keep getting this error message:</p> <pre class="lang-none prettyprint-override"><code>File "/Users/SalamonCreamcheese/Documents/4.py", line 31, in &lt;module&gt; testFindRoot() File "/Users/SalamonCreamcheese/Documents/4.py", line 29, in testFindRoot print " ", result**power, " ~= ", x TypeError: unsuppo...
1
2016-07-30T15:45:10Z
38,675,824
<p>You can't apply a powers operation to a tuple. If you need to have all of the values to that power, try operating them separately.</p> <p>You might need: [power**n for n in result]</p>
1
2016-07-30T15:58:44Z
[ "python", "typeerror" ]
** operator TypeError
38,675,717
<p>I keep getting this error message:</p> <pre class="lang-none prettyprint-override"><code>File "/Users/SalamonCreamcheese/Documents/4.py", line 31, in &lt;module&gt; testFindRoot() File "/Users/SalamonCreamcheese/Documents/4.py", line 29, in testFindRoot print " ", result**power, " ~= ", x TypeError: unsuppo...
1
2016-07-30T15:45:10Z
38,675,882
<p><code>result**power</code> is trying to find <code>x to the y</code> where <code>x = result</code> and <code>y = power</code>.</p> <p>Your problem is that <code>result</code> is a <strong>tuple.</strong> You can't raise a tuple to a power. It makes no sense...</p> <p>You need to access the value inside the tuple t...
2
2016-07-30T16:04:13Z
[ "python", "typeerror" ]
** operator TypeError
38,675,717
<p>I keep getting this error message:</p> <pre class="lang-none prettyprint-override"><code>File "/Users/SalamonCreamcheese/Documents/4.py", line 31, in &lt;module&gt; testFindRoot() File "/Users/SalamonCreamcheese/Documents/4.py", line 29, in testFindRoot print " ", result**power, " ~= ", x TypeError: unsuppo...
1
2016-07-30T15:45:10Z
38,680,370
<p>I think you have a mistake on this line:</p> <pre><code>result = (x, power, epsilon) </code></pre> <p>I suspect you want to be calling the <code>findroot</code> function with those three values as arguments rather than creating a tuple out of them. Try changing it to:</p> <pre><code>result = findroot(x, power, ep...
2
2016-07-31T03:03:39Z
[ "python", "typeerror" ]
** operator TypeError
38,675,717
<p>I keep getting this error message:</p> <pre class="lang-none prettyprint-override"><code>File "/Users/SalamonCreamcheese/Documents/4.py", line 31, in &lt;module&gt; testFindRoot() File "/Users/SalamonCreamcheese/Documents/4.py", line 29, in testFindRoot print " ", result**power, " ~= ", x TypeError: unsuppo...
1
2016-07-30T15:45:10Z
38,680,393
<p>It looks like you meant to call <code>findRoot</code> with the three arguments <code>x</code>, <code>power</code>, and <code>epsilon</code>. Try editing the line </p> <pre><code>result = (x, power, epsilon) </code></pre> <p>to be </p> <pre><code>result = findRoot(x, power, epsilon) </code></pre> <p>As that line ...
2
2016-07-31T03:09:12Z
[ "python", "typeerror" ]
Random Number following a certain distribution
38,675,845
<p>I'm stuck with a problem. I have to implement an algorithm in python which needs a random number X such as Pr[X ≥ k] = 1/k. I don't know if already exists a distribution which can give me this exact value or if there is a way to implement this random generator using the simple random python library. Is there a way...
2
2016-07-30T16:01:15Z
38,676,004
<p>The easiest attempt is to make</p> <pre><code>X = 1.0 / random.random() </code></pre> <p>However, <code>random.random()</code> can have a value of zero, so this may result in a divide-by-zero error. The value can never be 1.0, according to the documentation, so use</p> <pre><code>X = 1.0 / (1.0 - random.random())...
6
2016-07-30T16:18:50Z
[ "python", "random", "probability" ]
Random Number following a certain distribution
38,675,845
<p>I'm stuck with a problem. I have to implement an algorithm in python which needs a random number X such as Pr[X ≥ k] = 1/k. I don't know if already exists a distribution which can give me this exact value or if there is a way to implement this random generator using the simple random python library. Is there a way...
2
2016-07-30T16:01:15Z
38,676,015
<p>What you need is a uniform random number generator for generating random numbers. These numbers can then be transformed into a distribution (e.g. multiplication)</p> <p><a href="https://docs.python.org/2/library/random.html" rel="nofollow">https://docs.python.org/2/library/random.html</a><br> <a href="https://docs....
-2
2016-07-30T16:19:45Z
[ "python", "random", "probability" ]
Random Number following a certain distribution
38,675,845
<p>I'm stuck with a problem. I have to implement an algorithm in python which needs a random number X such as Pr[X ≥ k] = 1/k. I don't know if already exists a distribution which can give me this exact value or if there is a way to implement this random generator using the simple random python library. Is there a way...
2
2016-07-30T16:01:15Z
38,676,339
<p>Rory ended up at the correct answer, but his math justifying it is not constructive&mdash;it doesn't show how to get to the answer, it only shows that his assertion is correct. The following uses basic rules of probability to derive the answer.</p> <pre><code>Pr{X ≥ k} = 1 - Pr{X &lt; k} </code></pre> <p>If <co...
1
2016-07-30T16:53:14Z
[ "python", "random", "probability" ]
Print has "No Output" in STDOUT
38,675,965
<p>I have been writing code in HackerRank to count how many valleys that a hiker (Gary) walked through in a hike. Right now, it looks something like this.</p> <pre><code>#Defining variables for later use and a list of Gary's steps steps = ["U", "D", "D", "D", "D", "D", "U", "U"] sea_level = 0 valleys = 0 #For loop to...
1
2016-07-30T16:14:43Z
38,676,213
<p>Lets try out some debugging here:<br> I know its a bad idea when you are working on big solutions, anyway when you <br>will run this code you will see that you are never getting the condition <code>elif step_ud="D"</code> because it will check <code>elif sea_level==0</code> and continue the for loop. </p> <pre><cod...
2
2016-07-30T16:41:05Z
[ "python", "printing", "output" ]
Loop needs to reference list returned by terminal in notebook
38,676,041
<p>I have a folder structure with 3 folder X,Y and Z. Each of these folders contains 3 files X1.csv, X2.csv, X3.csv, Y1.csv, Y2.csv, Y3.csv, Z1.csv, Z2.csv, Z3.csv.</p> <p>In my jupyter notebook I can do the following:</p> <pre><code>folders = ['X','Y','Z'] for f in folders: a = !ls data/X print(a) </code>...
2
2016-07-30T16:23:31Z
38,676,408
<p>Simply do not use magical notebook commands to do something that <a href="http://www.tutorialspoint.com/python/os_listdir.htm" rel="nofollow">can be easily done with pure python</a>. Magic notebook commands are supposed to be used for quick hacks and supporting non-python functionality, not to be actually placed as ...
3
2016-07-30T17:01:55Z
[ "python", "ipython" ]
List and maximum numbers
38,676,297
<p>Here's the question: Using a <strong>for loop</strong>, write a <strong>function</strong> called <strong><em>getMax4</em></strong> that takes in a list of numbers. It determines and <strong>returns</strong> the <strong>maximum</strong> number that is <strong>divisible by 4.</strong> The function returns -999...
-5
2016-07-30T16:49:05Z
38,680,662
<p>Your first problem is at <code>highest = List[0]</code>. Since <code>List</code> is not guaranteed to have at least one item, you will have an error if <code>List</code> is empty. You should add a check:</p> <pre><code>def getMax4(List): if not List: # or if len(List) == 0: return -999 ... </code>...
0
2016-07-31T04:05:49Z
[ "python", "python-3.x" ]
List and maximum numbers
38,676,297
<p>Here's the question: Using a <strong>for loop</strong>, write a <strong>function</strong> called <strong><em>getMax4</em></strong> that takes in a list of numbers. It determines and <strong>returns</strong> the <strong>maximum</strong> number that is <strong>divisible by 4.</strong> The function returns -999...
-5
2016-07-30T16:49:05Z
38,681,901
<p>In regards to your 2nd piece of code you need to be mindful of where you place your returns. A return statement will exit the function with the value. Therefore these checks should be done before and after the loop as your function requires it to go through the entire list.</p> <p>I'm not too fond of setting your i...
0
2016-07-31T07:49:36Z
[ "python", "python-3.x" ]
Is it possible to get monthly historical stock prices in python?
38,676,323
<p>I know using pandas this is how you normally get daily stock price quotes. But I'm wondering if its possible to get monthly or weekly quotes, is there maybe a parameter I can pass through to get monthly quotes?</p> <pre><code> from pandas.io.data import DataReader from datetime import datetime ibm = Dat...
-1
2016-07-30T16:51:49Z
38,676,389
<p>try this:</p> <pre><code>In [175]: from pandas_datareader.data import DataReader In [176]: ibm = DataReader('IBM', 'yahoo', '2001-01-01', '2012-01-01') </code></pre> <p><strong>UPDATE:</strong> show average for <code>Adj Close</code> only (month start)</p> <pre><code>In [12]: ibm.groupby(pd.TimeGrouper(freq='MS...
0
2016-07-30T16:58:49Z
[ "python", "pandas", "quantitative-finance" ]
Is it possible to get monthly historical stock prices in python?
38,676,323
<p>I know using pandas this is how you normally get daily stock price quotes. But I'm wondering if its possible to get monthly or weekly quotes, is there maybe a parameter I can pass through to get monthly quotes?</p> <pre><code> from pandas.io.data import DataReader from datetime import datetime ibm = Dat...
-1
2016-07-30T16:51:49Z
38,773,260
<p>Get it from Quandl:</p> <pre><code>import pandas as pd import quandl quandl.ApiConfig.api_key = 'xxxxxxxxxxxx' # Optional quandl.ApiConfig.api_version = '2015-04-09' # Optional ibm = quandl.get("WIKI/IBM", start_date="2000-01-01", end_date="2012-01-01", collapse="monthly", returns="pandas") </code></pre>
0
2016-08-04T16:55:11Z
[ "python", "pandas", "quantitative-finance" ]
Is it possible to get monthly historical stock prices in python?
38,676,323
<p>I know using pandas this is how you normally get daily stock price quotes. But I'm wondering if its possible to get monthly or weekly quotes, is there maybe a parameter I can pass through to get monthly quotes?</p> <pre><code> from pandas.io.data import DataReader from datetime import datetime ibm = Dat...
-1
2016-07-30T16:51:49Z
38,833,988
<p>Monthly closing prices from Yahoo! Finance... </p> <pre><code>import pandas_datareader.data as web data = web.get_data_yahoo('IBM','01/01/2015',interval='m') </code></pre> <p>where you can replace the interval input as required ('d', 'w', 'm', etc).</p>
1
2016-08-08T16:12:34Z
[ "python", "pandas", "quantitative-finance" ]
Beautiful Soup is not selecting any element
38,676,348
<p>This is the code I am using to iterate over all elements:</p> <pre><code>soup_top = bs4.BeautifulSoup(r_top.text, 'html.parser') selector = '#ContentPlaceHolder1_gvDisplay table tr td:nth-of-type(3) a' for link in soup_top.select(selector): print(link) </code></pre> <p>The same selector gives a length of 57 ...
0
2016-07-30T16:54:06Z
38,683,486
<p>It seems that this is due to the <a href="http://beautiful-soup-4.readthedocs.io/en/latest/#installing-a-parser" rel="nofollow">parser</a> you used (i.e. <code>html.parser</code>). If I try the same thing with <code>lxml</code> as parser:</p> <pre><code>from bs4 import BeautifulSoup import requests url = 'http://w...
0
2016-07-31T11:27:42Z
[ "python", "python-3.x", "web-scraping", "python-3.5", "bs4" ]
highcharts not showing on heroku using python flask app
38,676,388
<p>i have created an html which visualizes some data using highcharts. When using this html on <strong>localhost</strong> i can successfully see my charts. But when i use it on heroku i do not get my charts. Any ideas?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">...
0
2016-07-30T16:58:48Z
38,697,898
<p>A few things that I noticed and corrected:</p> <ul> <li>Your code snippet did not have a starting <code>&lt;head&gt;</code> tag.</li> <li>You had an unclosed instance of <code>&lt;script type="text/javascript"&gt;</code> right before your <code>&lt;/head&gt;</code> tag. This was causing an <code>Uncaught SyntaxErro...
1
2016-08-01T11:38:49Z
[ "javascript", "python", "heroku", "highcharts", "flask" ]
Pandas DatetimeIndex indexing dtype: datetime64 vs Timestamp
38,676,418
<p>Indexing a pandas DatetimeIndex (with dtype numpy datetime64[ns]) returns either:</p> <ul> <li>another DatetimeIndex for multiple indices</li> <li>a pandas Timestamp for single index</li> </ul> <p>The confusing part is that Timestamps do not equal np.datetime64, so that:</p> <pre><code>import numpy as np import p...
1
2016-07-30T17:02:56Z
38,679,935
<p>You are using numpy functions to manipulate pandas types. They are not always compatible. </p> <p>The function <code>np.in1d</code> first converts its both arguments to ndarrays. A <code>DatetimeIndex</code> has a built-in conversion and an array of dtype <code>np.datetime64</code> is returned (it's <code>DatetimIn...
1
2016-07-31T01:19:50Z
[ "python", "pandas", "datetimeindex" ]
A transition from CountVectorizer to TfidfTransformer in sklearn
38,676,436
<p>I am processing a huge amount of text data in sklearn. First I need to vectorize the text context (word counts) and then perform a TfidfTransformer. I have the following code that doesn't seem to take the output from CountVectorizer to the input of TfidfTransformer. </p> <pre><code>TEXT = [data[i].values()[3] for i...
2
2016-07-30T17:04:36Z
38,676,483
<p>You're probably looking for a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html" rel="nofollow"><em>pipeline</em></a>, perhaps something like this:</p> <pre><code>pipeline = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ]) </code></pre> <p>or ...
1
2016-07-30T17:10:09Z
[ "python", "scikit-learn", "vectorization", "tf-idf" ]
A transition from CountVectorizer to TfidfTransformer in sklearn
38,676,436
<p>I am processing a huge amount of text data in sklearn. First I need to vectorize the text context (word counts) and then perform a TfidfTransformer. I have the following code that doesn't seem to take the output from CountVectorizer to the input of TfidfTransformer. </p> <pre><code>TEXT = [data[i].values()[3] for i...
2
2016-07-30T17:04:36Z
38,676,485
<p>This line </p> <pre><code>X = vectorizer(TEXT) </code></pre> <p>does not produce the output of the vectorizer (and this is the one raising the exception, it has nothing to do with TfIdf itself), you are supposed to call <code>fit_transform</code>. Furthermore, your next call is also wrong. You have to pass data as...
1
2016-07-30T17:10:37Z
[ "python", "scikit-learn", "vectorization", "tf-idf" ]
Python how to make class object shared across functions
38,676,443
<p>Lets say I created a class object someClassObject in function A, and threw that object into a function B:</p> <pre><code>functionB(someClassObject) </code></pre> <p>How do I retain all the modifications I've made in function B to someClassObject so I can continue using someClassObject in function A if my function ...
0
2016-07-30T17:05:15Z
38,676,488
<p>I'm pretty sure that happens by default when you create a class:</p> <pre><code>Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class A: ... def __init__(self, x): ... self.x = x ... &gt;&gt;&gt; def modA(objA): ... objA.x = 9 ... &gt;&gt;&gt; def createA(): ... a = A(...
0
2016-07-30T17:10:43Z
[ "python", "oop" ]
Python how to make class object shared across functions
38,676,443
<p>Lets say I created a class object someClassObject in function A, and threw that object into a function B:</p> <pre><code>functionB(someClassObject) </code></pre> <p>How do I retain all the modifications I've made in function B to someClassObject so I can continue using someClassObject in function A if my function ...
0
2016-07-30T17:05:15Z
38,676,517
<p>if you pass a class object (generally any object) around, it stays one single object so all changes to it are visible for all references to it.</p> <p>for example in</p> <pre><code>def B(cls): cls.value=2 def A(): class C(object): value=1 B(C) return C.value </code></pre> <p>A() returns 2...
0
2016-07-30T17:13:37Z
[ "python", "oop" ]