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 |
---|---|---|---|---|---|---|---|---|---|
Writing intersection data to new CSV
| 39,636,426 |
<p>I have 2 CSV files which have a list of unique words. After I complete my intersection on them I get the results, but when I try to write it to a new file it creates a very large sized file of almost 155MB, when it should be well below 2MB.</p>
<p><strong>Code:</strong></p>
<pre><code>alist, blist = [], []
with open("SetA-unique.csv", "r") as fileA:
reader = csv.reader(fileA, delimiter=',')
for row in reader:
alist += row
with open("SetB-unique.csv", "r") as fileB:
reader = csv.reader(fileB, delimiter=',')
for row in reader:
blist += row
first_set = set(alist)
second_set = set(blist)
res = (first_set.intersection(second_set))
writer = csv.writer(open("SetA-SetB.csv", 'w'))
for row in res:
writer.writerow(res)
</code></pre>
| -1 |
2016-09-22T10:19:56Z
| 39,636,462 |
<p>You're <em>writing</em> the entire set <code>res</code> to the file on each iteration. You probably want to write the rows instead:</p>
<pre><code>for row in res:
writer.writerow([row])
</code></pre>
| 2 |
2016-09-22T10:21:34Z
|
[
"python",
"csv"
] |
Writing intersection data to new CSV
| 39,636,426 |
<p>I have 2 CSV files which have a list of unique words. After I complete my intersection on them I get the results, but when I try to write it to a new file it creates a very large sized file of almost 155MB, when it should be well below 2MB.</p>
<p><strong>Code:</strong></p>
<pre><code>alist, blist = [], []
with open("SetA-unique.csv", "r") as fileA:
reader = csv.reader(fileA, delimiter=',')
for row in reader:
alist += row
with open("SetB-unique.csv", "r") as fileB:
reader = csv.reader(fileB, delimiter=',')
for row in reader:
blist += row
first_set = set(alist)
second_set = set(blist)
res = (first_set.intersection(second_set))
writer = csv.writer(open("SetA-SetB.csv", 'w'))
for row in res:
writer.writerow(res)
</code></pre>
| -1 |
2016-09-22T10:19:56Z
| 39,638,303 |
<p>Apart from writing the whole set each iteration you also don't need to create multiple sets and lists, you can use <em>itertools.chain</em>:</p>
<pre><code>from itertools import chain
with open("SetA-unique.csv") as file_a, open("SetB-unique.csv") as file_b,open("SetA-SetB.csv", 'w') as inter :
r1 = csv.reader(file_a)
r2 = csv.reader(file_b)
for word in set(chain.from_iterable(r1)).intersection(chain.from_iterable(r2)):
inter.write(word)+"\n"
</code></pre>
<p>If you are just writing words there is also no need to use <em>csv.writer</em> just use <em>file.write</em> as above.</p>
<p>If you are actually trying do the comparison row wise, you should not be creating a flat iterable of words, you can <em>imap</em> to tuples:</p>
<pre><code>from itertools import imap
with open("SetA-unique.csv") as file_a, open("SetB-unique.csv") as file_b,open("SetA-SetB.csv", 'w') as inter :
r1 = csv.reader(file_a)
r2 = csv.reader(file_b)
writer = csv.writer(inter)
for row in set(imap(tuple, r1).intersection(imap(tuple, r2)):
writer.writerow(row)
</code></pre>
<p>And if you only have one word per line you don't need the csv lib at all.</p>
<pre><code>from itertools import imap
with open("SetA-unique.csv") as file_a, open("SetB-unique.csv") as file_b,open("SetA-SetB.csv", 'w') as inter :
for word in set(imap(str.strip, file_a)).intersection(imap(str.strip, file_b)):
inter.write(word) + "\n"
</code></pre>
| 0 |
2016-09-22T11:52:28Z
|
[
"python",
"csv"
] |
How to avoid quotes from a comma separated string joined from a list in python
| 39,636,437 |
<p>I have created a comma separated string by joining strings from a list in Python 3.5 and use it to write it to an INI file using configobj. Here is a sample Python script used in a Ubuntu 16.04 terminal:</p>
<pre><code>sudo python3 << EOP
from configobj import ConfigObj
config=ConfigObj("myconfig.ini")
config['items']={}
itemlist=('item1','item2')
csvstr=",".join(list)
config['items']['itemlist'] = csvstr
config.write()
EOP
</code></pre>
<p>This writes the string with quotes as "item1,item2" as shown below. </p>
<pre><code>[items]
itemlist = "item1,item2"
</code></pre>
<p>However, if the items are joined with other characters such as ";", it writes the string without quotes! How to make it write the comma separated string without quotes?</p>
<p>Appreciate for any tips or solution.</p>
| 0 |
2016-09-22T10:20:26Z
| 39,636,679 |
<p>Commas are reserved for field separation and so you cannot have (unless you <a href="http://stackoverflow.com/a/39636774/2681632">really want to</a>) an unquoted string value with commas in it. Apparently you do want to have a list of values, so just pass a list as the value:</p>
<pre><code>from configobj import ConfigObj
config=ConfigObj("myconfig.ini")
config['items']={}
itemlist=['item1','item2']
config['items']['itemlist'] = itemlist
config.write()
</code></pre>
<p>This will result in </p>
<pre><code>[items]
itemlist = item1, item2
</code></pre>
| 2 |
2016-09-22T10:32:22Z
|
[
"python",
"string",
"csv",
"quotes"
] |
How to avoid quotes from a comma separated string joined from a list in python
| 39,636,437 |
<p>I have created a comma separated string by joining strings from a list in Python 3.5 and use it to write it to an INI file using configobj. Here is a sample Python script used in a Ubuntu 16.04 terminal:</p>
<pre><code>sudo python3 << EOP
from configobj import ConfigObj
config=ConfigObj("myconfig.ini")
config['items']={}
itemlist=('item1','item2')
csvstr=",".join(list)
config['items']['itemlist'] = csvstr
config.write()
EOP
</code></pre>
<p>This writes the string with quotes as "item1,item2" as shown below. </p>
<pre><code>[items]
itemlist = "item1,item2"
</code></pre>
<p>However, if the items are joined with other characters such as ";", it writes the string without quotes! How to make it write the comma separated string without quotes?</p>
<p>Appreciate for any tips or solution.</p>
| 0 |
2016-09-22T10:20:26Z
| 39,636,774 |
<p>Another solution is to use the <code>list_values</code> keyword:</p>
<pre><code>config = ConfigObj('myconfig.ini', list_values=False)
</code></pre>
<p><a href="https://configobj.readthedocs.io/en/latest/configobj.html#configobj-specifications" rel="nofollow">As the documentation says</a>, if <code>list_values=False</code> then single line values are not quoted or unquoted when reading and writing.</p>
<p>The result:</p>
<pre><code>[items]
itemlist = item1,item2
</code></pre>
| 2 |
2016-09-22T10:37:56Z
|
[
"python",
"string",
"csv",
"quotes"
] |
python - regex for matching text between two characters while ignoring backslashed characters
| 39,636,439 |
<p>I am trying to use python to get text between two dollar signs ($), but the dollar signs should <strong>not</strong> start with a backslash i.e. \$ (this is for a LaTeX rendering program). So if this is given</p>
<pre><code>$\$x + \$y = 5$ and $3$
</code></pre>
<p>This is what should be outputted</p>
<pre><code>['\$x + \$y = 5', ' and ', '3']
</code></pre>
<p>This is my code so far:</p>
<pre><code>def parse_latex(text):
return re.findall(r'(^|[^\\])\$.*?[^\\]\$', text)
print(parse_latex(r'$\$x + \$y = 5$ and $3$'))
</code></pre>
<p>But this is what I get:</p>
<pre><code>['', ' ']
</code></pre>
<p>I am not sure how to proceed from here.</p>
| 1 |
2016-09-22T10:20:28Z
| 39,636,533 |
<p>You can use this lookaround based regex that excluded escaped characters:</p>
<pre><code>>>> text = r'$\$x + \$y = 5$ and $3$'
>>> re.findall(r'(?<=\$)([^$\\]*(?:\\.[^$\\]*)*)(?=\$)', text)
['\\$x + \\$y = 5', ' and ', '3']
</code></pre>
<p><a href="https://regex101.com/r/zA7zE2/1" rel="nofollow">RegEx Demo</a></p>
<p><a href="http://ideone.com/7xzBwE" rel="nofollow">Code Demo</a></p>
<p><strong>RegEx Breakup:</strong></p>
<pre><code>(?<=\$) # Lookbehind to assert previous character is $
( # start capture group
[^$\\]* # match 0 or more characters that are not $ and \
(?: # start non-capturing group
\\. # match \ followed any escaped character
[^$\\]* # match 0 or more characters that are not $ and \
)* # non-capturing group, match 0 or more of this non-capturing group
) # end capture group
(?=\$) # Lookahead to assert next character is $
</code></pre>
| 1 |
2016-09-22T10:25:02Z
|
[
"python",
"regex",
"escaping"
] |
Destroy function Tkinter
| 39,636,507 |
<p>In this program I am attempting to destroy all on screen widgets at the start of a new function and instantly re-create them on screen to replicate a new page appearing. I used the destroy function once already to "change pages" when clicking on the start button in the game menu which worked fine. </p>
<p>However when attempting to destroy all pages a second time when clicking on the canvas to the error:</p>
<blockquote>
<p>_tkinter.TclError: bad window path name ".49314384"</p>
</blockquote>
<p>is presented. </p>
<pre><code>from tkinter import *
import tkinter
window = tkinter.Tk() #Here is where we set up the window and it's aesthetics,
window.title("BINARY-SUMZ!!!") #here we give the window a name,
window.geometry("1000x800") #here we give the window a size,
window.wm_iconbitmap('flower3.ico') #and here we give the window an icon.
def Destroy(): #this function destroys any widgets on the current page.
for widget in window.winfo_children():
widget.destroy()
def StartButton(): #This function starts the game after being clicked on.
print ("Game started from beginning.")
Intro() #This function starts the game after being clicked on.
def Menu(): #Creating a menu function
SumsTitle = tkinter.Label(window, text="BINARY-SUMS!!!", #Here is where we create the title for the menu screen, we give it a name,
fg = "light Green", #a foreground (text) color
bg = "tomato", #a backgorund color
font = "'Bauhaus 93 bold italic")
SumsTitle.pack() #and the text is given a font.
StartButtonWid = tkinter.Button(window, text = "Start Learning!!!",
fg = "tomato",
command= (StartButton))
StartButtonWid.pack() #Setting up the button for the start of the game.
TitleCanvas = tkinter.Canvas(window, bg = "light blue" ,
height = 1000,
width = 1000)
TitleCanvas.pack()
def Intro():
Destroy() #This function works fine
SumsTitle = tkinter.Label(window, text="Welcome!!!", #Here is where we create the title for the menu screen, we give it a name,
fg = "light green", #a foreground (text) color
bg = "tomato", #a backgorund color
height = 1,
width = 14,
font = "'Bauhaus 93 bold italic")
SumsTitle.pack()
Intro1 = tkinter.Label(window, text='Welcome to BINARY-SUMS!!! The fun, interactive binary learning game! in this game we will be learning about language based topics',
font= "30")
Intro1.pack()
Intro2 = tkinter.Label(window, text='that will be vital to know in your AS computing or computer science exams. Please click the screen to continue.',
font= "30")
Intro2.pack()
IntroCanvas = tkinter.Canvas(window, bg = "light blue" ,
height = 1500,
width = 1000)
IntroCanvas.bind("<Button-1>", Activ1())
IntroCanvas.pack()
def Activ1():
Destroy() #this function crashes.
if __name__ == "__main__":
Menu()
tkinter.mainloop()
</code></pre>
| 0 |
2016-09-22T10:23:48Z
| 39,640,158 |
<pre><code>IntroCanvas.bind("<Button-1>", Activ1())
^^
IntroCanvas.pack()
</code></pre>
<p>You are getting the error in above lines.</p>
<p>Adding parentheses means, "<em>call</em> that function as soon as compiler reaches there". After <code>Activ1</code> gets called, it calls <code>Destroy()</code> which destroys <code>IntroCanvas</code> then you are trying to <code>pack</code> destroyed widget. Hence you are getting that error.</p>
<p>As a debug note, if you see an error message like this one, most of the times it is because you are trying to do some action on <em>destroyed</em> widget/object so you should look for your destroying calls. </p>
<p>For solution,<br>
You should remove parenthesis and add an argument to <code>Activ1</code>. </p>
<pre><code>IntroCanvas.bind("<Button-1>", Activ1)
def Activ1(event):
</code></pre>
| 1 |
2016-09-22T13:16:04Z
|
[
"python",
"tkinter",
"destroy",
"tkinter-canvas"
] |
SSH tunnel from Python is too slow to connect
| 39,636,740 |
<p>I'm connecting to a remote SQL database over SSH. If I set up the SSH connection from the Linux command line (using <code>ssh-add my_private_key.key</code> and then <code>ssh [email protected]</code>), it takes less than a second to connect. But if I do it from Python using <a href="https://github.com/pahaz/sshtunnel" rel="nofollow">sshtunnel</a> (in the following script), it takes around 70 seconds. I accept that using Python might be a bit of an overhead, but not that much! And especially since, if I run the Python script <em>after</em> having connected from the command line, it's very fast. What do I need to add in the script to make it faster?</p>
<p>Python script:</p>
<pre><code>import pymysql, shlex, shutil, subprocess
import logging
import sshtunnel
from sshtunnel import SSHTunnelForwarder
import iot_config as cfg
def OpenRemoteDB():
global remotecur, remotedb
sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG
with SSHTunnelForwarder(
(cfg.sshconn['host'], cfg.sshconn['port']),
ssh_username = cfg.sshconn['user'],
ssh_private_key = cfg.sshconn['private_key_loc'],
ssh_private_key_password = cfg.sshconn['private_key_passwd'],
remote_bind_address = ('127.0.0.1', 3306)) as server:
print("OK")
# Main program starts here
OpenRemoteDB()
</code></pre>
<p>Python output:</p>
<pre><code>2016-09-20 12:34:15,272 | WARNING | Could not read SSH configuration file: ~/.ssh/config
2016-09-20 12:34:15,305 | INFO | 0 keys loaded from agent
2016-09-20 12:34:15,332 | DEBUG | Private key file (/etc/ssh/my_private_key.key, <class 'paramiko.rsakey.RSAKey'>) successfully loaded
2016-09-20 12:34:15,364 | INFO | Connecting to gateway: mysite.co.uk:22 as user 'user'
2016-09-20 12:34:15,389 | DEBUG | Concurrent connections allowed: True
2016-09-20 12:34:15,409 | DEBUG | Trying to log in with key: b'XXX'
2016-09-20 12:35:26,610 | INFO | Opening tunnel: 0.0.0.0:34504 <> 127.0.0.1:3306
</code></pre>
| 0 |
2016-09-22T10:36:21Z
| 39,830,029 |
<p>Doh! After posting this question I thought it would be a good idea to make sure sshtunnel was up-to-date - and it wasn't. So I've updated from 0.0.8.1 to the latest version (0.1.0) and my problem is solved!</p>
| 0 |
2016-10-03T11:00:29Z
|
[
"python",
"linux",
"python-3.x",
"ssh"
] |
Python: extract text request from url
| 39,636,797 |
<p>I try to extract users requests from url. I try to search answer, but I only find how to parse string.
But I have a problem, that I should identify a lot of urls with request and when I try to get string with attribute, attributes with text are different.
I mean when I try</p>
<pre><code>pat = re.compile(r"\?\w+=(.*)")
search = ['yandex.ru/search', 'youtube.com/results', 'google.com/search', 'google.ru/search', 'go.mail.ru/search', 'search.yahoo.com/search', 'market.yandex.ru/search', 'bing.com/search']
for i in urls:
u = re.findall(pat, i)
if any(ext in i for ext in search):
if len(u) > 0:
str = urllib.unquote(u[0])
print str
print {k: [s for s in v] for k, v in parse_qs(str).items()}
</code></pre>
<p>And it looks like </p>
<pre><code>chromesearch&clid=2196598&text=коÑÐ¾Ð»ÐµÐ²Ñ ÐºÑика ÑмоÑÑеÑÑ Ð¾Ð½Ð»Ð°Ð¹Ð½&lr=213&redircnt=1467230336.1
{'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\xbe\xd0\xbd\xd0\xbb\xd0\xb0\xd0\xb9\xd0\xbd'], 'clid': ['2196598'], 'lr': ['213'], 'redircnt': ['1467230336.1']}
минималиÑÑиÑнÑй+ÑÑилÑ&newwindow=1&biw=1280&bih=909&source=lnms&tbm=isch&sa=X&ved=0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:
{'bih': ['909'], 'newwindow': ['1'], 'source': ['lnms'], 'ved': ['0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:'], 'tbm': ['isch'], 'biw': ['1280'], 'sa': ['X']}
минималиÑÑиÑнÑй+ÑÑилÑ&newwindow=1&biw=1280&bih=909&source=lnms&tbm=isch&sa=X&ved=0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:
{'bih': ['909'], 'newwindow': ['1'], 'source': ['lnms'], 'ved': ['0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:'], 'tbm': ['isch'], 'biw': ['1280'], 'sa': ['X']}
rjulf+ddjlbim+ytdthysq+gby+rjl+d+,fyrjvfn&ie=utf-8&oe=utf-8&gws_rd=cr&ei=ezZ0V-7iOoab6ASvlJe4Dg
{'ie': ['utf-8'], 'oe': ['utf-8'], 'gws_rd': ['cr'], 'ei': ['ezZ0V-7iOoab6ASvlJe4Dg']}
маÑкаи гейла&lr=10750&clid=1985551-210&win=213
{'win': ['213'], 'clid': ['1985551-210'], 'lr': ['10750']}
1&q=как+вÑбÑаÑÑ+ÑмаÑÑÑон
{'q': ['\xd0\xba\xd0\xb0\xd0\xba \xd0\xb2\xd1\x8b\xd0\xb1\xd1\x80\xd0\xb0\xd1\x82\xd1\x8c \xd1\x81\xd0\xbc\xd0\xb0\xd1\x80\xd1\x82\xd1\x84\xd0\xbe\xd0\xbd']}
Jade+Jantzen&ie=utf-8&oe=utf-8&gws_rd=cr&ei=FQB0V9WbIoahsAH5zZGACg
{'ie': ['utf-8'], 'oe': ['utf-8'], 'gws_rd': ['cr'], 'ei': ['FQB0V9WbIoahsAH5zZGACg']}
</code></pre>
<p>Is any way to get only text to all strings? </p>
| -1 |
2016-09-22T10:39:03Z
| 39,638,211 |
<p>You can access the text using a dictionary lookup to get the list, then access the first element of the list:</p>
<pre><code>d = {'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\xbe\xd0\xbd\xd0\xbb\xd0\xb0\xd0\xb9\xd0\xbd'], 'clid': ['2196598'], 'lr': ['213'], 'redircnt': ['1467230336.1']}
text = d['text'][0]
>>> print text
коÑÐ¾Ð»ÐµÐ²Ñ ÐºÑика ÑмоÑÑеÑÑ Ð¾Ð½Ð»Ð°Ð¹Ð½
</code></pre>
<p>Or you can get it directly from the <code>parse_qs</code> result:</p>
<pre><code>>>> print urlparse.parse_qs(s)['text'][0]
коÑÐ¾Ð»ÐµÐ²Ñ ÐºÑика ÑмоÑÑеÑÑ Ð¾Ð½Ð»Ð°Ð¹Ð½
</code></pre>
<p>To apply that to your code such that it will work for all values:</p>
<pre><code>print {k: v[0] for k, v in parse_qs(str).items()}
</code></pre>
<p>i.e. take the first item of each values list.</p>
<hr>
<p>If you want to print the dictionaries and have the strings appear in the proper representation, i.e. not as produced by <em>repr</em>, you could use the <code>json</code> module to dump the dictionary objects as strings, then print them:</p>
<pre><code>import json
d = {'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\xbe\xd0\xbd\xd0\xbb\xd0\xb0\xd0\xb9\xd0\xbd'], 'clid': ['2196598'], 'lr': ['213'], 'redircnt': ['1467230336.1']}
s = json.dumps(d, ensure_ascii=False)
>>> print s
{"text": ["коÑÐ¾Ð»ÐµÐ²Ñ ÐºÑика ÑмоÑÑеÑÑ Ð¾Ð½Ð»Ð°Ð¹Ð½"], "clid": ["2196598"], "lr": ["213"], "redircnt": ["1467230336.1"]}
</code></pre>
| 0 |
2016-09-22T11:49:08Z
|
[
"python",
"urllib2",
"urllib",
"urlparse"
] |
Module in Python
| 39,636,825 |
<p>Command :Import setuptools .</p>
<p>Where python will going to search the setuptools ?</p>
<p>Like command : Import ryu.hooks </p>
<p>In this case it will search the ryu folder then import the code into the script which is calling it .</p>
<p>-Ajay</p>
| 1 |
2016-09-22T10:40:12Z
| 39,636,916 |
<blockquote>
<p>the interpreter first searches for a built-in module</p>
</blockquote>
<p><a href="https://docs.python.org/2/tutorial/modules.html#the-module-search-path" rel="nofollow">https://docs.python.org/2/tutorial/modules.html#the-module-search-path</a></p>
| 3 |
2016-09-22T10:44:52Z
|
[
"python"
] |
extracting a set amount of lines from a Text file - Python
| 39,637,063 |
<p>let us imagine I have a text file with the following inside of it: (each line starts with a number and contains information next to it which I need) </p>
<blockquote>
<p>1 325315</p>
<p>2 234265</p>
<p>3 345345</p>
<p>4 234234</p>
<p>5 373432</p>
<p>6 436721 </p>
<p>7 325262</p>
<p>8 235268</p>
</blockquote>
<p>How would I go about extracting the lines that are after number 3 and before number 6 for example? While keeping the other data that is held on the same line.</p>
<p>I have a very large text file ~1000 lines, which I need to extract the lines starting with 300 through to 800. Either extract or remove the lines that I do not need, either way is ok.</p>
<p>Thanks for any help</p>
| 0 |
2016-09-22T10:53:14Z
| 39,637,423 |
<p>Something like this?</p>
<pre><code>def extract(file, fr, to):
f = open(file, "r+")
[next(f) for i in range(fr)]
return [f.readline() for i in range(to - fr)]
</code></pre>
<p>or extract only the 2nd column</p>
<pre><code> return [f.readline().split()[1] for i in range(500)]
</code></pre>
<p>Output:</p>
<pre><code>extract("file",3,5)
['4 234234\n', '5 373432\n']
</code></pre>
| 0 |
2016-09-22T11:11:03Z
|
[
"python",
"text"
] |
extracting a set amount of lines from a Text file - Python
| 39,637,063 |
<p>let us imagine I have a text file with the following inside of it: (each line starts with a number and contains information next to it which I need) </p>
<blockquote>
<p>1 325315</p>
<p>2 234265</p>
<p>3 345345</p>
<p>4 234234</p>
<p>5 373432</p>
<p>6 436721 </p>
<p>7 325262</p>
<p>8 235268</p>
</blockquote>
<p>How would I go about extracting the lines that are after number 3 and before number 6 for example? While keeping the other data that is held on the same line.</p>
<p>I have a very large text file ~1000 lines, which I need to extract the lines starting with 300 through to 800. Either extract or remove the lines that I do not need, either way is ok.</p>
<p>Thanks for any help</p>
| 0 |
2016-09-22T10:53:14Z
| 39,637,691 |
<p>Do like this.</p>
<pre><code>l = [line for line in (open('xyz.txt','r')).readlines() if int(line.split()[0]) > 3 and int(line.split()[0]) < 6 ]
</code></pre>
<p>Output:(Output will be lines between 3 and 6)</p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
['4 234234\n', '5 373432\n']
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 0 |
2016-09-22T11:23:56Z
|
[
"python",
"text"
] |
extracting a set amount of lines from a Text file - Python
| 39,637,063 |
<p>let us imagine I have a text file with the following inside of it: (each line starts with a number and contains information next to it which I need) </p>
<blockquote>
<p>1 325315</p>
<p>2 234265</p>
<p>3 345345</p>
<p>4 234234</p>
<p>5 373432</p>
<p>6 436721 </p>
<p>7 325262</p>
<p>8 235268</p>
</blockquote>
<p>How would I go about extracting the lines that are after number 3 and before number 6 for example? While keeping the other data that is held on the same line.</p>
<p>I have a very large text file ~1000 lines, which I need to extract the lines starting with 300 through to 800. Either extract or remove the lines that I do not need, either way is ok.</p>
<p>Thanks for any help</p>
| 0 |
2016-09-22T10:53:14Z
| 39,637,791 |
<p>Assuming the indexes are not sequential</p>
<pre><code>outList=[]
with open('somefile') as f:
for line in f:
a=line.split()
if 3<int(a[0])<6:
outlist.append(a[1]) # or append(line), append(a) depending on needs
</code></pre>
<p>Or just use <code>numpy.loadtxt</code> and use array methods.</p>
| 0 |
2016-09-22T11:29:46Z
|
[
"python",
"text"
] |
python leading and trailing underscores in user defined functions
| 39,637,164 |
<p>How can i used the rt function, as i understand leading & trailing underscores <code>__and__()</code> is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,</p>
<pre><code>class A(object):
def __rt__(self,r):
return "Yes special functions"
a=A()
print dir(a)
print a.rt('1') # AttributeError: 'A' object has no attribute 'rt'
</code></pre>
<p>But</p>
<pre><code>class Room(object):
def __init__(self):
self.people = []
def add(self, person):
self.people.append(person)
def __len__(self):
return len(self.people)
room = Room()
room.add("Igor")
print len(room) #prints 1
</code></pre>
| 1 |
2016-09-22T10:58:28Z
| 39,637,203 |
<p>Because there are builtin methods that you can overriden and then you can use them, ex <code>__len__</code> -> <code>len()</code>, <code>__str__</code> -> <code>str()</code> and etc.</p>
<p>Here is the <a href="https://docs.python.org/3/reference/datamodel.html#basic-customization" rel="nofollow">list of these functions</a></p>
<blockquote>
<p>The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of x.name) for class instances.</p>
</blockquote>
| 1 |
2016-09-22T11:00:54Z
|
[
"python"
] |
python leading and trailing underscores in user defined functions
| 39,637,164 |
<p>How can i used the rt function, as i understand leading & trailing underscores <code>__and__()</code> is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,</p>
<pre><code>class A(object):
def __rt__(self,r):
return "Yes special functions"
a=A()
print dir(a)
print a.rt('1') # AttributeError: 'A' object has no attribute 'rt'
</code></pre>
<p>But</p>
<pre><code>class Room(object):
def __init__(self):
self.people = []
def add(self, person):
self.people.append(person)
def __len__(self):
return len(self.people)
room = Room()
room.add("Igor")
print len(room) #prints 1
</code></pre>
| 1 |
2016-09-22T10:58:28Z
| 39,637,230 |
<p>Python doesn't translate one name into another. Specific operations will <em>under the covers</em> call a <code>__special_method__</code> if it has been defined. For example, the <code>__and__</code> method is called by Python to hook into the <code>&</code> operator, because the Python interpreter <em>explicitly looks for that method</em> and documented how it should be used.</p>
<p>In other words, calling <code>object.rt()</code> is not translated to <code>object.__rt__()</code> anywhere, not automatically.</p>
<p>Note that Python <em>reserves</em> such names; future versions of Python may use that name for a specific purpose and then your existing code using a <code>__special_method__</code> name for your own purposes would break.</p>
<p>From the <a href="https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers" rel="nofollow"><em>Reserved classes of identifiers</em> section</a>:</p>
<blockquote>
<p><code>__*__</code><br>
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the <a href="https://docs.python.org/3/reference/datamodel.html#specialnames" rel="nofollow">Special method names</a> section and elsewhere. More will likely be defined in future versions of Python. Any use of <code>__*__</code> names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.</p>
</blockquote>
<p>You can ignore that advice of course. In that case, you'll have to write code that actually <em>calls your method</em>:</p>
<pre><code>class SomeBaseClass:
def rt(self):
"""Call the __rt__ special method"""
try:
return self.__rt__()
except AttributeError:
raise TypeError("The object doesn't support this operation")
</code></pre>
<p>and subclass from <code>SomeBaseClass</code>.</p>
<p>Again, Python won't automatically call your new methods. You still need to actually write such code.</p>
| 3 |
2016-09-22T11:02:13Z
|
[
"python"
] |
How do i read multiple json objects in django using POST method
| 39,637,305 |
<p>I am sending multiple json object to server and django views how to get this multiple json objects and extracting each key value.</p>
| 0 |
2016-09-22T11:05:35Z
| 39,637,315 |
<pre><code><html>
<head>
<link rel="stylesheet" href='/static/js/file.txt' type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.get('static/js/file.txt', function (data) {
var lines = data.split("\n");
var dict = {};
$.each(lines, function (n, elem) {
var fields = elem.split("\t");
var service_id = fields[0];
dict[fields[0]] = {'owner':fields[1],'email':fields[2],'phone':fields[3],
'model':fields[4],'date':fields[5],'problem':fields[6]};
});
var jsonObj = JSON.stringify(dict);
//console.log(dict);
$.ajax({
type: 'POST',
url: 'load/data/',
dataType: 'json',
data: {simple:jsonObj,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()},
contentType: 'application/json',
success: function (json) {
$("#simple").append("<p>" + json + "</p>");
}
});
});
});
</script>
</head>
<div id ="simple"></div>
</html>
</code></pre>
| 0 |
2016-09-22T11:06:10Z
|
[
"javascript",
"jquery",
"python",
"html",
"django"
] |
How do I prevent `format()` from inserting newlines in my string?
| 39,637,407 |
<p>It might be my mistake, but <code>cmd = 'program {} {}'.format(arg1, arg2)</code> will always get a newline between the two args... like this
<code>program 1\n2</code></p>
<p>what should i do to put them in one line (<code>cmd</code> need to be passed to system shell)?</p>
| -1 |
2016-09-22T11:10:22Z
| 39,637,460 |
<p><code>arg1</code> contains <code>\n</code>. Use <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow">strip()</a></p>
<pre><code>cmd = 'program {} {}'.format(arg1.strip(), arg2.strip())
</code></pre>
| 3 |
2016-09-22T11:12:57Z
|
[
"python",
"string-formatting"
] |
Convert 1D object numpy array of lists to 2D numeric array and back
| 39,637,486 |
<p>Say I have this object array containing lists of the same length:</p>
<pre><code>>>> a = np.empty(2, dtype=object)
>>> a[0] = [1, 2, 3, 4]
>>> a[1] = [5, 6, 7, 8]
>>> a
array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
</code></pre>
<ol>
<li><p>How can I convert this to a numeric 2D array?</p>
<pre><code>>>> a.shape
(2,)
>>> b = WHAT_GOES_HERE(a)
>>> b
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> b.shape
(2, 4)
</code></pre></li>
<li><p>How can I do the reverse?</p></li>
<li><p>Does it get easier if my <code>a</code> array is an <code>np.array</code> of <code>np.array</code>s, rather than an <code>np.array</code> of <code>list</code>s?</p>
<pre><code>>>> na = np.empty(2, dtype=object)
>>> na[0] = np.array([1, 2, 3, 4])
>>> na[1] = np.array([5, 6, 7, 8])
>>> na
array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object)
</code></pre></li>
</ol>
| 2 |
2016-09-22T11:14:01Z
| 39,637,586 |
<p>One approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>np.concatenate</code></a> -</p>
<pre><code>b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))
</code></pre>
<p>The improvement suggest by <code>@Eric</code> to use <code>*np.shape(a[0])</code> should make it work for generic <code>ND</code> shapes.</p>
<p>Sample run -</p>
<pre><code>In [183]: a
Out[183]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
In [184]: a.shape
Out[184]: (2,)
In [185]: b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))
In [186]: b
Out[186]:
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
In [187]: b.shape
Out[187]: (2, 4)
</code></pre>
<hr>
<p>To get back <code>a</code>, it seems we can use a two-step process, like so -</p>
<pre><code>a_back = np.empty(b.shape[0], dtype=object)
a_back[:] = b.tolist()
</code></pre>
<p>Sample run -</p>
<pre><code>In [190]: a_back = np.empty(b.shape[0], dtype=object)
...: a_back[:] = b.tolist()
...:
In [191]: a_back
Out[191]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
In [192]: a_back.shape
Out[192]: (2,)
</code></pre>
| 3 |
2016-09-22T11:19:17Z
|
[
"python",
"numpy"
] |
Convert 1D object numpy array of lists to 2D numeric array and back
| 39,637,486 |
<p>Say I have this object array containing lists of the same length:</p>
<pre><code>>>> a = np.empty(2, dtype=object)
>>> a[0] = [1, 2, 3, 4]
>>> a[1] = [5, 6, 7, 8]
>>> a
array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
</code></pre>
<ol>
<li><p>How can I convert this to a numeric 2D array?</p>
<pre><code>>>> a.shape
(2,)
>>> b = WHAT_GOES_HERE(a)
>>> b
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> b.shape
(2, 4)
</code></pre></li>
<li><p>How can I do the reverse?</p></li>
<li><p>Does it get easier if my <code>a</code> array is an <code>np.array</code> of <code>np.array</code>s, rather than an <code>np.array</code> of <code>list</code>s?</p>
<pre><code>>>> na = np.empty(2, dtype=object)
>>> na[0] = np.array([1, 2, 3, 4])
>>> na[1] = np.array([5, 6, 7, 8])
>>> na
array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object)
</code></pre></li>
</ol>
| 2 |
2016-09-22T11:14:01Z
| 39,637,610 |
<p>You canuse np.vstack():</p>
<pre><code>>>> a = np.vstack(a).astype(int)
</code></pre>
| 1 |
2016-09-22T11:20:25Z
|
[
"python",
"numpy"
] |
Convert 1D object numpy array of lists to 2D numeric array and back
| 39,637,486 |
<p>Say I have this object array containing lists of the same length:</p>
<pre><code>>>> a = np.empty(2, dtype=object)
>>> a[0] = [1, 2, 3, 4]
>>> a[1] = [5, 6, 7, 8]
>>> a
array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
</code></pre>
<ol>
<li><p>How can I convert this to a numeric 2D array?</p>
<pre><code>>>> a.shape
(2,)
>>> b = WHAT_GOES_HERE(a)
>>> b
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> b.shape
(2, 4)
</code></pre></li>
<li><p>How can I do the reverse?</p></li>
<li><p>Does it get easier if my <code>a</code> array is an <code>np.array</code> of <code>np.array</code>s, rather than an <code>np.array</code> of <code>list</code>s?</p>
<pre><code>>>> na = np.empty(2, dtype=object)
>>> na[0] = np.array([1, 2, 3, 4])
>>> na[1] = np.array([5, 6, 7, 8])
>>> na
array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object)
</code></pre></li>
</ol>
| 2 |
2016-09-22T11:14:01Z
| 39,637,657 |
<p>Here's an approach that converts the source NumPy array to lists and then into the desired NumPy array:</p>
<pre><code>b = np.array([k for k in a])
b
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
c = np.array([k for k in b], dtype=object)
c
array([[1, 2, 3, 4],
[5, 6, 7, 8]], dtype=object)
</code></pre>
| 0 |
2016-09-22T11:22:20Z
|
[
"python",
"numpy"
] |
Convert 1D object numpy array of lists to 2D numeric array and back
| 39,637,486 |
<p>Say I have this object array containing lists of the same length:</p>
<pre><code>>>> a = np.empty(2, dtype=object)
>>> a[0] = [1, 2, 3, 4]
>>> a[1] = [5, 6, 7, 8]
>>> a
array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
</code></pre>
<ol>
<li><p>How can I convert this to a numeric 2D array?</p>
<pre><code>>>> a.shape
(2,)
>>> b = WHAT_GOES_HERE(a)
>>> b
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> b.shape
(2, 4)
</code></pre></li>
<li><p>How can I do the reverse?</p></li>
<li><p>Does it get easier if my <code>a</code> array is an <code>np.array</code> of <code>np.array</code>s, rather than an <code>np.array</code> of <code>list</code>s?</p>
<pre><code>>>> na = np.empty(2, dtype=object)
>>> na[0] = np.array([1, 2, 3, 4])
>>> na[1] = np.array([5, 6, 7, 8])
>>> na
array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object)
</code></pre></li>
</ol>
| 2 |
2016-09-22T11:14:01Z
| 39,637,667 |
<p>I found that round-tripping through <code>list</code> with <code>np.array(list(a))</code> was sufficient.</p>
<p>This seems to be equivalent to using <code>np.stack(a)</code>.</p>
<p>Both of these have the benefit of working in the more general case of converting a 1D array of ND arrays into an (N+1)D array.</p>
| 0 |
2016-09-22T11:22:46Z
|
[
"python",
"numpy"
] |
Python - Tkinter - Label Not Updating
| 39,637,493 |
<p>Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change. </p>
<pre><code>from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
read.set(1)
total.set(1)
left.set(1)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
def func1():
left.set(total.get() - read.get())
print(left.get())
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)
root.mainloop()
</code></pre>
| 0 |
2016-09-22T11:14:17Z
| 39,638,316 |
<p>To make the function do the job, you'd rather have your label:</p>
<pre><code>leftresult_label = Label(root, textvariable=left)
</code></pre>
<p>Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,</p>
<pre><code>def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
</code></pre>
<p>left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.</p>
<p>Here is full code:</p>
<pre><code>from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
read.set(1)
total.set(1)
left.set(1)
percent.set(1)
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
</code></pre>
| 1 |
2016-09-22T11:53:19Z
|
[
"python",
"tkinter",
"label"
] |
How verify function implemented?
| 39,637,629 |
<p>I want to find how <code>verify()</code> function from <code>Pillow</code> library implemented. In a source code i found only this:</p>
<pre><code>def verify(self):
"""
Verifies the contents of a file. For data read from a file, this
method attempts to determine if the file is broken, without
actually decoding the image data. If this method finds any
problems, it raises suitable exceptions. If you need to load
the image after using this method, you must reopen the image
file.
"""
pass
</code></pre>
<p>Where i can find implementation?</p>
<p>(source code i found here: <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/Image.html#Image.verify" rel="nofollow">Pillow source code</a> )</p>
| 0 |
2016-09-22T11:21:17Z
| 39,640,274 |
<p>A <a href="https://github.com/python-pillow/Pillow/issues/1408#issuecomment-139024840" rel="nofollow">comment on GitHub</a> explains:</p>
<blockquote>
<p>Image.[v]erify only checks the chunk checksums in png files, and is a no-op elsewhere.</p>
</blockquote>
<p>So the short answer is that you already did find the default implementation which does absolutely nothing.</p>
<p><strong>Except for PNG files</strong>, for which you can find the implementation in the <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/PngImagePlugin.html#PngImageFile.verify" rel="nofollow"><code>PngImageFile.verify</code></a> method:</p>
<pre class="lang-python prettyprint-override"><code> def verify(self):
"Verify PNG file"
if self.fp is None:
raise RuntimeError("verify must be called directly after open")
# back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8)
self.png.verify()
self.png.close()
self.fp = None
</code></pre>
<p>which in turn through <code>self.png.verify()</code> calls <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/PngImagePlugin.html#ChunkStream.verify" rel="nofollow"><code>ChunkStream.verify</code></a>:</p>
<pre class="lang-python prettyprint-override"><code> def verify(self, endchunk=b"IEND"):
# Simple approach; just calculate checksum for all remaining
# blocks. Must be called directly after open.
cids = []
while True:
cid, pos, length = self.read()
if cid == endchunk:
break
self.crc(cid, ImageFile._safe_read(self.fp, length))
cids.append(cid)
return cids
</code></pre>
<h2>More detailed source code breakdown</h2>
<p>Your already quoted code for the <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/Image.html#Image.verify" rel="nofollow"><code>verify</code></a> method of the <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/Image.html#Image" rel="nofollow"><code>Image</code></a> class shows that it by default does nothing:</p>
<pre class="lang-python prettyprint-override"><code>class Image:
...
def verify(self):
"""
Verifies the contents of a file. For data read from a file, this
method attempts to determine if the file is broken, without
actually decoding the image data. If this method finds any
problems, it raises suitable exceptions. If you need to load
the image after using this method, you must reopen the image
file.
"""
pass
</code></pre>
<p>But in the case of PNG files the default <code>verify</code> method is overridden, as seen from the source code for the <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/ImageFile.html" rel="nofollow"><code>ImageFile</code></a> class, which inherits from the <code>Image</code> class:</p>
<pre class="lang-python prettyprint-override"><code>class ImageFile(Image.Image):
"Base class for image file format handlers."
...
</code></pre>
<p>and the source code for the PNG plugin class <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/PngImagePlugin.html#PngImageFile" rel="nofollow"><code>PngImageFile</code></a> which inherits from <code>ImageFile</code>:</p>
<pre class="lang-python prettyprint-override"><code>##
# Image plugin for PNG images.
class PngImageFile(ImageFile.ImageFile):
...
</code></pre>
<p>and has this overridden implementation of <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/PngImagePlugin.html#PngImageFile.verify" rel="nofollow"><code>verify</code></a>:</p>
<pre class="lang-python prettyprint-override"><code> def verify(self):
"Verify PNG file"
if self.fp is None:
raise RuntimeError("verify must be called directly after open")
# back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8)
self.png.verify()
self.png.close()
self.fp = None
</code></pre>
<p>which in turn through <code>self.png.verify()</code> calls <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/PngImagePlugin.html#ChunkStream.verify" rel="nofollow"><code>ChunkStream.verify</code></a>:</p>
<pre class="lang-python prettyprint-override"><code> def verify(self, endchunk=b"IEND"):
# Simple approach; just calculate checksum for all remaining
# blocks. Must be called directly after open.
cids = []
while True:
cid, pos, length = self.read()
if cid == endchunk:
break
self.crc(cid, ImageFile._safe_read(self.fp, length))
cids.append(cid)
return cids
</code></pre>
<p>through the <a href="https://pillow.readthedocs.io/en/3.0.0/_modules/PIL/PngImagePlugin.html#PngStream" rel="nofollow"><code>PngStream</code></a> class which doesn't override <code>verify</code>:</p>
<pre class="lang-python prettyprint-override"><code>class PngStream(ChunkStream):
...
</code></pre>
| 1 |
2016-09-22T13:21:56Z
|
[
"python",
"pillow"
] |
Jinja range raises TemplateSyntaxError in Django view
| 39,637,677 |
<p>In a django jinja2 tempate with the code</p>
<pre><code>{% for i in range(10) %}
foo {{ i }}<br>
{% endfor %}
</code></pre>
<p>a <code>TemplateSyntaxError</code> is raised with the error message</p>
<blockquote>
<p>Could not parse the remainder: '(10)' from 'range(10)'</p>
</blockquote>
<p>What do I need to do in order to loop over a <a href="http://jinja.pocoo.org/docs/dev/templates/#range" rel="nofollow">range</a> in a jinja2 template.</p>
<p>I found a <a href="https://docs.djangoproject.com/en/1.8/ref/templates/language/#accessing-method-calls" rel="nofollow">link</a> in the django documentation explaining that </p>
<blockquote>
<p>Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display.</p>
</blockquote>
<p>but I don't think that this applies to the range function.</p>
| -2 |
2016-09-22T11:23:23Z
| 39,647,252 |
<p>Django is not using Jinja2, but the Django template language. There is no range function in the Django template language.</p>
| 0 |
2016-09-22T19:19:35Z
|
[
"python",
"django",
"range",
"jinja2"
] |
how to iterate through a json that has multiple pages
| 39,637,713 |
<p>I have created a program that iterates through a multi-page json object.</p>
<pre><code>def get_orgs(token,url):
part1 = 'curl -i -k -X GET -H "Content-Type:application/json" -H "Authorization:Bearer '
final_url = part1 + token + '" ' + url
pipe = subprocess.Popen(final_url, shell=False,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
data = pipe.communicate()[0]
for line in data.split('\n'):
print line
try:
row = json.loads(line)
print ("next page url ",row['next'])
except :
pass
return row
my_data = get_orgs(u'MyBeearerToken',"https://data.ratings.com/v1.0/org/576/portfolios/36/companies/")
</code></pre>
<p>The json object is as below:</p>
<pre><code>[{results: [{"liquidity":"Strong","earningsPerformance":"Average"}]
,"next":"https://data.ratings.com/v1.0/org/576/portfolios/36/companies/?page=2"}]
</code></pre>
<p>I am using 'next' key to iterate,but at times it points to "Invalid Page" ( a page that doesn't exist). Does JSON object have a rule about how many records are there on each page ? In that case , I will use that to estimate how many pages are possible.</p>
<p>EDIT: Adding more details
The json has just 2 keys ['results','next']. If there are multiple pages, then the 'next' key has the next page's url (<code>as you can see in the output above</code>). Else , it contains 'None'.
But, problem is that at times, instead of 'None' , it points to the next page (which does not exist). So, I want to see if I can count the rows in Json and divide by a number to know how many pages the loop needs to iterate through.</p>
| 0 |
2016-09-22T11:25:15Z
| 39,645,162 |
<p>In my opinion using urllib2 or urllib.request would be a much better option than curl in order to make the code easier to understand, but if that's a constraint - I can work with that ;-)</p>
<p>Assuming the json-response is all in one line (Otherwise your json.loads will throw an Exception), the task is pretty simple and this will allow you to fetch the amount of items behind the result key:</p>
<pre><code>row = [{'next': 'https://data.ratings.com/v1.0/org/576/portfolios/36/companies/?page=2', 'results': [{'earningsPerformance':'Average','liquidity': 'Strong'}, {'earningsPerformance':'Average','liquidity': 'Strong'}]}]
result_count = len(row[0]["results"])
</code></pre>
<p>The alternative solution using httplib2 should look something like this (I didn't test this):</p>
<pre><code>import httplib2
import json
h = httplib2.Http('.cache')
url = "https://data.ratings.com/v1.0/org/576/portfolios/36/companies/"
token = "Your_token"
try:
response, content = h.request(
url,
headers = {'Content-Type': 'application/json', 'Authorization:Bearer': token}
)
# Convert the response to a string
content = content.decode('utf-8') # You could get the charset from the header as well
try:
object = json.loads(content)
result_count = len(object[0]["results"])
# Yay, we got the result count!
except Exception:
# Do something if the server responds with garbage
pass
except httplib2.HttpLib2Error:
# Handle the exceptions, here's a list: https://httplib2.readthedocs.io/en/latest/libhttplib2.html#httplib2.HttpLib2Error
pass
</code></pre>
<p>For more on httplib2 and why its amazing I suggest reading <a href="http://www.diveintopython3.net/http-web-services.html#introducing-httplib2" rel="nofollow">Dive Into Python</a>.</p>
| 0 |
2016-09-22T17:18:33Z
|
[
"python",
"json"
] |
I keep getting this error and I dont know hove to fix it
| 39,637,744 |
<p>I open the file but is saying the file is not open. I stuck on what to do . I am new to python.</p>
<p>Here is the error:</p>
<pre><code>Traceback (most recent call last):
File "\\users2\121721$\Computer Science\Progamming\task3.py", line 43, in <module>
file.write(barcode + ":" + item + ":" + price + ":" +str(int((StockLevel- float(HowMany)))))
ValueError: I/O operation on closed file.
</code></pre>
<p>Here is the code:</p>
<pre><code>#open a file in read mode
file = open("data.txt","r")
#read each line of data to a vairble
FileData = file.readlines()
#close the file
file.close()
total = 0 #create the vairble total
AnotherItem = "y" # create
while AnotherItem == "y" or AnotherItem == "Y" or AnotherItem == "yes" or AnotherItem == "Yes" or AnotherItem == "YES":
print("please enter the barcode")
UsersItem=input()
for line in FileData:
#split the line in to first and second section
barcode = line.split(":")[0]
item = line.split(":")[1]
price = line.split(":")[2]
stock = line.split(":")[3]
if barcode==UsersItem:
file = open("data.txt","r")
#read each line of data to a vairble
FileData = file.readlines()
#close the file
file.close()
print(item +" £" + str(float(price)/100) + " Stock: " + str(stock))
print("how many do you want to buy")
HowMany= input()
total+=float(price) * float( HowMany)
for line in FileData:
#split the line in to first and second section
barcode = line.split(":")[0]
item = line.split(":")[1]
price = line.split(":")[2]
stock = line.split(":")[3]
if barcode!=UsersItem:
open("data.txt","w")
file.write(barcode + ":" + item + ":" + price + ":" +stock)
file.close()
else:
StockLevel=int(stock)
open("data.txt","w")
file.write(barcode + ":" + item + ":" + price + ":" +str(int((StockLevel-float(HowMany)))))
file.close()
open("data.txt","w")
StockLevel=int(stock)
print("Do you want to buy another item? [Yes/No]")
AnotherItem = input()
if AnotherItem == "n" or "N" or "no" or "No" or "NO":
print("total price: £"+ str(total/100))
</code></pre>
| 0 |
2016-09-22T11:27:07Z
| 39,637,778 |
<p>There is </p>
<pre><code>if barcode!=UsersItem:
open("data.txt","w")
</code></pre>
<p>You need to </p>
<pre><code>if barcode!=UsersItem:
file = open("data.txt","w")
</code></pre>
<p>Also the same error you have in <code>else</code> statement.</p>
<p>And you should also consider refactoring your code, because you have a lot of file openings and closings.</p>
<p><em>Edit</em>: as @roganjosh mentioned <code>file</code> is a builtin name in Python 2, so you'd better change all occurrences of <code>file</code> to e.g. <code>f</code>.</p>
| 3 |
2016-09-22T11:29:02Z
|
[
"python"
] |
Can lambda be used instead of a method, as a key in sorted()?
| 39,637,810 |
<p>This is my first time asking a question. I've already got so much help from you without even asking. (Gratitude face).
So, I found this useful piece of code from around here a few weeks ago.</p>
<pre><code>import re
def yearly_sort(value):
numbers = re.compile(r'(\d+)')
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
</code></pre>
<p>It works perfectly here:</p>
<pre><code>def get_files_sorted(path_to_dir):
file_names = []
for root, dirs, files in os.walk(path_to_dir):
for file_name in sorted(files, key=yearly_sort):
file_names.append(os.path.join(root, file_name))
return file_names
</code></pre>
<p>Now, I'm facing a problem describing the above function (as you can already see from a non-descriptive method name).</p>
<p>What should be the name of above method (instead of some_sort())?</p>
<p>Can this method be squeezed somehow in a lambda such that <strong>key</strong> in the sorted() can bind to key=lambda?</p>
| 0 |
2016-09-22T11:30:41Z
| 39,637,974 |
<p>It definitely can be <code>lambda</code> function. For example look at that <a href="http://stackoverflow.com/questions/3766633/how-to-sort-with-lambda-in-python">question</a>.</p>
<p>But if you have complex function you should never move it to <code>lambda</code> because readability significantly decreases.</p>
<p>So here is <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Python</a></p>
<blockquote>
<p>Complex is better than complicated.</p>
</blockquote>
| 2 |
2016-09-22T11:38:29Z
|
[
"python",
"python-3.x",
"lambda"
] |
Can lambda be used instead of a method, as a key in sorted()?
| 39,637,810 |
<p>This is my first time asking a question. I've already got so much help from you without even asking. (Gratitude face).
So, I found this useful piece of code from around here a few weeks ago.</p>
<pre><code>import re
def yearly_sort(value):
numbers = re.compile(r'(\d+)')
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
</code></pre>
<p>It works perfectly here:</p>
<pre><code>def get_files_sorted(path_to_dir):
file_names = []
for root, dirs, files in os.walk(path_to_dir):
for file_name in sorted(files, key=yearly_sort):
file_names.append(os.path.join(root, file_name))
return file_names
</code></pre>
<p>Now, I'm facing a problem describing the above function (as you can already see from a non-descriptive method name).</p>
<p>What should be the name of above method (instead of some_sort())?</p>
<p>Can this method be squeezed somehow in a lambda such that <strong>key</strong> in the sorted() can bind to key=lambda?</p>
| 0 |
2016-09-22T11:30:41Z
| 39,638,008 |
<p>you could squeeze it into a lambda provided that <code>numbers</code> is previously compiled (which increases performance)</p>
<pre><code>numbers = re.compile(r'(\d+)')
for file_name in sorted(files, key=lambda value : [int(x) if x.isdigit() else 0 for x in numbers.split(value)][1::2]):
</code></pre>
<p>In that case, we do an unnecessary test for items #0 and #3 onwards. Maybe it could be better, but that's the risk with complex lambdas: performance & lisibility can suffer.</p>
| 0 |
2016-09-22T11:40:02Z
|
[
"python",
"python-3.x",
"lambda"
] |
Blackjack Game - displaying ASCII Graphics / Multiline Strings
| 39,637,848 |
<p>I'm pretty new to Python and currently trying to create a basic blackjack game using ASCII graphics to represent the cards. I've placed the card images in a list of multiline strings and the idea is to call the specific index for each one when a card needs to be displayed. </p>
<p>However I can't get them to print next to each other, and no amount of tinkering seems to get it to work. Here's the code: </p>
<pre><code>CARDS = ['''
-------
|K |
| |
| |
| |
| K|
------- ''', '''
-------
|Q |
| |
| |
| |
| Q|
------- ''', '''
-------
|J |
| |
| |
| |
| J|
------- ''', '''
-------
|10 |
| |
| |
| |
| 10|
------- ''', '''
-------
|9 |
| |
| |
| |
| 9|
------- ''', '''
-------
|8 |
| |
| |
| |
| 8|
------- ''', '''
-------
|7 |
| |
| |
| |
| 7|
------- ''', '''
-------
|6 |
| |
| |
| |
| 6|
------- ''', '''
-------
|5 |
| |
| |
| |
| 5|
------- ''', '''
-------
|6 |
| |
| |
| |
| 6|
------- ''', '''
-------
|5 |
| |
| |
| |
| 5|
------- ''', '''
-------
|4 |
| |
| |
| |
| 4|
------- ''', '''
-------
|3 |
| |
| |
| |
| 3|
------- ''', '''
-------
|2 |
| |
| |
| |
| 2|
------- ''', '''
-------
|A |
| |
| |
| |
| A|
------- '''
]
BLANKCARD = '''
-------
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
------- '''
def displayCards():
print(CARDS[2] + CARDS[14], end='')
displayCards()
</code></pre>
<p>The above code prints the following:</p>
<pre><code> -------
|J |
| |
| |
| |
| J|
-------
-------
|A |
| |
| |
| |
| A|
-------
</code></pre>
<p>I've tried using end='' to get rid of the new line, but no joy. Does anyone have any suggestions about how I can get the cards next to each other?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-22T11:32:26Z
| 39,637,958 |
<p>With the way you're doing it, that would be very difficult. When you write</p>
<pre><code>end=''
</code></pre>
<p>That only gets rid of the newline at the very end of the printed text. The problem is, every one of your cards has a new line on the right side:</p>
<pre><code> -------
|J |
| |
| | # <--- Newline here
| |
| J|
-------
</code></pre>
<p>You would need to create a function that takes a list of cards, and creates one long line of them. That will be a solid project in its own. You would have to take the strings that make up the cards, cut them into lines (cut on each new line), place all the corresponding lines together, getting rid of the newlines in between, then glue all the pieces together. I might actually try this for a morning project now. </p>
<p>And instead of hard coding all the cards like you have, create a function that you give a card value to, and it creates a card for you.</p>
| 2 |
2016-09-22T11:37:30Z
|
[
"python",
"python-3.x"
] |
Blackjack Game - displaying ASCII Graphics / Multiline Strings
| 39,637,848 |
<p>I'm pretty new to Python and currently trying to create a basic blackjack game using ASCII graphics to represent the cards. I've placed the card images in a list of multiline strings and the idea is to call the specific index for each one when a card needs to be displayed. </p>
<p>However I can't get them to print next to each other, and no amount of tinkering seems to get it to work. Here's the code: </p>
<pre><code>CARDS = ['''
-------
|K |
| |
| |
| |
| K|
------- ''', '''
-------
|Q |
| |
| |
| |
| Q|
------- ''', '''
-------
|J |
| |
| |
| |
| J|
------- ''', '''
-------
|10 |
| |
| |
| |
| 10|
------- ''', '''
-------
|9 |
| |
| |
| |
| 9|
------- ''', '''
-------
|8 |
| |
| |
| |
| 8|
------- ''', '''
-------
|7 |
| |
| |
| |
| 7|
------- ''', '''
-------
|6 |
| |
| |
| |
| 6|
------- ''', '''
-------
|5 |
| |
| |
| |
| 5|
------- ''', '''
-------
|6 |
| |
| |
| |
| 6|
------- ''', '''
-------
|5 |
| |
| |
| |
| 5|
------- ''', '''
-------
|4 |
| |
| |
| |
| 4|
------- ''', '''
-------
|3 |
| |
| |
| |
| 3|
------- ''', '''
-------
|2 |
| |
| |
| |
| 2|
------- ''', '''
-------
|A |
| |
| |
| |
| A|
------- '''
]
BLANKCARD = '''
-------
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
------- '''
def displayCards():
print(CARDS[2] + CARDS[14], end='')
displayCards()
</code></pre>
<p>The above code prints the following:</p>
<pre><code> -------
|J |
| |
| |
| |
| J|
-------
-------
|A |
| |
| |
| |
| A|
-------
</code></pre>
<p>I've tried using end='' to get rid of the new line, but no joy. Does anyone have any suggestions about how I can get the cards next to each other?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-22T11:32:26Z
| 39,638,485 |
<p>I suggest you write a function that, given i and n, returns a string which represents line i of card n. You can then call that in a double nested loop, printing the results in sequence, to get the result you need.
You can start by making an example of the output you want to see, to use as a reference while coding the loop.</p>
| 2 |
2016-09-22T12:01:06Z
|
[
"python",
"python-3.x"
] |
Blackjack Game - displaying ASCII Graphics / Multiline Strings
| 39,637,848 |
<p>I'm pretty new to Python and currently trying to create a basic blackjack game using ASCII graphics to represent the cards. I've placed the card images in a list of multiline strings and the idea is to call the specific index for each one when a card needs to be displayed. </p>
<p>However I can't get them to print next to each other, and no amount of tinkering seems to get it to work. Here's the code: </p>
<pre><code>CARDS = ['''
-------
|K |
| |
| |
| |
| K|
------- ''', '''
-------
|Q |
| |
| |
| |
| Q|
------- ''', '''
-------
|J |
| |
| |
| |
| J|
------- ''', '''
-------
|10 |
| |
| |
| |
| 10|
------- ''', '''
-------
|9 |
| |
| |
| |
| 9|
------- ''', '''
-------
|8 |
| |
| |
| |
| 8|
------- ''', '''
-------
|7 |
| |
| |
| |
| 7|
------- ''', '''
-------
|6 |
| |
| |
| |
| 6|
------- ''', '''
-------
|5 |
| |
| |
| |
| 5|
------- ''', '''
-------
|6 |
| |
| |
| |
| 6|
------- ''', '''
-------
|5 |
| |
| |
| |
| 5|
------- ''', '''
-------
|4 |
| |
| |
| |
| 4|
------- ''', '''
-------
|3 |
| |
| |
| |
| 3|
------- ''', '''
-------
|2 |
| |
| |
| |
| 2|
------- ''', '''
-------
|A |
| |
| |
| |
| A|
------- '''
]
BLANKCARD = '''
-------
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
|XXXXXXX|
------- '''
def displayCards():
print(CARDS[2] + CARDS[14], end='')
displayCards()
</code></pre>
<p>The above code prints the following:</p>
<pre><code> -------
|J |
| |
| |
| |
| J|
-------
-------
|A |
| |
| |
| |
| A|
-------
</code></pre>
<p>I've tried using end='' to get rid of the new line, but no joy. Does anyone have any suggestions about how I can get the cards next to each other?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-22T11:32:26Z
| 39,640,926 |
<p>Interesting little problem. Here's a quick solution that I whipped up.</p>
<p><code>class Card:</code></p>
<pre><code>def topchar(char):
return '|{} |'.format(char)
def botchar(char):
return '| {}|'.format(char)
def print(char_list):
top = ' ------- '
side ='| |'
topout = ''
topchar = ''
botchar = ''
blankside = ''
for char in char_list:
topout += top + ' '
topchar += Card.topchar(char) + ' '
blankside += side + ' '
botchar += Card.botchar(char) + ' '
print(topout)
print(topchar)
print(blankside)
print(blankside)
print(blankside)
print(botchar)
print(topout)
</code></pre>
| 1 |
2016-09-22T13:49:30Z
|
[
"python",
"python-3.x"
] |
How to remove everything after the last number in a string
| 39,637,955 |
<p>I have strings like this:</p>
<pre><code>w = 'w123 o456 t789-- --'
</code></pre>
<p>My goal is to remove everything after the last number, so my desired output would be</p>
<pre><code>w123 o456 t789
</code></pre>
<p>It is not always the same ending, so <code>-- --</code> is just one example.</p>
<pre><code>import re
re.sub('(.*?)(\d)', '', w)
</code></pre>
<p>gives me</p>
<pre><code>'-- --'
</code></pre>
<p>How can I modify the command so that it removes this part?</p>
| 1 |
2016-09-22T11:37:21Z
| 39,637,977 |
<p>You can use:</p>
<pre><code>>>> w = 'w123 o456 t789-- --'
>>> re.sub(r'\D+$', '', w)
'w123 o456 t789'
</code></pre>
<p><code>\D+$</code> will remove 1 or more non-digit characters before end anchor <code>$</code>.</p>
| 7 |
2016-09-22T11:38:37Z
|
[
"python",
"regex"
] |
How to remove everything after the last number in a string
| 39,637,955 |
<p>I have strings like this:</p>
<pre><code>w = 'w123 o456 t789-- --'
</code></pre>
<p>My goal is to remove everything after the last number, so my desired output would be</p>
<pre><code>w123 o456 t789
</code></pre>
<p>It is not always the same ending, so <code>-- --</code> is just one example.</p>
<pre><code>import re
re.sub('(.*?)(\d)', '', w)
</code></pre>
<p>gives me</p>
<pre><code>'-- --'
</code></pre>
<p>How can I modify the command so that it removes this part?</p>
| 1 |
2016-09-22T11:37:21Z
| 39,637,986 |
<pre><code>st = 'w123 o456 t789-- --'
print st.rstrip()
"w123 o456 t789'
</code></pre>
| -1 |
2016-09-22T11:39:07Z
|
[
"python",
"regex"
] |
How to remove everything after the last number in a string
| 39,637,955 |
<p>I have strings like this:</p>
<pre><code>w = 'w123 o456 t789-- --'
</code></pre>
<p>My goal is to remove everything after the last number, so my desired output would be</p>
<pre><code>w123 o456 t789
</code></pre>
<p>It is not always the same ending, so <code>-- --</code> is just one example.</p>
<pre><code>import re
re.sub('(.*?)(\d)', '', w)
</code></pre>
<p>gives me</p>
<pre><code>'-- --'
</code></pre>
<p>How can I modify the command so that it removes this part?</p>
| 1 |
2016-09-22T11:37:21Z
| 39,638,161 |
<p>The point is that your expression contains <em>lazy</em> dot matching pattern and it matches up to and including the first one or more digits.</p>
<p>You need to use <em>greedy</em> dot matching pattern to match up to the <em>last</em> digit, and capture that part into a capturing group. Then, use a <code>r'\1'</code> backreference in the replacement pattern to restore the value in the result.</p>
<p>This will work with 1-line strings:</p>
<pre><code>re.sub(r'(.*\d).*', r'\1', w)
</code></pre>
<p>or with anchors and also supporting strings with linebreaks:</p>
<pre><code>re.sub(r'^(.*\d).*$', r'\1', w, flags=re.S)
</code></pre>
<p><a href="https://ideone.com/hX5aTY" rel="nofollow">Python demo:</a></p>
<pre><code>import re
w = 'w123 o456 t789-- --'
print(re.sub(r'^(.*\d).*$', r'\1', w, flags=re.S))
# => w123 o456 t789
</code></pre>
| 1 |
2016-09-22T11:47:06Z
|
[
"python",
"regex"
] |
Using regex, extract quoted strings that may contain nested quotes
| 39,638,172 |
<p>I have the following string:</p>
<pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'
</code></pre>
<p>Now, I wish to extract the following quotes:</p>
<pre class="lang-none prettyprint-override"><code>1. Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!
2. How Doth the Little Busy Bee,
3. I'll try again.
</code></pre>
<p>I tried the following code but I'm not getting what I want. The <code>[^\1]*</code> is not working as expected. Or is the problem elsewhere?</p>
<pre><code>import re
s = "'Well, I've tried to say \"How Doth the Little Busy Bee,\" but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'"
for i, m in enumerate(re.finditer(r'([\'"])(?!(?:ve|m|re|s|t|d|ll))(?=([^\1]*)\1)', s)):
print("\nGroup {:d}: ".format(i+1))
for g in m.groups():
print(' '+g)
</code></pre>
| 2 |
2016-09-22T11:47:43Z
| 39,640,166 |
<p>It seems difficult to achieve with juste one regex pass, but it could be done with a relatively simple regex and a recursive function:</p>
<pre><code>import re
REGEX = re.compile(r"(['\"])(.*?[!.,])\1", re.S)
S = """'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.' 'And we may now add "some more 'random test text'.":' "Yes it seems to be a good idea!" 'ok, let's go.'"""
def extract_quotes(string, quotes_list=None):
list = quotes_list or []
list += [found[1] for found in REGEX.findall(string)]
print("found: {}".format(quotes_list))
index = 0
for quote in list[:]:
index += 1
sub_list = extract_quotes(quote)
list = list[:index] + sub_list + list[index:]
index += len(sub_list)
return list
print extract_quotes(S)
</code></pre>
<p>This prints:</p>
<pre><code>['Well, I\'ve tried to say "How Doth the Little Busy Bee," but it all came different!', 'How Doth the Little Busy Bee,', "I'll try again.", 'And we may now add "some more \'random test text\'.":\' "Yes it seems to be a good idea!" \'ok, let\'s go.', "some more 'random test text'.", 'Yes it seems to be a good idea!']
</code></pre>
<p>Note that the regex uses the punctuation to determine if a quoted text is a "real quote". in order to be extracted, a quote need to be ended with a punctuation character before the closing quote. That is 'random test text' is not considered as an actual quote, while 'ok let's go.' is.</p>
<p>The regex is pretty simple, I think it does not need explanation.
Thue <code>extract_quotes</code> function find all quotes in the given string and store them in the <code>quotes_list</code>. Then, it calls itself for each found quote, looking for inner quotes...</p>
| 0 |
2016-09-22T13:16:30Z
|
[
"python",
"regex"
] |
Using regex, extract quoted strings that may contain nested quotes
| 39,638,172 |
<p>I have the following string:</p>
<pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'
</code></pre>
<p>Now, I wish to extract the following quotes:</p>
<pre class="lang-none prettyprint-override"><code>1. Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!
2. How Doth the Little Busy Bee,
3. I'll try again.
</code></pre>
<p>I tried the following code but I'm not getting what I want. The <code>[^\1]*</code> is not working as expected. Or is the problem elsewhere?</p>
<pre><code>import re
s = "'Well, I've tried to say \"How Doth the Little Busy Bee,\" but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'"
for i, m in enumerate(re.finditer(r'([\'"])(?!(?:ve|m|re|s|t|d|ll))(?=([^\1]*)\1)', s)):
print("\nGroup {:d}: ".format(i+1))
for g in m.groups():
print(' '+g)
</code></pre>
| 2 |
2016-09-22T11:47:43Z
| 39,704,186 |
<p><strong>EDIT</strong></p>
<p>I modified my regex, it match properly even more complicated cases:</p>
<pre><code>(?=(?<!\w|[!?.])('|\")(?!\s)(?P<content>(?:.(?!(?<=(?=\1).)(?!\w)))*)\1(?!\w))
</code></pre>
<p><a href="https://regex101.com/r/Q0t3Rp/1" rel="nofollow">DEMO</a></p>
<p>It is now even more complicated, the main improvement is not matching directly after some of punctuation character (<code>[!?.]</code>) and better quote case separation. Verified on diversified examples.</p>
<p>The sentence will be in <code>content</code> captured group. Of course it has some restrictions, releted to usage of whitespaces, etc. But it should work with most of proper formatted sentences - or at least it work with examples.</p>
<ul>
<li><code>(?=(?<!\w|[!?.])('|\")(?!\s)</code> - match the <code>'</code> or <code>"</code> not preceded by word or punctuation character (<code>(?<!\w|[!?.])</code>) or not fallowed by whitespace(<code>(?!\s)</code>), the <code>'</code> or <code>"</code> part is captured in group 1 to further use,</li>
<li><code>(?P<content>(?:.(?!(?<=(?=\1).)(?!\w)))*)\1(?!\w))</code> - match sentence, followed by
same char (<code>'</code> or <code>"</code> captured in group 1) as it was started, ignore other quotes</li>
</ul>
<p>It doesn't match whole sentence directly, but with capturing group nested in lookaround construct, so with global match modifier it will match also sentences inside sentences - because it directly match only the place before sentence starts.</p>
<p><strong>About your regex:</strong></p>
<p>I suppose, that by <code>[^\1]*</code> you meant any char but not one captured in group 1, but character class doesn't work this way, because it treats <code>\1</code> as an char in octal notation (which I think is some kind of whitespace) not a reference to capturing group. Take a look on <a href="https://regex101.com/r/eN7jU3/1" rel="nofollow">this example</a> - read explanation. Also compare matching of <a href="https://regex101.com/r/qF5pI5/1" rel="nofollow">THIS</a> and <a href="https://regex101.com/r/jA2dZ7/1" rel="nofollow">THIS</a> regex. </p>
<p>To achieve what you want, you should use lookaround, something like this: <a href="https://regex101.com/r/cH4fG8/1" rel="nofollow"><code>(')((?:.(?!\1))*.)</code></a> - capture the opening char, then match every char which is not followed by captured opening char, then capture one more char, which is directly before captured char - and you have whole content between chars you excluded.</p>
| 1 |
2016-09-26T13:26:53Z
|
[
"python",
"regex"
] |
Using regex, extract quoted strings that may contain nested quotes
| 39,638,172 |
<p>I have the following string:</p>
<pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'
</code></pre>
<p>Now, I wish to extract the following quotes:</p>
<pre class="lang-none prettyprint-override"><code>1. Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!
2. How Doth the Little Busy Bee,
3. I'll try again.
</code></pre>
<p>I tried the following code but I'm not getting what I want. The <code>[^\1]*</code> is not working as expected. Or is the problem elsewhere?</p>
<pre><code>import re
s = "'Well, I've tried to say \"How Doth the Little Busy Bee,\" but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'"
for i, m in enumerate(re.finditer(r'([\'"])(?!(?:ve|m|re|s|t|d|ll))(?=([^\1]*)\1)', s)):
print("\nGroup {:d}: ".format(i+1))
for g in m.groups():
print(' '+g)
</code></pre>
| 2 |
2016-09-22T11:47:43Z
| 39,706,568 |
<p>If you <em>really</em> need to return all the results from a single regular expression applied only once, it will be necessary to use lookahead (<code>(?=findme)</code>) so the finding position goes back to the start after each match - see <a href="http://stackoverflow.com/questions/869809/combine-regexp#870506">this answer</a> for a more detailed explanation.</p>
<p>To prevent false matches, some clauses are also needed regarding the quotes that add complexity, e.g. the apostrophe in <code>I've</code> shouldn't count as an opening or closing quote. There's no single clear-cut way of doing this but the rules I've gone for are:</p>
<ol>
<li>An opening quote must not be immediately preceeded by a word character (e.g. letter). So for example, <code>A"</code> would not count as an opening quote but <code>,"</code> would count.</li>
<li>A closing quote must not be immediately followed by a word character (e.g. letter). So for example, <code>'B</code> would not count as a closing quote but <code>'.</code> would count.</li>
</ol>
<p>Applying the above rules leads to the following regular expression:</p>
<pre><code>(?=(?:(?<!\w)'(\w.*?)'(?!\w)|"(\w.*?)"(?!\w)))
</code></pre>
<p><img src="http://i.stack.imgur.com/vJP88.png" alt="Regular expression visualization"></p>
<p><a href="https://regex101.com/r/vX4cL9/1" rel="nofollow">Debuggex Demo</a></p>
<p>A good quick sanity check test on any possible candidate regular expression is to reverse the quotes. This has been done in the demo here: <a href="https://regex101.com/r/vX4cL9/1" rel="nofollow">https://regex101.com/r/vX4cL9/1</a></p>
| 2 |
2016-09-26T15:18:43Z
|
[
"python",
"regex"
] |
Using regex, extract quoted strings that may contain nested quotes
| 39,638,172 |
<p>I have the following string:</p>
<pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'
</code></pre>
<p>Now, I wish to extract the following quotes:</p>
<pre class="lang-none prettyprint-override"><code>1. Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!
2. How Doth the Little Busy Bee,
3. I'll try again.
</code></pre>
<p>I tried the following code but I'm not getting what I want. The <code>[^\1]*</code> is not working as expected. Or is the problem elsewhere?</p>
<pre><code>import re
s = "'Well, I've tried to say \"How Doth the Little Busy Bee,\" but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'"
for i, m in enumerate(re.finditer(r'([\'"])(?!(?:ve|m|re|s|t|d|ll))(?=([^\1]*)\1)', s)):
print("\nGroup {:d}: ".format(i+1))
for g in m.groups():
print(' '+g)
</code></pre>
| 2 |
2016-09-22T11:47:43Z
| 39,729,281 |
<p>This is a great question for Python regex because sadly, in my opinion the <code>re</code> module is <a href="http://www.rexegg.com/regex-python.html#missing_in_re" rel="nofollow">one of the most underpowered of mainstream regex engines</a>. That's why for any serious regex work in Python, I turn to Matthew Barnett's stellar <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex</a> module, which incorporates some terrific features from Perl, PCRE and .NET.</p>
<p>The solution I'll show you can be adapted to work with <code>re</code>, but it is much more readable with <code>regex</code> because it is made modular. Also, consider it as a starting block for more complex nested matching, because <code>regex</code> lets you write <a href="http://www.rexegg.com/regex-recursion.html" rel="nofollow">recursive regular expressions</a> similar to those found in Perl and PCRE.</p>
<p>Okay, enough talk, here's the code (a mere four lines apart from the import and definitions). Please don't let the long regex scare you: it is long because it is designed to be readable. Explanations follow.</p>
<p><strong>The Code</strong></p>
<pre><code>import regex
quote = regex.compile(r'''(?x)
(?(DEFINE)
(?<qmark>["']) # what we'll consider a quotation mark
(?<not_qmark>[^'"]+) # chunk without quotes
(?<a_quote>(?P<qopen>(?&qmark))(?&not_qmark)(?P=qopen)) # a non-nested quote
) # End DEFINE block
# Start Match block
(?&a_quote)
|
(?P<open>(?&qmark))
(?&not_qmark)?
(?P<quote>(?&a_quote))
(?&not_qmark)?
(?P=open)
''')
str = """'Well, I have tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I will try again.'"""
for match in quote.finditer(str):
print(match.group())
if match.group('quote'):
print(match.group('quote'))
</code></pre>
<p><strong>The Output</strong></p>
<pre><code>'Well, I have tried to say "How Doth the Little Busy Bee," but it all came different!'
"How Doth the Little Busy Bee,"
'I will try again.'
</code></pre>
<p><strong>How it Works</strong></p>
<p>First, to simplify, note that I have taken the liberty of converting <code>I'll</code> to <code>I will</code>, reducing confusion with quotes. Addressing <code>I'll</code> would be no problem with a negative lookahead, but I wanted to make the regex readable.</p>
<p>In the <code>(?(DEFINE)...)</code> block, we define the three sub-expressions <code>qmark</code>, <code>not_qmark</code> and <code>a_quote</code>, much in the way that you define variables or subroutines to avoid repeating yourself. </p>
<p>After the definition block, we proceed to matching:</p>
<ul>
<li><code>(?&a_quote)</code> matches an entire quote,</li>
<li><code>|</code> or...</li>
<li><code>(?P<open>(?&qmark))</code> matches a quotation mark and captures it to the <code>open</code> group,</li>
<li><code>(?&not_qmark)?</code> matches optional text that is not quotes,</li>
<li><code>(?P<quote>(?&a_quote))</code> matches a full quote and captures it to the <code>quote</code> group,</li>
<li><code>(?&not_qmark)?</code> matches optional text that is not quotes,</li>
<li><code>(?P=open)</code> matches the same quotation mark that was captured at the opening of the quote.</li>
</ul>
<p>The Python code then only needs to print the match and the <code>quote</code> capture group if present.</p>
<p>Can this be refined? You bet. Working with <code>(?(DEFINE)...)</code> in this way, you can build beautiful patterns that you can later re-read and understand. </p>
<p><strong>Adding Recursion</strong></p>
<p>If you want to handle more complex nesting using pure regex, you'll need to turn to recursion.</p>
<p>To add recursion, all you need to do is define a group and refer to it using the subroutine syntax. For instance, to execute the code within Group 1, use <code>(?1)</code>. To execute the code within group <code>something</code>, use <code>(?&something)</code>. Remember to leave an exit for the engine by either making the recursion optional (<code>?</code>) or one side of an alternation.</p>
<p><strong>References</strong></p>
<ul>
<li><a href="http://www.rexegg.com/regex-disambiguation.html#define" rel="nofollow">Pre-defined regex subroutines</a></li>
<li><a href="http://www.rexegg.com/regex-capture.html#namedgroups" rel="nofollow">Named capture groups</a></li>
</ul>
| 1 |
2016-09-27T15:59:09Z
|
[
"python",
"regex"
] |
Replacing nodal values in a mesh with >1e6 inputs selectively using a polygon
| 39,638,189 |
<p>I have a set of data which represents a set of nodes, each node is associated with a value (represented by a color in the image). What I want to achieve is selectively changing those values.</p>
<p>The mesh represents a porous system (say a rock for example) model. The pressure in my system is specified at the nodes. My input already contains a pressure attributed to each node but I want to be able to re-assign initial conditions for the pressure at specific nodes only (the ones located inside the polygon). So the weights of my nodes are the pressure at that node. </p>
<p>I actually want to define a polygon, and attribute a value to each vertex (think of it as a weight), and using the weight of the vertex and the distance from the vertices to each node INSIDE the polygon to correct the value for that node.</p>
<p>This is what my output look like:</p>
<p><a href="http://i.stack.imgur.com/B9YBP.png" rel="nofollow"><img src="http://i.stack.imgur.com/B9YBP.png" alt="enter image description here"></a></p>
<p>I am working on an algorithm which takes in a set of values of the form [x,y,z] and another with [value,value,value,value]. Both have the same number of rows. e.i, the rows in the first input are the location of the node, and the rows in the second the values associated with that node.</p>
<p>I made an algorithm which takes in a set of points forming a polygon and a set of weights corresponding to each vertex of that polygon.</p>
<p>I then scan my merged inputs and replace the value of any node found to be inside the polygon. The value is defined by the algorithm in this <a href="http://codereview.stackexchange.com/questions/141546/algorithm-to-find-the-value-of-a-point-inside-a-polygone-using-weighted-vertices">post</a>. If the node is not inside the polygon it's value is preserved.</p>
<p>I then write all the new_values to a file.</p>
<p>My concern is that I will not be able to handle large inputs of a few million nodes without a MemoryError. At the moment handling a 9239 rows of inputs, takes me 9 seconds.</p>
<p>This is my code:</p>
<pre><code># for PIP problem
import shapely.geometry as shapely
# for plot
import matplotlib.pyplot as plt
# for handling data
import csv
import itertools
# for timing
import time
#=================================================================================
# POINT IN POLYGONE PROBLEM
#=================================================================================
class MyPoly(shapely.Polygon):
def __init__(self,points):
closed_path = list(points)+[points[0]]
super(MyPoly,self).__init__(closed_path)
self.points = closed_path
self.points_shapely = [shapely.Point(p[0],p[1]) for p in closed_path]
def convert_to_shapely_points_and_poly(poly,points):
poly_shapely = MyPoly(poly)
points_shapely = (shapely.Point(p[0],p[1]) for p in points)
return poly_shapely,points_shapely
def isBetween(a, b, c): #is c between a and b ?
crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
if abs(crossproduct) > 0.01 : return False # (or != 0 if using integers)
dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0 : return False
squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if dotproduct > squaredlengthba: return False
return True
def get_edges(poly):
# get edges
edges = []
for i in range(len(poly.points)-1):
t = [poly.points_shapely[i],poly.points_shapely[i+1]]
edges.append(t)
return edges
def inPoly(poly,point, inclusive):
if poly.contains(point) == True:
return 1
elif inclusive:
for e in get_edges(poly):
if isBetween(e[0],e[1],point):
return 1
return 0
def plot(poly_init,points_init, inclusive = True):
#convert to shapely poly and points
poly,points = convert_to_shapely_points_and_poly(poly_init,points_init)
#plot polygon
plt.plot(*zip(*poly.points))
#plot points
xs,ys,cs = [],[],[]
for point in points:
xs.append(point.x)
ys.append(point.y)
color = inPoly(poly,point, inclusive)
cs.append(color)
print point,":", color
plt.scatter(xs,ys, c = cs , s = 20*4*2)
#setting limits
axes = plt.gca()
axes.set_xlim([min(xs)-5,max(xs)+50])
axes.set_ylim([min(ys)-5,max(ys)+10])
plt.show()
# TESTS ========================================================================
#set up poly
polys = {
1 : [[10,10],[10,50],[50,50],[50,80],[100,80],[100,10]], # test rectangulary shape
2 : [[20,10],[10,20],[30,20]], # test triangle
3 : [[0,0],[0,10],[20,0],[20,10]], # test bow-tie
4 : [[0,0],[0,10],[20,10],[20,0]], # test rect clockwise
5 : [[0,0],[20,0],[20,10],[0,10]] # test rect counter-clockwise
}
#points to check
points = {
1 : [(10,25),(50,75),(60,10),(20,20),(20,60),(40,50)], # rectangulary shape test pts
2 : [[20,10],[10,20],[30,20],[-5,0],[20,15]] , # triangle test pts
3 : [[0,0],[0,10],[20,0],[20,10],[10,0],[10,5],[15,5]], # bow-tie shape test pts
4 : [[0,0],[0,10],[20,0],[20,10],[10,0],[10,5],[15,2],[30,8]], # rect shape test pts
5 : [[0,0],[0,10],[20,0],[20,10],[10,0],[10,5],[15,2],[30,8]] # rect shape test pts
}
for data in zip(polys.itervalues(),points.itervalues()):
plot(data[0],data[1], True)
#================================================================================
# WEIGHTING FUNCTION
#================================================================================
def add_weights(poly, weights):
poly.weights = [float(w) for w in weights]+[weights[0]] #need to add the first weight
# at the end to account for
# the first point being added to close the loop
def distance(a,b):
dist = ( (b.x - a.x)**2 + (b.y - a.y)**2 )**0.5
if dist == 0: dist = 0.000000001
return dist
def get_weighted_sum(poly, point):
return sum([poly.weights[n]/distance(point,p) for n,p in enumerate(poly.points_shapely) if poly.weights[n] != 'nan'])
def get_weighted_dist(poly, point):
return sum([1/distance(point,p) for n,p in enumerate(poly.points_shapely) if poly.weights[n] != 'nan'])
def get_point_weighted_value(poly, point):
return get_weighted_sum(poly,point)/get_weighted_dist(poly,point)
#==============================================================================
# GETTING THE DATA inside the Polygone
#==============================================================================
'''Function Definitions'''
def data_extraction(filename,start_line,node_num,span_start,span_end):
with open(filename, "r") as myfile:
file_= csv.reader(myfile, delimiter=' ') #extracts data from .txt as lines
return (x for x in [filter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, node_num)])
def merge_data(msh_data,reload_data):
return (zip(msh_data,reload_data))
def edit_value(data, poly_init, weights):
#make x,y coordinates of the data into points
points_init = ([float(pair[0][0]),float(pair[0][2])]for pair in data)
#convert to shapely poly and points
poly,points = convert_to_shapely_points_and_poly(poly_init,points_init)
add_weights(poly,weights)
#fliter out points in polygon
new_pair = []
for n,point in enumerate(points):
if inPoly(poly, point, True):
value = str(get_point_weighted_value(poly, point))
new_pair.append([value,value,value,value])
else:
new_pair.append(data[n][1])
return (x for x in new_pair)
def make_file(filename,data):
with open(filename, "w") as f:
f.writelines('\t'.join(i) + '\n' for i in data)
f.close()
def run(directory_path,poly_list,weight_list):
''' Directory and File Names'''
msh_file = '\\nodes.txt'
reload_file = '\\values.txt'
new_reload_file = '\\new_values.txt'
dir_path = directory_path
msh_path = dir_path+msh_file
reload_path = dir_path+reload_file
'''Running the Code with your data'''
mesh_data = data_extraction(msh_path,0,54,1,4)
reload_data = data_extraction(reload_path,0,54,0,7)
data = merge_data(mesh_data,reload_data)
new_values = edit_value(data,poly_list,weight_list)
make_file(dir_path+new_reload_file,new_values)
t0 = time.time()
run("M:\\MyDocuments"
,([75,-800],[50,-900],[50,-1350],[90,-1000],[100,-900])
,(5.0e5,1e6,1e8,5.0e5,1.0e7))
t1= time.time()
print t1-t0
</code></pre>
<p>And this is sample data for you to play with (you will need to save it as a <code>values.txt</code> in the folder of interest):</p>
<pre><code>1.067896706746556e+006 8.368595971460000e+006 1.068728658407457e+006 8.368595971460000e+006
2.844581459224940e+005 8.613334125294963e+006 2.846631849296530e+005 8.613337865004616e+006
1.068266636556349e+006 8.368595971460000e+006 1.069097067800019e+006 8.368595971460000e+006
2.844306728256134e+005 8.613334269264592e+006 2.846366503960088e+005 8.613338015263893e+006
2.646871122251647e+003 9.280390372578276e+006 2.647124079593603e+003 9.279361848151272e+006
2.645513962411728e+003 9.280388336827532e+006 2.645732877622660e+003 9.279359747270351e+006
1.067996132697676e+006 8.368595971460000e+006 1.068827019510901e+006 8.368595971460000e+006
1.068040363056876e+006 8.368595971460000e+006 1.068870797759632e+006 8.368595971460000e+006
1.068068562573701e+006 8.368595971460000e+006 1.068898735336173e+006 8.368595971460000e+006
1.068088894288788e+006 8.368595971460000e+006 1.068918905897983e+006 8.368595971460000e+006
1.068104407561180e+006 8.368595971460000e+006 1.068934323713974e+006 8.368595971460000e+006
1.068116587634527e+006 8.368595971460000e+006 1.068946455001944e+006 8.368595971460000e+006
1.068126287610437e+006 8.368595971460000e+006 1.068956140100951e+006 8.368595971460000e+006
1.068134059350058e+006 8.368595971460000e+006 1.068963921144020e+006 8.368595971460000e+006
1.068140293705664e+006 8.368595971460000e+006 1.068970181121935e+006 8.368595971460000e+006
1.068145286907994e+006 8.368595971460000e+006 1.068975209852979e+006 8.368595971460000e+006
1.068149274285654e+006 8.368595971460000e+006 1.068979237556288e+006 8.368595971460000e+006
1.068152448234754e+006 8.368595971460000e+006 1.068982452745734e+006 8.368595971460000e+006
1.068154968237062e+006 8.368595971460000e+006 1.068985012157432e+006 8.368595971460000e+006
1.068156966832556e+006 8.368595971460000e+006 1.068987046589365e+006 8.368595971460000e+006
1.068158553584154e+006 8.368595971460000e+006 1.068988664694503e+006 8.368595971460000e+006
1.068159818109515e+006 8.368595971460000e+006 1.068989955820237e+006 8.368595971460000e+006
1.068160832713088e+006 8.368595971460000e+006 1.068990992449035e+006 8.368595971460000e+006
1.068161654841110e+006 8.368595971460000e+006 1.068991832481593e+006 8.368595971460000e+006
1.068162329417389e+006 8.368595971460000e+006 1.068992521432464e+006 8.368595971460000e+006
1.068162891039026e+006 8.368595971460000e+006 1.068993094522149e+006 8.368595971460000e+006
1.068163365980015e+006 8.368595971460000e+006 1.068993578612505e+006 8.368595971460000e+006
1.068163773959426e+006 8.368595971460000e+006 1.068993993936813e+006 8.368595971460000e+006
1.068164129647837e+006 8.368595971460000e+006 1.068994355591033e+006 8.368595971460000e+006
1.068164443906155e+006 8.368595971460000e+006 1.068994674772899e+006 8.368595971460000e+006
1.068164724771358e+006 8.368595971460000e+006 1.068994959776965e+006 8.368595971460000e+006
1.068164978220522e+006 8.368595971460000e+006 1.068995216771951e+006 8.368595971460000e+006
1.068165208742598e+006 8.368595971460000e+006 1.068995450386572e+006 8.368595971460000e+006
1.068165419759155e+006 8.368595971460000e+006 1.068995664143054e+006 8.368595971460000e+006
1.068165613928702e+006 8.368595971460000e+006 1.068995860772074e+006 8.368595971460000e+006
1.068165793358832e+006 8.368595971460000e+006 1.068996042433189e+006 8.368595971460000e+006
1.068165959755557e+006 8.368595971460000e+006 1.068996210870328e+006 8.368595971460000e+006
1.068166114528858e+006 8.368595971460000e+006 1.068996367521690e+006 8.368595971460000e+006
1.068166258863683e+006 8.368595971460000e+006 1.068996513593785e+006 8.368595971460000e+006
1.068166393771001e+006 8.368595971460000e+006 1.068996650114520e+006 8.368595971460000e+006
1.068166520124043e+006 8.368595971460000e+006 1.068996777970799e+006 8.368595971460000e+006
1.068166638684427e+006 8.368595971460000e+006 1.068996897935547e+006 8.368595971460000e+006
1.068166750121474e+006 8.368595971460000e+006 1.068997010687638e+006 8.368595971460000e+006
1.068166855027363e+006 8.368595971460000e+006 1.068997116827437e+006 8.368595971460000e+006
1.068166953929060e+006 8.368595971460000e+006 1.068997216889020e+006 8.368595971460000e+006
1.068167047297063e+006 8.368595971460000e+006 1.068997311349124e+006 8.368595971460000e+006
1.068167135553131e+006 8.368595971460000e+006 1.068997400635036e+006 8.368595971460000e+006
1.068167219077452e+006 8.368595971460000e+006 1.068997485131862e+006 8.368595971460000e+006
1.068167298214444e+006 8.368595971460000e+006 1.068997565188462e+006 8.368595971460000e+006
1.068167373276848e+006 8.368595971460000e+006 1.068997641121696e+006 8.368595971460000e+006
1.068167444552389e+006 8.368595971460000e+006 1.068997713223352e+006 8.368595971460000e+006
1.068167512315698e+006 8.368595971460000e+006 1.068997781772706e+006 8.368595971460000e+006
1.068167576851623e+006 8.368595971460000e+006 1.068997847061655e+006 8.368595971460000e+006
1.068167638524622e+006 8.368595971460000e+006 1.068997909469268e+006 8.368595971460000e+006
1.068167697990453e+006 8.368595971460000e+006 1.068997969688582e+006 8.368595971460000e+006
</code></pre>
<p>and a sample of the node data (will need to be saved as <code>nodes.txt</code>):</p>
<pre><code>0 0.26 0 -800.0
1 0.26 0 -1062.5
2 143.0 0 -800.0
3 143.0 0 -1062.5
4 0.26 0 -1150.0
5 143.0 0 -1150.0
6 1.17057404659 0 -800.0
7 2.10837283486 0 -800.0
8 3.07421037484 0 -800.0
9 4.06892500937 0 -800.0
10 5.0933801161 0 -800.0
11 6.14846485319 0 -800.0
12 7.23509501358 0 -800.0
13 8.35421377171 0 -800.0
14 9.50679247207 0 -800.0
15 10.6938315019 0 -800.0
16 11.9163611811 0 -800.0
17 13.1754426445 0 -800.0
18 14.472168711 0 -800.0
19 15.8076649025 0 -800.0
20 17.1830903981 0 -800.0
21 18.59963901 0 -800.0
22 20.0585402542 0 -800.0
23 21.5610604197 0 -800.0
24 23.1085036396 0 -800.0
25 24.7022130583 0 -800.0
26 26.3435719675 0 -800.0
27 28.0340049986 0 -800.0
28 29.7749793906 0 -800.0
29 31.5680062618 0 -800.0
30 33.4146418792 0 -800.0
31 35.3164890883 0 -800.0
32 37.2751986287 0 -800.0
33 39.2924705661 0 -800.0
34 41.3700558588 0 -800.0
35 43.5097577902 0 -800.0
36 45.7134335243 0 -800.0
37 47.9829957969 0 -800.0
38 50.3204145133 0 -800.0
39 52.7277184748 0 -800.0
40 55.2069971476 0 -800.0
41 57.7604024715 0 -800.0
42 60.3901507176 0 -800.0
43 63.0985244223 0 -800.0
44 65.8878743782 0 -800.0
45 68.7606216458 0 -800.0
46 71.7192596577 0 -800.0
47 74.7663564153 0 -800.0
48 77.904556725 0 -800.0
49 81.1365844387 0 -800.0
50 84.4652448319 0 -800.0
51 87.8934270922 0 -800.0
52 91.4241067682 0 -800.0
53 95.0603483625 0 -800.0
54 98.8053080549 0 -800.0
55 102.662236327 0 -800.0
</code></pre>
| 0 |
2016-09-22T11:48:15Z
| 39,641,942 |
<p>I'm trying to answer, but not sure if this will suffice:</p>
<p>You can save a list creation by replacing this part in <code>edit_values</code>:</p>
<pre><code>for n,point in enumerate(points):
if inPoly(poly, point, True):
value = str(get_point_weighted_value(poly, point))
new_pair.append([value,value,value,value])
else:
new_pair.append(data[n][1])
return (x for x in new_pair)
</code></pre>
<p>by</p>
<pre><code>for n,point in enumerate(points):
if inPoly(poly, point, True):
value = str(get_point_weighted_value(poly, point))
yield [value,value,value,value]
else:
yield data[n][1]
</code></pre>
<p>you save the creation of the <code>new_pair</code> list and the associated memory.</p>
| 1 |
2016-09-22T14:32:13Z
|
[
"python",
"performance",
"python-2.7",
"optimization",
"geometry"
] |
How to print words (and punctuation) from a list of positions
| 39,638,306 |
<p>(Removed Code to stop Class mates copying)
Right now it will create a text file with positions of each word, so for example if I wrote</p>
<p>"Hello, my name is mika, Hello" </p>
<p>The positions in that list would be [1,2,3,4,5,6,2,1], and it will also list each word/punctuation but only once, so in this case it would be </p>
<p>['Hello', ',', 'my', 'name', 'is', 'mika'] </p>
<p>The only thing now is to be able to get the words back into the original sentence using those positions in the list, which I can't seem to do.
I did try searching for other posts but it seemed to come up only with other people wanting the positions of the words rather than wanting to put the words back into a sentence using the positons.
I also thought it could be started by doing this:</p>
<pre><code>for i in range(len(readlines[1])):
</code></pre>
<p>but I honestly have no idea how to go around doing this.</p>
<p>Edit: This has now been solved by @Abhishek, thank you.</p>
| -1 |
2016-09-22T11:52:39Z
| 39,638,466 |
<pre><code>indices = [1,2,3,4,5,6,2,1]
namelst = ['Hello', ',', 'my', 'name', 'is', 'mika']
newstr = " ".join([namelst[x-1] for x in indices])
print (newstr)
</code></pre>
<p>output:</p>
<pre><code>>> 'Hello , my name is mika , Hello'
</code></pre>
<p>I agree there will be some offsets / spaces, but it will give you the complete sentence again</p>
| 0 |
2016-09-22T12:00:03Z
|
[
"python",
"list"
] |
How to print words (and punctuation) from a list of positions
| 39,638,306 |
<p>(Removed Code to stop Class mates copying)
Right now it will create a text file with positions of each word, so for example if I wrote</p>
<p>"Hello, my name is mika, Hello" </p>
<p>The positions in that list would be [1,2,3,4,5,6,2,1], and it will also list each word/punctuation but only once, so in this case it would be </p>
<p>['Hello', ',', 'my', 'name', 'is', 'mika'] </p>
<p>The only thing now is to be able to get the words back into the original sentence using those positions in the list, which I can't seem to do.
I did try searching for other posts but it seemed to come up only with other people wanting the positions of the words rather than wanting to put the words back into a sentence using the positons.
I also thought it could be started by doing this:</p>
<pre><code>for i in range(len(readlines[1])):
</code></pre>
<p>but I honestly have no idea how to go around doing this.</p>
<p>Edit: This has now been solved by @Abhishek, thank you.</p>
| -1 |
2016-09-22T11:52:39Z
| 39,638,740 |
<p><strong>Code:</strong> (Will remove spaces after punctuation)</p>
<pre><code>postitions = [1,2,3,4,5,6,2,1]
wordslist = ['Hello', ',', 'my', 'name', 'is', 'mika']
recreated=''
for i in indices:
w = namelst[i-1]
if w not in ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]:
w = ' ' + w
recreated = (recreated + w).strip()
print (recreated)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Hello, my name is mika, Hello
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 0 |
2016-09-22T12:12:16Z
|
[
"python",
"list"
] |
How to print words (and punctuation) from a list of positions
| 39,638,306 |
<p>(Removed Code to stop Class mates copying)
Right now it will create a text file with positions of each word, so for example if I wrote</p>
<p>"Hello, my name is mika, Hello" </p>
<p>The positions in that list would be [1,2,3,4,5,6,2,1], and it will also list each word/punctuation but only once, so in this case it would be </p>
<p>['Hello', ',', 'my', 'name', 'is', 'mika'] </p>
<p>The only thing now is to be able to get the words back into the original sentence using those positions in the list, which I can't seem to do.
I did try searching for other posts but it seemed to come up only with other people wanting the positions of the words rather than wanting to put the words back into a sentence using the positons.
I also thought it could be started by doing this:</p>
<pre><code>for i in range(len(readlines[1])):
</code></pre>
<p>but I honestly have no idea how to go around doing this.</p>
<p>Edit: This has now been solved by @Abhishek, thank you.</p>
| -1 |
2016-09-22T11:52:39Z
| 39,638,837 |
<p>You can use <code>numpy</code> to do this.</p>
<pre><code>>>> import numpy as np
>>> indices = np.array([1,2,3,4,5,6,2,1])
>>> namelst = np.array(['Hello', ',', 'my', 'name', 'is', 'mika', ',', 'Hello'])
>>> ' '.join(namelst[indices-1])
'Hello , my name is mika , Hello'
</code></pre>
| 0 |
2016-09-22T12:16:51Z
|
[
"python",
"list"
] |
Convert entries of an array to a list
| 39,638,324 |
<p>I have numpy arrays which entries consists of either zeros or ones. For example <code>A = [ 0. 0. 0. 0.]</code>, <code>B= [ 0. 0. 0. 1.]</code>, <code>C= [ 0. 0. 1. 0.]</code> Now I want to convert them into a list: <code>L =['0000', '0001', '0010']</code>. Is there an easy way to do it?</p>
| 0 |
2016-09-22T11:53:38Z
| 39,638,764 |
<p>You can convert each list to a string using <code>join</code> like this</p>
<pre><code>def join_list(x):
return ''.join([str(int(i)) for i in x])
A = [0, 0, 0, 0]
B = [0, 0, 0, 1]
C = [0, 0, 1, 0]
print(join_list(A))
# 0000
</code></pre>
<p>The you can add them all to a new list with a <code>for</code> loop</p>
<pre><code>new_list = []
for l in [A, B, C]:
new_list.append(join_list(l))
print(new_list)
# ['0000', '0001', '0010']
</code></pre>
| 1 |
2016-09-22T12:13:35Z
|
[
"python",
"arrays",
"list"
] |
Convert entries of an array to a list
| 39,638,324 |
<p>I have numpy arrays which entries consists of either zeros or ones. For example <code>A = [ 0. 0. 0. 0.]</code>, <code>B= [ 0. 0. 0. 1.]</code>, <code>C= [ 0. 0. 1. 0.]</code> Now I want to convert them into a list: <code>L =['0000', '0001', '0010']</code>. Is there an easy way to do it?</p>
| 0 |
2016-09-22T11:53:38Z
| 39,638,877 |
<p>You need to cast to <code>str(int(ele))</code> and then join:</p>
<pre><code>["".join([str(int(f)) for f in arr]) for arr in (A, B, C)]
</code></pre>
<p>Or since you seem to have numpy arrays:</p>
<pre><code>["".join(map(str, arr.astype(int))) for arr in (A,B,C)]
</code></pre>
<p>Or use astype twice:</p>
<pre><code>["".join(arr.astype(int).astype(str)) for arr in (A,B,C)]
</code></pre>
| 1 |
2016-09-22T12:19:10Z
|
[
"python",
"arrays",
"list"
] |
Raising my own Exception in Python 2.7
| 39,638,400 |
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p>
<pre><code>def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise 'BadNumberError', '17 is a bad number'
return x
inputNumber()
</code></pre>
<p>This is what I got when I run the code:</p>
<pre><code>Pick a number: 17
Traceback (most recent call last):
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 153, in <module>
inputNumber()
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 151, in inputNumber
raise 'BadNumberError', '17 is a bad number'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
</code></pre>
| 0 |
2016-09-22T11:56:51Z
| 39,638,450 |
<p>You should be raising exceptions as raise as follows <code>BadNumberError('17 is a bad number')</code> if you have already defined <code>BadNumberError</code> class exception.</p>
<p>If you haven't, then</p>
<pre><code>class BadNumberError(Exception):
pass
</code></pre>
<p>And here is the <a href="https://docs.python.org/2/tutorial/errors.html#raising-exceptions" rel="nofollow">docs</a> with information about raising exceptions</p>
| 0 |
2016-09-22T11:59:18Z
|
[
"python"
] |
Raising my own Exception in Python 2.7
| 39,638,400 |
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p>
<pre><code>def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise 'BadNumberError', '17 is a bad number'
return x
inputNumber()
</code></pre>
<p>This is what I got when I run the code:</p>
<pre><code>Pick a number: 17
Traceback (most recent call last):
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 153, in <module>
inputNumber()
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 151, in inputNumber
raise 'BadNumberError', '17 is a bad number'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
</code></pre>
| 0 |
2016-09-22T11:56:51Z
| 39,638,486 |
<p>Just inherit from <code>Exception</code> class, then you can throw your own exceptions:</p>
<pre><code>class BadNumberException(Exception):
pass
raise BadNumberException('17 is a bad number')
</code></pre>
<p>output:</p>
<pre><code>Traceback (most recent call last):
File "<module1>", line 4, in <module>
BadNumberException: 17 is a bad number
</code></pre>
| 0 |
2016-09-22T12:01:09Z
|
[
"python"
] |
Raising my own Exception in Python 2.7
| 39,638,400 |
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p>
<pre><code>def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise 'BadNumberError', '17 is a bad number'
return x
inputNumber()
</code></pre>
<p>This is what I got when I run the code:</p>
<pre><code>Pick a number: 17
Traceback (most recent call last):
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 153, in <module>
inputNumber()
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 151, in inputNumber
raise 'BadNumberError', '17 is a bad number'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
</code></pre>
| 0 |
2016-09-22T11:56:51Z
| 39,638,489 |
<p>If you want to define a <a href="https://docs.python.org/2/tutorial/errors.html#user-defined-exceptions" rel="nofollow">your own error</a> you have to do:</p>
<pre><code>class BadNumberError(Exception):
pass
</code></pre>
<p>and then use it:</p>
<pre><code>def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise BadNumberError('17 is a bad number')
return x
inputNumber()
</code></pre>
| 0 |
2016-09-22T12:01:17Z
|
[
"python"
] |
Raising my own Exception in Python 2.7
| 39,638,400 |
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p>
<pre><code>def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise 'BadNumberError', '17 is a bad number'
return x
inputNumber()
</code></pre>
<p>This is what I got when I run the code:</p>
<pre><code>Pick a number: 17
Traceback (most recent call last):
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 153, in <module>
inputNumber()
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 151, in inputNumber
raise 'BadNumberError', '17 is a bad number'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
</code></pre>
| 0 |
2016-09-22T11:56:51Z
| 39,638,537 |
<p>You can use standard exceptions:</p>
<pre><code>raise ValueError('17 is a bad number')
</code></pre>
<p>Or you can define your own:</p>
<pre><code>class BadNumberError(Exception):
pass
</code></pre>
<p>And then use it:</p>
<pre><code>raise BadNumberError('17 is a bad number')
</code></pre>
| 2 |
2016-09-22T12:02:57Z
|
[
"python"
] |
ValueError: cannot use inplace with CategoricalIndex
| 39,638,403 |
<p>I am using <strong>pandas 0.18</strong>.</p>
<p>This fails </p>
<pre><code> cat_fields[f[0]].add_categories(s,inplace=True)
</code></pre>
<p>However the <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.Series.cat.add_categories.html#pandas.Series.cat.add_categories" rel="nofollow">docs</a> say</p>
<blockquote>
<p>inplace : boolean (default: False)</p>
<p>Whether or not to add the categories inplace or return a copy of this categorical with added categories.</p>
</blockquote>
<p>Am I missing something ?</p>
<p>I am creating a superset of categories/columns across many dataframes to eventually be able to concatenate them.</p>
<p>My error: </p>
<blockquote>
<p>ValueError: cannot use inplace with CategoricalIndex </p>
</blockquote>
| 0 |
2016-09-22T11:57:00Z
| 39,638,446 |
<p>I think you need assign to original column, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cat.add_categories.html" rel="nofollow"><code>Series.add_categories</code></a> has <code>inplace</code> parameter and it works nice.</p>
<p>But in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.CategoricalIndex.add_categories.html" rel="nofollow"><code>CategoricalIndex.add_categories</code></a> has also <code>inplace</code> parameter, but it fails. I think it is bug.</p>
<pre><code>cat_fields[f[0]] = cat_fields[f[0]].add_categories(s)
</code></pre>
<p>or:</p>
<pre><code>cat_fields[f[0]] = cat_fields[f[0]].cat.add_categories(s)
</code></pre>
<p>Sample:</p>
<pre><code>cat_fields = pd.DataFrame({'A':[1,2,3]}, index=['a','d','f'])
cat_fields.index = pd.CategoricalIndex(cat_fields.index)
cat_fields.A = pd.Categorical(cat_fields.A)
print (cat_fields)
A
a 1
d 2
f 3
s = ['b','c']
cat_fields.A.cat.add_categories(s,inplace=True)
print (cat_fields.A)
Name: A, dtype: category
Categories (5, object): [1, 2, 3, b, c]
cat_fields.index.add_categories(s,inplace=True)
print (cat_fields)
</code></pre>
<blockquote>
<p>ValueError: cannot use inplace with CategoricalIndex</p>
</blockquote>
| 0 |
2016-09-22T11:59:01Z
|
[
"python",
"pandas",
"add",
"categorical-data",
"in-place"
] |
What's The Mapping Reduction Function
| 39,638,679 |
<p>This is (I think) easy problem from Complexity Theory. </p>
<pre><code>#Consider the language E over the binary alphabet
#consisting of strings representing even non-negative
#integers (with leading zeros allowed).
#I.e. E = {x | x[-1] == '0'}.
#
#Reduce E to the language {'Even'} by implementing
#the function R
def R(x):
#Code
def main():
#test cases
assert(R('10010') in ['Even'])
assert(R('110011') not in ['Even'])
if __name__ == '__main__':
main()
</code></pre>
<p>According to Mapping Reduction def:<br>
"Language A is mapping reducible to language B, written A ⤠mB,
if there is a computable function f : Σ â ââΣ â , where for every w,
w â A ââ f (w) â B.
The function f is called the reduction from A to B."<br>
A computable mapping function would be f(n) = 2n (or x << y in Python), but in that case, those assertions doesn't make sense, because every R(x) should be in {'Even'}...?</p>
| 0 |
2016-09-22T12:09:25Z
| 39,639,102 |
<p>So basically you have <code>E</code> as the binary representations of integers, even numbers only. This is indicated by the last digit (integer 1) being <code>0</code>. All other digits represent multiples of 2 and therefore do not matter.</p>
<p>The target "language" consists just of the string <code>"Even"</code>. That is, every even number must map to the word <code>"Even"</code>.</p>
<p>So the assignment is practically: if <code>x</code> represents an even binary number, return <code>"Even"</code>, otherwise return something else.</p>
<p>The most straightforward way is to check the definition of an even binary number:</p>
<pre><code>def R(x): # shortest/fastest option
return 'Even' if x[-1] == 0 else ''
def Rdocs(x):
"""
Map any of {x | x[-1] == '0'} to {'Even'}
Uses the definition {x | x[-1] == '0'}
"""
if x[-1] == '0': # check that x satisfies definition of even binary
return 'Even'
return ''
</code></pre>
<p>One can also do this with an explicit mapping:</p>
<pre><code>translate = {'0': 'Even', '1': ''}
def Rmap(x, default=''):
"""
Map any of {x | x[-1] == '0'} to {'Even'}
Uses a literal mapping of x[-1]
"""
return translate[x[-1]]
</code></pre>
<p>Alternatively, you can convert the binary to a number. Python's <code>int</code> type also takes binary literals:</p>
<pre><code>def Rbin(x):
"""
Map any of {x | x[-1] == '0'} to {'Even'}
Uses python builtin to evaluate binary
"""
return '' if int(x, 2) % 2 else 'Even'
</code></pre>
<p>I guess technically speaking, <code>R(x)</code> should be <strong>only</strong> defined for every <code>x</code> in <code>{x | x[-1] == '0'}</code>, unless you assume the empty word is implicitly contained in every language. Your unit tests suggest it must return something, however. You may want to return <code>'Odd'</code> or <code>None</code> instead of the empty word.</p>
| 0 |
2016-09-22T12:29:23Z
|
[
"python",
"complexity-theory",
"turing-machines"
] |
PyQT4: why does QDialog returns from exec_() when setVisible(false)
| 39,638,749 |
<p>I'm using Python 2.7 and PyQT4.</p>
<p>I want to hide a modal QDialog instance and later on show it again. However, when dialog.setVisible(false) is called (e.g., using QTimer), the dialog.exec_() call returns (with QDialog.Rejected return value).</p>
<p>However, according to <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qdialog.html#exec" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/qdialog.html#exec</a>, the _exec() call should block until the user <em>closes</em> the dialog.</p>
<p>Is there a way to hide the dialog without _exec() returning?</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from PyQt4 import QtGui, QtCore
class MyDialog(QtGui.QDialog):
def __init__(self, parent):
QtGui.QDialog.__init__(self, parent)
def closeEvent(self, QCloseEvent):
print "Close Event"
def hideEvent(self, QHideEvent):
print "Hide Event"
class MyWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle("Main Window")
button = QtGui.QPushButton("Press me", self)
button.clicked.connect(self.run_dialog)
def run_dialog(self):
self.dialog = MyDialog(self)
self.dialog.setModal(True)
self.dialog.show()
QtCore.QTimer.singleShot(1000, self.hide_dialog)
status = self.dialog.exec_()
print "Dialog exited with status {}".format(status), "::", QtGui.QDialog.Accepted, QtGui.QDialog.Rejected
def hide_dialog(self):
self.dialog.setVisible(False)
# self.dialog.setHidden(True)
if __name__ == '__main__':
app = QtGui.QApplication([])
w = MyWindow()
w.show()
sys.exit(app.exec_())
</code></pre>
<p>PS1: This code prints the following output:</p>
<pre><code>Hide Event
Dialog exited with status 0 :: 1 0
</code></pre>
<p>(the close event is not called).</p>
<p>PS2: For context, I'm trying to implement a SystemTrayIcon that allows to hide and restore a QMainWindow (this part is fine) and possibly its modal QDialog without closing the dialog.</p>
<p>Thanks!</p>
| 1 |
2016-09-22T12:12:53Z
| 39,640,634 |
<p>In case anyone is interested, the following code provides a quick-and-dirty way to circunvent the problem for me, although it does not really answer the question.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Extension of the QDialog class so that exec_() does not exit when hidden.
Dialogs inheriting will only exit exec_() via close(), reject() or accept()
"""
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class HideableQDialog(QDialog):
def __init__(self, *args, **kwargs):
super(HideableQDialog, self).__init__(*args, **kwargs)
self._mutex = QMutex()
self._is_finished = False
self._finished_condition = QWaitCondition()
self.finished.connect(self._finish_dialog)
def _finish_dialog(self):
self._is_finished = True
self._finished_condition.wakeOne()
def close(self):
super(HideableQDialog, self).close()
self._finish_dialog()
def reject(self):
super(HideableQDialog, self).reject()
self._finish_dialog()
def accept(self):
super(HideableQDialog, self).accept()
self._finish_dialog()
def exec_(self):
status = super(HideableQDialog, self).exec_()
self._mutex.lock()
condition_succedeed = False
while not condition_succedeed and not self._is_finished:
condition_succedeed = self._finished_condition.wait(self._mutex, 10)
QApplication.processEvents()
self._mutex.unlock()
</code></pre>
| 0 |
2016-09-22T13:36:31Z
|
[
"python",
"pyqt",
"pyqt4"
] |
PyQT4: why does QDialog returns from exec_() when setVisible(false)
| 39,638,749 |
<p>I'm using Python 2.7 and PyQT4.</p>
<p>I want to hide a modal QDialog instance and later on show it again. However, when dialog.setVisible(false) is called (e.g., using QTimer), the dialog.exec_() call returns (with QDialog.Rejected return value).</p>
<p>However, according to <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qdialog.html#exec" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/qdialog.html#exec</a>, the _exec() call should block until the user <em>closes</em> the dialog.</p>
<p>Is there a way to hide the dialog without _exec() returning?</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from PyQt4 import QtGui, QtCore
class MyDialog(QtGui.QDialog):
def __init__(self, parent):
QtGui.QDialog.__init__(self, parent)
def closeEvent(self, QCloseEvent):
print "Close Event"
def hideEvent(self, QHideEvent):
print "Hide Event"
class MyWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle("Main Window")
button = QtGui.QPushButton("Press me", self)
button.clicked.connect(self.run_dialog)
def run_dialog(self):
self.dialog = MyDialog(self)
self.dialog.setModal(True)
self.dialog.show()
QtCore.QTimer.singleShot(1000, self.hide_dialog)
status = self.dialog.exec_()
print "Dialog exited with status {}".format(status), "::", QtGui.QDialog.Accepted, QtGui.QDialog.Rejected
def hide_dialog(self):
self.dialog.setVisible(False)
# self.dialog.setHidden(True)
if __name__ == '__main__':
app = QtGui.QApplication([])
w = MyWindow()
w.show()
sys.exit(app.exec_())
</code></pre>
<p>PS1: This code prints the following output:</p>
<pre><code>Hide Event
Dialog exited with status 0 :: 1 0
</code></pre>
<p>(the close event is not called).</p>
<p>PS2: For context, I'm trying to implement a SystemTrayIcon that allows to hide and restore a QMainWindow (this part is fine) and possibly its modal QDialog without closing the dialog.</p>
<p>Thanks!</p>
| 1 |
2016-09-22T12:12:53Z
| 39,644,737 |
<p>You can bypass the normal behaviour of <code>QDialog.setVisible</code> (which implicitly closes the dialog), by calling the base-class method instead:</p>
<pre><code> def hide_dialog(self):
# self.dialog.setVisible(False)
QtGui.QWidget.setVisible(self.dialog, False)
</code></pre>
<p>However, it might be preferrable to connect to the dialog's <code>finished()</code> signal, rather than using <code>exec()</code>, and explicitly <code>reject()</code> the dialog in its <code>closeEvent</code>.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from PyQt4 import QtGui, QtCore
class MyDialog(QtGui.QDialog):
def __init__(self, parent):
QtGui.QDialog.__init__(self, parent)
layout = QtGui.QHBoxLayout(self)
for title, slot in ('Ok', self.accept), ('Cancel', self.reject):
button = QtGui.QPushButton(title)
button.clicked.connect(slot)
layout.addWidget(button)
def closeEvent(self, QCloseEvent):
print "Close Event"
self.reject()
def hideEvent(self, QHideEvent):
print "Hide Event"
class MyWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle("Main Window")
button = QtGui.QPushButton("Press me", self)
button.clicked.connect(self.run_dialog)
def run_dialog(self):
self.dialog = MyDialog(self)
self.dialog.finished.connect(self.dialog_finished)
self.dialog.setModal(True)
self.dialog.show()
QtCore.QTimer.singleShot(3000, self.dialog.hide)
def dialog_finished(self, status):
print "Dialog exited with status:", status
if __name__ == '__main__':
app = QtGui.QApplication([])
w = MyWindow()
w.show()
sys.exit(app.exec_())
</code></pre>
| 3 |
2016-09-22T16:52:20Z
|
[
"python",
"pyqt",
"pyqt4"
] |
how to apply filter on one variable considering other two variable using python
| 39,638,777 |
<p>I am having data with variables <code>participants</code>, <code>origin</code>, and <code>score</code>. And I want those participants and origin whose score is <code>greater than 60</code>. That means to filter participants I have to consider origin and score. I can filter only on origin or only on score but it will not work.</p>
<p>If anyone can help me, its great!!!</p>
| 2 |
2016-09-22T12:14:00Z
| 39,638,824 |
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>df = pd.DataFrame({'participants':['a','s','d'],
'origin':['f','g','t'],
'score':[7,80,9]})
print (df)
origin participants score
0 f a 7
1 g s 80
2 t d 9
df = df[df.score > 60]
print (df)
origin participants score
1 g s 80
</code></pre>
| 2 |
2016-09-22T12:16:27Z
|
[
"python",
"pandas",
"indexing",
"condition",
"tableau"
] |
Loop over groups Pandas Dataframe and get sum/count
| 39,638,801 |
<p>I am using Pandas to structure and process Data.
This is my DataFrame:</p>
<p><a href="http://i.stack.imgur.com/PQ6lS.png" rel="nofollow"><img src="http://i.stack.imgur.com/PQ6lS.png" alt="DataFrame"></a></p>
<p>And this is the code which enabled me to get this DataFrame:</p>
<pre><code>(data[['time_bucket', 'beginning_time', 'bitrate', 2, 3]].groupby(['time_bucket', 'beginning_time', 2, 3])).aggregate(np.mean)
</code></pre>
<p>Now I want to have the sum (Ideally, the sum and the count) of my 'bitrates' grouped in the same time_bucket. For example, for the first time_bucket((2016-07-08 02:00:00, 2016-07-08 02:05:00), it must be 93750000 as sum and 25 as count, for all the case 'bitrate'.</p>
<p>I did this :</p>
<pre><code>data[['time_bucket', 'bitrate']].groupby(['time_bucket']).agg(['sum', 'count'])
</code></pre>
<p>And this is the result :</p>
<p><a href="http://i.stack.imgur.com/66k9O.png" rel="nofollow"><img src="http://i.stack.imgur.com/66k9O.png" alt="enter image description here"></a></p>
<p>But I really want to have all my data in one DataFrame.</p>
<p>Can I do a simple loop over 'time_bucket' and apply a function which calculate the sum of all bitrates ?
Any ideas ? Thx !</p>
| 0 |
2016-09-22T12:15:13Z
| 39,640,134 |
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, but need same levels of <code>indexes</code> of both <code>DataFrames</code>, so use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>. Last get original <code>Multiindex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a>:</p>
<pre><code>data = pd.DataFrame({'A':[1,1,1,1,1,1],
'B':[4,4,4,5,5,5],
'C':[3,3,3,1,1,1],
'D':[1,3,1,3,1,3],
'E':[5,3,6,5,7,1]})
print (data)
A B C D E
0 1 4 3 1 5
1 1 4 3 3 3
2 1 4 3 1 6
3 1 5 1 3 5
4 1 5 1 1 7
5 1 5 1 3 1
</code></pre>
<pre><code>df1 = data[['A', 'B', 'C', 'D','E']].groupby(['A', 'B', 'C', 'D']).aggregate(np.mean)
print (df1)
E
A B C D
1 4 3 1 5.5
3 3.0
5 1 1 7.0
3 3.0
df2 = data[['A', 'C']].groupby(['A'])['C'].agg(['sum', 'count'])
print (df2)
sum count
A
1 12 6
print (pd.merge(df1.reset_index(['B','C','D']), df2, left_index=True, right_index=True)
.set_index(['B','C','D'], append=True))
E sum count
A B C D
1 4 3 1 5.5 12 6
3 3.0 12 6
5 1 1 7.0 12 6
3 3.0 12 6
</code></pre>
<p>I try another solution to get output from <code>df1</code>, but this is aggregated so it is impossible get right data. If sum level <code>C</code>, you get <code>8</code> instead <code>12</code>.</p>
| 1 |
2016-09-22T13:14:52Z
|
[
"python",
"pandas",
"dataframe",
"count",
"sum"
] |
Aggregate dataframe indices in python
| 39,638,833 |
<p>I want to aggregate indices of a dataframe with groupby function. </p>
<pre><code> word count
0 a 3
1 the 5
2 a 3
3 an 2
4 the 1
</code></pre>
<p>What I want is a pd.Series which consists of list(descending order) of indices,</p>
<pre><code>word
a [2, 0]
an [3]
the [4, 1]
</code></pre>
<p>I've tried some built-in functions with groupby, however, I couldn't find a way to aggregate indices. Would you like to provide any hint or solution for this problem?</p>
| 1 |
2016-09-22T12:16:44Z
| 39,638,881 |
<p>I think you can first change order of <code>index</code> by <code>[::-1]</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> and <code>apply</code> <code>index</code> to <code>list</code>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_index.html" rel="nofollow"><code>sort_index</code></a>:</p>
<pre><code>print (df[::-1].groupby('word', sort=False).apply(lambda x: x.index.tolist()).sort_index())
word
a [2, 0]
an [3]
the [4, 1]
dtype: object
</code></pre>
<p>Another similar solution:</p>
<pre><code>print (df.sort_index(ascending=False)
.groupby('word', sort=False)
.apply(lambda x: x.index.tolist())
.sort_index())
word
a [2, 0]
an [3]
the [4, 1]
dtype: object
</code></pre>
| 2 |
2016-09-22T12:19:25Z
|
[
"python",
"pandas",
"series"
] |
recv_pyobj behaves different from Thread to Process
| 39,638,835 |
<p><br>
I am trying to read data from sockets on 6 different proceses at a time for perfomance sake. I made a test with opening 6 threads and do a socket read from each one and another test with opening 6 sub-processes and read a different socket. Thread reading works fine and it looks like this: </p>
<pre><code>class ZMQServer:
context = zmq.Context()
socket = None
ZMQthread = None
def __init__(self, port, max_size):
self.socket = self.context.socket(zmq.SUB)
self.socket.setsockopt(zmq.SUBSCRIBE, '')
self.socket.connect("tcp://127.0.0.1:" + str(port))
def StartAsync(self):
ZMQthread = threading.Thread(target=self.Start)
ZMQthread.start()
def Start(self):
print "ZMQServer:Wait for next request from client on port: %d" % self.port
while True:
print "Running another loop"
try:
message = self.socket.recv_pyobj()
except:
print "ZMQServer:Error receiving messages"
if __name__ == '__main__':
zmqServers = [None] * 6
for idx in range (0, 6):
zmqServers[idx] = ZMQServer(DTypes.PORTS_RECREGISTER[idx], 1024)
zmqServers[idx].StartAsync()
</code></pre>
<p>This will display:</p>
<blockquote>
<p>ZMQServer:Wait for next request from client on port: 4994<br>
Running another loop<br>
ZMQServer:Wait for next request from client on port: 4995<br>
Running another loop<br>
ZMQServer:Wait for next request from client on port: 4996<br>
Running another loop<br>
ZMQServer:Wait for next request from client on port: 4997<br>
Running another loop<br>
ZMQServer:Wait for next request from client on port: 4998<br>
Running another loop<br>
ZMQServer:Wait for next request from client on port: 4999<br></p>
</blockquote>
<p>IMPORTANT: I receive data on socket wen I send it.<br>
Now, I need to acheieve the same behaviour but only instead of threads use Processes so the octa core will use more of the processor. The code looks like this:</p>
<pre><code>context = zmq.Context()
def CreateSocket(port):
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, '')
socket.connect("tcp://127.0.0.1:" + str(port))
def Listen(socket, port):
print "ZMQServer:Wait for next request from client on port: %d" % port
while True:
print "Running another loop"
try:
message = socket.recv_pyobj()
print "ZMQServer:Received request: %s" % message
except:
print "ZMQServer:Error receiving messages"
continue
#I'm trying first only with 1 Process - 1 socket:
if __name__ == '__main__':
port = DTypes.PORTS_RECREGISTER[0]
socket = CreateSocket(port)
proc = Process(target=Listen, args=(socket, port))
proc.start()
proc.join()
</code></pre>
<p>The output is strange:</p>
<blockquote>
<p>ZMQServer:Wait for next request from client on port: 4994<br>
Running another loop<br>
ZMQServer:Error receiving messages<br>
Running another loop<br>
ZMQServer:Error receiving messages<br>
Running another loop<br>
ZMQServer:Error receiving messages<br>
............<br></p>
</blockquote>
<p>AND VERY IMPORTANT is that I do not receive data on the socket when I send it<br>
So, from what I can understand:<br>
1. Method enters and on every while loop the socket is changed?<br>
2. OR The recv_pyobj is not blocking anymore?<br>
Does anybody experienced that before? Does anybody know how to correclty do the multi-process socket reading?
<br>Thank you</p>
| 0 |
2016-09-22T12:16:48Z
| 39,640,540 |
<p>Actually, the problem was because of the passing SOCKET type argument to a Process/Thread. It seems that pickling, behind the scenes that serializes the data passed to callback method does not serialize well the SOCKET argument. <br>
So, I changed it so I would not pass a socket argument:</p>
<pre><code>context = zmq.Context()
def ListeToSocket(port):
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, '')
socket.connect("tcp://127.0.0.1:" + str(port))
print "Wait for data on port: %d" % port
while True:
try:
message = socket.recv_pyobj()
print "PORT:%d Received data: %s" % (port, message)
except:
print "PORT:%d: Error receiving messages" % port
if __name__ == '__main__':
for idx in range(0, DTypes.SOCKET_MAX):
proc1 = Process(target=ListeToSocket, args=(DTypes.PORTS_RECREGISTER[idx], ))
proc1.start()
</code></pre>
| 0 |
2016-09-22T13:32:46Z
|
[
"python",
"multithreading",
"sockets",
"subprocess"
] |
redis.exceptions.ConnectionError after approximately one day celery running
| 39,638,839 |
<p>This is my full trace:</p>
<pre><code> Traceback (most recent call last):
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/app/trace.py", line 283, in trace_task
uuid, retval, SUCCESS, request=task_request,
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/backends/base.py", line 256, in store_result
request=request, **kwargs)
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/backends/base.py", line 490, in _store_result
self.set(self.get_key_for_task(task_id), self.encode(meta))
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/backends/redis.py", line 160, in set
return self.ensure(self._set, (key, value), **retry_policy)
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/backends/redis.py", line 149, in ensure
**retry_policy
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/kombu/utils/__init__.py", line 243, in retry_over_time
return fun(*args, **kwargs)
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/backends/redis.py", line 169, in _set
pipe.execute()
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/redis/client.py", line 2593, in execute
return execute(conn, stack, raise_on_error)
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/redis/client.py", line 2447, in _execute_transaction
connection.send_packed_command(all_cmds)
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/redis/connection.py", line 532, in send_packed_command
self.connect()
File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/redis/connection.py", line 436, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 0 connecting to localhost:6379. Error.
[2016-09-21 10:47:18,814: WARNING/Worker-747] Data collector is not contactable. This can be because of a network issue or because of the data collector being restarted. In the event that contact cannot be made after a period of time then please report this problem to New Relic support for further investigation. The error raised was ConnectionError(ProtocolError('Connection aborted.', BlockingIOError(11, 'Resource temporarily unavailable')),).
</code></pre>
<p>I really searched for ConnectionError but there was no matching problem with mine. </p>
<p>My platform is ubuntu 14.04. This is a part of my redis config. (I can share if you need the whole redis.conf file. By the way all parameters are closed on LIMITS section.)</p>
<pre><code># By default Redis listens for connections from all the network interfaces
# available on the server. It is possible to listen to just one or multiple
# interfaces using the "bind" configuration directive, followed by one or
# more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
bind 127.0.0.1
# Specify the path for the unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /var/run/redis/redis.sock
# unixsocketperm 755
# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0
# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
# equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 60 seconds.
tcp-keepalive 60
</code></pre>
<p>This is my mini redis wrapper:</p>
<pre class="lang-py prettyprint-override"><code>import redis
from django.conf import settings
REDIS_POOL = redis.ConnectionPool(host=settings.REDIS_HOST, port=settings.REDIS_PORT)
def get_redis_server():
return redis.Redis(connection_pool=REDIS_POOL)
</code></pre>
<p>And this is how i use it:</p>
<pre class="lang-py prettyprint-override"><code>from redis_wrapper import get_redis_server
# view and task are working in different, indipendent processes
def sample_view(request):
rs = get_redis_server()
# some get-set stuff with redis
@shared_task
def sample_celery_task():
rs = get_redis_server()
# some get-set stuff with redis
</code></pre>
<p>Package versions:</p>
<pre><code>celery==3.1.18
django-celery==3.1.16
kombu==3.0.26
redis==2.10.3
</code></pre>
<p>So the problem is that; this connection error occurs after some time of starting celery workers. And after first seem of that error, all the tasks ends with this error until i restart all of my celery workers. (Interestingly, celery flower also fails during that problematic period)</p>
<p>I suspect of my redis connection pool usage method, or redis configuration or less probably network issues. Any ideas about the reason? What am i doing wrong?</p>
<p>(PS: I will add redis-cli info results when i will see this error today)</p>
<p><strong>UPDATE:</strong></p>
<p>I temporarily solved this problem by adding <a href="http://docs.celeryproject.org/en/latest/userguide/workers.html#max-tasks-per-child-setting" rel="nofollow">--maxtasksperchild</a> parameter to my worker starter command. I set it to 200. Ofcourse it is not the proper way to solve this problem, it is just a symptomatic cure. It basically refreshes the worker instance periodically (closes old process and creates new one when old one reached 200 task) and refreshes my global redis pool and connections. <strong>So i think i should focus on global redis connection pool usage way and i'm still waiting for new ideas and comments.</strong></p>
<p>Sorry for my bad English and thanks in advance.</p>
| 0 |
2016-09-22T12:16:59Z
| 39,639,598 |
<p>Have you enabled the rdb background save method in redis ??<br/>
if so check for the size of the <code>dump.rdb</code> file in <code>/var/lib/redis</code>.<br/>
Sometimes the file grows in size and fill the <code>root</code> directory and the redis instance cannot save to that file anymore.</p>
<p>You can stop the background save process by issuing <br/>
<code>config set stop-writes-on-bgsave-error no</code><br/>
command on <code>redis-cli</code></p>
| 0 |
2016-09-22T12:51:11Z
|
[
"python",
"django",
"redis",
"celery",
"redis-py"
] |
What happens when I loop a dict in python
| 39,638,897 |
<p>I know <code>Python</code> will simply return the key list when I put a <code>dict</code> in <code>for...in...</code> syntax.</p>
<p>But what what happens to the dict?</p>
<p>When we use <code>help(dict)</code>, we can not see <code>__next()__</code> method in the method list. So if I want to make a derived class based on <code>dict</code>:</p>
<pre><code>class MyDict(dict)
def __init__(self, *args, **kwargs):
super(MyDict, self).__init__(*args, **kwargs)
</code></pre>
<p>and <strong>return the value list with <code>for...in...</code></strong></p>
<pre><code>d = Mydict({'a': 1, 'b': 2})
for value in d:
</code></pre>
<p>what should I do?</p>
| 1 |
2016-09-22T12:20:09Z
| 39,639,173 |
<p>Naively, if all you want is for iteration over an instance of <code>MyClass</code> to yield the values instead of the keys, then in <code>MyClass</code> define:</p>
<pre><code>def __iter__(self):
return self.itervalues()
</code></pre>
<p>In Python 3:</p>
<pre><code>def __iter__(self):
return iter(self.values())
</code></pre>
<p>But beware! By doing this your class no longer implements the contract of <code>collections.MutableMapping</code>, even though <code>issubclass(MyClass, collections.MutableMapping)</code> is True. You might be better off <em>not</em> subclassing <code>dict</code>, if this is the behaviour you want, but instead have an attribute of type <code>dict</code> to hold the data, and implement only the functions and operators you need.</p>
| 0 |
2016-09-22T12:32:20Z
|
[
"python",
"dictionary"
] |
Adding two asynchronous lists, into a dictionary
| 39,639,035 |
<p>I've always found Dictionaries to be an odd thing in python. I know it is just me i'm sure but I cant work out how to take two lists and add them to the dict. If both lists were mapable it wouldn't be a problem something like <code>dictionary = dict(zip(list1, list2))</code> would suffice. However, during each run the <code>list1</code> will always have one item and the <code>list2</code> could have multiple items or single item that I'd like as values.</p>
<p>How could I approach adding the key and potentially multiple values to it?</p>
<p>After some deliberation, Kasramvd's second option seems to work well for this scenario:</p>
<p><code>dictionary.setdefault(list1[0], []).append(list2)</code></p>
| 0 |
2016-09-22T12:26:03Z
| 39,639,242 |
<p>Based on your comment all you need is assigning the second list as a value to only item of first list.</p>
<pre><code>d = {}
d[list1[0]] = list2
</code></pre>
<p>And if you want to preserve the values for duplicate keys you can use <code>dict.setdefault()</code> in order to create value of list of list for duplicate keys.</p>
<pre><code>d = {}
d.setdefault(list1[0], []).append(list2)
</code></pre>
| 2 |
2016-09-22T12:35:53Z
|
[
"python",
"dictionary"
] |
finding string in a list and return it index or -1
| 39,639,097 |
<p>Defining a procedure which return an index of item or -1 if the item not in list</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
else:
return -1
print (ser([1,2,3],3))
</code></pre>
<p>It's always return me -1. If i cut the 'else' part, it works. So why ?</p>
| -2 |
2016-09-22T12:29:10Z
| 39,639,143 |
<p>The <code>else</code> block is executed after the first iteration does not fulfill <code>j == b</code>. </p>
<p>You're better off moving the else block to the <code>for</code> which executes if the item is not found after the <code>for</code> loop is <em>exhausted</em>:</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
else: # or put default return on this line
return -1
</code></pre>
<p>More importantly, You could also check for containment using <code>b in a</code> without needing to iterate through the list.</p>
| 1 |
2016-09-22T12:31:18Z
|
[
"python",
"list",
"indexing"
] |
finding string in a list and return it index or -1
| 39,639,097 |
<p>Defining a procedure which return an index of item or -1 if the item not in list</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
else:
return -1
print (ser([1,2,3],3))
</code></pre>
<p>It's always return me -1. If i cut the 'else' part, it works. So why ?</p>
| -2 |
2016-09-22T12:29:10Z
| 39,639,191 |
<p>That is because the first time you do not match the condition in your loop you immediately return and leave your method. You need to re-think your logic here to determine what it is you want to do when you don't match. Ultimately, you want to continue looping until you have exhausted your checks.</p>
<p>So, simply set your <code>return -1</code> outside of your loop. If you go through your entire loop, you have not found your match, so you can then return -1</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
return -1
print (ser([1,2,3],3))
</code></pre>
<p>Alternatively, the loop can be avoided by using <a href="https://docs.python.org/3/reference/expressions.html#in" rel="nofollow">in</a>. So, you can actually re-write your method to this:</p>
<pre><code>def ser(a, b):
if b in a:
return a.index(b)
return -1
</code></pre>
<p>You are checking to see if item <code>b</code> is in list <code>a</code>, if it is, return the index, otherwise return -1</p>
<p>To take the simplification further, you can actually set this in to a single line in your <code>return</code>:</p>
<pre><code>def ser(a, b):
return a.index(b) if b in a else -1
</code></pre>
| 2 |
2016-09-22T12:33:12Z
|
[
"python",
"list",
"indexing"
] |
finding string in a list and return it index or -1
| 39,639,097 |
<p>Defining a procedure which return an index of item or -1 if the item not in list</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
else:
return -1
print (ser([1,2,3],3))
</code></pre>
<p>It's always return me -1. If i cut the 'else' part, it works. So why ?</p>
| -2 |
2016-09-22T12:29:10Z
| 39,639,235 |
<p>In the first iteration of the for loop, it will test if the first element in the array is equal to b. It is not, so the code returns -1 immediately, without testing the other elements of the array.</p>
<p>For your case, the correct code is:</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
return -1
</code></pre>
<p>In this way, the code will try all elements in the array, and will return -1 if none of them is equal to b.</p>
| 0 |
2016-09-22T12:35:39Z
|
[
"python",
"list",
"indexing"
] |
finding string in a list and return it index or -1
| 39,639,097 |
<p>Defining a procedure which return an index of item or -1 if the item not in list</p>
<pre><code>def ser(a,b):
for j in a:
if j == b:
return (a.index(b))
else:
return -1
print (ser([1,2,3],3))
</code></pre>
<p>It's always return me -1. If i cut the 'else' part, it works. So why ?</p>
| -2 |
2016-09-22T12:29:10Z
| 39,639,901 |
<p>You need not to do anything fancy, simple one-liner will work:</p>
<pre><code>def ser(a,b):
return a.index(b) if b in a else -1
# Example
my_list = [1, 2, 3, 4]
ser(my_list, 2)
# returns: 1
ser(my_list, 8)
# returns: -1
</code></pre>
| 0 |
2016-09-22T13:04:01Z
|
[
"python",
"list",
"indexing"
] |
Error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
| 39,639,127 |
<p>I'm trying to write an importer for a csv file. Here is a minimal example</p>
<pre><code>csv_filepathname="/home/thomas/Downloads/zip.csv"
your_djangoproject_home="~/Desktop/Projects/myproject/myproject/"
import sys,os,csv
sys.path.append(your_djangoproject_home)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.db.models.fields.related import ManyToManyField
from myapp.models import ZipCode,state
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
def import_SO(item, crit,val):
debug = 1;
obj_state=type(item).objects.filter(crit=val)
<...some other stuff...>
return
for row in dataReader:
st=state(statecode=row[2],statename=row[3])
import_SO(st,"statename",row[3])
</code></pre>
<p>And here is my model</p>
<pre><code>class state(models.Model):
statecode = models.CharField(max_length=2, default='XX')
statename = models.CharField(max_length=32, default='XXXXXXXXXXXXX')
</code></pre>
<p>When I execute the code like it is, then I get the following error:</p>
<pre><code>File "load_data.py", line 101, in <module>
import_SO(st,"statename",row[3]) # Objekt, Kriterium, zu vergleichender Wert
File "load_data.py", line 68, in import_SO
obj_state=type(item).objects.filter(crit=val)#crit=val) # suche object mit merkmal, hier statename
File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 679, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 697, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1310, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1338, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1150, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1036, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1394, in names_to_path
field_names = list(get_field_names_from_opts(opts))
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 45, in get_field_names_from_opts
for f in opts.get_fields()
File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 740, in get_fields
return self._get_fields(include_parents=include_parents, include_hidden=include_hidden)
File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 802, in _get_fields
all_fields = self._relation_tree
File "/usr/lib/python2.7/dist-packages/django/utils/functional.py", line 59, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 709, in _relation_tree
return self._populate_directed_relation_graph()
File "/usr/lib/python2.7/dist-packages/django/db/models/options.py", line 681, in _populate_directed_relation_graph
all_models = self.apps.get_models(include_auto_created=True)
File "/usr/lib/python2.7/dist-packages/django/utils/lru_cache.py", line 101, in wrapper
result = user_function(*args, **kwds)
File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
</code></pre>
<p>But when i change the line "obj_state=type(item).objects.filter(crit=val)" to "obj_state=type(item).objects.filter(statename=val)"
then everything works fine. So there seems to be a problem with the variable "crit" whicht stands for the searchcriteria, in this example "statename". So I want to pass the crit via arguments to the method "import_SO" but for some reason it doesn't work.</p>
<p>When I print the variable crit right before the error occurs, the content of the variable seems to be correct.</p>
<p>Any ideas?</p>
<p>Update:
after adding
<code>your_djangoproject_home="~/Desktop/Projects/myproject</code> and <code>os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'</code></p>
<p>to my code I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "load_data.py", line 11, in <module>
django.setup()
File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/lib/python2.7/dist-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named myproject
</code></pre>
<p>UPDATE:
my installed apps:</p>
<pre><code>INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myproject.myapp'
)
</code></pre>
| 0 |
2016-09-22T12:30:28Z
| 39,639,198 |
<p>You need to call <code>django.setup()</code> in your script before you use the ORM to access data.</p>
<pre><code>import django
sys.path.append(your_djangoproject_home)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
django.setup()
</code></pre>
<p>See <a href="https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage" rel="nofollow">the docs</a> for more info.</p>
| 0 |
2016-09-22T12:33:38Z
|
[
"python",
"django"
] |
Convert pandas dataframe column with xml data to normalised columns?
| 39,639,160 |
<p>I have a <code>DataFrame</code> in <code>pandas</code>, one of whose columns is a XML string. What I want to do is create one column for each of the xml nodes with column names in a normalised form. For example,</p>
<pre><code> id xmlcolumn
1 <main attr1='abc' attr2='xyz'><item><prop1>text1</prop1><prop2>text2</prop2></item></main>
2 <main ........</main>
</code></pre>
<p>I want to convert this to a data frame like so:</p>
<pre><code>id main.attr1 main.attr2 main.item.prop1 main.item.prop2
1 abc xyz text1 text2
2 .....
</code></pre>
<p>How would I do that, while still keeping the existing columns in the <code>DataFrame</code>?</p>
| 1 |
2016-09-22T12:31:59Z
| 39,656,957 |
<p>The first step that needs to be done is to convert the XML string to a pandas <code>Series</code> (under the assumption, that there will always be the same amount of columns in the end). So you need a function like:</p>
<pre><code>def convert_xml(raw):
# some etree xml mangling
</code></pre>
<p>This can be achieved e.g. using the <a href="https://docs.python.org/2/library/xml.etree.elementtree.htm" rel="nofollow">etree</a> package in python. The returned series must have an index, where each entry in the index is the new column name to appear, e.g. for your example:</p>
<pre><code>pd.Series(['abc', 'xyz'], index=['main.attr1', 'main.attr2'])
</code></pre>
<p>Given this function, you can do the following with pandas (mocking away the XML mangling):</p>
<pre><code>frame = pd.DataFrame({'keep': [42], 'xml': '<foo></foo>'})
temp = frame['xml'].apply(convert_xml)
frame = frame.drop('xml', axis=1)
frame = pd.concat([frame, temp], axis=1)
</code></pre>
| 0 |
2016-09-23T09:10:32Z
|
[
"python",
"xml",
"pandas",
"data-analysis"
] |
'None' is not displayed as I expected in Python interactive mode
| 39,639,342 |
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p>
<pre><code>>>> None
>>> print(repr(None))
None
>>>
</code></pre>
| 3 |
2016-09-22T12:40:19Z
| 39,639,399 |
<p>It's a deliberate feature. If the python code you run evaluates to exactly <code>None</code> then it is not displayed.</p>
<p>This is useful a lot of the time. For example, calling a function with a side effect may be useful, and such functions actually return <code>None</code> but you don't usually want to see the result.</p>
<p>For example, calling <code>print()</code> returns <code>None</code>, but you don't usually want to see it:</p>
<pre><code>>>> print("hello")
hello
>>> y = print("hello")
hello
>>> y
>>> print(y)
None
</code></pre>
| 3 |
2016-09-22T12:42:57Z
|
[
"python"
] |
'None' is not displayed as I expected in Python interactive mode
| 39,639,342 |
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p>
<pre><code>>>> None
>>> print(repr(None))
None
>>>
</code></pre>
| 3 |
2016-09-22T12:40:19Z
| 39,639,575 |
<p>In Python, a function that does not return anything but is called only for its side effects actually returns None. As such functions are common enough, Python interactive interpreter does not print anything in that case. By extension, it does not print anything when the interactive expression evaluates to None, even if it is not a function call.</p>
<p>If can be misleading for beginners because you have </p>
<pre><code>>>> a = 1
>>> a
1
>>>
</code></pre>
<p>but </p>
<pre><code>>>> a = None
>>> a
>>>
</code></pre>
<p>but is is indeed <em>by design</em></p>
| 1 |
2016-09-22T12:50:18Z
|
[
"python"
] |
'None' is not displayed as I expected in Python interactive mode
| 39,639,342 |
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p>
<pre><code>>>> None
>>> print(repr(None))
None
>>>
</code></pre>
| 3 |
2016-09-22T12:40:19Z
| 39,639,637 |
<p><a href="https://docs.python.org/3/library/constants.html#None" rel="nofollow"><code>None</code></a> represents the absence of a value, but that absence can be observed. Because it represents <em>something</em> in Python, its <code>__repr__</code> cannot possibly return <em>nothing</em>; <code>None</code> is not nothing.</p>
<p>The outcome is deliberate. If for example a function returns <code>None</code> (similar to having no return statement), the return value of a call to such function does not get shown in the console, so for example <code>print(None)</code> does not <em>print</em> <code>None</code> twice, as the function <code>print</code> equally returns <code>None</code>.</p>
<p>On a side note, <code>print(repr())</code> will raise a <code>TypeError</code> in Python.</p>
| 1 |
2016-09-22T12:52:56Z
|
[
"python"
] |
'None' is not displayed as I expected in Python interactive mode
| 39,639,342 |
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p>
<pre><code>>>> None
>>> print(repr(None))
None
>>>
</code></pre>
| 3 |
2016-09-22T12:40:19Z
| 39,641,065 |
<p>Yes, this behaviour is intentional.</p>
<p>From the <a href="https://docs.python.org/3/reference/simple_stmts.html#expression-statements" rel="nofollow">Python docs</a></p>
<blockquote>
<p>7.1. Expression statements</p>
<p>Expression statements are used (mostly interactively) to compute and
write a value, or (usually) to call a procedure (a function that
returns no meaningful result; in Python, procedures return the value
<code>None</code>). Other uses of expression statements are allowed and
occasionally useful. The syntax for an expression statement is:</p>
<pre><code>expression_stmt ::= starred_expression
</code></pre>
<p>An expression statement evaluates the expression list (which may be a
single expression).</p>
<p>In interactive mode, if the value is not <code>None</code>, it is converted to a
string using the built-in <code>repr()</code> function and the resulting string
is written to standard output on a line by itself (except if the
result is <code>None</code>, so that procedure calls do not cause any output.)</p>
</blockquote>
| 2 |
2016-09-22T13:54:52Z
|
[
"python"
] |
Drawing a rubberband on a panel without redrawing everthing in wxpython
| 39,639,497 |
<p>I use a wx.PaintDC() to draw shapes on a panel. After drawing the shapes, when I left click and drag mouse, a rubberband (transparent rectangle) is drawn over shapes. While dragging the mouse, for each motion of mouse, an EVT_PAINT is sent and everything (all shapes and rectangle) is redrawn.</p>
<p>How do I just draw the rubberband over the existing shapes (I don't want to redraw the shapes), I mean, it would be nice if I can save the existing shapes on some DC object and just draw the rubberband on it. So that the application will draw it faster.</p>
| 0 |
2016-09-22T12:47:35Z
| 39,640,694 |
<p>You presumably want to have a look at <a href="https://wxpython.org/Phoenix/docs/html/wx.Overlay.html?highlight=overlay" rel="nofollow"><code>wx.Overlay</code></a>. Look <a href="https://github.com/wxWidgets/wxPython/blob/master/sandbox/test_Overlay.py" rel="nofollow">here</a> for an example.</p>
| 2 |
2016-09-22T13:38:49Z
|
[
"python",
"wxpython"
] |
How can i use matplotlib on Anaconda? (Win 7 x64)
| 39,639,535 |
<p>I'm using Anaconda on Windows 7 64 bits but i'm unable to use any external package (numpy, matplotlib,scipy). At first when i tried to load this code:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
</code></pre>
<p>I got a DLL error. Then, i downloaded and installed manually the 64 bits packages from here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> but when i ran the code this message appeared: "Apparently the core died unexpectedly. Use 'Restart the core' to continue using this terminal."</p>
<p>I would appreciate if someone can help me with this problem because i have to do some projects and i'm wasting time. Thank you in advance.</p>
| -1 |
2016-09-22T12:49:04Z
| 39,641,072 |
<p>You should try to run the installation without the mkl optimizations.</p>
<pre><code>conda remove mkl mkl-service
conda install nomkl numpy scipy scikit-learn numexpr
</code></pre>
<p>edit:</p>
<p>Your problem seems to be that you installed the packages from the website and not from the anaconda channels. Clean your current environment from all packages (or create a new one) and execute:</p>
<pre><code>conda install numpy matplotlib
</code></pre>
| 0 |
2016-09-22T13:55:06Z
|
[
"python",
"numpy",
"matplotlib",
"64bit",
"anaconda"
] |
Scrapy API - Spider class init argument turned to None
| 39,639,568 |
<p>After a fresh install of Miniconda 64-bit exe installer for Windows and Python 2.7 on Windows 7, through which I get Scrapy, here is what is installed:</p>
<ul>
<li>Python 2.7.12</li>
<li>Scrapy 1.1.1</li>
<li>Twisted 16.4.1</li>
</ul>
<p>This minimal code, run from "python scrapy_test.py" (using Scrapy API):</p>
<pre><code>#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import scrapy.spiders.crawl
import scrapy.crawler
import scrapy.utils.project
class MySpider(scrapy.spiders.crawl.CrawlSpider) :
name = "stackoverflow.com"
allowed_domains = ["stackoverflow.com"]
start_urls = ["http://stackoverflow.com/"]
download_delay = 1.5
def __init__(self, my_arg = None) :
print "def __init__"
self.my_arg = my_arg
print "self.my_arg"
print self.my_arg
def parse(self, response) :
pass
def main() :
my_arg = "Value"
process = scrapy.crawler.CrawlerProcess(scrapy.utils.project.get_project_settings())
process.crawl(MySpider(my_arg))
process.start()
if __name__ == "__main__" :
main()
</code></pre>
<p>gives this ouput:</p>
<pre><code>[scrapy] INFO: Scrapy 1.1.1 started (bot: scrapy_project)
[scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapy_project.spiders', 'SPIDER_MODULES': ['scrapy_project.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'scrapy_project'}
def __init__
self.my_arg
Value
[scrapy] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
def __init__
self.my_arg
None
[...]
</code></pre>
<p>Notice how the init method was run twice and how the stored argument got turned to None after the second run, which is not what I want. Is this supposed to happen??</p>
<p>If I change:</p>
<pre><code>def __init__(self, my_arg = None) :
</code></pre>
<p>to:</p>
<pre><code>def __init__(self, my_arg) :
</code></pre>
<p>the output is:</p>
<pre><code>[...]
Unhandled error in Deferred:
[twisted] CRITICAL: Unhandled error in Deferred:
Traceback (most recent call last):
File "scrapy_test.py", line 28, in main
process.crawl(MySpider(my_arg))
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 163, in crawl
return self._crawl(crawler, *args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 167, in _crawl
d = crawler.crawl(*args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\twisted\internet\defer.py", line 1331, in unwindGenerator
return _inlineCallbacks(None, gen, Deferred())
--- <exception caught here> ---
File "C:\Users\XYZ\Miniconda2\lib\site-packages\twisted\internet\defer.py", line 1185, in _inlineCallbacks
result = g.send(result)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 90, in crawl
six.reraise(*exc_info)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 71, in crawl
self.spider = self._create_spider(*args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 94, in _create_spider
return self.spidercls.from_crawler(self, *args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\spiders\crawl.py", line 96, in from_crawler
spider = super(CrawlSpider, cls).from_crawler(crawler, *args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\spiders\__init__.py", line 50, in from_crawler
spider = cls(*args, **kwargs)
exceptions.TypeError: __init__() takes exactly 2 arguments (1 given)
[twisted] CRITICAL:
Traceback (most recent call last):
File "C:\Users\XYZ\Miniconda2\lib\site-packages\twisted\internet\defer.py", line 1185, in _inlineCallbacks
result = g.send(result)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 90, in crawl
six.reraise(*exc_info)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 71, in crawl
self.spider = self._create_spider(*args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\crawler.py", line 94, in _create_spider
return self.spidercls.from_crawler(self, *args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\spiders\crawl.py", line 96, in from_crawler
spider = super(CrawlSpider, cls).from_crawler(crawler, *args, **kwargs)
File "C:\Users\XYZ\Miniconda2\lib\site-packages\scrapy\spiders\__init__.py", line 50, in from_crawler
spider = cls(*args, **kwargs)
TypeError: __init__() takes exactly 2 arguments (1 given)
</code></pre>
<p>No clue how to get around this problem. Any idea?</p>
| 0 |
2016-09-22T12:50:05Z
| 39,646,168 |
<p>Here is the method definition for <a href="http://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess.crawl" rel="nofollow"><code>scrapy.crawler.CrawlerProcess.crawl()</code></a>:</p>
<blockquote>
<p><code>crawl(crawler_or_spidercls, *args, **kwargs)</code></p>
<ul>
<li><strong>crawler_or_spidercls</strong> (<code>Crawler</code> instance, <code>Spider</code> subclass or string) â already created crawler, or a spider class or spiderâs name
inside the project to create it</li>
<li><strong>args</strong> (<em>list</em>) â arguments to initialize the spider</li>
<li><strong>kwargs</strong> (<em>dict</em>) â keyword arguments to initialize the spider</li>
</ul>
</blockquote>
<hr>
<p>This means you should be passing the name of your <code>Spider</code> separately from the <code>kwargs</code> needed to initialize said <code>Spider</code>, like so:</p>
<pre><code>process.crawl(MySpider, my_arg = 'Value')
</code></pre>
| 2 |
2016-09-22T18:17:08Z
|
[
"python",
"scrapy"
] |
Memory error on large Shapefile in Python
| 39,639,579 |
<pre><code>import shapefile
data = shapefile.Reader("data_file.shp")
shapes = data.shapes()
</code></pre>
<p>My problem is that getting the shapes from the Shapefile reader gives me an exception <code>MemoryError</code> when using <a href="https://pypi.python.org/pypi/pyshp" rel="nofollow">Pyshp</a>.</p>
<p>The <code>.shp</code> file is quite large, at 1.2 gB. But I am using ony 3% of my machine's 32gB, so I don't understand it.</p>
<p>Is there any other approach that I can take? Can process the file in chunks in Python? Or use some tool to spilt the file into chinks, then process each of them individually?</p>
| 0 |
2016-09-22T12:50:24Z
| 39,639,735 |
<p>Quoting from <a href="http://stackoverflow.com/questions/5537618/memory-errors-and-list-limits">this answer</a> by thomas:</p>
<blockquote>
<p>The <code>MemoryError</code> exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit imposed by Windows (<a href="http://msdn.microsoft.com/en-us/library/aa366778%28v=vs.85%29.aspx#memory_limits" rel="nofollow">32bit programs</a>), or lack of available RAM on your computer. (This <a href="http://stackoverflow.com/questions/4285185/python-memory-limit">link</a> is to a previous question). You should be able to extend the 2GB by using 64bit copy of Python, provided you are using a 64bit copy of windows.</p>
</blockquote>
<p>So try a 64bit copy of Python or provide more detail about your platform and Python versions.</p>
| 3 |
2016-09-22T12:57:06Z
|
[
"python",
"shapefile",
"pyshp"
] |
Memory error on large Shapefile in Python
| 39,639,579 |
<pre><code>import shapefile
data = shapefile.Reader("data_file.shp")
shapes = data.shapes()
</code></pre>
<p>My problem is that getting the shapes from the Shapefile reader gives me an exception <code>MemoryError</code> when using <a href="https://pypi.python.org/pypi/pyshp" rel="nofollow">Pyshp</a>.</p>
<p>The <code>.shp</code> file is quite large, at 1.2 gB. But I am using ony 3% of my machine's 32gB, so I don't understand it.</p>
<p>Is there any other approach that I can take? Can process the file in chunks in Python? Or use some tool to spilt the file into chinks, then process each of them individually?</p>
| 0 |
2016-09-22T12:50:24Z
| 39,649,506 |
<p>Although I haven't been able to test it, Pyshp should be able to read it regardless of the file size or memory limits. Creating the <code>Reader</code> instance doesn't load the entire file, only the header information. </p>
<p>It seems the problem here is that you used the <code>shapes()</code> method, which reads all shape information into memory at once. This usually isn't a problem, but it is with files this big. As a general rule you should instead use the <code>iterShapes()</code> method which reads each shape one by one. </p>
<pre><code>import shapefile
data = shapefile.Reader("data_file.shp")
for shape in data.iterShapes():
# do something...
</code></pre>
| 1 |
2016-09-22T21:57:31Z
|
[
"python",
"shapefile",
"pyshp"
] |
translating RegEx syntax working in php and python to JS
| 39,639,589 |
<p>I have this RegEx syntax: "(?<=[a-z])-(?=[a-z])"</p>
<p>It captures a dash between 2 lowercase letters. In example below the second dash is captured:</p>
<p>Krynica-Zdrój, ul. Uzdro-jowa</p>
<p>Unfortunately I can't use <= in JS.
My ultimate goal is to remove the hyphen with RegEx replace.</p>
| 1 |
2016-09-22T12:50:49Z
| 39,639,788 |
<p>It seems to me you need to remove the hyphen in between lowercase letters.</p>
<p>Use</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = "Krynica-Zdrój, ul. Uzdro-jowa";
var res = s.replace(/([a-z])-(?=[a-z])/g, "$1");
console.log(res);</code></pre>
</div>
</div>
</p>
<p>Note the first lookbehind is turned into a simple capturing group and the second lookahead is OK to use since - potentially, if there are chunks of hyphenated single lowercase letters - it will be able to deal with overlapping matches.</p>
<p><em>Details</em>:</p>
<ul>
<li><code>([a-z])</code> - Group 1 capturing a lowercase ASCII letter</li>
<li><code>-</code> - a hyphen</li>
<li><code>(?=[a-z])</code> - that is followed with a lowercase ASCII letter that is not added to the result
-<code>/g</code> - a global modifier, search for all occurrences of the pattern</li>
<li><code>"$1"</code> - the replacement pattern containing just the backreference to the value stored in Group 1 buffer.</li>
</ul>
<p><strong>VBA sample code</strong>:</p>
<pre><code>Sub RemoveExtraHyphens()
Dim s As String
Dim reg As New regexp
reg.pattern = "([a-z])-(?=[a-z])"
reg.Global = True
s = "Krynica-Zdroj, ul. Uzdro-jowa"
Debug.Print reg.Replace(s, "$1")
End Sub
</code></pre>
<p><a href="http://i.stack.imgur.com/kf40d.png" rel="nofollow"><img src="http://i.stack.imgur.com/kf40d.png" alt="enter image description here"></a></p>
| 1 |
2016-09-22T12:59:19Z
|
[
"javascript",
"php",
"python",
"regex"
] |
Closing a connection with a `with` statement
| 39,639,594 |
<p>I want to have a class that represents an IMAP connection and use it with a <code>with</code> statement as follows:</p>
<pre><code>class IMAPConnection:
def __enter__(self):
connection = imaplib.IMAP4_SSL(IMAP_HOST)
try:
connection.login(MAIL_USERNAME, MAIL_PASS)
except imaplib.IMAP4.error:
log.error('Failed to log in')
return connection
def __exit__(self, type, value, traceback):
self.close()
with IMAPConnection() as c:
rv, data = c.list()
print(rv, data)
</code></pre>
<p>Naturally this fails since <code>IMAPConnections</code> has no attribute <code>close</code>. How can I store the connection and pass it to the <code>__exit__</code> function when the <code>with</code> statement is finished?</p>
| 1 |
2016-09-22T12:51:07Z
| 39,639,643 |
<p>You need to implement a <code>__exit__()</code> function within your <code>IMAPConnection</code> class.</p>
<p><code>__enter__()</code> function is called before executing the code within the <code>with</code> block where as <code>__exit__()</code> is called while exiting the <code>with</code> block.</p>
<p>Below is the sample structure:</p>
<pre><code>def __exit__(self, exc_type, exc_val, exc_tb):
# Close the connection and other logic applicable
self.connection.close()
</code></pre>
<p>Check: <a href="http://stackoverflow.com/a/1984346/2063361">Explaining Python's '<strong>enter</strong>' and '<strong>exit</strong>'</a> for more information.</p>
| 0 |
2016-09-22T12:53:08Z
|
[
"python",
"imap",
"with-statement",
"imaplib"
] |
Closing a connection with a `with` statement
| 39,639,594 |
<p>I want to have a class that represents an IMAP connection and use it with a <code>with</code> statement as follows:</p>
<pre><code>class IMAPConnection:
def __enter__(self):
connection = imaplib.IMAP4_SSL(IMAP_HOST)
try:
connection.login(MAIL_USERNAME, MAIL_PASS)
except imaplib.IMAP4.error:
log.error('Failed to log in')
return connection
def __exit__(self, type, value, traceback):
self.close()
with IMAPConnection() as c:
rv, data = c.list()
print(rv, data)
</code></pre>
<p>Naturally this fails since <code>IMAPConnections</code> has no attribute <code>close</code>. How can I store the connection and pass it to the <code>__exit__</code> function when the <code>with</code> statement is finished?</p>
| 1 |
2016-09-22T12:51:07Z
| 39,639,686 |
<p>You need to store connection in object attributes. Something like this: </p>
<pre><code>class IMAPConnection:
def __enter__(self):
self.connection = imaplib.IMAP4_SSL(IMAP_HOST)
try:
self.connection.login(MAIL_USERNAME, MAIL_PASS)
except imaplib.IMAP4.error:
log.error('Failed to log in')
return self.connection
def __exit__(self, type, value, traceback):
self.connection.close()
</code></pre>
<p>You would also want to implement <code>list</code> method for you class.</p>
<p>Edit: I just now realized what your actual problem is. when you do <code>with SomeClass(*args, **kwargs) as c</code> <code>c</code> is not a value returned by <code>__enter__</code> method. <code>c</code> is instance of <code>SomeClass</code>. That's a root of your problem you returned connection from <code>__enter__</code> and assumed that <code>c</code> is said connection. </p>
| 3 |
2016-09-22T12:54:46Z
|
[
"python",
"imap",
"with-statement",
"imaplib"
] |
Class_weight for SVM classifier in Python
| 39,639,698 |
<p>I have a set of parameters to choose the best ones for svm.SVC classifier using GridSearchCV:</p>
<pre><code>X=dataset.ix[:, dataset.columns != 'class']
Y=dataset['class']
X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X, Y, test_size=0.5)
clf=svm.SVC()
params=
{'kernel':['linear', 'rbf', 'poly', 'sigmoid'],
'C':[1, 5, 10],
'degree':[2,3],
'gamma':[0.025, 1.0, 1.25, 1.5, 1.75, 2.0],
'coef0':[2, 5, 9],
'class_weight': [{1:10}, 'balanced']}
searcher = GridSearchCV(clf, params, cv=9, n_jobs=-1, scoring=f1)
searcher.fit(X_train, Y_train)
</code></pre>
<p>And i get the error: <code>ValueError: class_weight must be dict, 'auto', or None, got: 'balanced'</code>
Why do I have it, if in instructions of svm parameters there is <code>'balanced'</code>, not <code>'auto'</code> ?</p>
| 0 |
2016-09-22T12:55:33Z
| 39,640,552 |
<p><code>'balanced'</code> should be working as you can see in line 51 or 74 <a href="http://sklearn%20utils%20github" rel="nofollow">https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/class_weight.py</a></p>
<p>Execute <code>sklearn.__version__</code> to check what version you are running.</p>
| 0 |
2016-09-22T13:33:23Z
|
[
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
DRY way to call method if object does not exist, or flag set?
| 39,639,732 |
<p>I have a Django database containing Paper objects, and a management command to populate the database. The management command iterates over a list of IDs and scrapes information about each one, and uses this information to populate the database. </p>
<p>This command is run each week, and any new IDs are added to the database. If the object already exists, I don't scrape, which speeds things up hugely:</p>
<pre><code>try:
paper = Paper.objects.get(id=id)
except Paper.DoesNotExist:
info = self._scrape_info(id)
self._create_or_update_item(info, id)
</code></pre>
<p>Now I want to set an <code>UPDATE_ALL</code> flag on the management command to update information about existing Paper objects, as well as just creating new ones. The problem is that it's not very DRY:</p>
<pre><code>try:
paper = Paper.objects.get(id=id)
if UPDATE_ALL:
info = self._scrape_info(id)
self._create_or_update_item(info, id)
except Paper.DoesNotExist:
info = self._scrape_info(id)
self._create_or_update_item(info, id)
</code></pre>
<p>How can I make this DRYer?</p>
<p>Django obviously has the <code>get_or_create</code> method, which I'm using in <code>_create_or_update_item</code>. However, I only want to call <code>self._scrape_info</code>, as well as creating or updating the object. </p>
| 0 |
2016-09-22T12:57:02Z
| 39,639,828 |
<p>If you want to do something like</p>
<pre><code>obj, created = Paper.objects.update_or_create(
name='Paper')
</code></pre>
<p>There is a <code>update_or_create</code> in Django since 1.7.
Take a look into <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create" rel="nofollow">docs</a> if that is suitable for you.</p>
<blockquote>
<p>A convenience method for updating an object with the given kwargs,
creating a new one if necessary. The defaults is a dictionary of
(field, value) pairs used to update the object. The values in defaults
can be callables.</p>
</blockquote>
| 0 |
2016-09-22T13:00:59Z
|
[
"python",
"django"
] |
DRY way to call method if object does not exist, or flag set?
| 39,639,732 |
<p>I have a Django database containing Paper objects, and a management command to populate the database. The management command iterates over a list of IDs and scrapes information about each one, and uses this information to populate the database. </p>
<p>This command is run each week, and any new IDs are added to the database. If the object already exists, I don't scrape, which speeds things up hugely:</p>
<pre><code>try:
paper = Paper.objects.get(id=id)
except Paper.DoesNotExist:
info = self._scrape_info(id)
self._create_or_update_item(info, id)
</code></pre>
<p>Now I want to set an <code>UPDATE_ALL</code> flag on the management command to update information about existing Paper objects, as well as just creating new ones. The problem is that it's not very DRY:</p>
<pre><code>try:
paper = Paper.objects.get(id=id)
if UPDATE_ALL:
info = self._scrape_info(id)
self._create_or_update_item(info, id)
except Paper.DoesNotExist:
info = self._scrape_info(id)
self._create_or_update_item(info, id)
</code></pre>
<p>How can I make this DRYer?</p>
<p>Django obviously has the <code>get_or_create</code> method, which I'm using in <code>_create_or_update_item</code>. However, I only want to call <code>self._scrape_info</code>, as well as creating or updating the object. </p>
| 0 |
2016-09-22T12:57:02Z
| 39,641,487 |
<p>You could incapsulate the parsing process into a helper method:</p>
<pre><code>def scrape_new_object(self, id, force_update=False):
if not force_update:
try:
Paper.objects.get(id=id)
return
except Paper.DoesNotExists:
pass
info = self._scrape_info(id)
self._create_or_update_item(info, id)
</code></pre>
<p>and then passing <code>UPDATE_ALL</code> as value to <code>force_update</code></p>
<pre><code>MyCommand.scrape_new_object(id, force_update=UPDATE_ALL)
</code></pre>
| 0 |
2016-09-22T14:13:50Z
|
[
"python",
"django"
] |
Using regroup in Django template
| 39,639,747 |
<p>I'm receiving a JSON object that contains many objects and lists of objects etc. In one of those lists is Year list like this:</p>
<pre><code>[{'Year': '2015', 'Status': 'NR', 'Month': 'Jan'
{'Year': '2014', Status': '', 'Month': 'Jan'},
{'Year': '2015', 'Status': '',Month': 'Feb'},
{'Year': '2014', Status': '', 'Month': 'Feb'},
{'Year': '2015', 'Status': '', Month': 'Sep'},
{'Year': '2014', 'Status': 'OK', 'Month': 'Sep'},
{'Year': '2015', 'Status': '', 'Month': 'Oct'},
{'Year': '2014', 'Status': 'OK', 'Month': 'Oct'}]
</code></pre>
<p>I need to group this list by Year and display months according to their year. For example:</p>
<pre><code>{"2015":[{"Month":"Jan", "Status":"NR"}, {"Month" : "Feb". "Status" :""}]
</code></pre>
<p>Right now, the code I'm using doesn't work the way I want it to, instead it repeats the years according to the number of months:</p>
<pre><code>2015
2014
2015
2014
2015
2014
2015
2014
</code></pre>
<p>This is the code:</p>
<pre><code>{% regroup x.LstPaymentBehaviour by Year as yearList %}
{% for ym in yearList %}
<tr>
<td><strong>{{ ym.grouper }}</strong></td>
</tr>
{% endfor %}
</code></pre>
<p>What am I missing?</p>
| 0 |
2016-09-22T12:57:53Z
| 39,641,014 |
<p>docs: <a href="https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup</a></p>
<p><code>regroup</code> expects ordered data in the first place. If all the items with same year are consecutive then you will get the desired output. So first sort your input data</p>
<pre><code>{% regroup x.LstPaymentBehaviour|dictsort:'Year' by Year as yearList %}
</code></pre>
| 2 |
2016-09-22T13:52:59Z
|
[
"python",
"django",
"django-templates"
] |
Inserting one item on a matrix
| 39,639,953 |
<p>How do I insert a single element into an array on numpy. I know how to insert an entire column or row using the insert and axis parameter. But how do I insert/expand by one.</p>
<p>For example, say I have an array:</p>
<pre><code>1 1 1
1 1 1
1 1 1
</code></pre>
<p>How do I insert 0 (on the same row), say on (1, 1) location, say:</p>
<pre><code>1 1 1
1 0 1 1
1 1 1
</code></pre>
<p>is this doable? If so, then how do you do the opposite (on the same column), say:</p>
<pre><code>1 1 1
1 0 1
1 1 1
1
</code></pre>
| 1 |
2016-09-22T13:06:41Z
| 39,640,498 |
<p>I think you should use <code>append()</code> of regular Python arrays (not numpy)
Here is a short example</p>
<pre><code>A = [[1,1,1],
[1,1,1],
[1,1,1]]
A[1].append(1)
</code></pre>
<p>The result is</p>
<pre><code>[[1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1]] # like in your example
</code></pre>
<p>Column extension with one element is impossible, because values are stored by rows. Thechnically you can do something like this <code>A.append([None,1,None])</code>, but this is bad practice.</p>
| -1 |
2016-09-22T13:31:25Z
|
[
"python",
"numpy"
] |
Inserting one item on a matrix
| 39,639,953 |
<p>How do I insert a single element into an array on numpy. I know how to insert an entire column or row using the insert and axis parameter. But how do I insert/expand by one.</p>
<p>For example, say I have an array:</p>
<pre><code>1 1 1
1 1 1
1 1 1
</code></pre>
<p>How do I insert 0 (on the same row), say on (1, 1) location, say:</p>
<pre><code>1 1 1
1 0 1 1
1 1 1
</code></pre>
<p>is this doable? If so, then how do you do the opposite (on the same column), say:</p>
<pre><code>1 1 1
1 0 1
1 1 1
1
</code></pre>
| 1 |
2016-09-22T13:06:41Z
| 39,640,688 |
<p>Numpy has something that <em>looks</em> like ragged arrays, but those are arrays of objects, and probably not what you want. Note the difference in the following:</p>
<pre><code>In [27]: np.array([[1, 2], [3]])
Out[27]: array([[1, 2], [3]], dtype=object)
In [28]: np.array([[1, 2], [3, 4]])
Out[28]:
array([[1, 2],
[3, 4]])
</code></pre>
<p>If you want to insert <code>v</code> into row/column <code>i/j</code>, you can do so by padding the other rows. This is easy to do:</p>
<pre><code>In [29]: a = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
In [30]: i, j, v = 1, 1, 3
In [31]: np.array([np.append(a[i_], [0]) if i_ != i else np.insert(a[i_], j, v) for i_ in range(a.shape[1])])
Out[31]:
array([[1, 1, 1, 0],
[1, 3, 1, 1],
[1, 1, 1, 0]])
</code></pre>
<p>To pad along columns, not rows, first transpose <code>a</code>, then perform this operation, then transpose again.</p>
| 3 |
2016-09-22T13:38:38Z
|
[
"python",
"numpy"
] |
create dynamic fields in WTform in Flask
| 39,640,024 |
<p>I want to create different forms in Flask using WTForms and Jinja2. I make a call to mysql, which has the type of field. </p>
<p>So i.e. the table could be:</p>
<pre><code> form_id | type | key | options | default_value
1 | TextField | title | | test1
1 | SelectField | gender |{'male','female'}|
2 | TextAreaField| text | | Hello, World!
</code></pre>
<p>Then I query on form_id. then I want to create a form with WTforms having the fields of the rows which are returned.</p>
<p>For a normal form I do:</p>
<pre><code>class MyForm(Form):
title = TextField('test1', [validators.Length(min=4, max=25)])
gender = SelectField('', choices=['male','female'])
def update_form(request):
form = MyForm(request.form)
if request.method == 'POST' and form.validate():
title = form.title.data
gender = form.gender.data
#do some updates with data
return .....
else:
return render_template('template.html',form)
#here should be something like:
#dict = query_mysql()
#new_form = MyForm(dict);
#render_template('template.html',new_form)
</code></pre>
<p>I think best would be to create an empty form and then add fields in a for-loop, however if a form is posted back how can I validate the form if I don't have it defined in a class? I do have the form_id in the form so I can generate it and then validate.</p>
| 1 |
2016-09-22T13:09:59Z
| 39,675,444 |
<h1>Adding fields dynamically</h1>
<blockquote>
<p>I think best would be to create an empty form and then add fields in a for-loop, however if a form is posted back how can I validate the form if I don't have it defined in a class?</p>
</blockquote>
<p>Add the fields to the <strong>form class</strong> using <code>setattr</code> before the form is instantiated:</p>
<pre><code>def update_form(request):
table = query()
class MyForm(Form):
pass
for row in table:
setattr(MyForm, row.key, SomeField())
form = MyForm(request.form)
</code></pre>
<p>However, I think your question is part of a bigger problem, which I have tried to address below.</p>
<h1>Mapping tables to forms</h1>
<p>Your table seem to map very nicely to the form itself. If you want to create forms dynamically from your tables, you could write the logic yourself. But when the range of fields and options to support grows, it can be a lot of work to maintain. If you are using <a href="http://www.sqlalchemy.org" rel="nofollow">SQLAlchemy</a>, you might want to take a look at <a href="https://wtforms-alchemy.readthedocs.io/" rel="nofollow">WTForms-Alchemy</a>. From its introduction:</p>
<blockquote>
<p>Many times when building modern web apps with SQLAlchemy youâll have
forms that map closely to models. For example, you might have a
Article model, and you want to create a form that lets people post new
article. In this case, it would be time-consuming to define the field
types and basic validators in your form, because youâve already
defined the fields in your model.</p>
<p>WTForms-Alchemy provides a helper class that let you create a Form
class from a SQLAlchemy model.</p>
</blockquote>
<p>The helper class is <code>ModelForm</code>, and in the style of your table, below is a Python 2/3 sample with WTForms-Alchemy. Install the package <code>wtforms-alchemy</code> first, which will pull in SQLAlchemy and WTForms as well.</p>
<pre><code>from __future__ import print_function
from __future__ import unicode_literals
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from wtforms_alchemy import ModelForm
engine = create_engine('sqlite:///:memory:')
Base = declarative_base(engine)
Session = sessionmaker(bind=engine)
session = Session()
class MyClass(Base):
__tablename__ = 'mytable'
id = sa.Column(sa.BigInteger, autoincrement=True, primary_key=True)
title = sa.Column(sa.Unicode(5), nullable=False)
gender = sa.Column(sa.Enum('male', 'female', name='gender'))
text = sa.Column(sa.Text)
class MyForm(ModelForm):
class Meta:
model = MyClass
form = MyForm()
print('HTML\n====')
for field in form:
print(field)
</code></pre>
<p>Running the above code prints:</p>
<pre><code>HTML
====
<input id="title" name="title" required type="text" value="">
<select id="gender" name="gender"><option value="male">male</option><option value="female">female</option></select>
<textarea id="text" name="text"></textarea>
</code></pre>
<p>As you can see, WTForms-Alchemy did a whole lot with <code>MyForm</code>. The class is essentially this: </p>
<pre><code>class MyForm(Form):
title = StringField(validators=[InputRequired(), Length(max=5)])
gender = SelectField(choices=[('male', 'male'), ('female', 'female')])
text = TextField()
</code></pre>
<p>The documentation for WTForms-Alchemy seems to be very comprehensive. I have not used it myself, but if I had a similar problem to solve I would definitely try it out.</p>
| 1 |
2016-09-24T10:42:02Z
|
[
"python",
"flask",
"wtforms"
] |
How to temporarily disable foreign key constraint in django
| 39,640,037 |
<p>I have to update a record which have foreign key constraint.
i have to assign 0 to the column which is defined as foreign key
while updating django don't let me to update record. </p>
| 1 |
2016-09-22T13:10:39Z
| 39,640,286 |
<p><strong>ForeignKey</strong> is a many-to-one relationship. Requires a positional argument: the class to which the model is related. </p>
<p>It must be <strong>Relation</strong> (class) or <strong>Null</strong> (if null allowed). You cannot set 0 (integer) to ForeignKey columnn.</p>
| 1 |
2016-09-22T13:22:27Z
|
[
"python",
"django",
"django-models"
] |
Temporarily disable increment in SQLAlchemy
| 39,640,078 |
<p>I am running a Flask application with SQLAlchemy (1.1.0b3) and Postgres.</p>
<p>With Flask I provide an API over which the client is able to GET all instances of a type database and POST them again on a clean version of the Flask application, as a way of local backup. When the client posts them again, they should again have the same ID as they had when he downloaded them.</p>
<p>I don't want to disable the "increment" option for primary keys for normal operation but if the client provides an ID with a POST and wishes to give a new resource said ID I would like to set it accordingly without breaking the SQLAlchemy. How can I access/reset the current maximum value of ids?</p>
<pre><code>@app.route('/objects', methods = ['POST'])
def post_object():
if 'id' in request.json and MyObject.query.get(request.json['id']) is None: #1
object = MyObject()
object.id = request.json['id']
else: #2
object = MyObject()
object.fillFromJson(request.json)
db.session.add(object)
db.session.commit()
return jsonify(object.toDict()),201
</code></pre>
<p>When adding a bunch of object WITH an id <code>#1</code> and then trying to add on WITHOUT an id or with a used id <code>#2</code>, I get.</p>
<pre><code>duplicate key value violates unique constraint "object_pkey"
DETAIL: Key (id)=(2) already exists.
</code></pre>
<p>Usually, the id is generated <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.Column.params.autoincrement" rel="nofollow">incrementally</a> but when that id is already used, there is no check for that. How can I get between the auto-increment and the INSERT?</p>
| 0 |
2016-09-22T13:12:33Z
| 39,656,631 |
<p>After adding an object with a fixed ID, you have to make sure the normal incremental behavior doesn't cause any collisions with future insertions.</p>
<p>A possible solution I can think of is to set the next insertion ID to the maximum ID (+1) found in the table. You can do that with the following additions to your code:</p>
<pre><code>@app.route('/objects', methods = ['POST'])
def post_object():
fixed_id = False
if 'id' in request.json and MyObject.query.get(request.json['id']) is None: #1
object = MyObject()
object.id = request.json['id']
fixed_id = True
else: #2
object = MyObject()
object.fillFromJson(request.json)
db.session.add(object)
db.session.commit()
if fixed_id:
table_name = MyObject.__table__.name
db.engine.execute("SELECT pg_catalog.setval(pg_get_serial_sequence('%s', 'id'), MAX(id)) FROM %s;" % (table_name, table_name))
return jsonify(object.toDict()),201
</code></pre>
<p>The next object (without a fixed id) inserted into the table will continue the id increment from the biggest id found in the table.</p>
| 0 |
2016-09-23T08:53:13Z
|
[
"python",
"rest",
"flask",
"sqlalchemy",
"auto-increment"
] |
elasticsearch python client - work with many nodes - how to work with sniffer
| 39,640,200 |
<p>i have one cluster with 2 nodes. </p>
<p>i am trying to understand the best practise to connect the nodes, and check failover when there is downtime on one node.</p>
<p>from <a href="http://elasticsearch-py.readthedocs.io/en/master/api.html#nodes" rel="nofollow">documentation</a>:</p>
<pre><code>es = Elasticsearch(
['esnode1', 'esnode2'],
# sniff before doing anything
sniff_on_start=True,
# refresh nodes after a node fails to respond
sniff_on_connection_fail=True,
# and also every 60 seconds
sniffer_timeout=60
)
</code></pre>
<p>so i tried to connect to my nodes like this:</p>
<pre><code>client = Elasticsearch([ip1, ip2],sniff_on_start=True, sniffer_timeout=10,sniff_on_connection_fail=True)
</code></pre>
<p>where ip1/ip2 are machine ip's (for example 10.0.0.1, 10.0.0.2)</p>
<p>in order to test it, i terminated ip2 (or put non existent if)
now, when i am trying to connect, i am always get:</p>
<pre><code>TransportError: TransportError(N/A, 'Unable to sniff hosts - no viable hosts found.')
</code></pre>
<p>even that ip1 is exist and up.</p>
<p>if i am trying to connect like this:</p>
<pre><code>es = Elasticsearch([ip1, ip2])
</code></pre>
<p>then i can see in log that if the client is not getting any response from ip2, it will move to ip1, and return valid response.</p>
<p>so am i missing here something? i thought that with sniffing, client wont throw any exception if one of the nodes is down, and continue working with active nodes (until next sniffing)</p>
<p><strong>update</strong>:
i get this behaviour when ever i set sniff to 'True':</p>
<pre><code>----> 1 client = Elasticsearch([ip1, ip2],sniff_on_start=True)
/usr/local/lib/python2.7/dist-packages/elasticsearch/client/__init__.pyc in __init__(self, hosts, transport_class, **kwargs)
148 :class:`~elasticsearch.Connection` instances.
149 """
--> 150 self.transport = transport_class(_normalize_hosts(hosts), **kwargs)
151
152 # namespaced clients for compatibility with API names
/usr/local/lib/python2.7/dist-packages/elasticsearch/transport.pyc in __init__(self, hosts, connection_class, connection_pool_class, host_info_callback, sniff_on_start, sniffer_timeout, sniff_timeout, sniff_on_connection_fail, serializer, serializers, default_mimetype, max_retries, retry_on_status, retry_on_timeout, send_get_body_as, **kwargs)
128
129 if sniff_on_start:
--> 130 self.sniff_hosts(True)
131
132 def add_connection(self, host):
/usr/local/lib/python2.7/dist-packages/elasticsearch/transport.pyc in sniff_hosts(self, initial)
235 # transport_schema or host_info_callback blocked all - raise error.
236 if not hosts:
--> 237 raise TransportError("N/A", "Unable to sniff hosts - no viable hosts found.")
238
239 self.set_connections(hosts)
</code></pre>
| 0 |
2016-09-22T13:18:03Z
| 39,640,389 |
<p>You need to set <code>sniff_timeout</code> to a higher value than the default value (which is 0.1 if memory serves).</p>
<p>Try it like this</p>
<pre><code>es = Elasticsearch(
['esnode1', 'esnode2'],
# sniff before doing anything
sniff_on_start=True,
# refresh nodes after a node fails to respond
sniff_on_connection_fail=True,
# and also every 60 seconds
sniffer_timeout=60,
# set sniffing request timeout to 10 seconds
sniff_timeout=10
)
</code></pre>
| 0 |
2016-09-22T13:26:28Z
|
[
"python",
"elasticsearch",
"elasticsearch-py"
] |
How i can display customer balance on sale orders in odoo?
| 39,640,232 |
<p>I want to display <strong>customer balance</strong> in sale orders but don't know how to do that. Also i want to display customer's <strong>credit limit</strong> and <strong>next payment date</strong>. Anybody have idea how i can do that, Thanks in advance...</p>
| 0 |
2016-09-22T13:19:59Z
| 39,646,295 |
<p>You can add it by related fields as follow.</p>
<p><strong>Balance Field :</strong></p>
<pre><code>customer_balance = fields.Float(related="partner_id.credit",string="Balance")
</code></pre>
<p><strong>Credit Limit</strong></p>
<pre><code>customer_credit_limit = fields.Float(related="partner_id.credit_limit",string="Credit Limit")
</code></pre>
<p>Thanks.</p>
| 1 |
2016-09-22T18:24:13Z
|
[
"python",
"openerp",
"odoo-8"
] |
Error while updating document in Elasticsearch
| 39,640,268 |
<p>I am trying to update few documents in Elasticsearch.I want to update value of few fields whose mapping type is long.Currently value of those fields is null.</p>
<p>Python Script:</p>
<pre><code>def dump_random_values():
query = {"size": 2000, "query": {"bool": {"must": [{"term": {"trip_client_id": {"value": 23}}}, {"type": {"value": "trip-details"}}]}}}
docs = es.search(index=analytics_index, doc_type="trip-details", body=query)
trips = docs["hits"]["hits"]
for trip in trips:
doc_id = trip["_id"]
trip["_source"]["vehicle_capacityInWeight"] = random.randint(40, 50)
trip["_source"]["shipment_packageWeight"] = random.randint(1, 39)
trip["_source"]["vehicle_capacityInVolume"] = random.randint(40, 50)
trip["_source"]["shipment_packageVolume"] = random.randint(1, 39)
trip["_source"]["shipment_packageUnits"] = random.randint(40, 50)
trip = {"doc": trip}
es.update(index=analytics_index, doc_type="trip-details", id=doc_id, body=trip)
</code></pre>
<p>But I am getting this error :</p>
<pre><code>File "temp_updates.py", line 32, in <module>
dump_random_values()
File "temp_updates.py", line 30, in dump_random_values
es.update(index=analytics_index, doc_type="trip-details", id=doc_id, body=trip)
File "/Users/amanagarwal/Desktop/venv/analytics-django/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped
return func(*args, params=params, **kwargs)
File "/Users/amanagarwal/Desktop/venv/analytics-django/lib/python3.5/site-packages/elasticsearch/client/__init__.py", line 460, in update
doc_type, id, '_update'), params=params, body=body)
File "/Users/amanagarwal/Desktop/venv/analytics-django/lib/python3.5/site-packages/elasticsearch/transport.py", line 329, in perform_request
status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
File "/Users/amanagarwal/Desktop/venv/analytics-django/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 109, in perform_request
self._raise_error(response.status, raw_data)
File "/Users/amanagarwal/Desktop/venv/analytics-django/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 108, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'mapper_parsing_exception', 'failed to parse')
</code></pre>
<p>What am I missing?</p>
| 1 |
2016-09-22T13:21:34Z
| 39,641,641 |
<p>It was a small mistake that I was doing.When I queried in Elasticsearch and updated the field values,I should have indexed just the "_source",and not the entire document,which contains some extra fields such as "index","took" etc.</p>
<p>Hence this should be the code change:</p>
<pre><code>def dump_random_values():
query = {"size": 2000, "query": {"bool": {"must": [{"term": {"trip_client_id": {"value": 23}}}, {"type": {"value": "trip-details"}}]}}}
docs = es.search(index=analytics_index, doc_type="trip-details", body=query)
trips = docs["hits"]["hits"]
for trip in trips:
doc_id = trip["_id"]
current = trip["_source"]
current["vehicle_capacityInWeight"] = random.randint(40, 50)
current["shipment_packageWeight"] = random.randint(1, 39)
current["vehicle_capacityInVolume"] = random.randint(40, 50)
current["shipment_packageVolume"] = random.randint(1, 39)
current["shipment_packageUnits"] = random.randint(40, 50)
trip = {"doc": current}
es.update(index=analytics_index, doc_type="trip-details", id=doc_id, body=trip)
</code></pre>
| 0 |
2016-09-22T14:20:23Z
|
[
"python",
"elasticsearch"
] |
Python: I want to check for the count of the words in the string
| 39,640,333 |
<p>I managed to do that but the case I'm struggling with is when I have to consider 'color' equal to 'colour' for all such words and return count accordingly. To do this, I wrote a dictionary of common words with spelling changes in American and GB English for this, but pretty sure this isn't the right approach.</p>
<pre><code> ukus=dict() ukus={'COLOUR':'COLOR','CHEQUE':'CHECK',
'PROGRAMME':'PROGRAM','GREY':'GRAY',
'JEWELLERY':'JEWELERY','ALUMINIUM':'ALUMINUM',
'THEATER':'THEATRE','LICENSE':'LICENCE','ARMOUR':'ARMOR',
'ARTEFACT':'ARTIFACT','CENTRE':'CENTER',
'CYPHER':'CIPHER','DISC':'DISK','FIBRE':'FIBER',
'FULFILL':'FULFIL','METRE':'METER',
'SAVOURY':'SAVORY','TONNE':'TON','TYRE':'TIRE',
'COLOR':'COLOUR','CHECK':'CHEQUE',
'PROGRAM':'PROGRAMME','GRAY':'GREY',
'JEWELERY':'JEWELLERY','ALUMINUM':'ALUMINIUM',
'THEATRE':'THEATER','LICENCE':'LICENSE','ARMOR':'ARMOUR',
'ARTIFACT':'ARTEFACT','CENTER':'CENTRE',
'CIPHER':'CYPHER','DISK':'DISC','FIBER':'FIBRE',
'FULFIL':'FULFILL','METER':'METRE','SAVORY':'SAVOURY',
'TON':'TONNNE','TIRE':'TYRE'}
</code></pre>
<p>This is the dictionary I wrote to check the values. As you can see this is degrading the performance. Pyenchant isn't available for 64bit python. Someone please help me out. Thank you in advance.</p>
| 1 |
2016-09-22T13:24:31Z
| 39,640,514 |
<p><strong>Step 1:</strong>
Create a temporary string and then replace all the words with <code>values</code> of your dict with it's corresponding keys as:</p>
<pre><code>>>> temp_string = str(my_string)
>>> for k, v in ukus.items():
... temp_string = temp_string.replace(" {} ".format(v), " {} ".format(k)) # <--surround by space " " to replace only words
</code></pre>
<p><strong>Step 2:</strong>
Now, in order to find words in the string, firstly split it into <code>list</code> of words and then use <a href="https://pymotw.com/2/collections/counter.html" rel="nofollow"><code>itertools.Counter()</code></a> to get count of each element in the <code>list</code>. Below is the sample code:</p>
<pre><code>>>> from collections import Counter
>>> my_string = 'Hello World! Hello again. I am saying Hello one more time'
>>> count_dict = Counter(my_string.split())
# Value of count_dict:
# Counter({'Hello': 3, 'saying': 1, 'again.': 1, 'I': 1, 'am': 1, 'one': 1, 'World!': 1, 'time': 1, 'more': 1})
>>> count_dict['Hello']
3
</code></pre>
<p><strong>Step 3:</strong>
Now, since you want the count of both "colour" and "color" in your dict, re-iterate the <code>dict</code> to add those values, and the missing values as "0"</p>
<pre><code>for k, v in ukus.items():
if k in count_dict:
count_dict[v] = count_dict[k]
else:
count_dict[v] = count_dict[k] = 0
</code></pre>
| 0 |
2016-09-22T13:32:00Z
|
[
"python",
"count"
] |
Python: I want to check for the count of the words in the string
| 39,640,333 |
<p>I managed to do that but the case I'm struggling with is when I have to consider 'color' equal to 'colour' for all such words and return count accordingly. To do this, I wrote a dictionary of common words with spelling changes in American and GB English for this, but pretty sure this isn't the right approach.</p>
<pre><code> ukus=dict() ukus={'COLOUR':'COLOR','CHEQUE':'CHECK',
'PROGRAMME':'PROGRAM','GREY':'GRAY',
'JEWELLERY':'JEWELERY','ALUMINIUM':'ALUMINUM',
'THEATER':'THEATRE','LICENSE':'LICENCE','ARMOUR':'ARMOR',
'ARTEFACT':'ARTIFACT','CENTRE':'CENTER',
'CYPHER':'CIPHER','DISC':'DISK','FIBRE':'FIBER',
'FULFILL':'FULFIL','METRE':'METER',
'SAVOURY':'SAVORY','TONNE':'TON','TYRE':'TIRE',
'COLOR':'COLOUR','CHECK':'CHEQUE',
'PROGRAM':'PROGRAMME','GRAY':'GREY',
'JEWELERY':'JEWELLERY','ALUMINUM':'ALUMINIUM',
'THEATRE':'THEATER','LICENCE':'LICENSE','ARMOR':'ARMOUR',
'ARTIFACT':'ARTEFACT','CENTER':'CENTRE',
'CIPHER':'CYPHER','DISK':'DISC','FIBER':'FIBRE',
'FULFIL':'FULFILL','METER':'METRE','SAVORY':'SAVOURY',
'TON':'TONNNE','TIRE':'TYRE'}
</code></pre>
<p>This is the dictionary I wrote to check the values. As you can see this is degrading the performance. Pyenchant isn't available for 64bit python. Someone please help me out. Thank you in advance.</p>
| 1 |
2016-09-22T13:24:31Z
| 39,710,348 |
<p>Okay, I think I know enough from your comments to provide this as a solution. The function below allows you to choose either UK or US replacement (it uses US default, but you can of course flip that) and allows for you to either perform minor hygiene on the string.</p>
<pre><code>import re
ukus={'COLOUR':'COLOR','CHEQUE':'CHECK',
'PROGRAMME':'PROGRAM','GREY':'GRAY',
'JEWELLERY':'JEWELERY','ALUMINIUM':'ALUMINUM',
'THEATER':'THEATRE','LICENSE':'LICENCE','ARMOUR':'ARMOR',
'ARTEFACT':'ARTIFACT','CENTRE':'CENTER',
'CYPHER':'CIPHER','DISC':'DISK','FIBRE':'FIBER',
'FULFILL':'FULFIL','METRE':'METER',
'SAVOURY':'SAVORY','TONNE':'TON','TYRE':'TIRE'}
usuk={'COLOR':'COLOUR','CHECK':'CHEQUE',
'PROGRAM':'PROGRAMME','GRAY':'GREY',
'JEWELERY':'JEWELLERY','ALUMINUM':'ALUMINIUM',
'THEATRE':'THEATER','LICENCE':'LICENSE','ARMOR':'ARMOUR',
'ARTIFACT':'ARTEFACT','CENTER':'CENTRE',
'CIPHER':'CYPHER','DISK':'DISC','FIBER':'FIBRE',
'FULFIL':'FULFILL','METER':'METRE','SAVORY':'SAVOURY',
'TON':'TONNNE','TIRE':'TYRE'}
def str_wd_count(my_string, uk=False, hygiene=True):
us = not(uk)
# if the UK flag is TRUE, default to UK version, else default to US version
print "Using the "+uk*"UK"+us*"US"+" dictionary for default words"
# optional hygiene of non-alphanumeric characters for pure word counting
if hygiene:
my_string = re.sub('[^ \d\w]',' ',my_string)
my_string = re.sub(' {1,}',' ',my_string)
# create a list of the unqique words in the text
ttl_wds = [ukus.get(w,w) if us else usuk.get(w,w) for w in my_string.upper().split(' ')]
wd_counts = {}
for wd in ttl_wds:
wd_counts[wd] = wd_counts.get(wd,0)+1
return wd_counts
</code></pre>
<p>As a sample of use, consider the string </p>
<pre><code>str1 = 'The colour of the dog is not the same as the color of the tire, or is it tyre, I can never tell which one will fulfill'
# Resulting sorted dict.items() With Default Settings
'[(THE,5),(TIRE,2),(COLOR,2),(OF,2),(IS,2),(FULFIL,1),(NEVER,1),(DOG,1),(SAME,1),(IT,1),(WILL,1),(I,1),(AS,1),(CAN,1),(WHICH,1),(TELL,1),(NOT,1),(ONE,1),(OR,1)]'
# Resulting sorted dict.items() With hygiene=False
'[(THE,5),(COLOR,2),(OF,2),(IS,2),(FULFIL,1),(NEVER,1),(DOG,1),(SAME,1),(TIRE,,1),(WILL,1),(I,1),(AS,1),(CAN,1),(WHICH,1),(TELL,1),(NOT,1),(ONE,1),(OR,1),(IT,1),(TYRE,,1)]'
# Resulting sorted dict.items() With UK Swap, hygiene=True
'[(THE,5),(OF,2),(IS,2),(TYRE,2),(COLOUR,2),(WHICH,1),(I,1),(NEVER,1),(DOG,1),(SAME,1),(OR,1),(WILL,1),(AS,1),(CAN,1),(TELL,1),(NOT,1),(FULFILL,1),(ONE,1),(IT,1)]'
# Resulting sorted dict.items() With UK Swap, hygiene=False
'[(THE,5),(OF,2),(IS,2),(COLOUR,2),(ONE,1),(I,1),(NEVER,1),(DOG,1),(SAME,1),(TIRE,,1),(WILL,1),(AS,1),(CAN,1),(WHICH,1),(TELL,1),(NOT,1),(FULFILL,1),(TYRE,,1),(IT,1),(OR,1)]'
</code></pre>
<p>You can use the resulting dictionary of word counts in any way you'd like, and if you need the original string with the modifications added it is easy enough to modify the function to also return that.</p>
| 0 |
2016-09-26T18:58:29Z
|
[
"python",
"count"
] |
Django Admin: Numeric field filter
| 39,640,350 |
<p>How to create filter for numeric data in Django Admin with range inputs?</p>
<p>P.S. Found only this similar question, but here suggest only how to group by concrete ranges and last question activity was 2 years ago.</p>
<p><a href="http://stackoverflow.com/questions/4060396/django-admin-how-do-i-filter-on-an-integer-field-for-a-specific-range-of-values">Django Admin: How do I filter on an integer field for a specific range of values</a></p>
| 0 |
2016-09-22T13:25:01Z
| 39,641,497 |
<p><strong>Warning!</strong> Some parts of API from django, mentioned in my answer, are considered internal and may be changed in future releases of django without any notification.</p>
<p>Taking that note to your mind, it is actually pretty easy to create your own filter. All you need to do is:</p>
<ol>
<li>subclass <code>SimpleListFilter</code> and create some method inside that will generate your default range values and selected range values (for rendering template with your filter)</li>
<li>Set queryset method that will take parameters submitted by your filter and filter list queryset</li>
<li>create template with your filter (based on <a href="https://github.com/django/django/blob/stable/1.10.x/django/contrib/admin/templates/admin/filter.html" rel="nofollow">admin/filter.html</a>)</li>
<li>set <code>template</code> property in your <code>SimpleListFilter</code> subclass, pointing to your filter template.</li>
</ol>
<p>Django will pass to your template 3 parameters:</p>
<ul>
<li><code>title</code> - your filter title (taken from <code>title</code> property in your class)</li>
<li><code>choices</code> - list of dicts generated by <code>choices</code> method of your class (by default it modifies list of tuples returned by <code>lookups</code> method)</li>
<li><code>spec</code> - your class instance.</li>
</ul>
<p>From that point, you can get to any attribute or method of your class, using <code>spec</code> in template, so creation of any filter should be possible.</p>
| 1 |
2016-09-22T14:14:10Z
|
[
"python",
"django",
"django-admin"
] |
Python Unit Test Dictionary Assert KeyError
| 39,640,395 |
<p>I wasn't sure how to create a Python unittest to check if a dictionary returned a KeyError. I thought the unit test would call the dictionary key so it would look like this:</p>
<pre><code>def test_dict_keyerror_should_appear(self):
my_dict = {'hey': 'world'}
self.assertRaises(KeyError, my_dict['some_key'])
</code></pre>
<p>However, my test would just error out with a <strong>KeyError</strong> instead of asserting that a KeyError occurred.</p>
| 1 |
2016-09-22T13:26:54Z
| 39,640,396 |
<p>To solve this I used a <code>lambda</code> to call the dictionary key to raise the error.</p>
<pre><code>def test_dict_keyerror_should_appear(self):
my_dict = {'hey': 'world'}
self.assertRaises(KeyError, lambda: my_dict['some_key'])
</code></pre>
| 1 |
2016-09-22T13:26:54Z
|
[
"python",
"python-unittest"
] |
Python Unit Test Dictionary Assert KeyError
| 39,640,395 |
<p>I wasn't sure how to create a Python unittest to check if a dictionary returned a KeyError. I thought the unit test would call the dictionary key so it would look like this:</p>
<pre><code>def test_dict_keyerror_should_appear(self):
my_dict = {'hey': 'world'}
self.assertRaises(KeyError, my_dict['some_key'])
</code></pre>
<p>However, my test would just error out with a <strong>KeyError</strong> instead of asserting that a KeyError occurred.</p>
| 1 |
2016-09-22T13:26:54Z
| 39,640,548 |
<p>Another option would be to use <a href="https://docs.python.org/3/library/operator.html#operator.getitem" rel="nofollow"><code>operator.getitem</code></a>:</p>
<pre><code>from operator import getitem
self.assertRaises(KeyError, getitem, my_dict, 'some_key')
</code></pre>
| 1 |
2016-09-22T13:33:09Z
|
[
"python",
"python-unittest"
] |
Python requests module file
| 39,640,451 |
<p>I am using a third party tool which uses a basic python installation but can compile new python modules on its own. All it needs is a .py file which can be compiled. Somehow, I am not able to locate a readily available requests module file which has the python code within it. Is it possible to guide me to any such resources. I have checked the github link from the requests official page: <a href="https://github.com/kennethreitz/requests" rel="nofollow">https://github.com/kennethreitz/requests</a> but I'm confused as to which file to clone. My best guess is that its the <em>init</em>.py file but I'm not sure.Any guidance on this would be helpful-</p>
<p>Please refer the screenshot below; I have highlighted the folder which I presume has the correct compileable python files needed for requests. If this is not the right folder please share your suggestions-</p>
<p><a href="http://i.stack.imgur.com/fapPE.jpg" rel="nofollow">download page from github</a></p>
<p>Thanks</p>
| -1 |
2016-09-22T13:29:37Z
| 39,640,641 |
<p>you could do <code>pip install requests</code></p>
<p>If you dont have PIP installed then you can install it from <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">https://bootstrap.pypa.io/get-pip.py</a></p>
<p>and then can do <code>python get-pip.py</code>to install pip</p>
<p>alternatively you could also look at <code>easy-install</code></p>
| 0 |
2016-09-22T13:36:47Z
|
[
"python",
"python-requests"
] |
How do I make text(one letter) fill out a tkinter button?
| 39,640,537 |
<p>I have a tic tac toe game I'm trying to put the finishing touches on. Each tile in the game is a button with the letter 'x' or 'o'. But I can't seem to get the letters to fill out the frame. When I change the font size, the buttons bloat out. If I try to set the tile height/weight after setting the font size it doesn't seem to have any effect. </p>
<p>Is there a way to simply make an 'x' expand out to fill the button it's in?</p>
<pre><code>class TicTacToeBoard(Frame):
def __init__(self, parent=None, game=None):
Frame.__init__(self, parent)
# We are controlling the gui through an external game class.
self.game = game
self.symbol = game.sym()
mainframe = ttk.Frame(root, padding=(12, 12, 12, 12))
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
# This is how we change the tile a player plays on.
self.strVars = [StringVar() for x in range(9)]
# Setup the button tiles
self.buttons = []
for i, s in enumerate(self.strVars):
func = (lambda i=i: self.btn_press(i))
b = Button(mainframe, textvariable=s, font='size, 35', command=func)
b.config(height=5, width=10)
self.buttons.append(b)
# Add each tile to the grid
for x in range(3):
for y in range(3):
self.buttons.pop(0).grid(row=x, column=y)
</code></pre>
| -1 |
2016-09-22T13:32:41Z
| 39,901,263 |
<p>I would say there is no way to make characters automatically fill the entire button's space. Consider <code>Canvas</code> objects instead of <code>Button</code>s. There you can easily draw an X (two lines) and an O (circle) with full control over the size and the space between the edge of the canvas and the sign. Maybe it makes even sense to make a field in the UI an own class.</p>
<pre><code>from functools import partial
from itertools import cycle
import tkinter as tk
class FieldUI(tk.Canvas):
def __init__(self, parent, size, variable):
tk.Canvas.__init__(self, parent, width=size, height=size)
self.size = size
self.variable = variable
self.variable.trace('w', self.update_display)
self.update_display()
def update_display(self, *_args):
self.delete(tk.ALL)
value = self.variable.get()
if value == 'x':
self.create_line(5, 5, self.size - 5, self.size - 5, width=4)
self.create_line(self.size - 5, 5, 5, self.size - 5, width=4)
elif value == 'o':
self.create_oval(5, 5, self.size - 5, self.size - 5, width=4)
elif value != '':
raise ValueError("only 'x', 'o', and '' allowed")
class GameUI(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, background='black')
self.symbols = cycle('xo')
self.field_vars = [tk.StringVar() for _ in range(9)]
for i, field_var in enumerate(self.field_vars):
field_ui = FieldUI(self, 50, field_var)
field_ui.bind('<Button-1>', partial(self.on_click, i))
column, row = divmod(i, 3)
field_ui.grid(row=row, column=column, padx=1, pady=1)
def on_click(self, field_index, _event=None):
field_var = self.field_vars[field_index]
if not field_var.get():
field_var.set(next(self.symbols))
def main():
root = tk.Tk()
game_ui = GameUI(root)
game_ui.pack()
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
| 0 |
2016-10-06T16:31:15Z
|
[
"python",
"button",
"tkinter"
] |
Python multiprocessing pool with shared data
| 39,640,556 |
<p>I'm attempting to speed up a multivariate fixed-point iteration algorithm using multiprocessing however, I'm running issues dealing with shared data. My solution vector is actually a named dictionary rather than a vector of numbers. Each element of the vector is actually computed using a different formula. At a high level, I have an algorithm like this:</p>
<pre><code>current_estimate = previous_estimate
while True:
for state in all_states:
current_estimate[state] = state.getValue(previous_estimate)
if norm(current_estimate, previous_estimate) < tolerance:
break
else:
previous_estimate, current_estimate = current_estimate, previous_estimate
</code></pre>
<p>I'm trying to parallelize the for-loop part with multiprocessing. The <code>previous_estimate</code> variable is read-only and each process only needs to write to one element of <code>current_estimate</code>. My current attempt at rewriting the for-loop is as follows:</p>
<pre><code># Class and function definitions
class A(object):
def __init__(self,val):
self.val = val
# representative getValue function
def getValue(self, est):
return est[self] + self.val
def worker(state, in_est, out_est):
out_est[state] = state.getValue(in_est)
def worker_star(a_b_c):
""" Allow multiple arguments for a pool
Taken from http://stackoverflow.com/a/5443941/3865495
"""
return worker(*a_b_c)
# Initialize test environment
manager = Manager()
estimates = manager.dict()
all_states = []
for i in range(5):
a = A(i)
all_states.append(a)
estimates[a] = 0
pool = Pool(process = 2)
prev_est = estimates
curr_est = estimates
pool.map(worker_star, itertools.izip(all_states, itertools.repeat(prev_est), itertools.repreat(curr_est)))
</code></pre>
<p>The issue I'm currently running into is that the elements added to the <code>all_states</code> array are not the same as those added to the <code>manager.dict()</code>. I keep getting <code>key value</code> errors when trying to access elements of the dictionary using elements of the array. And debugging, I found that none of the elements are the same.</p>
<pre><code>print map(id, estimates.keys())
>>> [19558864, 19558928, 19558992, 19559056, 19559120]
print map(id, all_states)
>>> [19416144, 19416208, 19416272, 19416336, 19416400]
</code></pre>
| 1 |
2016-09-22T13:33:25Z
| 39,640,879 |
<p>This is happening because the objects you're putting into the <code>estimates</code> <code>DictProxy</code> aren't actually the same objects as those that live in the regular dict. The <code>manager.dict()</code> call returns a <code>DictProxy</code>, which is proxying access to a <code>dict</code> that actually lives in a completely separate manager process. When you insert things into it, they're really being copied and sent to a remote process, which means they're going to have a different identity.</p>
<p>To work around this, you can define your own <code>__eq__</code> and <code>__hash__</code> functions on <code>A</code>, as <a href="http://stackoverflow.com/questions/2909106/python-whats-a-correct-and-good-way-to-implement-hash">described in this question</a>:</p>
<pre><code>class A(object):
def __init__(self,val):
self.val = val
# representative getValue function
def getValue(self, est):
return est[self] + self.val
def __hash__(self):
return hash(self.__key())
def __key(self):
return (self.val,)
def __eq__(x, y):
return x.__key() == y.__key()
</code></pre>
<p>This means the key look ups for items in the <code>estimates</code> will just use the value of the <code>val</code> attribute to establish identity and equality, rather than the <code>id</code> assigned by Python.</p>
| 1 |
2016-09-22T13:47:31Z
|
[
"python",
"dictionary",
"multiprocessing",
"shared-memory"
] |
Issue trying to read spreadsheet line by line and write to excel (downsample)
| 39,640,561 |
<p>I am trying to write some code to downsample a very large excel file. It needs to copy the first 4 lines exactly, then on the 5th line start taking every 40th line. I currently have this</p>
<pre><code>import os
import string
import shutil
import datetime
folders = os.listdir('./')
names = [s for s in folders if "csv" in s]
zips = [s for s in folders if "zip" in s]
for folder in names:
filename = folder
shutil.move(folder, './Archive')
with open(filename) as f:
counter = 0
for line in f:
counter += 1
f_out = open('./DownSampled/' + folder + '.csv', 'w')
if counter < 5:
f_out.write(line)
elif (counter+35) % 40 == 0:
f_out.write(line)
f_out.close()
</code></pre>
<p>It moves the files to the Archive folder, but does not create a downsampled version, any ideas on what I could be doing wrong here?</p>
| 0 |
2016-09-22T13:33:43Z
| 39,640,638 |
<p>You're overwriting the file on each iteration of the previous file. Move that <code>open(...)</code> out of the <code>for</code> loop:</p>
<pre><code>with open(filename) as f, open('./DownSampled/' + folder + '.csv', 'w') as f_out:
for i, line in enumerate(f):
if i < 5:
f_out.write(line)
elif (i+35) % 40 == 0:
f_out.write(line)
</code></pre>
<p>More so, <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> can replace your count logic.</p>
| 1 |
2016-09-22T13:36:40Z
|
[
"python",
"excel"
] |
python logistic regression - patsy design matrix and categorical data
| 39,640,672 |
<p>Quite new to python and machine learning. </p>
<p>I am trying to build a logistic regression model. I have worked in R to gain lambda and used cross-validation to find the best model and am now moving it into python. </p>
<p>Here I have created a design matrix and made it sparse. Then ran the logistic regression. It seems to be working. </p>
<p>My question is, since I have stated my term item_number is a category how to I know which has become the dummy variable? And how do I know which coefficient goes with each category name?</p>
<pre><code>from patsy import dmatrices
from sklearn.linear_model import LogisticRegression
from sklearn import preprocessing
def train_model (data, frm, Rlambda):
y, X = dmatrices(frm , data, return_type="matrix")
y = np.ravel(y)
scaler = sklearn.preprocessing.MaxAbsScaler(copy=False)
X_trans = scaler.fit_transform(X)
model = LogisticRegression(penalty ='l2', C=1/Rlambda)
model = model.fit(X_trans, y)
frm = 'purchase ~ price + C(item_number)'
Rlambda = 0.01
model, train_score = train_model(data1,frm,Rlambda)
</code></pre>
| 0 |
2016-09-22T13:37:59Z
| 39,641,281 |
<p>First I will fix an error with your code and then I will answer your question.</p>
<p>Your code:
Your <code>train_model</code> function won't return what you think it returns. Currently, it doesn't return anything, and you want it to return both your model and the training score. When you fit a model, you need to define what you mean by the training score - the model won't return anything to you by default. For now let's just return the model that you trained.</p>
<p>So you should update your <code>train_model</code> function as follows:</p>
<pre><code>def train_model (data, frm, Rlambda):
y, X = dmatrices(frm , data, return_type="matrix")
y = np.ravel(y)
scaler = sklearn.preprocessing.MaxAbsScaler(copy=False)
X_trans = scaler.fit_transform(X)
model = LogisticRegression(penalty ='l2', C=1/Rlambda)
# model.fit() operates in-place
model.fit(X_trans, y)
return model
</code></pre>
<p>Now when you want to determine what variables correspond to, <code>model.coef_</code> returns you all the coefficients in the decision function, of size <code>(n_classes, n_features)</code>. The order of the coefficients correspond to the order that your features were passed into the <code>.fit()</code> method. So in your case, <code>X_trans</code> is the design matrix of size <code>(n_samples, n_features)</code>, so each of the coefficients in <code>model.coef_</code> exactly correspond to the coefficients for each of the <code>n_features</code> in <code>X</code> in the same order they are presented in <code>X</code>.</p>
| 0 |
2016-09-22T14:03:45Z
|
[
"python",
"scikit-learn",
"patsy"
] |
Django, tutorial - error: No module named urls
| 39,640,718 |
<p>Hi I am following the tutorial to make first web app by Django(<a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/#write-your-first-view" rel="nofollow">link</a>)
But I was given this error:</p>
<pre><code> File "c:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "c:\Python27\lib\site-packages\django\core\management\base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "c:\Python27\lib\site-packages\django\core\management\base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "c:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "c:\Python27\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "c:\Python27\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "c:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "c:\Python27\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "c:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "c:\Python27\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "c:\Python27\Proj\mysite\mysite\urls.py", line 7, in <module>
url(r'^polls/', include('polls.urls'))
File "c:\Python27\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name) ImportError: No module named urls
</code></pre>
<p>I have read some answers here on SO, but they suggest that this error is caused by wrong version of framework, which is not my case. My version of python is 2.7 and Djanog 1.10.1</p>
<p>My urls.py</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')) ]
</code></pre>
<p>Thank you.</p>
<p>EDIT:</p>
<p>File: polls/urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
</code></pre>
<p>EDIT 2:</p>
<p>Thank all for your comments. There is my file structure of the project.</p>
<p><a href="http://i.stack.imgur.com/5eYEX.png" rel="nofollow"><img src="http://i.stack.imgur.com/5eYEX.png" alt="enter image description here"></a></p>
| 1 |
2016-09-22T13:39:58Z
| 39,640,968 |
<p>Basic question, but in the settings.py file, do you have <code>polls</code> defined inside the <code>INSTALLED_APPS setting?</code></p>
| -2 |
2016-09-22T13:51:23Z
|
[
"python",
"django"
] |
Django, tutorial - error: No module named urls
| 39,640,718 |
<p>Hi I am following the tutorial to make first web app by Django(<a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/#write-your-first-view" rel="nofollow">link</a>)
But I was given this error:</p>
<pre><code> File "c:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "c:\Python27\lib\site-packages\django\core\management\base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "c:\Python27\lib\site-packages\django\core\management\base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "c:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "c:\Python27\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "c:\Python27\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "c:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "c:\Python27\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "c:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "c:\Python27\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "c:\Python27\Proj\mysite\mysite\urls.py", line 7, in <module>
url(r'^polls/', include('polls.urls'))
File "c:\Python27\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name) ImportError: No module named urls
</code></pre>
<p>I have read some answers here on SO, but they suggest that this error is caused by wrong version of framework, which is not my case. My version of python is 2.7 and Djanog 1.10.1</p>
<p>My urls.py</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')) ]
</code></pre>
<p>Thank you.</p>
<p>EDIT:</p>
<p>File: polls/urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
</code></pre>
<p>EDIT 2:</p>
<p>Thank all for your comments. There is my file structure of the project.</p>
<p><a href="http://i.stack.imgur.com/5eYEX.png" rel="nofollow"><img src="http://i.stack.imgur.com/5eYEX.png" alt="enter image description here"></a></p>
| 1 |
2016-09-22T13:39:58Z
| 39,641,026 |
<p><code>url(r'^polls/', include('polls.urls'))</code></p>
<p>What this line is doing is it's adding the <code>urls.py</code> of <code>polls</code> app folder, to your urls and also appending <code>polls/</code> in front of all.</p>
<p><strong>Coming to the error :</strong> </p>
<pre><code>File "c:\Python27\Proj\mysite\mysite\urls.py", line 7, in <module>
url(r'^polls/', include('polls.urls'))
</code></pre>
<p>The error says that it's not able to find that <code>urls.py</code> in <code>polls</code> folder, so make sure it's there. and properly configured as well.</p>
<p>And also make sure the following : </p>
<ul>
<li>your app polls listed in <code>INSTALLED_APPS</code> of <code>settings.py</code></li>
<li>confirm that there is an <code>__init__.py</code> file in your <code>polls</code> app folder</li>
</ul>
| 2 |
2016-09-22T13:53:23Z
|
[
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.