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 |
|---|---|---|---|---|---|---|---|---|---|
Setting Order of Columns with matplotlib bar chart | 39,135,472 | <p>I produce a bar graph with the following code: </p>
<pre><code>Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')
</code></pre>
<p>It produces the following bar chart: </p>
<p><a href="http://i.stack.imgur.com/4sWHw.png" rel="nofollow"><img src="http://i.stack.imgur.com/4sWHw.png" alt="enter image description here"></a></p>
<p>I would like to change the order the columns are listed. I've tried a few different things that aren't seeming to work. The DataFrame I am working with looks like this:</p>
<p><a href="http://i.stack.imgur.com/GBj7o.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/GBj7o.jpg" alt="enter image description here"></a></p>
<p>I am creating a barplot of the last column in the dataframe pictured. Any direction or ideas of alternate methods of creating a barplot that would allow me to change the order of the axis would be greatly appreciated. As it exists its difficult to interpret. </p>
| 2 | 2016-08-25T01:45:53Z | 39,135,642 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_index.html" rel="nofollow"><code>sort_index</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html" rel="nofollow"><code>Series.plot.bar</code></a>:</p>
<pre><code>weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()
</code></pre>
<p>Or if you want use your solution:</p>
<pre><code>Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
df.plot(kind = 'bar')
</code></pre>
<p>Sample:</p>
<pre><code>import matplotlib.pyplot as plt
weatherDFConcat = pd.DataFrame({'TEMPBIN_CON':['30 degrees or more', '-15 to -18 degrees', '-3 to 0 degrees', '15 to 18 degrees', '-15 to -18 degrees'
]})
print (weatherDFConcat)
TEMPBIN_CON
0 30 degrees or more
1 -15 to -18 degrees
2 -3 to 0 degrees
3 15 to 18 degrees
4 -15 to -18 degrees
weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()
plt.show()
</code></pre>
| 2 | 2016-08-25T02:07:56Z | [
"python",
"pandas",
"numpy",
"matplotlib",
"bar-chart"
] |
Send commands to twisted server | 39,135,509 | <p>I have a simple twisted TCP server that I am using to send and receive data from another application. I am able to communicate and send messages to this application once a connection has been established. </p>
<p>What I want to be able to do have an external module command when and what to send to the 3rd party application (instead of when connected). For example, here is my server code:</p>
<pre><code>from twisted.internet import reactor, protocol
# Twisted
class Tcp(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
print 'data received: ', data
# do something with data
def connectionMade(self, msg):
# Want to only transport message when I command not immediately when connected
self.transport.write(msg)
class TcpFactory(protocol.Factory):
def buildProtocol(self, addr):
return Tcp()
reactor.listenTCP(8001, TcpFactory())
reactor.run()
</code></pre>
<p>I have another module (operated by a GUI interface) which defines what message to send and this message needs to be passed as 'msg' into connectionMade</p>
<p>What is the best way to do this?</p>
| 0 | 2016-08-25T01:50:49Z | 39,147,570 | <p>Your 3rd party call will happen <strong>from within <code>connectionMade</code></strong> and should not call it directly. The <code>connectionMade</code> is a Twisted callback and it's there to signal that a client is on the other side. It's up to you to dictate what happens after that. So you can do something like make a series of <code>Deferred</code>s/callbacks which take <code>self.transport</code> (this holds relevant client data). In those series of callbacks, you'll have your logic for</p>
<ol>
<li>communicating with the 3rd party</li>
<li>validating client</li>
<li>sending a message to the client</li>
</ol>
<p>This is the gist of it:</p>
<pre><code>def connectionMade(self):
d = Deferred()
d.addCallback(self.thirdPartyComm).addErrBack(self.handleError)
d.addCallback(sendMsg)
d.callback(self.transport)
def thirdPartyComm(self, transport):
# logic for talking to 3rd party goes here
# 3rd party should validate the client then provide a msg
# or raise exception if client is invalid
return msg
def handleError(self, error):
# something went wrong, kill client connection
self.transport.loseConnection()
def sendMsg(self, msg):
self.transport.write(msg)
</code></pre>
| 0 | 2016-08-25T14:08:53Z | [
"python",
"tcp",
"twisted"
] |
Threading inside For Loop And While Using Events In Tkinter~Python | 39,135,649 | <p>Trying a scenario where in I wanted to proceed in the for loop based on threading mechanism [for syncing/wait mechanism] as shown in the code below.</p>
<pre><code>#!/tools/bin/python
# Global Import Variables
import Tkinter
from Tkinter import *
import subprocess
import shlex
import os
from PIL import Image, ImageTk
import time
import string
import threading
class test_template:
def __init__(self, master):
self.master = master
self.next_button = None
self.fruit_lbl = None
self.yes_button = None
self.no_button = None
self.yes_no_button_done = threading.Event()
# For Loop Goes From 0 To 10
for i in range (10):
if not (self.fruit_lbl):
self.fruit_lbl = Label(root, text="Do You Want To Change The Color Of Fruit %d"%i)
self.fruit_lbl.grid(row=1, column=0)
if not (self.yes_button):
self.yes_button = Button(root, background="lawn green", activebackground="forest green", text="YES", command=self.yes_button_code).grid(row=2, column=1)
if not (self.no_button):
self.no_button = Button(root, background="orange red", activebackground="orangered3", text="NO", command=self.no_button_code).grid(row=2, column=2)
while not self.yes_no_button_done.isSet():
self.yes_no_button_done.wait()
def yes_button_code(self):
print "Inside YES Button Config"
def no_button_code(self):
print "Inside No Button Config"
self.yes_no_button_done.set()
# Top Local Variables
root = Tk()
#root.configure(background='black')
# Top Level Default Codes
my_gui = test_template(root)
root.mainloop()
</code></pre>
<p>Its like the for loop needs to wait until I press either Yes Or No, until then the while loop should be waiting for the event set.</p>
<p>But somehow the threading/wait mechanism is not working fine i.e. as soon I launch the code, its goes into the while loop and goes haywire. Am I missing anything on the above code ? Share in your comments !! </p>
| 0 | 2016-08-25T02:08:49Z | 39,161,303 | <p>If I have undertood you correctly I dont think that you need to use threading at all. Consider the following:</p>
<pre><code>from Tkinter import *
class test_template:
def __init__(self, master):
self.master = master
self.loop_count = IntVar()
self.loop_count.set(1)
l = Label(self.master, text='Change colour of fruit?')
l.pack()
count = Label(self.master, textvariable = '%s' % self.loop_count)
count.pack()
yes = Button(self.master, text = 'YES', command = self.loop_counter)
yes.pack()
no = Button(self.master, text = 'NO', command = self.loop_counter)
no.pack()
def loop_counter(self):
if self.loop_count.get() == 10:
print 'Finished'
self.master.quit()
else:
self.loop_count.set(self.loop_count.get()+1)
print self.loop_count.get()
root = Tk()
GUI = test_template(root)
root.mainloop()
</code></pre>
<p>Let me know what you think.</p>
<p>Cheers,
Luke</p>
| 0 | 2016-08-26T08:03:06Z | [
"python",
"python-2.7",
"tkinter"
] |
Remove row from dataframe if column value | 39,135,698 | <p>If I have a dataframe like this:</p>
<pre><code>index col1 col2
a a1 a2
b b1 b2
c c1 b2
</code></pre>
<p>Is it possible to use the <code>.drop()</code> to delete rows which have a sudden value in one of their columns?</p>
<p>Something like: <code>df.drop(col2 = 'b2')</code></p>
| 2 | 2016-08-25T02:13:21Z | 39,135,709 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>df = df[df.col2 != 'b2']
</code></pre>
| 3 | 2016-08-25T02:15:19Z | [
"python",
"pandas",
"indexing",
"dataframe",
"filter"
] |
Remove row from dataframe if column value | 39,135,698 | <p>If I have a dataframe like this:</p>
<pre><code>index col1 col2
a a1 a2
b b1 b2
c c1 b2
</code></pre>
<p>Is it possible to use the <code>.drop()</code> to delete rows which have a sudden value in one of their columns?</p>
<p>Something like: <code>df.drop(col2 = 'b2')</code></p>
| 2 | 2016-08-25T02:13:21Z | 39,135,732 | <p>You can use a boolean filter. For example:</p>
<pre><code>df = df[df['col1'] != 'a1']
</code></pre>
<p>Would drop all rows with the value a1 in column col1. See <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow">this page of the Pandas docs</a> for more details. It's a very long page, search for 'filter' to jump to the relevant section.</p>
| 1 | 2016-08-25T02:18:04Z | [
"python",
"pandas",
"indexing",
"dataframe",
"filter"
] |
python url with unexpected "amp" and ";" | 39,135,716 | <p>Hi all I'm in a problem when doing web scraping with python.
code </p>
<pre><code>from urllib.request import urlopen
from urllib.request import urlretrieve
from bs4 import BeautifulSoup
import urllib.error
import http.cookiejar,requests,pymysql,json ,re
session = requests.Session()
monthurl = 'http://search.proquest.com/publication.publicationissuebrowse:drilldown/month/%E5%85%AB%E6%9C%88/08/year/2016/parentmonth082016'
payload = {"site": "news","t:ac" : "publications_105983"}
headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0','Accept':'text/javascript, text/html,application/xml, text/xml, */*',\
'Accept-Encoding':'gzip, deflate','Accept-Language':'zh-CN,zh;q=0.8','Host':'search.proquest.com', 'Content-type':'application/x-www-form-urlencoded; charset=UTF-8', 'Connection':'keep-alive','Content-Length':'0','Origin':'http://search.proquest.com','Referer':'http://search.proquest.com/news/publication/105983/citation/99D2C84D41804033PQ/2?accountid=13818','X-Prototype-Version':'1.7','X-Requested-With':'XMLHttpRequest',\
'Cookie':'availability-zone=us-east-1a; mwtbid=830706AE-9389-4BB4-812D-B597683B812E; _ga=GA1.2.1201070524.1446763952; fsr.r=%7B%22d%22%3A90%2C%22i%22%3A%22de07553-78769885-bcc1-4823-67c96%22%2C%22e%22%3A1467984529571%7D; fulltextShowAll=YES; oneSearchTZ=480; authenticatedBy=IP; availability-zone=us-east-1a; _gat_UA-61126923-3=1; JSESSIONID=69A1CC852FF1123A9A78CFC18E2B6AFF.i-b86ebbb9; OS_VWO_COUNTRY=CN; OS_VWO_INSTITUTION=13818; OS_VWO_LANGUAGE=zho; OS_VWO_MY_RESEARCH=false; OS_VWO_REFERRING_URL=""; OS_VWO_REQUESTED_URL="http://search.proquest.com/news/publication/105983/citation/8558F5818C234BCFPQ/2?accountid=13818"; OS_PERSISTENT="wrPZtfJDrH0WIWT5cZZs+CwLAAUhJMHD++Vls3rVx5E="; OS_VWO_VISITOR_TYPE=returning; AWSELB=C393A78D02CA3EE2799CF8894B23627240E8CACE66D1C0BB8AD720DF21EC8ACE1D897A32BEBC089642A0472335D0E12E2E117186F0CCDBF88A5E8AB2CD9F31FA13EA9CDBB3A68FF4DB78B55F4406384017E95C9573; AppVersion=r20161.6.0.834.574; _vwo_uuid_v2=0308785C38305F47209E7EC8811AC0A2|3ec2dd2ac5e7bfcc195a554e24406f22; osTimestamp=1472090234.391; WT_FPC=id=202.120.14.195-2899434048.30480412:lv=1472043437504:ss=1472043437504; fsr.s=%7B%22cp%22%3A%7B%22Usage_Session%22%3A%2220160825015947140%3A312846%22%2C%22cxreplayaws%22%3A%22true%22%2C%22Error_Page%22%3A%22no%22%2C%22No_Results%22%3A%22no%22%2C%22My_Research%22%3A%22no%22%2C%22Advanced%22%3A%22no%22%2C%22Professional%22%3A%22no%22%2C%22User_IP%22%3A%22202.120.19.186%22%2C%22Session_ID%22%3A%2269A1CC852FF1123A9A78CFC18E2B6AFF.i-b86ebbb9%22%2C%22Account_ID%22%3A%2213818%22%7D%2C%22v1%22%3A-2%2C%22v2%22%3A-2%2C%22rid%22%3A%22de07553-78562942-af91-5f91-ed200%22%2C%22ru%22%3A%22http%3A%2F%2Fourex.lib.sjtu.edu.cn%2Fprimo_library%2Flibweb%2Faction%2Fdisplay.do%3Bjsessionid%3D73028D8B75DB2FF259A0E736836BAA07%3Ftabs%3DdetailsTab%26ct%3Ddisplay%26fn%3Dsearch%26doc%3Dsjtulibxw000061822%26indx%3D1%26recIds%3Dsjtulibxw000061822%26recIdxs%3D0%26elementId%3D0%26renderMode%3DpoppedOut%26displayMode%3Dfull%26frbrVersion%3D%26dscnt%3D0%26scp.scps%3Dscope%253A%2528SJT%2529%252Cscope%253A%2528sjtu_metadata%2529%252Cscope%253A%2528sjtu_sfx%2529%252Cscope%253A%2528sjtulibzw%2529%252Cscope%253A%2528sjtulibxw%2529%252CDuxiuBook%26tab%3Ddefault_tab%26dstmp%3D1472033627266%26vl(freeText0)%3Dproquest%26vid%3Dchinese%22%2C%22r%22%3A%22ourex.lib.sjtu.edu.cn%22%2C%22st%22%3A%22%22%2C%22to%22%3A5%2C%22pv%22%3A34%2C%22lc%22%3A%7B%22d0%22%3A%7B%22v%22%3A34%2C%22s%22%3Atrue%7D%7D%2C%22cd%22%3A0%2C%22f%22%3A1472090225890%2C%22pn%22%3A0%2C%22sd%22%3A0%7D; _ga=GA1.3.1201070524.1446763952'}
req = session.post(monthurl,data = payload,headers = headers)
main = BeautifulSoup(req.text,"html.parser").decode('utf-8')
print(main)
</code></pre>
<p>result sample: <code>['/publication.publicationissuebrowse:openissue/issueName/02016Y08Y25$23Aug+25,+
2016?site=news&amp;t;:ac=publications_105983']</code> (this is a list I only show one element for conciseness),
this is what actually the url is : <code>/publication.publicationissuebrowse:openissue/issueName/02016Y08Y25$23Aug+25,+
2016?site=news&t:ac=publications_105983</code>
no "amp;" and ";" after "t",</p>
<p>So I actually have two questions here, why this happen? and how to fix it? can I just replace the specific characters in the elements of a list?</p>
<p>many thanks in advance for any help advices</p>
| 0 | 2016-08-25T02:16:52Z | 39,135,825 | <p>What you get back is apparently supposed to be injected on the website. <code>&amp;</code> is just <code>&</code> escaped for html usage. They're equivalent, but you have to unescape it first. You've got the function posted in <a href="https://wiki.python.org/moin/EscapingHtml" rel="nofollow">https://wiki.python.org/moin/EscapingHtml</a></p>
<pre><code>def unescape(s):
s = s.replace("&lt;", "<")
s = s.replace("&gt;", ">")
# this has to be last:
s = s.replace("&amp;", "&")
return s
</code></pre>
<p>As for the missing <code>;</code> - that's something the website either deals with in JS, or maybe both urls work just fine. Definitely not a mistake in this code. Check the scripts on the website carefully.</p>
| 0 | 2016-08-25T02:34:00Z | [
"python",
"amp"
] |
python load zip with modules from memory | 39,135,750 | <p>So lets say I have a zip file with modules/classes inside. I then read this file - read binary ("rb") to store it into memory. How would I take this zip file in memory and load a module from it. Would I need to write an import hook for this? One cannot simply run exec on binary zip data from memory, can they?</p>
<p>I know its simple just to load a module from a plain zip file on disk as this is done automatically by python2.7. I , however; want to know if this is possible via memory.</p>
<p>Update:
A lot of people are mentioning about importing the zip from disk. The issue is specifically that I want to import the zip from memory NOT disk. I obviously will read it from disk and into memory byte by byte. I want to take all these bytes from within memory that make up the zip file and use it as a regular import.</p>
| 5 | 2016-08-25T02:22:04Z | 39,136,299 | <p>read a test.txt from zip(not unzip or write to disk):</p>
<p>python 3(if you use py2.x, you should change the py3 zip API to py2)</p>
<pre><code>import zipfile
file_rst = []
with zipfile.ZipFile('/test/xxx.zip') as my_zip:
with my_zip.open('test.txt') as my_file:
for line in my_file:
file_rst.append(line.strip())
</code></pre>
| 0 | 2016-08-25T03:37:23Z | [
"python"
] |
python load zip with modules from memory | 39,135,750 | <p>So lets say I have a zip file with modules/classes inside. I then read this file - read binary ("rb") to store it into memory. How would I take this zip file in memory and load a module from it. Would I need to write an import hook for this? One cannot simply run exec on binary zip data from memory, can they?</p>
<p>I know its simple just to load a module from a plain zip file on disk as this is done automatically by python2.7. I , however; want to know if this is possible via memory.</p>
<p>Update:
A lot of people are mentioning about importing the zip from disk. The issue is specifically that I want to import the zip from memory NOT disk. I obviously will read it from disk and into memory byte by byte. I want to take all these bytes from within memory that make up the zip file and use it as a regular import.</p>
| 5 | 2016-08-25T02:22:04Z | 39,136,473 | <p><strong>EDIT:</strong> Fixed the ZipImporter to work for everything (I think)</p>
<p>Test Data:</p>
<pre><code>mkdir mypkg
vim mypkg/__init__.py
vim mypkg/test_submodule.py
</code></pre>
<p><code>__init__.py</code> Contents:</p>
<pre><code>def test():
print("Test")
</code></pre>
<p><code>test_submodule.py</code> Contents:</p>
<pre><code>def test_submodule_func():
print("This is a function")
</code></pre>
<p>Create Test Zip (on mac):</p>
<pre><code>zip -r mypkg.zip mypkg
rm -r mypkg # don't want to accidentally load the directory
</code></pre>
<p>Special zip import in <code>inmem_zip_importer.py</code>:</p>
<pre><code>import os
import imp
import zipfile
class ZipImporter(object):
def __init__(self, zip_file):
self.z = zip_file
self.zfile = zipfile.ZipFile(self.z)
self._paths = [x.filename for x in self.zfile.filelist]
def _mod_to_paths(self, fullname):
# get the python module name
py_filename = fullname.replace(".", os.sep) + ".py"
# get the filename if it is a package/subpackage
py_package = fullname.replace(".", os.sep, fullname.count(".") - 1) + "/__init__.py"
if py_filename in self._paths:
return py_filename
elif py_package in self._paths:
return py_package
else:
return None
def find_module(self, fullname, path):
if self._mod_to_paths(fullname) is not None:
return self
return None
def load_module(self, fullname):
filename = self._mod_to_paths(fullname)
if not filename in self._paths:
raise ImportError(fullname)
new_module = imp.new_module(fullname)
exec self.zfile.open(filename, 'r').read() in new_module.__dict__
new_module.__file__ = filename
new_module.__loader__ = self
if filename.endswith("__init__.py"):
new_module.__path__ = []
new_module.__package__ = fullname
else:
new_module.__package__ = fullname.rpartition('.')[0]
return new_module
</code></pre>
<p>Use:</p>
<pre><code>In [1]: from inmem_zip_importer import ZipImporter
In [2]: sys.meta_path.append(ZipImporter(open("mypkg.zip", "rb")))
In [3]: from mypkg import test
In [4]: test()
Test function
In [5]: from mypkg.test_submodule import test_submodule_func
In [6]: test_submodule_func()
This is a function
</code></pre>
<hr>
<p>(from efel) one more thing... :</p>
<p>To read directly from memory one would need to do this :</p>
<pre><code>f = open("mypkg.zip", "rb")
# read binary data we are now in memory
data = f.read()
f.close() #important! close the file! we are now in memory
# at this point we can essentially delete the actual on disk zip file
# convert in memory bytes to file like object
zipbytes = io.BytesIO(data)
zipfile.ZipFile(zipbytes)
</code></pre>
| 1 | 2016-08-25T03:57:32Z | [
"python"
] |
python: type error and index error (2.7.6) | 39,135,756 | <p>I am fairly new to python and I am having a problem on 2.7.6 that is not a problem on 3.4.4</p>
<p>The code:</p>
<pre><code>def answer(population, x, y, strength):
# make sure Z is infectable
if population[x][y] > strength:
return population
else:
population[x][y] = -1
# get array dimentions
rows = len(population)
cols = len(population[0])
# declare checking array
toCheck = []
toCheck.append([x,y])
# loop 4 way check
while(1):
#store and pop current element
i = toCheck[0][0]
j = toCheck[0][1]
toCheck.pop(0)
# left
if j != 0:
if population[i][j-1] <= strength and population[i][j-1] != -1:
population[i][j-1] = -1
toCheck.append([i,j-1])
# top
if i != 0:
if population[i-1][j] < strength and population[i-1][j] != -1:
population[i-1][j] = -1
toCheck.append([i-1,j])
# right
if j != cols-1:
if population[i][j+1] > strength and population[i][j+1] != -1:
population[i][j+1] = -1
toCheck.append([i,j+1])
# bottom
if i != rows-1:
if population[i+1][j] > strength and population[i+1][j] != -1:
population[i+1][j] = -1
toCheck.append([i+1][j])
if len(toCheck) == 0:
return population
</code></pre>
<p>gives me a 'TypeError'. While the code:</p>
<pre><code>def answer(population, x, y, strength):
# make sure Z is infectable
if population[x][y] > strength:
return population
else:
population[x][y] = -1
# get array dimentions
rows = len(population)
cols = len(population[0])
# declare checking array
toCheck = [[]]
toCheck.append([x,y])
# loop 4 way check
while(1):
#store and pop current element
i = toCheck[0][0]
j = toCheck[0][1]
toCheck.pop(0)
# left
if j != 0:
if population[i][j-1] <= strength and population[i][j-1] != -1:
population[i][j-1] = -1
toCheck.append([i,j-1])
# top
if i != 0:
if population[i-1][j] < strength and population[i-1][j] != -1:
population[i-1][j] = -1
toCheck.append([i-1,j])
# right
if j != cols-1:
if population[i][j+1] > strength and population[i][j+1] != -1:
population[i][j+1] = -1
toCheck.append([i,j+1])
# bottom
if i != rows-1:
if population[i+1][j] > strength and population[i+1][j] != -1:
population[i+1][j] = -1
toCheck.append([i+1][j])
if len(toCheck) == 0:
return population
</code></pre>
<p>Gives me and 'IndexError'. Both of these errors occur at the line i=toCheck[0][0].
Please help! thank you.</p>
| -2 | 2016-08-25T02:22:49Z | 39,135,812 | <p>Edit: this response was for an older version of the question's code.</p>
<p>Assuming that all of your code is supposed to be within funk():</p>
<p>You need to terminate your while loop once toCheck is empty. The original version tries to index an empty list after you've popped off all of the values. Try this:</p>
<pre><code># loop 4 way check
while len(toCheck) > 0:
#store and pop current element
i = toCheck[0][0]
j = toCheck[0][1]
toCheck.pop(0)
</code></pre>
<p>Also, you don't need to declare toCheck before adding values. You can replace</p>
<pre><code>toCheck = [[],[]]
toCheck.append([x,y])
</code></pre>
<p>With </p>
<pre><code>toCheck = [x, y]
</code></pre>
| 0 | 2016-08-25T02:32:13Z | [
"python",
"list",
"indexing",
"typeerror"
] |
Alternative way to using for loop | 39,135,968 | <p>Suppose a file looks like this:</p>
<pre><code>abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
</code></pre>
<p>My code:</p>
<pre><code>if "abcd" in line:
do something
elif "xyz" in line:
do something
</code></pre>
<p>If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?</p>
<p>Edit:</p>
<p>Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition. </p>
| -1 | 2016-08-25T02:52:46Z | 39,136,051 | <p>You can always use variables for matching, using your example:</p>
<pre><code>pattern1 = "abcd"
pattern2 = "xyz"
for line in lines_list:
if pattern1 in line:
do_smth
elif pattern2 in line:
do_smth2
pattern1 = get_new_pattern1()
pattern2 = get_new_pattern2()
</code></pre>
<p>Also you can split line to words with</p>
<pre><code>first, second = line.split(' ')
</code></pre>
<p>use this in loop to get access to first and second word in line correspondingly.</p>
| 0 | 2016-08-25T03:03:54Z | [
"python"
] |
Alternative way to using for loop | 39,135,968 | <p>Suppose a file looks like this:</p>
<pre><code>abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
</code></pre>
<p>My code:</p>
<pre><code>if "abcd" in line:
do something
elif "xyz" in line:
do something
</code></pre>
<p>If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?</p>
<p>Edit:</p>
<p>Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition. </p>
| -1 | 2016-08-25T02:52:46Z | 39,136,064 | <p>I don't know whether I catch your intention, but I hope the following code will help you. <code>keywords</code> simulates the <strong>dynamically changing</strong> variable.</p>
<pre><code>keywords = ['abcd', 'xyz', '123']
data = ['abcd',
'xyz',
'asdf',
'asdf',
'456',
'abcd',
'xyz',
'abcd',
'xyz',
'abcd',
'xyz',
'abcd',
'xyz',
'123',
'123']
counts = [ data.count(kw) for kw in keywords]
print(counts) # [5, 5, 2]
</code></pre>
| 0 | 2016-08-25T03:05:03Z | [
"python"
] |
Alternative way to using for loop | 39,135,968 | <p>Suppose a file looks like this:</p>
<pre><code>abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
</code></pre>
<p>My code:</p>
<pre><code>if "abcd" in line:
do something
elif "xyz" in line:
do something
</code></pre>
<p>If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?</p>
<p>Edit:</p>
<p>Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition. </p>
| -1 | 2016-08-25T02:52:46Z | 39,136,075 | <p>From your question (And making an assumption), it seems as though you want to go through each line in a file and than check if the text at that line matches something else. Say you have a file file.txt that is:</p>
<pre><code>abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
</code></pre>
<p>To read that file, you would do:</p>
<pre><code>filedata = open('file.txt', 'r') # Where r means read
first_match = 'abcd'
second_match = 'xyz'
for line in text:
if first_match in line:
# Do stuff here
elif second_line in line:
# Do other stuff here
first_match = change_first_match()
second_match = change_second_match()
</code></pre>
<p>More information on reading files <a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">here</a></p>
| 0 | 2016-08-25T03:06:39Z | [
"python"
] |
Alternative way to using for loop | 39,135,968 | <p>Suppose a file looks like this:</p>
<pre><code>abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
</code></pre>
<p>My code:</p>
<pre><code>if "abcd" in line:
do something
elif "xyz" in line:
do something
</code></pre>
<p>If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?</p>
<p>Edit:</p>
<p>Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition. </p>
| -1 | 2016-08-25T02:52:46Z | 39,136,113 | <p>Not sure I've understood correctly your question, but here's a possible way to gather key & values from your file:</p>
<pre><code>import re
from collections import defaultdict
file = """
abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
"""
output = defaultdict(list)
for line in file.split("\n"):
if line.strip() == "":
continue
key, value = re.search(r'(.*?)\s+(.*)', line).groups()
output[key].append(value)
print(output)
for k, v in output.iteritems():
print("{0} has {1} items".format(k, len(v)))
</code></pre>
| 0 | 2016-08-25T03:10:48Z | [
"python"
] |
Alternative way to using for loop | 39,135,968 | <p>Suppose a file looks like this:</p>
<pre><code>abcd 1
abcd 2
abcd 3
xyz 1
xyz 2
</code></pre>
<p>My code:</p>
<pre><code>if "abcd" in line:
do something
elif "xyz" in line:
do something
</code></pre>
<p>If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?</p>
<p>Edit:</p>
<p>Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition. </p>
| -1 | 2016-08-25T02:52:46Z | 39,136,239 | <p>You probably want this (some kind of dynamic-keyword counter):</p>
<pre><code>with open("filename.txt") as f:
d=dict()
for line in f:
line=line.rstrip("\n")
s=line.split(" ") # works iff you have only space as delimeter
if s[0] in d:
d[s[0]]+=int(s[1]) # replace by 1 if needed
else:
d[s[0]]=int(s[1]) # replace by 1
#print(d)
</code></pre>
| 0 | 2016-08-25T03:30:30Z | [
"python"
] |
Can a python dictionary be created and updated on the go | 39,136,022 | <p>I have to create a nested dictionary on the go inside a for loop. I have the parent dictionary <code>data</code> initialized to empty. Now inside the loop, I get the key to be added to the parent dictionary. And each key being again a dictionary.</p>
<pre><code>data = {}
for condition
Get x, y # x is the new key
if x not in data:
data[x] ={}
data[x].update({y:1}) # or data[x][y] = 1
</code></pre>
<p>But I want to do the above piece in one line as below </p>
<pre><code>data = {}
for condition
Get x, y # x is the new key
if x not in data:
data.update({x:{}}.update({y:1}))
</code></pre>
<p>Here I am getting <code>TypeError: 'NoneType' object is not iterable</code>. I guess this is due to the inner update (i.e. <code>update({y:1}</code>) is getting executed first and trying to update <code>x</code> which is not yet present, hence <code>NoneType</code>.</p>
<p>Is there any other way I can achieve this in one line? Or do I have the only way to create an empty dictionary first and then update the same as shown in first code piece ?</p>
| 1 | 2016-08-25T03:00:35Z | 39,136,127 | <p>It can also be achieved <code>data[x] = {y :1}</code> or <code>data.update({x: {y:1})</code> as mentioned by @karthikr</p>
| 0 | 2016-08-25T03:13:45Z | [
"python",
"python-2.7"
] |
Can a python dictionary be created and updated on the go | 39,136,022 | <p>I have to create a nested dictionary on the go inside a for loop. I have the parent dictionary <code>data</code> initialized to empty. Now inside the loop, I get the key to be added to the parent dictionary. And each key being again a dictionary.</p>
<pre><code>data = {}
for condition
Get x, y # x is the new key
if x not in data:
data[x] ={}
data[x].update({y:1}) # or data[x][y] = 1
</code></pre>
<p>But I want to do the above piece in one line as below </p>
<pre><code>data = {}
for condition
Get x, y # x is the new key
if x not in data:
data.update({x:{}}.update({y:1}))
</code></pre>
<p>Here I am getting <code>TypeError: 'NoneType' object is not iterable</code>. I guess this is due to the inner update (i.e. <code>update({y:1}</code>) is getting executed first and trying to update <code>x</code> which is not yet present, hence <code>NoneType</code>.</p>
<p>Is there any other way I can achieve this in one line? Or do I have the only way to create an empty dictionary first and then update the same as shown in first code piece ?</p>
| 1 | 2016-08-25T03:00:35Z | 39,136,500 | <p>Are you trying to do automatic nested dictionary insertion? If so, you could try using a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a>:</p>
<pre><code>from collections import defaultdict
data = defaultdict(dict)
for i in range(10):
x = "..."
y = "..."
data[x][y] = 1
print data["..."]["..."]
</code></pre>
<p>This prints <code>1</code></p>
| 2 | 2016-08-25T04:00:08Z | [
"python",
"python-2.7"
] |
Python3.4 error - Cannot enable executable stack as shared object requires: Invalid argument | 39,136,040 | <p>I've been trying to install <a href="http://opencv.org/" rel="nofollow">OpenCV</a> in a Bash on Windows (Windows Subsystem for Linux, wsl) environment and it's been proving very difficult.</p>
<p>I think I'm getting very close, but upon entering python, <code>import cv2</code> gives the following error:</p>
<pre><code>ImportError: libopencv_core.so.3.1: cannot enable executable stack as shared object requires: Invalid argument
</code></pre>
<p>How do I enable the library to execute on the stack?</p>
<hr>
<p>My OpenCV <code>*opencv*.so*</code> library files are located in <code>/usr/local/lib/</code>. In a normal Linux environment, I would grant these libraries the ability to execute on the stack using</p>
<pre><code>execstack -c /usr/local/lib/*opencv*.so*
</code></pre>
<p>However, even though I can successfully download the <code>execstack</code> package, it isn't a recognized command I can run to allow execution on the stack. I suspect this has something to do with Data Execution Prevention, Window's version of Exec-Shield to prevent stack smashing attacks.</p>
<p>But maybe I've just been too close to the problem to figure out what's wrong. Why can't I import this python package? I'm using Python v3.4 and OpenCV compiled from the <a href="https://github.com/opencv/opencv" rel="nofollow">latest source code</a> (v.3.1).</p>
| 0 | 2016-08-25T03:03:05Z | 39,223,317 | <p>There are lots of things that simply don't work at the moment, because there are either unimplemented syscalls (WSL only has partial coverage, only about 70% of syscalls are implemented, some of them only partially), or missing socket modes and options (WSL does not yet support Unix datagram sockets, although it should be available in the next insider build). </p>
<p>If you go to the github (BashOnWindows) and post an strace or search for your issue and find a copy of it, that's the best way to get an answer. The Microsoft team working on this project wants lots and lots of feedback and bugtesting.</p>
<p>To be clear, I am saying that you are 100% running into something that isn't implemented yet. However, there might be a way, if you look at the sourcecode for your .so file to disable the part of the code that uses that syscall (since Python is crossplatform and not all Linux syscalls are supported across all *nix operating systems). </p>
| 1 | 2016-08-30T09:12:37Z | [
"python",
"windows",
"python-3.x",
"opencv",
"wsl"
] |
Python Pandas with sqlalchemy | Bulk Insert Error | 39,136,120 | <p>I was try to Insert my millions of records from <strong>CSV</strong> File to <strong>MySQL</strong> Database, by using <strong>Python</strong> | <strong>Pandas</strong> with <strong>sqlalchemy</strong>. Some time this insertion is interrupted before the completion or not even insert single row to Database.</p>
<p>My Code is :</p>
<pre><code>import pandas as pd
from sqlalchemy import create_engine
df = pd.read_csv('/home/shankar/LAB/Python/Rough/*******.csv')
# 2nd argument replaces where conditions is False
df = df.where(pd.notnull(df), None)
df.head()
conn_str = "mysql+pymysql://root:MY_PASS@localhost/MY_DB?charset=utf8&use_unicode=0"
engine = create_engine(conn_str)
conn = engine.raw_connection()
df.to_sql(name='table_name', con=conn,
if_exists='append')
conn.close()
</code></pre>
<p>Error : </p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1563 else:
-> 1564 cur.execute(*args)
1565 return cur
/home/shankar/.local/lib/python3.5/site-packages/pymysql/cursors.py in execute(self, query, args)
164
--> 165 query = self.mogrify(query, args)
166
/home/shankar/.local/lib/python3.5/site-packages/pymysql/cursors.py in mogrify(self, query, args)
143 if args is not None:
--> 144 query = query % self._escape_args(args, conn)
145
TypeError: not all arguments converted during string formatting
During handling of the above exception, another exception occurred:
DatabaseError Traceback (most recent call last)
<ipython-input-6-bb91db9eb97e> in <module>()
11 df.to_sql(name='company', con=conn,
12 if_exists='append',
---> 13 chunksize=10000)
14 conn.close()
/home/shankar/.local/lib/python3.5/site-packages/pandas/core/generic.py in to_sql(self, name, con, flavor, schema, if_exists, index, index_label, chunksize, dtype)
1163 sql.to_sql(self, name, con, flavor=flavor, schema=schema,
1164 if_exists=if_exists, index=index, index_label=index_label,
-> 1165 chunksize=chunksize, dtype=dtype)
1166
1167 def to_pickle(self, path):
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in to_sql(frame, name, con, flavor, schema, if_exists, index, index_label, chunksize, dtype)
569 pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
570 index_label=index_label, schema=schema,
--> 571 chunksize=chunksize, dtype=dtype)
572
573
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype)
1659 if_exists=if_exists, index_label=index_label,
1660 dtype=dtype)
-> 1661 table.create()
1662 table.insert(chunksize)
1663
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in create(self)
688
689 def create(self):
--> 690 if self.exists():
691 if self.if_exists == 'fail':
692 raise ValueError("Table '%s' already exists." % self.name)
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in exists(self)
676
677 def exists(self):
--> 678 return self.pd_sql.has_table(self.name, self.schema)
679
680 def sql_schema(self):
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in has_table(self, name, schema)
1674 query = flavor_map.get(self.flavor)
1675
-> 1676 return len(self.execute(query, [name, ]).fetchall()) > 0
1677
1678 def get_table(self, table_name, schema=None):
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1574 ex = DatabaseError(
1575 "Execution failed on sql '%s': %s" % (args[0], exc))
-> 1576 raise_with_traceback(ex)
1577
1578 @staticmethod
/home/shankar/.local/lib/python3.5/site-packages/pandas/compat/__init__.py in raise_with_traceback(exc, traceback)
331 if traceback == Ellipsis:
332 _, _, traceback = sys.exc_info()
--> 333 raise exc.with_traceback(traceback)
334 else:
335 # this version of raise is a syntax error in Python 3
/home/shankar/.local/lib/python3.5/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1562 cur.execute(*args, **kwargs)
1563 else:
-> 1564 cur.execute(*args)
1565 return cur
1566 except Exception as exc:
/home/shankar/.local/lib/python3.5/site-packages/pymysql/cursors.py in execute(self, query, args)
163 pass
164
--> 165 query = self.mogrify(query, args)
166
167 result = self._query(query)
/home/shankar/.local/lib/python3.5/site-packages/pymysql/cursors.py in mogrify(self, query, args)
142
143 if args is not None:
--> 144 query = query % self._escape_args(args, conn)
145
146 return query
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting
</code></pre>
<p>This error is Occurred in some sort of CSV files only.
Kindly notify my bug on this !</p>
<p>Thanks in Advance.</p>
| 0 | 2016-08-25T03:12:09Z | 39,136,153 | <p>From the error raised your arguments in to the query aren't all strings so what you would have to do is go and convert each of the elements of data frame to string. <code>df =df.astype(str)</code></p>
| 0 | 2016-08-25T03:17:38Z | [
"python",
"mysql",
"csv",
"pandas",
"sqlalchemy"
] |
change image names from a text file python | 39,136,126 | <p>I know that there are python scripts that can change a file name But i have a little problem
I am trying to bulk upload some images into yahoo store, The names for the images has to be the same as the product id for the server to link the images to the proper product. (I still cant understand why they don't just have a field in the database that you can list the name you have set but anyway)
I have all my images in one file for all my products (supplied by my supplier) but the names are something like benj7007.jpg
I also have a csv product file that lists the sku number and what the image name is.
When I am uploading the products into the yahoo store i am using the SKU number for the product id.
I can easily create a text file that will list the SKU and Image name for the group of products i am uploading and use it for python to read from
SKU Number 700756 Image benj7007.jpg </p>
<p>I need to change the Image name of all of the images to match the SKU but i am lost as to how to do this.
can someone point me in the right direction.
Thanks Again,
I did search but i couldnt find an solution for this kind of issue</p>
| -2 | 2016-08-25T03:13:13Z | 39,136,147 | <p>Renaming files:</p>
<pre><code>import os
os.rename("filename.jpg","newname.jpg")
</code></pre>
<p>If you want to read from list and rename</p>
<pre><code>with open("listname") as f:
for line in f:
os.rename(line,"newname.jpg")
</code></pre>
| 0 | 2016-08-25T03:16:23Z | [
"python",
"excel",
"image"
] |
change image names from a text file python | 39,136,126 | <p>I know that there are python scripts that can change a file name But i have a little problem
I am trying to bulk upload some images into yahoo store, The names for the images has to be the same as the product id for the server to link the images to the proper product. (I still cant understand why they don't just have a field in the database that you can list the name you have set but anyway)
I have all my images in one file for all my products (supplied by my supplier) but the names are something like benj7007.jpg
I also have a csv product file that lists the sku number and what the image name is.
When I am uploading the products into the yahoo store i am using the SKU number for the product id.
I can easily create a text file that will list the SKU and Image name for the group of products i am uploading and use it for python to read from
SKU Number 700756 Image benj7007.jpg </p>
<p>I need to change the Image name of all of the images to match the SKU but i am lost as to how to do this.
can someone point me in the right direction.
Thanks Again,
I did search but i couldnt find an solution for this kind of issue</p>
| -2 | 2016-08-25T03:13:13Z | 39,176,702 | <pre><code>import os
import csv
keys{}
with open('product_image.csv',rU) as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for rowDict in reader:
keys[ rowDict[0] ] = rowDict[1]
print (rowDict)
for fileName in (os.listdir('.') & keys.keys() ):
try:
os.rename(fileName, keys[fileName])
except:
print('image was not renamed')
</code></pre>
<p>For those of you who are like me and still trying to learn what everything does,
in a spreadsheet the first column is the current name of the image the second column is the name you want to change to. saved as a csv with the name product_image.csv.
the script will use the csv list to change the names in the file.
One note of error that i found is that for some reason the first file in the list will not rename and will be deleted. I don't take credit for the script I scavenged it and updated it to work with 3.4 </p>
| 0 | 2016-08-27T01:47:21Z | [
"python",
"excel",
"image"
] |
importlib can't find module | 39,136,134 | <p><strong>cat test.py</strong> </p>
<pre><code>from importlib import import_module
bar = import_module('bar', package='project')
</code></pre>
<p><strong>ls project/</strong></p>
<pre><code>__init__.py
__init__.pyc
bar.py
bar.pyc
</code></pre>
<p><strong>python test.py</strong></p>
<pre><code>Traceback (most recent call last):
File "test.py", line 5, in <module>
bar = import_module('bar', package='project')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named bar
</code></pre>
<p>Listing imported modules (sys.modules) doesn't show any module <em>project</em>.</p>
<p>I can import <em>bar</em> using the python shell.</p>
<p>Any ideas?</p>
| 0 | 2016-08-25T03:14:54Z | 39,136,163 | <p>It needs a dot in front of bar .. :-(</p>
<pre><code>bar = import_module('.bar', package='project')
</code></pre>
| 0 | 2016-08-25T03:18:45Z | [
"python",
"python-importlib"
] |
importlib can't find module | 39,136,134 | <p><strong>cat test.py</strong> </p>
<pre><code>from importlib import import_module
bar = import_module('bar', package='project')
</code></pre>
<p><strong>ls project/</strong></p>
<pre><code>__init__.py
__init__.pyc
bar.py
bar.pyc
</code></pre>
<p><strong>python test.py</strong></p>
<pre><code>Traceback (most recent call last):
File "test.py", line 5, in <module>
bar = import_module('bar', package='project')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named bar
</code></pre>
<p>Listing imported modules (sys.modules) doesn't show any module <em>project</em>.</p>
<p>I can import <em>bar</em> using the python shell.</p>
<p>Any ideas?</p>
| 0 | 2016-08-25T03:14:54Z | 39,136,654 | <p>The documentation for <a href="https://docs.python.org/2/library/importlib.html" rel="nofollow">import_lib</a> says that </p>
<blockquote>
<p>If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). </p>
</blockquote>
<p>Thus the expression can also be written as </p>
<pre><code>bar = import_module('..bar',package='project.bar')
</code></pre>
| 0 | 2016-08-25T04:20:16Z | [
"python",
"python-importlib"
] |
Program that prints one word per line | 39,136,165 | <p>Need to create a program that prints one word per line, but only if that word is less than 4 character. I have this so far</p>
<p>The input will be a list such as ['Not','very','good','at','python']</p>
<pre><code>string = input("Enter word list:")
txt = string.split()
for words in txt:
print(words)
</code></pre>
<p>When the input is a list, it prints it in one line, but if the input is just text, for example</p>
<p>Enter word list: Not very good at python</p>
<p>then it'll print every word on its own single line. </p>
<p>Not sure how to implement a 4 character only print and not sure how to get the list to print its elements on its own lines</p>
| -1 | 2016-08-25T03:18:58Z | 39,136,224 | <p>well, check the length of the word. </p>
<pre><code>string = input('Enter word list:\n')
txt = string.split()
for word in txt:
if len(word) < 4:
print('{0}'.format(word))
else:
continue
</code></pre>
| 1 | 2016-08-25T03:28:29Z | [
"python"
] |
Program that prints one word per line | 39,136,165 | <p>Need to create a program that prints one word per line, but only if that word is less than 4 character. I have this so far</p>
<p>The input will be a list such as ['Not','very','good','at','python']</p>
<pre><code>string = input("Enter word list:")
txt = string.split()
for words in txt:
print(words)
</code></pre>
<p>When the input is a list, it prints it in one line, but if the input is just text, for example</p>
<p>Enter word list: Not very good at python</p>
<p>then it'll print every word on its own single line. </p>
<p>Not sure how to implement a 4 character only print and not sure how to get the list to print its elements on its own lines</p>
| -1 | 2016-08-25T03:18:58Z | 39,136,243 | <p>Use the built-in function <code>len()</code> to count the length of each word. I have also included a simple parsing if statement to detect if your input is a list. </p>
<pre><code>string = raw_input('Enter word list: ')
if string[0] == "[" and string[-1] == "]": # simple method to parse
print(string)
else:
txt = string.split()
for words in txt:
if len(words) <= 4:
print(words)
</code></pre>
| 0 | 2016-08-25T03:30:49Z | [
"python"
] |
Program that prints one word per line | 39,136,165 | <p>Need to create a program that prints one word per line, but only if that word is less than 4 character. I have this so far</p>
<p>The input will be a list such as ['Not','very','good','at','python']</p>
<pre><code>string = input("Enter word list:")
txt = string.split()
for words in txt:
print(words)
</code></pre>
<p>When the input is a list, it prints it in one line, but if the input is just text, for example</p>
<p>Enter word list: Not very good at python</p>
<p>then it'll print every word on its own single line. </p>
<p>Not sure how to implement a 4 character only print and not sure how to get the list to print its elements on its own lines</p>
| -1 | 2016-08-25T03:18:58Z | 39,136,247 | <p>When you input['Not','very','good','at','python'],there has âï¼â. But when you input "Not very good at python", there not has ','.</p>
| 0 | 2016-08-25T03:31:21Z | [
"python"
] |
Program that prints one word per line | 39,136,165 | <p>Need to create a program that prints one word per line, but only if that word is less than 4 character. I have this so far</p>
<p>The input will be a list such as ['Not','very','good','at','python']</p>
<pre><code>string = input("Enter word list:")
txt = string.split()
for words in txt:
print(words)
</code></pre>
<p>When the input is a list, it prints it in one line, but if the input is just text, for example</p>
<p>Enter word list: Not very good at python</p>
<p>then it'll print every word on its own single line. </p>
<p>Not sure how to implement a 4 character only print and not sure how to get the list to print its elements on its own lines</p>
| -1 | 2016-08-25T03:18:58Z | 39,136,287 | <p>Is the input you are providing literally ['Not','very','good','at','python']?<br>
If so that's your problem. The input is being seen as a literal string, not a list. Calling split on that input will produce a single item list of your input "list", as there are no white spaces in that string to split on.
I'm also seeing nothing in your bit of code that determines word length for printing but perhaps that was just omitted.</p>
| 0 | 2016-08-25T03:35:46Z | [
"python"
] |
Script waits for input when importing the webbrowser module | 39,136,176 | <p>I'm having a small yet quite annoying issue with Python. When I import the webbrowser module in a Python script that is run from IDLE, it works perfectly fine. However, if the script is run outside of IDLE, importing the webbrowser module makes the program stop and wait for user input. </p>
<p>I made the following basic example that shows the problem step by step:</p>
<pre><code>print('the program has started')
print('importing some random modules')
import sys
print('sys imported')
import pyperclip
print('pyperclip imported')
import logging
print('logger imported')
print('this is the line before importing the webbrowser module')
import webbrowser
print('webbrowser module imported')
print('end of demo program')
</code></pre>
<p><a href="http://imgur.com/a/lXtwV" rel="nofollow">Here</a> is a screenshot of what happens when I launch the program. And finally, <a href="http://imgur.com/a/HNCs9" rel="nofollow">here</a> is a screenshot of the program after I enter some text and press enter. </p>
<p>What is it that it stops the webbrowser module when importing it outside of IDLE? I only want the program to import the module and to continue normally.</p>
| -2 | 2016-08-25T03:19:55Z | 39,156,409 | <p>Found the problem! there was a 'copy.py' script in the folder in which I store my scripts. The webbrowser module has to import a module named copy. Deleted 'copy.py' from the directory, everything works fine.</p>
| 2 | 2016-08-25T23:50:58Z | [
"python",
"windows",
"python-3.x",
"windows-console"
] |
Using python, how to use collect tweets (using tweepy) between two dates? | 39,136,226 | <p>How can i use python and tweepy in order to collect tweets from twitter that are between two given dates?</p>
<p>is there a way to pass from...until... values to the search api?</p>
<p><br/>
Note:
I need to be able to search back but WITHOUT limitation to a specific user</p>
<p>i am using python and I know that the code should be something like this but i need help to make it work.</p>
<pre>
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
api = tweepy.API(auth)
collection = []
for tweet in tweepy.Cursor(api.search, ???????).items():
collection[tweet.id] = tweet._json
</pre>
| -2 | 2016-08-25T03:28:40Z | 39,137,390 | <p>You have to use max_id parameters as described in <a href="https://dev.twitter.com/rest/public/timelines" rel="nofollow">twitter documentation</a></p>
<p>tweepy is a wrapper around twitter API so you should be able to use this parameter.</p>
<p>As per geolocation, take look at <a href="https://dev.twitter.com/rest/public/search-by-place" rel="nofollow">The Search API: Tweets by Place</a>. It uses same search API, with customized keys.</p>
| -1 | 2016-08-25T05:34:24Z | [
"python",
"twitter",
"tweepy",
"tweets"
] |
Using python, how to use collect tweets (using tweepy) between two dates? | 39,136,226 | <p>How can i use python and tweepy in order to collect tweets from twitter that are between two given dates?</p>
<p>is there a way to pass from...until... values to the search api?</p>
<p><br/>
Note:
I need to be able to search back but WITHOUT limitation to a specific user</p>
<p>i am using python and I know that the code should be something like this but i need help to make it work.</p>
<pre>
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
api = tweepy.API(auth)
collection = []
for tweet in tweepy.Cursor(api.search, ???????).items():
collection[tweet.id] = tweet._json
</pre>
| -2 | 2016-08-25T03:28:40Z | 39,185,427 | <p>After long hours of investigations and stabilization i can gladly share my findings.
<br/></p>
<ul>
<li><p>search by geocode: pass the geocode parameter in the 'q' parameter in this format: <em>geocode:"37.781157,-122.398720,500mi"</em> , <strong>the double quotes are important</strong>. notice that the parameter <em>near</em> is not supported anymore by this api. The geocode gives more flexibility</p></li>
<li><p>search by timeline: use the parameters "since" and "until" in the following format: "since:2016-08-01 until:2016-08-02" </p></li>
</ul>
<p>there is one more important note... twitter don't allow queries with too old dates. I am not sure but i think they give only 10-14 days back. So you cannot query this way for tweets of last month.</p>
<p>===================================</p>
<pre><code>for status in tweepy.Cursor(api.search,
q='geocode:"37.781157,-122.398720,1mi" since:2016-08-01 until:2016-08-02 include:retweets',
result_type='recent',
include_entities=True,
monitor_rate_limit=False,
wait_on_rate_limit=False).items(300):
tweet_id = status.id
tweet_json = status._json
</code></pre>
| 0 | 2016-08-27T20:22:54Z | [
"python",
"twitter",
"tweepy",
"tweets"
] |
How to add/drop items from a list | 39,136,260 | <p>I see plenty of posts adding and subtracting strings from a list but I need help with keeping count of those items.</p>
<p>I would like to couple those items so there are no repeats just a counter.</p>
<p>Ex:
3 Apples 4 Oranges 2 Bananas</p>
<p>I want to be able to "take" one item at a time so if I were to call:
"take Apple"
and I were to check my inventory then, I would have:
2 Apples 4 Oranges 2 Bananas</p>
<p>I would also like to do the opposite. I would like to "drop" an item and have it added to the inventory in the room.</p>
<p>Right now I only know how to pick up ALL of the apples at once and not just 1 at a time. Also, my items are loaded into the program from a separate txt file which is where all the items for each room are kept.</p>
| 2 | 2016-08-25T03:32:47Z | 39,136,627 | <p>Consider using a <code>dictionary</code> instead of a <code>list</code>. Dictionaries are ideal for maintaining <code>counts</code> of <code>things</code>:</p>
<pre><code>from random import choice
def get_rooms(file_name):
rooms = {}
with open(file_name) as f:
for l in f:
room = l.split()
room_number = int(room[0])
rooms[room_number] = {}
for index, data in enumerate(room[1:], 1):
if index % 2:
item = data
else:
rooms[room_number][item] = int(data)
return rooms
def generate_tests(number_of_test_actions):
tests = []
for _ in range(number_of_test_actions):
tests.append((choice([1,2,3,4,5,6]),
choice(['Apple', 'Sword', 'Bow', 'Arrow', 'monkey']),
choice(['take', 'drop'])))
return tests
def take_item(room, item):
# generates and propagates KeyError exception if item not in room
room[item] -= 1
if not room[item]:
room.pop(item)
def drop_item(room, item):
if item in room:
room[item] += 1
else:
room[item] = 1
rooms = get_rooms("rooms.txt")
for room, item, action in generate_tests(10):
if action == 'take':
print('taking', item, 'from room', room, ':', rooms[room])
try:
take_item(rooms[room], item)
except KeyError:
print('-- Sorry, no', item, 'in room', room, 'to take')
else:
print('-- took', item, 'from room', room, ':', rooms[room])
elif action == 'drop':
print('dropping', item, 'in room', room, ':', rooms[room])
drop_item(rooms[room], item)
print('-- dropped', item, 'in room', room, ':', rooms[room])
</code></pre>
<p><strong>rooms.txt</strong></p>
<pre><code>1 Sword 1 Apple 2
2 Apple 3
3 Bow 1 Arrow 3
4 Arrow 5
5 Bow 1
6 Arrow 10
</code></pre>
<p><strong>Output</strong></p>
<pre><code>taking Apple from room 3 : {'Arrow': 3, 'Bow': 1}
-- Sorry, no Apple in room 3 to take
taking Apple from room 4 : {'Arrow': 5}
-- Sorry, no Apple in room 4 to take
dropping monkey in room 6 : {'Arrow': 10}
-- dropped monkey in room 6 : {'monkey': 1, 'Arrow': 10}
dropping Apple in room 5 : {'Bow': 1}
-- dropped Apple in room 5 : {'Apple': 1, 'Bow': 1}
taking Bow from room 3 : {'Arrow': 3, 'Bow': 1}
-- took Bow from room 3 : {'Arrow': 3}
dropping monkey in room 3 : {'Arrow': 3}
-- dropped monkey in room 3 : {'monkey': 1, 'Arrow': 3}
dropping Arrow in room 6 : {'monkey': 1, 'Arrow': 10}
-- dropped Arrow in room 6 : {'monkey': 1, 'Arrow': 11}
taking Bow from room 5 : {'Apple': 1, 'Bow': 1}
-- took Bow from room 5 : {'Apple': 1}
taking Bow from room 4 : {'Arrow': 5}
-- Sorry, no Bow in room 4 to take
taking Bow from room 5 : {'Apple': 1}
-- Sorry, no Bow in room 5 to take
</code></pre>
| 0 | 2016-08-25T04:17:14Z | [
"python",
"list"
] |
uWSGI: Override default harakiri duration in flask/python | 39,136,396 | <p>For most requests/routes a standard harakiri value of 15s or 30s will be fine.</p>
<p>But a few endpoints are long running (such as when generating reports) and I want the client to wait synchronously while they are prepared and returned.</p>
<p>Can I set a default harakiri value in uwsgi.ini and then override it in flask/python, either in code or by using a decorator in flask?</p>
<p>A previous answer shows how to do this using uWSGI config/routes but I would prefer to keep these special cases separate from the standard uWSGI timeout configuration. <a href="http://stackoverflow.com/questions/27758999/uwsgi-different-harakiri-timeout-for-django-admin">uWSGI - Different Harakiri Timeout for Django Admin</a></p>
<p>Any pointers?</p>
| 0 | 2016-08-25T03:48:53Z | 39,136,614 | <p>Well, if project you're writing could be written in different way, then you can do the generating process. It's one of many options:</p>
<p>Create a link which will fire up backend process. After user page refresh, there will be wording that generating is in progress. Then you have two options, first is to tell end-user that: We will notify you when will finish and send him some kind of even email notification, or simplest one, where you do nothing, but just only checking if specific process is running in the background on your machine and according to answer yes/no, display a link to a file or leave a message that he must still wait, because process hasn't been ended.</p>
<p>In case I described, every long generating will be separated from HTTP layer. You can even mix it with your method if you can predict when it's heading to timeout.</p>
<p>Hope I explained it enough.</p>
| 0 | 2016-08-25T04:15:23Z | [
"python",
"flask",
"uwsgi"
] |
Multiprocessing to speed up for loop | 39,136,575 | <p>Just trying to learn and I"m wondering if multiprocessing would speed
up this for loop ,.. trying to compare
alexa_white_list(1,000,000 lines) and
dnsMISP (can get up to 160,000 lines)</p>
<p>Code checks each line in dnsMISP and looks for it in alexa_white_list.
if it doesn't see it, it adds it to blacklist. </p>
<p>Without mp_handler function the code works fine but it takes
around 40-45 minutes. For brevity, I've omitted all the other imports and
the function that pulls down and unzips the alexa white list. </p>
<p>The below gives me the following error -
File "./vetdns.py", line 128, in mp_handler
p.map(dns_check,dnsMISP,alexa_white_list)
NameError: global name 'dnsMISP' is not defined</p>
<pre><code>from multiprocessing import Pool
def dns_check():
awl = []
blacklist = []
ctr = 0
dnsMISP = open(INPUT_FILE,"r")
dns_misp_lines = dnsMISP.readlines()
dnsMISP.close()
alexa_white_list = open(outname, 'r')
alexa_white_list_lines = alexa_white_list.readlines()
alexa_white_list.close()
print "converting awl to proper format"
for line in alexa_white_list_lines:
awl.append(".".join(line.split(".")[-2:]).strip())
print "done"
for host in dns_misp_lines:
host = host.strip()
host = ".".join(host.split(".")[-2:])
if not host in awl:
blacklist.append(host)
file_out = open(FULL_FILENAME,"w")
file_out.write("\n".join(blacklist))
file_out.close()
def mp_handler():
p = Pool(2)
p.map(dns_check,dnsMISP,alexa_white_list)
if __name__ =='__main__':
mp_handler()
</code></pre>
<p>If I label it as global etc I still get the error. I'd appreciate any
suggestions!!</p>
| -1 | 2016-08-25T04:09:40Z | 39,136,644 | <p>You tried to read a variable named <code>dnsMISP</code> to pass as an argument to <code>Pool.map</code>. It doesn't exist in local or global scope (where do you think it's coming from?), so you got a <code>NameError</code>. This has nothing to do with <code>multiprocessing</code>; you could just type a line with nothing but:</p>
<pre><code>dnsMISP
</code></pre>
<p>and have the same error.</p>
| 0 | 2016-08-25T04:19:32Z | [
"python"
] |
Multiprocessing to speed up for loop | 39,136,575 | <p>Just trying to learn and I"m wondering if multiprocessing would speed
up this for loop ,.. trying to compare
alexa_white_list(1,000,000 lines) and
dnsMISP (can get up to 160,000 lines)</p>
<p>Code checks each line in dnsMISP and looks for it in alexa_white_list.
if it doesn't see it, it adds it to blacklist. </p>
<p>Without mp_handler function the code works fine but it takes
around 40-45 minutes. For brevity, I've omitted all the other imports and
the function that pulls down and unzips the alexa white list. </p>
<p>The below gives me the following error -
File "./vetdns.py", line 128, in mp_handler
p.map(dns_check,dnsMISP,alexa_white_list)
NameError: global name 'dnsMISP' is not defined</p>
<pre><code>from multiprocessing import Pool
def dns_check():
awl = []
blacklist = []
ctr = 0
dnsMISP = open(INPUT_FILE,"r")
dns_misp_lines = dnsMISP.readlines()
dnsMISP.close()
alexa_white_list = open(outname, 'r')
alexa_white_list_lines = alexa_white_list.readlines()
alexa_white_list.close()
print "converting awl to proper format"
for line in alexa_white_list_lines:
awl.append(".".join(line.split(".")[-2:]).strip())
print "done"
for host in dns_misp_lines:
host = host.strip()
host = ".".join(host.split(".")[-2:])
if not host in awl:
blacklist.append(host)
file_out = open(FULL_FILENAME,"w")
file_out.write("\n".join(blacklist))
file_out.close()
def mp_handler():
p = Pool(2)
p.map(dns_check,dnsMISP,alexa_white_list)
if __name__ =='__main__':
mp_handler()
</code></pre>
<p>If I label it as global etc I still get the error. I'd appreciate any
suggestions!!</p>
| -1 | 2016-08-25T04:09:40Z | 39,136,828 | <p>There's no need for multiprocessing here. In fact this code can be greatly simplified:</p>
<pre><code>def get_host_form_line(line):
return line.strip().split(".", 1)[-1]
def dns_check():
with open('alexa.txt') as alexa:
awl = {get_host_from_line(line) for line in alexa}
blacklist = []
with open(INPUT_FILE, "r") as dns_misp_lines:
for line in dns_misp_lines:
host = get_host_from_line(line)
if host not in awl:
blacklist.append(host)
with open(FULL_FILENAME,"w") as file_out:
file_out.write("\n".join(blacklist))
</code></pre>
<p>Using a set comprehension to create your Alexa collection has the advantage of being <code>O(1)</code> lookup time. Sets are similar to dictionaries. They are pretty much dictionaries that only have keys with no values. There is some additional overhead in memory and the initial creation time will likely be slower since the values you put in to a set need to be hashed and hash collisions dealt with but the increase in performance you gain from the faster look ups should make up for it.</p>
<p>You can also clean up your line parsing. <code>split()</code> takes an additional parameter that will limit the number of times the input is split. I'm assuming your lines look something like this:</p>
<p><code>http://www.something.com</code> and you want <code>something.com</code> (if this isn't the case let me know)</p>
<p>It's important to remember that the <code>in</code> operator isn't magic. When you use it to check membership (is an element in the list) what it's essentially doing under the hood is this:</p>
<pre><code>for element in list:
if element == input:
return True
return False
</code></pre>
<p>So every time in your code you did <code>if element in list</code> your program had to iterate across each element until it either found what you were looking for or got to the end. This was probably the biggest bottleneck of your code.</p>
| 1 | 2016-08-25T04:44:21Z | [
"python"
] |
Retrieve data from hardware(eg CCTV,RFID) if library/API is not available | 39,136,621 | <p>I want to access data from devices like <strong>RFID reader</strong>,<strong>CCTV camera</strong> which will be connected to a device which has <strong><em>SUSE Linux</em></strong> in it.This is a proprietary device --> <strong>Huawei AR515</strong>. </p>
<p>But, I am not sure in what format, data will be produced by these devices. If i want to get data, say using <code>Python/C++</code> what will I have to do?</p>
<p>Help in this regard will be appreciated</p>
| -1 | 2016-08-25T04:16:38Z | 39,137,018 | <p>In python, maybe this way can helps you </p>
<p><a href="http://stackoverflow.com/questions/19908167/reading-serial-data-in-realtime-in-python">Reading serial data in realtime in Python</a></p>
<p>In C/C++ for linux platform, you can read directly in /dev/.
In both cases, is mandatory knows whats commands and sequences the device require. In general lines, if you before never try this and you're begginer, the first steps more appropriate are the AT commands. </p>
<p>This can help <a href="http://stackoverflow.com/questions/2161197/how-to-send-receive-sms-using-at-commands">How to Send/Receive SMS using AT commands?</a></p>
| 1 | 2016-08-25T05:03:17Z | [
"python",
"c++",
"embedded",
"hardware",
"embedded-linux"
] |
I am new at this and am trying to figure out how to use timers and loops. I am trying to loop this with a timer. Can you help me? | 39,136,660 | <pre><code>for i in xrange(5):
abc()
time.sleep(3)
print('?~~~~~')
print('~?~~~~')
print('~~?~~~')
print('~~~?~~')
print('~~~~?~')
print('~~~~~?')
print('?~~~~~')
print('~?~~~~')
print('~~?~~~')
print('~~~?~~')
print('~~~~?~')
print('~~~~~?')
</code></pre>
| -2 | 2016-08-25T04:21:11Z | 39,138,016 | <p>In this answer I am assuming that you want to move the question mark along the line as the timer advances, with a three second gap in between.</p>
<p>This code nearly needs to be rewritten completely. Don't fret, it's not too bad and it's easy to fix.</p>
<p>The first thing that is wrong here is that you haven't imported your time module for <code>time.sleep()</code>. To do this you must simply add at the top of the code <code>import time</code>. Secondly, you do not need to use <code>abs()</code> in your code, and Python doesn't understand it. Thirdly, when you use a for loop, or any loop for that matter, it executes the whole thing one iteration, then goes back to the start for the next, so your timer is just printing all of that every time it goes through. It does not wait to make it flow, it just prints a block of the tildes every three seconds.
At your current level, I would use a simple if and a variable to test for which iteration it is, because you might not know how to splice yet. Here it is:</p>
<pre><code>import time # importing time so time.sleep() works properly
iteration = 1 # Code to tell where the question mark is
for i in xrange(5):
time.sleep(3)
if iteration == 1: # asking if the variable is 1
print('?~~~~~') # printing this
iteration += 1 # adding one to the iteration variable
elif iteration == 2:
print('~?~~~~')
iteration += 1
elif iteration == 3:
print('~~?~~~')
iteration += 1
elif iteration == 4:
print('~~~?~~')
iteration += 1
elif iteration == 5:
print('~~~~?~')
iteration += 1
elif iteration == 6:
print('~~~~~?')
iteration = 1
</code></pre>
<p>Here is the version using splicing</p>
<pre><code>import time
iteration = 1
list = list('~~~~~~')
old_list = list
for i in xrange(5):
time.sleep(3)
list[iteration-1] = '?'
print("".join(list))
list = list('~~~~~~')
if iteration == 6:
iteration = 1
else:
iteration += 1
</code></pre>
<p>If you want a tutorial, that I would recommend is the one at <a href="http://tutorialspoint.com/python/" rel="nofollow">http://tutorialspoint.com/python/</a></p>
<p>Otherwise, the original Python tutorial is great: <a href="https://docs.python.org/2/tutorial/" rel="nofollow">https://docs.python.org/2/tutorial/</a></p>
| 0 | 2016-08-25T06:20:03Z | [
"python",
"loops",
"timer",
"python-2.x"
] |
confused about numpy.c_ document and sample code | 39,136,730 | <p>I read the document about numpy.c_ many times but still confused. It is said -- "Translates slice objects to concatenation along the second axis." in the following document. Could anyone clarify in the example below, what is slice objects, and what is 2nd axis? I see they are all one dimension and confused where the 2nd axis coming from.</p>
<p>Using Python 2.7 on Windows.</p>
<p><a href="http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.c_.html#numpy.c_" rel="nofollow">http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.c_.html#numpy.c_</a></p>
<pre><code>>>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
array([[1, 2, 3, 0, 0, 4, 5, 6]])
</code></pre>
| 0 | 2016-08-25T04:32:14Z | 39,137,008 | <p><code>np.c_</code> is another way of doing array concatenate</p>
<pre><code>In [701]: np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
Out[701]: array([[1, 2, 3, 0, 0, 4, 5, 6]])
In [702]: np.concatenate([np.array([[1,2,3]]), [[0]], [[0]], np.array([[4,5,6]])],
axis=1)
Out[702]: array([[1, 2, 3, 0, 0, 4, 5, 6]])
</code></pre>
<p>The output shape is (1,8) in both cases; the concatenation was on axis=1, the 2nd axis.</p>
<p><code>c_</code> took care of expanding the dimensions of the <code>0</code> to <code>np.array([[0]])</code>, the 2d (1,1) needed to concatenate.</p>
<p><code>np.c_</code> (and <code>np.r_</code>) is actually a class object with a <code>__getitem__</code> method, so it works with the <code>[]</code> syntax. The <code>numpy/lib/index_tricks.py</code> source file is instructive reading.</p>
<p>Note that the <code>row</code> version works with the : slice syntax, producing a 1d (8,) array (same numbers, but in 1d)</p>
<pre><code>In [706]: np.r_[1:4,0,0,4:7]
Out[706]: array([1, 2, 3, 0, 0, 4, 5, 6])
In [708]: np.concatenate((np.arange(4),[0],[0],np.arange(4,7)))
Out[708]: array([0, 1, 2, 3, 0, 0, 4, 5, 6])
In [710]: np.hstack((np.arange(4),0,0,np.arange(4,7)))
Out[710]: array([0, 1, 2, 3, 0, 0, 4, 5, 6])
</code></pre>
<p><code>np.c_</code> is a convenience, but not something you are required to understand. I think being able to work with <code>concatenate</code> directly is more useful. It forces you to think explicitly about the dimensions of the inputs.</p>
<p><code>[[1,2,3]]</code> is actually a list - a list containing one list. <code>np.array([[1,2,3]])</code> is a 2d array with shape (1,3). <code>np.arange(1,4)</code> produces a (3,) array with the same numbers. <code>np.arange(1,4)[None,:]</code> makes it a (1,3) array. </p>
<p><code>slice(1,4)</code> is a slice object. <code>np.r_</code> and <code>np.c_</code> can turn a slice object into a array - by actually using <code>np.arange</code>.</p>
<pre><code>In [713]: slice(1,4)
Out[713]: slice(1, 4, None)
In [714]: np.r_[slice(1,4)]
Out[714]: array([1, 2, 3])
In [715]: np.c_[slice(1,4)] # (3,1) array
Out[715]:
array([[1],
[2],
[3]])
In [716]: np.c_[1:4] # equivalent with the : notation
Out[716]:
array([[1],
[2],
[3]])
</code></pre>
<p>And to get back to the original example (which might not be the best):</p>
<pre><code>In [722]: np.c_[[np.r_[1:4]],0,0,[np.r_[4:7]]]
Out[722]: array([[1, 2, 3, 0, 0, 4, 5, 6]])
</code></pre>
<p>==========</p>
<pre><code>In [731]: np.c_[np.ones((5,3)),np.random.randn(5,10)].shape
Out[731]: (5, 13)
</code></pre>
<p>For <code>np.c_</code> the 1st dimension of both needs to match.</p>
<p>In the <code>learn</code> example, <code>n_samples</code> is the 1st dim of <code>X</code> (rows), and the <code>randn</code> also needs to have that many rows.</p>
<pre><code>n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
</code></pre>
<p><code>np.concatenate([(X, randn(n_samples...)], axis=1)</code> should work just as well here. A little wordier, but functionally the same.</p>
| 2 | 2016-08-25T05:02:13Z | [
"python",
"python-2.7",
"numpy",
"machine-learning"
] |
How can I get axis of different length but same scale for subplots in matplotlib? | 39,136,786 | <p>If I have, for example, these 3 datasets to plot:</p>
<pre><code>a = np.arange(0,10,1)
b = np.arange(2,6,1)
c = np.arange(5,10,1)
</code></pre>
<p>and obviously, I don't want them to share the same axis, because some of them would basically just have a big empty graph with a few datapoints somewhere in the corner. So I would ideally have subplots of different sizes, but all with the same scale (i.e. that the step 1 has the same length on all subplots). I know I could do this manually by setting the size of the figure, but for a larger number of datasets or not so nice numbers it would be a real pain. But searching through other questions or the documentation, I couldn't find anything that would, for example, set the fixed distance of ticks on axis or something. Please note that I am not asking about the aspect ratio. The aspect ratio can be different, I just need the same scale on an axis. (See the image below, which hopefully illustrates my problem. Note: no I don't need the scale bar in my actual plot, this is here for you to see how the scale is the same.)
Thanks.</p>
<p><a href="http://i.stack.imgur.com/g44D0.png" rel="nofollow"><img src="http://i.stack.imgur.com/g44D0.png" alt="updated image"></a></p>
| 0 | 2016-08-25T04:39:05Z | 39,137,050 | <p>Well after an hour:</p>
<pre><code>__author__ = 'madevelasco'
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def group(x, max, min, iters):
total_range = max - min
for i in range(0, iters):
if (x > min + i*total_range/iters and x <= min + (i+1)*total_range/iters):
return i
def newPlots():
df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
df.plot(x = 'x', y = 'y', kind = 'scatter', alpha=0.5)
plt.show()
##Sort by the column you want
df.sort_values(['x'], ascending=[False], inplace=True)
result = df.reset_index(drop=True).copy()
#Number of groups you want
iterations = 3
max_range = df['x'].max()
min_range = df['x'].min()
total_range = max_range - min_range
result['group'] = result.apply(lambda x: group(x['x'], max_range, min_range, iterations ), axis=1)
print(result)
for x in range (0, iterations):
lower = min_range + (x)*total_range/iterations
upper = min_range + (1+x)*total_range/iterations
new = result[result['group'] == x]
new.plot(x = 'x', y = 'y', kind = 'scatter', alpha=0.3)
axes = plt.gca()
axes.set_xlim([lower, upper])
axes.set_ylim([df['y'].min(),df['y'].max()])
plt.show()
if __name__ == '__main__':
newPlots()
</code></pre>
<p>I used pandas to to this. Honestly, the idea of visualization is to have all data in one graph but not separated like that. To maintain the idea of your date and even for readability, one of the axis should be fixed. I did between edits</p>
<p>Image of all points</p>
<p><a href="http://i.stack.imgur.com/O0o2c.png" rel="nofollow"><img src="http://i.stack.imgur.com/O0o2c.png" alt="General"></a></p>
<p>Sub plots</p>
<p><a href="http://i.stack.imgur.com/K5tD5.png" rel="nofollow"><img src="http://i.stack.imgur.com/K5tD5.png" alt="first subplot"></a></p>
<p><a href="http://i.stack.imgur.com/G9hIJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/G9hIJ.png" alt="second subplot"></a></p>
<p><a href="http://i.stack.imgur.com/ANv7n.png" rel="nofollow"><img src="http://i.stack.imgur.com/ANv7n.png" alt="third subplot"></a></p>
| 0 | 2016-08-25T05:05:37Z | [
"python",
"matplotlib"
] |
How can I get axis of different length but same scale for subplots in matplotlib? | 39,136,786 | <p>If I have, for example, these 3 datasets to plot:</p>
<pre><code>a = np.arange(0,10,1)
b = np.arange(2,6,1)
c = np.arange(5,10,1)
</code></pre>
<p>and obviously, I don't want them to share the same axis, because some of them would basically just have a big empty graph with a few datapoints somewhere in the corner. So I would ideally have subplots of different sizes, but all with the same scale (i.e. that the step 1 has the same length on all subplots). I know I could do this manually by setting the size of the figure, but for a larger number of datasets or not so nice numbers it would be a real pain. But searching through other questions or the documentation, I couldn't find anything that would, for example, set the fixed distance of ticks on axis or something. Please note that I am not asking about the aspect ratio. The aspect ratio can be different, I just need the same scale on an axis. (See the image below, which hopefully illustrates my problem. Note: no I don't need the scale bar in my actual plot, this is here for you to see how the scale is the same.)
Thanks.</p>
<p><a href="http://i.stack.imgur.com/g44D0.png" rel="nofollow"><img src="http://i.stack.imgur.com/g44D0.png" alt="updated image"></a></p>
| 0 | 2016-08-25T04:39:05Z | 39,239,438 | <p>After doing a lot of research, it looks like there really isn't any simple command to do this. But first, giving a thought of the range of both x and y values of each subplot and their ratios, and the layout, GridSpec will do the job.</p>
<p>So for our example, the layout is as presented in the question, i.e. the biggest picture on top, the two smaller ones next to each other underneath. To make it easier, the y range is the same for all of them (but if it wasn't we would use the same calculations as for x). Now, knowing this layout, we can create a grid. The vertical span is 20 (because we have two rows of 4 plots with y-range 10) and we may want some space between them for axis labels, legend etc., so we'll add extra 5. The first plot has x range of 10, However, the second and third figures have the range of 4 and 5, which is 9 in total, and we may also want some space between them, so let us add 3 extra. So the horizontal grid will span over 12. Hence, we create a grid 25 x 12 and fit our plots in this grid as follows:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
## GRIDSPEC INTRO - creating a grid to distribute the subplots with same scales and different sizes.
fig = plt.figure()
gs=gridspec.GridSpec(25,12)
## SUBPLOTS of GRIDSPEC
#the first (big) plot
axes1 = plt.subplot(gs[:10,:10])
ax1 = plt.plot(x,y) # plot some data here
ax1 = plt.xlim(1,10)
ax1 = plt.ylim(1,10)
# the second plot below the big one on the left
axes2 = plt.subplot(gs[15:,:4])
ax2 = plt.plot(x,y) # plot some data here
ax2 = plt.xlim(2,6)
ax2 = plt.ylim(1,10)
# the third plot - below the big one on the right
axes3 = plt.subplot(gs[15:,7:])
ax3 = plt.plot(x,y) # plot some data here
ax3 = plt.xlim(5,10)
ax3 = plt.ylim(1,10)
plt.show()
</code></pre>
| 0 | 2016-08-31T01:36:59Z | [
"python",
"matplotlib"
] |
How can I split an integer into a list of n length evenly in Python 3.5? | 39,136,825 | <p>I need to be able to split an integer into a list of n-length evenly.</p>
<p>For example n = 4,</p>
<pre><code>12 -> [0, 0, 1, 2]
1234 -> [1, 2, 3, 4]
12345 -> [1, 2, 3, 45]
123456 -> [1, 2, 34, 56]
1234567 -> [1, 23, 45, 67]
12345678 -> 12, 34, 56, 78]
123456789 -> [12, 34, 56, 789]
</code></pre>
<p>I'm sure I went overkill with the number of examples I have given, but it'll help get the point across.</p>
<p>The code that I have used in the past to split items into lists is:</p>
<pre><code>def split(s, chunk_size):
a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
return [''.join(t) for t in a]
</code></pre>
<p>but this code only breaks into n-chunks. (Code from StackOverflow, I don't remember the exact post, sorry).</p>
<p>Thanks for the help.</p>
| 2 | 2016-08-25T04:43:51Z | 39,137,047 | <p>sorry - for faulty code
It is working according to the spec</p>
<pre><code>def split(s, list_size):
s = str(s)
assert len(s) >= list_size, "assertion failed"
r, rem = divmod(len(s), list_size)
lst = []
for i in range(list_size):
lst.append(s[i*r:(i+1)*r])
for j in range(rem):
lst[-(j+1)] += s[list_size + j]
return lst
</code></pre>
| -1 | 2016-08-25T05:05:21Z | [
"python",
"python-3.x"
] |
How can I split an integer into a list of n length evenly in Python 3.5? | 39,136,825 | <p>I need to be able to split an integer into a list of n-length evenly.</p>
<p>For example n = 4,</p>
<pre><code>12 -> [0, 0, 1, 2]
1234 -> [1, 2, 3, 4]
12345 -> [1, 2, 3, 45]
123456 -> [1, 2, 34, 56]
1234567 -> [1, 23, 45, 67]
12345678 -> 12, 34, 56, 78]
123456789 -> [12, 34, 56, 789]
</code></pre>
<p>I'm sure I went overkill with the number of examples I have given, but it'll help get the point across.</p>
<p>The code that I have used in the past to split items into lists is:</p>
<pre><code>def split(s, chunk_size):
a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
return [''.join(t) for t in a]
</code></pre>
<p>but this code only breaks into n-chunks. (Code from StackOverflow, I don't remember the exact post, sorry).</p>
<p>Thanks for the help.</p>
| 2 | 2016-08-25T04:43:51Z | 39,137,072 | <pre><code>def split(seq, n):
"""Partitions `seq` into `n` successive slices of roughly equal size.
The sizes of each yielded slice shall differ by at most one.
"""
q, r = divmod(len(seq), n)
start = 0
for i in range(n):
size = q + (i < r)
yield seq[start : start + size]
start += size
</code></pre>
<p>It basically works the same way as <a href="http://stackoverflow.com/a/312464">this popular answer</a>, except it evenly distributes the remainder into each of the <em>n</em> slices.</p>
<p>Unfortunately, this will distribute towards the head of the list. To tweak it for your case, you need to change <code>size = q + (i < r)</code> to something like:</p>
<pre><code>size = q + (i >= (n - r))
</code></pre>
<p>With this change, the following:</p>
<pre><code>print(list(split('1234', 4)))
print(list(split('12345', 4)))
print(list(split('123456', 4)))
print(list(split('1234567', 4)))
print(list(split('12345678', 4)))
print(list(split('123456789', 4)))
</code></pre>
<p>prints:</p>
<pre><code>['1', '2', '3', '4']
['1', '2', '3', '45']
['1', '2', '34', '56']
['1', '23', '45', '67']
['12', '34', '56', '78']
['12', '34', '56', '789']
</code></pre>
| 4 | 2016-08-25T05:08:13Z | [
"python",
"python-3.x"
] |
How can I split an integer into a list of n length evenly in Python 3.5? | 39,136,825 | <p>I need to be able to split an integer into a list of n-length evenly.</p>
<p>For example n = 4,</p>
<pre><code>12 -> [0, 0, 1, 2]
1234 -> [1, 2, 3, 4]
12345 -> [1, 2, 3, 45]
123456 -> [1, 2, 34, 56]
1234567 -> [1, 23, 45, 67]
12345678 -> 12, 34, 56, 78]
123456789 -> [12, 34, 56, 789]
</code></pre>
<p>I'm sure I went overkill with the number of examples I have given, but it'll help get the point across.</p>
<p>The code that I have used in the past to split items into lists is:</p>
<pre><code>def split(s, chunk_size):
a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
return [''.join(t) for t in a]
</code></pre>
<p>but this code only breaks into n-chunks. (Code from StackOverflow, I don't remember the exact post, sorry).</p>
<p>Thanks for the help.</p>
| 2 | 2016-08-25T04:43:51Z | 39,137,319 | <p>Variant on Ahsan's answer that should distribute to the remainder across the end of the sequence correctly:</p>
<pre><code>from itertools import accumulate
def split(s, parts):
s = str(s)
r, rem = divmod(len(s), parts)
norem = parts - rem
counts = [r]*norem + [r+1]*rem
# Prepend 0 to counts only for accumulate to start from 0
return [s[start:start+cnt] for start, cnt in zip(accumulate([0] + counts), counts)]
</code></pre>
| 1 | 2016-08-25T05:28:36Z | [
"python",
"python-3.x"
] |
How can I split an integer into a list of n length evenly in Python 3.5? | 39,136,825 | <p>I need to be able to split an integer into a list of n-length evenly.</p>
<p>For example n = 4,</p>
<pre><code>12 -> [0, 0, 1, 2]
1234 -> [1, 2, 3, 4]
12345 -> [1, 2, 3, 45]
123456 -> [1, 2, 34, 56]
1234567 -> [1, 23, 45, 67]
12345678 -> 12, 34, 56, 78]
123456789 -> [12, 34, 56, 789]
</code></pre>
<p>I'm sure I went overkill with the number of examples I have given, but it'll help get the point across.</p>
<p>The code that I have used in the past to split items into lists is:</p>
<pre><code>def split(s, chunk_size):
a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
return [''.join(t) for t in a]
</code></pre>
<p>but this code only breaks into n-chunks. (Code from StackOverflow, I don't remember the exact post, sorry).</p>
<p>Thanks for the help.</p>
| 2 | 2016-08-25T04:43:51Z | 39,137,377 | <p>The selected answer has its advantage, but I did it in a more straightforward way:</p>
<pre><code>def chunk(s, n):
return [s[i:i+n] for i in range(0, len(s), n)]
def split(s0, numberOfChunks):
s = ('0' * max(0, numberOfChunks - len(s0))) + s0
sizeOfChunk = len(s) / numberOfChunks
numberOfSmallChunks = numberOfChunks - len(s) % numberOfChunks
return chunk(s[:numberOfSmallChunks * sizeOfChunk], sizeOfChunk) +
chunk(s[sizeOfChunk*numberOfSmallChunks:], sizeOfChunk+1)
</code></pre>
| 0 | 2016-08-25T05:33:38Z | [
"python",
"python-3.x"
] |
how scikit learn figure out logistic regression for classification or regression | 39,136,833 | <p>I think logistic regression could be used for both regression (get number between 0 and 1, e.g. using logistic regression to predict a probability between 0 and 1) and classification. The question is, it seems after we provide the training data and target, logistic regression could automatically figure out if we are doing a regression or doing a classification?</p>
<p>For example, in below example code, logistic regression figured out we just need output to be one of the 3 class <code>0, 1, 2</code>, other than any number between <code>0</code> and <code>2</code>? Just curious how logistic regression automatically figured out whether it is doing a regression (output is a continuous range) or classification (output is discrete) problem?</p>
<p><a href="http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html</a></p>
<pre><code>print(__doc__)
# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, datasets
# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
Y = iris.target
h = .02 # step size in the mesh
logreg = linear_model.LogisticRegression(C=1e5)
# we create an instance of Neighbours Classifier and fit the data.
logreg.fit(X, Y)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.show()
</code></pre>
| 0 | 2016-08-25T04:45:02Z | 39,150,081 | <p>Logistic regression often uses a cross-entropy cost function, which models loss according to a binary error. Also, the output of logistic regression usually follows a sigmoid at the decision boundary, meaning that while the decision boundary may be linear, the output (often viewed as a probability of the point representing one of two classes on either side of the boundary) transitions in non-linear fashion. This would make your regression model from 0 to 1 a very particular, non-linear function. That might be desirable in certain circumstances, but is probably not generally desirable.</p>
<p>You can think of logistic regression as providing an amplitude that represents probability of being in a class, or not. If you consider a binary classifier with two independent variables, you can picture a surface where the decision boundary is the topological line where probability is 0.5. Where the classifier is certain the of the class, the surface is either on the plateau (probability = 1) or in the low lying region (probability = 0). The transition from low probability regions to high follows a sigmoid function, usually.</p>
<p>You might look at Andrew Ng's Coursera course, which has a set of classes on logistic regression. <a href="https://www.youtube.com/watch?v=K5oZM1Izn3c&list=PLZ9qNFMHZ-A4rycgrgOYma6zxF4BZGGPW&index=33" rel="nofollow">This</a> is the first of the classes. I have a github repo that is the R version of that class's output, <a href="https://github.com/johnyetter/R-CourseraML/tree/master/Rmlclass-ex2" rel="nofollow">here</a>, which you might find helpful in understanding logistic regression better.</p>
| 1 | 2016-08-25T16:11:23Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
Django: Redirecting to another url based on user input in form | 39,136,861 | <p>I am trying to achieve something really simple and having no luck after reviewing the Django forms documentation as well as the section in the Django Tutorial on Forms (Part 4), and several SO threads.</p>
<p>I have a home page which has a form in which the user should be able to enter the name of some basketball player. When they hit submit it should redirect to my other page, the player_stats page, which will show some information about that player. I would ideally also like to have this same form available on the player_stats page itself so that the user can go from player to player without having to go back to the home page in between.</p>
<p>I should add, the name of the app in which all these files live in "desk".</p>
<p><strong>forms.py</strong></p>
<pre><code>from django import forms
class NameForm(forms.Form):
name = forms.CharField(label='Name', max_length=100)
</code></pre>
<p><strong>index.html</strong></p>
<pre><code><div> HOME PAGE </div>
<form action="{% url 'player_stats' name %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Go"/>
</form>
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>def index(request):
template = loader.get_template('desk/index.html')
return HttpResponse(template.render(request))
def player_stats(request, name):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# redirect to a new URL:
name = form.cleaned_data['name']
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
template = loader.get_template('desk/player_stats.html')
context = get_player_stats_context(tag)
return HttpResponse(template.render(context, request))
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<name>([\s\S]+))/player_stats/$', views.player_stats, name='player_stats'),
]
</code></pre>
<p>I guess the examples shown in the docs are slightly different from my situation because the template always seems to have some context object provided by the view or the redirect is to a hardcoded url that just happens if the form is valid and the url doesn't depend on what the content of the submitted form was. What am I not getting here?</p>
| 1 | 2016-08-25T04:48:55Z | 39,137,292 | <p>You should use name given in <code>form.cleaned_data</code> not <code>form.name</code>.
So your code should be </p>
<pre><code>return HttpResponseRedirect(reverse('desk:player_stats',
args=(form.cleaned_data['name'],)))
</code></pre>
| 3 | 2016-08-25T05:27:06Z | [
"python",
"django",
"forms"
] |
Going through words in a list in a python for loop and it says that it's out of range? | 39,137,033 | <p>I am writing a python script and at one point I use the following for loop:</p>
<pre><code>word=raw_input("Pick one of the words above. ")
print(sentence.split())
number = len(sentence.split()) + 1
for y in range (0, number):
if sentence.split()[y] == word:
global wordNumber
wordNumber = y
print wordNumber
</code></pre>
<p>I get the following error</p>
<pre><code> if sentence.split()[y] == word:
IndexError: list index out of range
</code></pre>
<p>Any ideas? Thanks so much.</p>
| 0 | 2016-08-25T05:04:24Z | 39,137,085 | <p>You are iterating past the end of the list. Since the list has <code>len(sentence.split())</code> items, that means its indices go from <code>0</code> to <code>len(sentence.split()) - 1</code>. So, you want to iterate over <code>range(0, len(sentence_split())</code> so that the last iterated index is <code>len(sentence.split()) - 1</code>.</p>
<p>Also, I would suggest saving <code>sentence.split()</code> into a list so that you don't have to continue to call it. In fact, you don't have to iterate on indices at all - just iterate over the list.</p>
<pre><code>word = raw_input('Pick one of the words above.')
tokens = sentence.split()
print tokens
for i, token in enumerate(tokens):
if token == word:
global wordNumber
wordNumber = i
print wordNumber
</code></pre>
<p>Or even more concisely:</p>
<pre><code>word = raw_input('Pick one of the words above.')
tokens = sentence.split()
print tokens
wordNumber = tokens.find(word)
print wordNumber
</code></pre>
| 0 | 2016-08-25T05:09:13Z | [
"python"
] |
Scraping Restaurant Details from Trip Advisor | 39,137,066 | <p>I am trying to make a script to scrap Restaurant details from TripAdvisor site. Just for learning.</p>
<p>The problem here is I cant find restaurant names in Source page from the second page. Well, actually there is no correct second link. But when I check live site and inspect, I can see the restaurant name.</p>
<p>For Eg: </p>
<pre><code>https://www.tripadvisor.in/Restaurants-g294003-Kuwait_City.html
</code></pre>
<p>In the above link, te first link, I can get all the source correctly. But when I select 2,3 or Other Links from bottom, I cant able to view page source correctly. It is displaying the same source of first one.</p>
<p>My current Code </p>
<pre><code>import urllib.request
import requests #Install certifi for https
from bs4 import BeautifulSoup
url = "https://www.tripadvisor.in/Restaurants-g294003-Kuwait_City.html"
r=requests.get(url)
data=r.text
soup = BeautifulSoup(data,"lxml")
for link in soup.find_all('a'):
print(link.get('href'))
print ("\n\n\n\n\n\n")
url1 = "https://www.tripadvisor.in/RestaurantSearch-g294003-oa120-Kuwait_City.html"
r=requests.get(url)
data=r.text
soup = BeautifulSoup(data,"lxml")
for link in soup.find_all('a'):
print(link.get('href'))
</code></pre>
<p>I am Stuck here. Dont know what to do .</p>
| 0 | 2016-08-25T05:07:45Z | 39,138,363 | <p>I think you had a typo in the second part of your code:</p>
<pre><code>url1 = "https://www.tripadvisor.in/RestaurantSearch-g294003-oa120-Kuwait_City.html"
r=requests.get(url)
#Change this to:
r=requests.get(url1)
</code></pre>
| 1 | 2016-08-25T06:42:20Z | [
"python",
"screen-scraping",
"bs4"
] |
How to Run a Python Script from a Rails Application? | 39,137,179 | <p>I am working on a rails application now that needs to run a single python script whenever a button is clicked on our apps home page. I am trying to figure out a way to have rails run this script, and both of my attempts so far have failed. </p>
<p>My first try was to use the exec(..) command to just run the "python script.py", but when I do this it seems to run the file but terminate the rails server so I would need to manually reboot it each time.</p>
<p>My second try was to install the gem "RubyPython" and attempt from there, but I am at a loss at what to do once I have it running.. I can not find any examples of people using it to run or load a python script.</p>
<p>Any help for this would be appreciated.</p>
| 0 | 2016-08-25T05:16:50Z | 39,137,328 | <p><code>exec</code> replaces the current process with the new one. You want to run it as a subprocess. See <a href="http://stackoverflow.com/questions/7212573/when-to-use-each-method-of-launching-a-subprocess-in-ruby">When to use each method of launching a subprocess in Ruby</a> for an overview; I suggest using either backticks for a simple process, or <code>popen</code>/<code>popen3</code> when more control is required.</p>
<p>Alternately, you can use <a href="https://github.com/halostatue/rubypython" rel="nofollow"><code>rubypython</code></a>, the Ruby-Python bridge gem, to execute Python from Ruby itself (especially if you'll be executing the same Python function repeatedly). To do so, you would need to make your script into a proper Python module, start the bridge when the Rails app starts, then use <code>RubyPython.import</code> to get a reference to your module into your Ruby code. The examples on the gem's GitHub page are quite simple, and should be sufficient for your purpose.</p>
| 1 | 2016-08-25T05:29:24Z | [
"python",
"ruby-on-rails",
"ruby"
] |
How to fix TypeError: __init__() takes at least 2 arguments (1 given) Error | 39,137,214 | <p>I am trying to split the uploaded pdf file into images but i am getting error like take at least 2 arguments(1given).</p>
<p>I know this error is already asked but i confused to fix in my program.</p>
<pre><code>from pyPdf import PdfFileWriter, PdfFileReader
from wand.image import Image
import os
from Tkinter import *
from tkFileDialog import askopenfilename
root =Tk()
root.geometry("500x500")
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("pdf")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
label = Label(self,text="Upload a pdf file",font = ('Arial' , 25))
label.pack()
self.Label1=Label(self)
self.Label1.pack()
self.button = Button(self, text="Upload", command=self.load_file, fg="red", width=10).pack(side=TOP, expand=YES)
self.pack(fill=BOTH, expand=YES)
def load_file(self):
fname = askopenfilename()
self.Label1.config(text=os.path.basename(fname), fg="blue")
self.im = Image(filename=fname, resolution=200)
for i, page in enumerate(im.sequence):
with Image(page) as page_image:
page_image.alpha_channel = False
page_image.save(filename='page-%s.png' % i)
print "suceSsfully"
if __name__ == "__main__":
MyFrame().mainloop()
</code></pre>
<p>Whenever i run this code ,i am getting this error.</p>
<blockquote>
<pre><code>File "root.py", line 27, in load_file
self.im = Image(filename=fname, resolution=200)
TypeError: __init__() takes at least 2 arguments (1 given)
</code></pre>
</blockquote>
| -2 | 2016-08-25T05:19:50Z | 39,137,747 | <p><code>Tkinter</code> has it's own <code>Image</code> class <code>Tkinter.Image</code>.
When you import all from Tkinter after import <code>wand.image.Image</code>, you start to use <code>Image</code> class from <code>Tkinter</code>.
You should import <code>Tkinter</code> as <code>import Tkinter as tk</code> and use it with <code>tk.class_name</code>, or explicit use <code>wand.image.Image</code> instead of <code>Image</code>.</p>
| 2 | 2016-08-25T06:03:25Z | [
"python",
"tkinter",
"wand"
] |
Django exception : django.core.exceptions.ImproperlyConfigured: | 39,137,339 | <p>When i run the same code in django shell it works fine for me. but when I fire up the Python interpreter (Python 2) to check some things, I get the an error when I try importing - from django.contrib.auth.models import User </p>
<pre><code>import os
import django
django.setup()
import smtplib
import sys
sys.path.insert(0, "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware")
import dateutil.relativedelta
from django.conf import settings
from django.contrib.auth.models import User
from opaque_keys.edx.keys import CourseKey
from courseware.models import StudentModule
from datetime import datetime
def PCSurvey_email():
for student in StudentModule.objects.filter(module_type="PCSurvey"):
two_months_date = datetime.now().date() - dateutil.relativedelta.relativedelta(months=2)
created = student.created.date()
if created == two_months_date :
user_id = student.student_id
user_email = User.objects.get(id = user_id).email
FROM = "user@example.com"
TO = [user_email] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP('outlook.net')
server.sendmail(FROM, TO, message)
server.quit()
#deleting the module
smod = StudentModule.objects.get(module_type="PCSurvey", course_id = student.course_id, student_id= student.student_id)
smod.delete()
</code></pre>
<p>The error that I get is </p>
<pre><code> Traceback (most recent call last):
File "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware/PCSurvey_email.py", line 4, in <module>
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code></pre>
<p>Any help on this is very much appreciated.</p>
| 0 | 2016-08-25T05:30:03Z | 39,137,386 | <p>When you open a shell, <code>django</code> automatically sets itself up. </p>
<p>With Python interpreter you have to do this manually:</p>
<pre><code>import django
django.setup()
</code></pre>
| 0 | 2016-08-25T05:34:12Z | [
"python",
"django"
] |
Django exception : django.core.exceptions.ImproperlyConfigured: | 39,137,339 | <p>When i run the same code in django shell it works fine for me. but when I fire up the Python interpreter (Python 2) to check some things, I get the an error when I try importing - from django.contrib.auth.models import User </p>
<pre><code>import os
import django
django.setup()
import smtplib
import sys
sys.path.insert(0, "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware")
import dateutil.relativedelta
from django.conf import settings
from django.contrib.auth.models import User
from opaque_keys.edx.keys import CourseKey
from courseware.models import StudentModule
from datetime import datetime
def PCSurvey_email():
for student in StudentModule.objects.filter(module_type="PCSurvey"):
two_months_date = datetime.now().date() - dateutil.relativedelta.relativedelta(months=2)
created = student.created.date()
if created == two_months_date :
user_id = student.student_id
user_email = User.objects.get(id = user_id).email
FROM = "user@example.com"
TO = [user_email] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP('outlook.net')
server.sendmail(FROM, TO, message)
server.quit()
#deleting the module
smod = StudentModule.objects.get(module_type="PCSurvey", course_id = student.course_id, student_id= student.student_id)
smod.delete()
</code></pre>
<p>The error that I get is </p>
<pre><code> Traceback (most recent call last):
File "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware/PCSurvey_email.py", line 4, in <module>
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code></pre>
<p>Any help on this is very much appreciated.</p>
| 0 | 2016-08-25T05:30:03Z | 39,137,721 | <p>Django needs to be setup, in order to run fine, when you run it through manage.py shell, manage.py takes care or setting it up for you, but doing it via a python script, needs manual setup.</p>
<p>You also seem to have used your defined models, to be able to import them into your python script, you need to add the path to the root folder of your project to the current python path.</p>
<p>Finally, you need to tell django where your <strong>settings file</strong> is (<em>before</em> setting up your django), in your manage.py file, you should have something like this :</p>
<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
</code></pre>
<p>Go make it a constant, name it * DEFAULT_SETTINGS_MODULE *, so you now have:</p>
<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", DEFAULT_SETTINGS_MODULE)
</code></pre>
<p>Now you need to import the constant into your script and tell django (By setting an env var) where it should look for the settings file. </p>
<p>So in all:</p>
<pre><code>import sys, os
sys.path.insert(0, "/path/to/parent/of/courseware") # /home/projects/my-djproj
from manage import DEFAULT_SETTINGS_MODULE
os.environ.setdefault("DJANGO_SETTINGS_MODULE", DEFAULT_SETTINGS_MODULE)
import django
django.setup()
</code></pre>
<p>This way you're setup up just fine.</p>
| 1 | 2016-08-25T06:01:42Z | [
"python",
"django"
] |
Short Unique Hexadecimal String in Python | 39,137,344 | <p>I need to generate a unique hexadecimal string in Python 3 that meets following requirements:</p>
<ol>
<li>It should contain 6 characters</li>
<li>it should not contain just digits. There must be at least one character. </li>
<li>These generated strings should be random. They should not be in any order.</li>
<li>There should be minimum probability of conflict</li>
</ol>
<p>I have considered uuid4(). But the problem is that it generates strings with too many characters and any substring of the generated string can contain all digits(i.e. no character) at some point.</p>
<p>Is there any other way to fulfill this conditions? Thanks in advance!</p>
<p><strong>EDIT</strong></p>
<p>Can we use a hash for example SHA-1 to fulfill above requirements?</p>
| 0 | 2016-08-25T05:30:18Z | 39,137,997 | <p><strong>Note:</strong> Updated the answer for hexadecimal unique string. Earlier I assumed for alhanumeric string.</p>
<p>You may create your own unique function using <code>uuid</code> and <code>random</code> library</p>
<pre><code>>>> import uuid
>>> import random
# Step 1: Slice uuid with 5 i.e. new_id = str(uuid.uuid4())[:5]
# Step 2: Convert string to list of char i.e. new_id = list(new_id)
>>> uniqueval = list(str(uuid.uuid4())[:5])
# uniqueval = ['f', '4', '4', '4', '5']
# Step 3: Generate random number between 0-4 to insert new char i.e.
# random.randint(0, 4)
# Step 4: Get random char between a-f (for Hexadecimal char) i.e.
# chr(random.randint(ord('a'), ord('f')))
# Step 5: Insert random char to random index
>>> uniqueval.insert(random.randint(0, 4), chr(random.randint(ord('a'), ord('f'))))
# uniqueval = ['f', '4', '4', '4', 'f', '5']
# Step 6: Join the list
>>> uniqueval = ''.join(uniqueval)
# uniqueval = 'f444f5'
</code></pre>
| 1 | 2016-08-25T06:19:05Z | [
"python",
"python-3.x",
"uuid"
] |
Short Unique Hexadecimal String in Python | 39,137,344 | <p>I need to generate a unique hexadecimal string in Python 3 that meets following requirements:</p>
<ol>
<li>It should contain 6 characters</li>
<li>it should not contain just digits. There must be at least one character. </li>
<li>These generated strings should be random. They should not be in any order.</li>
<li>There should be minimum probability of conflict</li>
</ol>
<p>I have considered uuid4(). But the problem is that it generates strings with too many characters and any substring of the generated string can contain all digits(i.e. no character) at some point.</p>
<p>Is there any other way to fulfill this conditions? Thanks in advance!</p>
<p><strong>EDIT</strong></p>
<p>Can we use a hash for example SHA-1 to fulfill above requirements?</p>
| 0 | 2016-08-25T05:30:18Z | 39,138,110 | <p>Here's a simple method that samples evenly from all allowed strings. Sampling uniformly makes conflicts as rare as possible, short of keeping a log of previous keys or using a hash based on a counter (see below).</p>
<pre><code>import random
digits = '0123456789'
letters = 'abcdef'
all_chars = digits + letters
length = 6
while True:
val = ''.join(random.choice(all_chars) for i in range(length))
# The following line might be faster if you only want hex digits.
# It makes a long int with 24 random bits, converts it to hex,
# drops '0x' from the start and 'L' from the end, then pads
# with zeros up to six places if needed
# val = hex(random.getrandbits(4*length))[2:-1].zfill(length)
# test whether it contains at least one letter
if not val.isdigit():
break
# now val is a suitable string
print val
# 5d1d81
</code></pre>
<p>Alternatively, here's a somewhat more complex approach that also samples uniformly, but doesn't use any open-ended loops:</p>
<pre><code>import random, bisect
digits = '0123456789'
letters = 'abcdef'
all_chars = digits + letters
length = 6
# find how many valid strings there are with their first letter in position i
pos_weights = [10**i * 6 * 16**(length-1-i) for i in range(length)]
pos_c_weights = [sum(pos_weights[0:i+1]) for i in range(length)]
# choose a random slot among all the allowed strings
r = random.randint(0, pos_c_weights[-1])
# find the position for the first letter in the string
first_letter = bisect.bisect_left(pos_c_weights, r)
# generate a random string matching this pattern
val = ''.join(
[random.choice(digits) for i in range(first_letter)]
+ [random.choice(letters)]
+ [random.choice(all_chars) for i in range(first_letter + 1, length)]
)
# now val is a suitable string
print val
# 4a99f0
</code></pre>
<p>And finally, here's an even more complex method that uses the random number <code>r</code> to index directly into the entire range of allowed values, i.e., this converts any number in the range of 0-15,777,216 into a suitable hex string. This could be used to completely avoid conflicts (discussed more below).</p>
<pre><code>import random, bisect
digits = '0123456789'
letters = 'abcdef'
all_chars = digits + letters
length = 6
# find how many valid strings there are with their first letter in position i
pos_weights = [10**i * 6 * 16**(length-1-i) for i in range(length)]
pos_c_weights = [sum(pos_weights[0:i+1]) for i in range(length + 1)]
# choose a random slot among all the allowed strings
r = random.randint(0, pos_c_weights[-1])
# find the position for the first letter in the string
first_letter = bisect.bisect_left(pos_c_weights, r) - 1
# choose the corresponding string from among all that fit this pattern
offset = r - pos_c_weights[first_letter]
val = ''
# convert the offset to a collection of indexes within the allowed strings
# the space of allowed strings has dimensions
# 10 x 10 x ... (for digits) x 6 (for first letter) x 16 x 16 x ... (for later chars)
# so we can index across it by dividing into appropriate-sized slices
for i in range(length):
if i < first_letter:
offset, v = divmod(offset, 10)
val += digits[v]
elif i == first_letter:
offset, v = divmod(offset, 6)
val += letters[v]
else:
offset, v = divmod(offset, 16)
val += all_chars[v]
# now val is a suitable string
print val
# eb3493
</code></pre>
<h3>Uniform Sampling</h3>
<p>I mentioned above that this samples <em>uniformly</em> across all allowed strings. Some other answers here choose 5 characters completely at random and then force a letter into the string at a random position. That approach produces more strings with multiple letters than you would get randomly. e.g., that method always produces a 6-letter string if letters are chosen for the first 5 slots; however, in this case the sixth selection should actually only have a 6/16 chance of being a letter. Those approaches can't be fixed by forcing a letter into the sixth slot only if the first 5 slots are digits. In that case, all 5-digit strings would automatically be converted to 5 digits plus 1 letter, giving too many 5-digit strings. With uniform sampling, there should be a 10/16 chance of completely rejecting the string if the first 5 characters are digits.</p>
<p>Here are some examples that illustrate these sampling issues. Suppose you have a simpler problem: you want a string of two binary digits, with a rule that at least one of them must be a 1. Conflicts will be rarest if you produce 01, 10 or 11 with equal probability. You can do that by choosing random bits for each slot, and then throwing out the 00's (similar to my approach above).</p>
<p>But suppose you instead follow this rule: Make two random binary choices. The first choice will be used as-is in the string. The second choice will determine the location where an additional 1 will be inserted. This is similar to the approach used by the other answers here. Then you will have the following possible outcomes, where the first two columns represent the two binary choices:</p>
<pre><code>0 0 -> 10
0 1 -> 01
1 0 -> 11
1 1 -> 11
</code></pre>
<p>This approach has a 0.5 chance of producing 11, or 0.25 for 01 or 10, so it will increase the risk of collisions among 11 results.</p>
<p>You could try to improve this as follows: Make three random binary choices. The first choice will be used as-is in the string. The second choice will be converted to a 1 if the first choice was a 0; otherwise it will be added to the string as-is. The third choice will determine the location where the second choice will be inserted. Then you have the following possible outcomes:</p>
<pre><code>0 0 0 -> 10 (second choice converted to 1)
0 0 1 -> 01 (second choice converted to 1)
0 1 0 -> 10
0 1 1 -> 01
1 0 0 -> 10
1 0 1 -> 01
1 1 0 -> 11
1 1 1 -> 11
</code></pre>
<p>This gives 0.375 chance for 01 or 10, and 0.25 chance for 11. So this will slightly increase the risk of conflicts between duplicate 10 or 01 values.</p>
<h3>Reducing Conflicts</h3>
<p>If you are open to using all letters instead of just 'a' through 'f' (hexadecimal digits), you could alter the definition of <code>letters</code> as noted in the comments. This will give much more diverse strings and much less chance of conflict. If you generated 1,000 strings allowing all upper- and lowercase letters, you'd only have about a 0.0009% chance of generating any duplicates, vs. 3% chance with hex strings only. (This will also virtually eliminate double-passes through the loop.)</p>
<p>If you really want to avoid conflicts between strings, you could store all the values you've generated previously in a <code>set</code> and check against that before breaking from the loop. This would be good if you are going to generate fewer than about 5 million keys. Beyond that, you'd need quite a bit of RAM to hold the old keys, and it might take a few runs through the loop to find an unused key.</p>
<p>If you need to generate more keys than that, you could encrypt a counter, as described at <a href="http://stackoverflow.com/questions/2076838/generating-non-repeating-random-numbers-in-python">Generating non-repeating random numbers in Python</a>. The counter and its encrypted version would both be ints in the range of 0 to 15,777,216. The counter would just count up from 0, and the encrypted version would look like a random number. Then you would convert the encrypted version to hex using the third code example above. If you do this, you should generate a random encryption key at the start, and change the encryption key each time the counter rolls past your maximum, to avoid producing the same sequence again.</p>
| 3 | 2016-08-25T06:26:34Z | [
"python",
"python-3.x",
"uuid"
] |
Short Unique Hexadecimal String in Python | 39,137,344 | <p>I need to generate a unique hexadecimal string in Python 3 that meets following requirements:</p>
<ol>
<li>It should contain 6 characters</li>
<li>it should not contain just digits. There must be at least one character. </li>
<li>These generated strings should be random. They should not be in any order.</li>
<li>There should be minimum probability of conflict</li>
</ol>
<p>I have considered uuid4(). But the problem is that it generates strings with too many characters and any substring of the generated string can contain all digits(i.e. no character) at some point.</p>
<p>Is there any other way to fulfill this conditions? Thanks in advance!</p>
<p><strong>EDIT</strong></p>
<p>Can we use a hash for example SHA-1 to fulfill above requirements?</p>
| 0 | 2016-08-25T05:30:18Z | 39,139,235 | <p>The following approach works as follows, first pick one random letter to ensure rule 2, then select 4 random entries from the list of all available characters. Shuffle the resulting list. Lastly prepend one value taken from the list of all entries except <code>0</code> to ensure the string has 6 characters.</p>
<pre><code>import random
all = "0123456789abcdef"
result = [random.choice('abcdef')] + [random.choice(all) for _ in range(4)]
random.shuffle(result)
result.insert(0, random.choice(all[1:]))
print(''.join(result))
</code></pre>
<p>Giving you something like:</p>
<pre><code>3b7a4e
</code></pre>
<p>This approach avoids having to repeatedly check the result to ensure that it satisfies the rules.</p>
| 1 | 2016-08-25T07:32:05Z | [
"python",
"python-3.x",
"uuid"
] |
Short Unique Hexadecimal String in Python | 39,137,344 | <p>I need to generate a unique hexadecimal string in Python 3 that meets following requirements:</p>
<ol>
<li>It should contain 6 characters</li>
<li>it should not contain just digits. There must be at least one character. </li>
<li>These generated strings should be random. They should not be in any order.</li>
<li>There should be minimum probability of conflict</li>
</ol>
<p>I have considered uuid4(). But the problem is that it generates strings with too many characters and any substring of the generated string can contain all digits(i.e. no character) at some point.</p>
<p>Is there any other way to fulfill this conditions? Thanks in advance!</p>
<p><strong>EDIT</strong></p>
<p>Can we use a hash for example SHA-1 to fulfill above requirements?</p>
| 0 | 2016-08-25T05:30:18Z | 39,139,679 | <p>This function returns the nth string conforming to your requirements, so you can simply generate unique integers and convert them using this function.</p>
<pre><code>def inttohex(number, digits):
# there must be at least one character:
fullhex = 16**(digits - 1)*6
assert number < fullhex
partialnumber, remainder = divmod(number, digits*6)
charposition, charindex = divmod(remainder, digits)
char = ['a', 'b', 'c', 'd', 'e', 'f'][charposition]
hexconversion = list("{0:0{1}x}".format(partialnumber, digits-1))
hexconversion.insert(charposition, char)
return ''.join(hexconversion)
</code></pre>
<p>Now you can get a particular one using for instance</p>
<pre><code>import random
digits = 6
inttohex(random.randint(0, 6*16**(digits-1)), digits)
</code></pre>
<p>You can't have maximum randomness along with minimum probability of conflict. I recommend keeping track of which numbers you have handed out or if you are looping through all of them somehow, using a randomly sorted list.</p>
| 0 | 2016-08-25T07:56:43Z | [
"python",
"python-3.x",
"uuid"
] |
Vtk inserts incorrect color between nodes when mapping texture to mesh | 39,137,374 | <p>Hi I am trying to map a texture to 3d mesh using Mayavi and Python bindings of vtk. I am visualising an .obj wavefront. This obj is 3D photograph of a face. The texture image is a composite of three 2D photographs.</p>
<p><a href="http://i.stack.imgur.com/KNNGr.png" rel="nofollow"><img src="http://i.stack.imgur.com/KNNGr.png" alt="enter image description here"></a></p>
<p>Each node in the mesh has an (uv) co-ordinate in the image, which defines its color. Different regions of the mesh draw their colours from different sections of the image. To illustrate this I have replaced the actual texture image with this one:</p>
<p><a href="http://i.stack.imgur.com/XHFgV.png" rel="nofollow"><img src="http://i.stack.imgur.com/XHFgV.png" alt="enter image description here"></a></p>
<p>And mapped this to the mesh instead. </p>
<p><a href="http://i.stack.imgur.com/mIIq0.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/mIIq0.jpg" alt="enter image description here"></a></p>
<p>The problem I am having is illustrated around the nose. At the border between red and green there is an outline of blue. Closer inspection of this region in wireframe mode shows that it is not a problem with the uv mapping, but with how vtk is interpolating colour between two nodes. For some reason it is adding a piece of blue in between two nodes where one is red and one is green.</p>
<p><a href="http://i.stack.imgur.com/M1XHH.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/M1XHH.jpg" alt="enter image description here"></a></p>
<p>This causes serious problems when visualising using the real texture</p>
<p><a href="http://i.stack.imgur.com/2pu7n.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/2pu7n.jpg" alt="enter image description here"></a> </p>
<p>Is there a way to force vtk to choose the colour of one or the other neighbouring nodes for the colour between them? I tried turning "edge-clamping" on, but this did not achieve anything.</p>
<p>The code that I am using is below and you can access the files in question from here <a href="https://www.dropbox.com/sh/ipel0avsdiokr10/AADmUn1-qmsB3vX7BZObrASPa?dl=0" rel="nofollow">https://www.dropbox.com/sh/ipel0avsdiokr10/AADmUn1-qmsB3vX7BZObrASPa?dl=0</a>
but I hope this is a simple solution.</p>
<pre><code>from numpy import *
from mayavi import mlab
from tvtk.api import tvtk
import os
from vtk.util import numpy_support
def obj2array(f):
"""function for reading a Wavefront obj"""
if type(f)==str:
if os.path.isfile(f)==False:
raise ValueError('obj2array: unable to locate file ' + str(f))
f =open(f)
vertices = list()
connectivity = list()
uv = list()
vt = list()
fcount = 0
for l in f:
line = l.rstrip('\n')
data = line.split()
if len(data)==0:
pass
else:
if data[0] == 'v':
vertices.append(atleast_2d(array([float(item) for item in data[1:4]])))
elif data[0]=='vt':
uv.append(atleast_2d(array([float(item) for item in data[1:3]])))
elif data[0]=='f':
nverts = len(data)-1 # number of vertices comprising each face
if fcount == 0: #on first face establish face format
fcount = fcount + 1
if data[1].find('/')==-1: #Case 1
case = 1
elif data[1].find('//')==True:
case = 4
elif len(data[1].split('/'))==2:
case = 2
elif len(data[1].split('/'))==3:
case = 3
if case == 1:
f = atleast_2d([int(item) for item in data[1:len(data)]])
connectivity.append(f)
if case == 2:
splitdata = [item.split('/') for item in data[1:len(data)]]
f = atleast_2d([int(item[0]) for item in splitdata])
connectivity.append(f)
if case == 3:
splitdata = [item.split('/') for item in data[1:len(data)]]
f = atleast_2d([int(item[0]) for item in splitdata])
connectivity.append(f)
if case == 4:
splitdata = [item.split('//') for item in data[1:len(data)]]
f = atleast_2d([int(item[0]) for item in splitdata])
connectivity.append(f)
vertices = concatenate(vertices, axis = 0)
if len(uv)==0:
uv=None
else:
uv = concatenate(uv, axis = 0)
if len(connectivity) !=0:
try:
conarray = concatenate(connectivity, axis=0)
except ValueError:
if triangulate==True:
conarray=triangulate_mesh(connectivity,vertices)
else:
raise ValueError('obj2array: not all faces triangles?')
if conarray.shape[1]==4:
if triangulate==True:
conarray=triangulate_mesh(connectivity,vertices)
return vertices, conarray,uv
# load texture image
texture_img = tvtk.Texture(interpolate = 1,edge_clamp=1)
texture_img.input = tvtk.BMPReader(file_name='HM_1_repose.bmp').output
#load obj
verts, triangles, uv = obj2array('HM_1_repose.obj')
# make 0-indexed
triangles = triangles-1
surf = mlab.triangular_mesh(verts[:,0],verts[:,1],verts[:,2],triangles)
tc=numpy_support.numpy_to_vtk(uv)
pd = surf.mlab_source.dataset._vtk_obj.GetPointData()
pd.SetTCoords(tc)
surf.actor.actor.mapper.scalar_visibility=False
surf.actor.enable_texture = True
surf.actor.actor.texture = texture_img
mlab.show(stop=True)
</code></pre>
| 0 | 2016-08-25T05:33:30Z | 39,237,979 | <p>You can turn off all interpolation (change <code>interpolate = 1</code> to <code>interpolate = 0</code> in your example), but there is not a way to turn off interpolation at just the places where it would interpolate across sub-images of the texture â at least not without writing your own fragment shader. This will likely look crude.</p>
<p>Another solution would be to create 3 texture images with transparent texels at each location that is not part of the actor's face. Then render the same geometry with the same texture coordinates but a different image each time (i.e., have 3 actors each with the same polydata but a different texture image).</p>
| 1 | 2016-08-30T22:22:00Z | [
"python",
"vtk",
"texture-mapping",
"wavefront"
] |
Loading css in python web app using jinja2 | 39,137,499 | <p>I'm trying to make a little bioinformatics web app. I had it working with CGI, I am trying to tweak it so I can serve it on pythonanywhere or heroku. </p>
<p>The problem I am having is that the stylesheet and javascript aren't loading. I'm pretty new to programming, but I have searched extensively before posting. I removed a lot of the heft from the app to isolate the problem. The app's directory now looks like:</p>
<pre><code>/app
main.html
main.css
main.js
WSGI_app.py
</code></pre>
<p>The code in WSGI_app.py looks like:</p>
<pre><code>from wsgiref.simple_server import make_server
import jinja2
def application( environ, start_response ):
templateLoader = jinja2.FileSystemLoader( searchpath="./" )
env = jinja2.Environment( loader=templateLoader )
template = env.get_template( 'main.html' )
template = template.render()
start_response("200 OK", [( "Content-Type", "text/html" )])
yield(template.encode( "utf8" ))
httpd = make_server('localhost', 8051, application)
httpd.serve_forever()
</code></pre>
<p>The top of main.html looks like:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chimera Quest</title>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="./main.css" />
<script type="text/javascript" src="./main.js"></script>
</head>
</code></pre>
<p>I've tried replacing "./main.css" with "/main.css" and "main.css".</p>
<p>My browser's console reads:</p>
<pre><code>Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8051/main.css".
</code></pre>
<p>Does anyone have see anything here? I'm totally out of ideas.</p>
| 3 | 2016-08-25T05:43:04Z | 39,137,725 | <p>If you are not using a WSGI server that also provides support for hosting static files, such as mod_wsgi with Apache, the best thing to do is to use a WSGI middleware to handle serving up static files. The main such WSGI middleware people use is called Whitenoise.</p>
<ul>
<li><a href="https://pypi.python.org/pypi/whitenoise" rel="nofollow">https://pypi.python.org/pypi/whitenoise</a></li>
</ul>
| 2 | 2016-08-25T06:01:54Z | [
"python",
"html",
"css",
"jinja2",
"wsgi"
] |
Map to List error: Series object not callable | 39,137,506 | <pre><code>from nsepy import get_history
from datetime import date
import datetime
import pandas as pd
import numpy as np
file = r'C:\Users\Raspberry-Pi\Desktop\Desktop\List.xlsx'
list = pd.read_excel(file)
list = list['SYMBOL']
start = date.today()-datetime.timedelta(days = 10)
end = date.today()
symb = get_history(symbol='INFY',start = start,end = end)
h = symb.tail(3).High.tolist()
l = symb.tail(3).Low.tolist()
print(type(h))
print(type(l))
x = map(lambda a,b:a-b,h,l)
print(type(x))
x = list(x)
</code></pre>
<p>I am getting error: </p>
<blockquote>
<p>series object not callable</p>
</blockquote>
<p>and its pointing to <code>x = list(x)</code> line.</p>
| 3 | 2016-08-25T05:43:46Z | 39,137,601 | <p>But I think you can omit <code>map</code> and use simple subtract and then convert to <code>list</code>:</p>
<pre><code>symb = get_history(symbol='INFY',start = start,end = end)
print ((symb.tail(3).High - symb.tail(3).Low).tolist())
</code></pre>
<p>Also don't use variable <code>list</code> (reserved word in python) rather <code>L</code> (or something else):</p>
<pre><code>L = pd.read_excel(file)
L = L['SYMBOL']
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
symb = pd.DataFrame({'High':[8,9,7,5,3,4],'Low':[1,2,3,1,0,1]})
print (symb)
High Low
0 8 1
1 9 2
2 7 3
3 5 1
4 3 0
5 4 1
print ((symb.tail(3).High - symb.tail(3).Low).tolist())
[4, 3, 3]
</code></pre>
<p>EDIT:</p>
<p>I try simulate problem:</p>
<pre><code>list = pd.DataFrame({'SYMBOL':['sss old','dd','old']})
print (list)
SYMBOL
0 sss old
1 dd
2 old
list = list['SYMBOL']
print (list)
0 sss old
1 dd
2 old
Name: SYMBOL, dtype: object
print (type(list))
<class 'pandas.core.series.Series'>
x = [1,2,3]
#list is Series, not function
x = list(x)
print (x)
TypeError: 'Series' object is not callable
</code></pre>
<hr>
<p>If change <code>list</code> to <code>L</code>, is important reopen python console, because still same error.</p>
<p>So this works perfectly:</p>
<pre><code>df = pd.DataFrame({'SYMBOL':['sss old','dd','old']})
print (df)
SYMBOL
0 sss old
1 dd
2 old
L = df['SYMBOL']
print (L)
0 sss old
1 dd
2 old
Name: SYMBOL, dtype: object
x = [1,2,3]
x = list(x)
print (x)
[1, 2, 3]
</code></pre>
| 2 | 2016-08-25T05:52:02Z | [
"python",
"list",
"pandas",
"dictionary",
"dataframe"
] |
Map to List error: Series object not callable | 39,137,506 | <pre><code>from nsepy import get_history
from datetime import date
import datetime
import pandas as pd
import numpy as np
file = r'C:\Users\Raspberry-Pi\Desktop\Desktop\List.xlsx'
list = pd.read_excel(file)
list = list['SYMBOL']
start = date.today()-datetime.timedelta(days = 10)
end = date.today()
symb = get_history(symbol='INFY',start = start,end = end)
h = symb.tail(3).High.tolist()
l = symb.tail(3).Low.tolist()
print(type(h))
print(type(l))
x = map(lambda a,b:a-b,h,l)
print(type(x))
x = list(x)
</code></pre>
<p>I am getting error: </p>
<blockquote>
<p>series object not callable</p>
</blockquote>
<p>and its pointing to <code>x = list(x)</code> line.</p>
| 3 | 2016-08-25T05:43:46Z | 39,137,723 | <p>The problem is that you have reassigned reserve word </p>
<pre><code>list = pd.read_excel(file)
list = list['SYMBOL']
</code></pre>
<p>hence list here is just a list of <code>['S', 'Y', 'M', 'B'..]</code>. Use another name for this definition the program will work fine</p>
| 0 | 2016-08-25T06:01:48Z | [
"python",
"list",
"pandas",
"dictionary",
"dataframe"
] |
Map to List error: Series object not callable | 39,137,506 | <pre><code>from nsepy import get_history
from datetime import date
import datetime
import pandas as pd
import numpy as np
file = r'C:\Users\Raspberry-Pi\Desktop\Desktop\List.xlsx'
list = pd.read_excel(file)
list = list['SYMBOL']
start = date.today()-datetime.timedelta(days = 10)
end = date.today()
symb = get_history(symbol='INFY',start = start,end = end)
h = symb.tail(3).High.tolist()
l = symb.tail(3).Low.tolist()
print(type(h))
print(type(l))
x = map(lambda a,b:a-b,h,l)
print(type(x))
x = list(x)
</code></pre>
<p>I am getting error: </p>
<blockquote>
<p>series object not callable</p>
</blockquote>
<p>and its pointing to <code>x = list(x)</code> line.</p>
| 3 | 2016-08-25T05:43:46Z | 39,138,151 | <p><code>list(x)</code> normally means turn <code>x</code> into a <code>list</code> object. It's a function that creates a list object. But near the top you redefined <code>list</code>:</p>
<pre><code>list = pd.read_excel(file)
</code></pre>
<p>Now <code>list</code> is now a pandas <code>series</code> object (as the error message says), and it does not function as a function, i.e. it is not <code>callable</code>, it cannot be used with <code>()</code>.</p>
<p>Use a different name for this object. Use a silly name like <code>foo</code> if you can't think of a better descriptor.</p>
| 2 | 2016-08-25T06:29:29Z | [
"python",
"list",
"pandas",
"dictionary",
"dataframe"
] |
Installing PyMongo and bottle in cloud9 IDE | 39,137,507 | <p>How to install PyMongo and bottle in cloud9 IDE?</p>
| 0 | 2016-08-25T05:44:01Z | 39,144,674 | <p>The best method to install PyMongo and Bottle in Cloud9 is via <strong>Python-pip</strong>. Get pip first. Open your C9 terminal and run the following commands:</p>
<pre><code>sudo apt-get install python-pip
</code></pre>
<p>After pip is installed you can get PyMongo and Bottle by running the following commands:</p>
<pre><code>sudo pip install pymongo
sudo pip install bottle
</code></pre>
<p>A tip, while specifying the localhost url enter 0.0.0.0 instead of localhost on your C9 machine. For example in your server file use,</p>
<pre><code>bottle.run(host='0.0.0.0', port=8080)
</code></pre>
| 1 | 2016-08-25T11:56:54Z | [
"python",
"mongodb",
"bottle",
"cloud9-ide"
] |
How do I set up Scrapy to deal with a captcha | 39,137,559 | <p>I'm trying to scrape a site that requires the user to enter the search value and a captcha. I've got an optical character recognition (OCR) routine for the captcha that succeeds about 33% of the time. Since the captchas are always alphabetic text, I want to reload the captcha if the OCR function returns non-alphabetic characters. Once I have a text "word", I want to submit the search form. </p>
<p>The results come back in the same page, with the form ready for a new search and a new captcha. So I need to rinse and repeat until I've exhausted my search terms.</p>
<p>Here's the top-level algorithm:</p>
<ol>
<li>Load page initially</li>
<li>Download the captcha image, run it through the OCR </li>
<li>If the OCR doesn't come back with a text-only result, refresh the captcha and repeat this step</li>
<li>Submit the query form in the page with search term and captcha</li>
<li>Check the response to see whether the captcha was correct</li>
<li>If it was correct, scrape the data </li>
<li>Go to 2</li>
</ol>
<p>I've tried using a pipeline for getting the captcha, but then I don't have the value for the form submission. If I just fetch the image without going through the framework, using urllib or something, then the cookie with the session is not submitted, so the captcha validation on the server fails. </p>
<p>What's the ideal Scrapy way of doing this? </p>
| 2 | 2016-08-25T05:48:28Z | 39,140,393 | <p>It's a really deep topic with a bunch of solutions. But if you want to apply the logic you've defined in your post you can use scrapy <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html" rel="nofollow">Downloader Middlewares</a>.</p>
<p>Something like:</p>
<pre><code>class CaptchaMiddleware(object):
max_retries = 5
def process_response(request, response, spider):
if not request.meta.get('solve_captcha', False):
return response # only solve requests that are marked with meta key
catpcha = find_catpcha(response)
if not captcha: # it might not have captcha at all!
return response
solved = solve_captcha(captcha)
if solved:
response.meta['catpcha'] = captcha
response.meta['solved_catpcha'] = solved
return response
else:
# retry page for new captcha
# prevent endless loop
if request.meta.get('catpcha_retries', 0) == 5:
logging.warning('max retries for captcha reached for {}'.format(request.url))
raise IgnoreRequest
request.meta['dont_filter'] = True
request.meta['captcha_retries'] = request.meta.get('captcha_retries', 0) + 1
return request
</code></pre>
<p>This example will intercept every response and try to solve the captcha. If failed it will retry the page for new captcha, if successful it will add some meta keys to response with solved captcha values.<br>
In your spider you would use it like this:</p>
<pre><code>class MySpider(scrapy.Spider):
def parse(self, response):
url = ''# url that requires captcha
yield Request(url, callback=self.parse_captchad, meta={'solve_captcha': True},
errback=self.parse_fail)
def parse_captchad(self, response):
solved = response['solved']
# do stuff
def parse_fail(self, response):
# failed to retrieve captcha in 5 tries :(
# do stuff
</code></pre>
| 2 | 2016-08-25T08:34:42Z | [
"python",
"web-scraping",
"scrapy",
"captcha"
] |
Renaming file name by incrementing them | 39,137,574 | <p>I would like to rename a list of pictures in the same folder(For e.g <code>001.jpg</code> to <code>020.jpg</code> , <code>002.jpg</code> to <code>021.jpg</code> and increment).I was thinking of using Python. Recommendations?</p>
| -4 | 2016-08-25T05:49:33Z | 39,137,621 | <p>Refer <a href="https://docs.python.org/2/library/os.html" rel="nofollow">os</a> library. You'll get all what you need. You have to use <code>rename</code> method to rename the file.</p>
<p>Below is the sample code to rename all the files in the directory to <code>0-N.jpg</code>.</p>
<pre><code>>>> import os
>>> for i, f in enumerate(os.listdir(".")):
... f_new = '{}.jpg'.format(i)
... os.rename(f, f_new)
... print '{}.'.format(i), f, '->', f_new
0. file1.jpg -> 0.jpg
1. file2.jpg -> 1.jpg
2. file3.jpg -> 2.jpg
3. file4.jpg -> 3.jpg
</code></pre>
| 1 | 2016-08-25T05:53:40Z | [
"python"
] |
Renaming file name by incrementing them | 39,137,574 | <p>I would like to rename a list of pictures in the same folder(For e.g <code>001.jpg</code> to <code>020.jpg</code> , <code>002.jpg</code> to <code>021.jpg</code> and increment).I was thinking of using Python. Recommendations?</p>
| -4 | 2016-08-25T05:49:33Z | 39,137,694 | <pre><code>import os, sys
files = os.listdir()
counter = 0
for file in files:
if file[-4:] == '.jpg':
os.rename(file, "{0}.jpg".format(counter))
counter += 1
</code></pre>
| 0 | 2016-08-25T05:59:32Z | [
"python"
] |
How to deal with repeated letters in arabic | 39,137,851 | <p>I want to normalize arabic string by replacing repeated characters with only one character. For example: the word </p>
<pre><code> رااااائع
</code></pre>
<p>will be normalized as </p>
<pre><code>رائع
</code></pre>
<p>I found a regular expression suitable for english (python):</p>
<pre><code>s="I loooooooooooooooooove you"
s = re.sub(r'(.)\1+', r'\1', s) // s= "I love you"
</code></pre>
<p>But, this regular expression does not work for arabic strings. I don't undertand the cause. I'm wondering if anyone could help me and thanks in advance. </p>
| 0 | 2016-08-25T06:09:49Z | 39,138,200 | <p>Try the following:</p>
<pre><code>import itertools
string = u"رااااائع"
''.join(char for char, _ in itertools.groupby(string))
</code></pre>
<p>I can't test it with arabic but it works with normal strings</p>
<p>reference: <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby</a></p>
| 0 | 2016-08-25T06:32:09Z | [
"python",
"arabic"
] |
How to deal with repeated letters in arabic | 39,137,851 | <p>I want to normalize arabic string by replacing repeated characters with only one character. For example: the word </p>
<pre><code> رااااائع
</code></pre>
<p>will be normalized as </p>
<pre><code>رائع
</code></pre>
<p>I found a regular expression suitable for english (python):</p>
<pre><code>s="I loooooooooooooooooove you"
s = re.sub(r'(.)\1+', r'\1', s) // s= "I love you"
</code></pre>
<p>But, this regular expression does not work for arabic strings. I don't undertand the cause. I'm wondering if anyone could help me and thanks in advance. </p>
| 0 | 2016-08-25T06:09:49Z | 39,140,438 | <p>Now, I want to do normalization for each line in a file.</p>
<pre><code>mon_fichier = open("./file.txt", "r")
my_file = open("./normalisation/file_norm.txt", "w")
contenu = mon_fichier.read()
liste = contenu.split('\n')
for var in liste:
v= var.encode('utf-8')
s ="".join(c for c, _ in itertools.groupby(v))
a=s.encode('utf-8')
my_file.write(a +"\n")
</code></pre>
<p>But, I have the following error:</p>
<pre><code>v= var.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 0: ordinal not in range(128)
</code></pre>
| 0 | 2016-08-25T08:37:16Z | [
"python",
"arabic"
] |
How to deal with repeated letters in arabic | 39,137,851 | <p>I want to normalize arabic string by replacing repeated characters with only one character. For example: the word </p>
<pre><code> رااااائع
</code></pre>
<p>will be normalized as </p>
<pre><code>رائع
</code></pre>
<p>I found a regular expression suitable for english (python):</p>
<pre><code>s="I loooooooooooooooooove you"
s = re.sub(r'(.)\1+', r'\1', s) // s= "I love you"
</code></pre>
<p>But, this regular expression does not work for arabic strings. I don't undertand the cause. I'm wondering if anyone could help me and thanks in advance. </p>
| 0 | 2016-08-25T06:09:49Z | 39,140,580 | <p>You are converting a character that cannot be converted to utf-8.</p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position
0: ordinal not in range(128)</p>
</blockquote>
<p>I suggest you use either ignore or replace:</p>
<pre><code>v= var.encode('utf-8', 'ignore')
</code></pre>
<p>or:</p>
<pre><code>v= var.encode('utf-8', 'replace')
</code></pre>
<p><a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Reference</a></p>
| 0 | 2016-08-25T08:43:39Z | [
"python",
"arabic"
] |
How to deal with repeated letters in arabic | 39,137,851 | <p>I want to normalize arabic string by replacing repeated characters with only one character. For example: the word </p>
<pre><code> رااااائع
</code></pre>
<p>will be normalized as </p>
<pre><code>رائع
</code></pre>
<p>I found a regular expression suitable for english (python):</p>
<pre><code>s="I loooooooooooooooooove you"
s = re.sub(r'(.)\1+', r'\1', s) // s= "I love you"
</code></pre>
<p>But, this regular expression does not work for arabic strings. I don't undertand the cause. I'm wondering if anyone could help me and thanks in advance. </p>
| 0 | 2016-08-25T06:09:49Z | 39,140,877 | <p>You need to add this line to your code :
<code>from __future__ import unicode_literals</code></p>
<pre><code># encoding: utf-8
from __future__ import unicode_literals
import re
s="رااااائع"
s = re.sub(r'(.)\1+', r'\1', s)
print s
</code></pre>
<p>Out put :</p>
<pre><code>رائع
</code></pre>
| 1 | 2016-08-25T08:59:27Z | [
"python",
"arabic"
] |
How to deal with repeated letters in arabic | 39,137,851 | <p>I want to normalize arabic string by replacing repeated characters with only one character. For example: the word </p>
<pre><code> رااااائع
</code></pre>
<p>will be normalized as </p>
<pre><code>رائع
</code></pre>
<p>I found a regular expression suitable for english (python):</p>
<pre><code>s="I loooooooooooooooooove you"
s = re.sub(r'(.)\1+', r'\1', s) // s= "I love you"
</code></pre>
<p>But, this regular expression does not work for arabic strings. I don't undertand the cause. I'm wondering if anyone could help me and thanks in advance. </p>
| 0 | 2016-08-25T06:09:49Z | 39,142,114 | <p>the code that works for a string is the following:</p>
<pre><code>#!/usr/bin/python
# -*-coding:utf-8 -*
import re, string,sys
import itertools
my_file = open("./out.txt", "w")
ch= u"ÙØªØ§Ø¨ راااااائع جداااا"
s ="".join(c for c, _ in itertools.groupby(ch))
a=s.encode('utf-8')
my_file.write(a +"\n") // le fichier contient "ÙØªØ§Ø¨ رائع جدا"
</code></pre>
<p>When I want to do normalization for each line in a file, I use the following code:</p>
<pre><code>#!/usr/bin/python
# -*-coding:utf-8 -*
import re, string,sys
import itertools
mon_fichier = open("./file.txt", "r")
my_file = open("./file_norm.txt", "w")
contenu = mon_fichier.read()
liste = contenu.split('\n')
for var in liste:
v= var.encode('utf-8')
s ="".join(c for c, _ in itertools.groupby(v))
b= s.encode('utf-8')
my_file.write(b +"\n")
</code></pre>
<p>I have the following error: </p>
<pre><code>v = var.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
</code></pre>
<p>Here is a sample of my file:</p>
<pre><code>ÙØªØ§Ø¨ Ù
Ù
Ù
Ù
Ù
Ù
Ù
Ù
Ù
تاز جدااااااا
ÙØµÙØ© Ø´ÙÙØ© ٠راااااائعة
Ù
ذذذذذذÙÙ
</code></pre>
| 0 | 2016-08-25T09:57:34Z | [
"python",
"arabic"
] |
Calling functions from external python file throws 500 error | 39,137,874 | <p>I am trying to call a function from another python file. I have imported that function. When i call the function externally it works as expected.</p>
<p>But when i try to call the function before returning a render_template or a redirect , i get a 500 error.
I know i am doing something wrong but i am not sure what. Any kind of help will be highly appreciated.</p>
<pre><code>from flask import Flask, render_template, request, redirect, url_for
from content_man import Content,Page_Content
from url_trigger import trigger
TEST_TOPIC = Content()
PAGE_TOPIC = Page_Content()
app = Flask(__name__)
@app.route('/',methods=["GET","POST"])
def homepage():
return render_template("main.html")
@app.route('/dashboard/',methods=["GET","POST"])
def dashboard():
return render_template("dashboard.html", TEST_TOPIC=TEST_TOPIC)
@app.route('/test/', methods=["GET","POST"])
def test():
if request.method == "POST":
selected_list = request.form.getlist("to_run")
print (selected_list)
return redirect(url_for('trigger',selected_list=selected_list))
else:
return render_template("test.html", PAGE_TOPIC=PAGE_TOPIC)
@app.route('/trigger/', methods=["GET","POST"])
def trigger():
data = request.args.getlist('selected_list')
t = trigger(data)
return "hey"
if __name__ == "__main__":
app.run()
</code></pre>
<p>The error is in @app.route('/trigger/', methods=["GET","POST"]) where i am trying to call the function trigger.</p>
<p>My url_trigger python file contains the below simple definition:</p>
<pre><code>def trigger(my_list=[], *args):
for i in my_list:
print (i)
</code></pre>
<p>The HTML file for the page test is as:</p>
<pre><code><div class="container">
<form method="post" action = "{{ url_for('test') }}">
{% for row_index in range(PAGE_TOPIC['Critical BP']|count) %}
<div class="checkbox">
<label><input type="checkbox" name="to_run" value="{{ PAGE_TOPIC['Critical BP'][row_index] }}">{{ PAGE_TOPIC['Critical BP'][row_index] }}</label>
</div>
{% endfor %}
<div>
<label><input type="submit" /></label>
</div>
</form>
</div>
</code></pre>
| -1 | 2016-08-25T06:11:24Z | 39,138,382 | <p>You import a function named <code>trigger</code>, but you also a define a function named <code>trigger</code> in the module where you do the import. When <code>trigger</code> calls <code>trigger</code>, it is calling itself, and it accepts no arguments. You need to rename one of the functions, or do the import as <code>import url_trigger</code> and then refer to the imported function as <code>url_trigger.trigger</code>.</p>
| 1 | 2016-08-25T06:43:17Z | [
"python",
"flask"
] |
Iterating through capture fields in a Rust regex | 39,137,905 | <p>I'm playing around with the frowns parser available from http:// frowns.sourceforge.net, a parser that tokenizes SMILES standard chemical formula strings. Specifically I'm trying to port it to Rust.</p>
<p>The original regex for an "atom" token in the parser looks like this (Python):</p>
<pre><code>element_symbols_pattern = \
r"C[laroudsemf]?|Os?|N[eaibdpos]?|S[icernbmg]?|P[drmtboau]?|" \
r"H[eofgas]?|c|n|o|s|p|A[lrsgutcm]|B[eraik]?|Dy|E[urs]|F[erm]?|" \
r"G[aed]|I[nr]?|Kr?|L[iaur]|M[gnodt]|R[buhenaf]|T[icebmalh]|" \
r"U|V|W|Xe|Yb?|Z[nr]|\*"
atom_fields = [
"raw_atom",
"open_bracket",
"weight",
"element",
"chiral_count",
"chiral_named",
"chiral_symbols",
"hcount",
"positive_count",
"positive_symbols",
"negative_count",
"negative_symbols",
"error_1",
"error_2",
"close_bracket",
"error_3",
]
atom = re.compile(r"""
(?P<raw_atom>Cl|Br|[cnospBCNOFPSI]) | # "raw" means outside of brackets
(
(?P<open_bracket>\[) # Start bracket
(?P<weight>\d+)? # Atomic weight (optional)
( # valid term or error
( # valid term
(?P<element>""" + element_symbols_pattern + r""") # element or aromatic
( # Chirality can be
(?P<chiral_count>@\d+) | # @1 @2 @3 ...
(?P<chiral_named> # or
@TH[12] | # @TA1 @TA2
@AL[12] | # @AL1 @AL2
@SP[123] | # @SP1 @SP2 @SP3
@TB(1[0-9]?|20?|[3-9]) | # @TB{1-20}
@OH(1[0-9]?|2[0-9]?|30?|[4-9])) | # @OH{1-30}
(?P<chiral_symbols>@+) # or @@@@@@@...
)? # and chirality is optional
(?P<hcount>H\d*)? # Optional hydrogen count
( # Charges can be
(?P<positive_count>\+\d+) | # +<number>
(?P<positive_symbols>\++) | # +++... This includes the single '+'
(?P<negative_count>-\d+) | # -<number>
(?P<negative_symbols>-+) # ---... including a single '-'
)? # and are optional
(?P<error_1>[^\]]+)? # If there's anything left, it's an error
) | ( # End of parsing stuff in []s, except
(?P<error_2>[^\]]*) # If there was an error, we get here
))
((?P<close_bracket>\])| # End bracket
(?P<error_3>$)) # unexpectedly reached end of string
)
""", re.X)
</code></pre>
<p>The field list is used to improve the reportability of the regex parser, as well as track parsing errors.</p>
<p>I wrote <a href="https://gitlab.com/araster/frowns_regex" rel="nofollow">something that compiles</a> and parses tokens without brackets properly, but something about the inclusion of brackets (such as <code>[S]</code> instead of <code>S</code>) breaks it. So I've narrowed it down with comments:</p>
<pre><code>extern crate regex;
use regex::Regex;
fn main() {
let atom_fields: Vec<&'static str> = vec![
"raw_atom",
"open_bracket",
"weight",
"element",
"chiral_count",
"chiral_named",
"chiral_symbols",
"hcount",
"positive_count",
"positive_symbols",
"negative_count",
"negative_symbols",
"error_1",
"error_2",
"close_bracket",
"error_3"
];
const EL_SYMBOLS: &'static str = r#"(?P<element>S?|\*")"#;
let atom_re_str: &String = &String::from(vec![
// r"(?P<raw_atom>Cl|Br|[cnospBCNOFPSI])|", // "raw" means outside of brackets
r"(",
r"(?P<open_bracket>\[)", // Start bracket
// r"(?P<weight>\d+)?", // Atomic weight (optional)
r"(", // valid term or error
r"(", // valid term
&EL_SYMBOLS, // element or aromatic
// r"(", // Chirality can be
// r"(?P<chiral_count>@\d+)|", // @1 @2 @3 ...
// r"(?P<chiral_named>", // or
// r"@TH[12]|", // @TA1 @TA2
// r"@AL[12]|", // @AL1 @AL2
// r"@SP[123]|", // @SP1 @SP2 @SP3
// r"@TB(1[0-9]?|20?|[3-9])|", // @TB{1-20}
// r"@OH(1[0-9]?|2[0-9]?|30?|[4-9]))|", // @OH{1-30}
// r"(?P<chiral_symbols>@+)", // or @@@@....,
// r")?", // and chirality is optional
// r"(?P<hcount>H\d*)?", // Optional hydrogen count
// r"(", // Charges can be
// r"(?P<positive_count>\+\d+)|", // +<number>
// r"(?P<positive_symbols>\++)|", // +++...including a single '+'
// r"(?P<negative_count>-\d+)|", // -<number>
// r"(?P<negative_symbols>-+)", // ---... including a single '-'
// r")?", // and are optional
// r"(?P<error_1>[^\]]+)?", // anything left is an error
r")", // End of stuff in []s, except
r"|((?P<error_2>[^\]]*)", // If other error, we get here
r"))",
r"((?P<close_bracket>\])|", // End bracket
r"(?P<error_3>$)))"].join("")); // unexpected end of string
println!("generated regex: {}", &atom_re_str);
let atom_re = Regex::new(&atom_re_str).unwrap();
for cur_char in "[S]".chars() {
let cur_string = cur_char.to_string();
println!("cur string: {}", &cur_string);
let captures = atom_re.captures(&cur_string.as_str()).unwrap();
// if captures.name("atom").is_some() {
// for cur_field in &atom_fields {
// let field_capture = captures.name(cur_field);
// if cur_field.contains("error") {
// if *cur_field == "error_3" {
// // TODO replace me with a real error
// println!("current char: {:?}", &cur_char);
// panic!("Missing a close bracket (]). Looks like: {}.",
// field_capture.unwrap());
// } else {
// panic!("I don't recognize the character. Looks like: {}.",
// field_capture.unwrap());
// }
// } else {
// println!("ok! matched {:?}", &cur_char);
// }
// }
// }
}
}
</code></pre>
<p>--</p>
<p>You can see that the generated Rust regex works in Debuggex:</p>
<pre><code>((?P<open_bracket>\[)(((?P<element>S?|\*"))|((?P<error_2>[^\]]*)))((?P<close_bracket>\])|(?P<error_3>$)))
</code></pre>
<p><img src="http://debuggex.com/i/7j75Y2F1ph1v9jfL.png" alt="Regular expression visualization"> </p>
<p>(<a href="http://debuggex.com/r/7j75Y2F1ph1v9jfL" rel="nofollow">http://debuggex.com/r/7j75Y2F1ph1v9jfL</a>)</p>
<p>If you run the example (<a href="https://gitlab.com/araster/frowns_regex" rel="nofollow">https://gitlab.com/araster/frowns_regex</a>), you'll see that the open bracket parses correctly, but the <code>.captures().unwrap()</code> dies on the next character 'S'. If I use the complete expression I can parse all kinds of things from the frowns test file, as long as they don't have brackets.</p>
<p>What am I doing wrong?</p>
| 3 | 2016-08-25T06:13:08Z | 39,138,538 | <p>You are iterating on each character of your input string and trying to match the regex on a string composed of a single character. However, this regex is not designed to match individual characters. Indeed, the regex will match <code>[S]</code> as a whole.</p>
<p>If you want to be able to find multiple matches in a single string, use <a href="https://doc.rust-lang.org/regex/regex/struct.Regex.html#method.captures_iter"><code>captures_iter</code></a> instead of <code>captures</code> to iterate on all matches and their respective captures (each match will be a formula, the regex will skip text that doesn't match a formula).</p>
<pre><code>for captures in atom_re.captures_iter("[S]") {
// check the captures of each match
}
</code></pre>
<p>If you only want to find the first match in a string, then use <code>captures</code> on the whole string, rather than on each individual character.</p>
| 5 | 2016-08-25T06:52:35Z | [
"python",
"regex",
"parsing",
"rust"
] |
build dynamic filters in sqlalchemy python | 39,137,911 | <p>I need to generate/build sqlalchemy query dynamically using dynamic columns and their values.</p>
<p>Example -
I have a table in SQL called "Convo" and it has columns like - UserID, ConvoID, ContactID.</p>
<p>I need to get rows based on the below criteria.</p>
<pre><code>criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
</code></pre>
<p>I have used "Baked query" logic for this. But Some how I am not able to run this query successfully.</p>
<p>Below is the my code.</p>
<pre><code>criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
baked_query = bakery(lambda session: session.query(tablename))
for key1 in condition:
baked_query += lambda q: q.filter(tablename.key1 == condition[key1])
result = baked_query(self.session).all()
</code></pre>
<p>I am getting error as - </p>
<pre><code>AttributeError: type object 'Convo' has no attribute 'key1'
</code></pre>
<p>Please help me out with this</p>
| 1 | 2016-08-25T06:13:27Z | 39,138,179 | <pre><code>criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
query = session.query(tablename)
for _filter, value in criteria:
query = query.filter(getattr(tablename, _filter) == value)
result = query.all()
</code></pre>
| 1 | 2016-08-25T06:31:02Z | [
"python",
"sqlalchemy"
] |
build dynamic filters in sqlalchemy python | 39,137,911 | <p>I need to generate/build sqlalchemy query dynamically using dynamic columns and their values.</p>
<p>Example -
I have a table in SQL called "Convo" and it has columns like - UserID, ConvoID, ContactID.</p>
<p>I need to get rows based on the below criteria.</p>
<pre><code>criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
</code></pre>
<p>I have used "Baked query" logic for this. But Some how I am not able to run this query successfully.</p>
<p>Below is the my code.</p>
<pre><code>criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
baked_query = bakery(lambda session: session.query(tablename))
for key1 in condition:
baked_query += lambda q: q.filter(tablename.key1 == condition[key1])
result = baked_query(self.session).all()
</code></pre>
<p>I am getting error as - </p>
<pre><code>AttributeError: type object 'Convo' has no attribute 'key1'
</code></pre>
<p>Please help me out with this</p>
| 1 | 2016-08-25T06:13:27Z | 39,138,227 | <p>If you're using dynamic keys and "simple" equality checks, the <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html?highlight=filter_by#sqlalchemy.orm.query.Query.filter_by" rel="nofollow">filter_by</a> method might be more convenient, as it takes keyword arguments that match you property names and assembles that into where clause.</p>
<p>So your iterative query construction could look like that:</p>
<pre><code>baked_query = bakery(lambda session: session.query(tablename))
for key, value in condition.items():
baked_query += lambda q: q.filter_by(key=value)
</code></pre>
<p>Plus, since <code>filter_by</code> takes mulitple keyword arguments, you can probably simplify your query construction to a single <code>filter_by</code> invocation:</p>
<pre><code>baked_query = bakery(lambda session: session.query(tablename))
baked_query += lambda q: q.filter_by(**condition)
</code></pre>
<p>All of the above obviously assuming that your <code>condition</code> variable refers to a dictionary.</p>
| 1 | 2016-08-25T06:33:35Z | [
"python",
"sqlalchemy"
] |
Dataframe SMA Calculation | 39,138,299 | <p>Is there any simple tool/lib that can help me easily calculate the sma(..) of dataframe ?</p>
<pre><code> GLD SMA(5)
Date
2005-01-03 00:00:00+00:00 43.020000 Nan
2005-01-04 00:00:00+00:00 42.740002 Nan
2005-01-05 00:00:00+00:00 42.669998 Nan
2005-01-06 00:00:00+00:00 42.150002 Nan
2005-01-07 00:00:00+00:00 41.840000 ..
2005-01-10 00:00:00+00:00 41.950001 ..
2005-01-11 00:00:00+00:00 42.209999 ..
2005-01-12 00:00:00+00:00 42.599998 ..
2005-01-13 00:00:00+00:00 42.599998 ..
2005-01-14 00:00:00+00:00 42.320000 ..
</code></pre>
| 2 | 2016-08-25T06:38:23Z | 39,138,436 | <pre><code>df['SMA(5)'] = df.GLD.rolling(5).mean()
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Li6Ke.png" rel="nofollow"><img src="http://i.stack.imgur.com/Li6Ke.png" alt="enter image description here"></a></p>
| 3 | 2016-08-25T06:46:46Z | [
"python",
"pandas"
] |
How to protect some files from the Jinja template processor? | 39,138,386 | <p>I am using cookiecutter to create a tornado project, using <a href="https://github.com/luizalabs/tornado-cookiecutter" rel="nofollow">this template</a> (it has several bugs, so you'll probably won't be able to use it out of the box). I have hit a problem which I do not know how to solve:</p>
<pre><code>jinja2.exceptions.TemplateSyntaxError: unexpected char '\\' at 124272
File "./{{cookiecutter.project_slug}}/static/swagger/lib/jsoneditor.min.js", line 10
</code></pre>
<p>I am not sure, but I have the impression that <code>cookiecutter</code> is trying to Jinja-process the <code>jsoneditor.min.js</code>, which is not supposed to happen, since the "templating" in that file is not supposed to be processed by <code>cookiecutter</code>, it just happens to include the same escape characters that <code>Jinja</code> is using.</p>
<p>Is it possible to tell <code>cookiecutter</code> not to process files inside a certain directory? This is probably a matter of properly setting up the <code>cookiecutter</code> template, but not sure how this can be specified.</p>
| 0 | 2016-08-25T06:43:23Z | 39,151,217 | <p>By default cookiecutter will try to process every file as a jinja template which produces wrong results if you have something that looks like a jinja template but is only supposed to be taken literal. Starting with cookiecutter 1.1 one can tell cookiecutter to only copy some files without interpreting them as jinja template (<a href="http://cookiecutter.readthedocs.io/en/latest/advanced/copy_without_render.html" rel="nofollow">documentation</a>). </p>
<p>To do that you have to add a <code>_copy_without_render</code> key in the cookiecutter config file (<code>cookiecutter.json</code>). It takes a list of regular expressions. If a filename matches the regular expressions it will be copied and not processed as a jinja template.</p>
<p>Example</p>
<pre><code>{
"project_slug": "sample",
"_copy_without_render": [
"*.js",
"not_rendered_dir/*",
"rendered_dir/not_rendered_file.ini"
]
}
</code></pre>
<p>This will not process any javascript files (files which end with <code>.js</code>), any files that are in the <code>not_rendered_dir</code> and not the <code>not_rendered_file.ini</code> in the <code>rendered_dir</code>. They will only get copied.</p>
| 1 | 2016-08-25T17:19:16Z | [
"python",
"cookiecutter"
] |
Increment a char given a sequence | 39,138,533 | <p>Given a sequence of characters, return next following in alphabetical order. </p>
<p><code>Example: given 'A' it should return 'B', 'Z' -> 'AA', 'ZYZ' -> 'ZZA'</code> etc. </p>
<p>One relevant reference using modulo and math i have found <a href="http://stackoverflow.com/a/4583231/1256112">is in c#</a>.
Instead of converting it into python, i came up with my own solution.</p>
<p>What would be a more effective algorithmic approach than the one below?</p>
<pre><code>import string
def increment_excel(s=''):
"""
A->B, Z->AA, AZ->BA, KZZ->LAA
"""
def wrapped(s):
if not s:
return string.uppercase[0]
ind = string.uppercase.index(s[-1])
if ind < len(string.uppercase) - 1:
return s[:-1] + string.uppercase[ind + 1]
return wrapped(s[:-1]) + string.uppercase[0]
return wrapped(s.upper().replace(' ',''))
increment_excel('TRYME') # -> 'TRYMF'
increment_excel('TRY ZZ') # -> 'TRZAA'
increment_excel('ABCC') # -> 'ABCD'
increment_excel('ZZ Z') # -> 'AAAA'
</code></pre>
| 0 | 2016-08-25T06:52:11Z | 39,138,668 | <p>Here is the simple elegant recursive solution, but be careful when the number is divisible by 26. Before passing to function check if it divisible by 26. </p>
<pre><code>def convert(num,a):
if(num<=26):
a+=chr(64+num)
return a
a+=convert(int(num/26),a)
num=num%26
if(num>0):
a+=chr(64+num)
return a
n=input('Enter Number:')
if(n%26==0):
qt=(n/26)-1
if(qt>26):
k=convert(qt,'')
else:
k=chr(64+qt)
k+='z'
else:
res=convert(n,'')
</code></pre>
| 0 | 2016-08-25T07:00:02Z | [
"python",
"string",
"algorithm"
] |
Increment a char given a sequence | 39,138,533 | <p>Given a sequence of characters, return next following in alphabetical order. </p>
<p><code>Example: given 'A' it should return 'B', 'Z' -> 'AA', 'ZYZ' -> 'ZZA'</code> etc. </p>
<p>One relevant reference using modulo and math i have found <a href="http://stackoverflow.com/a/4583231/1256112">is in c#</a>.
Instead of converting it into python, i came up with my own solution.</p>
<p>What would be a more effective algorithmic approach than the one below?</p>
<pre><code>import string
def increment_excel(s=''):
"""
A->B, Z->AA, AZ->BA, KZZ->LAA
"""
def wrapped(s):
if not s:
return string.uppercase[0]
ind = string.uppercase.index(s[-1])
if ind < len(string.uppercase) - 1:
return s[:-1] + string.uppercase[ind + 1]
return wrapped(s[:-1]) + string.uppercase[0]
return wrapped(s.upper().replace(' ',''))
increment_excel('TRYME') # -> 'TRYMF'
increment_excel('TRY ZZ') # -> 'TRZAA'
increment_excel('ABCC') # -> 'ABCD'
increment_excel('ZZ Z') # -> 'AAAA'
</code></pre>
| 0 | 2016-08-25T06:52:11Z | 39,139,733 | <p>Try:</p>
<pre><code>def increment_excel(s=''):
arr = list(s.upper().replace(' ', ''))
if arr:
arr.reverse()
n = 1
for i in range(len(arr)):
if ord(arr[i])+n <= ord('Z'):
arr[i] = chr(ord(arr[i]) + n)
n = 0
else:
arr[i] = 'A'
n = 1
if n == 1:
arr.append('A')
arr.reverse()
return ''.join(arr)
</code></pre>
| 1 | 2016-08-25T07:59:20Z | [
"python",
"string",
"algorithm"
] |
Increment a char given a sequence | 39,138,533 | <p>Given a sequence of characters, return next following in alphabetical order. </p>
<p><code>Example: given 'A' it should return 'B', 'Z' -> 'AA', 'ZYZ' -> 'ZZA'</code> etc. </p>
<p>One relevant reference using modulo and math i have found <a href="http://stackoverflow.com/a/4583231/1256112">is in c#</a>.
Instead of converting it into python, i came up with my own solution.</p>
<p>What would be a more effective algorithmic approach than the one below?</p>
<pre><code>import string
def increment_excel(s=''):
"""
A->B, Z->AA, AZ->BA, KZZ->LAA
"""
def wrapped(s):
if not s:
return string.uppercase[0]
ind = string.uppercase.index(s[-1])
if ind < len(string.uppercase) - 1:
return s[:-1] + string.uppercase[ind + 1]
return wrapped(s[:-1]) + string.uppercase[0]
return wrapped(s.upper().replace(' ',''))
increment_excel('TRYME') # -> 'TRYMF'
increment_excel('TRY ZZ') # -> 'TRZAA'
increment_excel('ABCC') # -> 'ABCD'
increment_excel('ZZ Z') # -> 'AAAA'
</code></pre>
| 0 | 2016-08-25T06:52:11Z | 39,152,192 | <p>Here's a solution which just uses string manipulation.</p>
<p>Leaving aside the normalization of the string (uppercase it, strip blanks), the function essentially finds the suffix consisting of an optional letter other than <kbd>Z</kbd> followed by any number of <kbd>Z</kbd>s (including none). The trailing <kbd>Z</kbd>s are all changed to <kbd>A</kbd>, while the last character before the <kbd>Z</kbd>s (if any) is incremented. Finally, an <kbd>A</kbd> is prepended if the string consists only of <kbd>Z</kbd>s.</p>
<pre><code>import re
import string
succ_tb = string.maketrans(string.uppercase,
string.uppercase[1:]+string.uppercase[0])
up_tb = string.maketrans(string.lowercase, string.uppercase)
suff_re = re.compile('(([A-Y]?)Z*)$')
def increment_excel(s):
return suff_re.sub(
lambda m: (('' if m.group(2) else 'A') +
m.group(1).translate(succ_tb)),
s.translate(up_tb, ' '))
</code></pre>
| 1 | 2016-08-25T18:16:20Z | [
"python",
"string",
"algorithm"
] |
Extract the data specified in brackets '[ ]' from a string message in python | 39,138,999 | <p>I want to extract fields from below Log message.</p>
<p>Example:</p>
<blockquote>
<p>Ignoring entry, Affected columns [column1:column2], reason[some reason], Details[some entry details]</p>
</blockquote>
<p>I need to extract the data specified in the brackets <code>[ ]</code> for "Affected columns,reason, Details"</p>
<p>What would be the efficient way to extract these fields in Python?</p>
<p><em>Note: I can modify the log message format if needed.</em></p>
| 1 | 2016-08-25T07:19:10Z | 39,139,293 | <p>If you are free to change the log format, it's easiest to use a common data format - I'd recommend JSON for such data. It is structured, but lightweight enough to write it even from custom bash scripts. The <a href="https://docs.python.org/3.5/library/json.html" rel="nofollow"><code>json</code> module</a> allows you to directly convert it to native python objects:</p>
<pre><code>import json # python has a default parser
# assume this is your log message
log_line = '{"Ignoring entry" : {"Affected columns": [1, 3], "reason" : "some reason", "Details": {}}}'
data = json.loads(log_line)
print("Columns to ignore:", data["Ignoring entry"]["Affected columns"])
</code></pre>
<hr>
<p>If you want to work with the current format, you'll have to work with <code>str</code> methods or the <code>re</code> module.</p>
<p>For example, you could do this:</p>
<pre><code>log_msg = "Ignoring entry, Affected columns [column1:column2], reason[some reason], Details[some entry details]"
def parse_log_line(log_line):
if log_line.startswith("Ignoring entry"):
log_data = {
for element in log_line.split(',')[1:]: # parse all elements but the header
key, value = element.partition('[')
if value[-1] != ']':
raise ValueError('Malformed Content. Expected %r to end with "]"' % element)
value = value[:-1]
log_data[key] = value
return log_data
raise ValueError('Unrecognized log line type')
</code></pre>
<p>Many parsing tasks are <strike>best</strike> compactly handled by the <a href="https://docs.python.org/3.5/library/re.html#module-re" rel="nofollow"><code>re</code> module</a>. It allows you to use regular expressions. They are very powerful, but difficult to maintain if you are not used to it. In your case, the following would work:</p>
<pre><code>log_data = {key: value for key, value in re.findall(',\s?(.+?)\s?\[(.+?)\]', log_line)}
</code></pre>
<p>The re works like this:</p>
<ul>
<li><code>,</code> a literal comma, separating your entries</li>
<li><code>\s*</code> an arbitrary sequence of whitespace after the comma, before the next element</li>
<li><code>(.+?)</code> any non-whitespace characters (the key, captured via <code>'()'</code>)</li>
<li><code>\s*</code> an arbitrary sequence of whitespace between key and value</li>
<li><code>\[</code> a literal <code>[</code></li>
<li><code>(.+?)</code> the <em>shortest</em> sequence of non-whitespace characters before the next element (the value, captured via <code>'()'</code>)</li>
<li><code>\]</code> a literal <code>]</code></li>
</ul>
<p>The symbols <code>*</code>, <code>+</code> and <code>?</code> mean "any", "more than one", and "as few as possible".</p>
| 2 | 2016-08-25T07:35:37Z | [
"python",
"python-3.x"
] |
Reading input file and processing it in flask | 39,139,009 | <p>I'm trying to write a simple flask program that will create a web page in which it receives a file (by uploading it), and then using that file's data and displaying a filtered part of it in my web page, I just cant seem to understand how to do that.</p>
<p>This is the code I used to upload the file, which worked fine.</p>
<pre><code>import os
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'C:/Users/ohadt/PycharmProjects/logFiles'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'log'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('read_uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
</code></pre>
<p>Then I tried writing the method for opening the file and reading the data from it, but I couldn't figure how to do that, could you please help me understand how to read the file content and presenting a filtered version of it on my site?
Thanks! </p>
| 0 | 2016-08-25T07:19:39Z | 39,140,025 | <p>You already saved it here </p>
<pre><code>file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
</code></pre>
<p>just open it up and read as you work with any other files, example:</p>
<pre><code>@app.route('/read_file', methods=['GET'])
def read_uploaded_file():
filename = secure_filename(request.args.get('filename'))
try:
if filename and allowed_filename(filename):
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as f:
return f.read()
except IOError:
pass
return "Unable to read file"
</code></pre>
<p>You need to carefully sanitize user input here, otherwise method could be used to read something unintended (like app source code for example). Best is just not grant user ability to read arbitrary files - for example when you save a file, store it's path in database with some token and give user just this token:</p>
<pre><code>filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
token = store_in_db(filepath)
return redirect(url_for('read_uploaded_file',
token=token))
</code></pre>
<p>Then accept a token, not a filename when you read a file:</p>
<pre><code>@app.route('/read_file', methods=['GET'])
def read_uploaded_file():
filepath = get_filepath(request.args.get('token'))
try:
if filepath and allowed_filepath(filepath):
with open(filepath) as f:
return f.read()
except IOError:
pass
return "Unable to read file"
</code></pre>
<p>Tokens need to be random, long, not guessable (uuid4 for example) - otherwise there will be a possibility to easily read other users files. Or you need to store relation between file and user in database and check it too. Finally, you need to control size of file uploads to prevent user from uploading huge files (<code>app.config['MAX_CONTENT_LENGTH']</code>) and control amount of info you read in memory when you display "filtered" file content (<code>f.read(max_allowed_size)</code>).</p>
| 1 | 2016-08-25T08:15:29Z | [
"python",
"flask"
] |
create step spark python, amazon hadoop | 39,139,057 | <p>I am creating a Spark step with Hadoop on Amazon, but I left thinking all the time. Not if it's because I'm bad code or sending bad judgment, but can not find a way out.</p>
<p>I pass code</p>
<pre><code>spark-submit --deploy-mode cluster --master yarn --num-executors 5 --executor-cores 5 --executor-memory 1g s3://URL-S3/scripts/test.py
</code></pre>
<p>Script:</p>
<pre><code>import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('TestSpark')
table.put_item(
Item={
'app_token': "1a",
'advertising_id': "1b",
}
)
</code></pre>
<p>I returned all the time</p>
<pre><code>16/08/25 07:06:22 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:23 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:24 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:25 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:26 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:27 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:28 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:29 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:30 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:31 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:32 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:33 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:34 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:35 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:36 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:37 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:38 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:39 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:40 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:41 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:42 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
</code></pre>
<p>Error Log: </p>
<pre><code>2016-08-25T07:30:14.769Z INFO Step created jobs:
2016-08-25T07:30:14.769Z WARN Step failed with exitCode 1 and took 1062 seconds
</code></pre>
<p>Thx!</p>
<p>Which it is already the error, but the module and install it before.</p>
<blockquote>
<p>ImportError: No module named boto3</p>
</blockquote>
| 0 | 2016-08-25T07:21:58Z | 39,139,433 | <p>You application is waiting for yarn resources. Goto resource manager URL and see if you enough resources and using right queue. If you look at yarn resourcemanager logs will know the reason.</p>
| 1 | 2016-08-25T07:43:27Z | [
"python",
"hadoop",
"hive",
"pyspark",
"amazon-emr"
] |
create step spark python, amazon hadoop | 39,139,057 | <p>I am creating a Spark step with Hadoop on Amazon, but I left thinking all the time. Not if it's because I'm bad code or sending bad judgment, but can not find a way out.</p>
<p>I pass code</p>
<pre><code>spark-submit --deploy-mode cluster --master yarn --num-executors 5 --executor-cores 5 --executor-memory 1g s3://URL-S3/scripts/test.py
</code></pre>
<p>Script:</p>
<pre><code>import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('TestSpark')
table.put_item(
Item={
'app_token': "1a",
'advertising_id': "1b",
}
)
</code></pre>
<p>I returned all the time</p>
<pre><code>16/08/25 07:06:22 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:23 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:24 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:25 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:26 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:27 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:28 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:29 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:30 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:31 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:32 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:33 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:34 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:35 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:36 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:37 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:38 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:39 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:40 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:41 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:42 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
</code></pre>
<p>Error Log: </p>
<pre><code>2016-08-25T07:30:14.769Z INFO Step created jobs:
2016-08-25T07:30:14.769Z WARN Step failed with exitCode 1 and took 1062 seconds
</code></pre>
<p>Thx!</p>
<p>Which it is already the error, but the module and install it before.</p>
<blockquote>
<p>ImportError: No module named boto3</p>
</blockquote>
| 0 | 2016-08-25T07:21:58Z | 39,140,724 | <p>I don't work on Amazon EMR, but in Hadoop this happens when your YARN is waiting for resources for too long.</p>
<p>The resource negotiator couldn't allocate the required resources, try to reduce the resources required by your code. Also check the logs.</p>
<p>Read through: <a href="https://spark.apache.org/docs/1.2.0/running-on-yarn.html" rel="nofollow">this</a></p>
<p>Also check the status of YARN,</p>
<pre><code>sudo service hadoop-yarn-nodemanager status
sudo service hadoop-yarn-resourcemanager status
</code></pre>
| 1 | 2016-08-25T08:52:04Z | [
"python",
"hadoop",
"hive",
"pyspark",
"amazon-emr"
] |
create step spark python, amazon hadoop | 39,139,057 | <p>I am creating a Spark step with Hadoop on Amazon, but I left thinking all the time. Not if it's because I'm bad code or sending bad judgment, but can not find a way out.</p>
<p>I pass code</p>
<pre><code>spark-submit --deploy-mode cluster --master yarn --num-executors 5 --executor-cores 5 --executor-memory 1g s3://URL-S3/scripts/test.py
</code></pre>
<p>Script:</p>
<pre><code>import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('TestSpark')
table.put_item(
Item={
'app_token': "1a",
'advertising_id': "1b",
}
)
</code></pre>
<p>I returned all the time</p>
<pre><code>16/08/25 07:06:22 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:23 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:24 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:25 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:26 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:27 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:28 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:29 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:30 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:31 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:32 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:33 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:34 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:35 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:36 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:37 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:38 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:39 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:40 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:41 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
16/08/25 07:06:42 INFO Client: Application report for application_1472106590712_0002 (state: ACCEPTED)
</code></pre>
<p>Error Log: </p>
<pre><code>2016-08-25T07:30:14.769Z INFO Step created jobs:
2016-08-25T07:30:14.769Z WARN Step failed with exitCode 1 and took 1062 seconds
</code></pre>
<p>Thx!</p>
<p>Which it is already the error, but the module and install it before.</p>
<blockquote>
<p>ImportError: No module named boto3</p>
</blockquote>
| 0 | 2016-08-25T07:21:58Z | 39,194,277 | <p>And locate the error.</p>
<p>Boto3 module was not installed, install it from console, but the steps do not work, because they would have to install it in all instances. So what I did was create another claster running a boostrap-action update python I installed the module boto3</p>
| 0 | 2016-08-28T18:03:44Z | [
"python",
"hadoop",
"hive",
"pyspark",
"amazon-emr"
] |
Running simple python script consinuously on Heroku | 39,139,165 | <p>I have simple python script which I would like to host it on Heroku and run it every 10 minutes using Heroku scheduler. So can someone explain me what should I type on the rake command at the scheduler and how I should change the Procfile of Heroku?</p>
| 1 | 2016-08-25T07:27:57Z | 39,170,561 | <p>Sure, you need to do a few things:</p>
<ol>
<li><p>Define a <code>requirements.txt</code> file in the root of your project that lists your dependencies. This is what Heroku will use to 'detect' you're using a Python app.</p></li>
<li><p>In the Heroku scheduler addon, just define the command you need to run to launch your python script. It will likely be something like <code>python myscript.py</code>.</p></li>
<li><p>Finally, you need to have some sort of web server that will listen on the proper Heroku PORT -- otherwise, Heroku will think your app isn't working and it will be in the 'crashed' state -- which isn't what you want. To satisfy this Heroku requirement, you can run a really simple Flask web server like this...</p></li>
</ol>
<p>Code (<code>server.py</code>):</p>
<pre><code>from os import environ
from flask import Flask
app = Flask(__name__)
app.run(environ.get('PORT'))
</code></pre>
<p>Then, in your <code>Procfile</code>, just say: <code>web: python server.py</code>.</p>
<p>And that should just about do it =)</p>
| 1 | 2016-08-26T16:13:16Z | [
"python",
"heroku"
] |
django authorization without using request.user.is_authenticated() | 39,139,248 | <p>I am working on django website and I am using django Auth for user authentication and for authorization of user i am using request.user.is_authenticated() code in django view but using this i have to write this code in each and every view, because in my site there is only homepage, registration page and login page which can be accessed without login. So in each and every view i have to right this code.</p>
<pre><code>def dashboard(request):
if request.user.is_authenticated():
return render(request, 'home/dashboard.py')
else:
return HttpResponse('User is not logged In')
</code></pre>
<p>That's why I want to ask is there any way to write code only once for all views those can not be accessed without login as we do in CakePHP using authcomponent. </p>
| 0 | 2016-08-25T07:32:46Z | 39,139,290 | <p>Yes, just use the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.decorators.login_required" rel="nofollow"><code>login_required</code></a> decorator or <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-loginrequired-mixin" rel="nofollow"><code>LoginRequiredMixin</code></a></p>
<pre><code>from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, 'home/dashboard.py')
from django.contrib.auth.mixins import LoginRequiredMixin
class MyCBV(LoginRequiredMixin, GenericView):
</code></pre>
<p>What this will do is redirect anyone attempting to access the view back to the <code>LOGIN_URL</code> (which can be overridden here) with a next get parameter back to the view, so that they must login before continuing. This isn't the same as what you currently do, but its much friendlier</p>
<p>If your entire website needs to be logged in, then you can use a <a href="http://stackoverflow.com/q/2164069/1324033">middleware to make this the default</a></p>
| 0 | 2016-08-25T07:35:35Z | [
"python",
"django"
] |
django authorization without using request.user.is_authenticated() | 39,139,248 | <p>I am working on django website and I am using django Auth for user authentication and for authorization of user i am using request.user.is_authenticated() code in django view but using this i have to write this code in each and every view, because in my site there is only homepage, registration page and login page which can be accessed without login. So in each and every view i have to right this code.</p>
<pre><code>def dashboard(request):
if request.user.is_authenticated():
return render(request, 'home/dashboard.py')
else:
return HttpResponse('User is not logged In')
</code></pre>
<p>That's why I want to ask is there any way to write code only once for all views those can not be accessed without login as we do in CakePHP using authcomponent. </p>
| 0 | 2016-08-25T07:32:46Z | 39,139,303 | <p>You can use <strong>@login_required</strong> instead. See <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/" rel="nofollow">here</a></p>
| 0 | 2016-08-25T07:36:13Z | [
"python",
"django"
] |
Read and write data to new file Python | 39,139,306 | <p>I have to write substrings to a new file by reading from another file. The problem I am facing is that it only writes the last found substring.
Here is what I've tried.</p>
<pre><code>def get_fasta(site):
with open('file1.txt', 'r') as myfile:
data=myfile.read()
site = site-1
str1 = data[site:site+1+20]
temp = data[site-20:site]
final_sequence = temp+str1
with open('positive_results_sequences.txt', 'w') as my_new_file:
my_new_file.write(final_sequence + '\n')
def main():
# iterate over the list of IDS
for k,v in zip(site_id_list):
get_fasta(v)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-08-25T07:36:24Z | 39,139,386 | <p>That's because you've opened the inner file in <code>w</code> mode which recreates the file each time. So the end result is that only last write persists. You want to use <code>a</code> mode (which stands for "append").</p>
<p>Also there are some other issues with your code. For example you open and close both files in each loop iteration. You should move file opening code outside and pass them as parameters:</p>
<pre><code>def main():
with open('file1.txt', 'r') as myfile:
with open('positive_results_sequences.txt', 'a') as my_new_file:
for k,v in zip(site_id_list):
get_fasta(v, myfile, my_new_file)
</code></pre>
| 2 | 2016-08-25T07:41:02Z | [
"python",
"file"
] |
Python - How to create a folder with a user entered name? | 39,139,329 | <p>I have a python script which runs to take screenshots in a loop and save all those images. However currently, all images are stored in Python35 folder.</p>
<p>Therefore I want the user to enter a name for a folder and create one by this name.</p>
<p>I know to use makedirs function and specify a path by <code>newpath=r'C:/users/../'</code> .</p>
<p>But how to append this new folder name specified by the user to the path?</p>
<p>(EDIT) Here is the Code I have:-</p>
<pre><code>import openpyxl
import re
import os
import time
from PIL import ImageGrab
import webbrowser
source_excel=input('Enter the source excel file name-> ')
wb=openpyxl.load_workbook(source_excel)
sheet=wb.active
strt=int(input('Enter starting range-> '))
end=int(input('Enter ending range-> '))
#NEED THE CHANGE HERE
foldname=input("Enter a folder name to create where images will be saved")
newpath=r'C:\Users\rnair\AppData\Local\Programs\Python\Python35\'demofile
# Loop to get the link from excel and take the screenshot by opening the browser for each link
for q in range(strt,end):
getme=q,sheet.cell(row=q,column=1).value #get link from excel file
ab=getme[1]
#myopener=Myopen()
rowc=str(strt)
url=ab
webbrowser.open(url) #opens browser for the link fetched
time.sleep(7) # Delay to wait for the page to load completely
im=ImageGrab.grab()
os.chdir(newpath)
im.save("Row"+rowc+".jpg","JPEG") # Saving image to file
strt=strt+1
</code></pre>
| 0 | 2016-08-25T07:37:38Z | 39,139,537 | <p>If you mean building the path at which the file should be saved, use <a href="https://docs.python.org/2/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join</code></a> with the base directory first and the custom directory name second (the filename can be provided as a third argument). Just be very careful about trusting user input for anything, <em>especially</em> filesystem manipulation.</p>
| 3 | 2016-08-25T07:49:19Z | [
"python",
"python-3.x",
"mkdir"
] |
How can I get this series to a pandas dataframe? | 39,139,359 | <p>I have some data and after using a groupby function I now have a series that looks like this:</p>
<pre><code>year
1997 15
1998 22
1999 24
2000 24
2001 28
2002 11
2003 15
2004 19
2005 10
2006 10
2007 21
2008 26
2009 23
2010 16
2011 33
2012 19
2013 26
2014 25
</code></pre>
<p>How can I create a pandas dataframe from here with <code>year</code> as one column and the other column named <code>sightings</code> ?</p>
<p>I am a pandas novice so don't really know what I am doing. I have tried the <code>reindex</code> and <code>unstack</code> functions but haven't been able to get what I want...</p>
| 2 | 2016-08-25T07:39:17Z | 39,139,408 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and <code>rename</code> columns:</p>
<pre><code>print (df.reset_index())
index year
0 1997 15
1 1998 22
2 1999 24
3 2000 24
4 2001 28
5 2002 11
6 2003 15
7 2004 19
8 2005 10
9 2006 10
10 2007 21
11 2008 26
12 2009 23
13 2010 16
14 2011 33
15 2012 19
16 2013 26
17 2014 25
</code></pre>
<hr>
<pre><code>print (df.reset_index().rename(columns=({'index':'year','year':'sightings'})))
year sightings
0 1997 15
1 1998 22
2 1999 24
3 2000 24
4 2001 28
5 2002 11
6 2003 15
7 2004 19
8 2005 10
9 2006 10
10 2007 21
11 2008 26
12 2009 23
13 2010 16
14 2011 33
15 2012 19
16 2013 26
17 2014 25
</code></pre>
<p>Another solution is set column names by list of names:</p>
<pre><code>df1 = df.reset_index()
df1.columns = ['year','sightings']
print (df1)
year sightings
0 1997 15
1 1998 22
2 1999 24
3 2000 24
4 2001 28
5 2002 11
6 2003 15
7 2004 19
8 2005 10
9 2006 10
10 2007 21
11 2008 26
12 2009 23
13 2010 16
14 2011 33
15 2012 19
16 2013 26
17 2014 25
</code></pre>
<p>EDIT:</p>
<p>Sometimes help add parameter <code>as_index=False</code> to <code>groupby</code> for returning <code>DataFrame</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A':[1,1,3],
'B':[4,5,6]})
print (df)
A B
0 1 4
1 1 5
2 3 6
print (df.groupby('A')['B'].sum())
A
1 9
3 6
Name: B, dtype: int64
print (df.groupby('A', as_index=False)['B'].sum())
A B
0 1 9
1 3 6
</code></pre>
| 2 | 2016-08-25T07:42:13Z | [
"python",
"pandas",
"dataframe",
"multiple-columns",
"series"
] |
How can I get this series to a pandas dataframe? | 39,139,359 | <p>I have some data and after using a groupby function I now have a series that looks like this:</p>
<pre><code>year
1997 15
1998 22
1999 24
2000 24
2001 28
2002 11
2003 15
2004 19
2005 10
2006 10
2007 21
2008 26
2009 23
2010 16
2011 33
2012 19
2013 26
2014 25
</code></pre>
<p>How can I create a pandas dataframe from here with <code>year</code> as one column and the other column named <code>sightings</code> ?</p>
<p>I am a pandas novice so don't really know what I am doing. I have tried the <code>reindex</code> and <code>unstack</code> functions but haven't been able to get what I want...</p>
| 2 | 2016-08-25T07:39:17Z | 39,140,251 | <pre><code>s.rename('sightings').reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/JaaFK.png" rel="nofollow"><img src="http://i.stack.imgur.com/JaaFK.png" alt="enter image description here"></a></p>
| 1 | 2016-08-25T08:27:27Z | [
"python",
"pandas",
"dataframe",
"multiple-columns",
"series"
] |
Waiting for condition without loop Python | 39,139,422 | <p>I just created a script which triggers a report from specific API and then loads it into my database.
I have already built something that works but I would like to know if there is something a bit more "precise" or efficient without the need of making my script loop over and over again.</p>
<p>My current script is the following:</p>
<pre><code>import time
retry=1
trigger_report(report_id)
while report_id.status() != 'Complete':
time.sleep(retry * 1.3)
retry =+ 1
load_report(report_id)
</code></pre>
<p><strong>EDIT:</strong></p>
<p>The API doesn't provide with any wait for completion methods, the most it has is an endpoint which returns the status of the job.
It is a SOAP API.</p>
| 0 | 2016-08-25T07:42:44Z | 39,139,461 | <p>Rather use events, not polling. There are a lot of options for how to implement events in Python. There was a discussion <a href="http://stackoverflow.com/questions/1092531/event-system-in-python">here already on stack overflow</a>. </p>
<p>Here is a synthetic example uses zope.event and an event handler</p>
<pre><code>import zope.event
import time
def trigger_report(report_id):
#do expensive operation like SOAP call
print('start expensive operation')
time.sleep(5)
print('5 seconds later...')
zope.event.notify('Success') #triggers 'replied' function
def replied(event): #this is the event handler
#event contains the text 'Success'
print(event)
def calling_function():
zope.event.subscribers.append(replied)
trigger_report('1')
</code></pre>
<p>But futures as in accepted answer is also neat. Depends on what floats your boat.</p>
| -3 | 2016-08-25T07:45:10Z | [
"python",
"while-loop",
"sleep"
] |
Waiting for condition without loop Python | 39,139,422 | <p>I just created a script which triggers a report from specific API and then loads it into my database.
I have already built something that works but I would like to know if there is something a bit more "precise" or efficient without the need of making my script loop over and over again.</p>
<p>My current script is the following:</p>
<pre><code>import time
retry=1
trigger_report(report_id)
while report_id.status() != 'Complete':
time.sleep(retry * 1.3)
retry =+ 1
load_report(report_id)
</code></pre>
<p><strong>EDIT:</strong></p>
<p>The API doesn't provide with any wait for completion methods, the most it has is an endpoint which returns the status of the job.
It is a SOAP API.</p>
| 0 | 2016-08-25T07:42:44Z | 39,139,722 | <p>While this post doesn't hold any relevance anymore as you said, it' a soap API. But I put the work into it, so I'll post it anyway. :)</p>
<p>To answer your question. I don't see any more efficient methods than polling (aka. looping over and over again)</p>
<hr>
<p>There are multiple ways to do it.</p>
<p>The first way is implementing some sort of callback that is triggered when the task is completed. It will look something like this:</p>
<pre><code>import time
def expensive_operation(callback):
time.sleep(20)
callback(6)
expensive_operation(lambda x:print("Done", x))
</code></pre>
<p>As you can see, the Message "<code>Done 6</code>" will be printed as soon as the operation has been completed.</p>
<p>You can rewrite this with Future-objects.</p>
<pre><code>from concurrent.futures import Future
import threading
import time
def expensive_operation_impl():
time.sleep(20)
return 6
def expensive_operation():
fut = Future()
def _op_wrapper():
try:
result = expensive_operation_impl()
except Exception as e:
fut.set_exception(e)
else:
fut.set_result(result)
thr = threading.Thread(target=_op_wrapper)
thr.start()
return fut
future = expensive_operation()
print(future.result()) # Will block until the operation is done.
</code></pre>
<p>Since this looks complicated, there are some high-level functions implementing thread scheduling for you.</p>
<pre><code>import concurrent.futures import ThreadPoolExecutor
import time
def expensive_operation():
time.sleep(20)
return 6
executor = ThreadPoolExecutor(1)
future = executor.submit(expensive_operation)
print(future.result())
</code></pre>
| 0 | 2016-08-25T07:58:49Z | [
"python",
"while-loop",
"sleep"
] |
How to automatically call a text file with today's date in Python | 39,139,437 | <p>I have a text file that is generated everyday and is named in the following format: "year-month-date.txt" (e.g. 2016-08-25.txt).</p>
<p>Now I would like to open the text file with python and read some data from it. But I would like to do this without manually changing the name of text file inside the code everytime (remember the name of text file changes everyday).</p>
<p>So far I have (line 6 is is the part that needs fixing):</p>
<pre><code>#1 Get today's date
import datetime
todays_date=datetime.date.today()
print(todays_date)
#2 Import info from a text file that is named as today's date
filename=todays_date.txt
fin=open(filename,'r')
Line1list=fin.readline()
print(Line1list)
</code></pre>
| 0 | 2016-08-25T07:43:44Z | 39,139,489 | <p>You will have to extract a string in the correct format from <code>todays_date</code>. </p>
<p>Use <code>strftime</code> for that (see the <a href="https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior" rel="nofollow">docs</a>):</p>
<pre><code>filename = todays_date.strftime('%Y-%m-%d') + '.txt'
</code></pre>
<p>Full example:</p>
<pre><code>import datetime
todays_date = datetime.date.today()
filename = todays_date.strftime('%Y-%m-%d') + '.txt'
print(filename)
>> 2016-08-25.txt
</code></pre>
| 5 | 2016-08-25T07:47:01Z | [
"python",
"datetime",
"import",
"text-files"
] |
How to automatically call a text file with today's date in Python | 39,139,437 | <p>I have a text file that is generated everyday and is named in the following format: "year-month-date.txt" (e.g. 2016-08-25.txt).</p>
<p>Now I would like to open the text file with python and read some data from it. But I would like to do this without manually changing the name of text file inside the code everytime (remember the name of text file changes everyday).</p>
<p>So far I have (line 6 is is the part that needs fixing):</p>
<pre><code>#1 Get today's date
import datetime
todays_date=datetime.date.today()
print(todays_date)
#2 Import info from a text file that is named as today's date
filename=todays_date.txt
fin=open(filename,'r')
Line1list=fin.readline()
print(Line1list)
</code></pre>
| 0 | 2016-08-25T07:43:44Z | 39,139,491 | <p>filename should be a string, you are now trying to access the attribut .txt of todays date...</p>
<p>replace by:</p>
<pre><code>todays_date=datetime.date.today()
filename = str(todays_date)+'.txt'
</code></pre>
<p>Also make sure that todays_date exactly matches the name of the txt file, you may need to shuffle the days, months and years. The above only works if the file is indeed something like '2016-08-25.txt'</p>
| 3 | 2016-08-25T07:47:12Z | [
"python",
"datetime",
"import",
"text-files"
] |
Plotting a heatmap of temperatures | 39,139,444 | <p>I have a matrix of which a smaller version looks like this</p>
<pre>
318.3 318.3 318.3
318.3 318.3 318.3
318.3 318.3 318.3
</pre>
<p>These are the temperatures of a grid of processors. I want to plot a heat map by assigning regular colors i.e. blue to cool and red to hot cores.</p>
<p>An example of what I am looking for is :</p>
<p><a href="http://i.stack.imgur.com/DvhGS.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/DvhGS.jpg" alt="enter image description here"></a></p>
<p>How do I do this using a program or is there any software for linux which does this ?</p>
| -1 | 2016-08-25T07:44:12Z | 39,139,880 | <p>Looks like the <code>rainbow</code> palette could be used with <code>image</code></p>
<pre><code>m <- matrix(c(1, 1,1,1,1,1,1,
1,2,2,3,2,2,1,
1,2,3,4,3,2,1,
1,2,2,3,2,2,1,
1,1,1,1,1,1, 1), 5,7, byrow=TRUE)
image(m, col=rev(rainbow(100))[ 70:100]) # need to reverse it to have high values red.
</code></pre>
<p>(The <code>heatmap</code> functions generally are dolled-up versions of <code>image</code>.)</p>
<p>With the file (that doesn't have much variation) you can get results after reading in the file without a header, removing the column of NA's and coercing to a matrix:</p>
<pre><code> image( f, col=rev(rainbow(350))[ 270:350])
</code></pre>
<p><a href="http://i.stack.imgur.com/l7MIP.png" rel="nofollow"><img src="http://i.stack.imgur.com/l7MIP.png" alt="enter image description here"></a></p>
<p>Can also use lattice::levelplot with the obviousl advantage that you get a scale automagically:</p>
<pre><code>levelplot(f, col.regions=rev(rainbow(350))[ 270:350])
</code></pre>
<p><a href="http://i.stack.imgur.com/C45Pg.png" rel="nofollow"><img src="http://i.stack.imgur.com/C45Pg.png" alt="enter image description here"></a></p>
| 2 | 2016-08-25T08:07:41Z | [
"python",
"plot",
"heatmap"
] |
How to use list comprehension with list of variable number of filenames? | 39,139,620 | <p>Given the list of filenames <code>filenames = [...]</code>.</p>
<p>Is it possibly rewrite the next list comprehension for I/O-safety: <code>[do_smth(open(filename, 'rb').read()) for filename in filenames]</code>? Using <code>with</code> statement, <code>.close</code> method or something else.</p>
<p>Another problem formulation: is it possibly to write I/O-safe list comprehension for the next code?</p>
<pre><code>results = []
for filename in filenames:
with open(filename, 'rb') as file:
results.append(do_smth(file.read()))
</code></pre>
| 4 | 2016-08-25T07:53:54Z | 39,139,727 | <p>You can put the <code>with</code> statement/block to a function and call that in the list comprehension:</p>
<pre><code>def slurp_file(filename):
with open(filename, 'rb') as f:
return f.read()
results = [do_smth(slurp_file(f)) for f in filenames]
</code></pre>
| 9 | 2016-08-25T07:58:57Z | [
"python",
"python-3.x",
"file-io",
"list-comprehension",
"contextmanager"
] |
How to use list comprehension with list of variable number of filenames? | 39,139,620 | <p>Given the list of filenames <code>filenames = [...]</code>.</p>
<p>Is it possibly rewrite the next list comprehension for I/O-safety: <code>[do_smth(open(filename, 'rb').read()) for filename in filenames]</code>? Using <code>with</code> statement, <code>.close</code> method or something else.</p>
<p>Another problem formulation: is it possibly to write I/O-safe list comprehension for the next code?</p>
<pre><code>results = []
for filename in filenames:
with open(filename, 'rb') as file:
results.append(do_smth(file.read()))
</code></pre>
| 4 | 2016-08-25T07:53:54Z | 39,140,026 | <p>You can use the <a href="https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack" rel="nofollow"><code>ExitStack</code></a> introduced in Python 3.3 for this purpose:</p>
<pre><code>with ExitStack() as stack:
files = [stack.enter_context(open(name, "rb")) for name in filenames]
results = [do_smth(file.read()) for file in files]
</code></pre>
<p>Note that this opens all the files at once, which is not necessary for this use case, and might not be a good idea if you have a big number of files.</p>
| 3 | 2016-08-25T08:15:38Z | [
"python",
"python-3.x",
"file-io",
"list-comprehension",
"contextmanager"
] |
Adding tracks to a playlist in Spotify using Spotipy | 39,139,688 | <p>I'm using the Python bindings for the Spotify API to list an artists top tracks and add them to a playlist, but it fails every time, as if it excepts a different type of input.</p>
<p>New_Track_List is a string containing the output of the top tracks lookup as either:</p>
<h1>1: URIs:</h1>
<p>Example: "spotify:track:1pAyyxlkPuGnENdj4g7Y4f, spotify:track:7D2xaUXQ4DGY5JJAdM5mGP, spotify:track:74mG2xIxEUJwHckS0Co6jF, spotify:track:2rjqDPbLlbQRlcj8DVM9kn,"</p>
<p>Using URIs I get this back from the function</p>
<pre><code>sp.user_playlist_add_tracks(username, playlist_id=playlist, tracks=New_Track_List)
</code></pre>
<p>Traceback: </p>
<pre><code>spotipy.client.SpotifyException: http status: 400, code:-1 - https://api.spotify.com/v1/users/smokieprofile/playlists/40aijTeKoxo5u1VSS9E3UQ/tracks: You can add a maximum of 100 tracks per request.
</code></pre>
<p>There's only 20 tracks in the string.</p>
<h1>2nd try: Track IDs:</h1>
<p>Example: "1pAyyxlkPuGnENdj4g7Y4f, 7D2xaUXQ4DGY5JJAdM5mGP, 74mG2xIxEUJwHckS0Co6jF, 2rjqDPbLlbQRlcj8DVM9kn"</p>
<p>Same traceback output.</p>
<h1>Using a single track ID</h1>
<pre><code>sp.user_playlist_add_tracks(username, playlist_id=playlist, tracks="spotify:track:74mG2xIxEUJwHckS0Co6jF")
</code></pre>
<p>Trying to add just ONE track, gets me this message:</p>
<pre><code>spotipy.client.SpotifyException: http status: 400, code:-1 - https://api.spotify.com/v1/users/smokieprofile/playlists/40aijTeKoxo5u1VSS9E3UQ/tracks: Invalid track uri: spotify:track:s
</code></pre>
<p>Same message using only the Track ID, as if it only checks the first letter of the passed string.</p>
<pre><code> sp.user_playlist_add_tracks(username, playlist_id=playlist, tracks="7D2xaUXQ4DGY5JJAdM5mGP")
</code></pre>
<p>Error traceback:</p>
<pre><code>spotipy.client.SpotifyException: http status: 400, code:-1 - https://api.spotify.com/v1/users/smokieprofile/playlists/40aijTeKoxo5u1VSS9E3UQ/tracks: Invalid track uri: spotify:track:7
</code></pre>
| 1 | 2016-08-25T07:57:06Z | 39,153,639 | <p>This looks like a problem with duck typing in python and bad error message in the api. I guess that the api requires you to send a list and not a string, but doesn't actually check that. The problem is that a string is also iterable.</p>
<pre><code>>>> tracks = "spotify:track:1pAyyxlkPuGnENdj4g7Y4f, spotify:track:7D2xaUXQ4DGY5JJAdM5mGP, spotify:track:74mG2xIxEUJwHckS0Co6jF, spotify:track:2rjqDPbLlbQRlcj8DVM9kn"
>>> len(tracks)
150
</code></pre>
<p>and that the api takes actually a list of track ids (not a string of comma separated track uris) and prepends 'spotify:track:' infront of all ids:</p>
<pre><code>>>> tracks = "spotify:track:74mG2xIxEUJwHckS0Co6jF"
>>> ["spotify:track:" + track for track in tracks][0]
'spotify:track:s'
</code></pre>
<p>Thus, if you instead give the api a list of track Ids, it might work:</p>
<pre><code>>>> tracks = ["1pAyyxlkPuGnENdj4g7Y4f", "7D2xaUXQ4DGY5JJAdM5mGP"]
>>> ["spotify:track:" + track for track in tracks][0]
'spotify:track:1pAyyxlkPuGnENdj4g7Y4f'
</code></pre>
| 2 | 2016-08-25T19:50:04Z | [
"python",
"spotify",
"spotipy"
] |
Motion tracker using Raspberry pi 3, OpenCV and Python | 39,139,771 | <p>I have tried to change the parameters of variables.</p>
<h1>The error tells me "too many values to unpack".</h1>
<p>This code is written for OpenCV 2.0, however I am using <strong>OpenCV3.1.</strong>
Am I encountering a reverse compatibility issue here or is it something more trivial?</p>
<h1>Here is my error message</h1>
<pre><code> File "/home/pi/motion-track/motion-track.py", line 219, in <module>
motion_track()
File "/home/pi/motion-track/motion-track.py", line 174, in motion_track
contours, hierarchy = cv2.findContours(thresholdimage,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
ValueError: too many values to unpack
Here is my code:
#!/usr/bin/env python
progname = "motion_track.py"
ver = "version 0.95"
"""
motion-track ver 0.95 written by Claude Pageau pageauc@gmail.com
Raspberry (Pi) - python opencv2 motion tracking using picamera module
It will detect motion in the field of view and use opencv to calculate the
largest contour and return its x,y coordinate. I will be using this for
a simple RPI robotics project, but thought the code would be useful for
other users as a starting point for a project. I did quite a bit of
searching on the internet, github, etc but could not find a similar
implementation that returns x,y coordinates of the most dominate moving
object in the frame.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-opencv python-picamera
sudo apt-get install libgl1-mesa-dri
"""
print("%s %s using python2 and OpenCV2" % (progname, ver))
print("Loading Please Wait ....")
# import the necessary packages
import io
import time
import cv2
from picamera.array import PiRGBArray
from picamera import PiCamera
from threading import Thread
# Display Settings
debug = True # Set to False for no data display
window_on = False # Set to True displays opencv windows (GUI desktop reqd)
SHOW_CIRCLE = True # show a circle otherwise show bounding rectancle on window
CIRCLE_SIZE = 8 # diameter of circle to show motion location in window
LINE_THICKNESS = 1 # thickness of bounding line in pixels
WINDOW_BIGGER = 1 # Resize multiplier for Movement Status Window
# if gui_window_on=True then makes opencv window bigger
# Note if the window is larger than 1 then a reduced frame rate will occur
# Camera Settings
CAMERA_WIDTH = 320
CAMERA_HEIGHT = 240
big_w = int(CAMERA_WIDTH * WINDOW_BIGGER)
big_h = int(CAMERA_HEIGHT * WINDOW_BIGGER)
CAMERA_HFLIP = False
CAMERA_VFLIP = True
CAMERA_ROTATION=180
CAMERA_FRAMERATE = 35
FRAME_COUNTER = 1000
# Motion Tracking Settings
MIN_AREA = 200 # excludes all contours less than or equal to this Area
THRESHOLD_SENSITIVITY = 25
BLUR_SIZE = 10
#-----------------------------------------------------------------------------------------------
class PiVideoStream:
def __init__(self, resolution=(CAMERA_WIDTH, CAMERA_HEIGHT), framerate=CAMERA_FRAMERATE, rotation=0, hflip=False, vflip=False):
# initialize the camera and stream
self.camera = PiCamera()
self.camera.resolution = resolution
self.camera.rotation = rotation
self.camera.framerate = framerate
self.camera.hflip = hflip
self.camera.vflip = vflip
self.rawCapture = PiRGBArray(self.camera, size=resolution)
self.stream = self.camera.capture_continuous(self.rawCapture,
format="bgr", use_video_port=True)
# initialize the frame and the variable used to indicate
# if the thread should be stopped
self.frame = None
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
t = Thread(target=self.update, args=())
t.daemon = True
t.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
for f in self.stream:
# grab the frame from the stream and clear the stream in
# preparation for the next frame
self.frame = f.array
self.rawCapture.truncate(0)
# if the thread indicator variable is set, stop the thread
# and resource camera resources
if self.stopped:
self.stream.close()
self.rawCapture.close()
self.camera.close()
return
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
#-----------------------------------------------------------------------------------------------
def show_FPS(start_time,frame_count):
if debug:
if frame_count >= FRAME_COUNTER:
duration = float(time.time() - start_time)
FPS = float(frame_count / duration)
print("Processing at %.2f fps last %i frames" %( FPS, frame_count))
frame_count = 0
start_time = time.time()
else:
frame_count += 1
return start_time, frame_count
#-----------------------------------------------------------------------------------------------
def motion_track():
print("Initializing Camera ....")
# Save images to an in-program stream
# Setup video stream on a processor Thread for faster speed
vs = PiVideoStream().start()
vs.camera.rotation = CAMERA_ROTATION
vs.camera.hflip = CAMERA_HFLIP
vs.camera.vflip = CAMERA_VFLIP
time.sleep(2.0)
if window_on:
print("press q to quit opencv display")
else:
print("press ctrl-c to quit")
print("Start Motion Tracking ....")
cx = 0
cy = 0
cw = 0
ch = 0
frame_count = 0
start_time = time.time()
# initialize image1 using image2 (only done first time)
image2 = vs.read()
image1 = image2
grayimage1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
first_image = False
still_scanning = True
while still_scanning:
image2 = vs.read()
start_time, frame_count = show_FPS(start_time, frame_count)
# initialize variables
motion_found = False
biggest_area = MIN_AREA
# At this point the image is available as stream.array
# Convert to gray scale, which is easier
grayimage2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
# Get differences between the two greyed, blurred images
differenceimage = cv2.absdiff(grayimage1, grayimage2)
differenceimage = cv2.blur(differenceimage,(BLUR_SIZE,BLUR_SIZE))
# Get threshold of difference image based on THRESHOLD_SENSITIVITY variable
retval, thresholdimage = cv2.threshold(differenceimage,THRESHOLD_SENSITIVITY,255,cv2.THRESH_BINARY)
# Get all the contours found in the thresholdimage
contours, hierarchy = cv2.findContours(thresholdimage,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
total_contours = len(contours)
# save grayimage2 to grayimage1 ready for next image2
grayimage1 = grayimage2
# find contour with biggest area
for c in contours:
# get area of next contour
found_area = cv2.contourArea(c)
# find the middle of largest bounding rectangle
if found_area > biggest_area:
motion_found = True
biggest_area = found_area
(x, y, w, h) = cv2.boundingRect(c)
cx = int(x + w/2) # put circle in middle of width
cy = int(y + h/6) # put circle closer to top
cw = w
ch = h
if motion_found:
# Do Something here with motion data
if window_on:
# show small circle at motion location
if SHOW_CIRCLE:
cv2.circle(image2,(cx,cy),CIRCLE_SIZE,(0,255,0), LINE_THICKNESS)
else:
cv2.rectangle(image2,(cx,cy),(x+cw,y+ch),(0,255,0), LINE_THICKNESS)
if debug:
print("Motion at cx=%3i cy=%3i total_Contours=%2i biggest_area:%3ix%3i=%5i" % (cx ,cy, total_contours, cw, ch, biggest_area))
if window_on:
# cv2.imshow('Difference Image',differenceimage)
cv2.imshow('OpenCV Threshold', thresholdimage)
if WINDOW_BIGGER > 1: # Note setting a bigger window will slow the FPS
image2 = cv2.resize( image2,( big_w, big_h ))
cv2.imshow('Movement Status (Press q in Window to Quit)', image2)
# Close Window if q pressed while movement status window selected
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
print("End Motion Tracking")
still_scanning = False
#-----------------------------------------------------------------------------------------------
if __name__ == '__main__':
try:
motion_track()
finally:
print("")
print("+++++++++++++++++++++++++++++++++++")
print("%s %s - Exiting" % (progname, ver))
print("+++++++++++++++++++++++++++++++++++")
print("")
</code></pre>
| 3 | 2016-08-25T08:01:36Z | 39,141,625 | <p>The line
<code>contours, hierarchy = cv2.findContours(thresholdimage,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)</code>
is giving the error as cv2.findContours returns 3 values but you are assigning them to two variables.
So, correct code is
<code>-,contours, hierarchy = cv2.findContours(thresholdimage,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)</code>
assuming you don't want the first returned value.</p>
<p>cv2.findContours doc:
<a href="http://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html" rel="nofollow">http://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html</a></p>
| 2 | 2016-08-25T09:34:06Z | [
"python",
"c++",
"opencv",
"computer-vision",
"raspberry-pi3"
] |
ImportError: no module named gravatar | 39,139,870 | <p>I am using Django1.10, when I process <code>python manage.py migrate</code>.</p>
<p>I get: </p>
<blockquote>
<p>ImportError: no module named gravatar.</p>
</blockquote>
<p>Before that, I have installed <strong>python2.7</strong> and run it in virtual environment, as well as <strong>django_gravatar</strong>. </p>
<p>What's the problem?</p>
<p><img src="http://i.stack.imgur.com/2LVTD.png" alt="the detail of command line Error"></p>
| -1 | 2016-08-25T08:07:02Z | 39,139,931 | <p>You have to activate the virtual environment first. See this section of the <a href="https://virtualenv.pypa.io/en/stable/userguide/?highlight=activate#activate-script" rel="nofollow">docs</a>:</p>
<p>In a newly created virtualenv there will also be a activate shell script. For Windows systems, activation scripts are provided for the Command Prompt and Powershell.</p>
<p>On Posix systems, this resides in <code>/ENV/bin/</code>, so you can run:</p>
<pre><code>$ source bin/activate
</code></pre>
<p>For some shells (e.g. the original Bourne Shell) you may need to use the . command, when source does not exist. There are also separate activate files for some other shells, like csh and fish. bin/activate should work for <code>bash/zsh/dash</code>.</p>
<p>This will change your <code>$PATH</code> so its first entry is the virtualenvâs <code>bin/</code> directory. (You have to use source because it changes your shell environment in-place.) This is all it does; itâs purely a convenience. If you directly run a script or the python interpreter from the virtualenvâs bin/ directory (e.g. <code>path/to/ENV/bin/pip</code> or <code>/path/to/ENV/bin/python-script.py</code>) thereâs no need for activation.</p>
<p>The activate script will also modify your shell prompt to indicate which environment is currently active. To disable this behaviour, see VIRTUAL_ENV_DISABLE_PROMPT.</p>
<p>To undo these changes to your path (and prompt), just run:</p>
<pre><code>$ deactivate
</code></pre>
<p>On Windows, the equivalent activate script is in the Scripts folder:</p>
<pre><code>\path\to\env\Scripts\activate
</code></pre>
| 0 | 2016-08-25T08:10:35Z | [
"python",
"django"
] |
Settin general defaults for named arguments in python | 39,139,935 | <p>I have the following problem:
I have to set some values for special entities (points, lines, faces, volumes, spheres,...), via an API into a database.</p>
<p>Some values are unique for every entity, others are always the same.
So my idea was to do something like (SetValues is the API command i have to use putting something into the database):</p>
<pre><code>def CreateLineEntity(ID,Name,Solver,P1,P2,Move='no',Perimeter=0.0,Gap='yes'):
SetValues(ID, {'Name':Name})
SetValues(ID, {'P1':P1})
SetValues(ID, {'P2':P2})
SetValues(ID, {'Solver':Solver})
SetValues(ID, {'Move':Move})
SetValues(ID, {'Perim':Perimeter})
SetValues(ID, {'Gap':Gap})
######################################################################
def CreatePointEntity(ID,Name,Solver,P1,Move='no',Perimeter=0.0,Gap='yes'):
SetValues(ID, {'Name':Name})
SetValues(ID, {'P1':P1})
SetValues(ID, {'Solver':Solver})
SetValues(ID, {'Move':Move})
SetValues(ID, {'Perim':Perimeter})
SetValues(ID, {'Gap':Gap})
</code></pre>
<p>So in every function the default for Move is 'no'</p>
<p>If the default changes for some reason i had to check the complete code changing the default now.</p>
<p>Is there a more intelligent way to define such defaults?
My goal is to change only one value in the code and than all defaults in the functions are changed, too</p>
| 6 | 2016-08-25T08:10:48Z | 39,140,046 | <p>You can change default value for <code>Move</code> argument in your methods, by using <code>func_defaults</code> tuple, which holds values from kwargs:</p>
<pre><code># CreateLineEntity.func_defaults --> ('no', 0.0, 'yes')
defaults = list(CreateLineEntity.func_defaults)
# You're modyfying first one which is for ``Move``
defaults[0] = 'yes'
# And assign them back with changed value
CreateLineEntity.func_defaults = tuple(defaults)
</code></pre>
<p>Then running again the same function, <code>no</code> will be replaced by <code>yes</code> in this example.</p>
| 1 | 2016-08-25T08:17:16Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.