text
stringlengths 226
34.5k
|
---|
Python3 submodules setup does not update paths when run with -m switch
Question: I have the following project structure:
server/
server.py
__init__.py
sockets/
module.py
__init__.py
I set `PYTHONPATH` to one directory above server (for example
`/home/user/server` contains server, `PYTHONPATH` is set `/home/user`).
The main file is `server.py`; it imports modules:
import sockets
from sockets.module import Module
When I run `python3 $PYTHONPATH/server/server.py` directly it works perfectly.
However when I call `python3 -m server.server.py` it fails, despite the fact
that it is explicitly recommended to avoid Python path hell, but it fails to
find the the module, with an ugly message:
/usr/bin/python3: Error while finding spec for 'server.server.py' (<class 'ImportError'>: No module named 'sockets')
Why does the module import fail to import submodules? How to properly setup
sub-packages?
Answer: The behaviour is entirely correct; `sockets` is not a _top-level module_.
However, when you use `$PYTHONPATH/server/server.py`, Python also adds
`$PYTHONPATH/server/` to the Python search path, so now `sockets` _is_ a top-
level module. You should never directly run files in a package.
Import `sockets` relative to the current package:
from . import sockets
from .sockets.module import Module
or use fully-qualified imports:
from server import sockets
from server.sockets.module import Module
Also see the [_Interface Options_
section](https://docs.python.org/3//using/cmdline.html#interface-options) of
the Python Setup and Usage section in the fine manual:
> If the script name refers directly to a Python file, the **directory
> containing that file is added to the start of`sys.path`**, and the file is
> executed as the `__main__` module.
Note that the `-m` switch takes a _python identifier_ , not a filename, so
use:
python -m server.server
leaving of the `.py` extension.
|
Upgrade to django 1.7 - instance becomes unicode
Question: I recently moved from django 1.2.5 to 1.7.0 (A long overdue upgrade) and as
expected alot of things broke. I have been able to fix alot of things however
I am having one major issue.
I have pickled objects stored in the database. In django 1.2.5, I ran the
below commands and below are the results
>>> from app.foo.models import MyModel as s
>>> s.objects.get(id = 34567)
<MyModel: Foo (bar)>
>>> x = s.objects.get(id = 34567)
>>> x.myObject
<foor.bar.My Class instance at 0x3855878>
>>> y = x.myObject
>>> type(y)
<type 'instance'>
However on django 1.7.0 I get the below
>>> from app.foo.models import MyModel as s
>>> s.objects.get(id = 34567)
<MyModel: Foo (bar)>
>>> x = s.objects.get(id = 34567)
>>> x.myObject
>
> VHJlZUFuc3dlckNob2ljZQpwMjYyCihkcDI2MwpnNDEKUydXZWJzaXRlJwpwMjY0CnNnNDMKKGxwMjY1CnNiYShpbm9lLnN1cnZleTIudHJlZXN1cnZleQpUcmVlQW5zd2VyQ2hvaWNlCnAyNjYKKGRwMjY3Cmc0MQpTJ0VwYXBlcicKcDI2OApzZzQzCihscDI2OQpzYmEoaW5vZS5zdXJ2ZXkyLnRyZWVzdXJ2ZXkKVHJlZUFuc3dlckNob2ljZQpwMjcwCihkcDI3MQpnNDEKUydETiBTYWZhcmljb20gTW9iaWxlIEFwcCcKcDI3MgpzZzQzCihscDI3MwpzYmEoaW5vZS5zdXJ2ZXkyLnRyZWVzdXJ2ZXkKVHJlZUFuc3dlckNob2ljZQpwMjc0CihkcDI3NQpnNDEKUydPdGhlcicKcDI3NgpzZzQzCihscDI3NwpzYmFzZzYKZzEKc2cxMQpOc2c2NQpJMDEKc2c5ClMnMScKc2JhZzEyMQphZzEyOQphZzE2NQphZzE3MwphZzE4MAphZzE5MgphZzQKYXNTJ2N1cnJlbnRRdWVzdGlvbicKcDI3OApnNApzUydzZW5kRW5kTWVzc2FnZScKcDI3OQpJMDEKc1MnY2FuU2VuZEVuZE1lc3NhZ2UnCnAyODAKSTAxCnNTJ2Nob2ljZVF1ZXVlJwpwMjgxCihscDI4MgpzYi4='
(This is a snippet of the actual output)
>>> y = x.myObject
>>> type(y)
<type 'unicode'>
As such I am not able to access the instance methods. When i check the
properties of the object as of 1.7, i get
>>> dir(y)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'islower', 'isnumeric', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Here is MyModel:
from django.db import models
from django.contrib.auth.models import User
from SerializedDataField import SerializedDataFiel
class MyModel(models.Model):
title = models.TextField()
description = models.TextField()
creator = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
code = models.TextField()
active = models.BooleanField(default = None)
"""Pickled fresh survey object."""
myObject = SerializedDataField()
"""Can the pickled surveyObj be changed? Once a survey has been activated, myObject cannot be changed"""
mutable = models.BooleanField(default = None)
def __unicode__(self):
return self.title + " (" + self.code + ")"
And here is Serialized Data Field
from django.db import models
try:
import cPickle as pickle
except:
import pickle
import base64
class SerializedDataField(models.TextField):
"""Because Django for some reason feels its needed to repeatedly call
to_python even after it's been converted this does not support strings."""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if value is None: return
if not isinstance(value, basestring): return value
try:
value = pickle.loads(base64.b64decode(value))
return value
except:
return value
def get_db_prep_save(self, value *args, **kwargs):
if value is None: return
return base64.b64encode(pickle.dumps(value))
How can I access my instance methods if I keep getting getting a unicode
object?
Answer: _All_ text columns in Django are stored as Unicode data. If your column is
really _binary_ data, you can now migrate those to a
[`BinaryField`](https://docs.djangoproject.com/en/1.7/ref/models/fields/#binaryfield)
(the field was only added in Django 1.6).
For your existing data, you need to encode back to a binary byte string, you
can do so with the [Latin-1 (ISO
8859-1)](http://en.wikipedia.org/wiki/ISO/IEC_8859-1) codec; Unicode
codepoints U+0000 through to U+00FF map one-on-one to Latin-1 bytes:
y = x.surveyObject.encode('latin1')
The mistake then, was treating binary data as text; it never was text to begin
with.
|
Random Password Generator Keeps Generating the Same Password
Question: I have to write a program that generates random passwords (using ASCII values
and the chr() function) using Python and I have gotten my program to generate
a random password, but when the program loops, it keeps printing the same
random password and I have no idea what to do to fix it. If anyone could give
me some advice, that would be great because I'm new to python
here is the code that I have so far:
import random, string
LNGTH=8
position=0
password=""
start=0
stop=0
while start==stop:
input("would you like a password?")
while position<LNGTH:
x=random.randrange(9)
character=chr(random.randrange(97, 97 + 26))
choice=[str(x),character.upper(),character.lower()]
pass_pos=random.choice(choice)
password=password+pass_pos
position+=1
print(password)
Answer: You never reset `position`, so your `while` loop always returns `True` after
the first password is generated.
Because you also do not reset `password` that means you generate just the one
random password and re-display that value over and over again.
You need to reset both _inside_ the outer `while` loop:
while start==stop:
input("would you like a password?")
position = 0
password = ''
You could just use `while True` instead of `start == stop` there. You could
also use a `for` loop instead of your inner `while` loop, simplifying your
setup:
password = ''
for i in range(LNGTH):
x=random.randrange(9)
character=chr(random.randrange(97, 97 + 26))
choice=[str(x),character.upper(),character.lower()]
pass_pos=random.choice(choice)
password=password+pass_pos
Cleaning that up some more by using
[`string.ascii_letters`](https://docs.python.org/3/library/string.html#string.ascii_letters)
and
[`string.digits`](https://docs.python.org/3/library/string.html#string.digits):
import string
import random
password_characters = string.ascii_letters + string.digits
length = 8
while True:
if input("Would you like a password? ").lower() not in {'y', 'yes'}:
break
password = ''.join([random.choice(password_characters)
for _ in range(length)])
print(password)
|
Error while executing python code
Question:
# -*- coding: utf-8 -*-
# coding: utf-8
import sys
import os
import time
b = 'sudo tshark -i eth0 -R “tcp contains “attack”” -T fields -e ip.src -a duration:60>output.txt'
a = os.popen(b)
time.sleep(32)
f = open('output.txt','r')
text = 'IP address of attacker is'
print (text), f.read()
f.close
I am trying to execute this code to capture packets using tshark but i am
getting this error:
tshark: "�" was unexpected in this context.
Please help me why that error is caused, thank you
Answer: The error message is because `tshark` tries to disable some dangerous
functions in Lua like `dofile`.
If you don't need Lua in tshark, you can disable Lua support: edit `init.lua`,
change `disable_lua = false` to `disable_lua = true`.
If you need Lua support, read [Platform-Specific information about capture
privileges](http://wiki.wireshark.org/CaptureSetup/CapturePrivileges), see how
to capture packets without root rivilege.
|
Comparing 2 excel files via Python. Is there any other recommended language to use instead of python?
Question: reference file:

fill_in:
basically, the you're taking the values in col 1 (left) and comparing them
with the values in the reference file (col1). If the values are an exact
match, it will take the value in col2 from reference and place it into col2 of
the fill_in file. (below)

So far, my codes is this :
import win32com.client, csv, os, string
# Office 2010 - Microsoft Office Object 14.0 Object Library
from win32com.client import gencache
gencache.EnsureModule('{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}', 0, 2, 5)
#
# Office 2010 - Excel COM
from win32com.client import gencache
gencache.EnsureModule('{00020813-0000-0000-C000-000000000046}', 0, 1, 7)
#
Application = win32com.client.Dispatch("Excel.Application")
Application.Visible = True
Workbook = Application.Workbooks.Add()
Sheet = Application.ActiveSheet
#
#REFERENCE FILE
f = open("reference_file.csv", "rb")
ref = csv.reader(f)
ref_dict = dict()
#FILE WITH BLANKS
g = open("fill_in.csv", "rb")
fill = csv.reader(g)
fill_dict = dict()
#CODE STARTS
gene_dic = dict()
count = 0
#Make reference file into a dictionary
for line in ref:
ref_dict[line[1]] = [line[0]]
#Make Fill in file into a dictionary
for i in fill:
fill_dict[i[1]] = [i[0]]
#finding difference in both dictionaries
diff = {}
for key in ref_dict.keys():
if(not fill_dict.has_key(key)):
diff[key] = (ref_dict[key])
elif(ref_dict[key] != fill_dict[key]):
diff[key] = (ref_dict[key], fill_dict[key])
for key in fill_dict.keys():
if(not ref_dict.has_key(key)):
diff[key] = (fill_dict[key])
fill_dict.update(diff)
print fill_dict
#Put dictionary into an Array
temp = []
dictlist = []
for key, value in fill_dict.iteritems():
temp = [key, value]
dictlist.append(temp)
dictlist.sort()
print(dictlist)
for i in dictlist:
count += 1
Sheet.Range("A" + str(count)).Value = i[0]
Sheet.Range("B" + str(count)).Value = i[1]
Workbook.SaveAs(os.getcwd() + "/" + "result1.csv")
The results is this:

But the supposed result was suppose to be like this:

If in column 2(column B), there is a value, it should remain untouched. If
there's an empty cell, and it has a match in the reference file, it would
print the number into columnB
I've also tried this code, however i've only manage to put it in a list, not
in excel :
r=open("reference_file.csv","rb")
ref = csv.reader(r)
ref_dict = dict()
f=open("fill_in.csv", "rb")
fill = csv.reader(f)
#CODE STARTS
lst = []
lstkey = []
count = 0
#put reference file in a dictionary
for line in ref:
ref_dict[line[1]] = [line[0]]
all_values = defaultdict(list)
for key in ref_dict:
for value in (map(lambda x: x.strip(), ref_dict[key][0].split(","))):
all_values[value].append(key)
for i in lst:
lstkey.append(all_values[i])
print lstkey
Answer: I dont know if there is any specific language to use when operating with excel
files, but for sure you can use ruby. I personally find ruby codes easier to
understand and would use ruby for a task like this. You can check out
[this](http://stackoverflow.com/questions/3309511/how-do-i-read-the-content-
of-an-excel-spreadsheet-using-ruby) topic where they parse an excel file and
do some checks. Hope it helps.
|
How to get the xpath for jobpage?
Question: I have tried too many possibilities to get xpath for click the "Search Jobs
Now" and "Search " button for to get job list page. but its not find exactly
what i am expected.
Please let me know how to find click the "Search Jobs Now" and "Search" button
and get the joblist page.
Note:
I checked the Web-element **'Search jobs now'** is located under **frame id=
ptifrmtgtframe and name =TargetContent**. Once we switch to this frame then we
will be able to click on first page button and second page button like
"**Search** "
Platform : scrapy + selenium remote control + python
Here is spider code:
class WellsfargocomSpider(Spider):
name = 'wellsfargo'
allowed_domains = ['www.wellsfargo.com']
start_urls = ['https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS=']
#driver = webdriver.Remote('http://127.0.0.1:4444/wd/hub', desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)
# Create a new instance of the Firefox webdriver
driver = webdriver.Firefox()
# Create implicitly wait for 30
#driver.implicitly_wait(0.5)
def parse(self,response):
selector = Selector(response)
#self.driver.get('https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS=')
driver = self.driver
#driver = webdriver.Firefox()
self.driver.get('https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS=');
self.driver.switchTo().frame(self.driver.find_element_by_tag_name('TargetContent'))
Thread.sleep(10000)
clk = self.driver.find_element_by_xpath("//input[@id='HRS_CE_WELCM_WK_HRS_CE_WELCM_BTN']")
clk.click()
clk1 = self.driver.find_element_by_xpath("//input[@name='SEARCHACTIONS#SEARCH']")
clk1.click()
self.driver.switchTo().defaultContent()
#inputElement = self.driver.find_element_by_css_selector("input.PSPUSHBUTTON")
#inputElement.submit()
#inputElement1 = self.driver.find_element_by_xpath("//input[@name='SEARCHACTIONS#SEARCH']")
#inputElement1.click()
#while True:
#next = self.driver.find_element_by_xpath(".//*[@id='HRS_APPL_WRK_HRS_LST_NEXT']")
#try:
links = []
for link in selector.css('span.PSEDITBOX_DISPONLY').re('.*>(\d+)<.*'):
#intjid = selector.css('span.PSEDITBOX_DISPONLY').re('.*>(\d+)<.*')
abc = 'https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?Page=HRS_APP_JBPST&FOCUS=Applicant&SiteId=1&JobOpeningId='+link+'&PostingSeq=1'
#print abc
yield Request(abc,callback=self.parse_iframe, headers={"X-Requested-With": "XMLHttpRequest"}, dont_filter=True)
#next.click()
#except:
#break
#self.driver.close()
def parse_iframe(self,response):
selector = Selector(response)
url = selector.xpath('//*[@id="ptifrmtgtframe"]/@src').extract()[0]
yield Request(url,callback=self.parse_listing_page, headers={"X-Requested-With": "XMLHttpRequest"}, dont_filter=True)
Here is output:
C:\Users\xxxx\Downloads\wellsfargocom>scrapy crawl wellsfargo
2014-11-28 10:40:07+0530 [scrapy] INFO: Scrapy 0.24.4 started (bot: wellsfargoco
m)
2014-11-28 10:40:07+0530 [scrapy] INFO: Optional features available: ssl, http11
2014-11-28 10:40:07+0530 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE'
: 'wellsfargocom.spiders', 'SPIDER_MODULES': ['wellsfargocom.spiders'], 'BOT_NAM
E': 'wellsfargocom'}
2014-11-28 10:40:07+0530 [scrapy] INFO: Enabled extensions: LogStats, TelnetCons
ole, CloseSpider, WebService, CoreStats, SpiderState
2014-11-28 10:40:07+0530 [scrapy] INFO: Enabled downloader middlewares: HttpAuth
Middleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, Def
aultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, Redirec
tMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2014-11-28 10:40:07+0530 [scrapy] INFO: Enabled spider middlewares: HttpErrorMid
dleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddlew
are
2014-11-28 10:40:07+0530 [scrapy] INFO: Enabled item pipelines:
2014-11-28 10:40:07+0530 [wellsfargo] INFO: Spider opened
2014-11-28 10:40:07+0530 [wellsfargo] INFO: Crawled 0 pages (at 0 pages/min), sc
raped 0 items (at 0 items/min)
2014-11-28 10:40:07+0530 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6
023
2014-11-28 10:40:07+0530 [scrapy] DEBUG: Web service listening on 127.0.0.1:6080
2014-11-28 10:40:09+0530 [wellsfargo] DEBUG: Redirecting (302) to <GET https://e
mployment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GB
L?FOCUS=&> from <GET https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRM
S/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS=>
2014-11-28 10:40:10+0530 [wellsfargo] DEBUG: Redirecting (302) to <GET https://e
mployment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GB
L?FOCUS=> from <GET https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS
/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS=&>
2014-11-28 10:40:10+0530 [wellsfargo] DEBUG: Crawled (200) <GET https://employme
nt.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS
=> (referer: None)
2014-11-28 10:40:20+0530 [wellsfargo] ERROR: Spider error processing <GET https:
//employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB
.GBL?FOCUS=>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 82
4, in runUntilCurrent
call.func(*call.args, **call.kw)
File "C:\Python27\lib\site-packages\twisted\internet\task.py", line 63
8, in _tick
taskObj._oneWorkUnit()
File "C:\Python27\lib\site-packages\twisted\internet\task.py", line 48
4, in _oneWorkUnit
result = next(self._iterator)
File "C:\Python27\lib\site-packages\scrapy-0.24.4-py2.7.egg\scrapy\uti
ls\defer.py", line 57, in <genexpr>
work = (callable(elem, *args, **named) for elem in iterable)
--- <exception caught here> ---
File "C:\Python27\lib\site-packages\scrapy-0.24.4-py2.7.egg\scrapy\uti
ls\defer.py", line 96, in iter_errback
yield next(it)
File "C:\Python27\lib\site-packages\scrapy-0.24.4-py2.7.egg\scrapy\con
trib\spidermiddleware\offsite.py", line 26, in process_spider_output
for x in result:
File "C:\Python27\lib\site-packages\scrapy-0.24.4-py2.7.egg\scrapy\con
trib\spidermiddleware\referer.py", line 22, in <genexpr>
return (_set_referer(r) for r in result or ())
File "C:\Python27\lib\site-packages\scrapy-0.24.4-py2.7.egg\scrapy\con
trib\spidermiddleware\urllength.py", line 33, in <genexpr>
return (r for r in result or () if _filter(r))
File "C:\Python27\lib\site-packages\scrapy-0.24.4-py2.7.egg\scrapy\con
trib\spidermiddleware\depth.py", line 50, in <genexpr>
return (r for r in result or () if _filter(r))
File "C:\Users\sureshp\Downloads\wellsfargocom\wellsfargocom\spiders\w
ellsfargo.py", line 48, in parse
self.driver.switchTo().frame(self.driver.find_element_by_tag_name('T
argetContent'))
exceptions.AttributeError: 'WebDriver' object has no attribute 'switchTo
'
2014-11-28 10:40:20+0530 [wellsfargo] INFO: Closing spider (finished)
2014-11-28 10:40:20+0530 [wellsfargo] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1880,
'downloader/request_count': 3,
'downloader/request_method_count/GET': 3,
'downloader/response_bytes': 7190,
'downloader/response_count': 3,
'downloader/response_status_count/200': 1,
'downloader/response_status_count/302': 2,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2014, 11, 28, 5, 10, 20, 84000),
'log_count/DEBUG': 5,
'log_count/ERROR': 1,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 3,
'scheduler/dequeued/memory': 3,
'scheduler/enqueued': 3,
'scheduler/enqueued/memory': 3,
'spider_exceptions/AttributeError': 1,
'start_time': datetime.datetime(2014, 11, 28, 5, 10, 7, 448000)}
2014-11-28 10:40:20+0530 [wellsfargo] INFO: Spider closed (finished)
Answer: It is called [`switch_to`](http://selenium-
python.readthedocs.org/api.html#selenium.webdriver.remote.webdriver.WebDriver.switch_to),
not `switchTo`. Here is a working example:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://employment.wellsfargo.com/psp/PSEA/APPLICANT_NW/HRMS/c/HRS_HRAM.HRS_APP_SCHJOB.GBL?FOCUS=')
# find the frame and switch to it
frame = driver.find_element_by_id('ptifrmtgtframe')
driver.switch_to.frame(frame)
# find the button and click it
button = driver.find_element_by_id('HRS_CE_WELCM_WK_HRS_CE_WELCM_BTN')
button.click()
|
how to efficiently traverse a directory and get the sha256 checksum for each file
Question: I want to traverse any directory and been available to calculate the
[checkusum](http://en.wikipedia.org/wiki/Checksum) of each file, currently I
am using [python
multiprocessing](https://docs.python.org/2/library/multiprocessing.html) and
this following code:
import hashlib
import os
import time
from multiprocessing import Pool
def list_files(path):
directories = []
files = []
def append_files(x):
files.append(x)
pool = Pool()
src = os.path.abspath(os.path.expanduser(path))
for root, dirs_o, files_o in os.walk(src):
for name in dirs_o:
directories.append(os.path.join(root, name))
for name in files_o:
file_path = os.path.join(root, name)
if os.path.isfile(file_path):
pool.apply_async(
sha256_for_file,
args=(file_path,),
callback=append_files)
pool.close()
pool.join()
return directories, files
def sha256_for_file(path, block_size=4096):
try:
with open(path, 'rb') as rf:
h = hashlib.sha256()
for chunk in iter(lambda: rf.read(block_size), b''):
h.update(chunk)
return h.hexdigest(), path
except IOError:
return None, path
if __name__ == '__main__':
start_time = time.time()
d, f = list_files('~')
print len(f)
print '\n' + 'Elapsed time: ' + str(time.time() - start_time)
The code is using python `apply_async`, I tried using `map` and also
`map_async` but don't see any improvements in terms of speed, I also tried
`ThreadPool` but became more slower.
from multiprocessing.pool import ThreadPool
pool = TreadPool()
...
Any ideas of how to optimize the code or improve it in order to be available
to traverse huge directories and calculate the checksum of every file using
python 2.7?
On a MacBook Pro (3GHz Intel Core i7, 16 GB RAM 1600 MHz DDR3, SSD disk)
calculating the hash for all files (**215658**) in the user home '~' took:
**194.71100688** seconds.
Answer: Let's have a closer look at the multithreading part. What does your program
do?
1. traverse directories
2. open files and calculate their checksum
**1** and **2** require concurrent disk access, while only **2** performs
actual calculations. Using different thread for steps **1** and **2** wouldn't
increase speed, because of this concurrent disk access. But **2** could be
split in two distinct steps:
1. traverse directories
2. open files and read their contents
3. calculate checksum of contents
**1** and **2** could belong to one thread (disk access, writing to memory),
while **3** could be performed in a separate one (reading memory, CPU
calculation).
Still, I am not sure you would get a huge performance gain, as hash
computation is generally not so CPU-intensive: most of the computation time
might be used for disk reading...
|
How to loop over a response element in Scrapy?
Question: I am trying to code a scraper with Scrapy for Python. At this point, I am
trying to get the name of the webpage and all the outbound links within the
page. The output should be a dictionary like this
{'link': [u'Link1'], 'title': [u'Page title']}
I have created this code:
from scrapy.spider import Spider
from scrapy import Selector
from socialmedia.items import SocialMediaItem
class MySpider(Spider):
name = 'smm'
allowed_domains = ['*']
start_urls = ['http://en.wikipedia.org/wiki/Social_media']
def parse(self, response):
items =[]
for link in response.xpath("//a"):
item = SocialMediaItem()
item['title'] = link.xpath('text()').extract()
item['link'] = link.xpath('@href').extract()
items.append(item)
yield items
Could anyone help me to get this result? I've adapted the code from this page
<http://mherman.org/blog/2012/11/05/scraping-web-pages-with-scrapy/>
updating the code without the deprecated functions. Thank you so much!
Dani
Answer: If I understand correctly, you want to iterate all of the links and extract
links and titles.
Get all `a` tags via `//a` xpath and extract `text()` and `@href`:
def parse(self, response):
for link in response.xpath("//a"):
item = SocialMediaItem()
item['title'] = link.xpath('text()').extract()
item['link'] = link.xpath('@href').extract()
yield item
This yields:
{'link': [u'#mw-navigation'], 'title': [u'navigation']}
{'link': [u'#p-search'], 'title': [u'search']}
...
{'link': [u'/wiki/Internet_forum'], 'title': [u'Internet forums']}
...
Also, note that there are [`Link
Extractors`](http://doc.scrapy.org/en/latest/topics/link-extractors.html)
built-in into Scrapy:
> LinkExtractors are objects whose only purpose is to extract links from web
> pages (scrapy.http.Response objects) which will be eventually followed.
|
Efficiently keeping track of changes in text
Question: I have to send some text over the network to another computer in python. I'll
probably do this using sockets. I'm doing this so people on two different
computers can edit a document at the same time. I was wondering whether there
was an efficient way I could do this. I figure sending the updated text
everytime a user presses a key doesn't make sense at all. Could I instead only
send the changes that are made every time the user changes something in the
text. How do I go about doing this?
Answer: As you want to allow editing text to 2 (or more) clients, I would use a patch
library such as diff_match_patch (google diff match patch).
Here is a sample code you can use :
import diff_match_patch as dmp
d = dmp()
patch = d.patch_make(current_text, new_text)
updated_text, status = d.patch_apply(patch, current_text)
So you can handle insertions, deletions and can even add undo operations...
|
How to continuously updating the display in two different place in Python
Question: I know how to print one line in same plase but I want to print same place from
thread only.
Now I'm getting:
>
> OK 97035
>
I want to get:
>
> OK 97035
> OK 92035
>
First line is from t1 thread, second from t2 thread. Anyone know how to do it
?
This is sample code.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string, threading
def test():
for i in range(0, 100000):
print "\rOK "+str(i),
jczyd= ['1', '2']
while True:
for i in jczyd:
if i == '1':
#print i
t1 = threading.Thread(target=test, args = ())
t1.daemon = True
t1.start()
elif i == '2':
#print i
t2 = threading.Thread(target=test, args = ())
t2.daemon = True
t2.start()
t1.join()
t2.join()
Answer: Actually, this is trickier than you might think.
The problem is that there's no character in plain ASCII that you can use to
update two separate lines of text simultaneously. `\r` only lets you erase one
line.
If you want to update two lines you will have to use a platform-specific
method, like ANSI escape codes, or use `curses` to control the terminal in a
more general way.
On most UNIX systems, you can do this with code like this:
print '\x1b[%dH%s\x1b[K' % (thread_id, i)
which sets the cursor to the `thread_id`th line, prints `i`, then erases the
rest of the line.
|
Python: nested list output
Question: I am reading data from a text file like this
>VAL1;Date1;K123 K135;A lot of text
>VAL2;Date2;K231 K389;more text
>VAL3;Date3;K123;even more text
>VAL4;Date4;K389;even more text
>VAL5;Date5;K634 K123 K888;even more text
Desired output while col4 is a count of col2 and col5 is a count of col1
>K123;VAL1;Date1;2;3
>K135;VAL1;Date1;1;2
>K231;VAL2;Date2;1;2
>K398;VAL2;Date2;2;2
>K123;VAL3;Date3;2;3
>K398;VAL4;Date4;2;1
>K634;VAL5;Date5;3;1
>K123;VAL5;Date5;3;3
>K888;VAL5;Date5;3;1
Idea was to read it into lists and nested lists like this.
List = [['VAL1','Date1',['K123','K125'],'A lot of text'],['VAL2','Date2',['K231','K389'],'more text'],...]
This is my code so far to create list and nested lists but I can´t make it to
the desired output. Can you support?
import re
raw_data = open('C:\Users\denis.gerhardt\DMS\INC.txt').read().strip('\n')
val = re.findall('INC.+',raw_data)
meta=[]
for item in val:
meta.append(item.split(';'))
k=[]
for k in meta:
k.append(re.findall(r'\bK[0-9]+',k[2]))
print meta
close(raw_data)
Answer: Clever is good, but in this case, you should break the problem apart into
comprehensible bits and then put it all back together. Not only will this be
easier, it will also be more readable and more maintainable long term.
For instance, one of your columns is a count of your K values. There are many
ways of doing this:
# ['VAL1;Date1;K123 K135;A lot of text', ... ]
val = """VAL1;Date1;K123 K135;A lot of text
VAL2;Date2;K231 K389;more text
VAL3;Date3;K123;even more text
VAL4;Date4;K389;even more text
VAL5;Date5;K634 K123 K888;even more text""".split('\n')
# Most straightforward method:
# Parse the lines then use a dictionary to keep count
count_k_1 = {}
for line in val:
array = line.split(';')
ks = array[2].split(' ')
for k in ks:
try:
count_k_1[k] += 1
except KeyError:
count_k_1[k] = 1
print count_k_1
# Fancy method:
# Use a collection.Counter and then parse in a list comprehension
import collections
count_k_2 = collections.Counter([item for line in val for item in
line.split(';')[2].split(' ')])
print count_k_2
Output:
{'K888': 1, 'K231': 1, 'K123': 3, 'K634': 1, 'K389': 2, 'K135': 1}
Counter({'K123': 3, 'K389': 2, 'K888': 1, 'K231': 1, 'K634': 1, 'K135': 1})
There are probably two more major things to write:
1. How to count the values.
2. How to print the pairs of keys and values so that your final output has 9 lines, not 5.
These are left as an exercise for the reader.
|
Send input to program opened with subprocess using python?
Question: I have the following python code and just want to send a command to the
terminal when it asks a particular question. Here is what I have so far
import subprocess
import sys
cmd = "Some application"
dat = str("")
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Answer:
p.communicate(input="this is my input to the subprocess")
If you need to trap the output, do this instead:
output = p.communicate(input="this is my input to the subprocess")[0]
|
Lambda parameter function in python
Question: I am supposed to analyze shakespeare text using NLTK ( sentiment analysis)
using python 3.4. But I get this error message:
**Traceback (most recent call last):
File "C:\Users\HAMIMOUNE\AppData\Roaming\nltk_data\shakespeare.py", line 8, in <module>
[ line.split('\t') for line in open("AFINN-96.txt") ]))
TypeError: <lambda>() missing 1 required positional argument: 'v'**
here is my code:
from nltk.corpus import shakespeare
from collections import defaultdict
import json
hamlet = shakespeare.xml('hamlet.xml')
speeches = hamlet.findall('.//SPEECH')
prevSpeaker = speeches[0].find('SPEAKER').text
afinn = dict(map(lambda k,v: (k,int(v)),
[ line.split('\t') for line in open("AFINN-96.txt") ]))
dict = defaultdict(lambda: defaultdict(lambda: 0))
for speech in speeches:
speaker = speech.find('SPEAKER').text
lines = "\n".join(line.text for line in speech.findall('LINE') if line.text is not None)
sentiment = sum(map(lambda word: afinn.get(word, 0), lines.lower().split()))
dict[speaker][prevSpeaker] += sentiment
prevSpeaker = speaker
print(json.dumps(dict, sort_keys=True, indent=4))
Answer: The [`map`](https://docs.python.org/3/library/functions.html#map) calls the
function with an argument (a list of strings in this case). You need to adjust
the `lambda` to take a parameter:
afinn = dict(map(lambda item: (item[0], int(item[1])),
[ line.split('\t') for line in open("AFINN-96.txt") ]))
Alternative using dict-comprehension:
afinn = {k: int(v) for k, v in
[line.split('\t') for line in open("AFINN-96.txt")]}
BTW, don't use `dict` as a variable name. Overwriting it prevent you to use a
builtin function/type
[`dict`](https://docs.python.org/2/library/functions.html#func-dict).
|
how to import nested module from nested module
Question: Simple question, but could not find the answer. I've following structure:
./lib1:
main.py
./lib2:
__init__.py utils.py
From the root diretory, I'm running:
python lib1/main.py
and in main.py I want to import lib2/utils.py.
adding import lib2/utils.py fails. One solution I found is to add:
~/tmp/root$ cat lib1/main.py
import sys,os
sys.path.append(os.getcwd())
import lib2.utils
lib2.utils.foo()
which is good, but I wander if there is other solution. Thanks.
Answer: Are `lib1` and `lib2` separate modules? If yes, the comment by @BrenBarn
applies: You need to add the top directory (containing `lib1` and `lib2` to
the Python path (e.g using `PYTHONPATH` environment variable or appending to
`sys.path`).
If both `lib1` and `lib2` are part of one module (i.e. there is a
`__init__.py` file in the top directory) you can use relative imports
(<https://docs.python.org/2.5/whatsnew/pep-328.html>).
|
Python csv to list TypeError: cannot perform reduce with flexible type
Question: I am trying to get my test.csv file that looks like this:
hr,mime,active
100,0.41,1
101,0.19,1
102,0.18,1
103,0.6,1
104,0.45,1
105,0.7,1
90,0.4,1
72.43,0.17,1
73,0.17,1
110,0.5,1
120,1,1
130,2,1
72.19,0.5,1
72.68,0.5,1
To look like this:
data = ((100, 0.4, 1), (101, 0.19, 1), (102, 0.18, 1), (103, 0.4, 1),
(104, 0.4, 1), (105, 0.4, 1), (90, 0.4, 1), (72.43, 0.17, 1),
(73, 0.17, 1), (110, 0.5, 1), (120, 0.17, 1), (130, 0.18, 1),
(72.19, 0.5, 1), (72.68, 0.5, 1))
I've tried the following:
import csv
with open('test.csv', 'rb') as f:
reader = csv.reader(f)
data = map(tuple, reader)
But when it is printed it looks like this:
[('hr', 'mime', 'active'), ('100', '0.41', '1'), ('101', '0.19', '1'), ('102', '0.18', '1'), ('103', '0.6', '1'), ('104', '0.45', '1'), ('105', '0.7', '1'), ('90', '0.4', '1'), ('72.43', '0.17', '1'), ('73', '0.17', '1'), ('110', '0.5', '1'), ('120', '1', '1'), ('130', '2', '1'), ('72.19', '0.5', '1'), ('72.68', '0.5', '1')]
Also when I try to run some code with hr I get this error:
TypeError: cannot perform reduce with flexible type
What am I doing incorrectly?
Answer: This should work:
import csv
def convert(line):
return tuple(map(float, line))
with open('test.csv', 'rb') as f:
reader = tuple(csv.reader(f))[1:]
data = tuple(map(convert, reader))
|
Python efficiency for list comparison on numbers >= 10,000
Question: I've been trying to complete a problem from one of the most recent ACM
programming challenges post competition, and have been running into a snag.
The problem states
> Your team has been retained by the director of a competition who supervises
> a panel of judges. The competition asks the judges to assign integer scores
> to competitors – the higher the score, the better. Although the event has
> standards for what score values mean, each judge is likely to interpret
> those standards differently. A score of 100, say, may mean different things
> to different judges.
>
> The director's main objective is to determine which competitors should
> receive prizes for the top positions. Although absolute scores may differ
> from judge to judge, the director realizes that relative rankings provide
> the needed information – if two judges rank the same competitors first,
> second, third, ... then they agree on who should receive the prizes.
>
> Your team is to write a program to assist the director by comparing the
> scores of pairs of judges. The program is to read two lists of integer
> scores in competitor order and determine the highest ranking place (first
> place being highest) at which the judges disagree.
>
> Input to your program will be a series of score list pairs. Each pair begins
> with a single integer giving the number of competitors N, 1 < N < 1,000,000.
> The next N integers are the scores from the first judge in competitor order.
> These are followed by the second judge's scores – N more integers, also in
> competitor order. Scores are in the range 0 to 100,000,000 inclusive. Judges
> are not allowed to give ties, so each judge’s scores will be unique. Values
> are separated from each other by one or more spaces and/or newlines. The
> last score list pair is followed by the end-of-file indicator.
There were example test cases which cover N = 4, and N = 8
> 4
>
> 3 8 6 2
>
> 15 37 17 3
>
> 8
>
> 80 60 40 20 10 30 50 70
>
> 160 100 120 80 20 60 90 135
And the Expected Output: For each score pair, print a line with the integer
representing the highest-ranking place at which the judges do not agree. If
the judges agree on every place, print a line containing only the word
"agree". Use the format below: "Case", one space, the case number, a colon and
one space, and the answer for that case with no trailing spaces.
> Case 1: agree
>
> Case 2: 3
My Code is as follows:
import sys
def calculate(competitors, scores1, scores2):
scores1sort = sorted(scores1, reverse = True)
scores2sort = sorted(scores2, reverse = True)
for x in range(len(scores1)) :
indexed1 = scores1.index(scores1sort[x])
#print ('place: ', x+1, 'Position: ',indexed1+1)
#iterating over the entire length of the sorted lists multiple times takes too long
indexed2 = scores2.index(scores2sort[x])
#print ('place: ', x+1, 'Position: ',indexed2+1)
if indexed2 != indexed1 :
print ( "Case", str(case) + ":", x+1)
return
#run both fors at the same time, compare indexed of scores1 to index of scores2
#if the position(indexed + 1) doesnt match between the two, print the place(x+1) of the disparity
#if match:
#print ("Case " + case +": " + "agree"
#else: print (Case " + case + ": " + index of disagreement
print ("Case", str(case) + ":" , "agree")
scores1 = [];
scores2 = [];
case = 1;
state = 0;
# 0 indicates number of competitors
# 1 indicates judge 1
# 2 indicates judge 2
#for line in sys.stdin:
for line in test.split("\n"):
line = line.strip().split()
if not line:
continue
if state == 0:
#if empty line, error
competitors = int(line[0])
state = 1;
else:
for y in line:
if state == 1:
scores1.append(int(y))
if len(scores1) >= competitors:
state = 2;
elif state == 2:
scores2.append(int(y))
if len(scores2) >= competitors:
state = 0;
#print (competitors, score1, scores2)
calculate(competitors, scores1, scores2);
case += 1;
My code is currently run using a text file containing test input from the
programming contest that was left for us, which includes small test values,
but also includes a set of values with 10,000 competitors.
I have no doubt that the code could complete if given enough time, but the
programming challenge guidelines specified that the code had to run in a
window of time shorter than the current runtime.
As such I'd like to ask for any tips anyone might have on how to optimize my
code for faster execution.
Answer: Providing sample input will help a bit. At this point, seems that you are
loosing time at index method call and memory alloc in range(in case of running
at py2). Try using _enumerate_ to avoid indexing.
|
Trying to add max key to dictionary in another dictionary Error
Question: I am trying to add the max key of the first dictionary in a second but when I
run it shows me a syntax error for `sack{}`. And I can't seem to figure out
why this error occurs. Could anyone explain what the error is? Thank you.
The Code is as below:
#!/usr/bin/python3
import sys
def vault(dataFile):
gem = []
weight = []
value = []
valPerCarat = []
for l in dataFile.readlines():
attribute = l.split(",")
gem.append(str(attribute[0]))
weight.append(float(attribute[1]))
value.append(int(attribute[2]))
valPerCarat.append(int(attribute[2])/float(attribute[1]))
booty = theft_preparation(gem, valPerCarat)
return (booty)
#return(gem, weight, value, valPerCarat)
def theft_preparation(gem, valPerCarat):
loot = dict(zip(gem, valPerCarat)
sack = {}
precious = 0
while (precious =< 5.00):
max (loot, key=loot.get)
precious = dict.get(key, default=None)
precious +=precious
sack.update(key)
del(key)
return (sack)
def main():
fileFound = False
while not fileFound:
fileName = input("File name containing jewel data: ")
try:
dataFile = open(fileName, "r")
fileFound = True
except:
print("Could not find that file -- try again")
knapsackCapacity = 5.00
print (vault(dataFile))
main()
Answer: You are missing a closing parenthesis on the previous line:
loot = dict(zip(gem, valPerCarat)
^ HERE
|
Speeding up selecting sets of 3 nodes that form triangles with given min and max side length
Question: I've got a list of about 60 points, from which I'm generating all possible
combinations of size 3. I'm trying to determine whether any of the 3 points
are within certain distance parameters - that is, not too close to each other,
and not too far from each other (say, no point can be less than 10 units to
the next nearest point, and no point can be more than 100 units from the
furthest point).
I've got code to do so here:
def setPalmCombinations(self):
# Testing confirms that the range of distances is about 5 - 10 for
# minimum distance between points, and anywhere from 150 - 200 for max
# distance between points. 10 and 100 should be reasonable cutoffs.
minDistance = 10
maxDistance = 100
startTime = time.time()
iter = itertools.combinations(self.handContour, 3)
def distanceCheck(points):
A = points[0][0]
B = points[1][0]
C = points[2][0]
AB = np.linalg.norm(A - B)
if not(minDistance < AB < maxDistance): return None
BC = np.linalg.norm(B - C)
if not(minDistance < BC < maxDistance): return None
CA = np.linalg.norm(C - A)
if not(minDistance < CA < maxDistance): return None
return np.array([A, B, C])
a = [distanceCheck(i) for i in iter]
print time.time() - startTime
However, just generating this list of possible combinations takes roughly .4
to .5 seconds, which is far too slow. Is there a way I can optimize this
calculation (or fundamentally redo the algorithm so that it's not simply a
brute force search) so that I can get the time down to about a realtime
calculation (that is, 30ish times a second).
I was thinking about possibly generating a list of the distances between every
point, sorting it, and looking for the points with distances toward the center
of the cutoff range, but I think that may actually be slower than what I'm
doing now.
I'm also trying to figure out some more intelligent algorithm given the fact
that the points are originally stored in order of how they define the contour
- I should be able to eliminate some points before and after each point in the
list when making the combinations ... however, when I tried to generate the
combinations using this fact with Python's default for loops, it ended up
being slower than simply using itertools and generating everything.
Any advice is appreciated.
Thanks!
Answer: You can speedup using numpy. Assuming `comb` is your already calculated
possible combinations, you can easily vectorize distance calculations:
>>> import numpy as np
>>> comb = np.array(list(comb))
>>> dists = comb - np.roll(comb, -1)
# L2 norm
>>> dists = dists**2
dists will be a `Nx3` array containing `AB` `BC` and `CA` distances
respectively.
Mask it with your conditions:
>>> mask = (dists > minDist) & (dists < maxDist)
Find rows where all distances satisfy the conditon:
>>> rows = np.all(mask, axis=1)
return combinations that satisfy conditions:
>>> comb[rows]
UPDATE: Just noticed that this is still quite slow for large N. Here it is the
function that contains all the above steps:
>>> def palm_combinations(points, min_dist=10, max_dist=100):
combs = np.array(list(itertools.combinations(points, 3)))
dists = (combs - np.roll(combs, -1))**2
mask = (dists > min_dist) & (dists < max_dist)
return combs[np.all(mask, axis=1)]
For a sample data of 100 points:
>>> a = np.random.rand(100) * 500
>>> %timeit palm_combinations(a)
10 loops, best of 3: 79.5 ms per loop
The bottleneck of the function is the generation of all the combinations:
>>> %timeit combs = np.array(list(itertools.combinations(a, 3)))
10 loops, best of 3: 69.2 ms per loop
UPDATE 2: It can be speeded-up with a bit more complicated approach. Using
`np.fromiter`:
# Define combinations data type (3 float each combination)
>>> dt = np.dtype('f,f,f')
# Fast numpy array conversion
>>> combs = np.fromiter(itertools.combinations(points, 3), dt)
The function would be something like:
>>> def palm_combinations(points, min_dist=10, max_dist=100):
dt = np.dtype('f,f,f')
combs = np.fromiter(itertools.combinations(points, 3), dt)
combs = combs.view('f').reshape(-1,3)
dists = (combs - np.roll(combs, -1))**2
mask = (dists > min_dist) & (dists < max_dist)
return combs[np.all(mask, axis=1)]
And the speed test:
>>> %timeit palm_combinations(a)
10 loops, best of 3: 29.8 ms per loop
For N=100
|
Easy way to find what item repeated in list
Question: So I have list like
l = [1,2,3,4,4]
If I make a set obvilously I will get
([1,2,3,4])
I need a way to find what item repeated in list and was popped out and I do
not want to use looping. If there is an easy way to do so? I'm using python
2.7
Answer: You'll have to iterate the list, explicitly or implicitly. One way using
standard libraries would be with
[`collections.Counter`](https://docs.python.org/library/collections.html#collections.Counter):
In [1]: from collections import Counter
In [2]: l = [1,2,3,4,4]
In [3]: Counter(l).most_common(1)[0][0]
Out[3]: 4
* * *
A `Counter` object is a dictionary with elements of some iterable as keys and
their respective counts as values:
In [4]: Counter(l)
Out[4]: Counter({4: 2, 1: 1, 2: 1, 3: 1})
Its
[`most_common()`](https://docs.python.org/library/collections.html#collections.Counter.most_common)
method returns a list of items with highest counts:
In [5]: Counter(l).most_common()
Out[5]: [(4, 2), (1, 1), (2, 1), (3, 1)]
The optional argument restricts the length of the returned list:
In [6]: Counter(l).most_common(1)
Out[6]: [(4, 2)]
|
Integrating exisiting Python Library to Anaconda
Question: I've been installing few Library/Toolkit for Python like NLTK, SciPy and NumPy
on my Ubuntu. I would like to try to use Anaconda distribution though. Should
I remove my existing libraries before installing Anaconda?
Answer: There is no need to remove your system Python. Anaconda sits alongside it.
When it installs, it adds a line to your `.bashrc` that adds the Anaconda
directory first in your `PATH`. This means that whenever you type `python` or
`ipython` in the terminal, it will use the Anaconda Python (and the Anaconda
Python will automatically use all the Anaconda Python libraries like numpy and
scipy rather than the system ones). You should leave the system Python alone,
as some system tools use it. The important points are:
* Whichever Python is first on your `PATH` is what gets used when you use Python in the terminal. If you create a conda environment with `conda` and use `source activate` it will put that environment first on the `PATH`.
* Each Python (Anaconda or the system) will use its own libraries and not look at the others (this is not true if you set the `PYTHONPATH` environment variable, but I recommend that you don't).
|
Simultaneously using multiple views in the iPython Notebook
Question: I've got a question I'm hoping someone can help me figure out. I'm trying to
construct two different parallel views in an iPython notebook. The first view
has the processor with ID 0, and the second has all the rest of the
processors. I associate a prefix with each of the views so I can easily run
different things on the different processors.
I launch a background thread that does a long calculation using the processors
in the second view. While that's running in the background, I try to run a
command using the first view, but it doesn't work. I get this error:
ValueError: '' is not in list.
So I'm wondering if there's a way to do what I'm trying to do here, or if this
is unsupported behavior. In short, I'd like to create two different views
using different processors. No processors will be shared between the views.
Then I'd like to be able to run a background task that uses one view, while
simultaneously using the other view for unrelated tasks.
Here's a small example script that results in the error. I'm not sure how to
post a notebook directly, so I've just copied and pasted the python script
generated from it.
# <codecell>
from IPython import parallel
cli = parallel.Client()
# <codecell>
view1 = cli[0]
view1.block = True
view1.activate("_one")
# <codecell>
view2 = cli[1:]
view2.block = True
view2.activate("_two")
# <codecell>
%px_two import time
def backFunc():
for i in range(10):
%px_two time.sleep(5)
%px_two print "In bg thread"
# <codecell>
from IPython.lib import backgroundjobs as bg
bgJob = bg.BackgroundJobManager()
bgJob.new('backFunc()')
# <codecell>
%px_one import time
def foreFunc():
for i in range(10):
%px_one time.sleep(1)
%px_one print "In fg thread"
# <codecell>
foreFunc()
As soon as foreFunc() is run, it gives the error:
ValueError: '<IDS|MSG>' is not in list
Any thoughts? I'd appreciate any ideas anyone has.
Answer: ## Short Answer
The sockets used by the Client are not threadsafe, so you cannot use them
simultaneously in multiple threads. You can use the _cluster_ simultaneously,
but you need to create a separate Client for the background task, which will
have its own set of sockets:
rc = parallel.Client()
rc2 = parallel.Client()
view1 = rc[0]
view2 = rc2[1:]
And the rest should work as expected.
## PS: What's going on
A Client object is mostly an API around a collection of sockets. Each Client
has its own set of sockets, and all Views on one Client use the same sockets.
When you share those sockets across threads, it's possible for one thread to
get part of a message intended for another thread, garbling the message.
Each message is actually a multi-part message zeromq message, sent or received
with
[zmq.Socket.send/recv_multipart](https://github.com/zeromq/pyzmq/blob/v14.4.1/zmq/sugar/socket.py#L275),
which amounts to:
multipart = []
for i in range(nparts):
multipart.append(socket.send/recv())
If two threads are doing this at the same time on the same socket, it's
possible for messages to get interleaved, so instead of getting two messages:
['a1', 'a2', 'a3'], ['b1', 'b2', 'b3']
we get
['a1', 'a2', 'b1', 'b2', 'b3'], ['a3']
causing the problem you are seeing. The simplest fix is to use different
sockets in different threads. An alternate fix is to use
[locking](https://docs.python.org/2/library/threading.html#lock-objects) to
ensure that the multi-part messages are received atomically. Separating
sockets per-thread allows you to avoid the need for locking, but it does
increase the number of sockets you need to use proportionally to the number of
concurrent threads.
## PPS ...but IPython.parallel is async
I will finish by asking why you are using the Background job at all. You do
not need to use threads to accomplish the task you described, because the
Client normally doesn't wait for results from the engines. IPython.parallel is
async by nature, so you don't need to wait for jobs to finish in order to
submit new ones, or do work locally in your interactive session. I generally
do not recommend using `block=True` for anything other than debugging.
|
Django datetime migration error
Question: I don't think anything in my model has changed. I have reverted it back to
times when it was all fully functional and I still get the following errors.
There are my models:
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
# Could create more post classes, or introduce foreign keys. Unsure as of now.
class Post(models.Model):
title = models.CharField(max_length = 140)
body = models.TextField()
date = models.DateTimeField(blank=True)
INTRODUCTION = 'I'
STORIES = 'S'
CATEGORY_CHOICES = (
(STORIES, 'Stories'), # Variable name and display value
(INTRODUCTION, 'Introduce Yourself'),
)
category = models.CharField(max_length=1,
choices=CATEGORY_CHOICES,
default=INTRODUCTION)
def __unicode__(self):
return self.title
class Photo(models.Model):
title = models.CharField(max_length = 140)
photo = models.ImageField(upload_to='user_images', blank=True, null=True)
date = models.DateTimeField(blank=True)
description = models.TextField()
def __unicode__(self):
return self.title
Upon running manage.py migrate I am confronted with the following error.
Having checked the other answers, it seems it was something to do with
datetime being used incorrectly but even if I remove date and the DateTime
field altogether the error still persists. Does anyone have any ideas?
Thank very much for your help.
Operations to perform:
Apply all migrations: contenttypes, admin, sessions, auth, blog
Running migrations:
Applying blog.0007_auto_20141201_0034...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
field,
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 160, in add_field
self._remake_table(model, create_fields=[field])
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 74, in _remake_table
self.effective_default(field)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/schema.py", line 183, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 627, in get_db_prep_save
prepared=False)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1286, in get_db_prep_value
value = self.get_prep_value(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1269, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1171, in get_prep_value
return self.to_python(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1228, in to_python
parsed = parse_datetime(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/dateparse.py", line 70, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or buffer
Here is 'blog.0007...' migration that seems to be failing. To clarify what is
going on I was attempting to add a few attributes in order to tell who posted,
and at what time etc. Clearly something is not going according to plan..
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0006_auto_20141201_0027'),
]
operations = [
migrations.AddField(
model_name='post',
name='created_by',
field=models.ForeignKey(default=0, related_name='created_by', to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
migrations.AddField(
model_name='post',
name='created_on',
field=models.DateTimeField(default=0, auto_now_add=True),
preserve_default=False,
),
migrations.AddField(
model_name='post',
name='edited_by',
field=models.ForeignKey(default=0, related_name='edited_by', to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
migrations.AddField(
model_name='post',
name='edited_on',
field=models.DateTimeField(default=0, auto_now=True),
preserve_default=False,
),
migrations.AddField(
model_name='post',
name='published',
field=models.BooleanField(default=None),
preserve_default=True,
),
]
Answer: I think the problem is here:
DateTimeField(default=0...)
Either use `None` or a `datetime` object
|
Python Include char every x positions
Question: I want to include a char every 2 positions, to be specific, I have a MAC
address this way: 00ffabcafe4c and I want it to be 00:ff:ab:ca:fe:4c
Any idea¿? Thank you in advance
Answer:
import re
x="00ffabcafe4c"
print re.sub(r"(\w{2}(?!$))",r"\1:",x)
Output:`00:ff:ab:ca:fe:4c`
|
Initialization of the kmeans2 in python
Question: I am using `scipy.cluster.vq.kmeans2` which, by definition, initializes the
K-means randomly (given the pre-defined initialization method - random,
points).
Is there a way to make the initialization stable, i.e., for the same initial
centroids to obtain the same clustering results, but without using
`minit='matrix'`? I really don't know what the initial point are but I want
them to be the same for all simulations runs (e.g. for reproducible outputs).
Answer: You can seed the default numpy random number generator, for example:
from numpy import random
random.seed(123)
as shown in the last example
[here](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.vq.kmeans.html)
(which seems to be applicable to `kmeans2` as well).
|
How can i use matplotlib's plot-directive with python-3 in ReadTheDocs?
Question: I'm having a **python-3** project that uses the **[plot-
directive](http://matplotlib.org/sampledoc/extensions.html#inserting-
matplotlib-plots)** to generate and embed matplotlib's diagrams on the fly,
and i'm using [ReadTheDocs](https://readthedocs.org) for auto-generating the
project's documentation.
The plot-directive indeed [works ok in
python-2](https://github.com/rtfd/readthedocs.org/issues/1021), but it
currently fails in python-3.
Specifically the failure i'm getting on the logs of RTD is this:
## Build Standard Error
html
-----
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/wltp/envs/master/lib/python3.4/site-packages/sphinx/application.py", line 325, in setup_extension
mod = __import__(extension, None, None, ['setup'])
ImportError: No module named 'matplotlib'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/wltp/envs/master/lib/python3.4/site-packages/sphinx/cmdline.py", line 253, in main
warningiserror, tags, verbosity, parallel)
File "/home/docs/checkouts/readthedocs.org/user_builds/wltp/envs/master/lib/python3.4/site-packages/sphinx/application.py", line 119, in __init__
self.setup_extension(extension)
File "/home/docs/checkouts/readthedocs.org/user_builds/wltp/envs/master/lib/python3.4/site-packages/sphinx/application.py", line 328, in setup_extension
err)
sphinx.errors.ExtensionError: Could not import extension matplotlib.sphinxext.plot_directive (exception: No module named 'matplotlib')
Extension error:
Could not import extension matplotlib.sphinxext.plot_directive (exception: No module named 'matplotlib')
And the culprit can be traced to matplotlib not being compiled due to mnissing
'freetype' C lib:
## Setup Output
...
requirements
-----
...
BUILDING MATPLOTLIB
matplotlib: yes [1.4.2]
python: yes [3.4.0 (default, Apr 11 2014, 13:05:11) [GCC
4.8.2]]
platform: yes [linux]
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [not found. pip may install it below.]
six: yes [six was not found.]
dateutil: yes [dateutil was not found. It is required for date
axis support. pip/easy_install may attempt to
install it after matplotlib.]
pytz: yes [pytz was not found. pip will attempt to install
it after matplotlib.]
tornado: yes [tornado was not found. It is required for the
WebAgg backend. pip/easy_install may attempt to
install it after matplotlib.]
pyparsing: yes [pyparsing was not found. It is required for
mathtext support. pip/easy_install may attempt to
install it after matplotlib.]
pycxx: yes [Official versions of PyCXX are not compatible
with matplotlib on Python 3.x, since they lack
support for the buffer object. Using local copy]
libagg: yes [pkg-config information for 'libagg' could not
be found. Using local copy.]
freetype: no [The C/C++ header for freetype2 (ft2build.h)
could not be found. You may need to install the
development package.]
OPTIONAL LATEX DEPENDENCIES
dvipng: yes [version 1.14]
ghostscript: yes [version 9.10]
latex: yes [version 3.1415926]
pdftops: no
============================================================================
* The following required packages can not be built:
* freetype
To make the doc-generation pass, I'm forced to "disable" plot-directive by
mocking it out, as [instructed in the RTD FAQ](http://read-the-
docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-
depend-on-c-modules), using the following code in the `./conf.py` file.
I've tried with various combinations of `virtualenv` (with or without site-
package visibility), rtd-specific `requirements.txt`, with no success.
Has anybody found a way to do it?
These are some hints for those willing to dig further into the issue:
* The ["official" list](https://docs.readthedocs.org/en/latest/builds.html#packages-installed-in-the-build-environment) of pre-installed native libraries on RTD
* The [actual `pip-requirements.txt`](https://github.com/rtfd/readthedocs.org/blob/master/pip_requirements.txt) file used to setup the build-server, as found from RTD's sources.
Answer: Since today, the problem is officially solved, according to [rtfd issue
#896](https://github.com/rtfd/readthedocs.org/issues/896). All required
dependencies (matplotlib, scipy and numpy) are also installed for python-3, so
mocking is not necessary anymore.
To make use of it, in the `Advanced settings` make the following choices:
* Check: `Install Project: Install your project inside a virtualenv using setup.py install`
* Select: `Python interpreter: CPython 3.x`
* Check: `Use system packages: Give the virtual environment access to the global site-packages dir`.
...although with a little training, it is easy to write _python-2/3_
compatible code.
|
Advice on code structure to prevent duplication of code (Python, lists)
Question: The scenario at play is that I have an ordered list of items. I want to
convert that list into a single string.
However.
It's not simply a matter of converting each item into a string and
concatenating. I need to do some processing on the list as part of the
conversion.
Here's a rough example:
List:
[1,
2,
3,
0,
1,
9,
-4,
3,
2]
The output I desire would be this:
The total of a group is 6.
The total of a group is 10.
The total of a group is 5.
Here's the code I've written that can do this:
total = 0
result = ""
for item in myList:
if (item <= 0):
result += "The total of a group is %d.\n" % total
total = 0
continue
total += item
# NOTICE THE CODE DUPLICATION HERE...
result += "The total of a group is %d.\n" % total
print result
The problem is I have the `result +=` in the code _twice_. The reason for that
is that we have no guarantee that the last item in the list is an item that is
going to cause the code that actually appends the string to execute. (i.e. we
don't have any guarantee that it's a number 0 or less.)
The obvious solution to this might be "check the last item in the list and if
it's not <= 0 then add a 0 as the last item." This would work on a list of
primitives like this. It however would not work on a list of objects or
complex types, or if the comparison is more involved than simply <= 0.
So the question is: IS there a good way to structure this code such so that I
am not duplicating code, which of course introduces a huge possibility for
errors?
Thanks!
F
Answer: If you're allowed to you can use `itertools.groupby` to group positive
numbers, eg:
from itertools import groupby
data = [1, 2, 3, 0, 1, 9, -4, 3, 2]
group_totals = [sum(g) for k, g in groupby(data, lambda L: L > 0) if k]
for group_total in group_totals:
print 'The sum of a group is', group_total
print 'Total of all groups is', sum(group_totals)
|
Django/Python Chain and Sort Querysets
Question: I have an inventory count that has N locations, this locations needs to be
counted N times, so I have one model for "the location header" and another for
the item list of every header.
I need to chain,sort AND get unique results of the items in N querysets
I have this:
loc_id = request.POST['loc_id'] # the Id of my location pivot
inv_location = InventoryLocations.objects.get(pk=loc_id) # get the location count pivot
inv_locations = InventoryLocations.objects.filter(location=inv_location.location,
inventory=inv_location.inventory) #get all related locations counts
# At this point i can have N inv_locations
count_items = [] # list of items in all inventory counts
for l in inv_locations:
items = InventoryDetails.objects.filter(inventory_location = l) # get items of every count
count_items.append(items)
# Now I have all the items counted in the counts_items array, I need to get from this a single
# list of items Ordered and not repeated
all_items = chain(count_items) <<< IS THIS CORRECT??
sorted_items = sorted(all_items,key=lambda item: item.epc) << THIS GIVE ME ERROR
unique_items = ???
My models are:
class InventoryCount(models.Model):
...nothing important
class InventoryLocation(models.Model):
inventory= models.ForeignKey(InventoryCount)
location= models.ForeignKey(Location)
...
class InventoryDetails(models.Model):
inventory_location= models.ForeignKey(InventoryLocations)
epc = models.CharField(max_length=25, null=True, blank=True)
item= models.ForeignKey(Item)
...
Basically, I need a list of all items counted in all inventoryDetails in the
array sorted by `epc` and not repeated
I'm stuck in here, i dont know if the chain is doing it right and the sort
function gives me an error saying that the item has no 'epc' attribute.
Help plz!
Answer: To solve your immediate problem - assuming that's `itertools.chain`, `chain`
takes multiple iterables. Use `chain(*count_items)` to expand your list of
querysets.
But you can save yourself some trouble by using
`InventoryDetails.objects.filter(inventory_location__in=inv_locations).order_by('epc').distinct()`
\- that'll do the sorting and uniquing in the database rather than you doing
it in your view.
|
Is deep monkeypatching possible in Python?
Question: Take a look at this [changeset for
Django](https://github.com/django/django/commit/be0ad62994a340ad54a0b328771931932a45a899).
I need this functionality, however this patch comes from Django's 1.7 release,
which I can't use in my environment (Python 2.6 only). So for now, I've copied
the `admin_view` method to my code and injected it with a
`admin.site.admin_view = partial(admin_view, admin.site)`.
However, I would like to keep the amount of "forked" code to the minimum and
wondered: is it possible to monkeypatch it, i.e. replace the `self.login`
function with `redirect_to_login` in the execution scope of the `inner`
function of the decorator?
I'm aware that this would be an evil hack, however, I want to find out how far
one can go with Python.
Answer: `django.contrib.admin.sites.inner = yourfunctionhere`
EDIT:
Wow. Kind of embarrassed I let this sit here for so long. I vaguely remember
the article that I was basing the second method off of (see below comment),
but I don't remember enough of the details to find it again. As such, I will
just recommend subclassing `AdminSite`.
* * *
EDIT 2: After some searching, I found this:
[Does an equivalent of override exist for nested
functions?](http://stackoverflow.com/questions/11911544/does-an-equivalent-of-
override-exist-for-nested-functions)
The 'monkey_patch_fn' function does exactly what you want and demonstrates one
possible approach. It may or may not be complete.
My original plan was to modify the function in place by disassembling it, but
I've been running into issues with the attributes being read-only (which I
_think_ was what my original article dealt with... but I can't find it).
* * *
EDIT 3:
Found another way using a module called `byteplay`. Glad I didn't give up so
soon. I like this way _a lot_ more. It might be just as hacky under the hood,
but I trust a full fledged published module to take more care than a random
answer for a specific question.
Anyway. Because I don't feel like looking at the Django code right now, I will
present an example which should suffice. First, the setup.
from byteplay import *
import dis
def test():
def printone():
print 1
printone()
def printtwo():
print 2
dis.dis(test)
The output here will be
2 0 LOAD_CONST 1 (<code object printone at 0x7f72097371b, file "<stdin>", line 1>)
3 MAKE_FUNCTION 0
6 STORE_FAST 0 (printone)
4 9 LOAD_FAST 0 (printone)
12 CALL_FUNCTION 0
15 POP_TOP
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
So, then we use `byteplay` to convert it to a `Code` object, edit it, then
turn it back into normal bytecode.
testcode = Code.from_code(test.__code__)
print testcode.code
The output is:
[(SetLineno, 2), (LOAD_CONST, <byteplay.Code object at 0x7f72096e6a50>), (MAKE_FUNCTION, 0), (STORE_FAST, 'printone'), (SetLineno, 4), (LOAD_FAST, 'printone'), (CALL_FUNCTION, 0), (POP_TOP, None), (LOAD_CONST, None), (RETURN_VALUE, None)]
which mirrors `dis`. So, we juts need to change the `Code` object in the
second tuple and put the new code into the original object.
testcode.code[1] = (LOAD_CONST, Code.from_code(printtwo.__code__))
test.__code__ = testcode.to_code()
dis.dis(test)
test()
The output is a little messy, but we see that:
5 0 LOAD_CONST 1 (<code object printtwo at 0x7fc668476230, file "byteplaytest.py", line 9>)
3 MAKE_FUNCTION 0
6 STORE_FAST 0 (printone)
7 9 LOAD_FAST 0 (printone)
12 CALL_FUNCTION 0
15 POP_TOP
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
2
So, we are loading the `printtwo` function, saving it as a function under the
local variable name `printone` and then the final `2` is just the `printtwo`
function successfully being called.
This should comprehensively illustrate what you need to do. You will need to
use `dis` to determine which line in the bytecode you need to change, but you
should only need to change the `LOAD_CONST`, I think. Granted, I have no tried
this with libraries or anything... but just let me know if there are any
issues.
|
How to parse sentences based on lexical content (phrases) with Python-NLTK
Question: Can Python-NLTK recognize input string and parse it not only based on white
space but also on the content? Say, "computer system" became a phrases in this
situation. Can anyone provide a sample code?
* * *
**input String** : "A survey of user opinion of computer system response time"
**Expected output** : ["A", "survey", "of", "user", "opinion", "of", "computer
system", "response", "time"]
Answer: The technology you're looking for is called multiple names from multiple sub-
fields or sub-sub-fields of linguistics and computing.
* **Keyphrase Extraction**
* From Information Retrieval, mainly use for improving indexing/querying for sear
* Read this recent survey paper: <http://www.hlt.utdallas.edu/~saidul/acl14.pdf>
* (I personally) strongly recommend: <https://code.google.com/p/jatetoolkit/> and of course the famous <https://code.google.com/p/kea-algorithm/> (from the people who brought you WEKA, <http://www.cs.waikato.ac.nz/ml/weka/>)
* For python, possibly <https://github.com/aneesha/RAKE>
* * *
* **Chunking**
* From Natural Language Processing, it's also call shallow parsing,
* Read Steve Abney's work on how it came about: <http://www.vinartus.net/spa/90e.pdf>
* Major NLP framework and toolkits should have them (e.g. OpenNLP, GATE, NLTK* (do note that NLTK's default chunker only works for name entities))
* Stanford NLP has one too: <http://nlp.stanford.edu/projects/shallow-parsing.shtml>
I'll give an example of the NE chunker in NLTK:
>>> from nltk import word_tokenize, ne_chunk, pos_tag
>>> sent = "A survey of user opinion of computer system response time"
>>> chunked = ne_chunk(pos_tag(word_tokenize(sent)))
>>> for i in chunked:
... print i
...
('A', 'DT')
('survey', 'NN')
('of', 'IN')
('user', 'NN')
('opinion', 'NN')
('of', 'IN')
('computer', 'NN')
('system', 'NN')
('response', 'NN')
('time', 'NN')
With named entities:
>>> sent2 = "Barack Obama meets Michael Jackson in Nihonbashi"
>>> chunked = ne_chunk(pos_tag(word_tokenize(sent2)))
>>> for i in chunked:
... print i
...
(PERSON Barack/NNP)
(ORGANIZATION Obama/NNP)
('meets', 'NNS')
(PERSON Michael/NNP Jackson/NNP)
('in', 'IN')
(GPE Nihonbashi/NNP)
You can see it's pretty much flawed, better something than nothing, i guess.
* * *
* **Multi-Word Expression extraction**
* Hot topic in NLP, everyone wants to extract them for one reason or another
* Most notable work by Ivan Sag: <http://lingo.stanford.edu/pubs/WP-2001-03.pdf> and a miasma of all sorts of extraction algorithms and extracted usage from ACL papers
* As much as this MWE is very mysterious and we don't know how to classify them automatically or extract them properly, there's no proper tools for this (strangely the output researchers of MWE wants often can be obtained with Keyphrase Extraction or chunking...)
* * *
* **Terminology Extraction**
* This comes from translation studies where they want the translators to use the correct technical word when translating a document.
* Do note that terminology comes with a cornocopia of ISO standards that one should follows because of the convoluted translation industry that generates billions in income...
* Monolingually, i've no idea what makes them different from terminology extractor, same algorithms, different interface... I guess the only thing about some term extractors is the ability to do it bilingually and produce a dictionary automatically.
* Here's a few tools
* <https://github.com/srijiths/jtopia> and
* <http://fivefilters.org/term-extraction/>
* <https://github.com/turian/topia.termextract>
* <https://www.airpair.com/nlp/keyword-extraction-tutorial>
* <http://termcoord.wordpress.com/about/testing-of-term-extraction-tools/free-term-extractors/>
* Note on tools: there's still no one tool that stands out for term extraction though. And because of then big money involved, it's always some API calls and most code are "semi-open".. mostly closed. Then again, SEO is also big money, possibly it's just a culture thing in translation industry to be super secretive.
* * *
Now back to OP's question.
Q: **Can NLTK extract "computer system" as a phrase?**
A: **Not really**
As shown above, NLTK has pre-trained chunker but it works on name entities and
even so, not all named entities are well recognized.
Possibly OP could try out more radical idea, let's assume that a sequence of
nouns together always form a phrase:
>>> from nltk import word_tokenize, pos_tag
>>> sent = "A survey of user opinion of computer system response time"
>>> tagged = pos_tag(word_tokenize(sent))
>>> chunks = []
>>> current_chunk = []
>>> for word, pos in tagged:
... if pos.startswith('N'):
... current_chunk.append((word,pos))
... else:
... if current_chunk:
... chunks.append(current_chunk)
... current_chunk = []
...
>>> chunks
[[('computer', 'NN'), ('system', 'NN'), ('response', 'NN'), ('time', 'NN')], [('survey', 'NN')], [('user', 'NN'), ('opinion', 'NN')]]
>>> for i in chunks:
... print i
...
[('computer', 'NN'), ('system', 'NN'), ('response', 'NN'), ('time', 'NN')]
[('survey', 'NN')]
[('user', 'NN'), ('opinion', 'NN')]
So even with that solution, seems like trying to get 'computer system' alone
is hard. But if you think for a bit seems like getting 'computer system
response time' is a more valid phrase than 'computer system'.
Do not that all interpretations of computer system response time seem valid:
* [computer system response time]
* [computer [system [response [time]]]]
* [computer system] [response time]
* [computer [system response time]]
And many many more possible interpretations. So you've got to ask, what are
you using the extracted phrase for and then see how to proceed with cutting
long phrases like 'computer system response time'.
|
Python XML Parsing can't find children of children
Question: I'm trying to parse XML returned as a string from a http get request. I need
to get a specific link inside the XML structure but for some reason I can't
get to the link I need. I tried `**enumerating**` the XML and printing
**`child.attrib`** but the link I need is not displaying.
I need to find an element that is a child of a child and the element is called
Vm, then I need to get the .attrib of that element.
Thus, I did some more research and tried finding the XML I needed by node name
The XML structure is:
<vapp>
<link></link>
<othertags></othertags>
<Children>
<Vm href='link I need'>
<other tag options>
</other tag options>
</vm>
</Children>
</vapp>
python code:
for i, child in enumerate(vappXML):
if 'href' in child.attrib and 'name' in child.attrib:
vapp_url = child.attrib['href']
r=requests.get(vapp_url, headers = new_headers)
vmlinkXML = fromstring(r.content)
for VM in vmlinkXML.findall('Children'):
print VM
for i, child in enumerate(vmlinkXML):
if 'vm-' in child:
print child.attrib
if 'href' in child.attrib:
vm_url = child.attrib['href']
if 'vm-' in vm_url:
print vm_url
I can't get to the url no matter how I try. I only get the main child of vApp
it never parses the tag, or rather my code never goes further than the first
child of the vapp and I don't know why.
I guess I wasn't clear. I'm parsing vCloud Director Rest API XML that is
returned as a string. The first level is the vApp link which is essentially a
container for VMs. I need to get the VM link under each vApp. The first one
will select vApp links and query them.
Once it does a get request on the vApp link it gets the next level of XML data
which is the structure I put above. so it passes the initial XML statement and
returns vApp information.
Even when I print out every child.attrib fom vmlinkXML the link with vm doesnt
get printed. however, If I just print r.content the link is there. Its almost
like the XML parser doesn't see the tag.
**I'm using Pythons XML.etree**
from lxml import etree
from xml.etree.ElementTree import XML, fromstring, tostring
**So to be clear the structure is:**
to get the vApp Links /api/admin/extension/vapps/query then the returned
information will contain links to each vapp in vCloud. then I call the vApp
link <https://vcloud.test.co/api/vApp/vapp-3b4980e7-c5ab-4462-9cfe-
abc6292c15748> and it will return a structure similar to this:
<vapp>
<link></link>
<othertags></othertags>
<Children>
<Vm href='link I need'>
<other tag options>
</other tag options>
</vm>
</Children>
</vapp>
Tag contains the next level of link I need to query. However the XML parser
with child.attrib never outputs anything under the tag.
Answer: Solved***
r=requests.get(url + '/api/admin/extension/vapps/query', headers = new_headers)
vappXML = fromstring(r.content)
for i, child in enumerate(vappXML):
if 'href' in child.attrib and 'name' in child.attrib:
vapp_url = child.attrib['href']
r=requests.get(vapp_url, headers = new_headers)
DOMTree = parseString(r.content)
vmElements = DOMTree.documentElement
VMS = vmElements.getElementsByTagName("Vm")
for vm in VMS:
if vm.hasAttribute("href"):
vm_link = vm.getAttribute("href")
print vm_link
|
Is it possible to slice keys in h5py using python 3, without forming a list?
Question: I am using h5py to read in data from an HDF5 file, and have found that code
which worked using Python 2 does not work using Python 3. The file is
formatted such that 2D frames of data are present as distinct datasets, which
I want to read into a 3D array. The file structure looks like this:
file.h5
|- groupname (group)
|- frame1 (dataset)
|- frame2 (dataset)
...
To read the frames into a 3D array, I have to access the first dataset to get
its shape and type information. Because I don't actually know the _exact_ name
for each frame, the code I had been using to access the first frame looked
like this:
import h5py
fid = h5py.File('file.h5', 'r')
datagroup = fid['groupname']
dataset0 = datagroup[datagroup.keys()[0]]
However, the [documentation](http://docs.h5py.org/en/latest/high/group.html)
for h5py says
> "When using h5py from Python 3, the keys(), values() and items() methods
> will return view-like objects instead of lists."
The view objects support iteration but not slicing. So to avoid an error I had
to change that line to the following:
dataset0 = datagroup[ [k for k in datagroup.keys()][0] ]
which artificially constructs a temporary list and then grabs its first
element. To me this looks awful. Is there a better way to do this?
Answer: `Group` supports returning an iterator but is not directly iterable. That
leads to the following:
dataset0 = datagroup[next(iter(datagroup))]
|
Python multithreading "ping"
Question: I have been trying to make a python script that will ask you for a IP and have
many simultaneous PING i shall do.
But it seems like i can only run one PING at a time
I'm running on OSX
import _thread
import os
import time
def main():
threadnbr = 0
ip = str(input("Input the ip adresse to play with? "))
threads = int(input("Have many threads? "))
check(ip)
if check(ip) == 0:
print("It is up")
else:
print("Is is down")
thread(ip, threads, threadnbr)
def thread(ip, threads, threadnbr):
while threads > threadnbr:
_thread.start_new_thread(dos(ip))
threadnbr = threadnbr + 1
else:
print(threadnbr, " started")
def check(ip):
response = os.system("ping -c 1 " + ip)
return response
def dos(ip):
os.system("ping -i 0.1 -s 8000 " + ip)
print("1")
main()
Answer:
_thread.start_new_thread(dos(ip))
You are not providing the arguments correctly here - your code is running in
the main thread. See [the
documentation](https://docs.python.org/2/library/thread.html#thread.start_new_thread)
for more details.
Also, you should be using `threading` instead of `thread`. That module is
deprecated.
If `dos` means `DoS`, I sincerely hope you're doing this for educational
purposes against your own infrastructure.
|
Unusual output using map() and filter() in Python
Question: I'm trying to learn how to use the map() and filter() functions in Python but
when I try and use them in visual studio, I'm getting an unusual output for
each one. I know the code is probably wrong, but I can't see what it's
outputting which is making it hard to sort out!
Thanks in advance
filter()
import functools
f = ["List", "of", "super", "crazily", "long", "words"]
new = lambda a, b: a if (len(a) > b) else b
print (filter(new, f))
Serves: filter object at 0x029AD5F0
map()
import functools
f = ["List", "of", "super", "crazily", "long", "words"]
map_loop = map((lambda x: len(x)), f)
print (type(map_loop), map_loop)
Serves: class 'map', map object at 0x0243D5D0
Answer: you need to use `list` like this:
print (type(map_loop), list(map_loop))
demo:
>>> f = ["List", "of", "super", "crazily", "long", "words"]
>>> print(list(map(len,f))) # no need of lembda, `len` is enough
[4, 2, 5, 7, 4, 5]
|
Universal iteration over all elements of: nested list, numpy array, pandas dataframe
Question: I am trying to write a function that applies to each element of the argument
provided, whether the argument is a nested python list, a numpy array or a
pandas dataframe or series.
Example: (not working)
import numpy as np
import pandas as pd
a = [[1,2,3,4,5], [6,7,8,9,10]]
b = np.array(a)
c = pd.DataFrame(a)
def printElement(x):
print x
def iterateOverElements(arg):
for element in arg:
printElement(element)
iterateOverElements(a)
iterateOverElements(b)
iterateOverElements(c)
Desired output: printing 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 in new lines for each
of the three calls. (Order is unimportant.)
True output:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[1 2 3 4 5]
[ 6 7 8 9 10]
0
1
2
3
4
As expected, the nested list iterates over its sub-lists, the numpy array over
its rows and the pandas dataframe over its column labels.
**Is there a concise way to achieving my goal, or do I need to check the
instance of the argument and construct different iteration codes for different
types?** If I need to type-check, is there a way of importing e.g. pandas just
to type-check and find out that it was a nested list after all?
Again, I do not care about the order in which I iterate over the elements,
just that it is really the "basic" elements rather than some sub-collection.
Answer: I would suggest something like this:
def printElements(arg):
x = arg.iterrows() if isinstance(arg, pd.DataFrame) else arg
try:
for element in x:
printElements(element)
except:
print x
|
How to patch a constant in python
Question: I have two different modules in my project. One is a config file which
contains
LOGGING_ACTIVATED = False
This constant is used in the second module (lets call it main) like the
following:
if LOGGING_ACTIVATED:
amqp_connector = Connector()
In my test class for the main module i would like to patch this constant with
the value
True
Unfortunately the following doesn't work
@patch("config.LOGGING_ACTIVATED", True)
nor does this work:
@patch.object("config.LOGGING_ACTIVATED", True)
Does anybody know how to patch a constant from different modules?
Answer: If the `if LOGGING_ACTIVATED:` test happens at the _module level_ , you need
to make sure that that module is not yet imported first. Module-level code
runs just once (the first time the module is imported anywhere), you cannot
test code that won't run again.
If the test is in a function, note that the global name used is
`LOGGING_ACTIVATED`, _not_ `config.LOGGING_ACTIVATED`. As such you need to
patch out `main.LOGGING_ACTIVATED` here:
@patch("main.LOGGING_ACTIVATED", True)
as that's the actual reference you wanted to replace.
Also see the [_Where to patch_
section](https://docs.python.org/3/library/unittest.mock.html#where-to-patch)
of the `mock` documentation.
You should consider refactoring module-level code to something more testable.
Although you can force a reload of module code by deleting the module object
from the `sys.modules` mapping, it is plain cleaner to move code you want to
be testable into a function.
So if your code now looks something like this:
if LOGGING_ACTIVATED:
amqp_connector = Connector()
consider using a function instead:
def main():
global amqp_connector
if LOGGING_ACTIVATED:
amqp_connector = Connector()
main()
or produce an object with attributes even.
|
save url as a file name in python
Question: Firstly, I'm pretty new in python, please leave a comment as well if you
consider to down vote
I have a url such as
http://example.com/here/there/index.html
now I want to save a file and its content in a directory. I want the name of
the file to be :
http://example.com/here/there/index.html
but I get error, I'm guessing that error is as the result of `/` in the url
name.
This is what I'm doing at the moment.
with open('~/' + response.url, 'w') as f:
f.write(response.body)
any ideas how I should do it instead?
Answer: You could use the reversible
[base64](https://docs.python.org/2/library/base64.html) encoding.
>>> import base64
>>> base64.b64encode('http://example.com/here/there/index.html')
'aHR0cDovL2V4YW1wbGUuY29tL2hlcmUvdGhlcmUvaW5kZXguaHRtbA=='
>>> base64.b64decode('aHR0cDovL2V4YW1wbGUuY29tL2hlcmUvdGhlcmUvaW5kZXguaHRtbA==')
'http://example.com/here/there/index.html'
or perhaps [binascii](https://docs.python.org/2/library/binascii.html)
>>> binascii.hexlify(b'http://example.com/here/there/index.html')
'687474703a2f2f6578616d706c652e636f6d2f686572652f74686572652f696e6465782e68746d6c'
>>> binascii.unhexlify('687474703a2f2f6578616d706c652e636f6d2f686572652f74686572652f696e6465782e68746d6c')
'http://example.com/here/there/index.html'
|
Python unittesting: Test whether two angles are almost equal
Question: I want to test a function that outputs a heading in degrees, which is a number
in the interval [0, 360). Since the result is a floating-point number,
comparing the actual result against the expected with `unittest.assertEqual()`
does not work. `unittest.assertAlmostEqual()` is better since it provides a
tolerance. This approach works for heading that are not close to 0 degrees.
Question: What is the correct way to test for headings whose expected value is
0 degrees? `assertAlmostEquals()` would only include angles that are slightly
larger than 0 degrees, but would miss those that are slightly smaller than 0,
i.e. 360 degrees...
Answer: You can use the squared Euclidian distance between two points on the unit
circle and the law of cosines to get the absolute difference between two
angles:
from math import sin, cos, acos
from unittest import assertAlmostEqual
def assertAlmostEqualAngles(x, y, **kwargs):
c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
angle_diff = acos((2.0 - c2)/2.0) # a = b = 1
assertAlmostEqual(angle_diff, 0.0, **kwargs)
This works with radians. If the angle is in degrees, you must do a conversion:
from math import sin, cos, acos, radians, degrees
from unittest import assertAlmostEqual
def assertAlmostEqualAngles(x, y, **kwargs):
x,y = radians(x),radians(y)
c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
angle_diff = degrees(acos((2.0 - c2)/2.0))
assertAlmostEqual(angle_diff, 0.0, **kwargs)
|
Dates ( pi-Day )
Question: I think everyone kwows when it's pi-Day (If you don't know it's on 14 March
each year). When you have a result in python like:
(2016, 4, 4)
(This stands for the April 4, 2016). How can I find in a fast way when it's
the next pi-Day. In this example the answer would be:
(2017, 3, 14)
Is there any formula I can use? Many thanks!
Answer: Using the [`datetime` module](https://docs.python.org/2/library/datetime.html)
you'd:
1. Get todays date
2. Get this years Pi-day (take the year from today's date)
3. If this date is in the past, add one year
In code:
from datetime import date
def next_pi_date():
today = date.today()
pi_date = date(today.year, 3, 14)
if pi_date < today:
pi_date = pi_date.replace(year=pi_date.year + 1)
return pi_date
Demo:
>>> from datetime import date
>>> def next_pi_date():
... today = date.today()
... pi_date = date(today.year, 3, 14)
... if pi_date < today:
... pi_date = pi_date.replace(year=pi_date.year + 1)
... return pi_date
...
>>> next_pi_date()
datetime.date(2015, 3, 14)
|
Hive with python transform function: "cannot recognize input near 'transform'" error
Question: I have a Hive table that tracks the status of an object moving through stages
of a process. The table looks like this:
hive> desc journeys;
object_id string
journey_statuses array<string>
Here's a typical example of a record:
12345678 ["A","A","A","B","B","B","C","C","C","C","D"]
The records in the table were generated using Hive 0.13's `collect_list` and
the statuses have an order (if order wasn't important, I would have used
`collect_set`). For each object_id, I'd like to abbreviate the journey to
return the journey statuses in the order that they appear.
I wrote a quick Python script that reads from stdin:
#!/usr/bin/env python
import sys
import itertools
for line in sys.stdin:
inputList = eval(line.strip())
readahead = iter(inputList)
next(readahead)
result = []
for id, (a, b) in enumerate(itertools.izip(inputList, readahead)):
if id == 0:
result.append(a)
if a != b:
result.append(b)
print result
I planned to use this in a Hive `transform` call. It seems to work when run
locally:
$ echo '["A","A","A","B","B","B","C","C","C","C","D"]' | python abbreviate_list.py
['A', 'B', 'C', 'D']
However, when I add the file and try to execute within Hive, an error is
returned:
hive> add file abbreviateList.py;
Added resource: abbreviateList.py
hive> select
> object_id,
> transform(journey_statuses) using 'python abbreviateList.py' as journey_statuses_abbreviated
> from journeys;
NoViableAltException( ... wall of Java error messages ... )
FAILED: ParseException line 3:2 cannot recognize input near 'transform' '(' 'journey_statuses' in select expression
Can you see what I'm doing wrong?
Answer: Apparently you can't SELECT other fields that are not in the transform (in
your example, object_id). This other SO question seems to indirectly address
that:
[How can select a column and do a TRANSFORM in
Hive?](http://stackoverflow.com/questions/16320185/how-can-select-a-column-
and-do-a-transform-in-hive)
You could in theory modify your Python to accept the object_id as an input
parameter and make it a passthrough to another output field if you need it to
be included in the output.
|
replace part of path - python
Question: Is there a quick way to replace part of the path in python?
for example:
old_path='/abc/dfg/ghi/f.txt'
I don't know the beginning of the path (`/abc/dfg/`), so what I'd really like
to tell python to keep everything that comes after `/ghi/` (inclusive) and
replace everything before `/ghi/` with `/jkl/mno/`:
>>> new_path
'/jkl/mno/ghi/f.txt/'
Answer:
>>> import os.path
>>> old_path='/abc/dfg/ghi/f.txt'
First grab the relative path from the starting directory of your choice using
[`os.path.relpath`](https://docs.python.org/2/library/os.path.html#os.path.relpath)
>>> rel = os.path.relpath(old_path, '/abc/dfg/')
>>> rel
'ghi\\f.txt'
Then add the new first part of the path to this relative path using
[`os.path.join`](https://docs.python.org/2/library/os.path.html#os.path.join)
>>> new_path = os.path.join('jkl\mno', rel)
>>> new_path
'jkl\\mno\\ghi\\f.txt'
|
How can I turn off error printing in libxml2.parseDoc?
Question: When using the library, I expect an exception for bad input, but I do not want
it to start printing things to stderr. How can I configure it to not print
anything?
Here's an example from the REPL of what I am talking about:
>>> import libxml2
>>> try:
... libxml2.parseDoc('junk')
... except:
... pass
...
Entity: line 1: parser error : Start tag expected, '<' not found
junk
^
>>>
With that code I expect to see nothing printed out. I found [this SO
post](http://stackoverflow.com/questions/2801315/disable-debug-output-in-
libxml2-and-xmlsec) about a similar issue with the c++ xmllib2, but I don't
see a way to do that with the python version.
Answer: You can **disable error logging** for `libxml2` by registering a silent error
handler:
def noerr(ctx, str):
pass
libxml2.registerErrorHandler(noerr, None)
Source: <http://xmlsoft.org/python.html>
|
Why doesn't my idea work in python2?
Question: Here is an idea for a dict subclass that can mutate keys. This is a simple
self contained example that's just like a `dict` but is case insensitive for
`str` keys.
from functools import wraps
def key_fix_decorator(f):
@wraps(f)
def wrapped(self, *args, **kwargs):
if args and isinstance(args[0], str):
args = (args[0].lower(),) + args[1:]
return f(self, *args, **kwargs)
return wrapped
class LowerDict(dict):
pass
for method_name in '__setitem__', '__getitem__', '__delitem__', '__contains__', 'get', 'pop', 'setdefault':
new_method = key_fix_decorator(getattr(LowerDict, method_name))
setattr(LowerDict, method_name, new_method)
**dev note:** if you copy my code for your own uses, you should implement
`LowerDict.__init__` to check for any key collisions - I haven't bothered to
include that for the purposes of this question
On python3 it all seems to works fine:
>>> d = LowerDict(potato=123, spam='eggs')
>>> d['poTATo']
123
>>> d.pop('SPAm')
'eggs'
>>> d['A']
# KeyError: 'a'
In python2 it doesn't even import, here is the traceback:
File "/tmp/thing.py", line 15, in <module>
new_method = key_fix_decorator(getattr(LowerDict, method_name))
File "/tmp/thing.py", line 4, in key_fix_decorator
@wraps(f)
File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'wrapper_descriptor' object has no attribute '__module__'
What could be the problem? I can't see any version-specific code except for
the `str`/`basestring` thing, which is just a minor detail not a code-breaking
issue.
Answer: The `functools.wraps()` version in Python 3 can handle function objects with
some of the attributes it copies across missing; the one in Python 2 cannot.
This is was because [issue #3445](http://bugs.python.org/issue3445) was fixed
only for Python 3; the methods of `dict` are defined in C code and have no
`__module__` attribute.
Omitting the `@wraps(f)` decorator makes everything work in Python 2 too:
>>> def key_fix_decorator(f):
... def wrapped(self, *args, **kwargs):
... if args and isinstance(args[0], str):
... args = (args[0].lower(),) + args[1:]
... return f(self, *args, **kwargs)
... return wrapped
...
>>> class LowerDict(dict):
... pass
...
>>> for method_name in '__setitem__', '__getitem__', '__delitem__', '__contains__', 'get', 'pop', 'setdefault':
... new_method = key_fix_decorator(getattr(LowerDict, method_name))
... setattr(LowerDict, method_name, new_method)
...
>>> d = LowerDict(potato=123, spam='eggs')
>>> d['poTATo']
123
>>> d.pop('SPAm')
'eggs'
>>> d['A']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in wrapped
KeyError: 'a'
You can replicate _enough_ of what `wraps` does manually:
def key_fix_decorator(f):
def wrapped(self, *args, **kwargs):
if args and isinstance(args[0], str):
args = (args[0].lower(),) + args[1:]
return f(self, *args, **kwargs)
wrapped.__name__ = f.__name__
wrapped.__doc__ = f.__doc__
return wrapped
or limit the attributes that `wraps` tries to copy across:
def key_fix_decorator(f):
@wraps(f, assigned=('__name__', '__doc__'))
def wrapped(self, *args, **kwargs):
if args and isinstance(args[0], str):
args = (args[0].lower(),) + args[1:]
return f(self, *args, **kwargs)
return wrapped
You don't really need to update `__module__` attribute here; that is mostly
useful only for introspection.
|
Migration error with Django 1.7.1
Question: I'm getting an error when performing a migration after introducing a new app
(django-allauth). I'm not sure what else to try in order to fix the error.
I've tried a few things but they don't seem to help unfortunately.
when running **manage.py migrate** :
File "D:\Python27\Lib\site-packages\django\db\migrations\state.py", line 71,
in render raise
InvalidBasesError("Cannot resolve bases for %r\nThis can happen if you are inheriting
models from an app with migrations (e.g. contrib.auth)\n in an app with no migrations;
see https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies for more" %
new_unrendered_models)
django.db.migrations.state.InvalidBasesError: Cannot resolve bases for
[<ModelState: 'blog.BlogPage'>, <ModelState: 'blog.BlogIndexPage'>]
This can happen if you are inheriting models from an app with migrations
(e.g. contrib.auth) in an app with no migrations; see
https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies for more
**models.py**
from django.db import models
from wagtail.wagtailcore.models import Page, Orderable
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel ,MultiFieldPanel,InlinePanel, PageChooserPanel
from modelcluster.fields import ParentalKey
class BlogPage(Page):
body = RichTextField()
date = models.DateField("Post date")
indexed_fields = ('body', )
search_name = "Blog Page"
BlogPage.content_panels = [
FieldPanel('title', classname="full title"),
FieldPanel('date'),
FieldPanel('body', classname="full"),
]
class LinkFields(models.Model):
link_page = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
related_name='+'
)
panels = [
PageChooserPanel('link_page'),
]
class Meta:
abstract = True
class RelatedLink(LinkFields):
title = models.CharField(max_length=255, help_text="Link title")
panels = [
FieldPanel('title'),
MultiFieldPanel(LinkFields.panels, "Link"),
]
class Meta:
abstract = True
class BlogIndexPageRelatedLink(Orderable, RelatedLink):
page = ParentalKey('blog.BlogIndexPage', related_name='related_links')
class BlogIndexPage(Page):
intro = models.CharField(max_length=256)
indexed_fields = ('body', )
search_name = "Blog Index Page"
BlogIndexPage.content_panels = [
FieldPanel('title', classname="full title"),
FieldPanel('intro', classname="full"),
InlinePanel(BlogIndexPage, 'related_links', label="Related links"),
]
**What I've tried so far:**
1. followed the advice here: <http://stackoverflow.com/a/25858659> however this has not changed anything for me.
2. I've also tried <https://code.djangoproject.com/ticket/22051#comment:12> with no success.
**note:** makemigrations runs (no changes detected) but migrate fails.
**platform setup** : This is currently on Django 1.7.1 on a Windows box.
django-allauth runs successfully within other apps on this box.
**Has anyone come across this before and is there a fix?**
thanks in advance
**\---issued command sequence below:**
(env) D:\git\rebootv2.1\blog>python manage.py migrate
D:\Python27\Lib\site-packages\treebeard\mp_tree.py:102: RemovedInDjango18Warning: `MP_NodeManager.get_query_set` method
should be renamed `get_queryset`.
class MP_NodeManager(models.Manager):
Operations to perform:
Synchronize unmigrated apps: account, allauth, modelcluster, blog, compressor, facebook, wagtailsnippets, socialaccount
Apply all migrations: core, wagtailusers, wagtailembeds, wagtailadmin, sessions, admin, wagtailcore, sites, auth, contenttypes, wagtaildocs, taggit, wagtailsearch, wagtailforms, wagtailredirects, wagtailimages
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying sites.0001_initial...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "D:\Python27\Lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line
utility.execute()
File "D:\Python27\Lib\site-packages\django\core\management\__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Python27\Lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "D:\Python27\Lib\site-packages\django\core\management\base.py", line 338, in execute
output = self.handle(*args, **options)
File "D:\Python27\Lib\site-packages\django\core\management\commands\migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "D:\Python27\Lib\site-packages\django\db\migrations\executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "D:\Python27\Lib\site-packages\django\db\migrations\executor.py", line 91, in apply_migration
if self.detect_soft_applied(migration):
File "D:\Python27\Lib\site-packages\django\db\migrations\executor.py", line 135, in detect_soft_applied
apps = project_state.render()
File "D:\Python27\Lib\site-packages\django\db\migrations\state.py", line 71, in render raise InvalidBasesError("Cannot resolve bases for %r\nThis can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)\n in an app with no migrations; see https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies for more" % new_unrendered_models)
django.db.migrations.state.InvalidBasesError: Cannot resolve bases for [<ModelState: 'blog.BlogPage'>, <ModelState: 'blog.BlogIndexPage'>]
This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)
in an app with no migrations; see https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies for more
(env) D:\git\rebootv2.1\blog>python manage.py makemigrations
D:\Python27\Lib\site-packages\treebeard\mp_tree.py:102: RemovedInDjango18Warning: `MP_NodeManager.get_query_set` method
should be renamed `get_queryset`.
class MP_NodeManager(models.Manager):
No changes detected
**[what fixed this for me]** \- ended up being a problem with sequencing I
guess....
1. disable all of the allauth apps within INSTALLED_APPS in settings.py
2. run manage.py migrate enable all of the allauth apps and disable the wagtail app that was generated for the project (e.g. blog)
3. run manage.py migrate again enable both sets of apps in INSTALLED_APPS
4. run manage.py migrate again
seems to be happy now.
hope this helps someone and saves them some time!
Answer: ended up being a problem with sequencing I guess....
1. disable all of the allauth apps within INSTALLED_APPS in settings.py
2. run manage.py migrate enable all of the allauth apps and disable the wagtail app that was generated for the project (e.g. blog)
3. run manage.py migrate again enable both sets of apps in INSTALLED_APPS
4. run manage.py migrate again
seems to be happy now.
hope this helps someone and saves them some time!
|
Read a list of file names without typing them manually
Question: I have a python code inside which the name of file is received with input
command
fileName = input("please enter the file name")
My purpose is to write a script to run this file. But I do not want to sit
there and input each file name manually. Is it possible to give the fileName
as a command line argument or so while running.
Edit: More explanation: I am given python codes with the above line inside,
which I should run on some sample input. I do not want to change the file or
sample input only want to run the file on the input automatically. The reason
is that there are many files to be checked and many sample inputs.
Answer: You have a few options, really.
# Redirect stdin to a file
One you might not have considered is leaving your program the way it is,
creating a text file with a list of file names, and then redirecting the
standard input to the file. Let's name the file `myfilelist.txt`. The file
would just be a list:
~/file1.txt
~/file2.txt
Or on Windows:
C:\file1.txt
C:\file2.txt
Then you would call your program like so:
python ./myprogram.py < ./myfilelist.txt
Here, the `<` character tells the operating system to use the contents of
`myfilelist.txt` instead of waiting for you to type. This does assume that
your program loops and continues to prompt for multiple files.
If it only accepts one file at a time, then you might consider...
# Using a script
You can write a script that calls your program a bunch of times separately,
each time with a different file name. A bash script on Linux might look like
this:
#!/bin/bash
echo '~/file1.txt' | python ./myprogram.py
echo '~/file2.txt' | python ./myprogram.py
Or a batch file on Windows:
echo C:\file1.txt | python .\myprogram.py
echo C:\file2.txt | python .\myprogram.py
Here, we execute the command `echo` to make the system "print" out some text,
and then we use the `|` (pipe) to tell the system to use `echo`'s output as
the other program's input (instead of printing the text to the screen).
# List file argument
Another option is to create an argument to your program that accepts a
_single_ file path, and then use the contents of that file as a list of files
to process. This requires modifying your program.
A quick and dirty way of doing that in code:
import sys
if '__main__' == __name__:
list_file = sys.argv[1]
with open(list_file) as f:
for r in f:
do_my_other_code(r)
Then you'd call it like this:
python ./myprogram.py ./myfilelist.txt
Look into [`argparse`](https://docs.python.org/3.3/library/argparse.html),
[`getopt`](https://docs.python.org/2/library/getopt.html), or similar to make
this cleaner.
# Argument list
You could just list all the files as part of the original command. Your code
would look something like this:
import sys
if '__main__' == __name__:
for a in sys.argv[1:]:
do_my_other_code(a)
(Note that `sys.argv[1:]` is what's called a "slice". Look that up if you're
unfamiliar with them.)
Then you would call it like this:
python ./myprogram.py ~/file1.txt ~/file2.txt
I don't especially like this option for your case because your question
suggests you have a fairly large list of files. Typing the command would be
tedious and error prone. You also wouldn't have the list saved anywhere if the
computer crashed or something. But it'd be fine for just a few files.
# Other
There are lots of ways to do things like this. These are just a few fairly
simple options. The _best_ one will depend on your exact usage.
|
How to ensure two line breaks between each paragraph in python
Question: I am reading txt files into python, and want to get paragraph breaks
consistent. Sometimes there is one, two, three, four... occasionally several
tens or hundreds of blank lines between paragraphs.
It is obviously easy to strip out all the breaks, but I can only think of
"botched" ways of making everything two breaks (i.e. a single blank line
between each paragraph). All i can think of would be specifying multiple
strips/replaces for different possible combinations of breaks... which gets
unwieldy when the number of breaks is very large ... or iterativly removing
excess breaks until left with two, which I guess would be slow and not
particularly scalable to many tens of thousands of txt files ...
Is there a moderately fast to process [/simple] way of achieving this?
Answer:
import re
re.sub(r"([\r\n]){2,}",r"\1\1",x)
You can try this.Here `x` will be your string containing all the paragraphs.
|
from pygtk_image import * ERROR
Question: I am new to python and I have question, please. I have python 2.7.3 and I have
installed gtk to make GUI. I found a code and I want to test it but I got this
error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from pygtk_image import *
ImportError: No module named pygtk_image
what does this mean? I searched in the internet about how to install
pygtk_image, but I did not find a solution. Thank you in advance.
Answer: Maybe you haven't downloaded all necessary modules for your code.
Try this:
<https://github.com/jayrambhia/SimpleCVexamples/blob/master/pygtk_image/pygtk_image.py>
Maybe it is the module you are missing.
|
How to make 1d array multiplied by 2d array resulting in 3d array for python
Question: I am worrying that this might be a really stupid question. However I can't
find a solution. I want to do the following operation in python without using
a loop, because I am dealing with large size arrays. Is there any suggestion?
import numpy as np
a = np.array([1,2,3,..., N]) # arbitrary 1d array
b = np.array([[1,2,3],[4,5,6],[7,8,9]]) # arbitrary 2d array
c = np.zeros((N,3,3))
c[0,:,:] = a[0]*b
c[1,:,:] = a[1]*b
c[2,:,:] = a[2]*b
c[3,:,:] = ...
...
...
c[N-1,:,:] = a[N-1]*b
Answer: To avoid Python-level loops, you could use `np.newaxis` to expand `a` (or
None, which is the same thing):
>>> a = np.arange(1,5)
>>> b = np.arange(1,10).reshape((3,3))
>>> a[:,None,None]*b
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[ 2, 4, 6],
[ 8, 10, 12],
[14, 16, 18]],
[[ 3, 6, 9],
[12, 15, 18],
[21, 24, 27]],
[[ 4, 8, 12],
[16, 20, 24],
[28, 32, 36]]])
Or
[`np.einsum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html),
which is overkill here, but is often handy and makes it very explicit what you
want to happen with the coordinates:
>>> c2 = np.einsum('i,jk->ijk', a, b)
>>> np.allclose(c2, a[:,None,None]*b)
True
|
Reading changes with dbf library in python
Question: I am trying to make a program that takes changes in a `dbf` file then uploads
them. I have got it to read the `dbf` file and upload them to a `mysql`
database but its a 50 minuite upload. I have tried to get it to only upload
fields that have been changed. The problem I have is that it seems i need to
close and re-open the `dbf` file. If someone makes a change whilst its doing
this, it doesnt notice theres been a change.
Is there a better/right way of doing this:
import time
import dbf
import MySQLdb
import os
source_path = r"\\path\to\file"
file_name = "\\test.Dbf"
print "Found Source DBF"
source = dbf.Table(source_path + file_name)
source.open()
print "Opened DBF"
updated = list(source)
print "Copied Source"
db = MySQLdb.connect(host = "myHost.com", port=3306, user = "user", passwd = "pass", db = "database")
cur = db.cursor()
print "Connected to database"
try:
cur.execute("DROP TABLE IF EXISTS dbftomysql")
except:
db.rollback()
print "Dropped old table"
sql = """CREATE TABLE table(
col1 VARCHAR(200) NOT NULL,
col2 VARCHAR(200),
col3 VARCHAR(200),
col4 NUMERIC(15,2),
col5 VARCHAR(200) )"""
cur.execute(sql)
print "Created new table"
for i, s in zip(source, updated):
query = """INSERT table SET col1 = %s, col2 = %s, col3 = %s, col4 = %s, col5 = %s"""
values = (i["col1"], i ["col2 "], i["col3"], i["col4"], i["col5"])
cur.execute(query, values)
db.commit()
print i["col1"], i ["col2 "], i["col3"], i["col4"], i["col5"]
print "First Upload Completed"
while True:
for i, s in zip(source, updated):
if i["col1"] != s["col1"]:
print i["col1"] + " col1Updated"
query = """UPDATE table SET col1= %s WHERE col1= %s"""
values = (i["col1"], s["col1"])
try:
cur.execute(query, values)
db.commit()
except:
db.rollback()
print "No connection to database"
if i["col2"] != s["col2"]:
print i["col2"] + " col2 Updated for " + i["col1"]
query = """UPDATE table SET col2 = %s WHERE col1= %s OR col1= %s"""
values = (i["col2"], i["col1"], s["col1"])
try:
cur.execute(query, values)
db.commit()
except:
db.rollback()
print "No connection to database"
#ect
updated = list(source)
source.close()
source.open()
time.sleep(0.2)
Answer: The `dbf` library will only fetch the record from the dbf file if it doesn't
already exist in memory; when you do
updated = list(source)
you are effectively freezing all the rows because `updated` is a list of
records (not a list of `list`s or a list of `tuple`s; this means that when you
later try to compare `source` and `updated` you are comparing the same data.
In order to make `updated` be a separate entity from `source` try
updated = [tuple(row) for row in source]
which will give you a list of tuples, or
updated = [scatter(row, dict) for row in source]
which will give you a list of dicts, which is what you need for your field
comparison code further down.
|
Trying to use docutils.parsers.rst.tableparser in Python
Question: I would like to use the parser in the Python docutils.parsers.rst.tableparser
package to grab a plaintext table and parse it easily. The format of the
tables tableparser can read is very convinient for my project.
The problem is that, even though the documentation says that the input to the
parse(block) function is a 'list of lines of text; no whitespace padding',
whenever I try to parse something it fails.
So a small piece of code like this:
import docutils.parsers.rst.tableparser as tbp
parser = tbp.GridTableParser()
parser.parse(['+---+---+', '| a | b |', '| c | d |', '+---+---+'])
will fail with the following error message:
File "[...]/python2.7/site-packages/docutils/parsers/rst/tableparser.py", line 149, in setup
self.block.disconnect() # don't propagate changes to parent
AttributeError: 'list' object has not attribute 'disconnect'
I've been trying to find examples of use of this function online but I haven't
been able to find anything, any clue on what type of 'list of lines of text'
do I need to pass to the `parse()` function?
Answer: After some source browsing I got to this point, it appears to be working :)
from docutils.parsers.rst import tableparser
from docutils import statemachine
parser = tableparser.GridTableParser()
block = statemachine.StringList([
'+---+---+',
'| a | b |',
'| c | d |',
'+---+---+',
])
print parser.parse(block)
Result:
(
[3, 3],
[],
[[
(0, 0, 1, StringList(['a', 'c'], items=[(None, 1), (None, 2)])),
(0, 0, 1, StringList(['b', 'd'], items=[(None, 1), (None, 2)])),
]],
)
|
most frequent words in a french text
Question: I am using the python `nltk` package to find the most frequent words in a
French text. I find it not really working... Here is my code:
#-*- coding: utf-8 -*-
#nltk: package for text analysis
from nltk.probability import FreqDist
from nltk.corpus import stopwords
import nltk
import tokenize
import codecs
import unicodedata
#output French accents correctly
def convert_accents(text):
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
### MAIN ###
#openfile
text_temp=codecs.open('text.txt','r','utf-8').readlines()
#put content in a list
text=[]
for word in text_temp:
word=word.strip().lower()
if word!="":
text.append(convert_accents(word))
#tokenize the list
text=nltk.tokenize.word_tokenize(str(text))
#use FreqDist to get the most frequents words
fdist = FreqDist()
for word in text:
fdist.inc( word )
print "BEFORE removing meaningless words"
print fdist.items()[:10]
#use stopwords to remove articles and other meaningless words
for sw in stopwords.words("french"):
if fdist.has_key(sw):
fdist.pop(sw)
print "AFTER removing meaningless words"
print fdist.items()[:10]
Here is the output:
BEFORE removing meaningless words
[(',', 85), ('"', 64), ('de', 59), ('la', 47), ('a', 45), ('et', 40), ('qui', 39), ('que', 33), ('les', 30), ('je', 24)]
AFTER removing meaningless words
[(',', 85), ('"', 64), ('a', 45), ('les', 30), ('parce', 15), ('veut', 14), ('exigence', 12), ('aussi', 11), ('pense', 11), ('france', 10)]
My problem is that `stopwords` does not discard all the meaningless words. For
example ',' is not a word and should be removed, 'les' is an article and
should be removed.
How to fix the problem?
The text I used can be found at this page: <http://www.elysee.fr/la-
presidence/discours-d-investiture-de-nicolas-sarkozy/>
Answer: Usually its a better idea to use a list of stopwords of your own. For this
purpose, you can get a list of French stopwords from
[here](http://www.ranks.nl/stopwords/french). The article word 'les' is also
on the list. Create a text file of them and use the file to remove stopwords
from your corpus. Then for punctuations you have to write a punctuation
removal function. How you should write it, highly depends on your application.
But just to show you a few examples that would get you started, you can write:
import string
t = "hello, eric! how are you?"
print t.translate(string.maketrans("",""), string.punctuation)
and the output is:
hello eric how are you
or, another way is to simply write:
t = t.split()
for w in t:
w = w.strip('\'"?,.!_+=-')
print w
So, it really depends on how you need them to be removed. In certain scenarios
these methods might not result in what you exactly wanted. But, you can build
on them. Let me know if you had any further questions.
|
Upload a recording to Google App Engine from Android app
Question: I have created an android app that does basic voice recordings (stored as
.mp4). I want to add a feature where I can send a recording (just one at a
time, no batches needed) to Google App Engine cloud storage. Then, I want to
be able to listen to these recordings on my (very basic) cloud app. I do not
want to use the
[blobstore](https://cloud.google.com/appengine/docs/python/blobstore/) but the
datastore. I have used the datastore before but always just with a cloud app
and python, never with an android app (and my java is shaky at best).
Previously, I just got other data from my appspot website form and sent it to
the datastore using html and python.
In short, my question is, how do I get my recordings from my android app to
the datastore. Code snippets and/or links to documentation would be very
helpful. Also a short explanation of how these things will communicate/work
together would help my brain connect the dots.
Note, this is a personal app just for my own learning and use so I am not
extremely concerned about security, user accounts, scalability etc.
Thanks for your help!
Answer: Datastore is not a good storage option for this use case, as the maximum
entity size is limited to
[1mb](https://cloud.google.com/appengine/docs/python/datastore/#Python_Quotas_and_limits).
GCS is a recommended option for this use case. Also, if you’re not very
comfortable with Java, you can use Python for your GAE backend.
Regarding your question on how to move recordings from Android to GAE GCS /
Datastore, you can use one of these options:
1. Use [GCS](https://cloud.google.com/storage/docs/json_api/v1/json-api-examples) JSON API via Google APIs Client library to upload directly from Android app. Thats an easy option and there are plenty of samples available. This library can be used for [Datastore](https://cloud.google.com/datastore/docs/apis/v1beta2/) too if you insist on using it.
2. Use [Cloud Endpoints](https://cloud.google.com/appengine/docs/python/endpoints/) as a proxy. You can submit a file to an endpoint handler, endpoint handler saves the file in GCS and returns a response. As you’re not concerned with security, here’s an example that doesn’t use OAuth:
>
> import cloudstorage as gcs
> import endpoints
> import os
>
> from google.appengine.api import app_identity
> from protorpc import messages
> from protorpc import message_types
> from protorpc import remote
>
> class Base64File(messages.Message):
> file = messages.BytesField(1, required=True,
> variant=messages.Variant.BYTES)
>
> class ResponseMSG(messages.Message):
> message = messages.StringField(1)
>
> FILE_RESOURCE = endpoints.ResourceContainer(Base64File,
>
> file_name=messages.StringField(2,required=True),
>
> content_type=messages.StringField(3,required=True))
>
> @endpoints.api(name='gcsuploadapi', version='v0.1',
> description='Upload a file to
> GCS.')
> class GCSUploadAPI(remote.Service):
> @endpoints.method(FILE_RESOURCE, ResponseMSG,
> path='upload/{file_name}', http_method='POST',
> name='upload.file')
> def upload_file(self, request):
> # get app default bucket and prepare filename (project should
> have billing enabled)
> bucket_name = os.environ.get('BUCKET_NAME',
>
> app_identity.get_default_gcs_bucket_name())
> bucket = '/' + bucket_name
> filename = bucket + '/' + request.file_name
>
> # create file (request.content_type contains MIME type
> submitted)
> write_retry_params = gcs.RetryParams(backoff_factor=1.1)
> gcs_file = gcs.open(filename, 'w',
> content_type=request.content_type,
> retry_params=write_retry_params)
> gcs_file.write(request.file)
> gcs_file.close()
>
> return ResponseMSG(message="done")
>
> app = endpoints.api_server([GCSUploadAPI])
>
You don’t have to generate client libraries and can submit directly via HTTP
POST. Endpoints only support HTTPS connections and requests are a subject to
same restrictions as other [GAE
requests](https://cloud.google.com/appengine/docs/python/requests#Python_Quotas_and_limits).
The main concern is the request size of 32 megabytes. Taking into account the
binary data submitted to an endpoint should be base64 encoded, it leaves you
with an approximate limit of 23-24mb of binary data. Another limit is a 60
second deadline for a request, it can be resolved if you go with a [modular
approach](https://cloud.google.com/appengine/docs/python/modules/) for your
GAE app and use a backend instance for your endpoint.
That’s probably the hardest option to implement, but the example I provided
should be a good start.
3. Use Cloud Endpoints to generate a Blobstore API upload url. Blobstore API allows [uploading to GCS](https://cloud.google.com/appengine/docs/python/blobstore/#Python_Using_the_Blobstore_API_with_Google_Cloud_Storage) instead of Blobstore. Thats a rather easy option too.
|
Python Subprocess Behavior with Eclipse
Question: I am trying to run Eclipse from the command line to automate some project
importing and i am having an issue with pythons subprocess. Subprocess seems
to be ignoring my command arguments and just running eclipse straight up.
Here is what i am trying to do:
subprocess.call(["C:/eclipse/eclipsec",
"-nosplash",
"--launcher.suppressErrors",
"-application org.eclipse.cdt.managedbuilder.core.headlessbuild",
"-data", workspace_dir,
"-import", project_dir])
But when i run this Eclipse just opens and doesn't perform the import. However
if i change the command to:
subprocess.call(['eclipse_import.bat', workspace_dir, project_dir)])
Where `eclipse_import.bat` is:
set workspace_dir=%1
set project_dir=%2
C:/eclipse/eclipsec -nosplash --launcher.suppressErrors -application org.eclipse.cdt.managedbuilder.core.headlessbuild -data %workspace_dir% -import %project_dir%
Then everything behaves exactly as i expect it to.
Any ideas as to what would cause the differences?
Answer: They way you're calling it _should_ work properly, and I don't know why it
isn't. Perhaps Eclipse is trying to accept arguments in an odd way that your
batch script handles correctly but `subprocess.call()` doesn't, but that's
entirely conjecture on my part.
As a alternative, you can try calling it with the `shell=True` argument and
make your argument list a string instead:
call_string = "C:/eclipse/eclipsec -nosplash --launcher.suppressErrors -application org.eclipse.cdt.managedbuilder.core.headlessbuild -data {} -import {}".format(workspace_dir, project_dir))
subprocess.call(call_string, shell=True)
This will cause your default shell to parse the arguments instead of doing it
natively in Python, which is very similar to your batch script workaround.
|
Python 2.7 Tkinter - Multiple window entry update
Question: I would like the text to appear and be updated in each window, instead of only
in one. I have noticed that the window that works is always the first that is
being called, but that does not help me solve the issue.
Another thing I noticed is that the program accepts entering new values into
the windows that display a value in the first place, but any attempt to change
`de` value by entering a value in the second window fails.
Here is a simplified version of my code:
from Tkinter import *
root = Tk()
root2 = Tk()
de= IntVar()
de.set(0)
def previous():
de.set(de.get()-1)
def Next():
de.set(de.get()+1)
def go_to(event) :
de.set(de.get())
button4 =Button( root2, text='Next', command=Next )
button4.grid(row=26 ,column=9, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)
button5 =Button( root2, text='Previous', command=previous )
button5.grid(row=26, column=6, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)
label1=Label(root2, text = 'Go to2')
entry1 = Entry(root2,textvariable=de,bd=1,width=3)
entry1.bind("<Return>", go_to)
label1.grid(row=25, column=8, columnspan=1, rowspan=1,padx=0, pady=0)
entry1.grid(row=26, column=8, columnspan=1, rowspan=1,padx=0, pady=0)
button3 =Button( root, text='Next', command=Next )
button3.grid(row=26 ,column=9, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)
button2 =Button( root, text='Previous', command=previous )
button2.grid(row=26, column=6, columnspan=2, rowspan=1,padx=0, pady=0, sticky=W+E+N+S)
label=Label(root, text = 'Go to1')
entry = Entry(root,textvariable=de,bd=1,width=3)
entry.bind("<Return>", go_to)
label.grid(row=25, column=8, columnspan=1, rowspan=1,padx=0, pady=0)
entry.grid(row=26, column=8, columnspan=1, rowspan=1,padx=0, pady=0)
root2.mainloop()
root.mainloop()
Answer: The root cause of the problem is that Tkinter isn't designed to have two root
windows. Doing so has some unexpected side effects such as what you're seeing.
In effect, you can think of the two root windows as two separate processes or
threads which cannot share information. Your `IntVar` belongs to the first
window, but you're trying to use it in the second.
The fix is to never create more than one instance of `Tk`. If you need more
windows, create instances of `Toplevel`. Doing that, you can share the same
`IntVar` among as many windows as you want.
|
String building with regex
Question: So I am fairly new to python and am only self taught in this particular
language, but I have hit a bit of a snag.
What I am trying to do is build a string that has with in it a digit that can
be of any length or pattern. For example:
"Data_image_%s.%d" %(myStr, r'[0-9]+')
# Well, this won't actually work since %d is expecting an integer,
# but you get the idea.
When I do this I get back
Data_image_picture.[0-9]+.png
The ultimate objective is to create a string that reads like:
`Data_image_picture.1234567.png`
Any thoughts on how I might go about correcting this?
Edit: What I am trying to do is take images off my companies website but the
image url is dynamic depending on who and when the images are loaded to the
browser. So the format is typically "data_image_Joe_session#id.png
Edit 2: I think I have been going about this problem the wrong way, I'll
likely need to parse through the data to figure what string patterns I need,
instead of creating a one size fits all string like I have been doing.
Thank you for your time and help
Answer: Regular expressions are used for _matching_ , not for building strings or
building random numbers.
To build a string with a random number between 0 and 9999999 you could do
something like:
from random import random
myStr = "Data_image_picture." + str(int(random()*10000000)) + ".png"
|
ctype - python - long int too long to convert -
Question: problem:
> Traceback (most recent call last): File "C:\Users\Nutzer\Google
> Drive\Code\Code\memory_read.py", line 26, in byref(bytesRead))
> ctypes.ArgumentError: argument 2: : **long int too long to convert**
code:
from ctypes import *
from ctypes.wintypes import *
PID = 4016
address = 0x6C532407C
OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle
PROCESS_ALL_ACCESS = 0x1F0FFF
datadummy = b'.'*200
buffer = c_char_p(datadummy)
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)
processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, int(PID))
ReadProcessMemory(processHandle,
address,
buffer,
bufferSize,
byref(bytesRead))
CloseHandle(processHandle)
I tried to change the bytesRead = c_ulong(0) to some other ctypes, but no
success. Im on a Windows 8.1 System 64bit. I couldnt find any solution or
similiar problems after hours of searching. Does someone know whats wrong
here?
Answer: After a long time of fail and error I finally have an answer.
from ctypes import *
from ctypes.wintypes import *
import ctypes
OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle
PROCESS_ALL_ACCESS = 0x1F0FFF
pid = 2320
address = 0x00C98FCC
buffer = c_char_p(b"The data goes here")
val = c_int()
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)
processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
memmove(ctypes.byref(val), buffer, ctypes.sizeof(val))
print("Success: " + str(val.value))
else:
print("Failed.")
CloseHandle(processHandle)
|
Elasticsearch TransportError(400, u'MapperParsingException
Question: I have run the following python code with no errors. But now I am having this
TransportError(400, u'MapperParsingException [Analyzer [whitespace_analyzer] not found for field [job style]]'
The code is :
from elasticsearch import Elasticsearch
import xlrd
es = Elasticsearch()
es.indices.create("we_doing",body={
'settings': {
"analysis": {
"tokenizer":{
"camel":{
"type": "pattern",
"pattern":"([^\\\\p{L}\\\\d]+)|(?<=\\\\D)(?=\\\\d)|(?<=\\\\d)(?=\\\\D)|(?<=[\\\\p{L}&&[^\\\\p{Lu}]])(?=\\\\p{Lu})|(?<=\\\\p{Lu})(?=\\\\p{Lu}[\\\\p{L}&&[^\\\\p{Lu}]])"
}},
"analyzer": {
"nGram_analyzer": {
"type": "custom",
"tokenizer": ["whitespace","camel"],
"filter": [
"lowercase",
"asciifolding"
]
},
"whitespace_analyzer": {
"type": "custom",
"tokenizer": ["whitespace","camel"],
"filter": [
"lowercase",
"asciifolding"
]
}}}}}, ignore = 400 )
mapping = {
"we_data": {
"properties": {
"job id": {"type": "string", "index": "not_analyzed"},
"job style":{
"type":"string",
"index_analyzer": "nGram_analyzer",
"search_analyzer": 'whitespace_analyzer',
},
"location": {"type": "string", "index": "not_analyzed"},
"experience": {"type": "string", "index": "not_analyzed"},
"post date": {"type": "string", "index": "not_analyzed"},
"job description": {"type": "string", "index": "not_analyzed"},
}}}
es.indices.put_mapping(index="we_doing", doc_type="we_data", body=mapping)
It was working perfectly. now i am in so much trouble. Its going to be live in
2 days. please be of some help .
Answer: Only one tokenizer can be used by an analyzer(per [Elasticsearch Analysis
reference
page](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/analysis.html)).
You'll need to use a TokenFilter to take to the place of one of them ([Word
Delimiter Token
Filter](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/analysis-
word-delimiter-tokenfilter.html#analysis-word-delimiter-tokenfilter) should do
nicely), or use a Tokenizer that accomplishes both.
|
SQL query in Python gives OperationalError: near "WITH": syntax error
Question: I've been trying to do some CSV file merging using SQL in Python with SQL
query being the following:
WITH
MATCHES AS( -- get all matches
SELECT CSV2.*
, CSV1.ROW as ROW_1
, CSV1.C4 as C4_1
, CSV1.C5 as C5_1
FROM CSV2
LEFT JOIN CSV1
ON CSV1.C4 LIKE '%' || CSV2.C2 || '%'
),
EXACT AS( -- matches where CSV1.C4 = CSV1.C5
SELECT *
FROM MATCHES
WHERE C4_1 = C5_1
),
MIN_ROW AS( -- CSV1.ROW of first occurence for each CSV2.C1
SELECT C1
, min(ROW_1) as ROW_1
FROM MATCHES
WHERE C1 NOT IN (SELECT C1 FROM EXACT)
GROUP BY C1, C2, C3, C4, C5
)
-- use C4=C5 first
SELECT *
FROM EXACT
UNION
-- if match not in exact, use first occurence
SELECT MATCHES.*
FROM MIN_ROW
INNER JOIN MATCHES
ON MIN_ROW.C1 = MATCHES.C1
AND (MIN_ROW.ROW_1 = MATCHES.ROW_1 OR MIN_ROW.ROW_1 IS NULL)
ORDER BY C1
However, I keep receiving OperationalError: near "WITH": syntax error. I'm not
very much familiar with SQL and haven't attempted to use it in Python before.
What can be done to fix this error? Update1- The query within the first pair
of brackets works fine without "with match as" part. Here are sample csv
files: CSV1
data13 data23 d main_data1;main_data2 data13 data23
data12 data22 d main_data1;main_data2 data12 data22
data11 data21 d main_data1;main_data2 data11 data21
data3 data4 d main_data2;main_data4 data3 data4
data52 data62 d main_data3 data51 data62
data51 data61 d main_data3 main_data3 data61
data7 data8 d main_data4 data7 data8
CSV2
id1 main_data1 a1 a2 a3
id2 main_data2 b1 b2 b3
id3 main_data3 c1 c2 c3
id4 main_data4 d1 d2 d3
id5 main_data5 e1 e2 e3
and the Python code
import csv
import sqlite3
def createTable(cursor, rows, tablename):
tableCreated = False
for row in rows:
if not tableCreated:
sql = "CREATE TABLE %s(ROW INTEGER PRIMARY KEY, " + ", ".join(["c%d" % (i+1) for i in range(len(row))]) + ")"
cur.execute(sql % tablename)
tableCreated = True
sql = "INSERT INTO %s VALUES(NULL, " + ", ".join(["'" + c + "'" for c in row]) + ")"
cur.execute(sql % tablename)
conn.commit()
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
for filename, tablename in [(path_to_csv1, "CSV1"), (path_to_csv2, "CSV2")]:
with open(filename, "r") as f:
reader = csv.reader(f, delimiter=',')
rows = [row for row in reader]
createTable(cur, rows, tablename)
Update2- I'm using Python 2.7
Answer: Add ';' before `With` as
;WITH
MATCHES AS( ...
|
Python cmd on linux does not autocomplete special characters or symbols
Question: Characters such as `-` , `+` etc are not parsed the same way as alphanumeric
ASCII characters by Python's readline based cmd module. This seems to be linux
specific issue only, as it seems to work as expected on Mac OS.
**Sample code**
import cmd
class Test(cmd.Cmd):
def do_abc(self, line):
print line
def complete_abc(self, text, line, begidx, endidx):
return [i for i in ['-xxx', '-yyy', '-zzz'] if i.startswith(text)]
try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
Test().cmdloop()
**Expected behavior on Mac OS**
(Cmd) abc <TAB>
abc
(Cmd) abc -<TAB>
-xxx -yyy -zzz
(Cmd) abc -x<TAB>
(Cmd) abc -xxx
**Incorrect behavior on Linux**
(Cmd) abc <TAB>
abc
(Cmd) abc -x<TAB>
<Nothing>
(Cmd) abc -<TAB>
(Cmd) abc --<TAB>
(Cmd) abc ---<TAB>
(Cmd) abc ----
I tried adding `-` to cmd.Cmd.identchars, but it didn't help.
cmd.Cmd.identchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'
Why is there a difference in readline parsing between Mac OS and Linux even
though both use GNU readline:
Mac OS:
>>> readline.__doc__
'Importing this module enables command line editing using GNU readline.'
Linux:
>>> readline.__doc__
'Importing this module enables command line editing using GNU readline.'
Thanks!
Answer: On linux, the `readline` module considers `-` a delimiter for tab completion.
That is, after a `-` is encountered a fresh completion will be tried.
The solution to your problem is the remove `-` from the set of characters used
by readline as delimiters.
eg.
old_delims = readline.get_completer_delims()
readline.set_completer_delims(old_delims.replace('-', ''))
|
Functions defined in dynamically-loaded scripts cannot refer to each other
Question: I'm trying to load functions from a script dynamically when I'm inside an
ipython interactive shell. For example, suppose I have a python script like
this:
# script.py
import IPython as ip
def Reload():
execfile('routines.py', {}, globals())
if __name__ == "__main__":
ip.embed()
Suppose the file routines.py is like this:
# routines.py
def f():
print 'help me please.'
def g():
f()
Now if I run the script script.py, I'll be entering the interactive shell. If
I type the following, my call to g() works:
execfile('routines.py')
g()
However, if I type the following, the call to g() fails:
Reload()
g()
I will get an error message saying that **"global name f is not defined."** ,
although I can still see that f and g are in the output when I type globals()
in the interactive shell.
What's the difference of these two?
UPDATE:
The following works, however it's not a preferred solution so I would like to
have a better solution for the problem above.
If I change script.py to:
# script.py
import IPython as ip
def Reload():
execfile('routines.py')
if __name__ == "__main__":
ip.embed()
And change routines.py to:
# routines.py
global f
global g
def f():
print 'help me please.'
def g():
f()
Then if I call Reload() in the interactive shell and then call g(), it works.
However this is not a preferred approach because I have to declare global
names.
UPDATE 2:
It seems that the problem is independent of ipython. With the first version of
routines.py if I start the python shell, and type the following by hand:
def Reload():
execfile('routines.py', {}, globals())
g()
The call to g() also fails. But the following works:
execfile('routines.py')
g()
Answer: As @Bakuriu said, importing is much preferred. Ignoring that, what you want is
def Reload():
execfile('routines.py', globals())
Lets clarify your example to show why it does not work.
# Setup the namespace to use for execfile
global_dict = {}
local_dict = globals()
execfile('routines.py', global_dict, local_dict)
g() # raises NameError
Since you are passing two different dicts to `execfile`, the file is executed
as if it were in a class definition ([from the
docs](https://docs.python.org/2/library/functions.html#execfile)). This means
your functions are defined in `local_dict` but not `global_dict`.
When you then call `g()`, it is executed using globals `global_dict` and a
fresh empty local dict. Since neither `global_dict` or the new locals doesn't
contain `f` we get a name error. By instead calling `execfile('routines.py',
globals())`, we are using `global_dict = globals()` and `local_dict =
globals()` so `f` is defined in `g`'s globals.
EDIT:
You noticed that `local_dict` has both `f` and `g`, but `global_dict` does not
in the second example. Defining any variable without explicitly marking it
global will always make a local variable, this applies to modules too! It just
so happens that normally a module has `locals() == globals()`; however, we
broke this standard by using different local and global dicts. This is what I
meant when I said "the file is executed as if it were in a class definition".
|
Testing programs that read form sys.stdin
Question: I am playing with some programming challenges that will check the submission
by:
python my_submission < in.txt > out.txt
When I try and make my submission, I want to read some cases/numbers/whatever
from _in.txt_ to see what is happening. Currently I am doing that by:
import sys
file = open('in.txt')
sys.stdin = file
for line in sys.stdin:
case1 = line.split()
some_function(case1)
So when I run my python program (hit cmd+B) in Sublime text, I can see whether
I manage to read the input correctly, process one test case correctly, etc....
Then I just commend out the 2nd and 3rd line when my program should be
submitted to the submission judge.
I was just wondering: is this the "preffered workflow" for dealing with this?
Do pro programmers write some kind of unit test template function to do this?
Answer: The preferred workflow is to let the shell doing the redirection so you don't
have to change the program code all the time.
But your IDE (sublime text) doesn't allow you to specify such arguments, so it
limits your options.
Solutions/workarounds:
1. Start the program from a shell. Which means you need to switch between the terminal window and sublime all the time.
2. Write a second program which runs the first and which sets up the input redirection. This way, you just need to switch tabs in sublime.
3. Instead of reading from `stdin` directly, use the `fileinput` module. See [How do you read from stdin in Python?](http://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python) This will allow you to write proper unit tests for your code. You can then use the [Python Unittest Helper](https://sublime.wbond.net/packages/Python%20Unittest%20Helper) plugin for Sublime.
|
graph in python from a list of edges
Question: I have a list of edges in a text file:
0 1
0 2
0 3
1 637
1 754
1 1319
1 1350
1 1463
1 1523
2 637
2 754
2 1319
2 1350
2 1463
2 1523
3 499
3 539
3 595
3 637
3 706
3 1128
3 1194
3 1213
3 1319
.. ...
I need to turn it into a dictionary like this:
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
my attempt so far has been:
import numpy as np
file_name='/Volumes/City_University/data_mining/Ecoli.txt'
key_column=0
dat=np.genfromtxt(file_name,dtype=str)
d={i:[] for i in np.unique(dat[:,key_column])}
for row in dat:
for key in d.keys():
if row[key_column]==key :d[key].append(row[1])
print (d)
However, this does not work properly inasmuch i don't get a new key when this
appear in the values: as an example I get:
'0': ["1", "2", "3"]
'1': ['637', '754', '1319', '1350', '1463', '1523']
in the '1', the "0" is missing.
to make it more simple. If I have a text like this
a b
c d
I should get an outcome like: graph = { "a": ["b"], "b": ["a"], "c": ["d"],
"d": ["c"]}
thank you in advance
Answer: If you want a bidirectional graph, you need two appends.
Also, you don't really need the `for key in d.keys()` loop, just append to
`d[row[0]]` instead of `d[key]`.
for row in dat:
d[row[0]].append(row[1])
d[row[1]].append(row[0])
* * *
Also, consider using a defaultdict, in which case you wouldn't need to
initialize `d` with `np.unique`. It will also guard against errors that would
otherwise occur when a node only appears in the second column.
import numpy as np
from collections import defaultdict
file_name='/Volumes/City_University/data_mining/Ecoli.txt'
dat=np.genfromtxt(file_name,dtype=str)
d=defaultdict(list)
for row in dat:
d[row[0]].append(row[1])
d[row[1]].append(row[0])
print (d)
|
Search elements in an array of arrays
Question: Sorry if I get terminology wrong - I've only just started learning Python, and
I'm receiving instruction from friends instead of being on an actual course.
I want to search a list containing lots of arrays containing multiple
elements, and find arrays with some elements matching, but some different.
In less confusing terms e.g. I have a list of arrays that each contain 2
elements (I think this is called a 2D array?) so:
list = [[1, 2], [2, 2], [3, 5], [4, 1], [5, 2], ...]
In my specific example, the first elements in each sub array just ascend
linearly, but the second elements are almost random. I want to find or sort
the arrays only by the second number. I could just remove the first number
from each array:
list = [2, 2, 5, 1, 2 ...]
And then use something like "if list[x] == 1" to find '1' etc.
(side note: I'm not sure how to find ALL the values if one value is repeated -
I can't remember quite what I wrote but it would only ever find the first
instance where the value matched, so e.g. it would detect the first '2' but
not the second or third)
But I want to keep the first values in each array. My friend told me that you
could use a dictionary with values and keys, which would work for my example,
but I want to know what the more general method would be.
So in my example, I hoped that if I wrote this:
if list[[?, x]] == [?, 1]
Then it would find the array where the second value of the array was 1, (i.e.
[4, 1] in my example) and not care about the first value. Obviously it didn't
work because '?' isn't Python syntax as far as I'm aware, but hopefully you
can see what I'm trying to do?
So for a more general case, if I had a list of 5 dimensional arrays and I
wanted to find the second and fourth values of each array, I would write:
if list[[?, x, ?, y, ?]] == [?, a, ?, b, ?]
And it would match any array where the value of the second element was 'a',
and the value of the fourth was 'b'.
e.g. [3, a, 4, b, 7], [20, a, 1, b, 9], ['cat', a, 'dog', b, 'fish'] etc.
would all be possible results found by the command.
So I want to know if there's any similar way to my method of using a question
mark (but that actually works) to denote that an element in an array can have
any value.
Answer: To sort on the second element for a list containg lists (or tuples):
from operator import itemgetter
mylist = [[1, 2], [2, 2], [3, 5], [4, 1], [5, 2]]
sortedlist = sorted(mylist, key=itemgetter(1))
See the [Python sorting howto](https://docs.python.org/2/howto/sorting.html).
|
Tkinter button not working (Python 3.x)
Question: I'm working on my final project for my computing I class.
The problem that I am having is:
When I click on the new entry button, hit the back button and click on the new
entry button once again it **does not work**.
If you guys could tell me why that is?
The command on the button seems to be only working once. Thanks for your help.
**Code:**
from tkinter import *
import tkinter.filedialog
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.title("Entry Sheet")
self.font = ("Helvetica","13")
self.header_font = ("Helvetica","18")
self.exercise_font = ("Helvetica","13","bold")
self.delete = 'a'
self.new_user()
def new_user(self):
if self.delete == 'b':
self.delete = 'c'
self.hide()
self.delete = 'b'
self.new_entry = Button(self, text = 'New Entry', command = self.entry, width = 15)
self.new_entry.grid(row = 1, column = 0, columnspan = 3, padx = 10, pady = 5)
self.look_entry = Button(self, text = 'See Entries', command = self.see_entries, width = 15)
self.look_entry.grid(row = 2, column =0, columnspan = 3, padx = 10, pady = 5)
def entry(self):
print(1)
self.delete = 'b'
self.hide()
self.entry = Label(self, text = 'New Entry', font = self.header_font)
self.entry.grid(row = 0, column = 0, columnspan = 2)
self.numberlbl = Label(self, text = 'Please choose a muscle?', font = self.font)
self.numberlbl.grid(row = 1, column= 0, columnspan = 2, sticky = 'w' )
self.muscle_chosen = IntVar()
self.chest = Radiobutton(self, text = "chest", variable = self.muscle_chosen, value = 1, font = self.font)
self.bicep = Radiobutton(self, text = "bicep", variable = self.muscle_chosen, value = 2, font = self.font)
self.chest.grid(row = 2, column = 0)
self.bicep.grid(row = 2, column = 1)
self.exerciseslbl = Label(self, text = 'Please enter the number of exercises: ', font = self.font)
self.exerciseslbl.grid(row = 3, column = 0, columnspan = 3)
self.exercises_spinbox = Spinbox(self, from_= 1, to_= 50, width = 5, font = self.font)
self.exercises_spinbox.grid(row = 4, column = 0)
self.back_button = Button(self, text = 'Back', command = self.new_user, width = 10)
self.back_button.grid(row =5, column=0, pady =10)
def see_entries(self):
print("Goes through")
def hide(self):
if self.delete == 'b':
self.new_entry.grid_remove()
self.look_entry.grid_remove()
elif self.delete == 'c':
self.entry.grid_remove()
self.numberlbl.grid_remove()
self.chest.grid_remove()
self.bicep.grid_remove()
self.exerciseslbl.grid_remove()
self.exercises_spinbox.grid_remove()
self.back_button.grid_remove()
def main():
app = App()
app.mainloop()
if __name__=="__main__":
main()
Answer: In your `entry` function you overwrite `self.entry`, which is the name of the
function, with a reference to a `Label`. When the button then calls
`self.entry` it isn't function.
Simply call the `Label` something else.
|
can't get correct python regex with this string that contains unicode
Question: I have this string:
s = u'vitamin a min. 14,053 iu/kg vitamin c 13,000iu/kg vitamin d max. 10,000\u03bc/kg copper 1mg/kg vitamin e mon 10.00iu/kg'
I want to break it apart so I get `[label, label2, amount, units]`.
* `label` is the name ie, `vitamin c` and can contain unicode characters
* `label2` is `min|max` depending on the particular string.
* `amount` is the numerical amount listed (can include commas or decimals)
* `units` can include unicode characters
You can see some edge cases cropping up already:
* Some ingredients don't contain a `label2` = `min` or `max` (see `copper` and `vitamin c`). The regex grouping can be `None` in this case.
* Some ingredients have `label2` mispelled (see `vitamin e` uses `mon`)
* There may be unicode in the units
Ideally, I would like a regex that can match against individual ingredients as
well as a messy list (like I have provided).
I came up with:
import re
regex = re.compile(ur'([a-z 0-9]+)(min|max|mon)?[. ]+([0-9., ]+)((?=[%])|[a-z/]+|[^\W\d_]+/[^\W\d_]+)', re.UNICODE)
re.findall(regex, s)
# [(u'vitamin a min', u'', u'14,053 ', u'iu/kg'), (u' vitamin c', u'', u'13,000', u'iu/kg'), (u' vitamin d max', u'', u'10,000', u'\u03bc/kg'), (u' copper', u'', u'1', u'mg/kg'), (u' vitamin e mon 10', u'', u'00', u'iu/kg')]
re.findall(regex, u'vitamin a min. 14,053 iu/kg')
# [(u'vitamin a min', u'', u'14,053 ', u'iu/kg')]
This matches nearly everything, but you can see some problems.
* the `label` is matching the `min`,`max` and `label2` matches nothing.
* I don't like hardcoding `(min|max|mon)` because there could be a case where the word is misspelled to something else and that hardcoding won't catch it.
Answer: You can deal with splitting the two labels by using non-greedy matching.
But there is no way to avoid hardcoding the second label. Even _without_ the
spelling variants, you would have to _at least_ specifiy `(min|max)`,
otherwise there would be no reason to separate the second label from the first
label (which can have any number of words). So the best you can do is extend
that list with whatever other variants you can find in the data (there
probably aren't all that many).
Anyway, here's one possible solution that works with the example data you've
provided:
>>> regex = re.compile(ur"""
... ((?:\w+\s+)+?)((?:min|max|mon)\.?)?
... ([0-9., ]+)(%|[^\W\d_]+/[^\W\d_]+)
... """, re.X | re.I | re.U)
>>> pprint(regex.findall(s))
[(u'vitamin a ', u'min.', u' 14,053 ', u'iu/kg'),
(u'vitamin c ', u'', u'13,000', u'iu/kg'),
(u'vitamin d ', u'max.', u' 10,000', u'\u03bc/kg'),
(u'copper ', u'', u'1', u'mg/kg'),
(u'vitamin e ', u'mon', u' 10.00', u'iu/kg')]
|
Django - passing a variable from a view into a url tag in template
Question: First of all, I apologize for the noobish question. I'm very new to Django and
I'm sure I'm missing something obvious. I have read many other posts here and
have not been able to find whatever obvious thing I am doing wrong. Thanks so
much for any help, I am on a deadline.
I am using Django 1.6 with Python 2.7. I have one app called dbquery that uses
a form to take data from the user and query a REST service. I am then trying
to display the results on a results page. Obviously there is more to add, this
is just a very simple start.
The problem is that I can't seem to get the autoincremented id field from my
search view into the url tag in the template properly. If I put the number 1
in like this `{% url 'dbquery:results' search_id=1 %}`, the page loads and
works well, but I can't seem to get the variable name right, and the django
documentation isn't helping- maybe this is obvious to most people. I get a
reverse error because the variable ends up always being empty, so it can't
match the results regex in my urls.py. I tested my code for adding an object
in the command line shell and it seems to work. Is there a problem with my
return render() statement in my view?
urls.py
from django.conf.urls import patterns, url
from dbquery import views
urlpatterns = patterns('',
# ex: /search/
url(r'^$', views.search, name='search'),
# ex: /search/29/results/ --shows response from the search
url(r'^(?P<search_id>\d+)/results/', views.results, name ='results'),
)
models.py
from django.db import models
from django import forms
from django.forms import ModelForm
import datetime
# response data from queries for miRNA accession numbers or gene ids
class TarBase(models.Model):
#--------------miRNA response data----------
miRNA_name = models.CharField('miRNA Accession number', max_length=100)
species = models.CharField(max_length=100, null=True, blank=True)
ver_method = models.CharField('verification method', max_length=100, null=True, blank=True)
reg_type = models.CharField('regulation type', max_length=100, null=True, blank=True)
val_type = models.CharField('validation type', max_length=100, null=True, blank=True)
source = models.CharField(max_length=100, null=True, blank=True)
pub_year = models.DateTimeField('publication year', null=True, blank=True)
predict_score = models.DecimalField('prediction score', max_digits=3, decimal_places=1, null=True, blank=True)
#gene name
gene_target = models.CharField('gene target name',max_length=100, null=True, blank=True)
#ENSEMBL id
gene_id = models.CharField('gene id', max_length=100, null=True, blank=True)
citation = models.CharField(max_length=500, null=True, blank=True)
def __unicode__(self):
return unicode(str(self.id) + ": " + self.miRNA_name) or 'no objects found!'
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from dbquery.models import TarBase, SearchMainForm
from tarbase_request import TarBaseRequest
#main user /search/ form view
def search(request):
if request.method == 'POST': #the form has been submitted
form = SearchMainForm(request.POST) #bound form
if form.is_valid(): #validations have passed
miRNA = form.cleaned_data['miRNA_name']
u = TarBase.objects.create(miRNA_name=miRNA)
#REST query will go here.
#commit to database
u.save()
return render(request,'dbquery/results.html', {'id':u.id})
else: #create an unbound instance of the form
form = SearchMainForm(initial={'miRNA_name':'hsa-let-7a-5p'})
#render the form according to the template, context = form
return render(request, 'dbquery/search.html', {'form':form})
#display results page: /search/<search_id>/results/ from requested search
def results(request, search_id):
query = get_object_or_404(TarBase, pk=search_id)
return render(request, 'dbquery/results.html', {'query':query} )
templates: search.html
<html>
<head><h1>Enter a TarBase Accession Number</h1>
</head>
<body>
<!--form action specifies the next page to load-->
<form action="{% url 'dbquery:results' search_id=1 %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Search" />
</form>
</body>
results.html
<html>
<head><h1>Here are your results</h1>
</head>
<body>
{{query}}
</body
Answer: The search results aren't created and don't have an ID until after you submit
your form. The usual way to do this would be to have your form use its own URL
as the action, then have the view redirect to the results view after
successfully saving:
from django.shortcuts import redirect
def search(request):
if request.method == 'POST': #the form has been submitted
form = SearchMainForm(request.POST) #bound form
if form.is_valid(): #validations have passed
miRNA = form.cleaned_data['miRNA_name']
u = TarBase.objects.create(miRNA_name=miRNA)
#REST query will go here.
#commit to database
u.save()
return redirect('results', search_id=u.id)
else: #create an unbound instance of the form
form = SearchMainForm(initial={'miRNA_name':'hsa-let-7a-5p'})
#render the form according to the template, context = form
return render(request, 'dbquery/search.html', {'form':form})
Then in your template:
<form action="" method="post">
That causes your form to submit its data to the `search` view for validation.
If the form is valid, the view saves the results, then redirects to the
appropriate results page based on the ID as determined after saving.
|
Why is module global assignment different simple types vs classes/dictionaries?
Question: Given the following example code:
test.py
import module
print 'main: Vars.foo: %s' % (module.Vars.foo)
print 'main: d.foo: %s' % (module.d['foo'])
print 'main: foo: %s' % (module.foo)
print
module.Vars.foo = 2
module.d['foo']=2
module.foo = 2
def baz():
print 'baz: Vars.foo: %s' % (module.Vars.foo)
print 'baz: d.foo: %s' % (module.d['foo'])
print 'baz: foo: %s' % (module.foo)
print
module.bar()
if __name__ == '__main__':
baz()
module/
module.py
`__init__.py`
`__init__.py`
from module import *
module.py
class Vars:
foo = None
d = {'foo': None}
foo = None
def bar():
print 'bar: Vars.foo: %s' % (Vars.foo)
print 'bar: d.foo: %s' % (d['foo'])
print 'bar: foo: %s' % (foo)
produces this output when test.py is run:
main: Vars.foo: None
main: d.foo: None
main: foo: None
baz: Vars.foo: 2
baz: d.foo: 2
baz: foo: 2
bar: Vars.foo: 2
bar: d.foo: 2
bar: foo: None
All of this makes sense to me except the bar() output. Why is the bar() output
different for a class/dictionary vs. a simple type? I think it has something
to do with the mutability of a class/dictionary but I'm not sure. What I'm
specifically looking for is the actual python language rules that are causing
that bar output to be as it is.
Answer: In test.py you are importing the `module` _package_ , not the `module.module`
_module_. In this package's `__init__.py` you're doing a star import from the
`module.module` module. So when you rebind `module.foo` in test.py, it's the
package's 'foo' you are rebinding, not the module's one. Wrt/ the other
objects, you are mutating them, not rebinding them, which is a different
operation.
If in test.py you replace `import module` with `from module import module`
you'll get a different behaviour.
|
Twill doesn't show forms
Question: I'm trying to login in <https://accounts.coursera.org/> using twill for python
I tried this sheet of code
import twill
b = get_browser()
b.go("https://accounts.coursera.org/")
b.showforms()
twill doesn't detect the form in the page and showforms methods doesn't show
anything !! Is that an internal issue in twill package or I'm misssing
something
Answer:
import twill
import webbrowser
b = twill.get_browser()
b.go("https://accounts.coursera.org/")
page = b.result.get_page()
tmp_page = "tmp.html"
with file(tmp_page, "w") as f:
f.write(page)
webbrowser.open(tmp_page)
# b.showforms()
I get a page that says..
> Please use a modern browser with JavaScript enabled to use Coursera.
So I suspect that twill doesn't include a javascript interpreter?
|
Why is PIP not upgrading the Package
Question: Why is `pip` not installing the LATEST? Is there a way to force LATEST?
$ sudo pip install --upgrade pefile
Requirement already up-to-date: pefile in /usr/local/lib/python2.7/dist-packages
Cleaning up...
$ pip show pefile
---
Name: pefile
Version: 1.2.10-114
Location: /usr/local/lib/python2.7/dist-packages
Requires:
$ pip search "pefile"
pefile - Python PE parsing module
INSTALLED: 1.2.10-114
LATEST: 1.2.10-139
$ sudo pip install --upgrade --force-reinstall --pre pefile
Downloading/unpacking pefile
Downloading pefile-1.2.10-114.tar.gz (49kB): 49kB downloaded
Running setup.py (path:/tmp/pip_build_root/pefile/setup.py) egg_info for package pefile
Installing collected packages: pefile
Found existing installation: pefile 1.2.10-114
Uninstalling pefile:
Successfully uninstalled pefile
Running setup.py install for pefile
Successfully installed pefile
Cleaning up...
Note:
$ pip list
pefile (1.2.10-114)
pip (1.5.6)
References: <https://code.google.com/p/pefile/>
Answer: If you look at the `pefile` pages for
[`1.2.10-114`](https://pypi.python.org/pypi/pefile/1.2.10-114) and
[`1.2.10-139`](https://pypi.python.org/pypi/pefile/1.2.10-139) \- you'll see
an important difference, the latter doesn't have a "Files" section with a
source and egg. That means that the files are hosted externally and you need
to allow `pip` to install from an
_[external](https://pip.pypa.io/en/latest/reference/pip_wheel.html#cmdoption--
allow-external) and
[unverified](https://pip.pypa.io/en/latest/reference/pip_wheel.html#cmdoption
--allow-unverified) source_:
pip install pefile --upgrade --allow-external=pefile --allow-unverified=pefile
Demo:
$ pip show pefile
---
Name: pefile
Version: 1.2.10-114
$ pip install pefile --upgrade --allow-external=pefile --allow-unverified=pefile
pefile an externally hosted file and may be unreliable
pefile is potentially insecure and unverifiable.
...
Installing collected packages: pefile
Found existing installation: pefile 1.2.10-114
Uninstalling pefile:
Successfully uninstalled pefile
Running setup.py install for pefile
Successfully installed pefile
Cleaning up...
$ pip show pefile
---
Name: pefile
Version: 1.2.10-139
|
Eucalyptus Walrus/Amazon S3 SOAP signature is failing
Question: I have been learning how to use Amazon S3 API by using the open source
Eucalyptus. So far I have been able to successfully use REST, but now I would
also like to use SOAP. I seem to be having trouble generating the correct
signature for my request. The service is giving me a 403 Forbidden error:
Traceback (most recent call last):
File "soap.py", line 31, in <module>
r = w.download_file('mybucket', 'test.txt')
File "soap.py", line 27, in download_file
r = self.client.service.ListAllMyBuckets(self.access_key, timestamp, signature)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 521, in __call__
return client.invoke(args, kwargs)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 581, in invoke
result = self.send(soapenv)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 619, in send
description=tostr(e), original_soapenv=original_soapenv)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 677, in process_reply
raise Exception((status, description))
Exception: (403, u'Forbidden')
My code is in Python 2 and uses the SUDS-Jurko library for sending SOAP
requests:
from suds.client import Client
class WalrusSoap:
wsdl_url = 'https://s3.amazonaws.com/doc/2006-03-01/AmazonS3.wsdl'
server_url = 'https://localhost:8773/services/Walrus'
def __init__(self, access_key, secret_key):
self.access_key = access_key
self.secret_key = secret_key
self.client = Client(self.wsdl_url)
self.client.wsdl.services[0].setlocation(self.server_url)
#print self.client
def create_signature(self, operation, timestamp):
import base64, hmac, hashlib
h = hashlib.sha1(self.secret_key)
h.update("AmazonS3" + operation + timestamp)
#h = hmac.new(key=self.secret_key, msg="AmazonS3" + operation + timestamp, digestmod=hashlib.sha1)
return base64.encodestring(h.digest()).strip()
def download_file(self, bucket, filename):
from time import gmtime, strftime
timestamp = strftime('%Y-%m-%dT%H:%M:%S.001Z', gmtime())
print(timestamp)
signature = self.create_signature('ListAllMyBuckets', timestamp)
print(signature)
r = self.client.service.ListAllMyBuckets(self.access_key, timestamp, signature)
return r
w = WalrusSoap(access_key='MOBSE7FNS6OC5NYC75PG8', secret_key='yxYZmSLCg5Xw6rQVgoIuVLMAx3hZRlxDc0VOJqox')
r = w.download_file('mybucket', 'test.txt')
print(r)
I changed the server endpoint, because otherwise the WSDL points to the
regular S3 servers at Amazon. I also have two different ways of creating the
signature in my create_signature function. I was swapping between one and the
other by simply commenting out the second one. Neither of the two seem to
work. My question is what am I doing wrong?
SOAP Authentication:
<http://docs.aws.amazon.com/AmazonS3/latest/dev/SOAPAuthentication.html>
SUDS-Jurko Documentation: <https://bitbucket.org/jurko/suds/overview>
Edit: I realized I forgot to include an example of what timestamp and
signature is printed for debugging purposes.
2014-12-05T00:27:41.001Z
0h8vxE2+k10tetXZQJxXNnNUjjw=
Edit 2: Also, I know that the download_file function does not download a file
:) I am still in testing/debug phase
Edit 3: I am aware that REST is better to use, at least according to Amazon.
(Personally I think REST is better also.) I am also already aware that SOAP is
deprecated by Amazon. However I would like to go down this path anyways, so
please do me a favor and do not waste my time with links to the deprecation. I
assure you that while writing this SOAP code, I was already well aware of the
deprecation. In fact one of the links I posted has the deprecation notice
printed at the top of its page. However, if you have evidence showing that
Walrus completely ditches SOAP or that they stopped working on the SOAP
portion, I would like to see something like that. But please do not tell me
Amazon has deprecated SOAP.
Answer: The S3 SOAP API does not support "new" features so the REST API should be used
where possible:
<http://docs.aws.amazon.com/AmazonS3/latest/dev/SOAPAPI3.html>
<https://forums.aws.amazon.com/message.jspa?messageID=77821>
IIRC recent versions of Eucalyptus do not support SOAP with S3.
That said, the signature looks good to me so I would check if the
client/service hosts have the correct time, if there is a difference of more
than 15 minutes authentication would fail.
You could also check the cloud-error.log on the Walrus service host as there
may be more details on the failure there.
|
Python SQLite ToDo script
Question: I'm trying to make a script that asks the user to input a task, the task is
then stored in a SQLite database. I am having a problem getting my delete
function to work. Also when I input a new task I have to encapsulate in quotes
in order to make it run.
import sqlite3
import sys
con = sqlite3.connect('taskmgr.db')
def create_db():
with con:
c.execute("DROP TABLE IF EXISTS ToDo")
c.execute("CREATE TABLE ToDo(Id int, Task char20, Due char20)")
def select_task():
with con:
cursor = con.execute("SELECT Id, Task, Due from ToDo")
for row in cursor:
print "Id:" ,row[0]
print "Task:" ,row[1]
print "Due:" ,row[2]
def insert_task():
with con:
print("New Task\n")
Id = input("Enter Id: ")
Task = input("Enter Task: ")
Due = input("Enter Due Date: ")
c.execute("INSERT INTO ToDo VALUES(?, ?, ?)", (Id, Task, Due))
con.commit()
def delete_record():
with con:
print("Enter task Id to delete:")
user = int(input())
c.execute("DELETE FROM ToDo WHERE Id=?",(user))
c = con.cursor()
create_db()
target= int(8)
while target != 9:
target=int(input("\nGood Morning Curtis!\n \nSelect option:\n 1.New Task\n 2.Select Task\n 3.Delete Task\n 9.Quit\n\nUser: "))
if target ==1:
insert_task()
elif target ==2:
select_task()
elif target ==3:
delete_record()
elif target ==9:
print("good bye")
Answer: Regarding the input requiring quotes, for Python 2 use `raw_input()` instead
of `input()`.
The other problem is with the `execute` statement, specifically the values for
the parameterised query needs to be of type tuple (or list), however, you are
passing in an integer value. Try changing it to this:
c.execute("DELETE FROM ToDo WHERE Id=?",(user,))
The reason is that wrapping a single value in parentheses does not create a
tuple:
>>> for user in 1, (1), (1,):
... print user, type(user)
...
1 <type 'int'>
1 <type 'int'>
(1,) <type 'tuple'>
From the above you can see that `(1)` is still `1` and is of type int.
Wrapping it in `()` did not convert it to a tuple. However, `(1,)` is a tuple.
Alternatively you could pass a list of the parameters, e.g.
c.execute("DELETE FROM ToDo WHERE Id=?",[user])
|
Using raw_input in python for lists
Question: I am trying to use raw_input in the python code to get user input of lists as
below.
input_array.append(list(raw_input()));
User input as:
1 2 3 5 100
But the code is interpreting input as
[['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']]
Try: If I use plain `input()` instead of `raw_input()`, I am facing the issue
in console.
"SyntaxError: ('invalid syntax', ('<string>', 1, 3, '1 2 3 4 100'))"
Note: I am not allowed to give the input in list format like
[1,2,3,5,100]
Could somebody please tell me how to proceed further.
Answer:
>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]
* * *
>>> raw_input().split()
1 2 3 5 100
['1', '2', '3', '5', '100']
Creates a new list split by whitespace and then
[int(x) for x in raw_input().split()]
Converts each string in this new list into an integer.
* * *
list()
is a function that constructs a list from an iterable such as
>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple
so
>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']
also works, the `list` function iterates through the string and appends each
character to a new list. However you need to separate by spaces so the `list`
function is not suitable.
`input` takes a string and converts it into an object
'1 2 3 5 100'
is not a valid python object, it is 5 numbers separated by spaces. To make
this clear, consider typing
>>> 1 2 3 5 100
SyntaxError: invalid syntax
into a Python Shell. It is just invalid syntax. So `input` raises this error
as well.
On an important side note: `input` is not a safe function to use so even if
your string was `'[1,2,3,5,100]'` as you mentioned you should not use `input`
because harmful python code can be executed through `input`. If this case ever
arises, use `ast.literal_eval`:
>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]
|
VIM/Python cannot return value to VIM
Question: I'm trying to create a Python plugin for VIM that will detect whether or not
the current project is an Android Project. Unfortunately, I cannot get it to
return boolean values back to VIM. Calling the plugin from within VIM just
outputs nothing. The code below uses the `print` command but I've also tried
`vim.command("return {value}")` and setting vim variables from within the
script. Any insight?
I have a plugin file with these contents
if !has('python')
echo "Error: Required vim compiled with +python"
finish
endif
" Get local path for the script, so we can import other files
let s:script_folder_path = escape( expand( '<sfile>:p:h' ), '\' )
let s:python_folder_path = s:script_folder_path . '/../python/'
" Start the python file in the scriptdir
function! s:startPyfile(fileName)
execute "pyfile " . s:python_folder_path . a:fileName
endfunction
command! Detect call Detect()
function! Detect()
call s:startPyfile("vim_detect.py")
endfunction
which calls vim_detect.py which contains this
#! /usr/bin/env python
import vim
import os
import sys
# Add current scriptdir to import sources
current_script_dir = vim.eval('s:python_folder_path')
sys.path.append(current_script_dir)
class VimDetect:
def executeCommand(self):
if self.isAndroidGradleProject():
print 1
else:
print 0
def isAndroidGradleProject():
if(isGradleProject() and isAndroidProject()):
return True
else:
return False
def isGradleProject():
if findFileInDirectory("build.gradle"):
return True
else:
return False
def isAndroidProject():
if findFileInDirectory("AndroidManifest.xml"):
return True
else:
return False
def findFileInDirectory(filename):
top = os.getcwd()
matches = 0
for root, dirnames, files in os.walk(top):
for file in fnmatch.filter(files, filename):
matches = matches + 1
if matches > 0:
return True
else:
return False
Answer: As others have commented, your example code (which you should have condensed
to a minimal example) isn't actually invoked. The way I've returned a result
from Python is by setting a Vim variable, like this:
strValue = "just a test"
vim.command("let python_result = '%s'" % str(strValue).replace("'", "''"))
For a boolean, just return `0` / `1` as a number, simplifying the logic:
vim.command("let python_result = %d" % int(boolValue))
|
why argument of type 'NoneType' is not iterable is shown in my program
Question: i made this hangman program but it is giving 'nonetype' error whenever i run
it program running- Whenever I enter a word the output is like this Hang Man
Game Guess a word a \----- You gussed one word correctly
-----a---------------
Traceback (most recent call last):
File "F:/coding/python/python programming for absolute beginners/chapter 5/Hang Man Game.py", line 129, in <module>
if guess in used:
TypeError: argument of type 'NoneType' is not iterable
The code:
print("\t\t\tHang Man Game")
import random
set=("happy","australia","punjab","criclet","tennis")
choose=random.choice(set)
correct=choose
HANGMAN=('''
_______
|
|
|
|
|
|
|
|
|
|
|
___
''',
'''
______________
| |
|
|
|
|
|
|
|
|
|
___
''',
'''
______________
| |
| O
|
|
|
|
|
|
|
|
___
''',
'''
______________
| |
| O
| |
| |
| |
| |
|
|
|
|
___
''',
'''
______________
| |
| O
| |
| ---|
| |
| |
|
|
|
|
___
''',
'''
______________
| |
| O
| |
| ---|---
| |
| |
|
|
|
|
___
''',
'''
______________
| |
| O
| |
| ---|---
| |
| |
| /
| /
| /
|
___
''',
'''
______________
| |
| O
| |
| ---|---
| |
| |
| / \
| / \
| / \
|
___
'''
)
MAX_WRONG=(len(HANGMAN)-1)
wrong=0
new=""
used=[]
so_far="-"*len(correct)
guess=raw_input("Guess a word\n")
while(so_far!=correct and wrong<MAX_WRONG):
print(so_far)
if guess in used:
print("you have already used it")
else:
if guess in correct:
print("You gussed one word correctly\n")
used.append(guess)
for i in range(len(correct)):
if guess==correct[i]:
new=new+guess
else:
new=new+so_far
so_far=new
else:
used=used.append(guess)
wrong=wrong+1
Answer: You cannot do this
used = used.append(guess)
The `append` function returns `None`, it modifies `used` in place. So you are
basically appending `guess` on the right hand side, but then assigning `None`
to `used`. So the next iteration of the `while` loop you are trying to iterate
over `None`, which is what the error is telling you.
You simply need to say
used.append(guess)
Or
used += [guess]
|
Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?
Question: I am trying to write an application that applies a function concurrently with
a `multiprocessing.Pool`. I would like this function to be an instance method
(so I can define it differently in different subclasses). This doesn't seem to
be possible; as I have learned elsewhere, apparently [bound methods can't be
pickled](http://stackoverflow.com/questions/1816958/cant-pickle-type-
instancemethod-when-using-pythons-multiprocessing-pool-ma). So why does
starting a `multiprocessing.Process` with a bound method as a target work? The
following code:
import multiprocessing
def test1():
print "Hello, world 1"
def increment(x):
return x + 1
class testClass():
def process(self):
process1 = multiprocessing.Process(target=test1)
process1.start()
process1.join()
process2 = multiprocessing.Process(target=self.test2)
process2.start()
process2.join()
def pool(self):
pool = multiprocessing.Pool(1)
for answer in pool.imap(increment, range(10)):
print answer
print
for answer in pool.imap(self.square, range(10)):
print answer
def test2(self):
print "Hello, world 2"
def square(self, x):
return x * x
def main():
c = testClass()
c.process()
c.pool()
if __name__ == "__main__":
main()
Produces this output:
Hello, world 1
Hello, world 2
1
2
3
4
5
6
7
8
9
10
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python27\Lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "C:\Python27\Lib\threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python27\Lib\multiprocessing\pool.py", line 319, in _handle_tasks
put(task)
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
Why can Processes handle bound methods, but not Pools?
Answer: The `pickle` module normally can't pickle instance methods:
>>> import pickle
>>> class A(object):
... def z(self): print "hi"
...
>>> a = A()
>>> pickle.dumps(a.z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/usr/local/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/usr/local/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/usr/local/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
However, the `multiprocessing` module [has a custom `Pickler` that adds some
code to enable this
feature](https://hg.python.org/cpython/file/84928af5d703/Lib/multiprocessing/forking.py#l56):
#
# Try making some callable types picklable
#
from pickle import Pickler
class ForkingPickler(Pickler):
dispatch = Pickler.dispatch.copy()
@classmethod
def register(cls, type, reduce):
def dispatcher(self, obj):
rv = reduce(obj)
self.save_reduce(obj=obj, *rv)
cls.dispatch[type] = dispatcher
def _reduce_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name)
ForkingPickler.register(type(ForkingPickler.save), _reduce_method)
You can replicate this using the
[`copy_reg`](https://docs.python.org/2/library/copy_reg.html) module to see it
work for yourself:
>>> import copy_reg
>>> def _reduce_method(m):
... if m.im_self is None:
... return getattr, (m.im_class, m.im_func.func_name)
... else:
... return getattr, (m.im_self, m.im_func.func_name)
...
>>> copy_reg.pickle(type(a.z), _reduce_method)
>>> pickle.dumps(a.z)
"c__builtin__\ngetattr\np0\n(ccopy_reg\n_reconstructor\np1\n(c__main__\nA\np2\nc__builtin__\nobject\np3\nNtp4\nRp5\nS'z'\np6\ntp7\nRp8\n."
When you use `Process.start` to spawn a new process on Windows, [it pickles
all the parameters you passed to the child process using this custom
`ForkingPickler`](https://hg.python.org/cpython/file/84928af5d703/Lib/multiprocessing/forking.py#l181):
#
# Windows
#
else:
# snip...
from pickle import load, HIGHEST_PROTOCOL
def dump(obj, file, protocol=None):
ForkingPickler(file, protocol).dump(obj)
#
# We define a Popen class similar to the one from subprocess, but
# whose constructor takes a process object as its argument.
#
class Popen(object):
'''
Start a subprocess to run the code of a process object
'''
_tls = thread._local()
def __init__(self, process_obj):
# create pipe for communication with child
rfd, wfd = os.pipe()
# get handle for read end of the pipe and make it inheritable
...
# start process
...
# set attributes of self
...
# send information to child
prep_data = get_preparation_data(process_obj._name)
to_child = os.fdopen(wfd, 'wb')
Popen._tls.process_handle = int(hp)
try:
dump(prep_data, to_child, HIGHEST_PROTOCOL)
dump(process_obj, to_child, HIGHEST_PROTOCOL)
finally:
del Popen._tls.process_handle
to_child.close()
Note the "send information to the child" section. It's using the `dump`
function, which uses `ForkingPickler` to pickle the data, which means your
instance method can be pickled.
Now, when you use methods on `multiprocessing.Pool` to send a method to a
child process, it's using a `multiprocessing.Pipe` to pickle the data. In
Python 2.7, `multiprocessing.Pipe` is implemented in C, [and calls
`pickle_dumps`
directly](https://hg.python.org/cpython/file/84928af5d703/Modules/_multiprocessing/connection.h#l260),
so it doesn't take advantage of the `ForkingPickler`. That means pickling the
instance method doesn't work.
However, if you use `copy_reg` to register the `instancemethod` type, rather
than a custom `Pickler`, _all_ attempts at pickling will be affected. So you
can use that to enable pickling instance methods, even via `Pool`:
import multiprocessing
import copy_reg
import types
def _reduce_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _reduce_method)
def test1():
print("Hello, world 1")
def increment(x):
return x + 1
class testClass():
def process(self):
process1 = multiprocessing.Process(target=test1)
process1.start()
process1.join()
process2 = multiprocessing.Process(target=self.test2)
process2.start()
process2.join()
def pool(self):
pool = multiprocessing.Pool(1)
for answer in pool.imap(increment, range(10)):
print(answer)
print
for answer in pool.imap(self.square, range(10)):
print(answer)
def test2(self):
print("Hello, world 2")
def square(self, x):
return x * x
def main():
c = testClass()
c.process()
c.pool()
if __name__ == "__main__":
main()
Output:
Hello, world 1
Hello, world 2
GOT (0, 0, (True, 1))
GOT (0, 1, (True, 2))
GOT (0, 2, (True, 3))
GOT (0, 3, (True, 4))
GOT (0, 4, (True, 5))
1GOT (0, 5, (True, 6))
GOT (0, 6, (True, 7))
2
GOT (0, 7, (True, 8))
3
GOT (0, 8, (True, 9))
GOT (0, 9, (True, 10))
4
5
6
7
8
9
10
GOT (1, 0, (True, 0))
0
GOT (1, 1, (True, 1))
1
GOT (1, 2, (True, 4))
4
GOT (1, 3, (True, 9))
9
GOT (1, 4, (True, 16))
16
GOT (1, 5, (True, 25))
25
GOT (1, 6, (True, 36))
36
GOT (1, 7, (True, 49))
49
GOT (1, 8, (True, 64))
64
GOT (1, 9, (True, 81))
81
GOT None
Also note that in Python 3.x, `pickle` can pickle instance method types
natively, so none of this stuff matters any more. :)
|
appending a list from a read text file python3
Question: I am attempting to read a txt file and create a dictionary from the text. a
sample txt file is:
John likes Steak
John likes Soda
John likes Cake
Jane likes Soda
Jane likes Cake
Jim likes Steak
My desired output is a dictionary with the name as the key, and the "likes" as
a list of the respective values:
{'John':('Steak', 'Soda', 'Cake'), 'Jane':('Soda', 'Cake'), 'Jim':('Steak')}
I continue to run into the error of adding my stripped word to my list and
have tried a few different ways:
pred = ()
prey = ()
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
while line!= "":
line = line.split()
pred.append = (line[0])
prey.append = (line[2])
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
and also:
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
while line!= "":
line = line.split()
if line[0] in chain:
chain[line[0] = [0, line[2]]
else:
chain[line[0]] = line[2]
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
any ideas?
Answer: This will do it (without needing to read the entire file into memory first):
likes = {}
for who, _, what in (line.split()
for line in (line.strip()
for line in open('likes.txt', 'rt'))):
likes.setdefault(who, []).append(what)
print(likes)
Output:
{'Jane': ['Soda', 'Cake'], 'John': ['Steak', 'Soda', 'Cake'], 'Jim': ['Steak']}
Alternatively, to simplify things slightly you could use a
temporary`collections.defaultdict`:
from collections import defaultdict
likes = defaultdict(list)
for who, _, what in (line.split()
for line in (line.strip()
for line in open('likes.txt', 'rt'))):
likes[who].append(what)
print(dict(likes)) # convert to plain dictionary and print
|
read in one row of csv file (based on input if i can) with DictReader, then format and write to new file
Question: I'm trying to read in a csv file with many rows and columns; i would like to
print one row, in a particular format, to a text file, and do some hashing on
the values. SO far, i have been able to read in the file, parse thru it using
DictReader, find the row i want using an IF statement and then print the keys
and values. I cannot figure out how to format it to the format i want in the
end ( Key = Value \n), and i cannot figure how to write to a file (much less
in the format i want) using the value of 'row' obtained below. I've been
trying for days and make a little progress but cannot get it to work. Here is
what i got to work (with much detail left out of results):
* * *
>>>import csv
with open("C:\path_to_script\filename_Brief.csv") as infh:
reader = csv.DictReader(infh)
for row in reader:
if row['ALIAS'] == 'Y4K':
print(row)
# result-output
{'Full_Name': 'Jack Flash', 'PHONE_NO': '555 555-1212', 'ALIAS': 'Y4K'}
* * *
I'd like to ask the user to input the Alias and then use that to determine row
to print. I've done a ton of research but am new-ish to Python so am asking
for help! i've used pyexcel, xlrd/xlwt, even thought I'd try pandas but too
much to learn. I also got it to format the way i wanted in one test but then
could not get the row selection to work--in other words, it prints all the
records rather than the row i want. Have 30 Firefox tabs open trying to find
an answer! Thanks in advance!
Answer: The following may at least be close to what you want (I think):
import csv
with open(r'C:\path_to_script\filename_Brief.csv') as infh, \
open('new_file.txt', 'wt') as outfh:
reader = csv.DictReader(infh)
for row in reader:
if row['ALIAS'] == 'Y4K':
outfh.write('Full_Name = {Full_Name}\n'
'PHONE_NO = {PHONE_NO}\n'
'ALIAS = {ALIAS}\n'.format(**row))
This would write 3 lines formatted like this into the output file for every
matching`row`:
Full_Name = Jack Flash
PHONE_NO = 555 555-1212
ALIAS = Y4K
BTW, the `**row`notation means basically "take all the entries in the
specified dictionary and turn them into keyword arguments for this function
call". The `{keyword}` syntax in the format string refers to any keyword
arguments that will be passed to the `str.format()` method.
|
Solving constrained maximization with SciPy
Question: Function to maximize:
x[0] + x[1] + x[2]
Constraints:
0.2 * x[0] + 0.4 * x[1] - 0.33 * x[2] <= 25
5 * x[0] + 8.33 * x[2] <= 130
...
x[0] >= 0
x[1] >= 0
x[2] >= 0
My code looks like:
from numpy import *
from scipy.optimize import minimize
cons = ({'type': 'ineq', 'fun': lambda x: array([25 - 0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]])},
{'type': 'ineq', 'fun': lambda x: array([130 - 5 * x[0] - 8.33 * x[2]])},
{'type': 'ineq', 'fun': lambda x: array([16 - 0.6 * x[1] - 0.33 * x[2]])},
{'type': 'ineq', 'fun': lambda x: array([7 - 0.2 * x[0] - 0.1 * x[1] - 0.33 * x[2]])},
{'type': 'ineq', 'fun': lambda x: array([14 - 0.5 * x[1]])},
{'type': 'ineq', 'fun': lambda x: array([x[0]])},
{'type': 'ineq', 'fun': lambda x: array([x[1]])},
{'type': 'ineq', 'fun': lambda x: array([x[2]])})
f = lambda x: -1 * (x[0] + x[1] + x[2])
res = minimize(f, [0, 0, 0], method='SLSQP', constraints=cons, options={'disp': True})
print(res)
Unfortunately, result I got is:
Positive directional derivative for linesearch (Exit mode 8)
Current function value: -18240083542.4
Iterations: 20
Function evaluations: 180
Gradient evaluations: 16
x: array([ 6.05846118e+09, 6.05846118e+09, 6.12316118e+09])
jac: array([ 0., 0., 0., 0.])
message: 'Positive directional derivative for linesearch'
fun: -18240083542.377449
status: 8
njev: 16
nfev: 180
nit: 20
success: False
I can successfully solve this problem in Excel Solver, so I guess I do
something wrong in Python.
Answer: Bug in SciPy, code works under Python2, but refuses to work under Python3
Issue on GitHub: <https://github.com/scipy/scipy/issues/4240>
|
How do I correctly pass double quotes to an awk subprocess in Python?
Question: I am trying to run simple awk shell command and capture its output (using
python2). Here is what I try to do:
import subprocess as sb
shell = ["awk '!/<tag>/ {print \"\\"\"$1\"\\"\", \"\\"\"$2\"\\"\"}' test.txt"]
p = sb.check_output(shell, shell=True)
print p
`test.txt` content:
a, b, 5
a, c, 3
d, d, 1
I want the to get the following output with awk and store it into a variable:
"a" "b"
"a" "c"
"d" "d"
However I obviously lack the knowledge of how to properly handle **double
quotes**. I tried escaping them with several backsplashes, it all didn't work.
How to correctly escape the double quotes so that the example above work?
Answer: When you use `shell=True` but pass a list, you're asking Python to merge your
list of strings together as if they were separate arguments. That means it may
do its own quoting, on top of whatever quoting you did, in hopes that the
shell will reverse things properly. This is going to be a nightmare to get
right. If you want to use `shell=True`, just pass a string.
But that raises the question of why you're using `shell=True` in the first
place. If you didn't use this, you could just pass a list of arguments,
without having to quote any of them to protect them from the shell. Much
easier to write, and easier to debug, and more efficient and more secure to
boot. Unless you actually need shell features, or you've got a command line
that you worked hard to get working and don't want to spend time breaking down
into separate arguments, never use the shell.
* * *
I'm not actually sure what `awk` command you're _trying_ to run here. If you
give it the double-quotes around `$1` and `$2` it's just going to print a
literal `"$1" "$2"`, because that's what quotes mean to awk. Maybe you wanted
something like this?
awk '!/<tag>/ {print "\""$1"\"", "\""$2"\""}' test.txt
In which case:
subprocess.check_output(['awk', r'!/<tag>/ {print "\""$1"\"", "\""$2"\""}',
'test.txt'])
(Note that I used a raw string so I could pass the `"\""` literally, without
having to backslash the backslash.)
But this still doesn't provide your desired output, because `$1` is going to
be `a,`, so `"\""$1"\""` is going to be `"a,"`.
|
Python 3.4 - Connect to imap server using only TLSv1
Question: I'm trying to connect to an imap mail server using only TLSv1 in Python 3.4.
After much troubleshooting (most of which determined that the mail server only
supports TLSv1), I've found that I can connect to the server using openssl:
openssl s_client -connect mail.calpoly.edu:993 -tls1
as well as with the sockets package in Python 2.7:
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> import socket
>>>
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> ssl_sock = ssl.wrap_socket(sock=sock, ssl_version=ssl.PROTOCOL_TLSv1)
>>> ssl_sock.connect(('mail.calpoly.edu', 993))
>>> ssl_sock
<ssl.SSLSocket object at 0x7fbab6e7aed8>
When I try to connect in Python 3.4, however, I get a Handshake error:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> import socket
>>>
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> ssl_sock = ssl.wrap_socket(sock=sock, ssl_version=ssl.PROTOCOL_TLSv1)
>>> ssl_sock.connect(('mail.calpoly.edu', 993))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/ssl.py", line 841, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.4/ssl.py", line 832, in _real_connect
self.do_handshake()
File "/usr/lib/python3.4/ssl.py", line 805, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:598)
It seems like Python 3.4 tries to use sslv3 even though I tell it not to.
Does anyone know why this is happening and how I can work around it?
P.S. - I'll be using imaplib in the code that will interface with the server.
I used sockets in this example to highlight that this doesn't seem to be just
an issue with the imaplib package.
Answer: > ...most of which determined that the mail server only supports TLSv1
Does this mean that the server will croak on any other handshake? Typically a
client will start with the best protocol it can (like TLSv12) and if the
server does not support it, then it will just reply with a lower protocol
(like TLSv1 in this case). But, some servers are just broken or there is a
broken middlebox in between.
[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure
....
It seems like Python 3.4 tries to use sslv3 even though I tell it not to.
Not necessarily. TLS1.0 is just SSL3.1 and lots of TLS handling is actually
done with SSLv3 functions. So this error message might be confusing.
When checking the server out with [some tool](https://github.com/noxxi/p5-io-
socket-ssl/blob/master/util/analyze-ssl.pl) it looks like, that it
* will return "unsupported protocol" with SSL3.0, which is fine.
* will croak with with TLS1.1 instead of just returning with TLS1.0. This means that the server or some middlebox in between is seriously broken.
* will only accept RC4-MD5 as a cipher and croak on any other ciphers. This also makes it broken because it should return "no shared ciphers" on unsupported ciphers instead.
RC4-MD5 also is the reason for not working with python 3.4. Contrary to python
2.7 there is a more secure default cipher set in python 3.4 which includes
"..:!MD5". This means the python 3.4 client will not offer RC4-MD5 as cipher
and thus the handshake will fail because of no shared ciphers.
Fix would be to fix the broken server. Workaround might be to explicitly set
the cipher for your connecion, i.e. `wrap_socket( ... , ciphers="RC4-MD5")` or
similar
|
Python, yahoo yql quote error
Question: I have used the yql Console and have received an appropriate response.
However, sending a python based query, I continue to have an error. First the
console example:
select * from yahoo.finance.quotes where symbol in ("yahoo", "aapl")
I receive a results block that has the expected fields. The python example:
import requests
base_url = 'https://query.yahooapis.com/v1/public/yql?'
query = 'q=select * from yahoo.finance.quotes where symbol in ("YHOO", "AAPL")'
full_query=base_url + query
result = requests.get(full_query)
print(result.content)
With the following response:
b'\nNo definition found for Table yahoo.finance.quotes'
What am I missing? TIA, Clayton
Answer: What you are missing is the env part of the query:
import json
import urllib
from pprint import pprint
base_url = 'https://query.yahooapis.com/v1/public/yql?'
query = {
'q': 'select * from yahoo.finance.quote where symbol in ("YHOO","AAPL")',
'format': 'json',
'env': 'store://datatables.org/alltableswithkeys'
}
url = base_url + urllib.urlencode(query)
response = urllib.urlopen(url)
data = response.read()
quote = json.loads(data)
pprint(quote)
Output:
{u'query': {u'count': 2,
u'created': u'2014-12-06T03:53:23Z',
u'lang': u'en-US',
u'results': {u'quote': [{u'AverageDailyVolume': u'38009400',
u'Change': u'+0.58',
u'DaysHigh': u'51.25',
u'DaysLow': u'50.51',
u'DaysRange': u'50.51 - 51.25',
u'LastTradePriceOnly': u'50.99',
u'MarketCapitalization': u'48.305B',
u'Name': u'Yahoo! Inc.',
u'StockExchange': u'NasdaqNM',
u'Symbol': u'YHOO',
u'Volume': u'15418123',
u'YearHigh': u'52.62',
u'YearLow': u'32.15',
u'symbol': u'YHOO'},
{u'AverageDailyVolume': u'57049800',
u'Change': u'-0.49',
u'DaysHigh': u'116.08',
u'DaysLow': u'114.64',
u'DaysRange': u'114.64 - 116.08',
u'LastTradePriceOnly': u'115.00',
u'MarketCapitalization': u'674.5B',
u'Name': u'Apple Inc.',
u'StockExchange': u'NasdaqNM',
u'Symbol': u'AAPL',
u'Volume': u'38318896',
u'YearHigh': u'119.75',
u'YearLow': u'70.5071',
u'symbol': u'AAPL'}]}}}
|
How to write output of web scrape to column instead of rows in Beautiful Soup
Question: I'm trying to write the results of scraping a webpage to a CSV file. I have
successfully written the output to CSV but it went in as rows instead of
columns. Here is the script:
import bs4
import requests
import csv
#get webpage for Apple inc. September income statement
page = requests.get("https://au.finance.yahoo.com/q/is?s=AAPL")
#put into beautiful soup
soup = bs4.BeautifulSoup(page.content)
#select table that holds data of interest
table = soup.find("table", class_="yfnc_tabledata1")
#creates generator that holds four values that are yearly revenues for company
revenue = table.tr.td.table.tr.next_sibling.td.next_siblings
#iterates through generator from above and writes output to CSV file
for value in revenue:
value = value.get_text(strip=True)
with open('/home/kwal0203/Desktop/Apple.csv', 'a') as csvfile:
s = csv.writer(csvfile)
s.writerow([data.encode("utf-8") for data in [value]])
I understand there is a `zip()` function in Python that may be of use but
haven't been able to figure out how I can apply it to this situation.
Thanks any help appreciated.
Answer: You have the right idea, **zip** can easily help you here:
#creates generator that holds four values that are yearly revenues for company
revenue = table.tr.td.table.tr.next_sibling.td.next_siblings
revenue = zip(*revenue) # <------ yes, it is that easy
#iterates through generator from above and writes output to CSV file
for value in revenue:
value = value.get_text(strip=True)
...
|
Simple Guess My Number Game in Python - invalid syntax
Question: I try to make a simple guessing game with the "Python programming for absolute
beginner" book. Game should generate random number from 0 to 10, then take
player's guesses and print "Too high!", if the guessed number is too high, or
"Too low!" if the number is too low. After each guess, game adds 1 to the
number of guesses. It ends, when the player's guess is correct and displays
number of guesses taken.
My code is exactly the same, as code in the book, but when I run it in IDLE, I
get "invalid syntax" error on "tries += 1" line. When I delete this line, the
error happens on the next line etc. When I run it from file, it just opens and
closes immediately. I use Python 3.4.1.
import random
number = random.randint(0,10)
player_guess = int(input("What's your guess?"))
tries = 1
while player_guess != number:
if player_guess > number:
print("Too high!")
else:
print("Too low!")
player_guess = int(input("What's your guess?")
tries += 1
print("Congrats!")
print(tries)
input("\n\nPress any key...")
Answer: You're missing a closing parentheses `)` on the above line to complete the
`int` conversion.
|
Using Python to Access Methods From C# Library - Interop .dll File
Question: I have a .dll file (with "Interop." prefix) containing a library written in
C#. Within the library is a class, several enums, several interfaces, and
several delgates. (Observed by decompiling the .dll with JetBrains dotPeek)
See the dll structure here:

I need to use pure Python to access the methods within the class. I have
tried:
from ctypes import *
name = "Interop.HTBRAILLEDRIVERSERVERLib.dll"
mydll = cdll.LoadLibrary(name)
However attempting to call any of the methods contained in the class
"HtBrailleDriverClass" leads to "AttributeError: function 'initialize' not
found". I have also attempted to access them from their ordinal indexes:
print mydll[1]
However this gives the error "AttributeError: function ordinal 1 not found".
Is anyone able to shed light on why I am unable to access the class within
this .dll and why I cannot access any of the methods either?
Please bear in mind I must use pure Python.
Answer: You can use python.net to access it
import clr,sys
sys.path.append("path of your dll")
clr.AddReference("YourDllName")
import YourDllName
Then Try printing any value of member of your class like
print YourDllName.ClassName.Member
from your python script
**Note : Your need to put clr.pyd and python.runtime.dll inside your**
**Python27/Dlls folder**
If You don't want to append your dll path then put the dll inside the
python2.x/Lib/site-packages folder . Then u can avoid 2nd line -
sys.path.append() too .
|
HTMLParser for Python 3.4
Question: I have some code written in Python(2.7) which uses HTMLParser. I am using
Pyhton 3.4 currently.
I can not find HTMLParse download module. I have searched a lot. I cannot find
it.
I am concerned if it even exists. If it exists, please share the link. If not,
what should I do?
Answer: You don't need install html parser for Python 3. It's pre installed. Just use:
import html.parser
|
TypeError: object() takes no parameters - making games
Question: I'm quite new to Python programming and just picked it up about a week ago. I
wrote (significantly altered) a game based on a pre-existing code and ran the
code and got an error message. So I went back to the original code that's
supposed to be working and ran the code but got the same following messages:
File "Game1.py", line 211, in <module>
a_map = Map('central_corridor')
TypeError: object() takes no parameters
Here is the original code:
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def _init_(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you."
action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
class TheBridge(Scene):
def enter(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
class EscapePod(Scene):
def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
return 'finished'
class Finished(Scene):
def enter(self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def _init_(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
I know it shouldn't have that error message and I tried to debug it for quite
some time now. I just can't figure it out. Please help a brother out. Thanks
much in advance.
Answer: You need double underscores for your init method in the Map class. You only
have single underscores currently.
def __init__(self, start_scene):
self.start_scene = start_scene
Same thing in the `Engine` class
Also un-indent all your methods in the `Map` class one level. They should only
be indented in one level from the Class declaration.
|
Creating a window with an unknown amount of checkboxes - Python/tkinter
Question: I'm working on a project for my computer science class involving python and
tkinter. I'm trying to make a fully-functional Monopoly game, and it's coming
along well. I've finally hit one roadblock that I can't seem to overcome. I'm
trying to make an interface to mortgage a user's properties, and I would like
to use tkinter checkbuttons to get user input, and then mortgage all of the
properties that were checked. Here's the snippet of the class I've made:
from tkinter import *
class Mortgager(Tk):
def __init__(self,coorder): # 'coorder' is a class that coordinates all of the
self.coorder = coorder # other classes together
Tk.__init__(self,className='Mortgager')
self.title('Mortgaging')
self.cbuttons = []
self.intvars = []
for prop in coorder.active_player.properties: # iterate through player's currently owned properties
if not prop.mortgaged:
self.intvars.append(IntVar(self,0))
self.cbuttons.append(Checkbutton(self,
variable=self.intvars[-1],text=prop.get_name(),
# Most recent intvar, method returns name of property
command=self.update_cash_onscreen)
#### Not sure what to do here...
self.cbuttons[-1].var = self.intvars[-1]
self.cbuttons[-1].text = prop.get_name()
i = 0
for cbutton in self.cbuttons: # Every three properties, new column
cbutton.grid(column=i//3,row=i%3,sticky=W,
padx=5,pady=5)
i += 1
# Haven't finished the rest of the class...
My question is this: How can I create an arbitrary amount of checkbuttons,
then tell which checkbuttons have been clicked "on the go," update some sort
of `Label` that displays the current amount to be mortgaged, with a
`StringVar` or something like that, and then do something with that total
amount?
Thanks in advance!
Answer: I quite did not understand your code but if you want to create N checkbuttons
with labels in a list "ctrls" try this
# if ctrls is a list of all lables to your checkboxes
# i is the count and j is the text of label
for i,j in enumerate(ctrls): #what ever loop you want
var = IntVar()
c = Checkbutton(self.master,text=j,variable=var)
boxes.append([j.strip(),var,c])
later if you want to check which buttons are checked
for i in boxes:
if i[1].get()==0:
#do what ever you want
i[2].destroy()
|
How to send an email in python?
Question: I would like to send an email in Python. Below an example code:
#!/usr/bin/python
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print("Send OK.")
except SMTPException:
print("Send NOT OK.")
When I try to run this program I got some errors:
Traceback (most recent call last):
File ".\sendEmail.py", line 16, in <module>
smtpObj = smtplib.SMTP('localhost')
File "C:\Python34\lib\smtplib.py", line 242,
(code, msg) = self.connect(host, port)
File "C:\Python34\lib\smtplib.py", line 321,
self.sock = self._get_socket(host, port, se
File "C:\Python34\lib\smtplib.py", line 292,
self.source_address)
File "C:\Python34\lib\socket.py", line 509, i
raise err
File "C:\Python34\lib\socket.py", line 500, i
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Nie mo
During handling of the above exception, another
Traceback (most recent call last):
File ".\sendEmail.py", line 19, in <module>
except SMTPException:
NameError: name 'SMTPException' is not defined
How can I improve this code to send an email? Thanks.
Answer: Look at this line:
`smtpObj = smtplib.SMTP('localhost')`
You're trying to connect to localhost - your own computer. Do you have running
SMTP server? I don't think so.
Configure proper SMTP server. You can use your personal e-mail account for
that.
|
Remove or keep specific columns in csv file
Question: I have a simple script to either remove last n columns from csv file or to
keep first n columns only in csv file:
from sys import argv
import csv
if len(argv) == 4:
script, inputFile, outputFile, n = argv
n = [int(i) for i in n.split(",")]
else:
script, inputFile, outputFile = argv
n = 1
with open(inputFile,"r") as fin:
with open(outputFile,"w") as fout:
writer=csv.writer(fout)
for row in csv.reader(fin):
writer.writerow(row[:n])
Example usage (remove last two columns): `removeKeepColumns.py sample.txt
out.txt -2`
How do I extend this to handle possibility to keep/remove specific set of
columns, e.g.:
* remove columns 3,4,5
* keep only columns, 1,4,6
I can split input arguments separted by comma into array, but don't know hot
to pass this to `writerow(row[])`
Links to scripts I used to create my example:
* [Delete or remove last column in CSV file using Python](http://stackoverflow.com/questions/7245738/delete-or-remove-last-column-in-csv-file-using-python)
* [Can sys.argv handle optional arguments?](http://stackoverflow.com/questions/9442313/can-sys-argv-handle-optional-arguments)
* [What is the easiest way to convert list with str into list with int?](http://stackoverflow.com/questions/2424412/what-is-the-easiest-way-to-convert-list-with-str-into-list-with-int)
Answer: Well there was an accepted answer already, here's my solution:
>>> import pyexcel as pe
>>> sheet = pe.load("your_file.csv")
>>> sheet.filter(sheet.ColumnFilter([1,4,5])) # the column indices to keep
>>> sheet.save_as("your_filtered_file.csv")
>>> exit()
Here is more details on
[filtering](http://pyexcel.readthedocs.org/en/latest/tutorial02.html)
|
Error importing module from package, package itself imported but empty, pip says package installed and up-to-date
Question: I have anaconda python 2.7 and installed the shapely package. Importing the
whole package does not give errors, but then when trying to access modules
that should be loaded, they dont seem to be there. Also importing the specific
module throws an error.
This is the error I get when importing the module
import shapely.geometry
WindowsError: [Error 126] The specified module could not be found
Though importing the whole package seems to work
import shapely
dir(shapely)
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__',
'__version__',
'ctypes_declarations',
'ftools']
So the modules are not there even though shapely seems to be there.
pip has it in its list
pip list
Shapely (1.5.1)
Then when I try to install with pip anyways:
pip install shapely
Requirements already satisfied: shapely in d:\...
Trying to upgrade with pip:
pip install shapely --upgrade
Requirements already up-to-date: shapely in d:\...
Forcing reinstall with pip as per
[this](http://stackoverflow.com/questions/19548957/can-i-force-pip-to-
reinstall-the-current-version) answer did not change the errors.
Deinstalling with pip and installing it again gives a warning:
warning the c extension could not be compiled speedups are not enabled
Im not sure whats wrong here and how I can fix it, any hints to help me in the
right direction would be super, thanks!
Answer: wwii `s comment solved this, using a windows installer did work. I got it from
[here](https://pypi.python.org/pypi/Shapely#downloads). Probably properly
installing and configuring a compiler would also work.
|
how to find all the index of an element in a list Python
Question: If I have a list
a=[1,0,0,1,0,1,1,1,0,1,0,0]
I want to find the index of 0 and 1 respectively, say in this case,
index_0 = [1,2,4,8,10,11]
index_1 = [0,3,5,6,7,9]
is there an efficient way to do this?
Answer:
index_0 = [i for i, v in enumerate(a) if v == 0]
index_1 = [i for i, v in enumerate(a) if v == 1]
Or with numpy:
import numpy as np
a = np.array(a)
index_0 = np.where(a == 0)[0]
index_1 = np.where(a == 1)[0]
|
Python Merge 2 or more Dicts using a value to handle duplicate keys
Question: I am merging dictionaries that have some duplicate keys. The values will be
different and I want to ignore the lower value record.
dict1 = {1 :["in",1], 2 :["out",1], 3 :["in",1]}
dict2 = {1 :["out",2], 2 :["out",1]}
If the keys are equal I want the `key[0][1`] with the greatest value to be in
the new dict. The output of merging these 2 dicts should be:
dict3 = {1 :["out",2], 2 :["out",1], 3 :["in",1]}
The only way I know to solve this is to run a loop with a condition to
determine which one to add into the merged dict. Is there a more pythonic way
of doing it?
The duplicate keys will be very few and far between, less than 1% if that will
make any difference to the end solution.
Answer: A single dictionary comprehension can do this
from operator import itemgetter
{k: max(dict1.get(k, (None, float('-Inf'))), dict2.get(k, (None,float('-Inf'))),
key=itemgetter(1)) for k in dict1.viewkeys() | dict2.viewkeys()}
|
Python Boolean in Brackets?
Question: I'm working on OpenCV using python, and in the edge detection script
[here](https://code.google.com/p/pythonxy/source/browse/src/python/OpenCV/DOC/samples/python2/edge.py?repo=xy-27&r=a2e41c7a3cb6db536b948747872cab71c696b44e)
I've encountered something I've never seen before. I apologize if this
question has been asked before on here, but I'm not really sure what to search
for.
I've pasted the relevant piece below:
while True:
flag, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thrs1 = cv2.getTrackbarPos('thrs1', 'edge')
thrs2 = cv2.getTrackbarPos('thrs2', 'edge')
edge = cv2.Canny(gray, thrs1, thrs2, apertureSize=5)
vis = img.copy()
vis /= 2
vis[edge != 0] = (0, 255, 0) #This is the line I'm trying to figure out
cv2.imshow('edge', vis)
The code isn't mine, but is part of the OpenCV documentation. As best as I can
tell, vis[edge != 0] is going through each element in edge, comparing it to
true, and then somehow (this is the strange part to me) turning the result of
the boolean evaluation into xy coordinates for vis, and then setting the image
value to green.
It just seems a little magical to me, as I've never encountered anything like
this, since I'm mostly a C/C++ programmer. Can someone point me to the docs
where I can read up on it? I have STFW unsuccessfully because I don't know
what to call this behavior.
Answer: `vis` is a numpy array, and the `[edge != 0]` seems like syntactic sugar for
the `numpy.where()` function...so its thresholding the values with Canny and
then drawing a green line on the `vis` image where the edges are.
Here is an analogous example.
import numpy as np
x = np.arange(10)
y = np.zeros(10)
print y
y[x>3] = 10
print y
|
How can I use pyglet batches to draw scenes or levels
Question: So I'm currently learning pyglet for Python 2.7 and I'm trying to make a
simple game that has levels. The 1st 'scene' would be the title/intro part,
2nd would be a tutorial of some sort, and the rest are the game levels
themselves.
For this, I've created 7 batches(1 intro, 1 tutorial, 5 levels) namely batch,
batch1, ... batch6. I've also created 7 classes for each of these batches that
represent the scenes/levels. This is what I've done for the intro batch and
class:
batch = pyglet.graphics.Batch()
batch1 = pyglet.graphics.Batch()
class StartState:
def __init__(self):
self.welcome = pyglet.text.Label('WELCOME TO', font_name='Arial', font_size=32, color=(200,255,255,255), x=400, y=550, anchor_x='center', anchor_y='center', batch=batch)
self.title = pyglet.text.Label("MY GAME", font_name='Arial', font_size=32, color=(100,200,170,255), x=400, y=450, anchor_x='center', anchor_y='center', batch=batch)
self.press = pyglet.text.Label("press 'SPACE' to continue", font_name='Arial', font_size=32, color=(200,255,150,255), x=400, y=250, anchor_x='center', anchor_y='center', batch=batch)
def update(self, dt):
if keymap[pyglet.window.key.SPACE]:
self.welcome.delete()
self.title.delete()
self.press.delete()
states.pop()
batch1.draw()
The other scenes would also look like that. the states list is a list that I
use to store my classes/scenes. states = [Level5(), Level4(), ... ,
TutorialState(), StartState()]. So every time the condition to advance is
fulfilled, which in this class is to press 'SPACE', the window will be
'cleared' i.e. delete the sprites/labels and proceed to the next scene by
using states.pop() and batch1.draw().
After I've typed these classes, I added this at the end:
@window.event
def on_draw():
window.clear()
batch.draw()
def update(dt):
if len(states):
states[-1].update(dt)
else:
pyglet.app.exit()
states.append(Level5())
states.append(Level4())
states.append(Level3())
states.append(Level2())
states.append(Level1())
states.append(TutorialState())
states.append(StartState())
pyglet.clock.schedule_interval(update, 1.0/60.0)
window.clear()
window.flip()
window.set_visible(True)
pyglet.app.run()
The problem here is that it only loads the starting batch/scene. Whenever I
press 'SPACE' to go to the tutorial scene the labels/sprites of the starting
batch disappear but it doesn't draw batch1 or load the the tutorial
class/scene. Any suggestions?
Answer: After creating a batch for each scene class:
import pyglet
from pyglet.window import key
class SceneTemplate(object):
"""a template with common things used by every scene"""
def __init__(self, text):
self.batch = pyglet.graphics.Batch()
self.label = pyglet.text.Label(
text,
font_name='Arial', font_size=32,
color=(200, 255, 255, 255), x=32, y=704,
batch=self.batch)
# (...)
class MainMenuScene(SceneTemplate):
def __init__(self):
super(MainMenuScene, self).__init__(text='MainMenuScene')
# (...)
class IntroScene(SceneTemplate):
def __init__(self):
super(IntroScene, self).__init__(text='Introduction')
# (...)
class Level1(SceneTemplate):
def __init__(self):
super(Level1, self).__init__(text='Level 1')
# (...)
You can control the state/scene in another class, such as a window class
(personally I like to [subclass the pyglet window, to keep things organized
and some other
reasons](http://pyglet.readthedocs.org/en/latest/programming_guide/windowing.html#subclassing-
window)):
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__(width=1024, height=768)
self.states = [MainMenuScene(), IntroScene(), Level1()] # and so on...
self.current_state = 0 # later you change it to get the scene you want
self.set_visible()
def on_draw(self):
self.clear()
self.states[self.current_state].batch.draw()
def on_key_press(self, symbol, modifiers):
if symbol == key.SPACE:
new_state = self.current_state + 1
new_state = new_state % len(self.states)
self.current_state = new_state
# if you want each scene to handle input, you could use pyglet's push_handlers(), or even something like:
# self.states[self.current_state].on_key_press(symbol, modifiers)
# giving them access to the window instance might be needed.
if __name__ == '__main__':
window = Window()
pyglet.app.run()
|
IOLoop.add_handler won't accept certain file descriptors
Question: Python tornado's `IOLoop.add_handler(fd,handler,events)` says "the fd argument
may either be an integer file descriptor or a file-like object with a fileno()
method", and as of 4.0, it "Added the ability to pass file-like objects in
addition to raw file descriptors.
However, adding a file-like object (an actual file object) fails on Linux:
>>> loop.add_handler (open ('XYZ'), handler, loop.READ)
IOError: [Errno 1] Operation not permitted
Adding the file descriptor directly also fails, even though stdin, stdout,
stderr are accepted:
>>> from tornado import ioloop
>>> loop = ioloop.IOLoop.current ()
>>> f = open ('XYZ')
>>> f.fileno()
4
>>> def handler (fd, events): pass
...
>>> loop.add_handler (0, handler, loop.READ)
>>> loop.add_handler (1, handler, loop.READ)
>>> loop.add_handler (2, handler, loop.READ)
>>> loop.add_handler (4, handler, loop.READ)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 677, in add_handler
self._impl.register(fd, events | self.ERROR)
IOError: [Errno 1] Operation not permitted
[This
explanation](https://github.com/tornadoweb/tornado/issues/104#issuecomment-286142)
says that async IO doesn't work on regular files.
Is there something terribly different about the fd's 0, 1, 2, and the fd of
open('XYZ').fileno()? That would mean the documentation should confusingly
say: "Added the ability to pass file-like objects, but not actually file
objects."
Answer: FDs 0, 1, and 2 are usually (but not always!) pipes instead of regular files.
The IOLoop docs should probably say "socket-like objects" instead of "file-
like objects", or simply "objects with a fileno method".
The types of file descriptors supported by IOLoop varies by platform. On posix
platforms it supports sockets and pipes (and maybe some others like ttys), and
on windows it only supports sockets.
|
Python urllib2.urlopen returns a HTTP error 503
Question: Here you can see my code snippet. Since 3 days it does not work any longer. My
python is running under Ubuntu 10.04.4 LTS. Python version is 2.6.5.
#!/usr/bin/env python
import urllib2 as ur
...
webpage = []
site = "http://www.gametracker.com/server_info/94.250.218.247:25200/top_players/"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = ur.Request(site , headers=hdr)
data = ur.urlopen(req)
for line in data:
line = line.split(",")
webpage.append(line)
...
here the returned Error-msg
Traceback (most recent call last):
File "read_top5.py", line 21, in <module>
data = ur.urlopen(req)
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 397, in open
response = meth(req, response)
File "/usr/lib/python2.6/urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.6/urllib2.py", line 435, in error
return self._call_chain(*args)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 503: Service Temporarily Unavailable
Answer: The service is not currently working. `curl`:
curl -i "http://www.gametracker.com/server_info/94.250.218.247:25200/top_players/"
also returns a 503:
HTTP/1.1 503 Service Temporarily Unavailable
Date: Mon, 08 Dec 2014 09:37:17 GMT
Content-Type: text/html; charset=UTF-8
Server: cloudflare-nginx
The service is using CloudFlare, which provides a [form of DDoS
protection](https://www.cloudflare.com/ddos) that requires you to use a full
web browser to connect.
Although you could likely work around it, by deciding to use this service, the
site operators are declaring that they don't want you to connect using a
script.
This is not a programming problem; you'll need to determine why the service is
not available to scripts.
|
Proper way to destroy a file chooser dialog in pygtk for python
Question: I've been trying to use gtk to create a folder choosing dialog, but I can't
figure out how to make the dialog close. Here is the code:
from gi.repository import Gtk
import time
dialog = Gtk.FileChooserDialog("Please choose a folder", None,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
"Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
print("Select clicked")
print("Folder selected: " + dialog.get_filename())
elif response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
dialog.destroy()
time.sleep(5)
I understand that I need to call gtk.main() in some way for it to work
properly, but I can't figure out how. I've been using the last example from
<http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html> but that
has a box at the beginning that I don't know how to get rid of.
Answer: There might be a nicer way, but I usually do it like this:
from gi.repository import Gtk, Gdk, GLib
def run_dialog(_None):
dialog = Gtk.FileChooserDialog("Please choose a folder", None,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
"Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
print("Select clicked")
print("Folder selected: " + dialog.get_filename())
elif response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
dialog.destroy()
Gtk.main_quit()
Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
Gtk.main()
This will call the `run_dialog` function as soon as the mainloop starts, which
will display the dialog and then quit.
**UPDATE:** If you want to enclose that code in a function that returns the
selected folder, you'll need to save the path to a non-local variable:
def run_folder_chooser_dialog():
result= []
def run_dialog(_None):
dialog = Gtk.FileChooserDialog("Please choose a folder", None,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
"Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
result.append(dialog.get_filename())
else:
result.append(None)
dialog.destroy()
Gtk.main_quit()
Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
Gtk.main()
return result[0]
In python 3, you can use `nonlocal result` and `result= dialog.get_filename()`
instead of the ugly list reference.
|
Error in import FloatField, using django-import-export
Question: I am using django-import-export for import csv file. I have a `FloatField` in
my model :
**models.py**
purchase_price = models.FloatField(null=True, blank=True)
When I import csv file with blank value, it throws an error :
**ValueError at /admin/csv_imp/book/process_import/**
could not convert string to float:
Request Method: POST
Request URL: http://localhost:8000/admin/csv_imp/book/process_import/
Django Version: 1.7.1
Exception Type: ValueError
Exception Value:
could not convert string to float:
Exception Location: /home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1550
Python Executable: /home/bgdev/Desktop/virtualenvs/django17/bin/python
Python Version: 2.7.6
Python Path:
['/home/bgdev/Desktop/virtualenvs/django17/test_pro',
'/home/bgdev/Desktop/virtualenvs/django17/src/admin-bootstrap',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/plat-i386-linux-gnu',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-tk',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-old',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/site-packages']
Server time: Tue, 9 Dec 2014 05:33:36 +0000
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/csv_imp/book/process_import/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('bootstrap_admin',
'import_export',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'csv_imp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
204. return view(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/admin.py" in process_import
130. raise_errors=True)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in import_data
359. six.reraise(*sys.exc_info())
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in import_data
345. self.save_instance(instance, real_dry_run)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in save_instance
163. instance.save()
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in save
591. force_update=force_update, update_fields=update_fields)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
619. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
681. forced_update)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_update
725. return filtered._update(values) > 0
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/query.py" in _update
600. return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1004. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
775. sql, params = self.as_sql()
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
969. val = field.get_db_prep_save(val, connection=self.connection)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
627. prepared=False)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
619. value = self.get_prep_value(value)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
1550. return float(value)
Exception Type: ValueError at /admin/csv_imp/book/process_import/
Exception Value: could not convert string to float:
Answer: This link will show you what null and blank do: [differentiate null=True,
blank=True in
django](http://stackoverflow.com/questions/8609192/differentiate-null-true-
blank-true-in-django)
If you can arrange your csv file to have all of the null values at the end,
you can just remove the commas. That might work. Or perhaps create a temporary
model that assigns those fields to a Charfield. Then copy appropriate fields
to your final model
This is untested:
update <table> set <field> = 0 where id in (select id from <table> where <field> = "");
Fill in your table name and the field name as appropriate. You can run this
from your sql command line program
|
Why inheriting from namedtuple results in infinite recursion in this case?
Question: I planned to write a small class to host a dictionary of stuff and some helper
methods related to it. While in this particular case inheriting from
`namedtuple` doesn't make much sense, I did it out of habit.
class Conf(collections.namedtuple('Conf', 'data')):
def __getitem__(self, attr):
return self.data[attr]
def get(self, attr, default=None):
return self.data.get(attr, default)
This, however, triggers in infinite recursion wrt `__getitem__` calling itself
repeatedly when I call `.get()` properly! F.ex like this:
Conf({}).get('')
-> RuntimeError: maximum recursion depth exceeded while calling a Python object
Why it seems like the methods on this external member are being overridden,
while all I try to do is to keep `data` out of the API. On the other hand, the
following works just fine.
class Config(object):
def __init__(self, d):
self.data = d
def __getitem__(self, attr):
return self.data[attr]
def get(self, attr, default=None):
return self.data.get(attr, default)
Answer: `namedtuple` define `data` as a kind of property.
You can confirm that if you define the namedtuple with `verbose=True`
argument:
>>> import collections
>>> collections.namedtuple('Conf', 'data', verbose=True)
class Conf(tuple):
...
data = _property(_itemgetter(0), doc='Alias for field number 0') # <---
Accessing the `data` will cause `__getitem__` to be called; which in turn
access `data` again; cause `__getitem__`, ....; causing the infinite
recursion.
* * *
You need to avoid accessing the `data` inside the your own `__getitem__`
method to prevent the recursion. For example:
>>> import collections
>>>
>>> class Conf(collections.namedtuple('Conf', 'data')):
... def __getitem__(self, attr):
... return super(Conf, self).__getitem__(0)[attr]
...
>>> Conf({'x': 'y'})['x']
'y'
|
python unittest with coverage report on (sub)processes
Question: I'm using `nose` to run my "unittest" tests and have `nose-cov` to include
coverage reports. These all work fine, but part of my tests require running
some code as a `multiprocessing.Process`. The `nose-cov` docs state that it
can do `multiprocessing`, but I'm not sure how to get that to work.
I'm just running tests by running `nosetests` and using the following
`.coveragerc`:
[run]
branch = True
parallel = True
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
# Have to re-enable the standard pragma
pragma: no cover
# Don't complain about missing debug-only code:
def __repr__
#if self\.debug
# Don't complain if tests don't hit defensive assertion code:
raise AssertionError
raise NotImplementedError
# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
def __main__\(\):
omit =
mainserver/tests/*
## EDIT:
I fixed the `parallel` switch in my ".coveragerc" file. I've also tried adding
a `sitecustomize.py` like so in my site-packages directory:
import os
import coverage
os.environ['COVERAGE_PROCESS_START']='/sites/metrics_dev/.coveragerc'
coverage.process_startup()
I'm pretty sure it's still not working properly, though, because **the
"missing" report still shows lines that I know are running (they output to the
console)**. I've also tried adding the environment variable in my test case
file and also in the shell before running the test cases. I also tried
explicitly calling the same things in the function that's called by
`multiprocessing.Process` to start the new process.
Answer: First, the configuration setting you need is `parallel`, not `parallel-mode`.
Second, you probably need to follow the directions in the [Measuring
Subprocesses](http://nedbatchelder.com/code/coverage/subprocess.html) section
of the coverage.py docs.
|
Python dictionary / database in memory
Question: I have a file that looks like this:
LastName FirstName Age Gender Height Weight
Smith May 20 F 1500 55
Wilder Harry 25 M 1800 65
Potter Harry 50 M 1600 66
Lincoln Abram 100 M 1800 55
Reynolds Mary 55 F 1600 55
Anderson Jane 40 F 1700 60
Smith William 42 M 1520 60
I want to be able to search in memory for example to find who has a height of
1800, or who has a last name of Smith, without having to read the file again.
I can read the file using import csv
filename = r'C:\Users\wsteve46\Documents\Python\People.csv'
reader = csv.DictReader(open(filename))
results = []
resdict = []
for row in reader:
try:
print 'Row = ',row
results.append(row.values())
resdict.append(row)
except:
break
print 'break ',row
fieldnames = row.keys()
However, resdict is a list, not a dictionary. What is the best way to access
this data by key/value?
Answer: the easiest way for this is using `pandas`
import pandas as pd
data = pd.read_csv(fn)
print data[data.Height == 1800]
print data[data.LastName == 'Smith']
you'll have to do more research on your own, but that answers your first
question.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.