title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to drop columns which have same values in all rows via pandas or spark dataframe? | 39,658,574 | <p>Suppose I've data similar to following:</p>
<pre><code> index id name value value2 value3 data1 val5
0 345 name1 1 99 23 3 66
1 12 name2 1 99 23 2 66
5 2 name6 1 99 23 7 66
</code></pre>
<p>How can we drop all those colu... | 2 | 2016-09-23T10:30:25Z | 39,658,853 | <p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from column which are not compared and then compare first row selected by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.... | 2 | 2016-09-23T10:45:33Z | [
"python",
"pandas",
"duplicates",
"multiple-columns",
"spark-dataframe"
] |
How can I search for specific part of strings in a list and list them? Python 2.7 | 39,658,589 | <p>With some help I'm hoping to build a list of strings from a bunch of text files whereby the date stamp of the filename is older than three days and the output list only contains part of the strings i.e. filename = 2016_08_18_23_10_00 - playlist, string in file is E:\media\filename.mxf or D:\media2\filename.mxf. I wi... | 0 | 2016-09-23T10:30:53Z | 39,667,274 | <p>If I understood you correctly, you want to put all the files of type "mxf" that are older than three days into an array. You are doing things more complicated then you have to. Simply check if the filename matches the pattern you have defined and add those files to an array (e.g matchingfiles):</p>
<pre><code>## im... | 0 | 2016-09-23T18:22:46Z | [
"python",
"arrays",
"list"
] |
Caching in python using *args and lambda functions | 39,658,710 | <p>I recently attempted Googles <a href="http://www.ibtimes.co.uk/google-foobar-how-searching-web-earned-software-graduate-job-google-1517284" rel="nofollow"> foo.bar challenge</a>. After my time was up I decided to try find a solution to the problem I couldn't do and found a solution <a href="https://github.com/rtheun... | 0 | 2016-09-23T10:37:35Z | 39,659,174 | <p>The notation <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow"><code>*args</code></a> stands for a variable number of positional arguments. For example, <code>print</code> can be used as <code>print(1)</code>, <code>print(1, 2)</code>, <code>print(1, 2, 3)</code> a... | 2 | 2016-09-23T11:02:20Z | [
"python",
"caching",
"lambda"
] |
Plot dynamically changing graph using matplotlib in Jupyter Notebook | 39,658,717 | <p>I have a M x N 2D array: ith row represents that value of N points at time i. </p>
<p>I want to visualize the points [1 row of the array] in the form of a graph where the values get updated after a small interval. Thus the graph shows 1 row at a time, then update the values to next row, so on and so forth. </p>
<p... | 3 | 2016-09-23T10:37:51Z | 39,793,063 | <p>I don't know much about matplotlib or jupyter. However, Graphs interest me. I just did some googling and came across this <a href="http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/" rel="nofollow">post</a>. Seems like you have to render the graph as an HTML video to see a dyna... | -1 | 2016-09-30T13:47:06Z | [
"python",
"matplotlib",
"plot",
"graph",
"jupyter-notebook"
] |
Plot dynamically changing graph using matplotlib in Jupyter Notebook | 39,658,717 | <p>I have a M x N 2D array: ith row represents that value of N points at time i. </p>
<p>I want to visualize the points [1 row of the array] in the form of a graph where the values get updated after a small interval. Thus the graph shows 1 row at a time, then update the values to next row, so on and so forth. </p>
<p... | 3 | 2016-09-23T10:37:51Z | 39,809,509 | <p>In addition to @0aslam0 I used code from <a href="http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/" rel="nofollow">here</a>. I've just changed animate function to get next row every next time. It draws animated evolution (M steps) of all N points.</p>
<pre><code>from IPython.display import... | 0 | 2016-10-01T17:24:54Z | [
"python",
"matplotlib",
"plot",
"graph",
"jupyter-notebook"
] |
Plot dynamically changing graph using matplotlib in Jupyter Notebook | 39,658,717 | <p>I have a M x N 2D array: ith row represents that value of N points at time i. </p>
<p>I want to visualize the points [1 row of the array] in the form of a graph where the values get updated after a small interval. Thus the graph shows 1 row at a time, then update the values to next row, so on and so forth. </p>
<p... | 3 | 2016-09-23T10:37:51Z | 39,853,938 | <p>Here's an alternative, possibly simpler solution:</p>
<pre><code>%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
m = 100
n = 100
matrix = np.random.normal(0,1,m*n).reshape(m,n)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
fig.show()
fig.canvas.draw()
for i in range(0,100):
... | 1 | 2016-10-04T13:43:17Z | [
"python",
"matplotlib",
"plot",
"graph",
"jupyter-notebook"
] |
Plot dynamically changing graph using matplotlib in Jupyter Notebook | 39,658,717 | <p>I have a M x N 2D array: ith row represents that value of N points at time i. </p>
<p>I want to visualize the points [1 row of the array] in the form of a graph where the values get updated after a small interval. Thus the graph shows 1 row at a time, then update the values to next row, so on and so forth. </p>
<p... | 3 | 2016-09-23T10:37:51Z | 39,857,366 | <p>Here is a library that deals with real-time plotting/logging data (<a href="https://pypi.python.org/pypi/joystick/" rel="nofollow">joystick</a>), although I am not sure it is working with jupyter. You can install it using the usual <code>pip install joystick</code>.</p>
<p>Hard to make a working solution without mo... | 0 | 2016-10-04T16:24:21Z | [
"python",
"matplotlib",
"plot",
"graph",
"jupyter-notebook"
] |
Conflict between PyQt5 and datetime.datetime.strptime | 39,658,719 | <p>So I was writing a tool that would read time from file using graphical user interface based on python 3.52 and Qt5. The minimal operation</p>
<pre><code>datetime.datetime.strptime('Tue', '%a')
</code></pre>
<p>works in an isolated environment, giving output "1900-01-01 00:00:00". However, when I run the following ... | 2 | 2016-09-23T10:37:56Z | 39,660,949 | <p>I can reproduce your problem: after calling the QtWidget, the </p>
<p><code>print(datetime.datetime.strptime('Tue', '%a'))</code></p>
<p>results in an error.</p>
<p>If I execute after QtWidget</p>
<p><code>print(datetime.datetime.strptime('Die', '%a'))</code>
this works.</p>
<p>I am located in Switzerland, so <... | 1 | 2016-09-23T12:37:11Z | [
"python",
"datetime",
"pyqt5"
] |
Conflict between PyQt5 and datetime.datetime.strptime | 39,658,719 | <p>So I was writing a tool that would read time from file using graphical user interface based on python 3.52 and Qt5. The minimal operation</p>
<pre><code>datetime.datetime.strptime('Tue', '%a')
</code></pre>
<p>works in an isolated environment, giving output "1900-01-01 00:00:00". However, when I run the following ... | 2 | 2016-09-23T10:37:56Z | 39,661,572 | <p>To elaborate on the nice answer by Patrick, I have now found a way to undo the localization enforced by QT</p>
<pre><code>import sys
import datetime as datetime
import locale
from PyQt5 import QtWidgets
## Start the QT window
print(datetime.datetime.strptime('Tue', '%a'))
app = QtWidgets.QApplication(sys.argv)
lo... | 0 | 2016-09-23T13:06:58Z | [
"python",
"datetime",
"pyqt5"
] |
Ending infinite loop for a bot | 39,658,736 | <p>I have created a chat bot for <strong>Twitch IRC</strong>, I can connect and create commands etc etc, however I cannot use keyboard-interrupt in the command prompt. I suspect it is because it's stuck in this infinite loop, and I don't know how to fix this? I am new to programming btw!</p>
<p>Here is the code I have... | 0 | 2016-09-23T10:38:41Z | 39,659,091 | <p>Part of code that you posted doesn't have much to do with problem you described.</p>
<p>This is a guess (although an educated one). In you socket connection you are probably using <code>try: except:</code> and using <code>Pokemon</code> approach (gotta catch 'em all)</p>
<p>Thing here would be to find a line where... | 0 | 2016-09-23T10:57:57Z | [
"python",
"loops",
"infinite"
] |
Parsing JSON feed with Ruby for use in Dashing Dashboard | 39,658,759 | <p>First post here, so ya know, be nice?</p>
<p>I'm setting up a dashboard in Dashing (<a href="http://dashing.io/" rel="nofollow"><a href="http://dashing.io/" rel="nofollow">http://dashing.io/</a></a>) using a JSON feed on a server, which looks like:</p>
<pre><code>{
"error":0,
"message_of_the_day":"Welcome!... | 3 | 2016-09-23T10:39:43Z | 39,659,297 | <p>In python code you are sending a JSON and adding a header. I bet it makes sense to do that in ruby as well. The code below is untested, since I canât test it, but it should lead you into the right direction:</p>
<pre><code>#!/usr/bin/ruby
require 'httparty'
require 'json'
response = HTTParty.post(
"http://192.... | 1 | 2016-09-23T11:09:22Z | [
"python",
"json",
"ruby",
"dashing"
] |
python bad operand type for unary -: 'NoneType' | 39,659,023 | <p>I send you a question because I have a problem on python and I don't understand why.
I created a function "mut1" to change the number inside a list (with a probability to 1/2) either in adding 1 or subtracting 1, except for 0 and 9:</p>
<pre><code>def mut1 (m):
i=np.random.randint(1,3)
j=np.random.randint(1... | 0 | 2016-09-23T10:54:04Z | 39,660,497 | <p>That happens because you have to make your <code>mut1</code> return an <code>numpy.int64</code> type of result. So I tried with the following modified code of yours and worked.</p>
<pre><code>>>> import numpy as np
>>> import random
>>>
>>> def mut1 (m):
... i=np.random.randi... | 1 | 2016-09-23T12:12:27Z | [
"python",
"nonetype"
] |
packet-sniffer can't sniff SIP(voip) packet | 39,659,096 | <p>I want to build "SIP sniffer" for my project to alert incoming call from VoIP communication.I try to call from my smartphone to my notebook and check incoming packet by wireshark. I see all SIP-message ( INVITE , BYE , TRYING ). I know basic of SIP ,it use UDP port 5060.</p>
<p>Next, I use this code from <a href="h... | 0 | 2016-09-23T10:58:01Z | 39,659,276 | <p>From the quick look , I see that your packets are UDP.
But the python code only sniffs for TCP.</p>
<p><code>#create an INET, raw socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)</code> </p>
<p>change socket.IPPROTO_TCP to socket.IPPROTO_UDP</p>
| 1 | 2016-09-23T11:08:27Z | [
"python",
"linux",
"sockets",
"udp",
"packet-sniffers"
] |
packet-sniffer can't sniff SIP(voip) packet | 39,659,096 | <p>I want to build "SIP sniffer" for my project to alert incoming call from VoIP communication.I try to call from my smartphone to my notebook and check incoming packet by wireshark. I see all SIP-message ( INVITE , BYE , TRYING ). I know basic of SIP ,it use UDP port 5060.</p>
<p>Next, I use this code from <a href="h... | 0 | 2016-09-23T10:58:01Z | 39,660,157 | <pre><code>#UDP packets
elif protocol == 17 :
u = iph_length + eth_length
udph_length = 8
udp_header = packet[u:u+8]
#now unpack them :)
udph = unpack('!HHHH' , udp_header)
source_port = udph[0]
dest_port = udph[1]
length = udph[2]
checksum =... | 1 | 2016-09-23T11:54:35Z | [
"python",
"linux",
"sockets",
"udp",
"packet-sniffers"
] |
Pandas DataFrame with date and time from JSON format | 39,659,146 | <p>I'm importing data from <code>.json</code> file with pandas <code>DataFrame</code> and the result is a bit broken: </p>
<pre><code> >> print df
summary response_date
8.0 {u'$date': u'2009-02-19T10:54:00.000+0000'}
11... | 1 | 2016-09-23T11:00:59Z | 39,659,312 | <p>You can use <code>DataFrame</code> constructor with converting column <code>response_date</code> to <code>list</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> if <code>type</code> is <code>dict</code>:</p>
<pre><code>print (t... | 2 | 2016-09-23T11:10:05Z | [
"python",
"json",
"pandas",
"dictionary",
"dataframe"
] |
I am trying to upgrading pip from 8.1.1 to 8.1.2 . but it showing following 'PermissionError: [WinError 5] Access is denied:.how to upgrade pip? | 39,659,180 | <blockquote>
<p>C:>python -m pip install --upgrade pip
Collecting pip
Using cached pip-8.1.2-py2.py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 8.1.1
Uninstalling pip-8.1.1:
Exception:
Traceback (most recent call last):
File "C:\Program Files\Python35\li... | 0 | 2016-09-23T11:02:35Z | 39,659,240 | <p>open your cmd with admin priviliges. for that right click in icon and select open with administrator.</p>
| 0 | 2016-09-23T11:06:08Z | [
"python",
"django",
"pip",
"pycharm",
"python-3.5.2"
] |
I am trying to upgrading pip from 8.1.1 to 8.1.2 . but it showing following 'PermissionError: [WinError 5] Access is denied:.how to upgrade pip? | 39,659,180 | <blockquote>
<p>C:>python -m pip install --upgrade pip
Collecting pip
Using cached pip-8.1.2-py2.py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 8.1.1
Uninstalling pip-8.1.1:
Exception:
Traceback (most recent call last):
File "C:\Program Files\Python35\li... | 0 | 2016-09-23T11:02:35Z | 39,659,449 | <p>Upgrade PIP on your default python environment required <code>sudo</code>, i.e. in Windows term, you must your start command prompt as administrator mode. In fact, this is not recommended.</p>
<p>You don't need to use <code>sudo</code>/'Windows adminsitrators" if you setup virtualenv. It is python best practice to ... | 0 | 2016-09-23T11:16:46Z | [
"python",
"django",
"pip",
"pycharm",
"python-3.5.2"
] |
How to parse XML by using python | 39,659,219 | <p>I want to parse this url to get the text of \Roman\ </p>
<p><a href="http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=dj0zaiZpPU5TV0Zwcm1vaFpIcCZzPWNvbnN1bWVyc2VjcmV0Jng9YTk-&grade=1&sentence=%E7%A7%81%E3%81%AF%E5%AD%A6%E7%94%9F%E3%81%A7%E3%81%99" rel="nofollow">http://jlp.yahooapis.jp/FuriganaServ... | 0 | 2016-09-23T11:04:54Z | 39,659,623 | <p>I recently ran into a similar issue to this. It was because I was using an older version of the xml.etree package and to workaround that issue I had to create a loop for each level of the XML structure. For example:</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = 'http://jlp.yahooapis.jp/Furi... | 0 | 2016-09-23T11:25:47Z | [
"python",
"xml",
"parsing"
] |
How to parse XML by using python | 39,659,219 | <p>I want to parse this url to get the text of \Roman\ </p>
<p><a href="http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=dj0zaiZpPU5TV0Zwcm1vaFpIcCZzPWNvbnN1bWVyc2VjcmV0Jng9YTk-&grade=1&sentence=%E7%A7%81%E3%81%AF%E5%AD%A6%E7%94%9F%E3%81%A7%E3%81%99" rel="nofollow">http://jlp.yahooapis.jp/FuriganaServ... | 0 | 2016-09-23T11:04:54Z | 39,660,296 | <p>Try <code>tree.findall('.//{urn:yahoo:jp:jlp:FuriganaService}Word')</code> . It seems you need to specify the namespace too .</p>
| 0 | 2016-09-23T12:01:02Z | [
"python",
"xml",
"parsing"
] |
Send PDF file path to client to download after covnersion in WeasyPrint | 39,659,311 | <p>In my Django app, I'm using WeasyPrint to convert html report to pdf. I need to send the converted file back to client so they can download it. But I don't see any code on WeasyPrint site where we can get the path of saved file or know in any way where the file was saved. </p>
<p>If I hard code the path, like, <cod... | -1 | 2016-09-23T11:09:56Z | 39,659,750 | <p>You didn't even bothered to post the relevant code, but anyway:</p>
<p>If you're using the Python API, you either specify the output file path when calling <code>weasyprint.HTML().write_pdf()</code> or get the PDF back as bytestring, <a href="http://weasyprint.readthedocs.io/en/latest/api.html#weasyprint.HTML.write... | 0 | 2016-09-23T11:32:27Z | [
"python",
"django",
"weasyprint"
] |
How to append several data frame into one | 39,659,316 | <p>I have write down a code to append several dummy DataFrame into one. After appending, the expected "DataFrame.shape" would be (9x3). But my code producing something unexpected output (6x3). How can i rectify the error of my code. </p>
<pre><code>import pandas as pd
a = [[1,2,4],[1,3,4],[2,3,4]]
b = [[1,1,1],[1,6,... | 1 | 2016-09-23T11:10:15Z | 39,659,404 | <p>Firstly use <code>concat</code> to concatenate a bunch of dfs it's quicker:</p>
<pre><code>In [308]:
df = pd.concat([df1,df2,df3], ignore_index=True)
df
Out[308]:
a b c
0 1 2 4
1 1 3 4
2 2 3 4
3 1 1 1
4 1 6 4
5 2 9 4
6 1 3 4
7 1 1 4
8 2 0 4
</code></pre>
<p>secondly you're reusing ... | 1 | 2016-09-23T11:14:34Z | [
"python",
"pandas"
] |
Binding outputs of transformers in FeatureUnion | 39,659,370 | <p>New to python and sklearn so apologies in advance. I have two transformers and I would like to gather the results in a `FeatureUnion (for a final modelling step at the end). This should be quite simple but FeatureUnion is stacking the outputs rather than providing an nx2 array or DataFrame. In the example below I wi... | 1 | 2016-09-23T11:12:40Z | 39,693,444 | <p>The transformers in the <code>FeatureUnion</code> need to return 2-dimensional matrices, however in your code by selecting a column, you are returning a 1-dimensional vector. You could fix this by selecting the column with <code>X[[self.col_name]]</code>.</p>
| 1 | 2016-09-26T01:17:26Z | [
"python",
"scikit-learn",
"pipeline"
] |
Building a python interface for a *.so | 39,659,419 | <p>I want to make use of a <code>C</code> library, from which a shared object and the header files are available. </p>
<p>As the documentation of <code>ctypes</code> and <code>Cython</code> are very scarce and tutorials about those were for different usage, I need some help. </p>
<p>So, I don't know where to start he... | 1 | 2016-09-23T11:15:07Z | 39,697,803 | <p>I finally managed to import the library with <code>ctypes</code>. <code>Cython</code> didn't work out for me, and seemed to complex with the different files needed. </p>
<p>After getting an error like: <code>undefined symbol: inflate</code>, the accessing really worked out with importing the needed pcap lib from th... | 0 | 2016-09-26T08:16:33Z | [
"python",
"shared-libraries",
"cython",
"ctypes"
] |
Animated text funtion only working for certain strings | 39,659,470 | <p>I am attempting to make a function that displays animated text in Python</p>
<pre><code>import sys
def anitext(str):
for char in str:
sys.stdout.write(char)
time.sleep(textspeed)
print ("")
</code></pre>
<p>This function is working for strings such as</p>
<pre><code>anitext ("Strin... | 1 | 2016-09-23T11:17:42Z | 39,659,641 | <p>You just need to use argument unpacking. See <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow">Arbitrary Argument Lists</a> in the official Python tutorial.</p>
<pre><code>import sys
import time
textspeed = 0.2
def anitext(*args):
for s in args:
for ... | 1 | 2016-09-23T11:26:51Z | [
"python",
"function",
"variables"
] |
How to get key and value in well format and n/a values at the end in pandas | 39,659,512 | <p>Sort the data in ascending order and the keys which are not present need to be printed in the last.</p>
<p>Please suggest a solution and also suggest if any modifications is required.</p>
<p><strong>Input.txt-</strong></p>
<pre><code>3=1388|4=1388|5=M|8=157.75|9=88929|1021=1500|854=n|388=157.75|394=157.75|474=157... | 0 | 2016-09-23T11:19:31Z | 39,660,297 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for creating <code>Series</code>, which is splited by <code>=</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofol... | 0 | 2016-09-23T12:01:06Z | [
"python",
"pandas"
] |
Caesar Cipher Code Python printing on separate lines | 39,659,538 | <p>The code below works fine, however the message prints onto separate lines once it has been encrypted. For example if I type: abc with the shift of 1 it encrypts it but prints it back as:</p>
<pre><code>b
c
d
</code></pre>
<p>And I don't understand why. I want it to print as:</p>
<pre><code> bcd
</code></pre>
<p... | -2 | 2016-09-23T11:21:19Z | 39,659,613 | <p>Indentation matters and you shouldn't create new list of <code>NewMessage</code> everytime </p>
<pre><code>print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(inpu... | 1 | 2016-09-23T11:25:03Z | [
"python",
"encryption",
"caesar-cipher"
] |
Caesar Cipher Code Python printing on separate lines | 39,659,538 | <p>The code below works fine, however the message prints onto separate lines once it has been encrypted. For example if I type: abc with the shift of 1 it encrypts it but prints it back as:</p>
<pre><code>b
c
d
</code></pre>
<p>And I don't understand why. I want it to print as:</p>
<pre><code> bcd
</code></pre>
<p... | -2 | 2016-09-23T11:21:19Z | 39,659,682 | <p>you should change the following part;</p>
<pre><code>print("".join(NewMessageList), end="")
</code></pre>
| 0 | 2016-09-23T11:28:41Z | [
"python",
"encryption",
"caesar-cipher"
] |
Caesar Cipher Code Python printing on separate lines | 39,659,538 | <p>The code below works fine, however the message prints onto separate lines once it has been encrypted. For example if I type: abc with the shift of 1 it encrypts it but prints it back as:</p>
<pre><code>b
c
d
</code></pre>
<p>And I don't understand why. I want it to print as:</p>
<pre><code> bcd
</code></pre>
<p... | -2 | 2016-09-23T11:21:19Z | 39,659,688 | <p>What happening was is that for each charachter it was running the loop and printing the answer, now I have collected all the encrypted letter and clubbed them as one in the end and printed it.</p>
<p>it at first initialize an empty list with <code>NewMessage = []</code> and then for every letter that we get encrypt... | 0 | 2016-09-23T11:29:02Z | [
"python",
"encryption",
"caesar-cipher"
] |
How can I convert a dict_keys list to integers | 39,659,619 | <p>I am trying to find a way of converting a list within dict_keys() to an integer so I can use it as a trigger to send to another system. My code (below) imports a list of 100 words (a txt file with words each on a new line) which belong to 10 categories (e.g. the first 10 words belong to category 1, second 10 words b... | -1 | 2016-09-23T11:25:42Z | 39,659,644 | <p>Just convert your keys to integers using a list comprehension; note that there is no need to call <code>.keys()</code> here as iteration over the dictionary directly suffices:</p>
<pre><code>[int(k) for k in categories]
</code></pre>
<p>You may want to bucket your values directly into integer categories rather tha... | 4 | 2016-09-23T11:27:02Z | [
"python",
"dictionary",
"defaultdict"
] |
force eclipse to use Python 3.5 autocompletion | 39,659,748 | <p>I changed the interpreter for my python projects from 2.x to 3.5 recently. The code interpretes correctly with the 3.5 version.</p>
<p>I noticed that the autocompletion function of Eclipse still autocompletes as if I am using 2.x Python version. For example: <code>print</code> gets autocompleted without parenthesis... | 0 | 2016-09-23T11:32:25Z | 39,773,761 | <p>If you are using PyDev, make sure that interpreter grammar is set to 3.0 (<code>right click project -> Properties -> PyDev - Interpreter/Grammar</code>) </p>
| 1 | 2016-09-29T15:00:15Z | [
"python",
"eclipse",
"python-3.x",
"autocomplete"
] |
Using regex to match a specific pattern in Python | 39,659,865 | <p>I am trying to create <strong>regex</strong> that matches the following pattern:</p>
<p><em>Note</em> : <strong><code>x</code> is a number e.g. 2</strong></p>
<p><strong><em>Pattern:</em></strong></p>
<pre><code>u'id': u'x' # x = Any Number e.g: u'id': u'2'
</code></pre>
<p>So far I have tried the... | 1 | 2016-09-23T11:38:12Z | 39,659,923 | <p>This regex will match your patterns:</p>
<p><code>u'id': u'(\d+)'</code></p>
<p>The important bits of the regex here are:</p>
<ul>
<li>the brackets <code>()</code> which makes a capture group (so you can get the information</li>
<li>the digit marker <code>\d</code> which specifies any digit 0 - 9</li>
<li>the mul... | 2 | 2016-09-23T11:41:29Z | [
"python",
"regex",
"python-2.7",
"nsregularexpression"
] |
Using regex to match a specific pattern in Python | 39,659,865 | <p>I am trying to create <strong>regex</strong> that matches the following pattern:</p>
<p><em>Note</em> : <strong><code>x</code> is a number e.g. 2</strong></p>
<p><strong><em>Pattern:</em></strong></p>
<pre><code>u'id': u'x' # x = Any Number e.g: u'id': u'2'
</code></pre>
<p>So far I have tried the... | 1 | 2016-09-23T11:38:12Z | 39,659,924 | <p>You have misplaced single quotes and you should use <code>\d+</code> instead of just <code>\d</code>:</p>
<pre><code>>>> s = "u'id': u'2'"
>>> re.findall(r"u'id'\s*:\s*u'\d+'", s)
["u'id': u'2'"]
</code></pre>
| 2 | 2016-09-23T11:41:37Z | [
"python",
"regex",
"python-2.7",
"nsregularexpression"
] |
Using regex to match a specific pattern in Python | 39,659,865 | <p>I am trying to create <strong>regex</strong> that matches the following pattern:</p>
<p><em>Note</em> : <strong><code>x</code> is a number e.g. 2</strong></p>
<p><strong><em>Pattern:</em></strong></p>
<pre><code>u'id': u'x' # x = Any Number e.g: u'id': u'2'
</code></pre>
<p>So far I have tried the... | 1 | 2016-09-23T11:38:12Z | 39,660,024 | <p>Try this:</p>
<p>str1 = "u'id': u'x'"</p>
<p>re.findall(r'u\'id\': u\'\d+\'',str1)</p>
<p>You need to escape single-quote(') because it's a special character</p>
| 1 | 2016-09-23T11:47:53Z | [
"python",
"regex",
"python-2.7",
"nsregularexpression"
] |
Python, scipy.optimize.curve_fit do not fit to a linear equation where the slope is known | 39,659,900 | <p>I think I have a relatively simple problem but I have been trying now for a few hours without luck. I am trying to fit a linear function (linearf) or power-law function (plaw) where I already known the slope of these functions (b, I have to keep it constant in this study). The results should give an intercept around... | 1 | 2016-09-23T11:40:07Z | 39,662,134 | <p>I just discover an error in the functions:</p>
<p>It should be : </p>
<pre><code>def plaw(x,a):
b=-0.1677 # known slope
y = a*(x**b)
return y
</code></pre>
<p>and not</p>
<pre><code>def plaw(a,x):
b=-0.1677 # known slope
y = a*(x**b)
return y
</code></pre>
<p>Stupid mistake.</p>
| 0 | 2016-09-23T13:33:05Z | [
"python",
"python-2.7"
] |
Using pyplot to create grids of plots | 39,659,998 | <p>I am new to python and having some difficulties with plotting using <code>pyplot</code>. My goal is to plot a grid of plots in-line (<code>%pylab inline</code>) in Juypter Notebook.</p>
<p>I programmed a function <code>plot_CV</code> which plots cross-validation erorr over the degree of polynomial of some x where a... | 0 | 2016-09-23T11:46:26Z | 39,660,225 | <p>A first suggestion to you problem would be taking a look at the "<a href="http://matplotlib.org/users/tight_layout_guide.html" rel="nofollow">Tight Layout guide</a>" for matplotlib. </p>
<p>They have an example that looks visually very similar to your situation. As well they have examples and suggestions for taking... | 2 | 2016-09-23T11:57:25Z | [
"python",
"matplotlib",
"plot"
] |
How do I return a JsonResponse if the post data is bad in tastypie? | 39,660,005 | <p>For example, client post a card number in data and I use it to fetch the card record from database. If it does not exist, I return a JsonResponse such as:</p>
<p><code>
return JsonResponse({
success:False,
msg:'The card does not exsit! Please check the card number.'
})
</code></p>
<p>If the card does e... | 0 | 2016-09-23T11:46:54Z | 39,677,892 | <p>Assuming you're returning django's <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#jsonresponse-objects" rel="nofollow">JsonResponse</a>, you can simply return it with appropriate <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpResponse.status_code" rel="no... | 0 | 2016-09-24T15:14:13Z | [
"python",
"django",
"tastypie"
] |
How to test faster GUI applications? | 39,660,019 | <p>I'd like to know to test faster my GUI applications. </p>
<p>For the backend I got a good set of unit-tests, so I think that's quite ok and I can iterate quite fast. </p>
<p>But to test the frontend logic I find myself running over and over repeating the same sequence of events to test certain part of the logic...... | 1 | 2016-09-23T11:47:25Z | 39,665,686 | <p>If you're just trying to validate that certain GUI actions do the correct thing, you can use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qtest.html" rel="nofollow"><code>QTest</code></a> to simulate button clicks and other GUI interaction.</p>
<p>Ideally, most of your business logic is in non-GUI modules to mak... | 1 | 2016-09-23T16:39:37Z | [
"python",
"qt",
"user-interface",
"pyqt",
"gui-testing"
] |
How to test faster GUI applications? | 39,660,019 | <p>I'd like to know to test faster my GUI applications. </p>
<p>For the backend I got a good set of unit-tests, so I think that's quite ok and I can iterate quite fast. </p>
<p>But to test the frontend logic I find myself running over and over repeating the same sequence of events to test certain part of the logic...... | 1 | 2016-09-23T11:47:25Z | 39,668,071 | <p>There are also UI blackbox testing tools such as <a href="https://wiki.ubuntu.com/Touch/Testing/Autopilot" rel="nofollow">AutoPilot</a> and <a href="https://www.froglogic.com/squish/gui-testing/" rel="nofollow">Squish</a> which allow you to record your interactions with the application and later on replay them again... | 1 | 2016-09-23T19:17:07Z | [
"python",
"qt",
"user-interface",
"pyqt",
"gui-testing"
] |
Cannot implement recursion with Python Scrapy | 39,660,025 | <p>Please pardon my knowledge in Scrapy, I have been doing Data Scraping for past 3 years or so using PHP and Python BeautifulSoup, but I am new to Scrapy.</p>
<p>I have Python 2.7 and latest Scrapy.</p>
<p>I have a requirement where I need to scrape <a href="http://www.dos.ny.gov/corps/bus_entity_search.html" rel="n... | 0 | 2016-09-23T11:47:55Z | 39,661,780 | <p>Well, without having had a deeper look at <code>scrapy</code>, I had to have a look at the recursion thing.</p>
<p>First, you may want to simplify your keyword generation.</p>
<pre><code>import itertools
import random
URL = 'https://appext20.dos.ny.gov/corp_public/CORPSEARCH.SELECT_ENTITY'
ALPHABET = [chr(i) for ... | 1 | 2016-09-23T13:17:14Z | [
"python",
"recursion",
"web-scraping",
"scrapy"
] |
Looping multiple values into dictionary | 39,660,069 | <p>I would like to expand on a previously asked question:</p>
<p><a href="http://stackoverflow.com/questions/39578130/nested-for-loop-with-unequal-entities">Nested For Loop with Unequal Entities</a></p>
<p>In that question, I requested a method to extract the location's type (Hospital, Urgent Care, etc) in addition t... | -1 | 2016-09-23T11:50:26Z | 39,660,117 | <p>Let's say you have a dict <code>my_dict</code> and you want to add <code>2</code> with <code>my_key</code> as key. Simply do:</p>
<pre><code>my_dict['my_key'] = 2
</code></pre>
| 1 | 2016-09-23T11:52:38Z | [
"python",
"loops",
"dictionary",
"beautifulsoup",
"nested-loops"
] |
Looping multiple values into dictionary | 39,660,069 | <p>I would like to expand on a previously asked question:</p>
<p><a href="http://stackoverflow.com/questions/39578130/nested-for-loop-with-unequal-entities">Nested For Loop with Unequal Entities</a></p>
<p>In that question, I requested a method to extract the location's type (Hospital, Urgent Care, etc) in addition t... | -1 | 2016-09-23T11:50:26Z | 39,660,295 | <p>Let say you have a dict <code>d = {'Name': 'Zara', 'Age': 7}</code> now you want to add another value </p>
<blockquote>
<p>'Sex'= 'female'</p>
</blockquote>
<p>You can use built in update method.</p>
<pre><code>d.update({'Sex': 'female' })
print "Value : %s" % d
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'fema... | 0 | 2016-09-23T12:01:01Z | [
"python",
"loops",
"dictionary",
"beautifulsoup",
"nested-loops"
] |
Doubts with Keras RNN formats and layers | 39,660,160 | <p>Ok, I know this has been asked before but I'm afraid I have not fully grasped the comments/solutions, so let me write here my own problem:</p>
<p>It's a very basic problem. I have an array <code>X_train</code> of shape <code>(35584,)</code> that represents measures each hour for several years. I also have the corre... | 0 | 2016-09-23T11:54:42Z | 40,059,477 | <p>Ok, I'm going to self answer this question in case it can be useful for someone. How to do a regression with a RNN in Keras it is very well explained here. The blog, besides, has a lot of resources for machine learning and the explanations are superb. Strongly recommended. Link with the explanations of formats, laye... | 0 | 2016-10-15T13:16:37Z | [
"python",
"neural-network",
"keras",
"recurrent-neural-network"
] |
designing the predicate for the filter function | 39,660,329 | <p>I have this in built filter function for my homework.</p>
<pre><code>def filter(pred, seq):
if seq == ():
return ()
elif pred(seq[0]):
return (seq[0],) filter(pred, seq[1:])
else:
return filter(pred, seq[1:])
</code></pre>
<p>We are supposed to convert a give function to one tha... | 1 | 2016-09-23T12:02:58Z | 39,661,203 | <pre><code>get_road_name(bus_stops) == road
</code></pre>
<p>is a boolean value, not a function. What you want to do is create a function that calls <code>get_road_name</code> and checks if the result is equal to <code>road</code></p>
<pre><code>filter(lambda x: get_road_name(x) == road, stops)
</code></pre>
<p>Fo... | 1 | 2016-09-23T12:49:03Z | [
"python",
"recursion",
"filter",
"higher-order-functions"
] |
Django: Setting the from address on an email | 39,660,409 | <p>I'd like for my users to be able to enter their <code>email-address</code> and <code>message</code> and then send the email with the 'from address' being their own email-address. Currently the <code>EMAIL_HOST</code> is set on our own domain and the emails arrives when it is sent with a "from address" equal to our <... | 0 | 2016-09-23T12:07:19Z | 39,661,013 | <p>If you allow your users to set the from addresss, you may find that your emails are blocked by anti-spam measures.</p>
<p>A better approach would be to use an email address you control as the from address, and set the <code>reply_to</code> header on your email. Then, when the recipients click 'reply', the reply wil... | 1 | 2016-09-23T12:40:04Z | [
"python",
"django",
"smtp"
] |
Python Pandas .Apply Function to Vectorized Form | 39,660,466 | <p>I'm trying to convert the following .apply transformation to a vectorized form which will run faster. I've tried .where, and I've tried normal boolean indexing, however my solutions are not working. Please send me in the right direction</p>
<pre><code>oneDayDelta = datetime.timedelta(days=1)
def correct_gps_datet... | 1 | 2016-09-23T12:10:22Z | 39,660,517 | <p>I think you need add <code>()</code> only to conditions:</p>
<pre><code>(allData['Created'].hour == 0) & (allData['GPS_DateTime'].hour > 10)
</code></pre>
<hr>
<pre><code>allData['GPS_DateTime'] = allData.where((allData['Created'].hour == 0) &
(allData['GPS_Date... | 2 | 2016-09-23T12:13:27Z | [
"python",
"pandas"
] |
Python Pandas .Apply Function to Vectorized Form | 39,660,466 | <p>I'm trying to convert the following .apply transformation to a vectorized form which will run faster. I've tried .where, and I've tried normal boolean indexing, however my solutions are not working. Please send me in the right direction</p>
<pre><code>oneDayDelta = datetime.timedelta(days=1)
def correct_gps_datet... | 1 | 2016-09-23T12:10:22Z | 39,660,525 | <p>You can do this in a single line using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a>:</p>
<pre><code>allData['GPS_DateTime'] = np.where((allData['Created'].dt.hour == 0) & (allData['GPS_DateTime'].dt.hour > 10), allData['GPS_DateTime'... | 2 | 2016-09-23T12:13:54Z | [
"python",
"pandas"
] |
numpy polyfit yields nonsense | 39,660,663 | <p>I am trying to fit these values: <a href="http://i.stack.imgur.com/KpLUj.png" rel="nofollow"><img src="http://i.stack.imgur.com/KpLUj.png" alt="Values to fit"></a></p>
<p>This is my code:</p>
<pre><code> for i in range(-area,area):
stDev1= []
for j in range(-area,area):
stDev0 = stDev[i+i0][j+j0]... | 0 | 2016-09-23T12:21:42Z | 39,667,945 | <p>I do not completely understand your program. In the future, it would be helpful if you were to distill your issue to a <a href="http://stackoverflow.com/help/mcve">MCVE</a>. But here are some thoughts:</p>
<ol>
<li><p>It seems, in your data, that for a given value of <em>x</em> there are multiple values of <em>y</e... | 1 | 2016-09-23T19:08:30Z | [
"python",
"numpy",
"data-fitting"
] |
Deciding if a Point is Inside a Polygon python | 39,660,851 | <p>I am trying to detect if a given point(x,y) is in a polygon of n*2 array. But it seems that some points on the borders of the polygon return that it's not include.</p>
<pre><code>def point_inside_polygon(x,y,poly):
n = len(poly)
inside =False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y ... | 1 | 2016-09-23T12:31:52Z | 39,663,561 | <p>You may use <code>contains_point</code> function from <code>matplotlib.path</code> with small negative and positive radius (small trick). Something like this:</p>
<pre><code>import matplotlib.path as mplPath
import numpy as np
crd = np.array([[0,0], [0,1], [1,1], [1,0]])# poly
bbPath = mplPath.Path(crd)
pnts = [[0... | 0 | 2016-09-23T14:42:24Z | [
"python",
"polygon",
"polygons",
"point-in-polygon"
] |
What method is equivalent to_internal_value in DRF 2? | 39,660,927 | <p>I can not find this in the documentation. </p>
<p>I remember that I used such a method in DRF 2 but can not recall the name.</p>
| 0 | 2016-09-23T12:35:53Z | 39,694,640 | <p>This was <code>from_native</code> as described in the <a href="http://www.django-rest-framework.org/topics/3.0-announcement/#changes-to-the-custom-field-api" rel="nofollow">release notes</a></p>
| 0 | 2016-09-26T04:14:28Z | [
"python",
"django",
"django-rest-framework"
] |
Error when using importlib.util to check for library | 39,660,934 | <p>I'm trying to use the importlib library to verify whether the nmap library is installed on the computer executing the script in Python 3.5.2</p>
<p>I'm trying to use <code>importlib.util.find_spec("nmap")</code> but receive the following error.</p>
<pre><code>>>> import importlib
>>> importlib.ut... | 2 | 2016-09-23T12:36:21Z | 39,661,116 | <p>Try this:</p>
<pre><code>from importlib import util
util.find_spec("nmap")
</code></pre>
<p>I intend to investigate, but honestly I don't know why one works and the other doesn't. Also, observe the following interactive session:</p>
<pre><code>>>> import importlib
>>> importlib.util
Traceback (m... | 3 | 2016-09-23T12:44:59Z | [
"python",
"python-3.x",
"python-importlib"
] |
Extracting ICCID from a string using regex | 39,660,961 | <p>I'm trying to return and print the ICCID of a SIM card in a device; the SIM cards are from various suppliers and therefore of differing lengths (either 19 or 20 digits). As a result, I'm looking for a regular expression that will extract the ICCID (in a way that's agnostic to non-word characters immediately surround... | 1 | 2016-09-23T12:37:42Z | 39,661,185 | <p>I'd go for</p>
<pre><code>89\d{17,18}[^\d]
</code></pre>
<p>This should prefer 18 digits, but 17 would also suffice. After that, no more other numeric characters would be allowed.</p>
<p>Only limitation: there must be at least one more character after the ICCID (which should be okay from what you described).</p>
... | 1 | 2016-09-23T12:48:14Z | [
"python",
"regex",
"string",
"iccid"
] |
Extracting ICCID from a string using regex | 39,660,961 | <p>I'm trying to return and print the ICCID of a SIM card in a device; the SIM cards are from various suppliers and therefore of differing lengths (either 19 or 20 digits). As a result, I'm looking for a regular expression that will extract the ICCID (in a way that's agnostic to non-word characters immediately surround... | 1 | 2016-09-23T12:37:42Z | 39,661,484 | <p>If the engine behind the scenes is really Python, and there can be any non-digits chars around the value you need to extract, use lookarounds to restrict the context around the values:</p>
<pre><code>(?<!\d)89\d{17,18}(?!\d)
^^^^^^^ ^^^^^^
</code></pre>
<p>The <code>(?<!\d)</code> loobehind will requ... | 1 | 2016-09-23T13:02:55Z | [
"python",
"regex",
"string",
"iccid"
] |
Extracting ICCID from a string using regex | 39,660,961 | <p>I'm trying to return and print the ICCID of a SIM card in a device; the SIM cards are from various suppliers and therefore of differing lengths (either 19 or 20 digits). As a result, I'm looking for a regular expression that will extract the ICCID (in a way that's agnostic to non-word characters immediately surround... | 1 | 2016-09-23T12:37:42Z | 39,661,691 | <pre><code>(\d+)\D+
</code></pre>
<p>seems like it would do the trick readily. (\d+ ) would capture 20 numbers. \D+ would match anything else afterwards. </p>
| 0 | 2016-09-23T13:12:44Z | [
"python",
"regex",
"string",
"iccid"
] |
How can I speed up nearest neighbor search with python? | 39,660,968 | <p>I have a code, which calculates the nearest voxel (which is unassigned) to a voxel ( which is assigned). That is i have an array of voxels, few voxels already have a scalar (1,2,3,4....etc) values assigned, and few voxels are empty (lets say a value of '0'). This code below finds the nearest assigned voxel to an una... | 3 | 2016-09-23T12:38:06Z | 39,680,380 | <p>It would be interesting to try <a href="http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html" rel="nofollow">sklearn.neighbors.NearestNeighbors</a>, which offers <code>n_jobs</code> parameter:</p>
<blockquote>
<p>The number of <strong>parallel jobs</strong> to run for neighbors... | 2 | 2016-09-24T19:54:47Z | [
"python",
"performance",
"parallel-processing",
"nearest-neighbor",
"kdtree"
] |
Spyder logging output only in file not IPython Console | 39,661,084 | <p>I'm having a problem with logging in Spyder.</p>
<p>My code has some important output like a progressbar and some logging.
I don't want the logging to be in the IPython console output, just in the log file.</p>
<p>There is a logging.conf file because i need the TimedRotatingFileHandler and a formatter.</p>
<p>The... | 0 | 2016-09-23T12:43:32Z | 39,787,835 | <p>There seems to be a problem with the timedRotatingHandler.
It works fine with the FileHandler.
Just rename the logfile with the datetime and os packages. This may not be the best solution but at least it is working.</p>
| 0 | 2016-09-30T09:11:08Z | [
"python",
"logging",
"console",
"spyder"
] |
Optimal way to add small lists to Pandas DataFrame | 39,661,198 | <p>I'm parsing some logs that contain HTTP transactions into a Pandas DataFrame. Each row is one trasaction, so one column has the IP address, the other has the hostname, etc. For each row (log entry) I'd like to extract the header parameters into a list, and store that list with the rest of the info for that row.</p>... | 1 | 2016-09-23T12:48:54Z | 39,661,899 | <p>The values in the columns of a Pandas DataFrame are stored in homogeneous numpy arrays. Consider the following:</p>
<pre><code>In [95]: pd.DataFrame({'a': ['foo', 'bar/baz']}).a.dtype
Out[95]: dtype('O')
In [96]: pd.DataFrame({'a': [['foo'], ['bar', 'baz']]}).a.dtype
Out[96]: dtype('O')
</code></pre>
<p>This show... | 2 | 2016-09-23T13:22:45Z | [
"python",
"pandas"
] |
Python 2.7 BeautifulSoup , email scraping | 39,661,367 | <p>Hope you are all well. I'm new in Python and using python 2.7.</p>
<p>I'm trying to extract only the mailto from this public website business directory: <a href="http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search" rel="nofollow">http://www.tecomdirectory.com/com... | 0 | 2016-09-23T12:56:35Z | 39,662,163 | <p>You cannot just find every anchor, you need to specifically look for "mailto:" in the href, you can use a css selector <code>a[href^=mailto:]</code> which finds <em>anchor</em> tags that have a <em>href</em> starting with <code>mailto:</code>:</p>
<pre><code>import requests
soup = BeautifulSoup(requests.get("htt... | 1 | 2016-09-23T13:34:31Z | [
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
Trying to loop over colums in DataFrame and strip Dollar Sign | 39,661,428 | <p>My DataFrame has way too many columns to manully type in all of the columns separately. Therefore I am trying to loop through them quickly and get rid of the dollar signs and the commas in the large numbers. This is the code that I have so far: </p>
<pre><code>for column in df1:
df1[column] = df1[column].str.ls... | 1 | 2016-09-23T12:59:16Z | 39,661,467 | <p>You can filter just the str columns using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow"><code>select_dtypes</code></a>:</p>
<pre><code>for col in df.select_dtypes([np.object]):
df[col] = df[col].str.lstrip('$')
</code></pre>
<p>Example:</p>
... | 3 | 2016-09-23T13:01:43Z | [
"python",
"pandas",
"dataframe"
] |
Get the corresponding XML nodes with xpath | 39,661,533 | <p>I have a XML file (actually is a xliff file) where a node has 2 children nodes with identical substructure (which is not known a priori, can be very complex and changes for each <code><trans-unit></code>). I'm working with python and lxml library... Example:</p>
<pre><code><trans-unit id="tu4" xml:space="p... | 1 | 2016-09-23T13:05:13Z | 39,661,906 | <p>if you want to pair them all you could just zip the nodes together so you can access the matching codes from each:</p>
<pre><code>from lxml import etree
tree = etree.fromstring(x)
nodes = iter(tree.xpath("//*[self::seg-source or self::target]"))
for seq, tar in zip(nodes, nodes):
# each node will be the matchi... | 0 | 2016-09-23T13:23:03Z | [
"python",
"xml",
"xpath",
"lxml",
"xliff"
] |
PyGobject error | 39,661,560 | <pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from gi.repository import Gtk
class ourwindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="My Hello World Program")
Gtk.Window.set_default_size(self, 400,325)
Gtk.Window.set_position(self, Gtk.WindowPosition.CENTER)
button1 = Gtk.Button("Hello, W... | 0 | 2016-09-23T13:06:20Z | 39,661,925 | <p>This is most likely how it should be formatted:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from gi.repository import Gtk
class ourwindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="My Hello World Program")
Gtk.Window.set_default_size(self, 400,325)
Gt... | 2 | 2016-09-23T13:23:52Z | [
"python",
"gtk",
"pygobject"
] |
How to create permanent MS Access Query by Python 3.5.1? | 39,661,582 | <p>I have about 40 MS Access Databases and have some troubles if need to create or transfer one of MS Access Query (like object) from one db to other dbs.
So I tried to solve this problem with <code>pyodbc</code> but.. as I saw <code>pyodbc</code> doesn't support to create new, permanent MS Access Query (object).
I can... | 3 | 2016-09-23T13:07:23Z | 39,662,166 | <p>You can use a <a href="https://msdn.microsoft.com/en-us/library/bb177895(v=office.12).aspx" rel="nofollow">CREATE VIEW</a> statement to create a saved Select Query in Access. The pyodbc equivalent to your VBA example would be</p>
<pre class="lang-python prettyprint-override"><code>crsr = conn.cursor()
sql = """\
CR... | 5 | 2016-09-23T13:34:37Z | [
"python",
"vba",
"ms-access",
"pyodbc"
] |
How to create permanent MS Access Query by Python 3.5.1? | 39,661,582 | <p>I have about 40 MS Access Databases and have some troubles if need to create or transfer one of MS Access Query (like object) from one db to other dbs.
So I tried to solve this problem with <code>pyodbc</code> but.. as I saw <code>pyodbc</code> doesn't support to create new, permanent MS Access Query (object).
I can... | 3 | 2016-09-23T13:07:23Z | 39,663,974 | <p>Consider the Python equivalent of the VBA running exactly what VBA uses: a COM interface to the Access Object library. With Python's <code>win32com</code> third-party module, you can call the <a href="https://msdn.microsoft.com/en-us/library/office/ff195966.aspx" rel="nofollow">CreateQueryDef</a> method. Do note: th... | 1 | 2016-09-23T15:03:39Z | [
"python",
"vba",
"ms-access",
"pyodbc"
] |
Show progress in Python from underlying C++ process | 39,661,708 | <p>I have a C++ program that runs for a long time and performs lots (e.g. 1,000,000) of iterations. Typically I run it from Python (usually Jupyter Notebook). I would like to see the a progress from the C++ program. Is there a convenient way to do it? Perhaps to link it to a Pythonic progress bar library, e.g. tqdm?</p... | 1 | 2016-09-23T13:13:28Z | 39,793,233 | <p>Disclaimer, I'm codeveloper of tqdm.</p>
<p>I see 3 solutions :</p>
<ul>
<li><p>Either the cpp lib regularly calls back to python like after processing each row of a matrix (as pandas does) and then you can use a Python progress bar like tqdm, just like for any other common python loop. The loop won't be updated a... | 0 | 2016-09-30T13:56:05Z | [
"python",
"subprocess",
"progress-bar",
"jupyter-notebook",
"tqdm"
] |
Merging multiple dataframe bassed on matching values from three column into single dataframe | 39,661,759 | <p>I have multiple data frames (25 dataframes), I am looking for recurrently occuuring row values from three columns of all dataframes. The following are my example of my daframes</p>
<pre><code>df1
chr start end name
1 12334 12334 AAA
1 2342 2342 SAP
2 3456 3456 SOS
3 4537 4537 ABR... | 1 | 2016-09-23T13:16:05Z | 39,662,541 | <p>Say you have a dictionary mapping sample names to DataFrames:</p>
<pre><code>dfs = {'df1': df1, 'df2': df2}
</code></pre>
<p>(and so on).</p>
<p>The common relevant keys (in hashable form) are</p>
<pre><code>common_tups = set.intersection(*[set(df[['chr', 'start', 'end']].drop_duplicates().apply(tuple, axis=1).v... | 1 | 2016-09-23T13:53:04Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
PyGame Space Invaders Game - Making aliens move together | 39,661,888 | <p>I've created a Space Invaders clone in Python using the PyGame modules but I'm running into some difficulty getting them to move down together when reaching the edge of the game screen. </p>
<p>How would I make it so when the aliens reach the edge of the game screen they all simultaneously change direction and drop... | 1 | 2016-09-23T13:22:17Z | 39,661,985 | <p>Your problem lies here:</p>
<pre><code>for alien in (allAliens.sprites()):
if alien.rect.x < 0:
alien.rect.y = alien.rect.y + 15
alien.Direction = "right"
if alien.rect.x > 395:
alien.rect.y = alien.rect.y + 15
alien.Direction = "left"
loop =+1
</code></pre>
<p>I a... | 4 | 2016-09-23T13:26:35Z | [
"python",
"python-2.7",
"pygame"
] |
2d density plot using Python | 39,661,929 | <p>I had been trying to make a 2D density plot from a data file using the code below in Python</p>
<h1>2d.py</h1>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
import numpy as np
fig1 = plt.figure(1)
x, y, z1, z2 = np.loadtxt('fort.101',unpack=True)
N = ... | 0 | 2016-09-23T13:23:57Z | 39,675,164 | <p><a href="http://i.stack.imgur.com/sD1Pe.png" rel="nofollow">enter image description here</a></p>
<p><a href="http://i.stack.imgur.com/Uri8R.png" rel="nofollow">enter image description here</a></p>
<p>This is what I am getting...</p>
| 0 | 2016-09-24T10:11:03Z | [
"python",
"plot",
"2d"
] |
How can I use NodeJS for front-end in large Python application? | 39,661,982 | <p>I am currently writing the front-end for a large python application and have realized that I would benefit a lot from various Node packages (I am currently trying to make it into a single page ReactJS application).</p>
<p>From my understanding though, in most tutorials, Node seems to be used for the entire applicat... | 0 | 2016-09-23T13:26:22Z | 39,663,885 | <p>Node.js doesn't run on the frontend but on the <strong>backend</strong> - you can use Node <strong>instead</strong> of Python.</p>
<p>You can use Node to prepare/compile/build/minify your frontend code.</p>
<p>You can use <code>npm</code> <strong>modules</strong> on the frontend - see <a href="http://browserify.or... | 1 | 2016-09-23T14:59:37Z | [
"python",
"node.js",
"npm",
"node-modules"
] |
Python: creating a group column in a Pandas dataframe based on an integer range of values | 39,662,016 | <p>For each range <code>[0, 150]</code> in the <code>diff</code> column, I want to create a group column that increases by 1 each time the range resets. When <code>diff</code> is negative, the range resets.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'year': [2016, 2016, 2016, 2016, 2016, 2016, 2016],
... | 1 | 2016-09-23T13:28:21Z | 39,662,141 | <p>IIUC you can test whether the <code>'diff'</code> column is negative which produces a boolean array, then cast this to <code>int</code> and the call <code>cumsum</code>:</p>
<pre><code>In [313]:
df_combined['group'] = (df_combined['diff'] < 0).astype(int).cumsum()
df_combined
Out[313]:
date percentworn... | 2 | 2016-09-23T13:33:20Z | [
"python",
"pandas"
] |
How to split a file in python | 39,662,094 | <p>I am trying to split 2 lists, compare them and make a new list without the succesfully compared items in 2 lists.</p>
<p>So lets say
List_1.txt =</p>
<pre><code>Failed = abc
Failed = hfi
Failed = kdi
</code></pre>
<p>and List_2.txt = </p>
<pre><code>1:1:1 - jdsfjdf
2:2:2 - iidf
3:3:3 - abc
6:3:1 - hfi
8:2:1 - k... | 0 | 2016-09-23T13:31:06Z | 39,662,242 | <pre><code>with open('File1', 'r') as f1:
f1_stored = []
for line in f1:
f1_stored.append(line.split('=')[1].strip())
with open('File2', 'r') as f2;
output = []
for line in f2:
if not any(failed in line for failed in f1_stored):
output.append(line)
</code>... | 1 | 2016-09-23T13:37:49Z | [
"python",
"list",
"file",
"split"
] |
How to split a file in python | 39,662,094 | <p>I am trying to split 2 lists, compare them and make a new list without the succesfully compared items in 2 lists.</p>
<p>So lets say
List_1.txt =</p>
<pre><code>Failed = abc
Failed = hfi
Failed = kdi
</code></pre>
<p>and List_2.txt = </p>
<pre><code>1:1:1 - jdsfjdf
2:2:2 - iidf
3:3:3 - abc
6:3:1 - hfi
8:2:1 - k... | 0 | 2016-09-23T13:31:06Z | 39,662,355 | <p>Something like this</p>
<pre><code>bad_stuff = []
with open('List_1', 'r') as fn:
for line in fn:
bad_stuff.append(line.split('=')[1].strip())
with open('List_2', 'r') as fn:
for line in fn:
if line.split(':')[1].strip() not in bad_stuff:
print(line)
</code></pre>
<p>The list ... | 1 | 2016-09-23T13:43:28Z | [
"python",
"list",
"file",
"split"
] |
Data responses in IMAP using Python | 39,662,099 | <p>Dear users of Stack Overflow,</p>
<p>My question is about how to use the returned data of an imap command in python (in this case printing the amount of messages in your inbox). What I was able to find on the internet is limited to the following two descriptions:</p>
<p><a href="http://i.stack.imgur.com/P9V0D.png"... | 0 | 2016-09-23T13:31:15Z | 39,726,876 | <p>The select function returns the number from the EXISTs response. Almost all imaplib commands return two values, <code>type</code>, and <code>data</code>.</p>
<p>From the <a href="https://docs.python.org/2/library/imaplib.html" rel="nofollow">documentation</a></p>
<blockquote>
<p>Each command returns a tuple: (t... | 0 | 2016-09-27T14:06:57Z | [
"python",
"imap",
"gmail-imap",
"imaplib"
] |
Checking If Word Is English Python | 39,662,212 | <p>So, I am doing a project where I have a list with english words and want it to check the word i write is in the list and tell me if it's in english or not, I have no idea how to do this but It's what i'm supposed to do so I am asking for your help</p>
<pre><code>text = open("dict.txt","r")
#Opens the dict.txt file ... | 0 | 2016-09-23T13:36:56Z | 39,662,299 | <p>In your code, <code>text</code> is a file object, which you first need to read from somehow. You could, for example, read them into a set (because of O(1) lookup times):</p>
<pre><code>with open("dict.txt", "r") as f:
text = {line.strip() for line in f} # set comprehension
word = input("Type a word to check i... | 2 | 2016-09-23T13:40:32Z | [
"python",
"list"
] |
Transforming an Abaqus macro into a python script | 39,662,277 | <p>I am using Abaqus (6.13) to run FEM thermal simulations. I need to get the total external heat flux aplied on that model. My searches indicated that the only way to get it was to sum de RFLE history output on the whole model and it works fine. The problem is that I have a ~300 000 elements model and that the simple ... | 1 | 2016-09-23T13:39:28Z | 39,708,953 | <p>here is a script that does essentially what you want:
(and you see we only need the three import's)</p>
<pre><code>from abaqus import *
from abaqusConstants import *
import visualization
odb=session.openOdb(name='/full/path/Job-1.odb')
session.viewports['Viewport: 1'].setValues(displayedObject=odb)
session.xyDataLi... | 0 | 2016-09-26T17:31:08Z | [
"python",
"macros",
"abaqus"
] |
How do I run parallel tasks with Celery? | 39,662,381 | <p>I am using Celery to run some tasks that take a long time to complete. There
is an initial task that needs to complete before two sub-tasks can run. The tasks that I created are file system operations and don't return a result. </p>
<p>I would like the subtasks to run at the same time, but when I use a group for t... | 0 | 2016-09-23T13:44:22Z | 39,662,548 | <p>The chain is definitely the right approach. </p>
<p>I would expect this to work: chain(initial_task.s(), g)()</p>
<p>Do you have more than one celery worker running to be able to run more than one task at the same time?</p>
| 0 | 2016-09-23T13:53:22Z | [
"python",
"celery"
] |
scikit learn output metrics.classification_report into CSV/tab-delimited format | 39,662,398 | <p>I'm doing a multiclass text classification in Scikit-Learn. The dataset is being trained using the Multinomial Naive Bayes classifier having hundreds of labels. Here's an extract from the Scikit Learn script for fitting the MNB model</p>
<pre><code>from __future__ import print_function
# Read **`file.csv`** into a... | 1 | 2016-09-23T13:45:19Z | 39,664,921 | <p>The way I have always solved output problems is like what I've mentioned in my previous comment, I've converted my output to a DataFrame. Not only is it incredibly easy to send to files (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">see here</a>), but <a ... | -1 | 2016-09-23T15:53:00Z | [
"python",
"text",
"machine-learning",
"scikit-learn",
"classification"
] |
Sending data from html to python flask server "GET / HTTP/1.1" 405 error | 39,662,447 | <p>very new to python/AJAX and have been piecing everything from examples on the internet/flask documentation and I've gotten so far. Basically what I am trying to do is send latitude and longitude coordinates on a click (from mapbox API) to flask, and have that data print to console (to prove it has successfully gone ... | -1 | 2016-09-23T13:47:57Z | 39,662,650 | <p>The reason you are getting 405 error is because you only have <code>home()</code> controller, that accept only <code>POST</code> methods. And you are trying to get response with <code>GET</code> method.</p>
<p>So you need to change <code>methods</code> argument in <code>@app.route()</code> decorator</p>
<pre><code... | 0 | 2016-09-23T13:58:10Z | [
"javascript",
"python",
"html",
"ajax",
"flask"
] |
Sending data from html to python flask server "GET / HTTP/1.1" 405 error | 39,662,447 | <p>very new to python/AJAX and have been piecing everything from examples on the internet/flask documentation and I've gotten so far. Basically what I am trying to do is send latitude and longitude coordinates on a click (from mapbox API) to flask, and have that data print to console (to prove it has successfully gone ... | -1 | 2016-09-23T13:47:57Z | 39,662,824 | <p>In your route, allow <code>GET</code> method, otherwise the html wil never render.</p>
<pre><code>@app.route('/', methods=['POST', 'GET'])
</code></pre>
<p>To print lat/lng to the console, first check if the method is <code>POST</code>, then print it:</p>
<pre><code>if request.method == 'POST':
print(request.... | 0 | 2016-09-23T14:06:43Z | [
"javascript",
"python",
"html",
"ajax",
"flask"
] |
Unable to resolve EOL error while using chdir along with path in python | 39,662,538 | <p>Code</p>
<pre><code>os.chdir(os.path.normpath(r"D:\mystuff\Ear\APP-INF\lib\extract-dto"))
</code></pre>
<p>I have tried other code sample :</p>
<pre><code>os.chdir("D:\\mystuff\\ekaEar\\APP-INF\\lib\\extract-dto")
</code></pre>
<p>Output:</p>
<pre><code>File "CreateJar.py", line 13
os.chdir(os.path.normpath('D:... | 0 | 2016-09-23T13:52:59Z | 39,664,036 | <p>It looks like the backslash at the end of the path is causing the single quote to be escaped. If possible, try removing the last backslash from the path.</p>
<pre><code>os.chdir(os.path.normpath('D:\mystuff\Ear\APP-INF\lib'))
</code></pre>
<p>If your path is stored in a variable, you can do this with code using so... | -1 | 2016-09-23T15:07:09Z | [
"python",
"cmd"
] |
cross products with einsums | 39,662,540 | <p>I'm trying to compute the cross-products of many 3x1 vector pairs as fast as possible. This</p>
<pre><code>n = 10000
a = np.random.rand(n, 3)
b = np.random.rand(n, 3)
numpy.cross(a, b)
</code></pre>
<p>gives the correct answer, but motivated by <a href="http://stackoverflow.com/a/20910319/353337">this answer to ... | 1 | 2016-09-23T13:53:03Z | 39,663,181 | <p>You can bring in matrix-multiplication using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a> to lose one of the dimensions at the first level and then use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" re... | 2 | 2016-09-23T14:23:50Z | [
"python",
"performance",
"numpy",
"cross-product",
"numpy-einsum"
] |
cross products with einsums | 39,662,540 | <p>I'm trying to compute the cross-products of many 3x1 vector pairs as fast as possible. This</p>
<pre><code>n = 10000
a = np.random.rand(n, 3)
b = np.random.rand(n, 3)
numpy.cross(a, b)
</code></pre>
<p>gives the correct answer, but motivated by <a href="http://stackoverflow.com/a/20910319/353337">this answer to ... | 1 | 2016-09-23T13:53:03Z | 39,663,686 | <p>The count of multiply operation of <code>einsum()</code> is more then <code>cross()</code>, and in the newest NumPy version, <code>cross()</code> doesn't create many temporary arrays. So <code>einsum()</code> can't be faster than <code>cross()</code>. </p>
<p>Here is the old code of cross:</p>
<pre><code>x = a[1]*... | 2 | 2016-09-23T14:48:00Z | [
"python",
"performance",
"numpy",
"cross-product",
"numpy-einsum"
] |
python xlsxwriter - wrong category axis in column chart in Excel 2013 | 39,662,555 | <p>I'm using <code>xlsxwriter</code> to generate a chart. I'm trying to use texts for the category axis, it works in almost every excel version (2007, 2010). But not in excel 2013, and not in Microsoft Excel Online (which seems to be like excel 2013). </p>
<p>The problem: the category axis is displayed as sequence nu... | 2 | 2016-09-23T13:53:41Z | 39,664,936 | <p>There isn't any reason that the XlsxWriter output would work in Excel 2007 and not in Excel 2013. The file format is the default 2007 file format and Excel is very good at backward compatibility.</p>
<p>Also, I don't see the issue you describe. I modified your example to add some sample input data:</p>
<pre><code>... | 2 | 2016-09-23T15:54:09Z | [
"python",
"axis",
"excel-2013",
"xlsxwriter"
] |
python xlsxwriter - wrong category axis in column chart in Excel 2013 | 39,662,555 | <p>I'm using <code>xlsxwriter</code> to generate a chart. I'm trying to use texts for the category axis, it works in almost every excel version (2007, 2010). But not in excel 2013, and not in Microsoft Excel Online (which seems to be like excel 2013). </p>
<p>The problem: the category axis is displayed as sequence nu... | 2 | 2016-09-23T13:53:41Z | 39,673,192 | <p>Problem actually solved by upgrading my version of the library. My version was 0.5.1 and now is 0.9. I wonder if it was a bug in the earlier version. Works great now, too bad it took me some time to figure out</p>
| -1 | 2016-09-24T06:17:13Z | [
"python",
"axis",
"excel-2013",
"xlsxwriter"
] |
Python: requests.get ignores the last record | 39,662,596 | <p>This is my code:</p>
<pre><code>response = requests.get(apiurl+'api/v1/watch/services',
auth=(apiuser,apipass), verify=False, stream=True)
for line in response.iter_lines():
try:
data = json.loads(line.decode('utf-8'))
pprint.pprint(data)
except Exception as e:
... | 0 | 2016-09-23T13:56:02Z | 39,755,743 | <p>OK so the answer is a bit unexpected for me.</p>
<p>Updating python from 3.4 to 3.5 helped, nothing else changed.</p>
<p>Hope this answer helps someone else fighting this problem.</p>
| 0 | 2016-09-28T19:07:09Z | [
"python",
"python-requests"
] |
getting the ascii code of a sentence | 39,662,665 | <p>I am trying to make a code that will give me the ascii code of a sentence, right now i can only give one letter</p>
<p>for example</p>
<pre><code>a = input("c")
b = ord(a)
print (b)
</code></pre>
<p>it prints 99, my goal is to type abc with the outcome of 97 98 99</p>
| 0 | 2016-09-23T13:59:03Z | 39,662,707 | <p>Loop through <code>a</code>:</p>
<pre><code>print([ord(c) for c in a])
</code></pre>
| 2 | 2016-09-23T14:00:38Z | [
"python",
"ascii"
] |
numpy.meshgrid explanation | 39,662,699 | <p>Could someone care to explin the <code>meshgrid</code> method ? I cannot wrap my mind around it. The example is from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html#numpy.meshgrid" rel="nofollow">SciPy</a> site:</p>
<pre><code>import numpy as np
nx, ny = (3, 2)
x = np.linspace(... | 0 | 2016-09-23T14:00:23Z | 39,663,187 | <p>Your linear spaced vectors <code>x</code> and <code>y</code> defined by <code>linspace</code> use 3 and 2 points respectively. </p>
<p>These linear spaced vectors are then used by the meshgrid function to create a 2D linear spaced point cloud. This will be a grid of points for each of the <code>x</code> and <code>y... | 0 | 2016-09-23T14:23:56Z | [
"python",
"numpy"
] |
numpy.meshgrid explanation | 39,662,699 | <p>Could someone care to explin the <code>meshgrid</code> method ? I cannot wrap my mind around it. The example is from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html#numpy.meshgrid" rel="nofollow">SciPy</a> site:</p>
<pre><code>import numpy as np
nx, ny = (3, 2)
x = np.linspace(... | 0 | 2016-09-23T14:00:23Z | 39,665,354 | <pre><code>In [214]: nx, ny = (3, 2)
In [215]: x = np.linspace(0, 1, nx)
In [216]: x
Out[216]: array([ 0. , 0.5, 1. ])
In [217]: y = np.linspace(0, 1, ny)
In [218]: y
Out[218]: array([ 0., 1.])
</code></pre>
<p>Using unpacking to better see the 2 arrays produced by <code>meshgrid</code>:</p>
<pre><code>In [225]: X... | 1 | 2016-09-23T16:18:37Z | [
"python",
"numpy"
] |
plot categorical variable compared to another categorical variable in Python | 39,662,817 | <p>What is the best way to plot a categorical variable versus another categorical variable in Python. Imagine we have "males" and "females" and, on the other side, we have "paid" and "unpaid". How can I plot a meaningful and easy-to-interpret figure in python describing the information about males and females and if th... | 1 | 2016-09-23T14:06:25Z | 39,690,919 | <p>This type of stacked bar charts can be used:
<a href="http://i.stack.imgur.com/q9QE5.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/q9QE5.jpg" alt="enter image description here"></a></p>
<hr>
<p>The code for the above stacked barchart:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
ra... | 0 | 2016-09-25T19:27:05Z | [
"python",
"matplotlib",
"plot",
"categorical-data"
] |
Tracking down implicit unicode conversions in Python 2 | 39,662,847 | <p>I have a large project where at various places problematic implicit Unicode conversions (coersions) were used in the form of e.g.:
</p>
<pre class="lang-python prettyprint-override"><code>someDynamicStr = "bar" # could come from various sources
# works
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
someD... | 7 | 2016-09-23T14:08:02Z | 39,688,614 | <p>I see you have a lot of edits relating to solutions you may have encountered. I'm just going to address your original post which I believe to be: "I want to create a wrapper around the unicode constructor that checks input".</p>
<p>The <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow... | -3 | 2016-09-25T15:31:51Z | [
"python",
"python-2.7",
"debugging",
"unicode",
"monkeypatching"
] |
Tracking down implicit unicode conversions in Python 2 | 39,662,847 | <p>I have a large project where at various places problematic implicit Unicode conversions (coersions) were used in the form of e.g.:
</p>
<pre class="lang-python prettyprint-override"><code>someDynamicStr = "bar" # could come from various sources
# works
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
someD... | 7 | 2016-09-23T14:08:02Z | 39,736,968 | <p>You can register a custom encoding which prints a message whenever it's used:</p>
<p>Code in <code>ourencoding.py</code>:</p>
<pre><code>import sys
import codecs
import traceback
# Define a function to print out a stack frame and a message:
def printWarning(s):
sys.stderr.write(s)
sys.stderr.write("\n")
... | 4 | 2016-09-28T02:12:07Z | [
"python",
"python-2.7",
"debugging",
"unicode",
"monkeypatching"
] |
Tracking down implicit unicode conversions in Python 2 | 39,662,847 | <p>I have a large project where at various places problematic implicit Unicode conversions (coersions) were used in the form of e.g.:
</p>
<pre class="lang-python prettyprint-override"><code>someDynamicStr = "bar" # could come from various sources
# works
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
someD... | 7 | 2016-09-23T14:08:02Z | 39,748,135 | <p>What you can do is the following:</p>
<p>First create a custom encoding. I will call it "lascii" for "logging ASCII":</p>
<pre><code>import codecs
import traceback
def lascii_encode(input,errors='strict'):
print("ENCODED:")
traceback.print_stack()
return codecs.ascii_encode(input)
def lascii_decode(... | 2 | 2016-09-28T12:52:15Z | [
"python",
"python-2.7",
"debugging",
"unicode",
"monkeypatching"
] |
Tracking down implicit unicode conversions in Python 2 | 39,662,847 | <p>I have a large project where at various places problematic implicit Unicode conversions (coersions) were used in the form of e.g.:
</p>
<pre class="lang-python prettyprint-override"><code>someDynamicStr = "bar" # could come from various sources
# works
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
someD... | 7 | 2016-09-23T14:08:02Z | 39,805,488 | <p>Just add:</p>
<pre><code>from __future__ import unicode_literals
</code></pre>
<p>at the beginning of your source code files - it has to be the first import and it has to be in all source code files affected and the headache of using unicode in Python-2.7 goes away. If you didn't do anything super weird with strin... | 2 | 2016-10-01T10:24:48Z | [
"python",
"python-2.7",
"debugging",
"unicode",
"monkeypatching"
] |
Read in the first column of a CSV in python | 39,662,891 | <p>I have a CSV (mylist.csv) with 2 columns that look similar to this:</p>
<blockquote>
<pre><code>jfj840398jgg item-2f
hd883hb2kjsd item-9k
jie9hgtrbu43 item-12
fjoi439jgnso item-3i
</code></pre>
</blockquote>
<p>I need to read the first column into a variable so I just get:</p>
<blockquote>
<pre><c... | 1 | 2016-09-23T14:10:07Z | 39,662,946 | <p>You should <code>split</code> the row and then append the first item </p>
<pre><code>list2 = []
with open("mylist.csv") as f:
for row in f:
list2.append(row.split()[0])
</code></pre>
<p>You could also use a <em>list comprehension</em> which are pretty standard for creating lists:</p>
<pre><code>wit... | 3 | 2016-09-23T14:12:41Z | [
"python",
"csv"
] |
Read in the first column of a CSV in python | 39,662,891 | <p>I have a CSV (mylist.csv) with 2 columns that look similar to this:</p>
<blockquote>
<pre><code>jfj840398jgg item-2f
hd883hb2kjsd item-9k
jie9hgtrbu43 item-12
fjoi439jgnso item-3i
</code></pre>
</blockquote>
<p>I need to read the first column into a variable so I just get:</p>
<blockquote>
<pre><c... | 1 | 2016-09-23T14:10:07Z | 39,662,990 | <p>you import <code>csv</code>, but then never use it to actually read the CSV. Then you open <code>mylist.csv</code> as a normal file, so when you declare:</p>
<pre><code> for row in f:
list2.append(row[0])
</code></pre>
<p>What you're actually telling Python to do is "iterate through the lines, and append the ... | 2 | 2016-09-23T14:14:48Z | [
"python",
"csv"
] |
Read in the first column of a CSV in python | 39,662,891 | <p>I have a CSV (mylist.csv) with 2 columns that look similar to this:</p>
<blockquote>
<pre><code>jfj840398jgg item-2f
hd883hb2kjsd item-9k
jie9hgtrbu43 item-12
fjoi439jgnso item-3i
</code></pre>
</blockquote>
<p>I need to read the first column into a variable so I just get:</p>
<blockquote>
<pre><c... | 1 | 2016-09-23T14:10:07Z | 39,842,693 | <p>You can also use <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a> here:</p>
<pre><code>import pandas as pd
df = pd.read_csv(mylist.csv)
</code></pre>
<p>Then, getting the first column is as easy as:</p>
<pre><code>matrix2 = df[df.columns[0]].as_matrix
list2 = matrix2.tolist()
</code></pr... | 0 | 2016-10-04T00:59:43Z | [
"python",
"csv"
] |
flask + mysql beginner issue | 39,662,909 | <p>This is my first ever SO post, so goes without saying I am only just starting with web programming. Did a lot of Pascal programming in high school, but that was long ago. Please bear with me.</p>
<p>I am trying to create a simple web app and the first thing I am building is the register feature. Using flask and mys... | -1 | 2016-09-23T14:10:51Z | 39,662,963 | <p>You need to add define <code>cursor</code> variable in <code>authenticate()</code> controller like this</p>
<pre><code>cursor = mysql.connection.cursor() # for Flask-MySQLdb package (not relevant here)
</code></pre>
<p>Also you need to define it before it's first use.</p>
<p><strong>UPDATE</strong> since you are... | 1 | 2016-09-23T14:13:47Z | [
"python",
"mysql",
"flask"
] |
Python pandas: Select columns where a specific row satisfies a condition | 39,662,941 | <p>I have a dataframe dfall where there is a row labeled 'row1' with values 'foo' and 'bar'. I want to select only columns of dfall where 'row1' has the value 'foo'.</p>
<p>In other words:</p>
<pre><code>dfall= pd.DataFrame([['bar','foo'],['bla','bli']], columns=['col1','col2'], index=['row1','row2'])
</code></pre>
... | 1 | 2016-09-23T14:12:37Z | 39,663,001 | <p>You can compare your df against the scalar value, and then use <code>any</code> with <code>axis=0</code> and pass this boolean mask to <code>ix</code>:</p>
<pre><code>In [324]:
df.ix[:,(df == 'foo').any(axis=0)]
Out[324]:
col2
row1 foo
row2 bli
</code></pre>
<p>breaking the above down:</p>
<pre><code>In [... | 0 | 2016-09-23T14:15:09Z | [
"python",
"pandas",
"select"
] |
Python pandas: Select columns where a specific row satisfies a condition | 39,662,941 | <p>I have a dataframe dfall where there is a row labeled 'row1' with values 'foo' and 'bar'. I want to select only columns of dfall where 'row1' has the value 'foo'.</p>
<p>In other words:</p>
<pre><code>dfall= pd.DataFrame([['bar','foo'],['bla','bli']], columns=['col1','col2'], index=['row1','row2'])
</code></pre>
... | 1 | 2016-09-23T14:12:37Z | 39,663,380 | <p>Using EdChum's answer, to make it row specific I did:
df.ix[:,(df.loc['row1'] == 'foo')]</p>
| 0 | 2016-09-23T14:33:08Z | [
"python",
"pandas",
"select"
] |
Django 1.9 Can't leave formfield blank issue | 39,662,975 | <p>I modified my forms to show a new label for the fields in my model. Now I can't have a user leave the form field blank. I've tried to add blank=True and null=True, but without luck. How can I allow fields to be blank?</p>
<p>My Model:</p>
<pre><code>class UserProfile(models.Model):
# Page 1
user = models.O... | 0 | 2016-09-23T14:14:11Z | 39,663,307 | <p>You overrode the fields, so they won't preserve any of the attributes; you need to set them explicitly.</p>
<pre><code>line1 = forms.CharField(label="Address", required=False)
</code></pre>
<p>Note also that your model field definitions shouldn't have <code>null=True</code> for CharFields, this is bad practice.</p... | 2 | 2016-09-23T14:29:28Z | [
"python",
"django",
"django-models",
"django-forms",
"django-1.9"
] |
Django 1.9 Can't leave formfield blank issue | 39,662,975 | <p>I modified my forms to show a new label for the fields in my model. Now I can't have a user leave the form field blank. I've tried to add blank=True and null=True, but without luck. How can I allow fields to be blank?</p>
<p>My Model:</p>
<pre><code>class UserProfile(models.Model):
# Page 1
user = models.O... | 0 | 2016-09-23T14:14:11Z | 39,663,355 | <p>Try to add this in forms.py:</p>
<pre><code>self.fields['line1'].required = false
</code></pre>
<p>You will have to do this for every field.</p>
| 1 | 2016-09-23T14:31:42Z | [
"python",
"django",
"django-models",
"django-forms",
"django-1.9"
] |
Find next lower value in list of (float) numbers? | 39,662,977 | <p>How should I write the <code>find_nearest_lower</code> function?</p>
<pre><code>>>> values = [10.1, 10.11, 10.20]
>>> my_value = 10.12
>>> nearest_lower = find_nearest_lower(values, my_value)
>>> nearest_lower
10.11
</code></pre>
<p>This needs to work in Python 2.6 without acces... | -2 | 2016-09-23T14:14:14Z | 39,663,039 | <pre><code>>>> def find_nearest_lower(seq, x):
... return max(item for item in seq if item < x)
...
>>> values = [10.1, 10.11, 10.20]
>>> my_value = 10.12
>>> nearest_lower = find_nearest_lower(values, my_value)
>>> nearest_lower
10.11
</code></pre>
<p>This approach ... | 4 | 2016-09-23T14:16:57Z | [
"python",
"python-2.6"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.