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
python - split iterable according string and make splits of same length
37,840,406
<p>I have a generator object like the following:</p> <pre><code>a = ["ab", "fasj", "sfk", "sfsfg", "ab", "gwre", "ab", "werwe", "fsfj", "lke"] </code></pre> <p>Using python, how do I split this according the occurrence of "ab" into chunks of the same length?</p> <p>I am looking for something like:</p> <pre><code>b ...
1
2016-06-15T15:58:53Z
37,841,306
<p>Here is my Pythonic way of using <code>numpy.split</code>, and <code>list comprehension</code>:</p> <pre><code>import numpy as np rslt = [list(x) for x in np.split(np.array(a), [i for i, x in enumerate(a) if x=="ab"][1:])] maxlen = max(len(x) for x in rslt) rslt = [x+['']*(maxlen-len(x)) if len(x)&lt;maxlen else x ...
1
2016-06-15T16:48:04Z
[ "python", "split", "generator" ]
Beautifulsoup/Python - Extract Link URL From Div, Dependent on Precluding Content
37,840,433
<p>I'm trying to extract a link in Python 3.4 with BeautifulSoup4, and there are no identifying element markers such as id, class, or etc.. However, before each link, there is a static string of text such as follows:</p> <pre><code>&lt;h2&gt; "Precluding-Text:" &lt;a href="http://the-link-im-after.com"&gt;Varying A...
0
2016-06-15T16:00:19Z
37,840,718
<p>You can use that static text to locate the link:</p> <pre><code>soup.find(text="Precluding-Text:").find_next_sibling("a")["href"] </code></pre> <p>Or, you may need a partial text match:</p> <pre><code>soup.find(text=lambda text: text and "Precluding-Text:" in text).find_next_sibling("a")["href"] </code></pre>
2
2016-06-15T16:16:50Z
[ "python", "regex", "beautifulsoup" ]
Beautifulsoup/Python - Extract Link URL From Div, Dependent on Precluding Content
37,840,433
<p>I'm trying to extract a link in Python 3.4 with BeautifulSoup4, and there are no identifying element markers such as id, class, or etc.. However, before each link, there is a static string of text such as follows:</p> <pre><code>&lt;h2&gt; "Precluding-Text:" &lt;a href="http://the-link-im-after.com"&gt;Varying A...
0
2016-06-15T16:00:19Z
37,841,032
<p>Another solutions using <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">python generators</a>:</p> <pre><code>from bs4 import BeautifulSoup as soup import re html = """ &lt;h2&gt; "Precluding-Text:" &lt;a href="http://the-link-im-after.com"&gt;Varying Anchor Text&lt;/a&gt...
0
2016-06-15T16:34:03Z
[ "python", "regex", "beautifulsoup" ]
PYTHON: how to avoid cyclic dependancy and combine local + global variables
37,840,456
<p>I need to feed <em>local variable</em> from one <code>python</code> file to another, combine the variables there and Then get the other variables back into first file.</p> <p>I looked at SO discussions for <code>cyclic dependency</code> and <code>combining local and global variables</code>, but it does not seem to ...
1
2016-06-15T16:01:12Z
37,840,916
<p>You should <em>define</em> a function in mysettings.py and <em>execute</em> it in other files:</p> <p>#mysettings.py</p> <pre><code>def getsettings(report_name): save_location= os.getcwd()+ "\\" + report_name + "\\" report_file = report_name + "_" + \ str(datetime.datetime.today().strftime('%m_%d_%Y...
3
2016-06-15T16:28:36Z
[ "python", "python-2.7", "variables" ]
PYTHON: how to avoid cyclic dependancy and combine local + global variables
37,840,456
<p>I need to feed <em>local variable</em> from one <code>python</code> file to another, combine the variables there and Then get the other variables back into first file.</p> <p>I looked at SO discussions for <code>cyclic dependency</code> and <code>combining local and global variables</code>, but it does not seem to ...
1
2016-06-15T16:01:12Z
37,841,416
<p>Ok the most strait forward way would be to execute the code in <code>mysettings.py</code> inside the report modules:</p> <pre><code>report_name = "blah" with open("mysettings.py","r") as common_code: exec(f.read(), globals()) #the globals() is actually implied if there is no second argument print(report_file)...
0
2016-06-15T16:55:21Z
[ "python", "python-2.7", "variables" ]
How to package other python scripts which are imported in one main python script in pyinstaller?
37,840,593
<p>So i have one main python script: <strong>Run.py</strong> in Directory: <strong>C:/python/project1</strong></p> <p>I have 8 other python scripts in directory <strong>C:/python/project1/Recov</strong></p> <p>The 8 scripts are imported in the Run.py script.</p> <p>Now when i run <strong>pyinstaller.exe --onefile --...
0
2016-06-15T16:08:28Z
37,841,065
<p>Put all of your script in the same folder. If you are importing them in the main script on which you are using pyinstaller, it will bundle those files.</p> <p>Also open cmd in the directory and run</p> <pre><code>pyinstaller -F -w -i app.ico Run.py </code></pre>
0
2016-06-15T16:35:24Z
[ "python", "python-2.7", "pyinstaller" ]
KMP algorithm with python
37,840,651
<p>I am following clrs book and came across with the kmp algorithm for string matching. I implemented it via python as it is and doesn't work for some reason. where is my fault?? Thanks in advance. The code is given below: </p> <pre><code>def kmp_matcher(t,p): n=len(t) m=len(p) #pi=[0]*n; pi = compute_prefix_function(...
0
2016-06-15T16:12:42Z
37,841,711
<p>Try this:</p> <pre><code>def kmp_matcher(t, d): n=len(t) m=len(d) pi = compute_prefix_function(d) q = 0 i = 0 while i &lt; n: if d[q]==t[i]: q=q+1 i = i + 1 else: if q != 0: q = pi[q-1] else: i =...
1
2016-06-15T17:11:23Z
[ "python", "algorithm" ]
Disassociate Foreign Key on django model for validation during editing
37,840,768
<p>I have the following model:</p> <pre><code>class Event(models.Model): assigned_to= models.ForeignKey(user) (...) # Some other fields </code></pre> <p>I create a Event instance</p> <pre><code>event = Event(assigned_to=someuser, **kwargs) event.save() </code></pre> <p>If I have to use the Model validation...
-3
2016-06-15T16:19:13Z
37,861,609
<p>I managed to generate errors by using <code>null=True</code> on ForeignKey as @Mad Wombat suggested, and by overriding the clean method on the model to check if the assigned_to on the instance is not None</p> <pre><code>def clean(self): if self.assinged_to is None: raise ValidationError({'assigned_to': ...
0
2016-06-16T14:07:09Z
[ "python", "django" ]
Importing between different versions of python
37,840,772
<p>I have a notebook in python 2 and a notebook in python 3. Code written in the notebook 2 is cannot be directly transfered to python 3 due to syntax differences. However, I do not want to import the code, I only want to import the final answer I got after running the code.</p> <pre><code>Notebook_A: Python 2 def fu...
0
2016-06-15T16:19:32Z
37,840,963
<p>You need a data structure to old these informations, and defining protocols for handling this data structure.</p> <p>For example common, well supported, data structures used in a Client/Server architecture are json(suggested)/XML you can also generate a .txt file with the result.</p> <p>Just encode your results in...
0
2016-06-15T16:31:07Z
[ "python", "import", "jupyter-notebook" ]
Dev_appserver.py error when trying to deploy to Google AppEngine
37,840,809
<p>I'm trying to deploy an example dart server using Google AppEngine. However when I run this python script (with the latest python version installed 3.5)</p> <blockquote> <p>dev_appserver.py</p> </blockquote> <p>I've also tried</p> <blockquote> <p>dev_appserver.py --custom_entrypoint "dart bin/server.dart {po...
2
2016-06-15T16:21:33Z
37,863,951
<p>I get the same error when using Python 3.4.3. It works fine with Python 2.7.6. </p>
3
2016-06-16T15:53:39Z
[ "python", "google-app-engine", "dart" ]
Dev_appserver.py error when trying to deploy to Google AppEngine
37,840,809
<p>I'm trying to deploy an example dart server using Google AppEngine. However when I run this python script (with the latest python version installed 3.5)</p> <blockquote> <p>dev_appserver.py</p> </blockquote> <p>I've also tried</p> <blockquote> <p>dev_appserver.py --custom_entrypoint "dart bin/server.dart {po...
2
2016-06-15T16:21:33Z
37,864,869
<p>GAE <a href="https://cloud.google.com/appengine/docs/about-the-standard-environment" rel="nofollow">standard environment</a> only supports Python 2.7 at this time, see <a href="https://cloud.google.com/appengine/docs" rel="nofollow">Google App Engine Documentation</a>.</p> <p>Python 3.4 is supported only in the <a ...
3
2016-06-16T16:39:07Z
[ "python", "google-app-engine", "dart" ]
Pandas: Subtracting two date columns and the result being an integer
37,840,812
<p>I have two columns in a Pandas data frame that are dates. </p> <p>I am looking to subtract one column from another and the result being the difference in numbers of days <strong>as an integer</strong>.</p> <p>A peek at the data:</p> <pre><code>df_test.head(10) Out[20]: First_Date Second Date 0 2016-02-09 2015...
1
2016-06-15T16:21:48Z
37,840,872
<p>You can divide column of <code>dtype</code> <code>timedelta</code> by <code>np.timedelta64(1, 'D')</code>, but output is not <code>int</code>, but <code>float</code>, because <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow"><code>NaN</code> values</a>:</p> <pre><c...
1
2016-06-15T16:25:23Z
[ "python", "datetime", "numpy", "pandas", "int" ]
Pandas: Subtracting two date columns and the result being an integer
37,840,812
<p>I have two columns in a Pandas data frame that are dates. </p> <p>I am looking to subtract one column from another and the result being the difference in numbers of days <strong>as an integer</strong>.</p> <p>A peek at the data:</p> <pre><code>df_test.head(10) Out[20]: First_Date Second Date 0 2016-02-09 2015...
1
2016-06-15T16:21:48Z
37,848,869
<p>You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:</p> <pre><code>import datetime as dt import numpy as np import pandas as pd #Assume we have df_test: In [222]: df_test Out[222]: first_date second_date 0 2016-01-31 2015-11-19 1 2016-02-29 2015-1...
1
2016-06-16T02:24:05Z
[ "python", "datetime", "numpy", "pandas", "int" ]
Columns to Rows in pandas
37,840,821
<p>I am trying to do the following operation in <code>pandas</code>. Any suggestions on <code>pandas</code> way of doing this?</p> <pre><code>In [1]: input = pd.DataFrame({"X_1": [1], "X_2": [2], "X_3": [5], "Y_1": [1.2], "Y_2": [2.3], "Y_3": [3.4]}) In [2]: input Out[2]: X_1 X_2 X_3 Y_1 Y_2 Y_3 0 1 2...
3
2016-06-15T16:22:17Z
37,840,930
<p>Probably not the best answer, but you can do the following:</p> <pre><code>a = {"X_1": [1], "X_2": [2], "X_3": [5], "Y_1": [1.2], "Y_2": [2.3], "Y_3": [3.4]} x = [a[key][0] for key in sorted(a.keys()) if 'X' in key] y = [a[key][0] for key in sorted(a.keys()) if 'Y' in key] df = pd.DataFrame([x, y]).T </code></pre...
1
2016-06-15T16:29:23Z
[ "python", "pandas", "dataframe", "transpose" ]
Columns to Rows in pandas
37,840,821
<p>I am trying to do the following operation in <code>pandas</code>. Any suggestions on <code>pandas</code> way of doing this?</p> <pre><code>In [1]: input = pd.DataFrame({"X_1": [1], "X_2": [2], "X_3": [5], "Y_1": [1.2], "Y_2": [2.3], "Y_3": [3.4]}) In [2]: input Out[2]: X_1 X_2 X_3 Y_1 Y_2 Y_3 0 1 2...
3
2016-06-15T16:22:17Z
37,841,281
<p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> columns by <code>_</code> and create <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.unique.html" rel="nofollow"><code>unique</code></a> values ...
1
2016-06-15T16:47:11Z
[ "python", "pandas", "dataframe", "transpose" ]
Columns to Rows in pandas
37,840,821
<p>I am trying to do the following operation in <code>pandas</code>. Any suggestions on <code>pandas</code> way of doing this?</p> <pre><code>In [1]: input = pd.DataFrame({"X_1": [1], "X_2": [2], "X_3": [5], "Y_1": [1.2], "Y_2": [2.3], "Y_3": [3.4]}) In [2]: input Out[2]: X_1 X_2 X_3 Y_1 Y_2 Y_3 0 1 2...
3
2016-06-15T16:22:17Z
37,841,468
<p>Use <code>str.split</code> and <code>stack</code>.</p> <pre><code>df.columns = df.columns.str.split('_', expand=True) df.stack().loc[0] X Y 1 1 1.2 2 2 2.3 3 5 3.4 </code></pre> <h3>Note: Index is <code>[1, 2, 3]</code> matching original columns.</h3>
4
2016-06-15T16:57:56Z
[ "python", "pandas", "dataframe", "transpose" ]
Columns to Rows in pandas
37,840,821
<p>I am trying to do the following operation in <code>pandas</code>. Any suggestions on <code>pandas</code> way of doing this?</p> <pre><code>In [1]: input = pd.DataFrame({"X_1": [1], "X_2": [2], "X_3": [5], "Y_1": [1.2], "Y_2": [2.3], "Y_3": [3.4]}) In [2]: input Out[2]: X_1 X_2 X_3 Y_1 Y_2 Y_3 0 1 2...
3
2016-06-15T16:22:17Z
37,841,511
<p>For this sort of thing, I prefer a <code>melt</code> followed by a string operation, followed by a <code>pivot</code>:</p> <pre><code>df = pd.melt(input) df[['column', 'index']] = df['variable'].str.split('_', expand=True) df = df.pivot(index='index', columns='column', values='value') print(df) </code></pre> <p>ou...
1
2016-06-15T17:00:09Z
[ "python", "pandas", "dataframe", "transpose" ]
Get JSON representation of Django model
37,840,839
<p>Let's say I have a Django model</p> <pre><code>class Book(models.Model): title = models.CharField() author = models.ForeignKey(Author) is_on_loan = models.BooleanField() </code></pre> <p>How do I get the JSON representation of the <code>Book</code>? I could easily write something like</p> <pre><co...
0
2016-06-15T16:23:32Z
37,840,878
<p>Yes there is a better way, use the built-in <a href="https://docs.djangoproject.com/en/1.9/topics/serialization" rel="nofollow">Django JSON serializer</a></p> <pre><code>from django.core import serializers json_data = serializers.serialize('json', Book.objects.all()) </code></pre>
1
2016-06-15T16:25:42Z
[ "python", "json", "django" ]
Get JSON representation of Django model
37,840,839
<p>Let's say I have a Django model</p> <pre><code>class Book(models.Model): title = models.CharField() author = models.ForeignKey(Author) is_on_loan = models.BooleanField() </code></pre> <p>How do I get the JSON representation of the <code>Book</code>? I could easily write something like</p> <pre><co...
0
2016-06-15T16:23:32Z
37,840,919
<p>This is called serializing. There are django native serializers, you can read about them in the docs (<a href="https://docs.djangoproject.com/en/1.9/topics/serialization/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/serialization/</a>), but the basic usage is</p> <pre> from django.core import serial...
1
2016-06-15T16:28:46Z
[ "python", "json", "django" ]
Python Selenium select only one item in a listbox
37,840,857
<p><code>ListBox</code> (not a drop downlist) as follows:</p> <pre><code>&lt;select name="lstym" onChange="SubmitForm(this.form,'ym')" multiple size="5"&gt; &lt;option value="All" selected&gt;All&lt;/option&gt; &lt;option value="201601"&gt;201601&lt;/option&gt; &lt;option value="201602"&gt;201602&lt;/optio...
0
2016-06-15T16:24:38Z
37,841,165
<p>By default, when you select one element in a listbox, the other elements are deselected. So you should be able to just click the element you want, and it will deselect all the other options.</p>
0
2016-06-15T16:40:48Z
[ "python", "selenium", "listbox", "webdriver", "scrapy" ]
Why 'all' function in Python receives array instead of *args?
37,840,866
<p>the question is about popular Pythonic function all.</p> <pre><code>a = True b = True print(all([a, b])) </code></pre> <p>Why not to use <code>*args</code> ? So it will look like this:</p> <pre><code>a = True b = True print(all(a, b)) </code></pre> <p>List seems redundant here - when we have the ability to pass ...
0
2016-06-15T16:25:10Z
37,840,910
<p>Because <code>all()</code> works with <strong>ANY</strong> iterable, not only lists. E.g:</p> <pre><code>def makeGen(): i = 1 while i &lt;= 10: yield i i = i + 1 all(makeGen()) </code></pre>
0
2016-06-15T16:28:09Z
[ "python" ]
Why 'all' function in Python receives array instead of *args?
37,840,866
<p>the question is about popular Pythonic function all.</p> <pre><code>a = True b = True print(all([a, b])) </code></pre> <p>Why not to use <code>*args</code> ? So it will look like this:</p> <pre><code>a = True b = True print(all(a, b)) </code></pre> <p>List seems redundant here - when we have the ability to pass ...
0
2016-06-15T16:25:10Z
37,840,938
<p><code>all</code> is for when you already have an iterable. If you have two individual booleans, that's <code>and</code>'s job:</p> <pre><code>print(a and b) </code></pre> <p>Making <code>all</code> take <code>*args</code> instead of an iterable would force materialization of the input, even in cases where a <code>...
3
2016-06-15T16:30:01Z
[ "python" ]
CQL TypeError: Received an argument of invalid type for column
37,840,876
<p>I am using <code>Cassandra Python driver</code>, and I created a table, in the table there is a column (called date) defined as <code>timestamp</code>. I tried to access values from a dataframe and insert rows into the table using these values. The dataframe value corresponding to date has the format (captured from ...
0
2016-06-15T16:25:30Z
37,847,792
<p>Try using <code>datetime.datetime(2016,09,29)</code> instead</p>
1
2016-06-16T00:09:36Z
[ "python", "python-3.x", "cassandra", "cql" ]
RDD, PySpark, Why rdd.flatMap seems does not do any operation in CPU?
37,840,885
<p>Show my code</p> <pre><code>In [10]: rdd = sc.mongoPairRDD("mongodb://localhost/stackoverflow.stack") ...... A lot of INFO ...... In [11]: newrdd = rdd.flatMap(f) # No INFO In [12]: newrdd.collect() # A lot of INFO </code></pre> <p>When a function of <code>rdd</code> was call, say <code>flatMap</code>...
0
2016-06-15T16:26:35Z
37,907,394
<p>Yes you are! It is actually the expected behavior for Spark. There are <em>transformations</em> (eg map, flatMap, reduce) and <em>actions</em> (count, collect, saveAsTextFile) that you can apply to an RDD.</p> <p>As you noted, when you call a transformation, no computation happen, it just stacks the operation to th...
1
2016-06-19T12:46:58Z
[ "python", "apache-spark", "pyspark", "rdd" ]
How to get the dragged objects and the destination object from event.mimeData() in dropEvent?
37,841,023
<p>I'm dragging <code>QTableWidgetItem</code>s or <code>QTreeWidgetItem</code>s onto a <code>QTreeWidgetItem</code>. How can I fetch the dragged object(s) I'm dragging and dropping and how can I fetch the destination <code>QTreeWidgetItem</code>?</p> <p>This is what I have (see <code>#COMMENTS</code>):</p> <pre><code...
0
2016-06-15T16:33:25Z
37,841,414
<p>This is how I solved it in the end:</p> <pre><code>def dropEvent(self, event): """On drop, get the target and the dragged item(s)""" print 'drop!' if (event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist')): source_widget = event.source() destination = self.itemAt(event.p...
0
2016-06-15T16:55:11Z
[ "python", "pyqt4", "pyside" ]
py2neo to BOLT: how to convert tx.append statements to BOLT
37,841,039
<p>In Py2neo there is the ability to append transactions and then commit them as one block to the server</p> <pre><code>from py2neo import Graph graph = Graph() tx = graph.cypher.begin() stmt1 = "CREATE (:Person {name: 'Guinevere'})" stmt2 = "CREATE (:Person {name: 'Tom'})" stmt3 = "CREATE (:Person {name: 'Anna'})" tx...
0
2016-06-15T16:34:25Z
38,067,135
<p>well I've tryed as you seeing below and it worked:</p> <p><code>from neo4j.v1 import GraphDatabase</code></p> <p><code>driver = GraphDatabase.driver("bolt://localhost")</code></p> <p><code>session = driver.session()</code></p> <p><code>stmt1 = "CREATE (:Person {name: 'Guinevere'})"</code></p> <p><code>stmt2 = "...
1
2016-06-28T04:34:51Z
[ "python", "neo4j", "py2neo" ]
py2neo to BOLT: how to convert tx.append statements to BOLT
37,841,039
<p>In Py2neo there is the ability to append transactions and then commit them as one block to the server</p> <pre><code>from py2neo import Graph graph = Graph() tx = graph.cypher.begin() stmt1 = "CREATE (:Person {name: 'Guinevere'})" stmt2 = "CREATE (:Person {name: 'Tom'})" stmt3 = "CREATE (:Person {name: 'Anna'})" tx...
0
2016-06-15T16:34:25Z
38,067,765
<p>JRenato's answer was indeed correct. I was confused by the word run and append. I believe they have slightly different meanings.</p> <p>I had also simplified my example. My problem arose from trying to use the same connection for another set of appended statement. It seems that you need to close the session to avoi...
0
2016-06-28T05:31:26Z
[ "python", "neo4j", "py2neo" ]
MatplotLib get all annotation by axes
37,841,048
<p>i'm doing a project with Python and Tkinter. I can plot an array of data and i also implemented a function to add annotation on plot when i click with the mouse, but now i need a list of all annotation that i added. Is there any way to have that? This is my function to add annotation:</p> <pre><code>def onclick(se...
0
2016-06-15T16:34:48Z
37,842,148
<p>You could loop over all the <code>ax</code> children and check if the child is of type <code>matplotlib.text.Annotation</code>:</p> <pre><code>for child in ax.get_children(): if isinstance(child, matplotlib.text.Annotation): print("bingo") # and do something </code></pre> <p>Or, if you want a list:</p>...
0
2016-06-15T17:37:21Z
[ "python", "matplotlib", "tkinter-canvas" ]
Python Input Prompt Go Back
37,841,115
<p>I have a script which has multiple raw_input statements. I would like to add the ability to enter 'undo' and allow the user to go back and re-enter the last raw_input value. How can I accomplish this without a goto type statement?</p> <pre><code>import sys prompt_a = raw_input('Please enter x for x \nPlease ente...
0
2016-06-15T16:38:26Z
37,841,484
<p>looks like you coded in a wrong way, an input raw cannot be your point ... maybe you should create an unique raw input and keep the entry into an array </p> <p>ok....now u post a code example i got it...my suggestion:</p> <pre><code>import sys def do(prompt, step): if 'u' in prompt: step = step-1 ...
-2
2016-06-15T16:58:32Z
[ "python", "python-2.7" ]
Python Input Prompt Go Back
37,841,115
<p>I have a script which has multiple raw_input statements. I would like to add the ability to enter 'undo' and allow the user to go back and re-enter the last raw_input value. How can I accomplish this without a goto type statement?</p> <pre><code>import sys prompt_a = raw_input('Please enter x for x \nPlease ente...
0
2016-06-15T16:38:26Z
37,841,543
<p>The first way that comes to mind is to separate what you do with each input into a function. That way you can build a list of these functions and progress through them one by one. This means that if the user enters the undo input, you can take one step back and go to the previous function.</p> <pre><code>def functi...
2
2016-06-15T17:02:02Z
[ "python", "python-2.7" ]
Python: what happens when code is executed, what's the logic?
37,841,135
<p>I'm a beginner at Python and I really need help understanding how this code works. I need to write down what this program does - what gets printed and how the values of variables change as the program does it's thing. I know functions need to be called and I know how loops work, but what confuses me about this is t...
0
2016-06-15T16:39:35Z
37,841,248
<p>Let's break down the last line only:</p> <pre><code>funk2(a + 1, funk2(a, a)) </code></pre> <p>It'll first evaluate <code>funk2(a, a)</code> which in turn returns a value (let's say it corresponds to <code>x</code>). Then it'll evaluate <code>a+1</code> where <code>a = 5</code>, so <code>6</code>.</p> <p>And then...
1
2016-06-15T16:45:25Z
[ "python", "function" ]
PLY yacc parser lost first term after every newline
37,841,161
<p>I try to write a simple parser by PLY, but the parser below will lose the first string after every NEWLINE. </p> <p>The input is "a b c\nb d e\nc f".</p> <p>My parser parsed first line statement as state (0, ((('a', 'b'), 'c'), 0)), but next token 'b' is lost. The second line statement is state (0, (('d', 'e'), 0)...
0
2016-06-15T16:40:38Z
37,843,743
<p>Your <code>p_error</code> function:</p> <pre><code>def p_error(p): if not p: print("SYNTAX ERROR AT EOF") </code></pre> <p>silently ignores errors except at the end of input. Silently ignoring errors is almost always wrong, and almost always confusing, as it is in this case.</p> <p>Your <code>statemen...
1
2016-06-15T19:01:39Z
[ "python", "parsing", "yacc", "ply" ]
Check input decimal number
37,841,206
<p>I want to check if the input is a number(float with 0,one or two decimals) and greater than 0</p> <pre><code>def getnumber(): print ( "write a number: \n") isValid = False while not isValid: try: number = float(raw_input().replace(",",".")) if number &gt;= 0: ...
-1
2016-06-15T16:43:01Z
37,841,692
<p>The reason why your code isn't working with negative numbers is because the function calls itself recursively when the number is negative, but the value of <code>isValid</code> is always false after that call, so the loop repeats.</p> <p>There isn't really any need for the Boolean variable.</p> <p>That leaves you ...
1
2016-06-15T17:10:01Z
[ "python", "raw-input" ]
Scheduling an asyncio coroutine from another thread
37,841,222
<p>I try to schedule an asyncio coroutine from another thread using <code>create_task()</code>. The problem is that the coroutine is not called, at least not in reasonable amount of time.</p> <p>Is there are way to wake up the event loop or at least specify a shorter timeout?</p> <pre><code>#!/usr/bin/python3 import...
0
2016-06-15T16:44:18Z
37,841,909
<p>Here we go this shuold work. It's a port. Try it out since I have the latest version, I can't really assure you it will work.</p> <pre><code>#!/usr/bin/python3 import concurrent.futures import threading, asyncio from asyncio import coroutines, futures def run_coroutine_threadsafe_my(coro, loop): """Submit a c...
2
2016-06-15T17:22:45Z
[ "python", "multithreading", "python-3.x", "python-asyncio" ]
Scheduling an asyncio coroutine from another thread
37,841,222
<p>I try to schedule an asyncio coroutine from another thread using <code>create_task()</code>. The problem is that the coroutine is not called, at least not in reasonable amount of time.</p> <p>Is there are way to wake up the event loop or at least specify a shorter timeout?</p> <pre><code>#!/usr/bin/python3 import...
0
2016-06-15T16:44:18Z
37,842,263
<p>According to the documentation of <a href="https://docs.python.org/3/library/asyncio-task.html#task" rel="nofollow">Task</a> "this class is not thread safe". So scheduling from another thread is not expected to work.</p> <p>I found two solutions for this based on the answers and comments here.</p> <ol> <li><p>@win...
4
2016-06-15T17:43:05Z
[ "python", "multithreading", "python-3.x", "python-asyncio" ]
optimize the python for loop
37,841,261
<p>I have a problem where I need to find the number of <code>unique numbers</code>. No digits in the number would have been <code>repeated</code>.</p> <p>Number like <code>11, 1123, 41124</code> <code>wont qualify</code>. Numbers should be <code>1234, 12, or 987</code> like these <code>would qualify</code>. My code wo...
0
2016-06-15T16:46:04Z
37,841,407
<p>You are going about this in possibly the least efficient way possible, and the longer the number gets, the longer it will take. Your code should look more like this:</p> <pre><code>for i in xrange(10000000): j = str(i) if len(set(j)) == len(j): count += 1 # print j print count </code></pre> ...
3
2016-06-15T16:54:40Z
[ "python", "for-loop", "optimization" ]
How do I enable a console of Python in Notepad++?
37,841,276
<p>Exactly, I need to execute some functions after programming a script(Like you can do in the IDLE)</p>
0
2016-06-15T16:46:52Z
37,841,503
<p>Choose the <strong>Run</strong> Menu, and the <strong>Run…</strong> command. Enter the path to your Python executable with the script in parameter.</p>
0
2016-06-15T16:59:19Z
[ "python", "notepad++" ]
How do I enable a console of Python in Notepad++?
37,841,276
<p>Exactly, I need to execute some functions after programming a script(Like you can do in the IDLE)</p>
0
2016-06-15T16:46:52Z
37,841,552
<p>Go to <code>Run &gt; Run...</code> in the menu. (Alternatively hit F5). Enter the following as the command to be run:</p> <pre><code>C:\Python26\python.exe "$(FULL_CURRENT_PATH)" </code></pre> <p>Note that depending on your Python version and where it's installed, you may have to change the path to python.exe.</p>...
0
2016-06-15T17:02:32Z
[ "python", "notepad++" ]
Alternate through lambda functions
37,841,315
<p>I have to make a function that takes a list and and maps two lambda functions alternatively. Like this:</p> <pre><code>&gt;&gt;&gt; alternateMap(lambda x: x+1, lambda y: y+10, [1, 2, 3, 4]) [2, 12, 4, 14] </code></pre> <p>So, the first function <code>lambda x: x+1</code> applies to the first element and the third ...
0
2016-06-15T16:48:49Z
37,841,432
<p>This works for any number of functions.</p> <pre><code>&gt;&gt;&gt; from itertools import cycle &gt;&gt;&gt; func_cycle = cycle([lambda x:x+1, lambda y:y+10]) &gt;&gt;&gt; [next(func_cycle)(item) for item in [1, 2, 3, 4]] [2, 12, 4, 14] </code></pre> <p>You stated in comments elsewhere that you need a version that...
3
2016-06-15T16:56:17Z
[ "python", "python-2.7", "dictionary", "lambda" ]
Python scrapy - Login Authenication Issue
37,841,409
<p>I have just started using scrapy. I am facing few problems with login in scrapy. I am trying the scrape items in the website www.instacart.com. But I am facing issues with logging in.</p> <p>The following is the code</p> <pre><code>import scrapy from scrapy.loader import ItemLoader from project.items import Proj...
2
2016-06-15T16:54:48Z
37,845,494
<p>if you look at the post data, you can see the fields for the post:</p> <p><a href="http://i.stack.imgur.com/wxT6S.png" rel="nofollow"><img src="http://i.stack.imgur.com/wxT6S.png" alt="enter image description here"></a></p> <pre><code>headers = {"X-Requested-With":"XMLHttpRequest"} formdata = {'user[email]': 'xxx@...
3
2016-06-15T20:48:52Z
[ "python", "web-scraping", "scrapy", "web-crawler", "scrapy-spider" ]
Looping through Django Templates
37,841,412
<p>I want to change the classes / attributes of the input fields of a ModelForm, but I'd like to do it from the template if possible.</p> <p>Below is my solution for this, using the django <a href="https://github.com/kmike/django-widget-tweaks" rel="nofollow">django-widget-tweaks</a></p> <pre><code>&lt;form action=""...
0
2016-06-15T16:55:01Z
37,841,639
<p>You can take the placeholder and store it inside the field's <a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/#help-text" rel="nofollow"><code>help_text</code> field</a>. With that out of the way, you can easily loop through the fields like so:</p> <pre><code>{% for field in form %} &lt;div class="fo...
2
2016-06-15T17:06:55Z
[ "python", "django", "templates" ]
How to plot DataFrames? in Python
37,841,496
<p>I'm trying to plot a DataFrame, but I'm not getting the results I need. This is an example of what I'm trying to do and what I'm currently getting. (I'm new in Python)</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 1966:{'a':34, 'b':34, '...
2
2016-06-15T16:59:06Z
37,841,705
<pre><code>import pandas as pd import matplotlib.pyplot as plt my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 1966:{'a':34, 'b':34, 'c':35, 'd':76}, 1967:{'a':56, 'b':56, 'c':54, 'd':34}} df = pd.DataFrame(my_data) df.T.plot( kind='bar') # or df.T.plot.bar() plt.show() </code></pre> <p><a href="ht...
1
2016-06-15T17:10:54Z
[ "python", "pandas", "plot", "dataframe" ]
How to plot DataFrames? in Python
37,841,496
<p>I'm trying to plot a DataFrame, but I'm not getting the results I need. This is an example of what I'm trying to do and what I'm currently getting. (I'm new in Python)</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 1966:{'a':34, 'b':34, '...
2
2016-06-15T16:59:06Z
37,842,325
<p>you can do it this way:</p> <pre><code>ax = df.T.plot(linewidth=2.5) plt.locator_params(nbins=len(df.columns)) ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%4d')) </code></pre> <p><a href="http://i.stack.imgur.com/FHap6.png" rel="nofollow"><img src="http://i.stack.imgur.com/FHap6.png" alt="enter image ...
1
2016-06-15T17:46:38Z
[ "python", "pandas", "plot", "dataframe" ]
Float error while attempting to use the bisect optimizer within scipy
37,841,611
<p>I’m having trouble using the bisect optimizer within scipy. Here are the relevant portions of my code:</p> <p>How I’m importing things</p> <pre><code>import numpy as np import scipy.optimize as sp import matplotlib.pyplot as plt </code></pre> <p>Break in code, section causing errors below</p> <pre><code>#All...
0
2016-06-15T17:05:45Z
37,841,863
<p>In Python, concatenation is not implicitly multiplication, and <code>^</code> is not exponentiation. Multiplication must be made explicit with <code>*</code>, and exponentiation must be written as <code>**</code>. This part of <code>BeamHeight</code>:</p> <pre><code>fw*h^3-(fw-wt)(h-2*ft)^3 </code></pre> <p>must b...
3
2016-06-15T17:19:50Z
[ "python", "optimization", "scipy" ]
Find elements of array one nearest to elements of array two
37,841,654
<p><a href="http://stackoverflow.com/a/26026189/230468">This answer</a> explains how to find the nearest (sorted) array element to a <em>single point</em>, in a manner efficient for large arrays (slightly modified):</p> <pre><code>def arg_nearest(array, value): idx = np.searchsorted(array, value, side="left") ...
1
2016-06-15T17:07:46Z
37,842,324
<p>You can make few changes to extend it for an array of elements in <code>value</code>, like so -</p> <pre><code>idx = np.searchsorted(xx, yy, side="left").clip(max=xx.size-1) mask = (idx &gt; 0) &amp; \ ( (idx == len(xx)) | (np.fabs(yy - xx[idx-1]) &lt; np.fabs(yy - xx[idx])) ) out = xx[idx-mask] </code></pr...
1
2016-06-15T17:46:38Z
[ "python", "arrays", "algorithm", "sorting", "numpy" ]
MUSIC Algorithm Spectrum Python Implementation
37,841,704
<p>I am working on a small radar project that can measure the Doppler shift created by the heart and chest. Since I know the number of sources in advance, I decided to choose the MUSIC Algorithm for spectral analysis. I am acquiring data and sending it to Python for analysis. However, my Python code is saying that the ...
0
2016-06-15T17:10:51Z
37,846,108
<p>Mathematically, the problem is that <strong>i</strong> and <strong>f</strong> are both integers. Thus, 2*π*i*f is an integral multiple of 2π. Allowing for a tiny bit of round-off error, this gives you a cosine very close to 1.0 and a sin very close to 0.0. These values yield virtually no variation in <strong>fr...
0
2016-06-15T21:29:29Z
[ "python", "signal-processing", "fft", "linear-algebra", "frequency-analysis" ]
Why doesnt this plugin decode $final?
37,841,747
<p>this is the plugin I am using:</p> <pre><code>add_shortcode( '3', 'execute_python_with_argv3' ); function execute_python_with_argv3() { $description = array ( array("pipe", "r"), // stdin array("pipe", "w"), // stdout ); $application_system = "python "; $application_path .= ...
1
2016-06-15T17:13:23Z
37,842,230
<p>You need to set the environment default encoding to <code>utf-8</code>. One way to do it is:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding("utf-8") line = "čęėččįą" enc = line.encode('utf-8') print (enc) </code></pre>
0
2016-06-15T17:41:37Z
[ "php", "python", "decoding" ]
Issue with "ValueError: Single '}' encountered in format string" in an API Call
37,841,795
<p>I'm using Python 3 for this.</p> <p>Basically, I'm making a API call using urllib and getting the error:</p> <p><em>"ValueError: Single '}' encountered in format string"</em> </p> <p>I have looked at a variety of other solutions but they don't seem to work.</p> <p>Basically what I am doing is:</p> <pre><code>im...
0
2016-06-15T17:16:07Z
37,841,866
<p>You need to double up on your single brace if you want it to remain in the string:</p> <p>For example:</p> <pre><code>'{first}}}'.format(first='John') == 'John}' </code></pre> <p>In your case:</p> <pre><code>person_request = urllib.request.urlopen('http://api.querysite.com/content/search/index:AUTHOR?query=authl...
2
2016-06-15T17:19:57Z
[ "python", "python-3.x", "urllib", "string.format" ]
Faster For Loops Python
37,841,828
<p>so I have been working on a simple python program to iterate through each file name on the computer to check for the file type of an image or well any file type.</p> <pre><code>for i in drives: for root, dirs, files in os.walk(str(i.replace("\\","\\\\"))): #print(root,dirs) for file in files: ...
0
2016-06-15T17:17:59Z
37,841,942
<p>There really isn't any significant improvement you can make due to the limitations of disk I/O (as the comments state). However, instead of using <code>os.walk(...)</code>, you can use <code>os.scandir(...)</code> to get a little more speed out of it. See this link: <a href="https://www.python.org/dev/peps/pep-0471/...
1
2016-06-15T17:25:32Z
[ "python", "python-3.x" ]
Faster For Loops Python
37,841,828
<p>so I have been working on a simple python program to iterate through each file name on the computer to check for the file type of an image or well any file type.</p> <pre><code>for i in drives: for root, dirs, files in os.walk(str(i.replace("\\","\\\\"))): #print(root,dirs) for file in files: ...
0
2016-06-15T17:17:59Z
37,842,085
<p>you can use threads and disparate one thread by driver at you first line...then you will get there faster</p> <pre><code>q = Queue() for i in drives: t = Thread(target=your_method, args=(q,pictures)) t.daemon = True t.start() q.join() </code></pre> <p>hope could helped</p>
0
2016-06-15T17:34:01Z
[ "python", "python-3.x" ]
Faster For Loops Python
37,841,828
<p>so I have been working on a simple python program to iterate through each file name on the computer to check for the file type of an image or well any file type.</p> <pre><code>for i in drives: for root, dirs, files in os.walk(str(i.replace("\\","\\\\"))): #print(root,dirs) for file in files: ...
0
2016-06-15T17:17:59Z
37,843,253
<p>Try using python's Multiprocessing package which may improve the performance of your current code.</p>
0
2016-06-15T18:35:32Z
[ "python", "python-3.x" ]
How to read the output of long running ssh command continuously without blocking using paramiko
37,841,830
<p>I am trying to read the output of a long-running ssh command continuously. I understand that <code>exec_command</code> is non-blocking. But as soon as I use <code>stdout.readlines()</code> it becomes blocking. I don't want to wait for 10 minutes for my ssh command to finish to read all the output lines. I want to ge...
0
2016-06-15T17:17:59Z
37,842,464
<pre><code>import paramiko ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname,username=username,password=password) stdin,stdout,stderr = ssh.exec_command(command) for line in iter(lambda: stdout.readline(2048), ""): print(line) </code></pre> <p>The above code he...
0
2016-06-15T17:53:08Z
[ "python", "ssh", "stdout", "nonblocking", "paramiko" ]
How to split a dataframe column in python. (Data from Qyandl)
37,841,919
<p>I download some data from Quandl. The dataentered as a DataFrame but with a wrong format:</p> <pre><code>In [81]: a Out[81]: RATE DATE 2000-01-01 1.806020 2000-01-02 1.804029 2000-01-03 1.809771 2000-01-04 1.829093 </code></pre> <p>This data frame is float64 and has only one co...
0
2016-06-15T17:23:21Z
37,841,979
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow">reset_index()</a> function:</p> <pre><code>In [128]: df.reset_index() Out[128]: DATE RATE 0 2000-01-01 1.806020 1 2000-01-02 1.804029 2 2000-01-03 1.809771 3 2000-01-04 1.829...
3
2016-06-15T17:28:09Z
[ "python", "regex", "pandas", "dataframe", "split" ]
How to use hist() in python?
37,841,948
<p>I read the data into a DataFrame and called it data. I have the following query in python:</p> <pre><code>new_data=data[data["gender"]=="male"].groupby('age').city.nunique().sort_values(ascending=False) </code></pre> <p>now I want to create its histogram using</p> <p><code>new_data.hist()</code> </p> <p>which wo...
0
2016-06-15T17:25:51Z
37,842,152
<p>You can manually define your bins. Or another common way is to use <code>np.arange()</code>. But in your case I guess you want some non-linear bin range. You can also do the same thing on <code>xticks</code> and <code>yticks</code>.</p> <pre><code>import matlibplot.pyplot as plt bins_range = np.array([20, 25, 36, 4...
0
2016-06-15T17:37:29Z
[ "python", "pandas" ]
Django - Script called from view with call_command connects to Pyro server script but freezes on model access
37,842,044
<h2>Case:</h2> <p>I've got a Django application running, and got an interface with a list of accounts and their state. In the interface I can f.e. choose to start an account by clicking on a button.</p> <p>This calls a view named 'start_session' which will start a script via the call_command function from <a href="ht...
0
2016-06-15T17:30:59Z
37,869,576
<p>You're linking to the Pyro4 library's documentation, but your code is using the ancient and no longer supported Pyro library version 3! Many problems will go away, including hopefully your "freeze" issue, by using the current version of Pyro4 instead (4.45 at the time of writing).</p>
0
2016-06-16T21:24:44Z
[ "python", "django", "pyro" ]
Should I have a NodeJS server for react server-side rendering?
37,842,052
<p>I have a API server which is written in python. And I wanted to render my react components on server side. So I searched the best practices and result was having a nodeJS server.</p> <p>But in my thoughts, this is weird because I have to build a another server with different language. This is bad at maintainable, a...
-1
2016-06-15T17:32:13Z
37,842,334
<p>If it is as simple as wanting to use Python with React, you can use <a href="https://github.com/markfinger/python-react" rel="nofollow">python-react</a> to render React components. </p> <p>As noted above, if you are using Flask, the templating is in Jinja2, but that isn't necessarily mutually exclusive to using Rea...
0
2016-06-15T17:47:04Z
[ "python", "node.js", "reactjs" ]
Showing legend for only one subplot using matplotlib
37,842,064
<p>I'm facing a problem in showing the legend in the correct format using matplotlib. </p> <p>EDIT: I have 4 subplots in a figure in 2 by 2 format and I want legend only on the first subplot which has two lines plotted on it. The legend that I got using the code attached below contained endless entries and extended ve...
0
2016-06-15T17:33:11Z
37,842,410
<p>It is useful to work with the axes directly (<code>ax</code> in your case) when when working with subplots. So if you set up two plots in a figure and only wish to have a legend in your second plot:</p> <pre><code>t = np.linspace(0, 10, 100) plt.figure() ax1 = plt.subplot(2, 1, 1) ax1.plot(t, t * t) ax2 = plt.s...
0
2016-06-15T17:50:24Z
[ "python", "matplotlib" ]
Showing legend for only one subplot using matplotlib
37,842,064
<p>I'm facing a problem in showing the legend in the correct format using matplotlib. </p> <p>EDIT: I have 4 subplots in a figure in 2 by 2 format and I want legend only on the first subplot which has two lines plotted on it. The legend that I got using the code attached below contained endless entries and extended ve...
0
2016-06-15T17:33:11Z
37,842,433
<p>If I understand correctly, you need to tell plt.legend what to put as legends... at this point it is being loaded empty. What you get must be from another source. I have quickly the following, and of course when I run fig.legend as you do I get nothing. </p> <pre><code>import numpy as np import matplotlib.pyplot as...
0
2016-06-15T17:51:52Z
[ "python", "matplotlib" ]
CPython strings larger than 21 chars - memory allocation
37,842,114
<p>I'm wondering what could be the reason of this behaviour (CPython 2.7 and 3.5):</p> <pre><code>&gt;&gt;&gt; a = 's' ; b = 's' &gt;&gt;&gt; id(a), id(b) (4322870976, 4322870976) </code></pre> <p>String shorter than 21 chars seems to share the same memory address (or id). </p> <pre><code>&gt;&gt;&gt; a = 's' * 20 ;...
2
2016-06-15T17:35:50Z
37,842,345
<p>The Python compiler <a href="https://github.com/python/cpython/blob/master/Python/peephole.c#L214" rel="nofollow">converts</a> as many expressions as possible and as makes sense to constants (i.e. it interns them) within bytecode. Constants with the same value will come to have the same <code>id()</code> by this pro...
3
2016-06-15T17:47:27Z
[ "python", "python-3.x", "memory", "cpython" ]
sklearn: calculating accuracy score of k-means on the test data set
37,842,165
<p>I am doing k-means clustering on the set of 30 samples with 2 clusters (I already know there are two classes). I divide my data into training and test set and try to calculate the accuracy score on my test set. But there are two problems: first I don't know if I can actually do this (accuracy score on test set) for ...
0
2016-06-15T17:38:12Z
37,845,595
<p>In terms of evaluating accuracy. You should remember that k-means <strong>is not a classification tool</strong>, thus analyzing accuracy is not a very good idea. You can do this, but this is not what k-means is for. It is supposed to find a grouping of data which maximizes between-clusters distances, it does not use...
2
2016-06-15T20:54:38Z
[ "python", "scikit-learn", "k-means" ]
(Pdb) coming up when executing python script
37,842,174
<p>I have a werid issue with a Python script. I already asked the developer of that script, unfortunately he did not gave any helpful answer besides telling me that it "should work fine".</p> <p>The script is <a href="https://github.com/monitisexchange/Monitis-Linux-Scripts/blob/master/nginx/python/nginx_stubstatus.py...
0
2016-06-15T17:38:35Z
37,842,283
<p>Line 83 of monitisserver.py: <code>import pdb; pdb.set_trace()</code>.</p> <p>This causes python to break into the debugger (pdb) on this line.</p> <hr> <p>Tell the maintainer about this. This should not be in production code without any condition (i.e debug mode)</p>
3
2016-06-15T17:44:13Z
[ "python", "linux" ]
pandas dataframe resample per day without date time index
37,842,260
<p>I have a dataframe in pandas of the following form:</p> <pre><code> timestamps light 7 2004-02-28 00:58:45 150.88 26 2004-02-28 00:59:45 143.52 34 2004-02-28 01:00:45 150.88 42 2004-02-28 01:01:15 150.88 59 2004-02-28 01:02:15 150.88 </code></pre> <p>Here note that the index is not the timestamp...
1
2016-06-15T17:42:59Z
37,842,295
<p>You are right - need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow"><code>DatetimeIndex</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.TimedeltaIndex.html" rel="nofollow"><code>TimedeltaIndex</code></a> or <code>PeriodIndex<...
2
2016-06-15T17:44:49Z
[ "python", "pandas", "dataframe", "time-series" ]
image tiling in loops using Python OpenCV
37,842,476
<p>Python noob needs some help guys! Can someone show me how to rewrite my code using loops? Tried some different syntaxes but did not seem to work!</p> <pre><code>img = cv2.imread("C://Users//user//Desktop//research//images//Underwater_Caustics//set1//set1_color_0001.png") tile11=img[1:640, 1:360] cv2.imwrit...
0
2016-06-15T17:53:39Z
37,843,004
<p>This won't produce the same result like your code, but will give you some ideas:</p> <pre><code>img = cv2.imread('sample.jpg') numrows, numcols = 4, 4 height = int(img.shape[0] / numrows) width = int(img.shape[1] / numcols) for row in range(numrows): for col in range(numcols): y0 = row * height ...
0
2016-06-15T18:21:58Z
[ "python", "image", "loops", "opencv", "tiling" ]
Python, eliminating lines within angle brackets with regex
37,842,552
<p>I'm writing a python script to assign grammatical categories to words in several text files. In each text file, I have file headers within angle brackets &lt;>. Throughout the texts there are also additional lines with information such as time stamps, page numbers, and questions from the transcriber. I want to remov...
0
2016-06-15T17:58:32Z
37,842,728
<p>Strings are <em>immutable</em>, meaning they cannot be modified, only reassigned. The <code>re.sub(...)</code> is working, but it's returning a <em>new</em> string. Try this:</p> <pre><code>text = re.sub(r"&lt;.*&gt;", " ", text) </code></pre> <p>If this still doesn't work, please give us more information about yo...
4
2016-06-15T18:07:49Z
[ "python", "regex" ]
Python, eliminating lines within angle brackets with regex
37,842,552
<p>I'm writing a python script to assign grammatical categories to words in several text files. In each text file, I have file headers within angle brackets &lt;>. Throughout the texts there are also additional lines with information such as time stamps, page numbers, and questions from the transcriber. I want to remov...
0
2016-06-15T17:58:32Z
37,843,965
<p>From what I understand, you may have several <code>&lt;...&gt;</code> on the same line. In this case, you are much safer with a negated character class solution:</p> <pre><code>text = re.sub(r"&lt;[^&gt;]*&gt;", " ", text) </code></pre> <p>The <code>text</code> variable, of course, should be updated as Python stri...
1
2016-06-15T19:15:19Z
[ "python", "regex" ]
Scraping Linkedin with python only returns ''[ ]'
37,842,588
<p>I am trying to scrape LinkedIn to get the current and education elements(This information is publicly available) from any user profile. However, after running this code I cant get the information i need but instead only empty brackets [].</p> <p><a href="https://www.linkedin.com/in/bryan-engelhardt-a099204b" rel="n...
-2
2016-06-15T18:00:37Z
37,842,992
<p>I think you should read linkedin terms of service. </p> <p>The linkedin <a href="https://www.linkedin.com/robots.txt" rel="nofollow">robots.txt file</a> states that you need whitelisting to scrape the site. </p> <pre><code># Notice: If you would like to crawl LinkedIn, # please email whitelistcrawl@linkedin.com to...
1
2016-06-15T18:21:12Z
[ "python", "request", "linkedin", "lxml", "data-extraction" ]
AttributeError: 'file' object has no attribute 'encode'
37,842,640
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Traceback (most recent call last): File "E:\blahblahblah\emailsend.py", line 26, in &lt;module&gt; msg.attach(MIMEText(file)) File "E:...
0
2016-06-15T18:03:07Z
37,842,715
<p>MIMEText takes the <em>content</em> of the file, not the file object.</p> <pre><code>msg.attach(MIMEText(open("newfile.txt").read())) </code></pre>
1
2016-06-15T18:07:15Z
[ "python" ]
How to update the display of Pygame only when there is fresh incoming data from another Python script?
37,842,649
<p>I have a Python script that receives data through Bluetooth at not so regular intervals. Specifically it receives the coordinates of an image through Bluetooth. Using those coordinates I want to update the display of an image in a separate Pygame script. I don't want the Pygame display to close and open again. The P...
0
2016-06-15T18:03:27Z
37,843,015
<pre><code>import pygame from pygame.locals import * def main(): # Initialise screen pygame.init() screen = pygame.display.set_mode((150, 50)) pygame.display.set_caption('Basic Pygame program') # Fill background background = pygame.Surface(screen.get_size()) background = background.convert...
0
2016-06-15T18:23:09Z
[ "python", "pygame" ]
Pandas dataframe and to_numeric: select column by index
37,842,651
<p>The question is probaly extremely dumb, but i hurt my brain figuring out what to do</p> <p>There is a <code>pd.dataframe</code> with N columns. I need to select some columns, referring by index of a column, then convert all values to numeric and rewrite that column in my <code>dataframe</code></p> <p>I've done it ...
1
2016-06-15T18:03:28Z
37,842,911
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting columns and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> <a href="http://pand...
1
2016-06-15T18:17:38Z
[ "python", "pandas", "dataframe", "numeric" ]
Pandas dataframe and to_numeric: select column by index
37,842,651
<p>The question is probaly extremely dumb, but i hurt my brain figuring out what to do</p> <p>There is a <code>pd.dataframe</code> with N columns. I need to select some columns, referring by index of a column, then convert all values to numeric and rewrite that column in my <code>dataframe</code></p> <p>I've done it ...
1
2016-06-15T18:03:28Z
37,868,009
<p>You may want to check the following post out <a href="http://stackoverflow.com/questions/27667759/is-ix-always-better-than-loc-and-iloc-since-it-is-faster-and-supports-i">Is .ix() always better than .loc() and .iloc() since it is faster and supports integer and label access?</a></p> <p>A must [Different choice of I...
0
2016-06-16T19:37:37Z
[ "python", "pandas", "dataframe", "numeric" ]
Highlight every match with Solr 6, Python 3 and pysolr
37,842,662
<p>I have this Solr index that contains a large numer of quite long text files, indexed with the <code>text_sv</code> schema. I want to print out <em>every</em> single snippet for each indexed document. However, I only retrieve a few ones, even though I have tried to smanipulate the various settings as specified in the...
0
2016-06-15T18:04:00Z
37,844,450
<p>You probably want a very large (or 0) value for the <code>hl.fragments</code> parameter (from <a href="http://wiki.apache.org/solr/HighlightingParameters#hl.fragsize" rel="nofollow">the Highlighting wiki page</a>):</p> <blockquote> <p>With the original Highlighter, if you have a use case where you need to highlig...
0
2016-06-15T19:46:26Z
[ "python", "solr", "highlight", "pysolr" ]
Pymssql trouble on python 3.5 (Anaconda Package): Dll Load Failed: The Specific Module could not be found
37,842,664
<p>I am having some issues importing pymssql. I installed it via PIP and I am using python 3.5 (anaconda package) on a win7 machine. I downloaded the appropriate DLL'S recommended here :</p> <p>[<a href="http://www.pymssql.org/en/latest/freetds.html#windows][1]" rel="nofollow">http://www.pymssql.org/en/latest/freetds....
1
2016-06-15T18:04:03Z
37,843,009
<p>I had the same problem, but I resolved it by using:</p> <pre><code>conda install -c prometeia pymssql=2.1.0 </code></pre>
1
2016-06-15T18:22:26Z
[ "python", "sql", "python-3.x", "pymssql" ]
Pymssql trouble on python 3.5 (Anaconda Package): Dll Load Failed: The Specific Module could not be found
37,842,664
<p>I am having some issues importing pymssql. I installed it via PIP and I am using python 3.5 (anaconda package) on a win7 machine. I downloaded the appropriate DLL'S recommended here :</p> <p>[<a href="http://www.pymssql.org/en/latest/freetds.html#windows][1]" rel="nofollow">http://www.pymssql.org/en/latest/freetds....
1
2016-06-15T18:04:03Z
37,847,262
<p>This worked for me: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql" rel="nofollow">pymssql binaries maintained by Christoph Gohlke (UCI) </a> I ended up just uninstalling anaconda (python 3.5), doing a clean install and doing a pip install on the 64bit .whl provided in the link above. Worked like a char...
2
2016-06-15T23:05:21Z
[ "python", "sql", "python-3.x", "pymssql" ]
add filename to RDD rows on wholeTextFiles
37,842,685
<p>I've been googling and trying this for a couple of hours with no luck, hope any of you can provide advice.</p> <p>I'm reading a large number of files into a Spark RDD, and I want to append the filename, which contains a timestamp, into each of the rows of the RDD. So far this is what I got.</p> <pre><code>def appe...
1
2016-06-15T18:04:56Z
37,844,065
<p>Try this:</p> <pre><code>&gt;&gt;&gt; def flatten(pair): ... f, text = pair ... return [line.split(",") + [f] for line in text.splitlines()] ... &gt;&gt;&gt; rdd = sc.wholeTextFiles("README.md").flatMap(flatten) &gt;&gt;&gt; for x in rdd.take(3): ... print(x) ... ['# Apache Spark', 'file:/some-pat...
2
2016-06-15T19:21:32Z
[ "python", "apache-spark", "pyspark" ]
Universalizing my program/Making it accessible to other users
37,842,741
<p>So I am creating a program that takes input, processes the data, then puts it in Excel. In order to do this, I am using the "xlwt" package (and possibly xlrd). How do I then give this program to other people without making them download python and the packages associated with my program? I considered utilizing an on...
0
2016-06-15T18:08:24Z
37,842,951
<p>You would have to compile the code into an exe file. The <code>py2exe</code> library can help you out with this</p>
0
2016-06-15T18:19:18Z
[ "python", "python-3.5" ]
Creating command line alias with python
37,842,862
<p>I want to create command line aliases in one of my python scripts. I've tried os.system(), subprocess.call() (with and without shell=True), and subprocess.Popen() but I had no luck with any of these methods. To give you an idea of what I want to do:</p> <p>On the command line I can create this alias: alias hello="...
1
2016-06-15T18:15:14Z
37,863,471
<p>You can do this, but you have to be careful to get the alias wording correct. I'm assuming you're on a Unix-like system and are using ~/.bashrc, but similar code will be possible with other shells.</p> <pre><code>import os alias = 'alias hello="echo hello world"\n' homefolder = os.path.expanduser('~') bashrc = os....
3
2016-06-16T15:30:09Z
[ "python", "bash", "subprocess", "alias" ]
Creating command line alias with python
37,842,862
<p>I want to create command line aliases in one of my python scripts. I've tried os.system(), subprocess.call() (with and without shell=True), and subprocess.Popen() but I had no luck with any of these methods. To give you an idea of what I want to do:</p> <p>On the command line I can create this alias: alias hello="...
1
2016-06-15T18:15:14Z
37,902,031
<p>Here's a simplified analog of the code from <a href="http://stackoverflow.com/a/37863471/4279">@Jonathan King' answer</a>:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 from pathlib import Path # $ pip install pathlib2 # for Python 2/3 alias_line = 'alias hello="echo hello world"' b...
2
2016-06-18T22:01:45Z
[ "python", "bash", "subprocess", "alias" ]
Lists and lambda expression
37,842,903
<p>First of all, hello, i have a little question. Im trying to learn how to use lambda expression etc... I have this bit of code, it's an example that i need to replicate.</p> <pre><code>&gt;&gt;&gt;something (lambda x:x+1, lambda y:y+10, [1, 2, 3, 4]) [2, 12, 4, 14] </code></pre> <p>I need that output and so far i g...
2
2016-06-15T18:17:15Z
37,843,056
<p>You're using those <code>lambda</code> functions wrongly. Why use multiple lambda functions to process a simple list? You can use just one, with a list comprehension:</p> <pre><code>r = [1, 2, 3, 4] func = lambda x: [v+1 if i%2==0 else v+10 for i,v in enumerate(x)] func(r) # [2, 12, 4, 14] </code></pre> <p>You may...
1
2016-06-15T18:25:21Z
[ "python", "python-2.7", "python-3.x" ]
Lists and lambda expression
37,842,903
<p>First of all, hello, i have a little question. Im trying to learn how to use lambda expression etc... I have this bit of code, it's an example that i need to replicate.</p> <pre><code>&gt;&gt;&gt;something (lambda x:x+1, lambda y:y+10, [1, 2, 3, 4]) [2, 12, 4, 14] </code></pre> <p>I need that output and so far i g...
2
2016-06-15T18:17:15Z
37,843,937
<p>Assuming each of the lambda expressions are used on every second value of the third argument to <code>something</code> you could simply overwrite the list(or alternatively make a new one):</p> <pre><code>def something(f1,f2,lst): for i,li in enumerate(lst): if not i%2: lst[i] = f1(li) ...
0
2016-06-15T19:13:48Z
[ "python", "python-2.7", "python-3.x" ]
Lists and lambda expression
37,842,903
<p>First of all, hello, i have a little question. Im trying to learn how to use lambda expression etc... I have this bit of code, it's an example that i need to replicate.</p> <pre><code>&gt;&gt;&gt;something (lambda x:x+1, lambda y:y+10, [1, 2, 3, 4]) [2, 12, 4, 14] </code></pre> <p>I need that output and so far i g...
2
2016-06-15T18:17:15Z
37,850,235
<p>The other answers will work, but if your question is just one case were you need to cycle several functions to be applied to different elements of a list, and then repeat the functions - then, semantically, a combination of <code>zip</code> and <code>itertools.cycle</code> would be a nice approach:</p> <pre><code>f...
0
2016-06-16T05:02:49Z
[ "python", "python-2.7", "python-3.x" ]
Tensorflow: Confusion regarding the adam optimizer
37,842,913
<p>I'm confused regarding as to how the adam optimizer actually works in tensorflow.</p> <p>The way I read the <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#AdamOptimizer" rel="nofollow">docs</a>, it says that the learning rate is changed every gradient descent iteration. </p> <p>But wh...
1
2016-06-15T18:17:40Z
37,843,152
<p>I find the documentation quite clear, I will paste here the algorithm in pseudo-code:</p> <p><strong>Your parameters</strong>:</p> <ul> <li><code>learning_rate</code>: between 1e-4 and 1e-2 is standard</li> <li><code>beta1</code>: 0.9 by default</li> <li><code>beta2</code>: 0.999 by default</li> <li><code>epsilon<...
3
2016-06-15T18:30:02Z
[ "python", "tensorflow" ]
Why does this condition execute to false when it should execute to true?
37,842,939
<p>I have this code in my spider <code>basic.py</code> file:</p> <pre><code>if l.add_xpath('price', '//*[@id="price"]/text()', MapCompose(lambda i: i.replace(',', ''), float), re = '[,.0-9]'): l.add_value('available', 1) else: l.add_value('price', 0) l.add_value('available', 0) </co...
-1
2016-06-15T18:18:53Z
37,899,266
<p>Just in case someone ran into the same situation:</p> <p>The answer is that <code>add_xpath</code> does not return anything, and in order to check whether there is an element found or not, <code>get_xpath</code> should be used instead (<a href="http://stackoverflow.com/q/37846006/587990">see here</a>).</p>
0
2016-06-18T16:35:47Z
[ "python", "scrapy" ]
Parsing values in a text file
37,842,990
<p>I'm kind of a beginner to all this and am trying to parse an organized text file.</p> <p>The text file resembles the following:</p> <pre><code>blahblahblahblahbblahb blahblahblahblahblahblah Variable: A Variable1: B Variable2: C blah blah blah </code></pre> <p>I'm trying to extract the values after Variable, Vari...
0
2016-06-15T18:21:09Z
37,843,239
<p>You can try:</p> <pre><code>fields=line.split() values = [] for k in range(len(fields)): if fields[k].startswith("Variable"): values.append(fields[k+1]) </code></pre> <p>Then values is what you want.</p>
0
2016-06-15T18:34:41Z
[ "python" ]
Parsing values in a text file
37,842,990
<p>I'm kind of a beginner to all this and am trying to parse an organized text file.</p> <p>The text file resembles the following:</p> <pre><code>blahblahblahblahbblahb blahblahblahblahblahblah Variable: A Variable1: B Variable2: C blah blah blah </code></pre> <p>I'm trying to extract the values after Variable, Vari...
0
2016-06-15T18:21:09Z
37,843,255
<p>If you're trying to save data to a text file then I suggest you check out <a href="http://docs.python-guide.org/en/latest/scenarios/json/" rel="nofollow">JSON</a> files as they are a lot easier to parse. </p>
0
2016-06-15T18:35:34Z
[ "python" ]
Parsing values in a text file
37,842,990
<p>I'm kind of a beginner to all this and am trying to parse an organized text file.</p> <p>The text file resembles the following:</p> <pre><code>blahblahblahblahbblahb blahblahblahblahblahblah Variable: A Variable1: B Variable2: C blah blah blah </code></pre> <p>I'm trying to extract the values after Variable, Vari...
0
2016-06-15T18:21:09Z
37,843,325
<p>You can use the regex module.</p> <pre><code>import re pattern = re.compile(r"(Variable\d*): (\w+)") with open('pathToFile') as f: fileString = f.read() data = pattern.findAll(fileString) </code></pre> <p>this will give you something like this : </p> <pre><code>&gt;&gt;&gt; data [('Variable', 'A'), ('Va...
0
2016-06-15T18:39:48Z
[ "python" ]
Parsing values in a text file
37,842,990
<p>I'm kind of a beginner to all this and am trying to parse an organized text file.</p> <p>The text file resembles the following:</p> <pre><code>blahblahblahblahbblahb blahblahblahblahblahblah Variable: A Variable1: B Variable2: C blah blah blah </code></pre> <p>I'm trying to extract the values after Variable, Vari...
0
2016-06-15T18:21:09Z
37,843,674
<p>Loop through the lines, then try:</p> <pre><code>result = filter(lambda item: line.split(' ').index(item)%2!=0,line.split(' ')) print(result) </code></pre> <p>If your want to do task of filtering, mapping, reducing etc. Please check out lambda function, easy to understand and use. <a href="http://www.u.arizona.edu...
0
2016-06-15T18:57:27Z
[ "python" ]
BeautifulSoup find() not finding anything
37,843,006
<p>Here is an example that replicates the problem I am having:</p> <pre><code>from bs4 import BeautifulSoup import re soup = BeautifulSoup('&lt;root&gt;&lt;td&gt;&lt;label for="pol_nbr"&gt;Policy number&lt;br&gt;&lt;/label&gt;&lt;/td&gt;&lt;/root&gt;', 'html.parser') anchor = soup.find('label', text=re.compile('Polic...
0
2016-06-15T18:22:00Z
37,844,072
<p>The issue is the <code>&lt;br&gt;</code> tag, if you remove it the code works:</p> <pre><code>In [39]: soup = BeautifulSoup('&lt;root&gt;&lt;td&gt;&lt;label for="pol_nbr"&gt;Policy number&lt;/label&gt;&lt;/td&gt;&lt;/root&gt;', 'html.parser') In [40]: soup.find('label', text=re.compile('Policy number')) Out[40]: &...
1
2016-06-15T19:22:05Z
[ "python", "python-2.7", "beautifulsoup" ]
2 questions about python/ My program doesn't start
37,843,007
<p>Hello I'm a beginner at python. So I made my program.</p> <pre><code># -*- coding: utf-8 -*- import os def baslangic(): print "Sonsuza kadar giden sayi programina hos geldin" print "Bana merhaba der misin?" cevap=raw_input("Evet ya da hayır= ") if cevap.lower()==("evet"): print "O zaman ha...
0
2016-06-15T18:22:02Z
37,843,136
<p>These two things need to be at the top of the file.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- </code></pre> <p>Also if you want the output to be slower try putting</p> <pre><code>import time </code></pre> <p>at the top</p> <p>and adding</p> <pre><code>time.sleep(1) </code></pre> <p>to the ...
1
2016-06-15T18:29:18Z
[ "python", "python-2.7", "syntax-error", "ascii", "startup" ]
2 questions about python/ My program doesn't start
37,843,007
<p>Hello I'm a beginner at python. So I made my program.</p> <pre><code># -*- coding: utf-8 -*- import os def baslangic(): print "Sonsuza kadar giden sayi programina hos geldin" print "Bana merhaba der misin?" cevap=raw_input("Evet ya da hayır= ") if cevap.lower()==("evet"): print "O zaman ha...
0
2016-06-15T18:22:02Z
37,843,157
<p>I think you are missing a line at the beginning</p> <p>Try this</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- </code></pre>
0
2016-06-15T18:30:16Z
[ "python", "python-2.7", "syntax-error", "ascii", "startup" ]
2 questions about python/ My program doesn't start
37,843,007
<p>Hello I'm a beginner at python. So I made my program.</p> <pre><code># -*- coding: utf-8 -*- import os def baslangic(): print "Sonsuza kadar giden sayi programina hos geldin" print "Bana merhaba der misin?" cevap=raw_input("Evet ya da hayır= ") if cevap.lower()==("evet"): print "O zaman ha...
0
2016-06-15T18:22:02Z
37,843,323
<p>Although you have just too many abnormalities in ur code you could just help urself by removing the foreign characters in your code like "ç" which is definitely a NON-ASCII character. instead of this:</p> <pre><code>print "O zaman haydi programa geçelim" </code></pre> <p>Use this:</p> <pre><code>print "O zaman ...
0
2016-06-15T18:39:41Z
[ "python", "python-2.7", "syntax-error", "ascii", "startup" ]
Python 3.5.1 - ValueError: invalid literal for int() with base 10
37,843,011
<p>What my program does is<br> - Take a sentence<br> - Make a dictionary and puts it in an external txt file<br> - Make a list of numbers which indicates what words are in what positions<br> - Recreate the original sentence using the numbers and the dictionary and puts it in an external txt file<br> However, I get this...
0
2016-06-15T18:22:41Z
37,843,060
<p>You are passing an empty String to the int() method.</p> <p>It is saying that it doesn't know how to parse an empty string. Echo printing and checking what your program is giving to the method would help you out the most for this.</p> <p>Numbers in this case is an empty string.</p>
0
2016-06-15T18:25:35Z
[ "python", "string", "python-3.x", "dictionary", "int" ]
Python 3.5.1 - ValueError: invalid literal for int() with base 10
37,843,011
<p>What my program does is<br> - Take a sentence<br> - Make a dictionary and puts it in an external txt file<br> - Make a list of numbers which indicates what words are in what positions<br> - Recreate the original sentence using the numbers and the dictionary and puts it in an external txt file<br> However, I get this...
0
2016-06-15T18:22:41Z
37,843,117
<p>It looks like you have an empty string in <code>numberList</code>. The reason is the splitting of the text.</p> <p>See the following example:</p> <pre><code>&gt;&gt;&gt; 'xx yy'.split() ['xx', 'yy'] &gt;&gt;&gt; 'xx yy'.split(' ') ['xx', '', 'yy'] </code></pre> <p>If you use a delimiter you will always get a re...
1
2016-06-15T18:27:58Z
[ "python", "string", "python-3.x", "dictionary", "int" ]
Python 3.5.1 - ValueError: invalid literal for int() with base 10
37,843,011
<p>What my program does is<br> - Take a sentence<br> - Make a dictionary and puts it in an external txt file<br> - Make a list of numbers which indicates what words are in what positions<br> - Recreate the original sentence using the numbers and the dictionary and puts it in an external txt file<br> However, I get this...
0
2016-06-15T18:22:41Z
37,843,199
<p>As designated by your traceback, you are passing in an empty string (''), and trying to make it an integer. You could either test for empty values before</p> <pre><code>newoutput = (wordDictionary[int(numbers)]) + " " </code></pre> <p>Or wrap the statement after it in a try/catch. </p> <p>However, the best soluti...
0
2016-06-15T18:32:37Z
[ "python", "string", "python-3.x", "dictionary", "int" ]
How to force Pandas to read numbers as "int64" instead of "float64"
37,843,053
<p>I have an issue where all of the legacy code I have written no longer works.</p> <p>I have pandas reading an Excel file, and instead of reading as int64, it now reads as float64. It is an issue because I cannot perform .merge or .isin on different data type. I know I can use df.blah.astype(int), but that is very ...
3
2016-06-15T18:25:10Z
37,843,105
<p>I think in problematic column between <code>int</code> values are some <code>NaN</code>. So <code>pandas</code> automatically convert <code>int</code> to <code>float</code>.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">Na type promotions</a>.</p> <p>Yo...
0
2016-06-15T18:27:29Z
[ "python", "pandas", "numbers", "int", null ]
python - comparing series/dataframe with multi-index dataframe
37,843,135
<p>I would like to compare (i.e. > or &lt;) the values in one column of a dataframe, which has a single, non-unique index (<code>df1</code>), to the values of another dataframe (<code>df2</code>) which has a unique, multi-index. The comparison should be such that the values in <code>df1</code> are matched against each ...
0
2016-06-15T18:29:18Z
37,843,774
<h3>Setup</h3> <pre><code>index_a = [1,2,2,3,3,3] index_b = [0,0,1,0,1,2] index = pd.MultiIndex.from_arrays([index_a,index_b], names=('a','b')) np.random.seed(3) df1 = pd.DataFrame(np.random.rand(4,), index = [1,2,3,3], columns=['p']) df2 = pd.DataFrame(np.random.rand(6,), index=index, columns=['p']) </code></pre> <p...
0
2016-06-15T19:03:33Z
[ "python", "loops", "numpy", "pandas" ]
Pandas SQLalchemy: complex filter on database columns
37,843,161
<p>I am new to both SQLalchemy and pandas. I am writing a python code to query a mysql database. </p> <p>I am fetching data from the database and keeping my data in a pandas dataframe. I could make simple operations on pandas dataframe columns like </p> <p>Example1: get the rows where all columns have some values <co...
0
2016-06-15T18:30:40Z
37,844,416
<p>With pandas, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow">boolean indexing</a> to filter your dataframe. For example, you can do things like</p> <pre><code>filtered = df[(df['Column 1'] == 'some value') or (df['Column 2'] == 'some value') and (df['Column 3'] &gt; 15...
0
2016-06-15T19:43:53Z
[ "python", "mysql", "pandas", "sqlalchemy" ]
Please look Info on for statement in django
37,843,182
<p>I'm having some trouble joining or correctly formatting my template... I'm new and have taught myself alot so far, but I'm having trouble with queries and for statements. </p> <p>What I have so far is:</p> <p>Output </p> <pre><code>June 13, 2016 June 14, 2016 Item Amount Amount Cars 10800.00 Tires 156400...
0
2016-06-15T18:31:23Z
37,847,113
<p>There are three solutions:</p> <p>1) Manipulate the <strong>front-end</strong>, by making the second "<em>Amount</em>" column as another <strong>separate table</strong> outside the original table and then making the <em>display</em> property of both the tables as "<strong>inline-block</strong>". Hence aligning them...
0
2016-06-15T22:50:57Z
[ "python", "html", "django", "for-loop" ]
Python update last line of file (stdout)
37,843,210
<p>In Python program, I am redirecting <code>stdout</code> using below:</p> <pre><code>sys.stdout = open("log_file.txt", "a",0) </code></pre> <p>On certain condition I want rewrite the last line of the file.</p> <p>I have tried below:</p> <pre><code>if (status=='SAME'): print '\r'+'Above status doesnot change and...
0
2016-06-15T18:33:20Z
37,843,842
<p>I think the only way you're going to be able to do it is if you read the whole file and print each line, except the last line, back into the log. Not terribly efficient but it should work. </p>
-1
2016-06-15T19:07:20Z
[ "python", "file" ]
Python update last line of file (stdout)
37,843,210
<p>In Python program, I am redirecting <code>stdout</code> using below:</p> <pre><code>sys.stdout = open("log_file.txt", "a",0) </code></pre> <p>On certain condition I want rewrite the last line of the file.</p> <p>I have tried below:</p> <pre><code>if (status=='SAME'): print '\r'+'Above status doesnot change and...
0
2016-06-15T18:33:20Z
37,843,945
<p>Without actually running a test case, I'd try:</p> <ul> <li><code>open</code> the file in <code>append</code> mode</li> <li>read lines, noting the file position at the start of each line</li> <li>after reading the last line, use <code>seek</code> to move back to the start of that line</li> <li><code>write</code> th...
1
2016-06-15T19:14:06Z
[ "python", "file" ]
Python update last line of file (stdout)
37,843,210
<p>In Python program, I am redirecting <code>stdout</code> using below:</p> <pre><code>sys.stdout = open("log_file.txt", "a",0) </code></pre> <p>On certain condition I want rewrite the last line of the file.</p> <p>I have tried below:</p> <pre><code>if (status=='SAME'): print '\r'+'Above status doesnot change and...
0
2016-06-15T18:33:20Z
37,845,270
<p>You can use separate class like this:</p> <pre><code>class OverwiteLogger(object): def __init__(self): self.filename = "filename.txt" def write(self, message): f = open(self.filename, "r") lines = f.readlines() lines[-1] = message open(self.filename, 'w').writelines(...
0
2016-06-15T20:34:48Z
[ "python", "file" ]