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
Media Url not resolving properly
37,509,140
<p>I have the media url and media root as follows.</p> <pre><code>MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_URL) </code></pre> <p>my urls.py is</p> <pre><code>if settings.DEBUG: # static files (images, css, javascript, etc.) urlpatterns += static(settings.MEDIA_URL, document_root=setti...
0
2016-05-29T11:09:39Z
37,510,224
<p>I suggest you use staticfile for this purpose, because you are using a specific image and not something that will be uploaded in the future.</p> <p>If you decide to use static files, put the image in your static folder and then use this:</p> <pre><code> &lt;img src="{% static 'image0.png' %}" style=""&gt; </code><...
0
2016-05-29T13:00:43Z
[ "python", "django", "url", "media-url" ]
Can you get a pulse value from txt file into a Shell script?
37,509,168
<p>thanks for helping out!</p> <p>I want a shell script to read the last value from a txt file. I've got this (another script) working from a python script, but this does not work in a shell script. I found some helping script parts here and there (on stackoverflow) Bu I cant get this to work.</p> <p>How can I read t...
1
2016-05-29T11:11:44Z
37,509,230
<p><code>tail -1 &lt;filename&gt;</code> will output the last line in the file. If by <code>last value</code> you mean the <code>last line</code> then this will work.</p>
0
2016-05-29T11:18:01Z
[ "python", "bash", "shell", "pulse" ]
final value in column of exponentially weighted average values
37,509,187
<p>I have a dataframe stockData which looks like this:</p> <pre><code>Name: BBG.XLON.VOD.S_MKTCAP_EUR, 04/02/2008 125761.8868 05/02/2008 124513.4973 06/02/2008 124299.8368 07/02/2008 122973.7429 08/02/2008 123451.0086 11/02/2008 122948.5002 12/02/2008 124336.3475 13/02/2008 124546.6607 14/02/2008 124434.876...
-1
2016-05-29T11:14:03Z
37,516,277
<p>Just simplifying <code>column</code> names:</p> <pre><code>df.columns = ['date', 'ticker'] </code></pre> <p>Use <code>adjust=False</code> (see <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.ewma.html" rel="nofollow">docs</a> for calculation of weights)</p> <pre><code>df['emwa'] = pd...
0
2016-05-30T00:41:10Z
[ "python", "python-3.x", "pandas" ]
Addition transactionSettings to a request object on Authorize.net (using sdk-python)
37,509,249
<p>I am using Authorize.net's native <a href="https://github.com/AuthorizeNet/sdk-python" rel="nofollow">python sdk</a>. In their <a href="https://developer.authorize.net/api/reference/index.html" rel="nofollow">API documentation</a>, it shows that you can nest a setting as follows:</p> <pre><code>transactionSettings ...
0
2016-05-29T11:19:23Z
37,510,610
<p>To remove the duplicate window protection you need to set it to zero:</p> <pre><code>request = apicontractsv1.ARBCreateSubscriptionRequest() request.transactionSettings = {'setting': [{'settingName': 'duplicateWindow', 'settingValue': 0}] } </code></pre>
0
2016-05-29T13:42:42Z
[ "python", "authorize.net", "pyxb", "authorize.net-python" ]
Addition transactionSettings to a request object on Authorize.net (using sdk-python)
37,509,249
<p>I am using Authorize.net's native <a href="https://github.com/AuthorizeNet/sdk-python" rel="nofollow">python sdk</a>. In their <a href="https://developer.authorize.net/api/reference/index.html" rel="nofollow">API documentation</a>, it shows that you can nest a setting as follows:</p> <pre><code>transactionSettings ...
0
2016-05-29T11:19:23Z
39,941,091
<p>The way I solved this is that I had the list and dictionaries set incorrectly. Unfortunately, it took a lot of digging thru source code to figure this out because the documentation was not as clear as I would have hoped. Regardless, now that I found the solution, all is well:</p> <pre><code>request.transactionSetti...
0
2016-10-09T07:27:11Z
[ "python", "authorize.net", "pyxb", "authorize.net-python" ]
Grid-search with specific validation data
37,509,409
<p>I'm looking for a way to grid-search for hyperparameters in sklearn, without using K-fold validation. I.e I want my grid to train on on specific dataset (X1,y1 in the example below) and validate itself on specific hold-out dataset (X2,y2 in the example below). </p> <p>X1,y2 = train data<br> X2,y2 = validation data...
0
2016-05-29T11:33:46Z
38,180,889
<pre><code>clf = GridSearchCV(clf_,dict(C=Cs,gamma=Gammas),cv=???, # validate on X2,y2,n_jobs=8,verbose=10) </code></pre> <ol> <li><p>n_jobs>1 does not make any sense. If n_jobs=-1 it means the processing will use all the cores on your machine. If it is 1 only one core would be use. </p></li> <li><p>If cv =5 it will r...
0
2016-07-04T09:12:45Z
[ "python", "scikit-learn", "grid-search" ]
Get data from Django model(mysql) as per user search
37,509,441
<p>I want to get data from Django model(mysql) as per user input. Like I have a html search tab where user will put search value which should get related data from Django-model and display in another html page. I tried but getting failed . Please help..</p> <pre><code>views.py from django.shortcuts import render_to_...
0
2016-05-29T11:36:25Z
37,509,786
<p>When rendering any template, you need to pass all the variables it needs as the context dictionary.</p> <pre><code>return render_to_response('results.html', {'name': name}) </code></pre> <p>This is all explained in the tutorial; you should probably go and follow it.</p>
0
2016-05-29T12:14:13Z
[ "python", "html", "django", "user-input" ]
Get data from Django model(mysql) as per user search
37,509,441
<p>I want to get data from Django model(mysql) as per user input. Like I have a html search tab where user will put search value which should get related data from Django-model and display in another html page. I tried but getting failed . Please help..</p> <pre><code>views.py from django.shortcuts import render_to_...
0
2016-05-29T11:36:25Z
37,512,078
<p>Assuming you are using GET method to submit your form:</p> <pre><code>def results(request): q = request.GET.get('q', None) if q: # icontains work similar to LIKE keyword in mysql. # for exact text search you can directly search City=q name=Techstop.objects.filter(City__icontains=q) ...
0
2016-05-29T16:06:53Z
[ "python", "html", "django", "user-input" ]
Get data from Django model(mysql) as per user search
37,509,441
<p>I want to get data from Django model(mysql) as per user input. Like I have a html search tab where user will put search value which should get related data from Django-model and display in another html page. I tried but getting failed . Please help..</p> <pre><code>views.py from django.shortcuts import render_to_...
0
2016-05-29T11:36:25Z
37,512,930
<p>you can simply do this using below functions:</p> <pre><code>import re from django.db.models import Q def normalize_query(query_string, findterms=re.compile(r'"([^"]+)"|(\S+)').findall, normspace=re.compile(r'\s{2,}').sub): return [normspace(' ', (t[0] or t[1]).strip())...
0
2016-05-29T17:38:05Z
[ "python", "html", "django", "user-input" ]
Trying to add a column to a data file
37,509,506
<p>I have a data file with 2 columns, x ranging from -5 to 4 and f(x). I need to add a third column with |f(x)| the absolute value of f(x). Then I need to export the 3 columns as a new data file. </p> <p>Currently my code looks like this: </p> <pre><code>from numpy import * data = genfromtxt("task1.dat") c = [] ab = ...
0
2016-05-29T11:44:07Z
37,509,857
<p><code>c</code> is a list and when you execute</p> <pre><code>c.append(ablist) c.append (datalist) </code></pre> <p>it appends 2 lists of different shapes to the list <code>c</code>. It will probably end up looking like this </p> <pre><code>c == [ [ [....],[....]], [....]] </code></pre> <p>which is not possible t...
0
2016-05-29T12:21:48Z
[ "python", "numpy", "append" ]
Trying to add a column to a data file
37,509,506
<p>I have a data file with 2 columns, x ranging from -5 to 4 and f(x). I need to add a third column with |f(x)| the absolute value of f(x). Then I need to export the 3 columns as a new data file. </p> <p>Currently my code looks like this: </p> <pre><code>from numpy import * data = genfromtxt("task1.dat") c = [] ab = ...
0
2016-05-29T11:44:07Z
37,509,859
<p>You are getting a list within a list in <code>c</code>.</p> <p>Anyway, I think this is much clearer:</p> <pre><code>import numpy as np data = np.genfromtxt("task1.dat") data_new = np.hstack((data, np.abs(data[:,-1]).reshape((-1,1)))) np.savetxt("task_out.dat", data_new) </code></pre>
0
2016-05-29T12:21:56Z
[ "python", "numpy", "append" ]
Trying to add a column to a data file
37,509,506
<p>I have a data file with 2 columns, x ranging from -5 to 4 and f(x). I need to add a third column with |f(x)| the absolute value of f(x). Then I need to export the 3 columns as a new data file. </p> <p>Currently my code looks like this: </p> <pre><code>from numpy import * data = genfromtxt("task1.dat") c = [] ab = ...
0
2016-05-29T11:44:07Z
37,512,908
<p><code>data</code> is a 2d array like:</p> <pre><code>In [54]: data=np.arange(-5,5).reshape(5,2) In [55]: data Out[55]: array([[-5, -4], [-3, -2], [-1, 0], [ 1, 2], [ 3, 4]]) In [56]: ab=abs(data[:,1]) </code></pre> <p>There are various ways to <code>concatenate</code> 2 arrays. I...
0
2016-05-29T17:34:47Z
[ "python", "numpy", "append" ]
When I install twisted, it missed out some files
37,509,577
<p><br/>I installed twisted with pip, but it missed some of the files (_win32stdio.py and _pollingfile.py). <br/>I tried copying those files into the directory(site-packages) and it work well. <br/>But I don't know why pip missed those files. <hr> <br/>English is my second language, Please forgive my grammar mistakes.<...
-2
2016-05-29T11:52:16Z
37,509,594
<p>Uninstall twisted and reinstall it. If the error still persists, check you installed Python from <a href="http://www.python.org" rel="nofollow">python.org</a> and try re-installing python as a whole. Try installing from terminal as well.</p>
0
2016-05-29T11:54:41Z
[ "python", "pip", "twisted" ]
BeautifulSoup search attributes-value
37,509,699
<p>I'm trying to search in HTML documents for specific attribute values. e.g.</p> <pre><code>&lt;html&gt; &lt;h2 itemprop="prio1"&gt; TEXT PRIO 1 &lt;/h2&gt; &lt;span id="prio2"&gt; TEXT PRIO 2 &lt;/span&gt; &lt;/html&gt; </code></pre> <p><strong>I want to find all items with atrributes values beginning with "p...
3
2016-05-29T12:05:29Z
37,509,893
<p>I don't know if this is the best way, but this works:</p> <pre><code>&gt;&gt;&gt; soup.find_all(lambda element: any(re.search('prio.*', attr) for attr in element.attrs.values())) [&lt;h2 itemprop="prio1"&gt; TEXT PRIO 1 &lt;/h2&gt;, &lt;span id="prio2"&gt; TEXT PRIO 2 &lt;/span&gt;] </code></pre> <p>In this case,...
0
2016-05-29T12:25:37Z
[ "python", "python-3.x", "beautifulsoup", "bs4" ]
BeautifulSoup search attributes-value
37,509,699
<p>I'm trying to search in HTML documents for specific attribute values. e.g.</p> <pre><code>&lt;html&gt; &lt;h2 itemprop="prio1"&gt; TEXT PRIO 1 &lt;/h2&gt; &lt;span id="prio2"&gt; TEXT PRIO 2 &lt;/span&gt; &lt;/html&gt; </code></pre> <p><strong>I want to find all items with atrributes values beginning with "p...
3
2016-05-29T12:05:29Z
37,510,152
<p>First off your regex is wrong, if you wanted to only find strings starting with <em>prio</em> you would prefix with <code>^</code>, as it is your regex would match prio anywhere in the string, if you were going to search each attribute you should just use <em>str.startswith</em>:</p> <pre><code>h = """&lt;html&gt...
1
2016-05-29T12:54:48Z
[ "python", "python-3.x", "beautifulsoup", "bs4" ]
efficiency of 'in' operation on different data structures in python
37,509,775
<p>I'new to programming, when I was using python, I find the 'in' operation's performances on different data structures are quite different. For example:</p> <pre><code>a=list_a######list_a and list_b both are lists,data scale:300,000 b=set(list_b) t1=time() s=0 for entry in a: if entry in b: s+=1 t2=time(...
1
2016-05-29T12:13:12Z
37,509,849
<p>Lists have linear time lookup. That's because to find whether an item is in a list, Python needs to scan through every item until it finds a match; so the time it takes is proportional to the length of the list. The longer the list, the longer it will take. In computer science terms, this is called <code>O(n)</code>...
3
2016-05-29T12:21:17Z
[ "python", "algorithm", "data-structures" ]
Python program to read function inputs
37,509,839
<p>Hi guy’s I’m trying to write a python program here and I’m just learning at the moment. what I’m trying to do is get the user to enter a 6 digit number and if they enter a number which is not 6 digits I want an error message to come us stating they must enter a 6 digit number. I have a function called <code>...
-1
2016-05-29T12:20:25Z
37,510,091
<p>I think you want something like:</p> <pre><code>def example_check_message(m): try: m = int(m) if m &gt;= 100000 and m &lt; 1000000: return m # &lt;- return something useful! except: print 'You must enter a number' return False </code></pre> <p>but there are errors i...
0
2016-05-29T12:47:55Z
[ "python", "python-2.7" ]
Not in list still gives me duplicate elements
37,509,902
<p>this is the code that I have. As you can see I append every element to the list if the element is not already in the list but I noticed I still somehow get duplicate elements. </p> <pre><code>def getExtraData(table): extraData = list() for ele in table: extras = re.findall('\[(.+?)\]', str(ele[0])) ...
0
2016-05-29T12:26:31Z
37,509,920
<blockquote> <p>Why could this happen and how can I fix it?</p> </blockquote> <p>There is nothing to fix, everything is fine. You get "Box <strong>S</strong>et" and "Box <strong>s</strong>et" because these are <strong>different strings</strong>. If you want to be case-insensitive, store lowercase versions, and test ...
2
2016-05-29T12:29:05Z
[ "python", "list" ]
Not in list still gives me duplicate elements
37,509,902
<p>this is the code that I have. As you can see I append every element to the list if the element is not already in the list but I noticed I still somehow get duplicate elements. </p> <pre><code>def getExtraData(table): extraData = list() for ele in table: extras = re.findall('\[(.+?)\]', str(ele[0])) ...
0
2016-05-29T12:26:31Z
37,509,996
<p>Alternatively to lejlot, if you want to preserve the case of string when storing them in <code>extraData</code>, you could use a generator for the check part:</p> <pre><code>if s.lower() not in map(str.lower, extraData): extraData.append(s) </code></pre> <p>Inspired by <a href="http://stackoverflow.com/a/3627815...
1
2016-05-29T12:39:32Z
[ "python", "list" ]
write spark dataframe as CSV with partitions
37,509,932
<p>I'm trying to write a dataframe in spark to an hdfs location and I expect that if I'm adding the 'partitionBy' notation spark will create partition (similar to writing in parquet format) folder in form of "partition_column_name=partition_value" ( i.e <code>partition_date=2016-05-03</code>). to do so, I ran the foll...
2
2016-05-29T12:30:45Z
37,510,415
<p><strong>Spark 2.0.0+</strong>:</p> <p>Built-in csv format supports partitioning out of the box so you should be able to simply use:</p> <pre><code>df.write.partitionBy('partition_date').mode(mode).format("csv").save(path) </code></pre> <p><strong>without including any additional packages</strong>.</p> <p><strong...
5
2016-05-29T13:24:00Z
[ "python", "csv", "apache-spark", "pyspark", "spark-dataframe" ]
Login to website with Python Selenium
37,509,945
<p>I want to login to this <a href="https://www.google.it/portaleTitolari/titolari.html" rel="nofollow">web site</a> with Python Selenium, for which I have written this code:</p> <pre><code># -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common...
1
2016-05-29T12:32:23Z
37,510,027
<p>Both of those input fields seem to have static classes. Simply search for an input element with the given class using xpath. Something like:</p> <pre><code>driver.find_element_by_xpath("//input[@class='login_component_input']") </code></pre> <p>Since the password uses the same class, you might try including the el...
0
2016-05-29T12:42:05Z
[ "python", "selenium", "selenium-webdriver" ]
Getting empty list while parsing
37,509,979
<p>I am parsing jeevansathi.com and want to select <code>&lt;ul&gt;</code> with id <code>#profileInfo2</code> but after using BeautifulSoup I am getting empty list Below is the code and the output</p> <pre><code>import requests, bs4 res = requests.get('http://www.jeevansathi.com/search/quick/169903999/1') try: r...
1
2016-05-29T12:37:15Z
37,510,285
<p>The content #profileInfo2 is not present in the page if you disable javascript in your browser, so it will not show up in python either without javascript. </p> <p>You can easily verify this by accessing the site with Firefox and an active NoScript Addon, and searching for #profileInfo2 in the html source code.</p>...
-1
2016-05-29T13:07:23Z
[ "python", "beautifulsoup" ]
Getting empty list while parsing
37,509,979
<p>I am parsing jeevansathi.com and want to select <code>&lt;ul&gt;</code> with id <code>#profileInfo2</code> but after using BeautifulSoup I am getting empty list Below is the code and the output</p> <pre><code>import requests, bs4 res = requests.get('http://www.jeevansathi.com/search/quick/169903999/1') try: r...
1
2016-05-29T12:37:15Z
37,510,653
<p>The content is dynamically loaded, you can see the template it in what requests returns or if you look at the view source in your browser:</p> <pre><code>&lt;div class="pt10 fontlig colr4 clearfix ulinline"&gt; &lt;ul id="profileInfo{profileNoId}" class="fl f14 wid83p descplist"&gt; &lt;li class="textTru"&gt;{age},...
3
2016-05-29T13:46:33Z
[ "python", "beautifulsoup" ]
getting Json from IBM watson
37,510,002
<p>I am new to python and trying to get Json output from IBM Watson tone analyzer. Here is what I used from Tone analyzer API reference:</p> <pre><code>import json from watson_developer_cloud import ToneAnalyzerV3 tone_analyzer = ToneAnalyzerV3( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD',...
0
2016-05-29T12:40:11Z
37,510,742
<p>Looks like you need to import <code>ToneAnalyzerV3</code>. Check this example from the docs. </p> <pre><code>import json from watson_developer_cloud import ToneAnalyzerV3 tone_analyzer = ToneAnalyzerV3( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', version='2016-05-19') print(js...
2
2016-05-29T13:54:59Z
[ "python", "ibm-watson-cognitive", "tone-analyzer" ]
Working with, preparing bag-of-word data for Regression
37,510,014
<p>Im trying to create a regression model that predicts an authors age. Im using (Nguyen et al,2011) as my basis.</p> <p>Using a Bag of Words Model I count the occurences of words per Document (which are Posts from Boards) and create the vector for every Post. </p> <p>I limit the size of each vector by using as featu...
0
2016-05-29T12:41:16Z
37,528,225
<p>To my knowledge Bag-of-words models usually use Naive Bayes as classifier to fit the document-by-term sparse matrix. </p> <p>None of your regressors can handle large sparse matrix well. Lasso may work well if you have groups of highly correlated features. </p> <p>I think for your problem, <a href="https://en.wikip...
2
2016-05-30T14:33:17Z
[ "python", "text", "machine-learning", "scikit-learn", "regression" ]
Unable to update nested dictionary value in multiprocessing's manager.dict()
37,510,076
<p>I am trying to update a key in a nested dictionary of multiprocessing module's manager.dict() but not able to do so. It doesn't update the value and doesn't throw any error too.</p> <p>Code:</p> <pre><code>import time import random from multiprocessing import Pool, Manager def spammer_task(d, token, repeat): ...
0
2016-05-29T12:46:07Z
37,510,417
<p>not sure why, but the Manager DictProxy object cant seems to handle mutating a nested part. this code works:</p> <pre><code>import time import random from multiprocessing import Pool, Manager def spammer_task(d, token, repeat): success = 0 fail = 0 while success+fail&lt;repeat: time.sleep(rand...
1
2016-05-29T13:24:19Z
[ "python", "dictionary", "multiprocessing", "python-multiprocessing", "multiprocessing-manager" ]
Python 2.7 csv download from URL
37,510,139
<p>I'm trying to do some basic analsys on ether historical prices for a school project. My problem is quite a simple one I think. I made a function that download the data from the URL, but the format is wrong. I got a dataframe thats size is (0,~14k). So I download the data, but I'm not sure how should I format it into...
1
2016-05-29T12:53:26Z
37,510,241
<p>The source data is not CSV, it's <a href="/questions/tagged/json" class="post-tag" title="show questions tagged &#39;json&#39;" rel="tag">json</a>. Luckily pandas <a href="http://stackoverflow.com/a/21266043/5113242">provides facilities for working with it as well</a>.</p> <pre><code>import requests from pandas.io....
3
2016-05-29T13:02:14Z
[ "python", "csv", "pandas" ]
Configure the path where Elasticsearch indexes are stored with Flask-Elasticsearch
37,510,289
<p>Flask-Elasticsearch doesn't document how to configure Elasticsearch. How can I specify the path for the storage of the indices with Elasticsearch? </p> <pre><code>from flask.ext.elasticsearch import FlaskElasticsearch app = Flask(__name__) es = FlaskElasticsearch(app) </code></pre>
1
2016-05-29T13:07:35Z
37,510,902
<p>Keyword args passed to <code>init_app</code> are <a href="https://github.com/chiangf/Flask-Elasticsearch/blob/0.2.5/flask_elasticsearch.py#L23" rel="nofollow">passed on</a> to the <code>Elasticsearch</code> instance. The <a href="http://elasticsearch-py.readthedocs.io/en/2.3.0/api.html#elasticsearch" rel="nofollow"...
1
2016-05-29T14:12:19Z
[ "python", "elasticsearch", "flask" ]
Convert content of Object datatype to Date datatype in Python
37,510,348
<p>I am using Jupyter Notebook, Pandas framework and Python as the programming language. I have a dataframe which is of the following shape (10500, 4). So it has 4 columns and 10500 records. Initial_Date is one out of the 4 columns which is an Object datatype. This is the type of information it contains:</p> <pre><co...
1
2016-05-29T13:14:09Z
37,510,475
<p>you can do it this way:</p> <pre><code>result = pd.to_datetime(d.Initial_Date.astype(str), dayfirst=True, errors='coerce') result.ix[result.isnull()] = pd.to_datetime(d.Initial_Date.astype(str), format='%d%m%Y', dayfirst=True, errors='coerce') #format is set to %d%m%Y </code></pre> <p>result:</p> <pre><code>In [...
1
2016-05-29T13:29:50Z
[ "python", "date", "pandas", "data-type-conversion", "jupyter" ]
Is there an equivalent of C's main() in a Python module?
37,510,364
<p>I'm creating a Python module <code>mymodule.py</code> and I need to run a function on import. The function should not be run by the user, and is only necessary to initiate the module properly.</p> <p>Since it's a module, this won't work:</p> <pre><code>if __name__ == '__main__': _main() </code></pre> <p>I wan...
0
2016-05-29T13:16:05Z
37,510,375
<p>Code that is not indented into a function will be run as the file is loaded (once). That's probably what you want:</p> <pre><code>def some_function(): pass def other_function(): pass init_value = 0 # This code here is run immediately. buffer = None </code></pre>
4
2016-05-29T13:18:18Z
[ "python" ]
Is there an equivalent of C's main() in a Python module?
37,510,364
<p>I'm creating a Python module <code>mymodule.py</code> and I need to run a function on import. The function should not be run by the user, and is only necessary to initiate the module properly.</p> <p>Since it's a module, this won't work:</p> <pre><code>if __name__ == '__main__': _main() </code></pre> <p>I wan...
0
2016-05-29T13:16:05Z
37,510,560
<p>Yeah have like a top level function that is like a main, something like this:</p> <pre><code> def interact(): # Your code which handles all the rest of the functions # For example print('Welcome to this program!') filename = input('Please enter the data source file: ') loa...
0
2016-05-29T13:37:57Z
[ "python" ]
Is there an equivalent of C's main() in a Python module?
37,510,364
<p>I'm creating a Python module <code>mymodule.py</code> and I need to run a function on import. The function should not be run by the user, and is only necessary to initiate the module properly.</p> <p>Since it's a module, this won't work:</p> <pre><code>if __name__ == '__main__': _main() </code></pre> <p>I wan...
0
2016-05-29T13:16:05Z
37,510,663
<p>Running a function on import is not equivalent to C's <code>main()</code>. C's <code>main()</code> is run when executing the program.</p> <p>Everything in a Python module which is top-level (i.e. not in a function) is executed when the module is imported. For example, if this is your module content:</p> <pre><co...
1
2016-05-29T13:47:18Z
[ "python" ]
Update rows in sql with new values
37,510,432
<p>i am working on python. i want to update every row of sql with new value. my code is:</p> <pre><code>val = cursor.execute("select id from tweeter1") words= processedRow.split() fdist2=len(words) for id1 in val: cursor.execute("""UPDATE TWEETER1 SET t1=%s where id = %s""",(fdist2,id1)) db...
0
2016-05-29T13:25:39Z
37,510,515
<p>You have to iterate over the cursor object:</p> <pre><code>cursor.execute("select id from tweeter1") words = processedRow.split() fdist2 = len(words) for id1 in cursor.fetchall(): cursor.execute("""UPDATE TWEETER1 SET t1=%s where id = %s""",(fdist2,id1)) db.commit() </code></pre> <p>But as long as you change a...
0
2016-05-29T13:33:07Z
[ "python", "mysql" ]
event handling of balloon tip with win32gui
37,510,460
<p>I'm currently using a slightly modified version of the <a href="http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html" rel="nofollow">common example of the systemtray</a>.</p> <pre><code>#!/usr/bin/env python # Module : SysTrayIcon.py # Synopsis : Windows System tray icon. # Programmer : Simon...
1
2016-05-29T13:28:20Z
39,960,137
<p>I ended up using the try, except block with a win32gui error exception. Anywhere I was making a call to win32gui, I wrapped in the win32gui.error exception block. AFAIK, that's the only method to obtain the exception.</p> <p><code> try: win32gui.&lt;something&gt; except win32gui.error as error: logging.e...
0
2016-10-10T14:03:48Z
[ "python", "win32com", "win32gui" ]
UnicodeDecodeError by python regex
37,510,616
<p>I am trying to replace all tabs with a space so I can put my Coma seperated text in one line in another file. Now my code look like this:</p> <pre><code>from __future__ import print_function import re import ast f = open('sample_test.txt', 'r') g = open('sample_test1.txt', 'w') for line in f: c = re.sub(r...
0
2016-05-29T13:43:22Z
37,511,868
<p>Open the files as <em>utf-8</em>, you also don't need a regex if you just want to replace tabs:</p> <pre><code>import io with io.open('sample_test.txt', encoding="utf-8") as f, io.open('sample_test1.txt', 'w', encoding="utf-8") as g: for line in f: g.write(line.replace("\t"," ")) </code></pre>
0
2016-05-29T15:47:42Z
[ "python", "unicode" ]
compare sum of column values in python
37,510,643
<p>I have a csv file loaded in a python object. 15 of the columns contains binary values. I have several thousands rows.</p> <p>I want to count the sum of the binary values of each of the columns and sort the result ascendingly. </p> <p>I only made it to: </p> <pre><code>sum1=sum(products['1']) sum2=sum(products['2...
0
2016-05-29T13:45:40Z
37,510,757
<p>you will find the solution here :</p> <pre><code>with open("file.csv") as fin: headerline = fin.next() list_sum_product=[] for i in range(15): total = 0 for row in csv.reader(fin): total += int(row[i]) list_sum_product.append(total) print sorted(list_sum_product) </code></pre>
1
2016-05-29T13:56:42Z
[ "python" ]
compare sum of column values in python
37,510,643
<p>I have a csv file loaded in a python object. 15 of the columns contains binary values. I have several thousands rows.</p> <p>I want to count the sum of the binary values of each of the columns and sort the result ascendingly. </p> <p>I only made it to: </p> <pre><code>sum1=sum(products['1']) sum2=sum(products['2...
0
2016-05-29T13:45:40Z
37,510,758
<p>How about this:</p> <pre><code>sorted_sum = sorted([sum(products[i]) for i in range(1, 16)]) </code></pre> <p>sorted_sum is the sorted list of column sums. However, I believe the index should run from 0 to 14, not 1 to 15.</p>
1
2016-05-29T13:56:54Z
[ "python" ]
How can I replace Unicode characters with Turkish characters in a text file with Python
37,510,650
<p>I am working on Twitter. I got data from Twitter with Stream API and the result of app is JSON file. I wrote tweets data in a text file and now I see Unicode characters instead of Turkish characters. I don't want to do find/replace in Notepad++ by hand. Is there any automatic option to replace characters by opening ...
0
2016-05-29T13:46:21Z
37,510,876
<p>JSON allows both "escaped" and "unescaped" characters. The reason why the Twitter API returns only escaped characters is that it can use the ASCII encoding, which increases interoperability. For Turkish characters you need another encoding. Opening a file with the <a href="https://docs.python.org/3/library/functi...
1
2016-05-29T14:09:46Z
[ "python", "unicode", "replace", "character", "turkish" ]
ubuntu install python 3.5
37,510,702
<p>How can I easily install python 3.5 on ubuntu? In this article <a href="http://askubuntu.com/questions/682869/install-python-3-5-on-vivid-using-apt-get">http://askubuntu.com/questions/682869/install-python-3-5-on-vivid-using-apt-get</a> write what im must run next comand</p> <pre><code>sudo add-apt-repository ppa:f...
2
2016-05-29T13:52:04Z
37,510,744
<p>It comes by default when you run <em>the current release</em>:</p> <pre><code>edd@max:~$ python --version Python 2.7.11+ edd@max:~$ python3.5 --version Python 3.5.1+ edd@max:~$ </code></pre> <p>So available but not yet the default python engine. That is using</p> <pre><code>edd@max:~$ lsb_release -a No LSB module...
2
2016-05-29T13:55:09Z
[ "python", "python-3.x", "ubuntu" ]
ubuntu install python 3.5
37,510,702
<p>How can I easily install python 3.5 on ubuntu? In this article <a href="http://askubuntu.com/questions/682869/install-python-3-5-on-vivid-using-apt-get">http://askubuntu.com/questions/682869/install-python-3-5-on-vivid-using-apt-get</a> write what im must run next comand</p> <pre><code>sudo add-apt-repository ppa:f...
2
2016-05-29T13:52:04Z
37,510,813
<p>Is software-properties-common installed? You can check by running <em>apt-cache search software-properties-common</em> On my 14.04 it shows:</p> <pre><code>$ apt-cache policy software-properties-common software-properties-common: Installed: 0.92.37.7 Candidate: 0.92.37.7 Version table: *** 0.92.37.7 0 ...
1
2016-05-29T14:03:20Z
[ "python", "python-3.x", "ubuntu" ]
Using np.argwhere to find the maximum in a matrix
37,510,720
<p>I am trying to get the indices of the maximum value in a matrix, using argwhere function. I am using this syntax:</p> <pre><code>where = np.argwhere(np.argmax(matrix)) </code></pre> <p>where matrix is the matrix i am using and i want where to be a tuple that gives me the coordinates of the maximum value. But wher...
0
2016-05-29T13:53:14Z
37,510,881
<p><code>np.argmax(arr)</code> by default, returns the index of the maximum value into the <em>flattened array</em>, <code>arr.ravel()</code>. </p> <p>To obtain the index of the maximum value of <code>arr</code> itself, use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unravel_index.html" r...
4
2016-05-29T14:10:28Z
[ "python", "numpy" ]
Python Imports Explained
37,510,745
<p>Having a hard time wrapping my head around Python imports. I've read the difference between import X and from X import * here- <a href="http://effbot.org/zone/import-confusion.htm" rel="nofollow">http://effbot.org/zone/import-confusion.htm</a> but I'm having a hard time understanding the difference between import "m...
0
2016-05-29T13:55:10Z
37,510,786
<p>In this specific case, the <code>datetime</code> <em>module</em> has a <code>datetime</code> <em>class</em>. It's confusing, since they have the same name. When you do <code>import datetime</code>, what you get is a module named <code>datetime</code>. To access members of that module (such as the <code>datetime</cod...
2
2016-05-29T14:00:23Z
[ "python", "python-import" ]
Python Imports Explained
37,510,745
<p>Having a hard time wrapping my head around Python imports. I've read the difference between import X and from X import * here- <a href="http://effbot.org/zone/import-confusion.htm" rel="nofollow">http://effbot.org/zone/import-confusion.htm</a> but I'm having a hard time understanding the difference between import "m...
0
2016-05-29T13:55:10Z
37,510,811
<p>the datetime module has a datetime class within it. This is how you would use it</p> <pre><code>from datetime import * datetime.datetime.fromtimestamp </code></pre> <p>or</p> <pre><code>from datetime import datetime datetime.fromtimestamp </code></pre> <p>the time module doesn't have a time class and exposes its...
1
2016-05-29T14:03:10Z
[ "python", "python-import" ]
python - if statement return wrong value
37,510,761
<p>I used the followng code to trigger IF statement based on the value of row[0] my problem is always IF statement give me wrong output even if the value is greater than 0 its keep printing NO FAILURE .</p> <pre><code>conn = psycopg2.connect(conn_string) cursor = conn.cursor() cursor.execute("select c...
0
2016-05-29T13:57:18Z
37,510,832
<p><code>'0'</code> is a string use <code>0</code>. Like this:</p> <pre><code>if( row[0] &gt; 0 ): ... </code></pre> <p>Otherwise you get this:</p> <pre><code>TypeError: unorderable types: int() &gt; str() </code></pre> <p>which means you may not compare an <code>int</code> to a <code>string</code>.</p>
1
2016-05-29T14:04:57Z
[ "python" ]
Does Python's DataReader count as an API?
37,510,822
<p>I've been using <code>pandas.io.data.DataReader</code> to pull data from Yahoo Finance. Does this count as using an API? My somewhat rudimentary understanding of an API is that it allows you to accomplish your goal within your program (Python, Excel, etc.) without having to visit the actual website. Thanks.</p>
0
2016-05-29T14:04:19Z
37,510,923
<p>See <a href="https://developer.yahoo.com/yql/guide/usage_info_limits.html" rel="nofollow">https://developer.yahoo.com/yql/guide/usage_info_limits.html</a></p> <p>If you access yahoo with one of the following addresses it counts as using an API:</p> <pre><code>/v1/public/* /v1/yql/* </code></pre>
0
2016-05-29T14:13:51Z
[ "python", "python-2.7", "python-3.x", "pandas", "yahoo-finance" ]
Define a function that repeat commands for each input given in python
37,510,854
<p>I want to define a function like the following in a class:</p> <pre><code>class multiprocessing_np_arr_base_class(object): def pool_init(self, _shr_var1, _shar_var2, _shr_var3,...): global shr_var1 shr_var1 = _shr_var1 global shr_var2 shr_var2 = _shr_var2 global shr_var3 ...
1
2016-05-29T14:07:38Z
37,511,213
<p>I would suggest you implement something like this:</p> <pre><code>shr_var = {} class multiprocessing_np_arr_base_class(object): def __init__(self, **kwargs): for k, v in kwargs.items(): shr_var[k] = v </code></pre> <p>Then the usage would be:</p> <pre><code>a = multiprocessing_np_arr_base...
1
2016-05-29T14:42:00Z
[ "python", "function" ]
python: Why diff processes return same epoll object when calling select.epoll()
37,510,896
<p><b>My goal</b>: start N sub-processes, each deal with different socket sets. -- This means different epoll objects are needed.<br> <b>Porblem</b>: When i call select.epoll() in sub-processes, it returns the same object.<br> Here's a simple example below:</p> <pre><code>from multiprocessing import Process,Lock impor...
0
2016-05-29T14:12:02Z
37,510,992
<p>Since this are different processes, the epoll resources are also different. Each process has it's own set of file numbers. They lowest free file number is selected for a new resource. That's why both processes uses the same file number. No fix needed.</p>
0
2016-05-29T14:21:09Z
[ "python", "multiprocessing", "epoll" ]
Connecting a one to many with three tables?
37,510,912
<p>Hello I am learning flask by working on a website and I came across an issue that I can't seem to figure out.</p> <p>I want to try and make a one to many table which connects through primary keys. The idea is that a user can create a character and if the type is original I can bring up the Original table and displa...
1
2016-05-29T14:13:12Z
37,511,498
<blockquote> <p>Is this possible and if so should I go about doing it this way or connecting them based on who created the character instead of their id?</p> </blockquote> <p>It is possible, and you can also connect them based on the creator.</p> <p>Depending on what the data is like and what you are trying to ...
0
2016-05-29T15:09:57Z
[ "python", "mysql", "database", "sqlalchemy" ]
Sort rows of numpy matrix efficiently
37,510,916
<p>I have a numpy 2d array of real numbers, for example</p> <pre><code>A= np.array( [[0.1, 0.01, 0.4, 0.9], [0.0005, -0.2, -0.1, 0.6], [-0.3, -0.5, 0.2, 0.9]]) </code></pre> <p>and a vector of indices of the same size of <code>A.shape[1]</code>: <code>idx=[5, 2, 3, 9]</code></p> <p>for every row of A, I need to so...
1
2016-05-29T14:13:28Z
37,511,046
<p>You can use <code>np.argsort()</code> to get the indices of your array in a sorted mode and reverse it to get the indices of decreasing mode, then use a simple indexing to get your expected output:</p> <pre><code>&gt;&gt;&gt; A.argsort() array([[1, 0, 2, 3], [1, 2, 0, 3], [1, 0, 2, 3]]) &gt;&gt;&gt; i...
3
2016-05-29T14:26:33Z
[ "python", "numpy" ]
Python: Read the input file of delimited strings into a nested dictionary and loop through it
37,510,946
<p>My input file would look like this:</p> <pre><code>1111;A:aaaa,B:aaaa,F:aaaa 2222;A:aaaa,B:aaaa,E:aaaa 3333;C:aaaa,D:aaaa,E:aaaa,F:aaaa 4444;D:aaaa 5555;C:bbbb 2222;A:bbbb,B:bbbb 2222;A:cccc,B:cccc 1111;C:cccc,D:cccc,E:cccc,F:cccc 2222;A:dddd,B:dddd 1111;A:eeee,B:eeee 1111;A:ffff,B:ffff 2222;C...
-1
2016-05-29T14:16:04Z
37,511,339
<p>The Python equivalent of a Java <code>Map</code> is a <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow"><code>dict</code></a>, and parsing such a simple input can be easily done with <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>sp...
2
2016-05-29T14:53:32Z
[ "python", "python-2.7" ]
np.fromfunction: Reference other arrays
37,510,982
<p>I am trying to create an array based on whether values in one array are in another array. I was hoping the following would work:</p> <pre><code>A = np.fromfunction(lambda x, y: tuple(order[x,:]) in paths[y,],\ shape=((len(order), len(paths))), dtype=int) </code></pre> <p>Unfortunately, this only yield a scalar...
2
2016-05-29T14:20:29Z
37,512,587
<p>Look at the code form <code>fromfunction</code>.</p> <pre><code>args = indices(shape, dtype=dtype) return function(*args,**kwargs) </code></pre> <p><code>np.indices</code> is like <code>meshgrid</code></p> <pre><code>In [28]: np.indices((2,3)) Out[28]: array([[[0, 0, 0], [1, 1, 1]], [[0, 1, 2], ...
2
2016-05-29T16:58:15Z
[ "python", "arrays", "numpy" ]
Input Defaulting to String in Python 3.x Even if Numbers are Entered
37,511,112
<p>I'm a total noob, so thank you for your patience. I'm having trouble accepting integer inputs in my program; they all come out as strings. I confirmed this by adding the type() lines that are currently commented out. How do I make my program accept inputs as integers? Thanks.</p> <pre><code># TIP CALCULATOR d...
0
2016-05-29T14:32:57Z
37,511,162
<p>You have to convert the string to a int:</p> <pre><code>cost = int(input('Please enter the cost of your meal or service.')) </code></pre>
0
2016-05-29T14:37:37Z
[ "python", "python-3.x" ]
Input Defaulting to String in Python 3.x Even if Numbers are Entered
37,511,112
<p>I'm a total noob, so thank you for your patience. I'm having trouble accepting integer inputs in my program; they all come out as strings. I confirmed this by adding the type() lines that are currently commented out. How do I make my program accept inputs as integers? Thanks.</p> <pre><code># TIP CALCULATOR d...
0
2016-05-29T14:32:57Z
37,511,212
<p>The <code>input()</code> function reads the input from <code>stdin</code> which is actually a file object and return a string. If you want to have your input in integer type you can use <code>int()</code> function for convert the string digits to integer. But note that you should wrap it with a <code>try-except</cod...
0
2016-05-29T14:41:56Z
[ "python", "python-3.x" ]
How to quickly print Tensorflow results to TXT?
37,511,148
<p>I would like to know how I can efficiently save the NN weighting factors to TXT file by Tensorflow. The flowing is an example that I try to save the results from Tensorflow to TXT by using <code>fp.write</code>. However, it takes more than 1 days when I have 4 layers NN with 1000 hidden units in each layer. </p> <...
1
2016-05-29T14:36:02Z
37,551,440
<p><strong>TL;DR:</strong> The overhead comes from calling <code>sess.run()</code> once per <em>element</em> of the weight matrix. You can call this once per matrix, and operate on a Numpy array instead.</p> <hr> <p>I suspect the source of the slowness is this expression, which is evaluated for every element of the w...
1
2016-05-31T16:49:21Z
[ "python", "tensorflow" ]
Pyinstaller Intel MKL fatal error when running .exe file Python 2.7
37,511,165
<p>I have made a GUI application using wxpython and some other packages (matplotlib, pandas, numpy). I tried to compile this into a standalone executable. However, when I run the 'my_script.exe' I get the following error in my command prompt: </p> <blockquote> <p>Intel MKL FATAL ERROR: Cannot load mkl_avx2.dll or m...
1
2016-05-29T14:37:47Z
37,513,422
<p>Search for <code>mkl_avx2.dll</code> &amp; <code>mkl_def.dll</code> files and paste them in your <code>.exe</code> folder.</p>
1
2016-05-29T18:25:47Z
[ "python", "executable", "anaconda", "pyinstaller" ]
pysftp connection to host with pem file raise exception paramiko.ssh_exception.BadAuthenticationType
37,511,190
<p>I have to connect to other server in python using the pysftp library, the target server had a key value pair file (pem file), and I've got the following exception:</p> <pre><code>paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey']) (allowed_types=[u'publickey']) </code></pre> <...
0
2016-05-29T14:39:49Z
37,511,268
<p>From the documentation :</p> <pre><code>import pysftp with pysftp.Connection('hostname', username='me', private_key='/path/to/keyfile') as sftp: # # ... do sftp operations # </code></pre> <p>As you can see there is no <code>password= "no password"</code>, in ther. Try, by just omitting that in your cod...
1
2016-05-29T14:47:33Z
[ "python" ]
Overriding Django's get_form_class() method throws string error
37,511,232
<p>I have a class based view that is supposed to dynamically select a form based on the name of the animal.</p> <pre><code>UpdateAnimalView(FormMixin, DetailView): def get_form_class(self): SOME_FORMS = { "Dog" : "UpdateDogForm", "Cat" : "UpdateCatForm", "Frog" : "UpdateFrogForm", } ...
0
2016-05-29T14:43:27Z
37,511,290
<p><code>get_form_class</code> should return the actual class, not its name:</p> <pre><code># import the form classes from wherever they live from .forms import UpdateDogForm, UpdateCatForm, UpdateFrogForm ... SOME_FORMS = { "Dog": UpdateDogForm, # &lt;- no string values here! "Cat": UpdateCatForm, # &lt;-...
3
2016-05-29T14:49:20Z
[ "python", "django", "django-class-based-views" ]
How can I start and stop a Python script from shell
37,511,265
<p>thanks for helping!</p> <p>I want to start and stop a Python script from a shell script. The start works fine, but I want to stop / terminate the Python script after 10 seconds. (it's a counter that keeps counting). bud is won't stop.... I think it is hanging on the first line.</p> <p>What is the right way to sta...
2
2016-05-29T14:47:05Z
37,511,354
<p>You're right, the shell script "hangs" on the first line until the python script finishes. If it doesn't, the shell script won't continue. Therefore you have to use <code>&amp;</code> at the end of the shell command to run it in the background. This way, the python script starts and the shell script continues.</p> ...
8
2016-05-29T14:54:59Z
[ "python", "shell" ]
How can I start and stop a Python script from shell
37,511,265
<p>thanks for helping!</p> <p>I want to start and stop a Python script from a shell script. The start works fine, but I want to stop / terminate the Python script after 10 seconds. (it's a counter that keeps counting). bud is won't stop.... I think it is hanging on the first line.</p> <p>What is the right way to sta...
2
2016-05-29T14:47:05Z
37,511,536
<p>You can terminate any process from any other if OS let you do it. I.e. if it isn't some critical process belonging to the OS itself.</p> <p>The command kill uses PID to kill the process, not the process's name or command.</p> <p>Use pkill for that.</p> <p>You can also, send it a different signal instead of SIGTER...
0
2016-05-29T15:13:09Z
[ "python", "shell" ]
How to plot confusion matrix with gridding without color using matplotlib?
37,511,277
<p>I found a similar quesion on <a href="http://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python">How to plot confusion matrix with string axis rather than integer in python</a>. But the answer is not exact what I want. Because it doesn't contain gridding (...
3
2016-05-29T14:48:24Z
37,511,601
<p>By making only a few changes to that rather excellent code proposal (I upvoted it, consider doing that too), you can get the figure you're describing. </p> <p>You'll get gridding by calling the <code>hlines</code> and <code>vlines</code> methods of the <code>ax</code> object, which will add horizontal and vertical ...
1
2016-05-29T15:20:26Z
[ "python", "matplotlib" ]
Scrapy returning 301 for reddit.com
37,511,312
<p>I'm using reddit as the basis for learning scrappy. It was working fine for a while, but now it always returns a 301 redirect, even when simply calling the shell with "scrapy shell www.reddit.com". Any ideas how to fix this?</p>
-1
2016-05-29T14:51:05Z
37,511,424
<p>use the https/http scheme in the url</p> <pre><code>scrapy shell https://www.reddit.com </code></pre>
0
2016-05-29T15:02:37Z
[ "python", "scrapy", "scrape", "reddit" ]
Scrapy returning 301 for reddit.com
37,511,312
<p>I'm using reddit as the basis for learning scrappy. It was working fine for a while, but now it always returns a 301 redirect, even when simply calling the shell with "scrapy shell www.reddit.com". Any ideas how to fix this?</p>
-1
2016-05-29T14:51:05Z
37,512,103
<p>I think it's something related to reddit itself as it seems blocking your IP or user agent, you need to try tweaking the following : 1- Raise the DOWNLOAD_DELAY in scrapy settings 2- Try to change your user agent 3- Use proxy with scrapy</p> <p>For more info on the settings: <a href="http://doc.scrapy.org/en...
0
2016-05-29T16:09:57Z
[ "python", "scrapy", "scrape", "reddit" ]
Python: Finding nearest integer value to specific integer
37,511,334
<p>I'm trying to add an algorithm to my script that would find the nearest integer value from few variables, so for example:</p> <pre><code>int = 700 value1 = 400 value2 = 500 value6 = 600 </code></pre> <p>How can I make a script that gets <code>value6</code> as the nearest value from all the value variables?</p>
1
2016-05-29T14:53:07Z
37,511,356
<p>You can use the <code>min</code>-function with key-argument:</p> <pre><code>values = [400, 500, 600] int = 700 nearest = min(values, key=lambda v: abs(v-int)) </code></pre>
1
2016-05-29T14:55:21Z
[ "python" ]
Python: Finding nearest integer value to specific integer
37,511,334
<p>I'm trying to add an algorithm to my script that would find the nearest integer value from few variables, so for example:</p> <pre><code>int = 700 value1 = 400 value2 = 500 value6 = 600 </code></pre> <p>How can I make a script that gets <code>value6</code> as the nearest value from all the value variables?</p>
1
2016-05-29T14:53:07Z
37,511,359
<p>Use <a href="https://docs.python.org/2/library/functions.html#min"><code>min</code></a> with an appropriate key function, e.g. the <a href="https://docs.python.org/2/library/functions.html#abs">abs</a> of the difference to <code>i</code> (which you really shouldn't name <code>int</code>):</p> <pre><code>i = 700 # ...
10
2016-05-29T14:55:29Z
[ "python" ]
Python: Finding nearest integer value to specific integer
37,511,334
<p>I'm trying to add an algorithm to my script that would find the nearest integer value from few variables, so for example:</p> <pre><code>int = 700 value1 = 400 value2 = 500 value6 = 600 </code></pre> <p>How can I make a script that gets <code>value6</code> as the nearest value from all the value variables?</p>
1
2016-05-29T14:53:07Z
37,511,405
<p>You can do it in <em>log n</em> time if you keep the numbers in order and <a href="https://docs.python.org/2/library/bisect.html" rel="nofollow">bisect</a></p> <pre><code>i = 540 value1 = 400 value2 = 500 value6 = 600 lst = [value1, value2, value6] from bisect import bisect ind = bisect(lst, i, hi=len(lst) - 1) p...
3
2016-05-29T15:00:43Z
[ "python" ]
Python: Finding nearest integer value to specific integer
37,511,334
<p>I'm trying to add an algorithm to my script that would find the nearest integer value from few variables, so for example:</p> <pre><code>int = 700 value1 = 400 value2 = 500 value6 = 600 </code></pre> <p>How can I make a script that gets <code>value6</code> as the nearest value from all the value variables?</p>
1
2016-05-29T14:53:07Z
37,511,576
<p>You could also try this longer way, for learning purposes I guess:</p> <pre><code> values = [400, 500, 600] i = 700 candidates = [] for value in values: candidates.append(abs(i-value)) closest_index = candidates.index(min(candidates)) print(values[closest_index]) </code></pre>
1
2016-05-29T15:17:44Z
[ "python" ]
Python: Finding nearest integer value to specific integer
37,511,334
<p>I'm trying to add an algorithm to my script that would find the nearest integer value from few variables, so for example:</p> <pre><code>int = 700 value1 = 400 value2 = 500 value6 = 600 </code></pre> <p>How can I make a script that gets <code>value6</code> as the nearest value from all the value variables?</p>
1
2016-05-29T14:53:07Z
37,511,693
<p>As a relative beginner to python I feel sure this could be improved. The other answers are great but only return the nearest value <em>under</em> the input when there are two values equally distant.</p> <p>(above edited for clarity in response to Padraic Cunningham)</p> <pre><code>#!/usr/bin/python3 values = (100...
2
2016-05-29T15:30:58Z
[ "python" ]
How to get the distribution name from a spicy.stats. frozen distribution?
37,511,416
<h1>Access to a Frozen Distribution's Name</h1> <p>When creating a <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#freezing-a-distribution" rel="nofollow"><em>frozen</em> distribution</a> from the <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#statistics-scipy-stats" rel=...
1
2016-05-29T15:01:37Z
37,511,417
<h1>The Frozen Distribution <code>rv_frozen</code> Class</h1> <p>The frozen distribution, or <a href="https://github.com/scipy/scipy/blob/v0.17.0/scipy/stats/_distn_infrastructure.py#L423-L431" rel="nofollow"><code>rv_frozen</code> class</a> creates an instance of the distribution during initialization and this is sto...
1
2016-05-29T15:01:37Z
[ "python", "random", "scipy", "distribution" ]
Add an object by id in a ManyToMany relation in Django
37,511,421
<p><a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField" rel="nofollow">Django's ManyToMany field</a> can be populated using <code>my_field.add(my_instance)</code>, but as I understand it only <code>my_instance.id</code> is actually needed to perform the corresponding SQL q...
1
2016-05-29T15:02:09Z
37,511,518
<p>Although <a href="https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.add" rel="nofollow">the documentation of the <code>add</code> method</a> does not mention it, you can actually pass directly an id to it, like this:</p> <pre>my_instance.add(id)</pre> <p>Sur...
3
2016-05-29T15:10:58Z
[ "python", "sql", "django", "many-to-many" ]
using bs4 to find a html tag (h2) having text
37,511,490
<p>for this part of html code: </p> <pre><code>html3= """&lt;a name="definition"&gt; &lt;/a&gt; &lt;h2&gt;&lt;span class="sectioncount"&gt;3.342.2323&lt;/span&gt; Content Logical Definition &lt;a title="link to here" class="self-link" href="valueset-investigation"&gt;&lt;img src="ta.png"/&gt;&lt;/a&gt;&lt;/h2&gt; &lt;...
1
2016-05-29T15:08:52Z
37,511,556
<p>The main problem is the way you are locating the <code>h2</code> element to find siblings from. I'd use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow">function</a> instead checking that <code>Content Logical Definition</code> is inside the text:</p> <pre><code>soup.find...
4
2016-05-29T15:15:03Z
[ "python", "html", "beautifulsoup", "html-parsing", "bs4" ]
compile Cython with specific compiler args
37,511,506
<p>When one runs the following code: </p> <pre><code>git clone https://github.com/cython/cython.git sudo python setup.py install </code></pre> <p>cython (<code>Cython==0.24</code>) is compiled with the default compilation arguments. <a href="http://stackoverflow.com/questions/8236648/how-does-one-overwrite-the-defaul...
1
2016-05-29T15:10:21Z
37,512,791
<p>I'm pretty sure that using <code>export CFLAGS="-O3"</code> from the terminal before running <code>setup.py</code> (as I mentioned in the comment) generally does the trick, but, I just realized what you were trying to do.</p> <p>You need to supply the <code>extra_compile_args</code> as an argument when creating the...
1
2016-05-29T17:19:15Z
[ "python", "cython" ]
TypeError: a bytes-like object is required, not 'Binary'
37,511,560
<p>I use <code>xmlrpc.server</code> to build a server and use <code>pickle.dumps()</code> to pickling some data. Then I use <code>xmlrpc.client</code> to build a client and use <code>pickle.loads()</code> to unpickle this data, but I counter following problems:</p> <p><img src="http://i.stack.imgur.com/NYB3f.jpg" alt=...
3
2016-05-29T15:15:31Z
37,511,706
<p>Given a <code>Binary</code> instance <code>bin</code>, you can get the data as a <code>bytes</code> or <code>bytearray</code> instance by <code>bin.data</code>.</p> <p>I can only guess from the code snippet you provided, but the following should work:</p> <pre><code>ret = pickle.loads(ret.data) </code></pre>
1
2016-05-29T15:32:19Z
[ "python", "pickle" ]
python if wait then statement
37,511,650
<p>I am working on a raspberry pi python script and I am struggling to get the if statement to do what I want.</p> <p>I can count fingers on a hand in a video stream and this is working fine.</p> <p>Next I want to initiate a first event (beep) when 5 fingers (defects) are counted, and then proceed into a sub loop whe...
3
2016-05-29T15:25:13Z
37,511,810
<p>The issue is that count_defects takes an initial value <code>== 5</code> to pass the <code>if</code> clause. However, it can never then assume another value unless you give it an opportunity to recalculate. I don't know the function you use to get this value, but your code should look something like the following.</...
2
2016-05-29T15:41:53Z
[ "python", "if-statement" ]
update multiple rows with different values python and mysql
37,511,682
<p>i want to update multiple rows with different values.</p> <p>for example my table is : </p> <blockquote> <p>id | Name | Data</p> <p>1 |ahmad | year 2015</p> <p>2 | ali | year 2014</p> </blockquote> <p>i want my table to look like this:</p> <blockquote> <p>id | Name | Data | number</p> <p...
0
2016-05-29T15:28:39Z
37,512,576
<p>Yes, you can. 7000 is a low number for a computer.</p> <p>You could try to optimise it for >100k to use multiple database connections or not to commit on each update but that's outside the scope of your questions.</p>
0
2016-05-29T16:57:30Z
[ "python", "mysql" ]
import modules in python jobs with dispy
37,511,799
<p>I'm working with a program that works in parallel execution with dispy. I'm using dispy to create tasks and then distribute it to different CPUs to execution.</p> <p>I have standar libraries and developed by me libraries (data and connection).</p> <p>The code is like this:</p> <pre><code>import dispy import sys i...
1
2016-05-29T15:40:36Z
37,512,352
<p>Put the <code>import data</code> call inside the compute function. </p> <p>Dispy ships the function to call along with its arguments to the new process. The new process doesn't have data imported. That's why adding <code>import data</code> inside the function definition should fix this.</p>
0
2016-05-29T16:36:06Z
[ "python", "python-2.7", "hpc", "dispy" ]
Why doesn't gunicorn log 500 internal server errors to stderr?
37,511,855
<p>I've got a website built with <a href="http://flask.pocoo.org" rel="nofollow">Flask</a> and running on <a href="http://gunicorn.org/" rel="nofollow">gunicorn</a> behind <a href="http://nginx.org/" rel="nofollow">Nginx</a>. When I run gunicorn manually using the following command</p> <pre><code>gunicorn --worker-cla...
0
2016-05-29T15:46:18Z
37,613,125
<p>Turns out that I forgot that if in production mode, the application logs errors to another application specific log file.</p> <p>Maybe this serves as a reminder for future people to check application-specific logs.. :-)</p>
0
2016-06-03T11:24:50Z
[ "python", "logging", "nginx", "gunicorn", "stderr" ]
'BoundField' object has no attribute '_committed' when saving object
37,511,862
<p>I'm facing a problem with saving an object <code>delivery</code>.</p> <p>So I have two objects - <code>Job</code> and <code>Delivery</code>. When the <code>job</code> instance is being delivered, some changes are happening in <code>job.delivery</code>.</p> <p>Everything works correct - the <code>delivery_form</cod...
0
2016-05-29T15:47:03Z
37,512,008
<p>For <code>notes</code>, you're correctly getting the value from <code>deliver_form.cleaned_data</code>. But for <code>file</code>, you're getting it directly from <code>deliver_form</code>; you should be using <code>cleaned_data</code> there too.</p>
1
2016-05-29T16:00:24Z
[ "python", "django", "django-models", "django-views", "django-database" ]
Evaluating vector distance measures
37,511,924
<p>I am working with vectors of word frequencies and trying out some of the different distance measures available in <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html" rel="nofollow">Scikit Learns Pairwise Distances</a>. I would like to use these distances for cl...
0
2016-05-29T15:52:33Z
37,522,798
<p>In general - this is just a heuristic, which might, or not - work. In particular, it is easy to construct a "dummy metric" which will "win" in your approach even though it is useless. Try out</p> <pre><code>class Dummy_dist: def __init__(self): self.cheat = True def __call__(self, x, y): if self.cheat...
1
2016-05-30T10:00:14Z
[ "python", "scipy", "nlp", "scikit-learn", "distance" ]
How to display default value of option in ModelChoiceField django when loading?
37,511,932
<p>I was trying to create a ModelChoiceField using form</p> <pre><code>class Person(forms.Form): person = forms.ModelChoiceField(queryset=Person.objects.filter(is_active=True).order_by('id'), required=False) age = forms.IntegerField(min_value=18, max_value=99, required=False) </code></pre> <p>return as an h...
3
2016-05-29T15:53:36Z
37,512,001
<p>First of all you need to change <code>__unicode__</code> method(or <code>__str__</code> if on python3) so it would return name of person object <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/#str" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/instances/#str</a></p> <pre><code>...
2
2016-05-29T15:59:46Z
[ "python", "django" ]
Python pandas: Why does df.iloc[:, :-1].values for my training data select till only the second last column?
37,512,079
<p>Very simply put, for the same training data frame df, when I use X = df.iloc[:, :-1].values, it will select till the second last column of the data frame instead of the last column (which is what I want BUT it's a strange behavior I've never seen before), and I know this as the second last column's value and the la...
0
2016-05-29T16:06:57Z
37,512,144
<p>I think you have only two columns in <code>df</code>, because if there is more columns, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> select all columns without last:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3], '...
1
2016-05-29T16:14:14Z
[ "python", "pandas" ]
Python pandas: Why does df.iloc[:, :-1].values for my training data select till only the second last column?
37,512,079
<p>Very simply put, for the same training data frame df, when I use X = df.iloc[:, :-1].values, it will select till the second last column of the data frame instead of the last column (which is what I want BUT it's a strange behavior I've never seen before), and I know this as the second last column's value and the la...
0
2016-05-29T16:06:57Z
37,512,482
<p>Just for clarity</p> <p><a href="http://stackoverflow.com/a/509295/2336654">With respect to python syntax, this question has been answered here.</a></p> <p>Python list slicing syntax states that for <code>a:b</code> it will get <code>a</code> and everything upto but not including <code>b</code>. <code>a:</code> w...
0
2016-05-29T16:47:55Z
[ "python", "pandas" ]
resize transparent image in opencv python (cv2)
37,512,119
<p>I have an image with shape (120, 470, 4) and I want to resize it to another size e.g. (100, 400, 4). I try to achieve it by using <code>cv2.resize</code> function as bellow</p> <p><code>reshaped_image = cv2.resize(image, (100, 400))</code></p> <p>and paste the reshaped_image inside a bigger transparent image, but ...
1
2016-05-29T16:11:18Z
37,512,380
<p>Here is an example which loads a 3 channel image, takes its blue channel and copies it as alpha channel (which makes no sense at all, but I had no 4 channel image at hand) and merges it again as a 4 channel image. Then this image is resized.</p> <p>If you load a 4 channel image, the flag -1 indicates that the image...
2
2016-05-29T16:38:56Z
[ "python", "image", "opencv", "image-resizing" ]
How can I periodically execute a function with asyncio?
37,512,182
<p>I'm migrating from <code>tornado</code> to <code>asyncio</code>, and I can't find the <code>asyncio</code> equivalent of <code>tornado</code>'s <code>PeriodicCallback</code>. (A <code>PeriodicCallback</code> takes two arguments: the function to run and the number of milliseconds between calls.)</p> <ul> <li>Is ther...
5
2016-05-29T16:17:38Z
37,512,399
<p>There is no built-in support for periodic calls, no.</p> <p>Just create your own scheduler loop that sleeps and executes any tasks scheduled:</p> <pre><code>import math, time async def scheduler(): while True: # sleep until the next whole second now = time.time() await asyncio.sleep(ma...
3
2016-05-29T16:41:05Z
[ "python", "python-3.x", "tornado", "python-3.5", "python-asyncio" ]
How can I periodically execute a function with asyncio?
37,512,182
<p>I'm migrating from <code>tornado</code> to <code>asyncio</code>, and I can't find the <code>asyncio</code> equivalent of <code>tornado</code>'s <code>PeriodicCallback</code>. (A <code>PeriodicCallback</code> takes two arguments: the function to run and the number of milliseconds between calls.)</p> <ul> <li>Is ther...
5
2016-05-29T16:17:38Z
37,512,537
<pre><code>import asyncio @asyncio.coroutine def periodic(): while True: print('periodic') yield from asyncio.sleep(1) def stop(): task.cancel() task = asyncio.Task(periodic()) loop = asyncio.get_event_loop() loop.call_later(5, stop) try: loop.run_until_complete(task) except asyncio.Canc...
5
2016-05-29T16:53:44Z
[ "python", "python-3.x", "tornado", "python-3.5", "python-asyncio" ]
How can I periodically execute a function with asyncio?
37,512,182
<p>I'm migrating from <code>tornado</code> to <code>asyncio</code>, and I can't find the <code>asyncio</code> equivalent of <code>tornado</code>'s <code>PeriodicCallback</code>. (A <code>PeriodicCallback</code> takes two arguments: the function to run and the number of milliseconds between calls.)</p> <ul> <li>Is ther...
5
2016-05-29T16:17:38Z
37,514,633
<p>When you feel that something should happen "in background" of your asyncio program, <code>asyncio.Task</code> might be good way to do it. You can read <a href="http://stackoverflow.com/a/37345564/1113207">this post</a> to see how to work with tasks.</p> <p>Here's possible implementation of class that executes some ...
2
2016-05-29T20:27:12Z
[ "python", "python-3.x", "tornado", "python-3.5", "python-asyncio" ]
ipython autoreload doesn't work
37,512,187
<p>autoreload doesn't work for me in subdirs at all.</p> <p>dir structure:</p> <pre><code>run.ipynb oof.py pertussis/ |-- __init__.py </code></pre> <p>on <strong>run.ipynb</strong> I have (running with notebook):</p> <pre><code>from pertussis import * check() #defined in the module </code></pre> <p>this doesn'...
0
2016-05-29T16:18:20Z
39,716,392
<p>Sorry for the late response, I've just stumbled upon a similar problem.</p> <p>In your <strong>run.ipynb</strong>, have you tried:</p> <pre><code>import pertussis pertussis.check() </code></pre> <p>Or </p> <pre><code>%load_ext autoreload %autoreload 1 </code></pre> <p>then </p> <pre><code>%aimport pertussis c...
1
2016-09-27T05:09:19Z
[ "python", "python-3.x", "ipython", "jupyter-notebook" ]
convert batch file to python script using sys and subprocess
37,512,205
<p>first i use python api from some program,and to can i do that i create .bat file with the paths and calls.</p> <p>but i want to convert this .bat file(with paths and calls) to python script using <code>sys.paths</code> and <code>subprocess</code>.</p> <hr> <p>mybatch.bat </p> <pre><code>set ROOT=C:\path\path c...
0
2016-05-29T16:20:28Z
37,512,268
<p>This is not a good candidate for converting to Python, because you are changing your MS Prompt environment. Changing sys.path will change your Python path within your script, but not the PYTHONPATH environment variable.</p>
0
2016-05-29T16:27:37Z
[ "python", "windows", "batch-file", "subprocess", "sys" ]
Slicing timestamps by month
37,512,271
<p>I have a Series with pandas datestamps as the index, how do I slice the index so that I can get all values from a specific month?</p> <pre><code>d = {'1993-01-01 00:00:00': 10, '1993-02-01 00:00:00': 12} s = pandas.Series(d) s.index = pandas.to_datetime(s.index, utc=True) </code></pre>
2
2016-05-29T16:28:10Z
37,512,298
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.month.html" rel="nofollow"><code>DatetimeIndex.month</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre...
3
2016-05-29T16:30:31Z
[ "python", "pandas" ]
Slicing timestamps by month
37,512,271
<p>I have a Series with pandas datestamps as the index, how do I slice the index so that I can get all values from a specific month?</p> <pre><code>d = {'1993-01-01 00:00:00': 10, '1993-02-01 00:00:00': 12} s = pandas.Series(d) s.index = pandas.to_datetime(s.index, utc=True) </code></pre>
2
2016-05-29T16:28:10Z
37,512,348
<p>If by specific month, you mean February 1993, then its just:</p> <pre><code>s['1993-02'] 1993-02-01 00:00:00+00:00 12 dtype: int64 </code></pre> <p>If you mean all Februarys, then you can't do much better than what jezrael provided.</p>
0
2016-05-29T16:35:40Z
[ "python", "pandas" ]
Can't install python Polyglot package on Windows
37,512,311
<p>I'm trying to install Polyglot package by using the command:</p> <pre><code>pip install polyglot </code></pre> <p>and I receive the following:</p> <pre><code>Collecting polyglot Using cached polyglot-15.10.03-py2.py3-none-any.whl Collecting pycld2&gt;=0.3 (from polyglot) Requirement already satisfied (use --upg...
1
2016-05-29T16:31:43Z
37,512,729
<p>As I suspect that you do not have good experience compiling code on Windows it could be a better for your to try the use of <a href="https://www.continuum.io/downloads" rel="nofollow">Anaconda</a> python distribution which has most of the Python packages already compiled.</p> <p>Once install you just use <code>cond...
0
2016-05-29T17:12:08Z
[ "python", "windows", "python-3.x", "pip", "polyglot" ]
Can't install python Polyglot package on Windows
37,512,311
<p>I'm trying to install Polyglot package by using the command:</p> <pre><code>pip install polyglot </code></pre> <p>and I receive the following:</p> <pre><code>Collecting polyglot Using cached polyglot-15.10.03-py2.py3-none-any.whl Collecting pycld2&gt;=0.3 (from polyglot) Requirement already satisfied (use --upg...
1
2016-05-29T16:31:43Z
37,530,107
<p>If you have now Windows vs2010 compiler, you may try this:</p> <ul> <li>launch "D:\Program Files\WinPython-64bit-3.4.4.2\make_cython_use_vc.bat"</li> <li>then launch "Winpython Command Prompt" and "pip install polyglot"</li> </ul> <p>If it fails, to revert to previous situation:</p> <ul> <li>launch "D:\Program Fi...
0
2016-05-30T16:23:19Z
[ "python", "windows", "python-3.x", "pip", "polyglot" ]
Attribute error when using signal.pthread_sigmask
37,512,359
<p>I keep getting an error every time I try to use signal.pthread_sigmask</p> <p>The error is: AttributeError: 'int' object has no attribute 'pthread_sigmask'</p> <pre><code>def clean_up(): socket.close() context.term() def receive_signal(signal, stack): signal.pthread_sigmask(signal.SIG_BLOC...
-2
2016-05-29T16:37:10Z
37,512,449
<p>By naming the parameter in your <code>receive_signal</code> function <code>signal</code> you are shadowing the module <code>signal</code>, just call it something else, you seem to be using something called <code>signum</code> maybe that is what you ment to use instead?</p> <pre><code>def receive_signal(signum, stac...
2
2016-05-29T16:45:13Z
[ "python" ]
Fastest method for comparing ranges of multidimensional lists
37,512,360
<p><strong>Context:</strong> I am trying to write an A* search in an unknown environment. To do this, I am maintaining a representation of the environment in a 2-D or 3-D list (depending on the environment), and another n-D list that represents the agent's knowledge of the environment.</p> <p>When the agent moves, I c...
1
2016-05-29T16:37:19Z
37,514,052
<p>It should already be a tad faster, when you employ the solution concept from the link given in my comment to the question. </p> <p>I modified / hacked up a bit the given code and tried:</p> <pre><code>#! /usr/bin/env python from __future__ import print_function from itertools import product from random import rand...
1
2016-05-29T19:30:32Z
[ "python", "algorithm", "performance", "search", "optimization" ]
How to convert a Series of arrays into a 2D numpy array
37,512,442
<p>Is there a way to convert a Pandas Series where each row contains an array into a 2D numpy array?</p> <p>The Series looks like the following below when you display it in Python:</p> <pre><code>[array([ 58., -1., -1., -1., -1.]) array([ 77., 95., -1., -1., -1.])] </code></pre> <p>I would like to get a num...
0
2016-05-29T16:44:05Z
37,512,513
<pre><code>l = [pd.Series([np.array([ 77., 95., -1., -1., -1.]),np.array([ 58., -1., -1., -1., -1.])])] </code></pre>
0
2016-05-29T16:51:21Z
[ "python", "numpy", "pandas" ]
How to convert a Series of arrays into a 2D numpy array
37,512,442
<p>Is there a way to convert a Pandas Series where each row contains an array into a 2D numpy array?</p> <p>The Series looks like the following below when you display it in Python:</p> <pre><code>[array([ 58., -1., -1., -1., -1.]) array([ 77., 95., -1., -1., -1.])] </code></pre> <p>I would like to get a num...
0
2016-05-29T16:44:05Z
37,512,532
<p>If:</p> <pre><code>s = pd.Series([np.array([ 58., -1., -1., -1., -1.]), np.array([ 77., 95., -1., -1., -1.])]) </code></pre> <p>Then</p> <pre><code>s.apply(pd.Series).values </code></pre>
1
2016-05-29T16:53:22Z
[ "python", "numpy", "pandas" ]
How to convert a Series of arrays into a 2D numpy array
37,512,442
<p>Is there a way to convert a Pandas Series where each row contains an array into a 2D numpy array?</p> <p>The Series looks like the following below when you display it in Python:</p> <pre><code>[array([ 58., -1., -1., -1., -1.]) array([ 77., 95., -1., -1., -1.])] </code></pre> <p>I would like to get a num...
0
2016-05-29T16:44:05Z
37,512,539
<pre><code>import pandas as pd import numpy as np s = pd.Series([np.array([ 58., -1., -1., -1., -1.]), np.array([ 77., 95., -1., -1., -1.])]) rslt = np.array(s.tolist()) rslt Out[16]: array([[ 58., -1., -1., -1., -1.], [ 77., 95., -1., -1., -1.]]) </code></pre>
1
2016-05-29T16:53:52Z
[ "python", "numpy", "pandas" ]
how to make arrow that loops in matplotlib?
37,512,502
<p>what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried:</p> <pre><code>plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", ...
9
2016-05-29T16:50:23Z
37,512,890
<p>Try this:</p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.set_xlim(1,3) ax.set_ylim(1,3) ax.plot([2.5],[2.5],marker=r'$\circlearrowleft$',ms=100) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/kyNYr.png" rel="nofollow"><img src="http://i.stack.imgur...
3
2016-05-29T17:32:11Z
[ "python", "matplotlib" ]
how to make arrow that loops in matplotlib?
37,512,502
<p>what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried:</p> <pre><code>plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", ...
9
2016-05-29T16:50:23Z
38,208,040
<p>It seems the easiest way to create an easily modifiable looping arrow is to use <a href="http://matplotlib.org/api/patches_api.html" rel="nofollow">patches</a>. I've pasted code to do this below. Change the variables in the variables section and things should all rotate and scale together. You can play around with t...
3
2016-07-05T16:10:09Z
[ "python", "matplotlib" ]
how to make arrow that loops in matplotlib?
37,512,502
<p>what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried:</p> <pre><code>plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", ...
9
2016-05-29T16:50:23Z
38,219,547
<p>My suggestion uses just the plot command</p> <pre><code>import matplotlib.pyplot as plt import numpy as np def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, arrowheadrelativesize=0.3, arrowheadopenangle=30, *args): """ Circular arrow drawing. x0 and y0 are t...
3
2016-07-06T08:34:32Z
[ "python", "matplotlib" ]
how to make arrow that loops in matplotlib?
37,512,502
<p>what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried:</p> <pre><code>plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", ...
9
2016-05-29T16:50:23Z
38,224,201
<p>I find no way to make a loop using <code>plt.annotate</code> only once, but using it four times works :</p> <pre><code>import matplotlib.pyplot as plt fig,ax = plt.subplots() # coordinates of the center of the loop x_center = 0.5 y_center = 0.5 radius = 0.2 # linewidth of the arrow linewidth = 1 ax.annotate("...
7
2016-07-06T12:37:08Z
[ "python", "matplotlib" ]