text
stringlengths 226
34.5k
|
---|
reading cookies file created by curl
Question: I have the following cookie saved by curl (in test.txt, tab-separated, this
editor doesn't preserve tabs):
# Netscape HTTP Cookie File
# http://curlm.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_my-example.com FALSE / FALSE 0 _rails-root_session test
I'm trying to read it with the following code:
import sys
if sys.version_info < (3,):
from cookielib import Cookie, MozillaCookieJar
else:
from http.cookiejar import Cookie, MozillaCookieJar
def load_cookies_from_mozilla(filename):
ns_cookiejar = MozillaCookieJar()
ns_cookiejar.load(filename, ignore_discard=True)
return ns_cookiejar
cookies = load_cookies_from_mozilla("test.txt")
print (len(cookies))
It outputs 0 (unable to read the cookie). If I manually modify my cookie to
the following line (remove HttpOnly flag and changing 0 to the empty string
for expiration time, and again, tab-separated):
my-example.com FALSE / FALSE _rails-root_session test
then it outputs 1 (successfully read the cookie).
What needs to be done to my python code to read the original cookie line? And
preferably to be able to save it in the same format (with HttpOnly flag and
with 0 instead of empty string for never-expiring cookie)?
Thanks.
Answer: I tested your code and modified it, it works. First in the cookie file you
have to put off the '**_#_** ' before your cookie, I think it will comment the
data after it. Second the 0 in the cookie means the expire time, 0 means
expire now, so you can change the 0 to empty string or latter time, but i
suggest you use the argument **_ignore_expire=True_** , the official means:
> ignore_discard: save even cookies set to be discarded.
>
> ignore_expires: save even cookies that have expiredThe file is overwritten
> if it already exists
and the result code is :
import sys
if sys.version_info < (3,):
from cookielib import Cookie, MozillaCookieJar
else:
from http.cookiejar import Cookie, MozillaCookieJar
def load_cookies_from_mozilla(filename):
ns_cookiejar = MozillaCookieJar()
ns_cookiejar.load(filename, ignore_discard=True, ignore_expires=True)
return ns_cookiejar
cookies = load_cookies_from_mozilla("test.txt")
print (len(cookies))
and you can see the link to find more detail: [Using cookies.txt file with
Python Requests](http://stackoverflow.com/questions/14742899/using-cookies-
txt-file-with-python-requests?answertab=active#tab-top)
|
GNU Parallel to run Python script on huge file
Question: I have a file which contains XML elements in every line, which needs to be
converted to JSON. I have written a Python script which does the conversion
but runs in serial mode. I have two options to use Hadoop or GNU Parallel, I
have tried Hadoop and want to see how GNU could help, will be simple for sure.
My Python code is as follows:
`import sys import json import xmltodict with open('/path/sample.xml') as fd:
for line in fd: o=xmltodict.parse(line) t=json.dumps(o) with
open('sample.json', 'a') as out: out.write(t+ "\n")` So can I use GNU parallel
to directly work on the huge file or do I need to split it?
Or is this right: `cat sample.xml | parallel python xmltojson.py >sample.json`
Thanks
Answer: You need to change your Python code to a UNIX filter, i.e. a program that
reads from standard input (stdin) and writes to standard output (stdout).
Untested:
import fileinput
import sys
import json
import xmltodict
for line in fileinput.input():
o=xmltodict.parse(line)
t=json.dumps(o)
print t + "\n"
Then you use `--pipepart` in GNU Parallel:
parallel --pipepart -a sample.xml --block 1M python my_script.py
Adjust 1M so (number_of_cpu * 10) < (total_size / blocksize) < (number_of_cpu
* 100). This should give a reasonable balance between starting new jobs and
waiting for old jobs to finish.
|
simpy 2.2 examples in 3.0
Question: I am trying to work through some of the examples of simpy 2.2 (see:
<https://pythonhosted.org/SimPy/Tutorials/TheBank2OO.html>) and rewrite them
using simpy 3.0 lexicon (see:
<http://simpy.readthedocs.io/en/latest/about/history.html>). Has anybody came
across the the following example (bank door opens) rewritten for 3.0? Im not
entirely sure how to write the "self.sim.door_open" in the "customer" class as
an event using simpy 3.0.
from SimPy.Simulation import Simulation,Process,Resource,hold,waituntil,request,release
from random import expovariate,seed
##Model components ------------------------
class Doorman(Process):
""" Doorman opens the door"""
def openthedoor(self):
""" He will open the door when he arrives"""
yield hold,self,expovariate(1.0/10.0)
self.sim.door = 'Open'
print "%7.4f Doorman: Ladies and "\
"Gentlemen! You may all enter."%(self.sim.now(),)
class Source(Process):
""" Source generates customers randomly"""
def generate(self,number,rate):
for i in range(number):
c = Customer(name = "Customer%02d"%(i,),sim=self.sim)
self.sim.activate(c,c.visit(timeInBank=12.0))
yield hold,self,expovariate(rate)
class Customer(Process):
""" Customer arrives, is served and leaves """
def visit(self,timeInBank=10):
arrive = self.sim.now()
if self.sim.dooropen():
msg = ' and the door is open.'
else:
msg = ' but the door is shut.'
print "%7.4f %s: Here I am%s"%(self.sim.now(),self.name,msg)
yield waituntil,self,self.sim.dooropen
print "%7.4f %s: I can go in!"%(self.sim.now(),self.name)
wait = self.sim.now()-arrive
print "%7.4f %s: Waited %6.3f"%(self.sim.now(),self.name,wait)
yield request,self,self.sim.counter
tib = expovariate(1.0/timeInBank)
yield hold,self,tib
yield release,self,self.sim.counter
print "%7.4f %s: Finished "%(self.sim.now(),self.name)
## Model ----------------------------------
class BankModel(Simulation):
def dooropen(self):
return self.door=='Open'
def run(self,aseed):
self.initialize()
seed(aseed)
self.counter = Resource(capacity=1,name="Clerk",sim=self)
self.door = 'Shut'
doorman=Doorman(sim=self)
self.activate(doorman,doorman.openthedoor())
source = Source(sim=self)
self.activate(source,
source.generate(number=5,rate=0.1),at=0.0)
self.simulate(until=400.0)
## Experiment data -------------------------
maxTime = 2000.0 # minutes
seedVal = 393939
## Experiment ----------------------------------
BankModel().run(aseed=seedVal)
What i have so far, but i get the error "Environment object has no attribute
'door_open'"
import simpy
import random
Ninja edit: I managed to get the simulation to run, however i cant get the
door to initialize as "closed" then open at some point.
def openthedoor(self):
yield self.timeout(random.expovariate(1.0 /10.0))
print('%7.4f Doorman: ladies and gentleman you may enter' %(self.now))
def source(env, name, counter):
for i in range(500):
env.process(customer(env, 'Customer%02d' % i, counter, time_in_queue=30.0))
t = random.expovariate(1.0 / 20.0)
yield env.timeout(t)
def customer(env, name, counter, time_in_queue):
arrive = env.now
if env.process.openthedoor(env):
msg = 'and the door is open'
else:
msg = 'but the door is sht'
print('%7.4f %s: Customer has entered queue and' % (arrive, name, msg))
yield env.process(openthedoor(env))
print('%7.4f %s: I can go in' % (env.now, name))
wait = env.now - arrive
print('%7.4f %s: Waited %6.3f' % (env.now, name, wait))
with counter.request() as req:
# Wait for the counter or abort at the end of our tether
yield req
waited = env.now - arrive
tib = random.expovariate(1.0 / 20.0)
yield env.timeout(tib)
print('%7.4f %s: Waited %6.3f' % (env.now, name, waited))
print('%7.4f %s: Finished' % (env.now, name))
print('Batch Record Review Simulation')
random.seed(RANDOM_SEED)
env = simpy.Environment()
data = []
counter = simpy.Resource(env, capacity=1)
env.process(source(env, CUSTOMERS, counter))
# Start processes and run
env.run(until=SIM_TIME)
Answer: In SimPy 2, `waituntil` used “busy waiting”, that means it checked at each
step if the condition evaluates to `True`. That is not very good practice and
may consume a lot of CPU time. That’s why this is no longer in SimPy 3.
In SimPy 3, you would use a normal `Event` (as createed by
`Environmanet.event()`). You could, for example, create a `Door` class and
pass a reference to the door instance to the door opener and the customer(s).
The customer could do a `door.open = env.event()` everytime they want to open
the door. The door opener would then trigger that event.
An alternative solution might be to use a `PriorityResource` (or maybe
`PreemptiveResource) as door. The door opener uses a higher priority than the
customers and is thus able to “block” the door (== door closed). Once the door
opener releases the resource, the next customer can “open” the door.
|
How would I take an excel file and convert its columns into lists in Python?
Question: I had the following question. Namely, suppose I have an excel file with some
names in the first row. Then the next however many rows are single letter
entries (so "A", "B", "C" and so on).
My goal is to extract the column and make it into a list, so that, say, for
column 1 the list would start in row 2, the next entry would be from row 3,
and so on, until the end is reached.
How would I do that in Python?
Answer: I used a module called **xlrd**.
Some information on that
<http://www.blog.pythonlibrary.org/2014/04/30/reading-excel-spreadsheets-with-
python-and-xlrd/>
And here is the package: <https://pypi.python.org/pypi/xlrd>
To exclude the first row, and make different lists for different columns you
could do something like...
from xlrd import open_workbook
book = open_workbook("mydata.xlsx")
sheet = book.sheet_by_index(0) #If your data is on sheet 1
column1 = []
column2 = []
#...
for row in range(1, yourlastrow): #start from 1, to leave out row 0
column1.append(sheet.cell(row, 0)) #extract from first col
column2.append(sheet.cell(row, 1))
#...
Put the index-1 of the last row that contains data in the 'yourlastrow'
placeholder.
|
MongoDB: mongoimport isodate on Ubuntu 14.04LTS
Question: Platform: Ubuntu 14.04 LTS 64bit Python installed, can't remember its version
right now: I can update this question later
....$>sudo mongod --versiondb
version v2.4.9 git
git version: nogitversion
....$>sudo service mongodb status
start
My dbpath variable set on _/etc/mongod.config_ is equals to
_/home/utente/OFS/datasource_. I gave right permissions with chmod. From
mongodb.log file I can see last line like:"_...waiting for connection on port
27017_ " Open a terminal, trying to import the json here below:
> { "_id":ObjectId("572f36bcb69df6b4280cee68"),
> "formatoPreferito":ObjectId("57121b0d1dab7d841d149ed0"), "nome":"fra",
> "cognome":"back", "dataNascita":ISODate("1987-09-17T22:00:00Z"),
> "email":"[email protected]",
> "password":"$2a$10$4LR/kFI.FHPXHug7Jo9z0.mSgFqT4j4ZMeM.x1MdBfp5HGAFCvdOG",
> "ereader":"kindle",
> "token":"$2a$10$WBT5.ylZiRkfSZM./7XUtemllTNN5jaJJy8KsVISvJTvUyUmP49ki",
> "dataRegistrazione":ISODate("2016-05-08T12:53:15.262Z"), "attivo":true }
With the command:
mongoimport --db ofs --collection utenti --host localhost --port 27017 --drop --file /home/utente/OFS/load.utenti.json
With the output:
> connected to: localhost:27017 Tue May 24 00:04:27.151 dropping: ofs.utenti
> Tue May 24 00:04:27.152 exception:BSON representation of supplied JSON is
> too large: code FailedToParse: FailedToParse: **Bad characters in value:
> offset:149** Tue May 24 00:04:27.152
> Tue May 24 00:04:27.152 exception:BSON representation of supplied JSON is
> too large: code FailedToParse: FailedToParse: Bad characters in value:
> offset:149 Tue May 24 00:04:27.152 imported 0 objects Tue May 24
> 00:04:27.152 ERROR: encountered 2 error(s)s utente@utente-X551CAP:~/OFS$Tue
> May 24 00:04:27.152 Tue May 24 00:04:27.152 check 0 0
offset 149, watched on text editor, is the position of the ':' character on
the **dataNascita** field. The --jsonArray parameter does not fix the errors.
Question: is It something wrong with the json file or is It something wrong
with ISODate data type and my version of mongodb? (it is not the mongodb-org
software installed).
### On Microsoft Windows 7
with a later mongodb version it seems all to work just fine: [](http://i.stack.imgur.com/VHEbv.jpg)
So now I am going back home, remove mongodb installed, install [later
version](https://www.mongodb.com/download-center#community) and update here.
Answer: It turns the installation was not successfully ended. **I installed the same
mongodb version one time again.** As soon as the installation ended, I was
able to run successfully the mongoimport command with the ISODate objects
inside the json input file.
|
Error when pip installing CRFsuite in Python 3 Windows 10 x86
Question: I'm trying to install [CRFsuite](https://python-
crfsuite.readthedocs.io/en/latest/) to my Python 3 based on Windows 10 x86
while an Error occured, please see below. At start, it was missing
`vcvars32.bat` but I managed to solve it by installing _Microsoft Visual
Studio 2015_ including _Common tools for visual c++ 2015_. After that, it
starts to run but this came out: `error: command 'C:\\Program Files
(x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit
status 2`.
The problem seems to be defining the `snprintf` in `stdio.h`, I have tried
solution provided
[here](http://stackoverflow.com/questions/27754492/vs-2015-compiling-
cocos2d-x-3-3-error-fatal-error-c1189-error-macro-definiti) by adding a few
lines of code in `stdio.h` but not working.
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\stdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration
Please see more details below. Kindly hope anyone would give me a hand. Thanks
in advance.
[Python3] C:\>cd "Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin"
[Python3] C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin>VCVARS32
[Python3] C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin>pip install python-crfsuite
Collecting python-crfsuite
Using cached python-crfsuite-0.8.4.tar.gz
Building wheels for collected packages: python-crfsuite
Running setup.py bdist_wheel for python-crfsuite ... error
Complete output from command f:\python3\anaconda3\envs\python3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-build-dwkmw7ii\\python-crfsuite\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\ADMINI~1\AppData\Local\Temp\tmph_uhnrfipip-wheel- --python-tag cp35:
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.5
creating build\lib.win-amd64-3.5\pycrfsuite
copying pycrfsuite\_dumpparser.py -> build\lib.win-amd64-3.5\pycrfsuite
copying pycrfsuite\_logparser.py -> build\lib.win-amd64-3.5\pycrfsuite
copying pycrfsuite\__init__.py -> build\lib.win-amd64-3.5\pycrfsuite
running build_ext
building 'pycrfsuite._pycrfsuite' extension
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
creating build\temp.win-amd64-3.5\Release\pycrfsuite
creating build\temp.win-amd64-3.5\Release\crfsuite
creating build\temp.win-amd64-3.5\Release\crfsuite\lib
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\crf
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\crf\src
creating build\temp.win-amd64-3.5\Release\crfsuite\swig
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\cqdb
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\cqdb\src
creating build\temp.win-amd64-3.5\Release\liblbfgs
creating build\temp.win-amd64-3.5\Release\liblbfgs\lib
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Icrfsuite/include/ -Icrfsuite/lib/cqdb/include -Iliblbfgs/include -Ipycrfsuite -Icrfsuite/win32 -If:\python3\anaconda3\envs\python3\include -If:\python3\anaconda3\envs\python3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /EHsc /Tppycrfsuite/_pycrfsuite.cpp /Fobuild\temp.win-amd64-3.5\Release\pycrfsuite/_pycrfsuite.obj
_pycrfsuite.cpp
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Icrfsuite/include/ -Icrfsuite/lib/cqdb/include -Iliblbfgs/include -Ipycrfsuite -Icrfsuite/win32 -If:\python3\anaconda3\envs\python3\include -If:\python3\anaconda3\envs\python3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /EHsc /Tppycrfsuite/trainer_wrapper.cpp /Fobuild\temp.win-amd64-3.5\Release\pycrfsuite/trainer_wrapper.obj
trainer_wrapper.cpp
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Icrfsuite/include/ -Icrfsuite/lib/cqdb/include -Iliblbfgs/include -Ipycrfsuite -Icrfsuite/win32 -If:\python3\anaconda3\envs\python3\include -If:\python3\anaconda3\envs\python3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /EHsc /Tccrfsuite/lib/crf/src\crf1d_context.c /Fobuild\temp.win-amd64-3.5\Release\crfsuite/lib/crf/src\crf1d_context.obj
crf1d_context.c
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\math.h(262): warning C4005: 'isfinite': macro redefinition
crfsuite/include/os.h(49): note: see previous definition of 'isfinite'
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\stdio.h(1925): warning C4005: 'snprintf': macro redefinition
crfsuite/include/os.h(50): note: see previous definition of 'snprintf'
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\stdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Failed building wheel for python-crfsuite
Running setup.py clean for python-crfsuite
Failed to build python-crfsuite
Installing collected packages: python-crfsuite
Running setup.py install for python-crfsuite ... error
Complete output from command f:\python3\anaconda3\envs\python3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-build-dwkmw7ii\\python-crfsuite\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\ADMINI~1\AppData\Local\Temp\pip-sd7k3msy-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.5
creating build\lib.win-amd64-3.5\pycrfsuite
copying pycrfsuite\_dumpparser.py -> build\lib.win-amd64-3.5\pycrfsuite
copying pycrfsuite\_logparser.py -> build\lib.win-amd64-3.5\pycrfsuite
copying pycrfsuite\__init__.py -> build\lib.win-amd64-3.5\pycrfsuite
running build_ext
building 'pycrfsuite._pycrfsuite' extension
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
creating build\temp.win-amd64-3.5\Release\pycrfsuite
creating build\temp.win-amd64-3.5\Release\crfsuite
creating build\temp.win-amd64-3.5\Release\crfsuite\lib
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\crf
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\crf\src
creating build\temp.win-amd64-3.5\Release\crfsuite\swig
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\cqdb
creating build\temp.win-amd64-3.5\Release\crfsuite\lib\cqdb\src
creating build\temp.win-amd64-3.5\Release\liblbfgs
creating build\temp.win-amd64-3.5\Release\liblbfgs\lib
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Icrfsuite/include/ -Icrfsuite/lib/cqdb/include -Iliblbfgs/include -Ipycrfsuite -Icrfsuite/win32 -If:\python3\anaconda3\envs\python3\include -If:\python3\anaconda3\envs\python3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /EHsc /Tppycrfsuite/_pycrfsuite.cpp /Fobuild\temp.win-amd64-3.5\Release\pycrfsuite/_pycrfsuite.obj
_pycrfsuite.cpp
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Icrfsuite/include/ -Icrfsuite/lib/cqdb/include -Iliblbfgs/include -Ipycrfsuite -Icrfsuite/win32 -If:\python3\anaconda3\envs\python3\include -If:\python3\anaconda3\envs\python3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /EHsc /Tppycrfsuite/trainer_wrapper.cpp /Fobuild\temp.win-amd64-3.5\Release\pycrfsuite/trainer_wrapper.obj
trainer_wrapper.cpp
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Icrfsuite/include/ -Icrfsuite/lib/cqdb/include -Iliblbfgs/include -Ipycrfsuite -Icrfsuite/win32 -If:\python3\anaconda3\envs\python3\include -If:\python3\anaconda3\envs\python3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /EHsc /Tccrfsuite/lib/crf/src\crf1d_context.c /Fobuild\temp.win-amd64-3.5\Release\crfsuite/lib/crf/src\crf1d_context.obj
crf1d_context.c
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\math.h(262): warning C4005: 'isfinite': macro redefinition
crfsuite/include/os.h(49): note: see previous definition of 'isfinite'
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\stdio.h(1925): warning C4005: 'snprintf': macro redefinition
crfsuite/include/os.h(50): note: see previous definition of 'snprintf'
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\stdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Command "f:\python3\anaconda3\envs\python3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-build-dwkmw7ii\\python-crfsuite\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\ADMINI~1\AppData\Local\Temp\pip-sd7k3msy-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\ADMINI~1\AppData\Local\Temp\pip-build-dwkmw7ii\python-crfsuite\
[Python3] C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin>
Answer: See this post regarding precisely why the compilation fails. [VS 2015
compiling cocos2d-x 3.3 error "fatal error C1189: #error: Macro definition of
snprintf conflicts with Standard Library function
declaration"](http://stackoverflow.com/questions/27754492/vs-2015-compiling-
cocos2d-x-3-3-error-fatal-error-c1189-error-macro-definiti/27754829#27754829)
WRT quick fixes - we were able to get a successful build on Python 3.4, so
perhaps consider using that if this isn't a major project?
|
python - Django : Page Not found
Question: I have looked around and can't really find a solution to my problem. Here is
the error django throws. This error is being thrown when on my homepage I have
a fiew links that upon clicking should direct you to a details view of said
link.
Using the URLconf defined in untitled.urls, Django tried these URL patterns, in this order:
^$
^index/ ^$ [name='index']
^index/ ^(?P<distro_id>[0-9]+)/$ [name='distro_id']
^admin/
The current URL, index//, didn't match any of these.
To my knowledge I don't understand why this error is being thrown.
Here is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
import index.views
urlpatterns = [
url(r'^$', index.views.index),
url(r'^index/', include('index.urls', namespace='index')),
url(r'^admin/', admin.site.urls),
]
My index/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# /index/
url(r'^$', views.index, name='index'),
#/distro/123/
url(r'^(?P<distro_id>[0-9]+)/$', views.detail, name='distro_id'),
]
My views.py
from django.shortcuts import get_object_or_404, render
from django.template import loader, RequestContext
from django.http import Http404
from .models import Distros
def index(request):
all_distros = Distros.objects.all()
context = {'all_distros': all_distros, }
return render(request, 'index/index.html', context)
def detail(request, distro_id,):
distro_id = get_object_or_404 (Distros, pk=distro_id)
return render(request, 'index/detail.html', {'distro_id': distro_id})
template code:
{% extends 'index/base.html' %}
{% block body %}
<ul>
{% for distro in all_distros %}
<li><a href="/index/{{ distro_id }}/">{{ index.distro_id }}</a></li>
{% endfor %}
</ul>
{% endblock %}
I believe those are all the relevent files. I believe everything is setup
correctly so I am not sure why the error is being thrown. I'm sure im missing
something simple that i'm just overlooking.
Answer: Please don't use hardcoded URLs as they are error prone as in your situation.
Instead of:
<a href="/index/{{ index.distro.id }}/">
use the `url` template tag with your namespace (`index`) and view name
(`distro_id`):
<a href="{% url 'index:distro_id' index.id %}">
Note that you also have an error with `index.distro.id` as `index` is actually
a `Distros` object. It has an `id` field, but not `distro.id`.
|
numpy.dtype error in machine learning code (Python)
Question: I am just trying to run a scikit-learn example source code successfully, but
am getting an consistent error. The code can be found [here](http://scikit-
learn.org/stable/auto_examples/covariance/plot_outlier_detection.html) \- it
has around 90 lines of code, so it wouldn't be efficient to put it in here.
However, whenever I run it, I get the error message called from the **Import
sklearn** stating:
File "plot_outlier_detection.py", line 33, in <module>
from sklearn import svm
File "/Library/Python/2.7/site-packages/sklearn/__init__.py", line 57, in <module>
from .base import clone
File "/Library/Python/2.7/site-packages/sklearn/base.py", line 11, in <module>
from .utils.fixes import signature
File "/Library/Python/2.7/site-packages/sklearn/utils/__init__.py", line 10, in <module>
from .murmurhash import murmurhash3_32
File "numpy.pxd", line 155, in init sklearn.utils.murmurhash (sklearn/utils/murmurhash.c:5029)
ValueError: numpy.dtype has the wrong size, try recompiling
The main error is
ValueError: numpy.dtype has the wrong size, try recompiling
and I've looked into many Stackoverflow posts already, saying that I need to
update my numpy, matplotlib, scipy, which I've done already multiple times
(upgrade / uninstall+install using pip / uninstall+install from source), but
the same error still shows up (I also reinstalled sklearn). I think I know why
this is the case:
When I use python in terminal and check the numpy version I get
import numpy
numpy.version.version
'1.9.2'
However, when I try installing or upgrading through pip -- I get the message
numpy in /Library/Python/2.7/site-packages/numpy-1.11.0-py2.7-macosx-10.10-intel.egg
I read in [this](http://stackoverflow.com/questions/26390895/why-isnt-pip-
updating-my-numpy-and-scipy) Stackoverflow query about this, and they said to
use easy_install as python doesn't read from the right path in Macs (IDK, can
someone confirm?) so I did it through easy_install, and get this message
Searching for numpy
Best match: numpy 1.11.0
Processing numpy-1.11.0-py2.7-macosx-10.10-intel.egg
numpy 1.11.0 is already the active version in easy-install.pth
Installing f2py script to /usr/local/bin
Using /Library/Python/2.7/site-packages/numpy-1.11.0-py2.7-macosx-10.10-intel.egg
Processing dependencies for numpy
Finished processing dependencies for numpy
which is the exact same thing. I don't really know what's going on. Can anyone
help me?
For reference of versions:
Python - 2.7.10
Numpy - 1.9.2
Matplotlib - 1.4.3
Scipy - 0.13.0b1
_The rest of the versions are also not up to date..but they derive from
numpy's version being up-to-date._
Answer: I've installed Anaconda (2.5.0) on my Ubuntu (14.04) With Anaconda 2.5.0 my
versions are:
python 2.7.11
Numpy 1.10.4
Scipy 0.17.0
I've download the code from the link, and it worked perfectly on my machine
Can you try to install Anaconda and see if it solve your problems?
<https://www.continuum.io/downloads>
|
opencv2 Aruco library modules not working with python
Question: I have compiled the aruco library as stated here [github link for aurco
library](https://github.com/fehlfarbe/python-aruco)
I have checked it has compiled successfully as i can import it in python
without any error and to check i have run the example.py script also it's
working but when i wrote this code
import cv2
import numpy as np
import aruco
Dictionary = aruco.getPredefinedDictionary(aruco.PREDEFINED_DICTIONARY_NAME(DICT_5X5_250=6))
aruco.drawMarker(Dictionary,5,250,markerImage,1)
aruco.drawMarker(Dictionary,10,250,markerImage,1)
aruco.drawMarker(Dictionary,20,250,markerImage,1)
aruco.drawMarker(Dictionary,25,250,markerImage,1)
aruco.drawMarker(Dictionary,50,250,markerImage,1)
aruco.drawMarker(Dictionary,100,250,markerImage,1)
aruco.drawMarker(Dictionary,200,250,markerImage,1)
cv2.imshow("markers",markerImage)
cv2.waitKey(0)
cv2.imgwrite(marker.jpg,markerImage)
it throws error
> Traceback (most recent call last): File "drawmarker.py", line 7, in
> Dictionary =
> aruco.getPredefinedDictionary(aruco.PREDEFINED_DICTIONARY_NAME(DICT_5X5_250=6))
> AttributeError: 'module' object has no attribute 'getPredefinedDictionary'
can someone please let me know what am i doing wrong, is this module not
imported in python version of aruco ?
Answer: maybe you should try this "aruco.DICT_5X5_250" as parameter, like...
`dict = aruco.getPredefinedDictionary( aruco.DICT_5X5_250 )`
it worked for me :)
|
Python tkinter: Using a "textvariable" in a combobox seems useless
Question: Using the `textvariable` attribute when creating a combobox in tkinter seems
completely useless. Can someone please explain what the purpose is? I looked
in the Tcl documentation and it says `textvariable` is used to set a default
value, but it looks like in tkinter you would just use the `.set` method to do
that.
**Example showing what I mean:**
This doesn't work...
from Tkinter import *
import ttk
master = Tk()
test = StringVar()
country = ttk.Combobox(master, textvariable=test)
country['values'] = ('USA', 'Canada', 'Australia')
country.pack()
# This does not set a default value...
test="hello"
mainloop()
This does work.
from Tkinter import *
import ttk
master = Tk()
country = ttk.Combobox(master)
country['values'] = ('USA', 'Canada', 'Australia')
country.pack()
# This does set a default value.
country.set("hello")
mainloop()
If you are supposed to just use the `.set` and `.get` methods, what is the
point of assigning anything to `textvariable`? Every example online seems to
use `textvariable`, but why? It seems completely pointless.
Answer: Since Python has no type safety, you're overwriting the reference to the
`StringVar` object with a string. To set the value, call the `set` method:
test = StringVar()
country = ttk.Combobox(master, textvariable=test)
#...
test.set("hello")
|
python maya, function call 2 functions, force to run both
Question: I made a windowUI with a button to run 2 functions so I defined a new function
to run the other 2
def addSlider_splitLoop():
addSlider()
splitLoop()
mc.button(label ='Combo' , command = 'addSlider_splitLoop()' )
when the button is pressed, only 1 function works:
* when nothing is selected the command only runs the addSlider() function,
* when the polygon loop is selected the command only runs the splitLoop() function
which actually make sense, but does not help me, and changing the order ot the
functions also does not help
I want to force it to run both functions, how can I do this?
actually the best thing would be to have the addSlider() to run only when the
splitLoop() works, but I'm a real beginner and I have no clue how to do
this... force to run both functions might be a dirty solution but is enough
for me at the moment
this is the full code anyway (the combo button is just for testing)
import maya.cmds as mc
def addSlider_splitLoop():
addSlider()
splitLoop()
def addSlider():
mc.floatSliderGrp( minValue = 1.00 , maxValue = 99.00 , value = 50.00 , field = True )
def splitLoop():
mc.ConvertSelectionToContainedEdges()
mc.polySplitRing(sma = 180 , wt = 0.5)
mc.polyDuplicateEdge(ch = True , of = loopDistance() )
#addSlider()
def doubleLoop():
mc.ConvertSelectionToContainedEdges()
mc.polySplitRing(sma = 180 , wt = 0.5)
mc.polyDuplicateEdge(ch = True , of = loopDistance() )
mc.polyDelEdge(e = False, cv = True,)
#addSlider()
def loopDistance():
distance = mc.floatSliderGrp('LoopDistanceValue' , query = True, value = True)
convertedDistance = distance / 100
return convertedDistance
def splitLoopUI():
if mc.window('splitLoopUI' , exists = True):
mc.deleteUI('splitLoopUI')
mc.window('splitLoopUI')
mc.frameLayout( label=' set loop distance')
mc.floatSliderGrp('LoopDistanceValue' , minValue = 1.00 , maxValue = 99.00 , value = 50.00 , field = True )
mc.button(label ='Triple Loop' , command = 'splitLoop()' )
mc.button(label ='Double Loop' , command = 'doubleLoop()' )
mc.button(label ='Combo' , command = 'addSlider_splitLoop()' )
mc.text( label=' + edit loop distance + ')
mc.scrollLayout( 'scrollLayout' )
mc.columnLayout( adjustableColumn=True )
mc.showWindow('splitLoopUI')
splitLoopUI()
Answer: A couple of things going on here.
1. Don't call the scripts as strings -- that's a recipe for wierdness down the road. Pass the function objects instead, as in @Dr.Weeny's example. It's more reliable and actually faster as well. [More here](http://techartsurvival.blogspot.com/2014/04/maya-callbacks-cheat-sheet.html)
2. In your posted code `addSlider()` doesn't do any work to get the currently active GUI object -- depending on when it runs that slider could be showing up anywhere -- in the channel box, in some other window, or it could be failing. This is probably why it seems like the function isn't running: you're just not spotting the new slider wherever it ends up. Try adding a debug print.
3. if you want to run `addSlider()` after other commands, the simplest thing to do is probably to have all of the tool commands return a value indicating that they have succeeded or failed:
def splitLoop():
try:
mc.ConvertSelectionToContainedEdges()
mc.polySplitRing(sma = 180 , wt = 0.5)
return mc.polyDuplicateEdge(ch = True , of = loopDistance() )
except:
return None
def addSlider_splitLoop():
if splitLoop():
addSlider()
|
Cannot merge .txt files having different encoding in Python
Question: I'm trying to merge a number of .txt files into one file. Some of the files
are plain text .txt files I created in advance, while some are files written
by the script itself. The script successfully merges some of the files (the
ones I wrote in advance) but does not include the ones created by the script,
even though it raises no error. It literally seems to ignore their existence.
I have tried different methods, including `shutil` and `fileinput`, and even
using `cat` from `subprocess.call` but without luck.
From the terminal, the files I created in advance are "XML document text"
(though I actually saved it as plain text, but it is formatted as XML), while
the other ones are "ASCII text". I believe this is the problem, as the XML
ones were .rtf files, and they wouldn't merge before I converted them – only
the first of the list would be included in the output file.
import os, itertools, subprocess, fileinput, shutil
os.chdir('/Users/MicTonutti/Dropbox/MRes/Individual Project/FEBio/Simulation')
forces = itertools.permutations([-1.5,-1,-0.5,0],3)
forces = list(forces)
force_node = 174
for i in range(0,len(forces)):
filename = '0_Insert' + str(i) + '.txt'
f = open(filename, 'w')
string_x = '<nodal_load bc="x" lc="2"> <node id="' + str(force_node) + '">' + str(forces[i][1]) + '</node> </nodal_load>\n'
string_y = '<nodal_load bc="y" lc="2"> <node id="' + str(force_node) + '">' + str(forces[i][2]) + '</node> </nodal_load>\n'
string_z = '<nodal_load bc="z" lc="2"> <node id="' + str(force_node) + '">' + str(forces[i][2]) + '</node> </nodal_load>\n'
f.write(string_x + string_y + string_z)
filename_2 = '1_Insert' + str(i) + '.txt'
g = open(filename_2, 'w')
string_1 = '<logfile>\n <node_data data="x;y;z" file = "coord_data' + str(i) + '.txt" delim=", "> </node_data>\n'
string_2 = '<node_data data="ux;uy;uz" file = "displacement_data' + str(i) + '.txt" delim=", "> </node_data>\n </logfile>\n'
g.write(string_1 + string_2)
files_list = ['Simulation 1.txt', filename, 'Simulation 2.txt', filename_2, 'Simulation 3.txt']
output_file = '/Users/MicTonutti/Dropbox/MRes/Individual Project/FEBio/Simulation/Python Output/FEBio Simulation Output' + str(i) + '.txt'
with open(output_file, 'w') as outfile:
for infile in files_list:
shutil.copyfileobj(open(infile), outfile)
The output basically looks like this:
Text of "Simulation1.txt" + Text of "Simulation2.txt + Text of
"Simulation3.txt", without the files in the middle. Any ideas?
Thanks.
Answer: You should call `flush()` on the files you write before you try to read them
again, else the written data might still be buffered.
Apart from that I wanted to point out that you write to 24 different
`0_Insert` files in your loop (`0_Insert1.txt` to `0_Insert23.txt`), but later
on only read from the last one. Is this what you actually are trying to do? Or
should your loop also include the bottom part of your code?
|
How to mock stompest send, and connect methods
Question: I am writing a log handler for `ActiveMQ`. I have one class, `Messenger`, to
publish a message to `ActiveMQ`. Also, I added class `Handler` to handle this
and `get_logger` to get this logger.
import json
import logging
from stompest.config import StompConfig
from stompest.sync import Stomp
class Messanger(object):
def __init__(self, uri):
self.cfg = StompConfig(uri)
def publish(self, queue, data):
data = json.dumps(data)
client = Stomp(self.cfg)
client.connect()
try:
client.send(queue, data)
except Exception, exc:
print "Error: ", exc
client.disconnect()
class Handler(logging.Handler):
def __init__(self, amq_uri, out_queue):
logging.Handler.__init__(self)
self.queue = queue
self.uri = uri
def emit(self, record):
msg = self.format(record)
messanger = Messanger(self.uri)
messanger.send(self.queue, msg)
def get_logger(uri, queue):
logger = logging.getLogger('testlogger')
logger.addHandler(Handler(uri, queue))
return logger
I have written a UT for this.
from unittest import TestCase
from mock import patch, Mock
from my_package import get_logger
class TestHandler(TestCase):
@patch('stompest.sync.client.Stomp')
def test_activemq_handler(self, mock_stomp):
URI = "tcp://localhost:61613"
QUEUE = "/queue/logger_queue"
mock_stomp.connect = Mock(return_value=1)
mock_stomp.send = Mock(return_value=2)
data = "This is test logging"
LOG = get_logger(URI, QUEUE)
LOG.error(data)
But still it goes to the original send method and tries to connect to the
server.
Traceback (most recent call last):
File ".my_package/venv/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "./my_package/tests/test_activemq_handler.py", line 23, in test_activemq_handler
LOG.error(data)
File "/System/Library/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1191, in error
self._log(ERROR, msg, args, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1284, in _log
self.handle(record)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1294, in handle
self.callHandlers(record)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1334, in callHandlers
hdlr.handle(record)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 757, in handle
self.emit(record)
File "./my_package/__init__.py", line 28, in emit
messanger.send(self.queue, msg)
File "./my_package/clients/stomp_messanger.py", line 41, in send
client.connect()
File "./my_package/venv/lib/python2.7/site-packages/stompest/sync/client.py", line 85, in connect
for (broker, connectDelay) in self._failover:
File "./my_package/venv/lib/python2.7/site-packages/stompest/protocol/failover.py", line 48, in __iter__
yield broker, self._delay()
File "./my_package/venv/lib/python2.7/site-packages/stompest/protocol/failover.py", line 66, in _delay
raise StompConnectTimeout('Reconnect timeout: %d attempts' % self._maxReconnectAttempts)
StompConnectTimeout: Reconnect timeout: 0 attempts
How can I mock this?
Answer: > The basic principle is that you patch where an object is looked up, which is
> not necessarily the same place as where it is defined.
You are adding the patch to the wrong place. The `Messenger` class module
imports `Stomp` from `stompest.sync` before the tests run, and that's why your
patching has no effect. You should patch the reference to `Stomp` in your
module.
from unittest import TestCase
from mock import patch, Mock
from my_package import get_logger
class TestHandler(TestCase):
@patch('path.to.your.Messenger_class_module.Stomp') #path to your module
def test_activemq_handler(self, mock_stomp):
URI = "tcp://localhost:61613"
QUEUE = "/queue/logger_queue"
...
[This](http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch) will
help if you need further clarification on why this is happening.
|
How to pre-process source files while a Sphinx run?
Question: I have set up a Sphinx documentation for my project and would like to extract
doc strings for the source files and embed them into the final documentation.
Unfortunately, the source file's language (VHDL) is not supported by Sphinx.
There seems to be no Sphinx domain for VHDL.
So my ideas is as follows:
* Hook into the Sphinx run and execute some Python code before Sphinx
* The Python codes extracts text blocks from each source file (the top-most multi-line comment block) and assembles one reST file per source file, consisting of this comment block and some other reST markup.
* All source files are listed in an `index.rst`, to generate the apropriate `.. toctree::` directive.
* The text extraction and transformation is done recursively per source code directory.
So the main question is: **How to hook into Spinx?**
Or should I just import and run my own configuration in `conf.py`?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from my_preprocessor import my_proc
proc = my_proc()
proc.run()
#
# Test documentation build configuration file, created by
# sphinx-quickstart on Tue May 24 11:28:20 2016.
# ....
I can't modify the build process files: `Makefile` and `make.bat`, because the
real build process runs on ReadTheDocs.org. RTDs only executes `conf.py`.
Answer: As noted in my previous comments and mertyildiran's answer, the official way
to hook into Sphinx for a language would be to [create an
extension](http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-
extensions) to implement a new domain for VHDL.
This has already been done for many other languages - e.g. Erlang, PHP,
CoffeeScript - and APIs - e.g. HTTP REST - just to name a few from [sphinx-
contrib](https://bitbucket.org/birkenfeld/sphinx-contrib). However, that is
going to take a lot of time, which you don't have... You are therefore left
with an option to do some quick parsing yourself and then hooking that into
your Sphinx build somehow.
Since you are bypassing the official hooks, this question becomes "how do I
run my own code inside a Sphinx build?" For which, I would recommend that you
simply follow the guidance for a local extension - i.e. put it in a separate
directory, add that to your path, then import and invoke it. As noted in the
[docs](http://www.sphinx-doc.org/en/stable/config.html):
> The configuration file is executed as Python code at build time (using
> execfile(), and with the current directory set to its containing directory),
> and therefore can execute arbitrarily complex code. Sphinx then reads simple
> names from the file’s namespace as its configuration.
As a final though, this opens up the options to use 3rd party packages like
pyVhdl2Sch (with a nod again to mertyildiran's answer) to create some
schematic and then maybe write your static `rst` files around it to explain
the schematic.
|
How do I secure an AWS API Gateway with Cognito?
Question: I've setup an Identity pool and using Python and boto3 I'm able to retrieve an
access key, secret key and session token, which I assume is for an
unauthenticated user:
import boto3
boto3.setup_default_session(region_name='us-east-1')
identity = boto3.client('cognito-identity',
region_name='us-east-1')
response = identity.get_id(AccountId='12344566', IdentityPoolId='us-east-1:XXXXXX')
identity_id = response['IdentityId']
print ("Identity ID: %s"%identity_id)
response = identity.get_open_id_token(IdentityId=identity_id)
token = response['Token']
print ("\nToken: %s"%(token))
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
print ("\nSecret Key: %s"%(secretKey))
print ("\nAccess Key %s"%(accessKey))
Once I have these details I'm then attempting to call the API Gateway. I use
javascript for this task as I haven't found an easy way to achieve the result
I want in python:
var apigClient = apigClientFactory.newClient({
accessKey: 'aaaaaaaa',
secretKey: 'kkkkkkkk',
sessionToken: 'ssssss',
region: 'us-east-1'
});
apigClient.helloworldGet({},'')
.then(function(result){
console.log("success!: " + result);
}).catch( function(result){
console.log("FAIL: " + result);
});
This fails with the response:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403
.
I've setup CORS correctly as the OPTIONS request succeeds. If I use my main
access key and secret to authenticate the script works. If I turn off the IAM
credentials requirement on the get/helloworld method the javascript runs
successfully. I've attached a policy to both the auth and unauth roles that
Cognito setup for the identity pool, this policy looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "dsfdsafasfdsfasdf",
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:123456787:dsfsdfsdfs/dev/GET/helloworld"
]
}
]
}
I've tried attaching this both as a managed policy and an inline policy.
What am I missing here? Is it something to do with trying to access as an
unauthenticated user (even though the role assigned to that type of user has a
policy attached that should allow it to access the API)?
Note that there's no Lamda's involved here, just a simple task definition
sitting in an ECS Autoscale group that the API Gateway calls when the
helloworld method is invoked. As detailed here:
<https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-with-
microservices-deployed-on-amazon-ecs/>
Answer: Turns out it was the way I was retrieving the token. I was using
sessionToken = identity.get_open_id_token(IdentityId=identity_id)
I should have got the token from the response when I requested credentials:
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
sessionToken = resp['Credentials']['SessionToken']
|
Beginners Python: Regex & Phone Numbers
Question: Working my way through a beginners Python book and there's two fairly simple
things I don't understand, and was hoping someone here might be able to help.
The example in the book uses regular expressions to take in email addresses
and phone numbers from a clipboard and output them to the console. The code
looks like this:
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
import pyperclip, re
# Create phone regex.
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? #[1] area code
(\s|-|\.)? #[2] separator
(\d{3}) #[3] first 3 digits
(\s|-|\.) #[4] separator
(\d{4}) #[5] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[6] extension
)''', re.VERBOSE)
# Create email regex.
emailRegex = re.compile(r'''(
[a-zA-Z0-9._%+-]+
@
[\.[a-zA-Z0-9.-]+
(\.[a-zA-Z]{2,4})
)''', re.VERBOSE)
# Find matches in clipboard text.
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups [8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
# Copy results to the clipboard.
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to Clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers of email addresses found')
Okay, so firstly, I don't really understand the phoneRegex object. The book
mentions that adding parentheses will create groups in the regular expression.
If that's the case, are my assumed index values in the comments wrong and
should there really be two groups in the index marked one? Or if they're
correct, what does groups[7,8] refer to in the matching loop below for phone
numbers?
Secondly, why does the emailRegex use a mixture of lists and tuples, while the
phoneRegex uses mainly tuples?
**Edit 1**
Thanks for the answers so far, they've been helpful. Still kind of confused on
the first part though. Should there be eight indexes like rock321987's answer
or nine like sweaver2112's one?
**Edit 2**
Answered, thank you.
Answer: every opening left `(` marks the beginning of a capture group, and you can
nest them:
( #[1] around whole pattern
(\d{3}|\(\d{3}\))? #[2] area code
(\s|-|\.)? #[3] separator
(\d{3}) #[4] first 3 digits
(\s|-|\.) #[5] separator
(\d{4}) #[6] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[7,8,9] extension
)
You should use [named groups](https://docs.python.org/2/howto/regex.html#non-
capturing-and-named-groups) here `(?<groupname>pattern)`, along with
clustering only parens `(?:pattern)` that don't capture anything. And
remember, you should capture quantified constructs, not quantify captured
constructs:
(?<areacode>(?:\d{3}|\(\d{3}\))?)
(?<separator>(?:\s|-|\.)?)
(?<exchange>\d{3})
(?<separator2>\s|-|\.)
(?<lastfour>\d{4})
(?<extension>(?:\s*(?:ext|x|ext.)\s*(?:\d{2,5}))?)
|
AttributeError: 'NoneType' object has no attribute 'lower' in python 3.4
Question: Code:
import requests
from bs4 import BeautifulSoup
import operator
def start(url):
word_list =[]
source_code =requests.get(url).text
soup = BeautifulSoup(source_code)
for post_string in soup.find_all('a',{'class':'cb-skin-ads-link'}):
content = post_string.string
words = content.lower()
for each_word in words:
print(each_word)
word_list.append(each_word)
start('http://www.cricbuzz.com/live-cricket-scorecard/16445/gl-vs-rcb-qualifier-1-indian-premier-league-2016')
Error:
Traceback (most recent call last):
File "C:/Users/Shera/PycharmProjects/Begin/wordcount.py", line 15, in <module>
start('http://www.cricbuzz.com/live-cricket-scorecard/16445/gl-vs-rcb-qualifier-1-indian-premier-league-2016')
File "C:/Users/Shera/PycharmProjects/Begin/wordcount.py", line 10, in start
words = content.lower()
AttributeError: 'NoneType' object has no attribute 'lower'
Answer: To understand what is going on, we should take a look at the
[documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string).
There is a case when `.string` would be `None`:
> If a tag contains more than one thing, then it’s not clear what .string
> should refer to, so .string is defined to be None
You should look into using
[`get_text()`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-
text) instead that would take into account the children of an element as well:
content = post_string.get_text()
Note that this would help to avoid the error, but you would still get no
output since the element you find really does not have any text:
<a target="_blank" href="Javascript:void(0)" class="cb-skin-ads-link cb-skin-ads-link-fixed ad-skin" rel="noreferrer"></a>
|
ipython notebook - memories disappear after running some function
Question: After runing some (imported) function that returns a variable, say X. The
memory usage increases much more than the size of X. And even I `del X` or all
variables by `%reest`. The memory usage is still much larger than before
running the function. And I can only clear all memory by restarting the
notebook.
I am confused, it seems the notebook saves the local variables used only
inside a (imported) function? Which seems unnecessary for me. And if this is
not a bug, how can I trace those large (local) variables used only in the
called function, and clear those memories?
Answer: As you said in your comment above, you are wondering why the iPython notebook
process doesn't release memory back to the OS. The answer is somewhat
complicated, and goes to the heart of how memory is managed in both the OS and
in the process.
When a process asks for more memory, the OS has to find an appropriately sized
chunk to map into the process's address space -- let's say 8KB (although it is
probably some large multiple of that). This is always done on page-boundaries
because of a number of factors, including how virtual memory works. TLDP has a
fairly decent description of how and why this is done: [Chapter 3 Memory
Management](http://www.tldp.org/LDP/tlk/mm/memory.html)
Meanwhile, the process didn't actually want 8KB for a new object, it only
wanted 128B. So it gets the 8KB chunk and adds it to the in-process pool of
available memory. Note that this is normally a portion of the process's
address space that is contiguous so that the 8KB boundaries of the OS page are
invisible to the process.
The in-process memory manager then allocates 128B to be used by whoever asked
for it. This happens over and over as objects are created. When they are
destroyed, the memory is returned _to the in-memory pool of available memory._
So if it's free, why not give it back to the OS? Well, for one thing it's
almost certainly not on a page boundary, so the OS wouldn't know what to do
with it. It's also almost certain that the freed memory is not at _the end_ of
the in-memory pool. So releasing it would create a discontinuity in the pool's
address space, which could then become a major PITA for the in-process memory
manager to tip-toe around.
In certain circumstances, where you _know_ you need some big chunk of memory,
that it will be used in a way that is independent from the rest of the in-
process memory management, and that when you're done with it you _can_ give it
back to the OS, then it is possible to reduce the process's memory size. This
is most often seen when a file is
[mmap](https://en.wikipedia.org/wiki/Mmap)'ed into the process image, worked
on, and then unmapped. But that's special case stuff.
|
Python Search text file & replace
Question: I want to take a list of words from textfile1.txt and replace the word
"example" on textfile2.txt to whatever the text is on line one, line two and
so on.. How would I do this?
Text file textfile1.txt
user1
user2
user3
user4
user5
Text file textfile2.txt
url/example
url/example
url/example
url/example
url/example
What I have so far
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput("textfile2.txt", inplace=True ) as file:
for line in file:
print(line.replace("example", "user1"), end='')
My goal:
url/user1
url/user2
url/user3
Answer: This should do it. In general, when you want to traverse 2 or more iterables
(lists, files, etc) in parallel, odds are you can use `zip`.
with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
for l, r in zip(f1, f2):
print(r[:r.find('/')+1] + l)
|
PyInstaller error with PySide
Question: I have been playing with PyInstaller on Windows 7 (64 bit). I am currently
using PyInstaller 3.1.1 with Python 2.7.6. I created an app that creates a
simple PySide GUI and generated a dist folder with an executable with this
command:
> C:\Python27\Scripts\pyinstaller.exe .\HelloWidget.spec
This is what the spec file looks like:
# -*- mode: python -*-
block_cipher = None
a = Analysis(['HelloWidget.py'],
pathex=['C:\\Users\\spearsc\\Documents\\python_projects\\HelloWorldGui'],
binaries=None,
datas=[('.\\mainwindow.ui', '.')],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='HelloWidget',
debug=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
name='HelloWidget')
I wanted to use a spec file, so the .ui file would be bundled along with
everything else. However, when I run the executable, I get this error:
> .\HelloWidget.exe
Traceback (most recent call last):
File "<string>", line 41, in <module>
File "c:\users\spearsc\appdata\local\temp\pip-build-djws3k\pyinstaller\PyInstaller\loader\pyimod03_importers.py", line
389, in load_module
File "PySide-1.2.2\PySide\__init__.py", line 55, in <module>
File "PySide-1.2.2\PySide\__init__.py", line 11, in _setupQtDirectories
File "PySide-1.2.2\PySide\_utils.py", line 87, in get_pyside_dir
File "PySide-1.2.2\PySide\_utils.py", line 83, in _get_win32_case_sensitive_name
File "PySide-1.2.2\PySide\_utils.py", line 58, in _get_win32_short_name
WindowsError: [Error 2] The system cannot find the file specified.
pyi_rth_qt4plugins returned -1
What is confusing to me is that when I look in the dist folder, I see compiled
PySide and Qt files:
Directory: C:\Users\spearsc\Documents\python_projects\HelloWorldGui\dist\HelloWidget
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 5/23/2016 4:45 PM 80896 bz2.pyd
-a--- 5/24/2016 5:20 PM 795278 HelloWidget.exe
-a--- 5/24/2016 5:20 PM 1019 HelloWidget.exe.manifest
-a--- 5/24/2016 4:42 PM 4102 mainwindow.ui
-a--- 5/24/2016 5:20 PM 1052 Microsoft.VC90.CRT.manifest
-a--- 5/23/2016 4:45 PM 245760 msvcm90.dll
-a--- 5/23/2016 4:45 PM 853328 msvcp90.dll
-a--- 5/23/2016 4:45 PM 641360 msvcr90.dll
-a--- 5/24/2016 4:43 PM 248320 pyside-python2.7.dll
-a--- 5/24/2016 4:43 PM 3063808 PySide.QtCore.pyd
-a--- 5/24/2016 4:43 PM 12750848 PySide.QtGui.pyd
-a--- 5/24/2016 4:43 PM 1095168 PySide.QtNetwork.pyd
-a--- 5/24/2016 4:43 PM 1052672 PySide.QtUiTools.pyd
-a--- 5/23/2016 4:45 PM 3004928 python27.dll
-a--- 5/24/2016 4:43 PM 3469824 QtCore4.dll
-a--- 5/24/2016 4:43 PM 11679744 QtGui4.dll
-a--- 5/24/2016 4:43 PM 1473536 QtNetwork4.dll
-a--- 5/23/2016 4:45 PM 10752 select.pyd
-a--- 5/24/2016 4:43 PM 330752 shiboken-python2.7.dll
-a--- 5/23/2016 4:45 PM 689664 unicodedata.pyd
-a--- 5/24/2016 4:43 PM 111616 _ctypes.pyd
-a--- 5/23/2016 4:45 PM 474624 _hashlib.pyd
Any thoughts? Can I not trust what I see in the dist folder?
5/25/16:
Well, this is interesting. I put a print statement in the
_get_win32_short_name function.
def _get_win32_short_name(s):
""" Returns short name """
print s
buf_size = MAX_PATH
for i in range(2):
buf = create_unicode_buffer(u('\0') * (buf_size + 1))
r = GetShortPathNameW(u(s), buf, buf_size)
if r == 0:
raise WinError()
if r < buf_size:
if PY_2:
return buf.value.encode(sys.getfilesystemencoding())
return buf.value
buf_size = r
raise WinError()
Here is the result I got back after I built a new executable.
> .\HelloWidget.exe
C:\Users\spearsc\DOCUME~1\PYTHON~1\HELLOW~1\dist\HELLOW~1\PySide
Traceback (most recent call last):
File "<string>", line 41, in <module>
File "c:\users\spearsc\appdata\local\temp\pip-build-djws3k\pyinstaller\PyInstaller\loader\pyimod03_importers.py", line
389, in load_module
File "PySide-1.2.2\PySide\__init__.py", line 55, in <module>
File "PySide-1.2.2\PySide\__init__.py", line 11, in _setupQtDirectories
File "PySide-1.2.2\PySide\_utils.py", line 88, in get_pyside_dir
File "PySide-1.2.2\PySide\_utils.py", line 84, in _get_win32_case_sensitive_name
File "PySide-1.2.2\PySide\_utils.py", line 59, in _get_win32_short_name
WindowsError: [Error 2] The system cannot find the file specified.
pyi_rth_qt4plugins returned -1
The directory does not exist. Any ideas on how to get around that?
Answer: The trick is to add an empty PySide folder in the dist folder.
Directory: C:\Users\spearsc\Documents\python_projects\HelloWorldGui\dist\HelloWidget
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/25/2016 2:46 PM PySide
-a--- 5/23/2016 4:45 PM 80896 bz2.pyd
-a--- 5/25/2016 2:46 PM 795278 HelloWidget.exe
-a--- 5/25/2016 2:46 PM 1019 HelloWidget.exe.manifest
-a--- 5/24/2016 4:42 PM 4102 mainwindow.ui
-a--- 5/25/2016 2:46 PM 1052 Microsoft.VC90.CRT.manifest
-a--- 5/23/2016 4:45 PM 245760 msvcm90.dll
-a--- 5/23/2016 4:45 PM 853328 msvcp90.dll
-a--- 5/23/2016 4:45 PM 641360 msvcr90.dll
-a--- 5/24/2016 4:43 PM 248320 pyside-python2.7.dll
-a--- 5/24/2016 4:43 PM 3063808 PySide.QtCore.pyd
-a--- 5/24/2016 4:43 PM 12750848 PySide.QtGui.pyd
-a--- 5/24/2016 4:43 PM 1095168 PySide.QtNetwork.pyd
-a--- 5/24/2016 4:43 PM 1052672 PySide.QtUiTools.pyd
-a--- 5/25/2016 2:46 PM 542208 PySide.QtXml.pyd
-a--- 5/23/2016 4:45 PM 3004928 python27.dll
-a--- 5/24/2016 4:43 PM 3469824 QtCore4.dll
-a--- 5/24/2016 4:43 PM 11679744 QtGui4.dll
-a--- 5/24/2016 4:43 PM 1473536 QtNetwork4.dll
-a--- 5/25/2016 2:46 PM 506368 QtXml4.dll
-a--- 5/23/2016 4:45 PM 10752 select.pyd
-a--- 5/24/2016 4:43 PM 330752 shiboken-python2.7.dll
-a--- 5/23/2016 4:45 PM 689664 unicodedata.pyd
-a--- 5/24/2016 4:43 PM 111616 _ctypes.pyd
-a--- 5/23/2016 4:45 PM 474624 _hashlib.pyd
After I did that I ran the executable and got an import error for
PySide.QtXml, so I generated a new spec file and modified it.
# -*- mode: python -*-
block_cipher = None
a = Analysis(['HelloWidget.py'],
pathex=['C:\\Users\\spearsc\\Documents\\python_projects\\HelloWorldGui'],
binaries=None,
datas=[('.\mainwindow.ui', '.')],
hiddenimports=['PySide.QtXml'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='HelloWidget',
debug=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
name='HelloWidget')
I then used the spec file to create the executable again. I added the empty
PySide to the dist folder, and it worked!
|
How to select the following specific XML nodes using XPath?
Question: I have an XML doc like the following:
<Objects>
<object distName="a/b"> </object>
<object distName="a/b/c1"> </object>
<object distName="a/b/c4/d/e"> </object>
<object distName="a/b/c2"> </object>
<object distName="a/b/c6/d"> </object>
</Objects>
And I need to select all nodes which has a path that ends with **"c" +
number**. Like: "_a/b/c1_ " and "_a/b/c2_ " but not like "_a/b/c6/d_ ", nor
"_a/b/c4/d/e_ ".
If I try the following:
`cNodes = xmlDoc.xpath("//object[contains(@path, `a/b/c`)]")`
Then this will include "a/b/c6/d" and "a/b/c4/d/e" which is not what I
require.
So is there a way to do the job **_in one or maybe two lines of code_**. I
mean I can do it with like a loop and stuff like that, which I don't want to.
That's because the real XML doc is thousands of nodes.
PS: Python 2.7, lxml
Answer: I'm afraid this can't be done using pure XPath 1.0 which is XPath version that
`lxml` supports.
As an alternative, you can try to split the attribute by `/`, get the last
split result, and check if it starts with `c`, all in one line using list
comprehension, for example :
>>> raw = '''<Objects>
... <object distName="a/b"> </object>
... <object distName="a/b/c1"> </object>
... <object distName="a/b/c4/d/e"> </object>
... <object distName="a/b/c2"> </object>
... <object distName="a/b/c6/d"> </object>
... </Objects>'''
...
>>> from lxml import etree
>>> xmlDoc = etree.fromstring(raw)
>>> cNodes = xmlDoc.xpath("//object[contains(@path, 'a/b/c')]")
>>> result = [etree.tostring(n) for n in cNodes if n.attrib["distName"].split('/')[-1].startswith("c")]
>>> print result
['<object distName="a/b/c1"> </object>\n ', '<object distName="a/b/c2"> </object>\n ']
|
How to I modify an external list?
Question: I'm trying to code this thing in python, and I have bumped into a road block.
I have this list, and I want to modify it, and keep the changes after the
program is exited. I have no clue where to start.
Essentially, I want a list that can be accessed and modified, and will be
saved and not reset after the thing using it is closed.
EDIT: Here is my idea; There is a list that I have, let's call it basket. I
want to code a program to add to and remove from the 'basket', and to keep the
changes after I close the program. Hope that clarifies... And I tried using
global, but that got all funny, so I essentially deleted that version.
Answer: You can use json, pickle, or any similar library to write data to a file and
read it back and store in a list. This will create the file save.json in your
current working directory that contains json-information about your list. You
will notice that your list will always contain the numbers you added before,
it doesn't "forget" what you added to the list since it's saved in a file.
import os
import json
foo = [1,2,5,9] #default
#if safe file exists, load its contents into foo list
if os.path.isfile("save.json"):
with open("save.json", "r") as file:
foo = json.loads(file.read())
foo.append(int(input("Enter a number to add to foo")))
print(foo)
#write foo list to file
with open("save.json", "w") as file:
file.write(json.dumps(foo))
|
Plot Cumulative Distribution Function from shape, scale, and location parameters
Question: After applying Generalised Extreme Value (GEV) theory I have a shape,
location, and scale parameter to describe my distribution. Now I'm trying to
plot a CDF with these three parameters in Python. In matlab there's a ["cdf"
function](http://www.mathworks.com/help/stats/cdf.html) that does this. I
cannot find a way to do it with scipy?
Answer: Use the `cdf` method of
[`scipy.stats.genextreme`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.genextreme.html).
For example, the following ipython session...
In [40]: from scipy.stats import genextreme
In [41]: shape = -0.5
In [42]: loc = 0.0
In [43]: scale = 2.5
In [44]: x = np.linspace(scale/shape, 20, 200)
In [45]: y = genextreme.cdf(x, shape, loc, scale)
In [46]: import matplotlib.pyplot as plt
In [47]: plt.plot(x, y, label="GEV CDF")
Out[47]: [<matplotlib.lines.Line2D at 0x10e135790>]
In [48]: plt.legend(loc='best')
Out[48]: <matplotlib.legend.Legend at 0x10de4cc50>
generates this plot:
[](http://i.stack.imgur.com/os0Ki.png)
Note that the shape parameter `c` in the scipy code has the opposite sign of
the shape parameter ξ used in the [wikipedia article on the generalized
extreme value
distribution](https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution).
|
How to load lists in pelilcanconf.py from external file
Question: There are different lists available in pelicanconf.py such as
SOCIAL = (('Facebook','www.facebook.com'),)
LINKS =
etc.
I want to manage these content and create my own lists by loading these values
from an external file which can be edited independently. I tried importing
data as a text file using python but it doesn't work. Is there any other way?
Answer: What exactly did not work? Can you provide code?
You can execute arbitrary python code in your `pelicanconf.py`.
Example for a very simple CSV reader:
# in pelicanconf.py
def fn_to_list(fn):
with open(fn, 'r') as res:
return tuple(map(lambda line: tuple(line[:-1].split(';')), res.readlines()))
print(fn_to_list("data"))
CSV file `data`:
A;1
B;2
C;3
D;4
E;5
F;6
Together, this yields the following when running `pelican`:
# ...
((u'A', u'1'), (u'B', u'2'), (u'C', u'3'), (u'D', u'4'), (u'E', u'5'), (u'F', u'6'))
# ...
Instead of printing you can also assign this list to a variable, say `LINKS`.
|
gem5 simulation time is high
Question: good day every body
I have a real problem here that took a near of couple weeks on searching but
without a conclusion
I'm trying to run a compiled c++ code (a binary file) on gem5 to measure the
time consumed for some architectures I made using python and make my compare
to show the statistics etc..
this would look OK using binaries that take a small amount of time to finish
but when a binary should take let's say 2 seconds for example, the simulation
time would be really big
how to resolve this issue, I need simulation time optimized as possible
I think it would be easy but I'm not able to figure it out until now :\
what I reached until now is:
\- building gem5 in fast mode, but that did not give me any difference from
the optimized mode in the simulation time
\- using the fast forwarding in the optimized mode, however. I could not get
that done until now
any help please !
Answer: A few suggestions:
* You can use Classical Memory model if the program does not involve complex memory interactions. This would be faster than the Ruby model.
* Fast forward your application upto the point where the real computation begins. You mentioned it did not work for you. One thing to check would be : if you're using Ruby memory model, that doesn't support fast forwarding. It works with Classic memory model. <http://www.m5sim.org/General_Memory_System>
* Another thing that might be of interest to you is Simpoints, which can characterize the important sections of your app so that you run those instead of the complete app. Of course, you might want to run the complete app later, but this can give you a decent first order comparison across architectures. Check <http://gem5.org/Simpoints>
|
Python object instantiation from within another object - is it a memory leak?
Question: Consider the following small Python GUI program, where the user can click a
button over and over to cycle between window 1 and window 2:
import tkinter
class Window1:
def __init__(self, parent):
# Initialize a new GUI window
self.parent = parent
self.window = tkinter.Toplevel(self.parent)
self.window.title('Window 1')
# Make a button to launch Window 2
launch_window_2_button = tkinter.Button(self.window, text='Launch Window 2')
launch_window_2_button.config(command=self.launch_window_2)
launch_window_2_button.pack()
def launch_window_2(self):
self.window.destroy()
Window2(self.parent)
class Window2:
def __init__(self, parent):
# Initialize a new GUI window
self.parent = parent
self.window = tkinter.Toplevel(self.parent)
self.window.title('Window 2')
# Make a button to launch Window 1
launch_window_1_button = tkinter.Button(self.window, text='Launch Window 1')
launch_window_1_button.config(command=self.launch_window_1)
launch_window_1_button.pack()
def launch_window_1(self):
self.window.destroy()
Window1(self.parent)
if __name__ == "__main__":
# Initialize and hide the root GUI
# (each class will spawn a new window that is a child of the root GUI)
root = tkinter.Tk()
root.withdraw()
Window1(root) # Start by spawning Window 1
root.mainloop()
**Question 1:** Since each new class is being instantiated from within another
class, is this a memory leak?
**Question 2:** Is this the most correct and Pythonic way to code this
application?
**Question 3:** Assuming that the answer to question 1 is no, what if I
changed `Window1(self.parent)` to `self.something = Window1(self.parent)`. Now
that there is a reference, is it a memory leak now?
Answer: > Question 1: Since each new class is being instantiated from within another
> class, is this a memory leak?
No. And I think you are confusing between a few things memory leak and object
references not being used. @kindall explains it beautifully in his comment
under your question.
The best way to understand what is going is to know that the
`tkinter.TopLevel(..)` constructor is [side-effects
based.](http://programmers.stackexchange.com/questions/40297/what-is-a-side-
effect) It will hold the reference to your window within the root object, so
that it knows how to deal with various windows. _And so is the constructor of
your class._ Once it creates a `self.window` and somehow has `root` have
reference to it, its job is done. The reference of this object is held too,
although not explicitly (see answer to your Question 3 below).
* * *
> Question 2: Is this the most correct and Pythonic way to code this
> application?
The fact that references to the objects `Window1` and `Window2` objects are
not used bugs me too. Other than that, I'd probably store away the references
of the window elements(buttons, etc) also within the object -- They might not
be of any immediate use, but they might be later on.
* * *
> Question 3: Assuming that the answer to question 1 is no, what if I changed
> the following lines:
>
> Window1(self.parent)
>
> to:
>
> self.something = Window1(self.parent)
>
> Now that there is a reference, is it a memory leak now?
Think about the below line:
launch_window_2_button.config(command=self.launch_window_2)
In order for that line to work, tkinter has to store the reference of
`self.launch_window2` (and thereby `self`) somewhere, so your `self.something`
is not doing anything significant at all.. :)
|
Python flask and restless - how to return gz file of json object
Question: I I am using flask-restless. I am trying to respond of a get request of a gz
file of a json object from s3 and do not understand how to send a gz file.
class report_download(Resource):
def get(self,report_name):
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(bucketname)
key = Key(bucket, report_name)
key.get_contents_to_filename('/tmp/%s' % report_name)
os.system('gzip /tmp/%s' % report_name)
data = open('/tmp/%s.gz' % report_name).readlines()[0]
return data
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 710, in finish
self.wfile.close()
File "/usr/lib/python2.7/socket.py", line 279, in close
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
File "/usr/local/lib/python2.7/dist-packages/gevent-1.0b2-py2.7-linux-x86_64.egg/gevent/socket.py", line 468, in sendall
data_sent += self.send(_get_memory(data, data_sent), flags)
File "/usr/local/lib/python2.7/dist-packages/gevent-1.0b2-py2.7-linux-x86_64.egg/gevent/socket.py", line 439, in send
return sock.send(data, flags)
error: [Errno 32] Broken pipe
127.0.0.1 - - [26/May/2016 03:29:03] "GET /api/driver/report/download/7000_upload_.json HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 481, in wrapper
return self.make_response(data, code, headers=headers)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 510, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/representations/json.py", line 20, in output_json
dumped = dumps(data, **settings) + "\n"
File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
return encode_basestring_ascii(o)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte
Answer: Zipped data is binary, so, `readlines` probably only reads corrupted data.
You can use python module `gzip`, without the need of any external program:
import gzip
class report_download(Resource):
def get(self,report_name):
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(bucketname)
key = Key(bucket, report_name)
contents = key.get_contents_as_string()
data = StringIO.StringIO()
zip = gzip.GzipFile(fileobj=data, mode='wb')
zip.write(contents)
zip.close()
return Response(data.getvalue(), mimetype='application/x-gzip')
|
Parsing IMDB with BeautifulSoup
Question: I've stripped the following code from IMDB's mobile site using BeautifulSoup,
with Python 2.7.
I want to create a separate object for the episode number '1', title 'Winter
is Coming', and IMDB score '8.9'. Can't seem to figure out how to split apart
the episode number and the title.
<a class="btn-full" href="/title/tt1480055?ref_=m_ttep_ep_ep1">
<span class="text-large">
1.
<strong>
Winter Is Coming
</strong>
</span>
<br/>
<span class="mobile-sprite tiny-star">
</span>
<strong>
8.9
</strong>
17 Apr. 2011
</a>
Answer: You can use `find` to locate the `span` with the class `text-large` to the
specific element you need.
Once you have your desired `span`, you can use `next` to grab the next line,
containing the episode number and `find` to locate the `strong` containing the
title
html = """
<a class="btn-full" href="/title/tt1480055?ref_=m_ttep_ep_ep1">
<span class="text-large">
1.
<strong>
Winter Is Coming
</strong>
</span>
<br/>
<span class="mobile-sprite tiny-star">
</span>
<strong>
8.9
</strong>
17 Apr. 2011
</a>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
span = soup.find('span', attrs={'text-large'})
ep = str(span.next).strip()
title = str(span.find('strong').text).strip()
print ep
print title
> 1.
> Winter Is Coming
|
Why isn't my WeakSet empty after deleting the only other reference?
Question: I decided I should familiarize myself with the [`weakref`
library](https://docs.python.org/3/library/weakref.html), so I started messing
around with the collections, thought I was getting the hang of it until this.
>>> import weakref
>>> class Greek():
def __init__(self, name):
self.name = name
>>> objs = [Greek('alpha'), Greek('gamma'), Greek('zeta')]
>>> weak_s = weakref.WeakSet()
>>> for obj in objs: weak_s.add(obj)
Here I have a WeakSet `weak_s` that I would expect to contain 3 `weakref`s to
each `Greek()` instance, and it does:
>>> weak_s.data
{<weakref at 0x02ECA690; to 'Greek' at 0x02E5FF90>,
<weakref at 0x02ECA720; to 'Greek' at 0x02E5FFB0>,
<weakref at 0x02ECA750; to 'Greek' at 0x02E5FFD0>}
Then I would expect that as soon as I get rid of the `objs` name, there won't
be any more "strong references" to each `Greek()` instance, and they will be
garbage collected. But for some reason this doesn't happen.
>>> del objs
>>> weak_s.data
{<weakref at 0x02ECA750; to 'Greek' at 0x02E5FFD0>}
Why is there still a weakref inside my WeakSet? I can use `del` again and it
persists, seemingly no matter what I do.
Answer: You still have the `obj` variable from here:
>>> for obj in objs: weak_s.add(obj)
That variable retains its last value from the loop, so it's still referring to
the last `Greek` instance, keeping it alive and in the `WeakSet`.
|
Importing modules from different directories
Question: What is the pythonic way for absolute importing modules located in different
directories in Python 3? I am able to import modules by modifying the
`sys.path` but that method is hackey.
The alternative method, from what I've read, is to turn the project into a pip
installable package. This is method beyond me, can someone elaborate on this
process and logic? After writing a `setup.py` script, do I just `python
setup.py install`, then all my modules and packages are in the right path and
will work?
Answer: ## Loading a script dynamically from anywhere via a given path
import importlib.machinery
import imp
import os.path
path = '/home/user/testscript' # without .py
fname = os.path.basename(path)
namespace = fname.replace(' ', '_').strip('\\/;,. ')
loader = importlib.machinery.SourceFileLoader(namespace, os.path.abspath(path+'.py'))
handle = loader.load_module(namespace)
imp.reload(handle)
ret = handle.mainFunction()
`handle` being your library name. I just call it handle because I use it in a
one shot test library myself so it gets deleted anyway in every iteration of
the loop.
Sorry for syntax issues, wrote it on the phone. I'll correct any syntax issues
or indentation issues in a few min.
## Minimalistic example would be:
import importlib.machinery
# Register the "mylib" namespace as "test.py"
loader = importlib.machinery.SourceFileLoader("mylib", r'C:\Users\OpenWindows\Desktop\test.py')
# And load that namespace
mylib = loader.load_module("mylib")
# And now we can call it whenever we want.
ret = mylib.someFunction()
## Traditional approach (not absolute path friendly)
Would be to just create a folder structure that looks like this:
|- main.py
|-- mylib /
|-- __init__.py
|-- mylib.py
And in the `__init__.py` file create something that looks like:
from mylib.mylib import *
That way, any function or class in `mylib.py` would be imported as if it
resided in `main.py`. However, again this is heavily dependant on the
subfolder residing in the same folder as the script you're executing. But it's
also a traditional way of shipping/adding functionality to a application.
There's some other stuff you can do in the
[`__init__.py`](https://docs.python.org/3/tutorial/modules.html#packages) file
that might be useful. Have a look at the documentation.
|
how to make a tkinter window not resizable?
Question: i need a tkinter (python) script to me static (not resizeable)
i have a pretty simple tkinter script but i don't want i to be reasizeable
like some kind of error message. i honestly don't know what to do
this is my script:
from tkinter import *
import ctypes, os
def callback():
active.set(False)
quitButton.destroy()
JustGo = Button(root, text=" Keep Going!", command= lambda: KeepGoing())
JustGo.pack()
JustGo.place(x=150, y=110)
#root.destroy() # Uncoment this to close the window
def sleep():
if not active.get(): return
root.after(1000, sleep)
timeLeft.set(timeLeft.get()-1)
timeOutLabel['text'] = "Time Left: " + str(timeLeft.get()) #Update the label
if timeLeft.get() == 0: #sleep if timeLeft = 0
os.system("Powercfg -H OFF")
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
def KeepGoing():
active.set(True)
sleep()
quitButton1 = Button(root, text="do not sleep!", command=callback)
quitButton1.pack()
quitButton1.place(x=150, y=110)
root = Tk()
root.geometry("400x268")
root.title("Alert")
root.configure(background='light blue')
timeLeft = IntVar()
timeLeft.set(10) # Time in seconds until shutdown
active = BooleanVar()
active.set(True) # Something to show us that countdown is still going.
label = Label(root, text="ALERT this device will go to sleep soon!", fg="red")
label.config(font=("Courier", 12))
label.configure(background='light blue')
label.pack()
timeOutLabel = Label(root, text = 'Time left: ' + str(timeLeft.get()), background='light blue') # Label to show how much time we have left.
timeOutLabel.pack()
quitButton = Button(root, text="do not sleep!", command=callback)
quitButton.pack()
quitButton.place(x=150, y=110)
root.after(0, sleep)
root.mainloop()
Answer: The `resizable` method on the root window takes two boolean parameters to
describe whether the window is resizable in the X and Y direction. To make it
completely fixed in size, set both parameters to `False`:
root.resizable(False, False)
|
Disable a Tkinter button when variables are at 0
Question: I'm learning python still so the rest of my code may be flawed but my main
problem is I cant disable this button when the Wood and Stone variable are at
0. I've tried using a while statement that runs the
_button.config(state=DISABLED)_ command when _stone > 0 and wood > 0_ but that
didn't seem to work.
from tkinter import *
from tkinter import tkk
class main:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.CraftPickaxe = Button(frame, text = 'Pickaxe', command = self.craftPick)
self.CraftPickaxe.pack()
###RESOURCES###
self.wood = 1
self.stone = 1
self.pickaxe = 0
def craftPick(self):
self.stone -= 1
self.wood -= 1
self.pickaxe += 1
print(self.stone)
print(self.wood)
print(self.pickaxe)
def loop(self):
while True:
if self.stone < 0 and self.wood < 0:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)
root = Tk()
b = main(root)
root.mainloop()
EDIT: what I think is happening now is that its not constantly checking the
variables to see if it goes below zero and therefore not disabling at all.
What I'm thinking may need to happen is a check that runs in the _craftPick_
function.
Answer: I think that your problem is that your variable is 0 and not a negative
number.
So when you check if your variable is less than 0 it won't disable it because
your variable is not smaller than 0, it is exactly 0.
Try with this better
while True:
if self.stone < 1 and self.wood < 1:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)
Also, you must avoid the loop.
def craftPick(self):
self.stone -= 1
self.wood -= 1
self.pickaxe += 1
if self.stone < 1 and self.wood < 1:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)
|
dataframe change size and the convert to panel python
Question: I have a question on how to change dataframe to a panel while changinig the
dimensions of the dataframe. Originally I have a data frame with 2000 rows and
784 colmuns:
data=pd.DataFrame(np.random.randn(2000,784))
data.shape
(2000, 784)
I would like to turn each column into a 28*28 dataframe and then store this
into a panel like structure with the size (2000,28,28) or 2000 28 by 28
dataframes. Looking at some
[answers](http://stackoverflow.com/questions/17243186/assigning-dataframe-to-
panel-in-pandas), I tried:
data_panel=pd.Panel(dict([ (i,data) for i in range(2000)]))
data_panel
<class 'pandas.core.panel.Panel'>
Dimensions: 2000 (items) x 2000 (major_axis) x 784 (minor_axis)
Items axis: 0 to 1999
Major_axis axis: 0 to 1999
Minor_axis axis: 0 to 783
But that is not what I want. The items axis is correct, but I would like the
major axis and minor axis to be 28 by 28.
Answer: What seems to be the problem? This works:
import pandas as pd
import numpy as np
data = pd.DataFrame(np.random.randn(2000,784))
panel = pd.Panel(data.values.reshape(2000, 28, 28))
# In [49]: q.panel[42].shape
# Out[49]: (28, 28)
# In [51]: q.panel
# Out[51]:
# <class 'pandas.core.panel.Panel'>
# Dimensions: 2000 (items) x 28 (major_axis) x 28 (minor_axis)
# Items axis: 0 to 1999
# Major_axis axis: 0 to 27
# Minor_axis axis: 0 to 27
|
ProgrammingError: column "column" of relation "schema" does not exist
Question: I'm following this tutorial about using Scrapy with Postgres
<http://newcoder.io/scrape>. I'm new with postgres and very familiar with
scrapy.
Nowhere in the tutorial does it state anything about migrations so I think it
intends to generate the tables using
`DeclarativeBase.metadata.create_all(engine)` or within the contents of the
code somewhere.
my `models.py`
from sqlalchemy import Table, create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def db_connect():
return create_engine(URL(**settings.DATABASE))
def create_scores_table(engine):
""""""
DeclarativeBase.metadata.create_all(engine)
class Scores(DeclarativeBase):
__tablename__ = "scores"
id = Column(Integer, primary_key=True)
score = Column('score', String, nullable=True)
my `pipelines.py`:
from sqlalchemy.orm import sessionmaker
from models import Scores, db_connect, create_scores_table
class RrsportsPipeline(object):
def __init__(self):
engine = db_connect()
create_scores_table(engine)
self.Session = sessionmaker(bind=engine)
def process_item(self, item, spider):
session = self.Session()
scores = Scores(**item)
try:
session.add(scores)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return item
I know the database is connecting correctly too with correct creds and
database name.
the full Traceback
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 588, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/ubuntu/rgsports/rgsports/rgsports/pipelines.py", line 44, in process_item
session.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 801, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 392, in commit
self._prepare_impl()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 372, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2019, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2137, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2101, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 174, in save_obj
mapper, table, insert)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 800, in _emit_insert_statements
execute(statement, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1146, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 450, in do_execute
cursor.execute(statement, parameters)
ProgrammingError: (psycopg2.ProgrammingError) column "score" of relation "scores" does not exist
LINE 1: INSERT INTO scores (score)
^
[SQL: 'INSERT INTO scores (score) VALUES (%(score)s) RETURNING scores.id'] [parameters: {'score': u'114'}]
but when I run the spider:
`ProgrammingError: column "score" of relation "scores" does not exist`
Should I just create the table manually? If so, how? I'd prefer to have it
within the code though. Is there something in my models that I'm missing? Or
do I have to run models as some sort of deliberate migration? I can't seem to
trigger the tables to be built.
Answer: In pipeline.py it looks like you need to import create_scores_table instead of
create_matchups_table
it reads:
from sqlalchemy.orm import sessionmaker
from models import Scores, db_connect, create_matchups_table
should read:
from sqlalchemy.orm import sessionmaker
from models import Scores, db_connect, create_scores_table
|
How to convert CSV to nested JSON(upto level 3) in Python
Question: I'm having the following data in CSV format.
id,category,sub_category,sub_category_type,count
0,fruits,citrus,lemon,30
1,fruits,citrus,lemon,40
2,fruits,citrus,lemon,50
3,fruits,citrus,grapefruit,20
4,fruits,citrus,orange,40
5,fruits,citrus,orange,10
6,fruits,berries,blueberry,20
7,fruits,berries,strawberry,50
8,fruits,berries,strawberry,90
9,fruits,berries,cranberry,70
10,fruits,berries,raspberry,16
11,fruits,berries,raspberry,80
12,fruits,dried fruit,raisins,10
13,fruits,dried fruit,dates,15
14,fruits,dried fruit,dates,10
15,vegetables,legumes,beans,12
16,vegetables,legumes,beans,15
17,vegetables,legumes,chickpea,12
18,vegetables,green leaf,spinach,18
19,vegetables,green leaf,cress,19
I want to convert the above CSV format to nested JSON as
pandas.DataFrame.to_json() donesn't help me in converting to nested JSON
format.
Is there any solution for this?
PS: I'm answering the above question in Q&A style to share the knowledge. I
would be happy to know if there is any other solution better than this.
Answer: The following code is inspired from
[this](https://github.com/andrewheekin/csv2flare.json/blob/master/csv2flare.json.py)
github link. This code will help us in converting CSV upto level 3 nested JSON
import pandas as pd
import json
df = pd.read_csv('data.csv')
# choose columns to keep, in the desired nested json hierarchical order
df = df[["category", "sub_category","sub_category_type", "count"]]
# order in the groupby here matters, it determines the json nesting
# the groupby call makes a pandas series by grouping "category", "sub_category" and"sub_category_type",
#while summing the numerical column 'count'
df1 = df.groupby(["category", "sub_category","sub_category_type"])['count'].sum()
df1 = df1.reset_index()
print df1
d = dict()
d = {"name":"stock", "children": []}
for line in df1.values:
category = line[0]
sub_category = line[1]
sub_category_type = line[2]
count = line[3]
# make a list of keys
category_list = []
for item in d['children']:
category_list.append(item['name'])
# if 'category' is NOT category_list, append it
if not category in category_list:
d['children'].append({"name":category, "children":[{"name":sub_category, "children":[{"name": sub_category_type, "count" : count}]}]})
# if 'category' IS in category_list, add a new child to it
else:
sub_list = []
for item in d['children'][category_list.index(category)]['children']:
sub_list.append(item['name'])
print sub_list
if not sub_category in sub_list:
d['children'][category_list.index(category)]['children'].append({"name":sub_category, "children":[{"name": sub_category_type, "count" : count}]})
else:
d['children'][category_list.index(category)]['children'][sub_list.index(sub_category)]['children'].append({"name": sub_category_type, "count" : count})
print json.dumps(d)
On execution,
{
"name": "stock",
"children": [
{"name": "fruits",
"children": [
{"name": "berries",
"children": [
{"count": 20, "name": "blueberry"},
{"count": 70, "name": "cranberry"},
{"count": 96, "name": "raspberry"},
{"count": 140, "name": "strawberry"}]
},
{"name": "citrus",
"children": [
{"count": 20, "name": "grapefruit"},
{"count": 120, "name": "lemon"},
{"count": 50, "name": "orange"}]
},
{"name": "dried fruit",
"children": [
{"count": 25, "name": "dates"},
{"count": 10, "name": "raisins"}]
}]
},
{"name": "vegtables",
"children": [
{"name": "green leaf",
"children": [
{"count": 19, "name": "cress"},
{"count": 18, "name": "spinach"}]
},
{
"name": "legumes",
"children": [
{"count": 27, "name": "beans"},
{"count": 12, "name": "chickpea"}]
}]
}]
}
|
String format python
Question: I'm trying to clean up a bad solution. I have a utils file, which contains
some generic methods and a commands file, where I store a list of commands to
use within the program. However, when trying to clean up files by using string
format, I'm starting to run into problems.
# utils.py
import os
bin = '/usr/bin'
tool = '{0}/tool'.format(bin)
command = '{0} -dir %s -o geniso'.format(tool)
def exec_cmd(cmd):
os.system(cmd)
# dowork.py
from utils import *
exec_cmd(command % '/var/tmp')
In the example you can see, I'm trying to clean up the commands/utils by
concatenating variables to reduce the amount of characters in the variable and
this works fine. The problem is when I'm trying to then extend that format,
with another variable, for example a directory name (which gets passed from a
different class), I'm getting confused on how to efficiently do this
formatting. I'm also hitting the follow exception:
Traceback (most recent call last):
File "some_script.py", line 12, in <module>
import commands as cmd
File "/var/tmp/commands.py", line 32, in <module>
SOME_CMD = '{0} -p %s | tail -n +4 | awk \'{print \$4}\''.format(SOMETOOL)
KeyError: 'print \\$4'
How can I clean up this absolute mess, into a way that I can nicely format my
commands file but also leave room for further extension when using the
commands within a script.
Answer: If you want to use braces in formatted string, you have to escape them, e.g.
in your example use
SOME_CMD = '{0} -p %s | tail -n +4 | awk \'{{print \$4}}\''.format(SOMETOOL)
\-- note the double braces around `print \$4`.
On a related note, concatenating strings for system calls is considered a very
bad practice. If you don't need shell expansion and functionality, you can use
`subprocess` API that lets you pass arguments as lists and not strings.
There's also a pretty nice `sh`(<http://amoffat.github.io/sh/>) package that
supports pipes, shell expansion etc.
|
golang: read file generator
Question: I'm learning _go_ language and try to rewrite some of my Python code using
golang. I wrote a generator function that reads a text file line by line and
send (using _yield_ keyword) only "valid" lines (blank lines are ignored,
uncompleted lines are recomposed).
Sample file (myfile.txt):
#123= FOOBAR(1.,'text');
#126= BARBAZ('poeazpfodsp',
234,56);
parse.py:
#!/usr/bin/python
def validlines(filename):
with open(filename) as fdin:
buff = ''
for line in fdin.readlines():
line = line.strip()
if line == '':
continue
buff += line
if line[-1] != ';':
continue
yield buff
buff = ''
fdin.close()
for line in validlines('myfile.txt'):
print(line)
displays:
#123= FOOBAR(1.,'text');
#126= BARBAZ('poeazpfodsp',234,56);
Now, I try to do it the same way using a closure in golang:
parse.go:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func validLines(filename string) (func() (string, bool)) {
file, _ := os.Open(filename)
scanner := bufio.NewScanner(file)
return func() (string, bool) {
buff := ""
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if line == "" {
continue
}
buff += line
if line[len(line)-1] != ';' {
continue
}
return buff, true
}
file.Close()
return "", false
}
}
func main() {
vline := validLines("myfile.txt")
for line, ok := vline(); ok; {
fmt.Println(line)
}
}
displays:
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
...
What's the right way to do it in golang?
Answer: In Go you can use channels instead of yield, it's very convenient.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func ValidLines(filename string) (c chan string) {
c = make(chan string)
buff := ""
go func() {
file, err := os.Open(filename)
if err != nil {
close(c)
return
}
reader := bufio.NewReader(file)
for {
line, err := reader.ReadString('\n')
if err != nil {
close(c)
return
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
buff += line
if line[len(line)-1] != ';' {
continue
}
c <- buff
buff = ""
}
}()
return c
}
func main() {
for line := range ValidLines("myfile.txt") {
fmt.Println(line)
}
}
|
python help! invalid literal for int() with base 10:
Question: hi currently doing a code where the programe recalls two files one with
positions of words the other words the following code combines them however
when i change my code to be imported from a file i get the following error (if
compressed_sentence[(int(i)-1)]==uncompressed: ValueError: invalid literal for
int() with base 10: "['1',")
here is my code aswell:
uncompressed = 0
file1 = open ("NonDupT2.txt" , "r")
compressed_sentence=file1.read()
file1.close()
file1 = open ("PositionT2.txt" , "r")
compressed_Positionsonly=file1.read()
file1.close()
compressed_Positions= compressed_Positionsonly.split()
print(str(compressed_Positions))
for i in compressed_Positions:
if compressed_sentence[(int(i)-1)]==uncompressed:
print(compressed_sentence[(int(i))])
uncompressed = compressed_sentence[(int(i))]
else:
print(compressed_sentence[(int(i)-1)])
uncompressed=compressed_sentence[(int(i)-1)]
print(str(int(i)))
however it work when the variables are detemined by the program
uncompressed = 0
compressed_sentence = ['hello' , 'hello' , 'why' , 'hello' , 'lmao']
compressed_Positions = ['1' , '1' , '2' , '1' , '3']
print(str(compressed_Positions))
for i in compressed_Positions:
if compressed_sentence[(int(i)-1)]==uncompressed:
print(compressed_sentence[(int(i))])
uncompressed = compressed_sentence[(int(i))]
else:
print(compressed_sentence[(int(i)-1)])
uncompressed=compressed_sentence[(int(i)-1)]
print(str(int(i)))
Answer: The issue is that the compressed_Positions are read wrongly. The file reads
the contents as one string. That string is the entire contents of the text
file.
The split operator makes a list of strings. The first element of that list is
everything from the file until the first space and that appears to be
'[1,'
And that is what is interpreted by int() and that does not work. I think that
your PositionT2.txt contains:
[1, 1, 2, 1, 3]
It works if it contained:
1 1 2 1 3
To make the program work the same as the example with the explicit definition,
you need a split operator for compressed_sentences as well and your
NonDupT2.txt file must contain
hello hello why hello lmao
Instead of spaces, you can also use line breaks as separators in your text
file.
Good luck, Joost
|
Why can I import module bs4 or requests from python IDLE shell but not from the python interpreter?
Question: I can import module BeautifulSoup or requests without any problem when I run
it from my script or do it directly in the python IDLE shell:
Python 2.7.9 (default, Mar 8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> import bs4
>>> bs4
<module 'bs4' from '/usr/local/lib/python2.7/dist-packages/bs4/__init__.pyc'>
>>> import requests
>>> requests
<module 'requests' from '/usr/lib/python2.7/dist-packages/requests/__init__.pyc'>
However, when I do it from the command prompt using the python interpreter I
run into the following errors:
pi@raspberrypi:~/Desktop/A/C $ python
Python 2.7.9 (default, Mar 8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import bs4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/bs4/__init__.py", line 30, in <module>
from .builder import builder_registry, ParserRejectedMarkup
File "/usr/local/lib/python2.7/dist-packages/bs4/builder/__init__.py", line 4, in <module>
from bs4.element import (
File "/usr/local/lib/python2.7/dist-packages/bs4/element.py", line 3, in <module>
from pdb import set_trace
File "/usr/lib/python2.7/pdb.py", line 9, in <module>
import cmd
File "/usr/lib/python2.7/cmd.py", line 53, in <module>
IDENTCHARS = string.ascii_letters + string.digits + '_'
AttributeError: 'module' object has no attribute 'ascii_letters'
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/requests/__init__.py", line 55, in <module>
import urllib3
File "/usr/lib/python2.7/dist-packages/urllib3/__init__.py", line 10, in <module>
from .connectionpool import (
File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 29, in <module>
from .packages.ssl_match_hostname import CertificateError
File "/usr/lib/python2.7/dist-packages/urllib3/packages/__init__.py", line 5, in <module>
from ssl import CertificateError
File "/usr/lib/python2.7/ssl.py", line 90, in <module>
import textwrap
File "/usr/lib/python2.7/textwrap.py", line 40, in <module>
class TextWrapper:
File "/usr/lib/python2.7/textwrap.py", line 82, in TextWrapper
whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
AttributeError: 'module' object has no attribute 'maketrans'
I read a lot of forums, but didn't really understood what could be causing
this, and most importantly, how to solve it.
Many thanks for your help, Best, Mathieu
Answer: It is not really IDLE vs. Python shell on console but where the current
working directory for the process is. Because in the directory from wich you
start the console Python shell there is a `string.py` which ”shadows” the
`string` module from the standard library. Delete that `string.py` (and the
`string.pyc` if it exists) from that folder and other modules will find the
standard `string` module again.
|
Python inheritance dilemma for plugin
Question: _Although this question is in the context of a Sublime Text plugin, it is
actually a question about Python object orientated design._
Writing a Sublime Text plugin which contains 2 complimentary commands (with
some shared functionality) has led me to a Python inheritance dilemma. Both
options work perfectly well - I'm just unsure which is better OO design.
Option 1 - plugin commands use multiple inheritance:
import sublime, sublime_plugin
class CopyLine():
def copy_line(self):
sels = self.view.sel()
# Do some stuff
return line_region
class CopyLineCommand(sublime_plugin.TextCommand, CopyLine):
def run(self, edit):
line_region = self.copy_line()
# Do some stuff
class CutLineCommand(sublime_plugin.TextCommand, CopyLine):
def run(self, edit):
line_region = self.copy_line()
# Do some stuff
Option 2 - plugin commands inherit the plugin `TextCommand` class from their
parent:
import sublime, sublime_plugin
class CopyLine(sublime_plugin.TextCommand):
def copy_line(self):
sels = self.view.sel()
# Do some stuff
return line_region
class CopyLineCommand(CopyLine):
def run(self, edit):
line_region = self.copy_line()
# Do some stuff
class CutLineCommand(CopyLine):
def run(self, edit):
line_region = self.copy_line()
# Do some stuff
Both options have an aspect that I'm slightly uneasy about:
In _Option 1_ the `copy_line()` method in the `CopyLine` class uses methods
from the `sublime_plugin.TextCommand` class - e.g. the call shown to
`view.sel()` \- even though the `CopyLine` class has not inherited the
`sublime_plugin.TextCommand` class.
In _Option 2_ the `CopyLine` class inherits the `sublime_plugin.TextCommand`
class even though it is not actually a plugin.
Which of these is better OO design? Is there an alternative design that I
should use instead?
I've put the full code of both options in a [GitHub
Gist](https://gist.github.com/mattst/28a2fbacbe5780c1e0f0434951c102f7).
Answer: Implementing r-stein's suggestion provides a solution to the plugin
inheritance dilemma by using a non-OO design.
import sublime, sublime_plugin
def copy_line(view):
sels = view.sel()
# Do some stuff
return line_region
class CopyLineCommand(sublime_plugin.TextCommand):
def run(self, edit):
line_region = copy_line(self.view)
# Do some stuff
class CutLineCommand(sublime_plugin.TextCommand):
def run(self, edit):
line_region = copy_line(self.view)
# Do some stuff
The full code is in `Option_3_CopyAndCutLine.py` of this [GitHub
Gist](https://gist.github.com/mattst/28a2fbacbe5780c1e0f0434951c102f7).
|
is it possible to restart the already terminated process in python multiprocessing?
Question: Here is the example code for my question:
import multiprocessing, time
def nopr():
i=0
while 1:
i = i+1
print i
time.sleep(1)
p = multiprocessing.Process(target = nopr)
print "process started"
p.start()
time.sleep(04)
print "process ended"
p.terminate()
time.sleep(1)
p.start()
Answer: No you cannot start a terminated process, you would have to recreate it :
import multiprocessing, time
def nopr():
i=0
while 1:
i = i+1
print i
time.sleep(1)
p = multiprocessing.Process(target = nopr)
print "process started"
p.start()
time.sleep(04)
print "process ended"
p.terminate()
time.sleep(1)
p = multiprocessing.Process(target = nopr) # recreate
p.start()
|
Live update image while using socketio
Question: I'm using python to push every nth image from a scientific camera to a web
page. The webpage updates the image using `.replace()`. It's probably
important to note that this is not a webcam - it's a scientific cam. I'm using
the developer software to save an image to the server every n seconds, which
is then grabbed by the client.
I'm using HTML, JavaScript, Jquery, and python.
I also have a bunch of web sockets (using socketio on the client side, and
flask on the server side) such that when a button is clicked it emits a
command to move a motor connected to the server. When this happens, the image
stops updating until that emit function on the server is finished.
I have thought about using a background thread to push the image to the server
every n seconds (based on user request for refresh rate), but not sure this
would help at all... or where to start, really.
Thanks in advance.
Answer: I assume you are running an eventlet or gevent web server, since you mention
you are using WebSocket.
Whenever you have a potentially long task, be it a HTTP request or a Socket.IO
event handler, you have to make sure it is done asynchronously, so that the
web server isn't blocked and can continue to respond.
You don't explain how your motor movement is handled, but it sounds like you
might need to put that in a background thread (green thread, not regular
Python thread), and make frequent calls to `sleep()` so that other coroutines
get a chance to run while the bg thread is running. I think this will enable
the images to continue flowing.
|
running unittests \ integration tests in python
Question: I have a Django project with multiple apps. Each app has a set of unittests.
I'm using pytest as my test runner. We have gotten to a point that we want to
start writing integration tests. I was wondering if there is any way to keep
the naming convention and thus the auto discovery of pytest but still be able
(via flag maybe?) to run the different test types. The most intuitive solution
that comes to mind is some sort of decorator on test methods or even
`TestCase` classes (something like Category in JUnit).
something like:
@testtype('unittest')
def test_my_test(self):
# do some testing
@testtype('integration')
def test_my_integration_test(self):
# do some integration testing
and then i could run the test like:
py.test --type=integration
py.test --type=unittest
Is there such a thing?
If not, the only other solution i can think about is to add a django command
and "manually" build a testsuite and run it with pytest... I would prefer not
to use this option. Is there any other solution that can help me?
Thanks
Answer: You can [mark test
functions](https://pytest.org/latest/example/markers.html#marking-test-
functions-and-selecting-them-for-a-run).
import pytest
@pytest.mark.unittest
def test_my_test(self):
# do some testing
@pytest.mark.integration
def test_my_integration_test(self):
# do some integration testing
These custom markers must be
[registered](http://pytest.org/latest/example/markers.html#registering-
markers) in your pytest.ini file.
Then use the `-m` flag to run the marked tests
py.test -v -m unittest
|
Send MySQL blob content as a json response
Question: I have the following code of a GET method which takes a photo which is stored
in a blob type field in MySql and return. I want to return it to the client
inside a JSON string in a type it can display the image in an angularjs
application.
def GET(self,r):
user_data = CC.get_data(query) # holds the content of the blob field.
print type(user_data) # prints <type 'str'>
data = {'name': 'test',
'photo': user_data}
return json.dump(data)
This gives,
UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0:
invalid start byte
I have found in some websites its better to send as photo as byte array. Im
using web.py python framework. whats the best way to do this?
Answer: To prevent data loss, the best thing you can do to send binary data is encode
as `base64`.
import base64
def GET(self,r):
user_data = CC.get_data(query) # holds the content of the blob field.
data = {'name': 'test',
'photo': base64.b64encode(user_data)}
return json.dump(data)
However, sending binary data over JSON is really not recommended, specially in
web. You can send a URL to download the photo, for example.
|
Python JSON Iteration into a POST request
Question: I have a JSON file that is formatted something like
{
"unknown1":
[
{"text": "random text again",
"time": "Thu May 15 19:21:59 +0000 2016"},
"text": "akmfkdlm safsa fasffalmfa",
"time": "Thu May 21 09:53:51 +0000 2016"}
]
"unknown2":
[
"text": "fsda lmfalmfa",
"time": "Thu May 21 09:53:51 +0000 2016"},
]
}
The first item in the JSON is a random (unknown) label and there can be any
number of these unknowns. Within these unknowns are always a bunch
`text`/`time` pairings.
I am trying to send each `text` into my REST post service which accepts JSON
formatted to
text: "foo bar bat",
mime_type: "text/html",
extract_type: "HP" # HP, MP
So I am getting this error when I try to run my code and I not sure what to
do.
Here is my code:
import json
import requests
with open('locations_stripped.json') as data_file:
data = json.load(data_file)
headers = {'Content-Type' : 'application/json'}
for thing in data:
for text, time in data.iteritems():
print text
body = [{ "text": text , "mime_type": "text/html", "extract_type": "HP"}]
r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers)
print (r.content)
and here is the error:
$ python filterrest.py
unknown1
Traceback (most recent call last):
File "filterrest.py", line 30, in <module>
r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 111, in post
return request('post', url, data=data, json=json, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 461, in request
prep = self.prepare_request(req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 394, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 298, in prepare
self.prepare_body(data, files, json)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 452, in prepare_body
body = self._encode_params(data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 89, in _encode_params
for k, vs in to_key_val_list(data):
ValueError: too many values to unpack
One thing to note is it is printing the wrong text ("unknown1" instead of
"random text again") and I am not sure how to get it to only print the text.
Any help on this?
**UPDATE**
Per everyone's answer/comment I changed my code
...
for thing in data:
for text in data[thing]:
print text['text']
and this prints the text['text'] as I would expect. The issue lies in the way
I am doing my request. I changed my code as a test and set the data to
something that I know should work (I ran it via
[Postman](https://www.getpostman.com/%20%22Postman)).
Changed code:
r = requests.post('localhost:3003/api/extract/run', data='Hello. Where does the brown fox go?', headers=headers)
Expected Response:
[
{
"score": 0.30253747367501777,
"tag": "HP",
}
]
Instead what gets printed is what looks like an entire HTML page.
Answer: Assuming you have a valid json. You first need to traverse the list
corresponding to "unknown" keys, now this list again contains dictionaries
with `text` `time` keys.
for unknown_key in data:
for obj in data[unknown_key]:
body = { "text": obj['text'] , "mime_type": "text/html", "extract_type": "HP"}
r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers)
print (r.content)
|
gaierror: [Errno 11004] getaddrinfo failed
Question: I hope to access the text file from the following url:
<http://www.pythonlearn.com/code/intro-short.txt>
My code is
import socket
socket.getaddrinfo('127.0.0.1', 8080)
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('http://www.pythonlearn.com', 80))
mysock.send('GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n')
I keep getting an error: `gaierror: [Errno 11004] getaddrinfo failed`
Can you help me with this?
Thanks.
Answer: In `mysock.connect(('http://www.pythonlearn.com', 80))`, the first element in
the tuple should be just the host name (or address), without 'http://'.
So `mysock.connect(('www.pythonlearn.com', 80))` should work.
Incidentally, `socket.getaddrinfo('127.0.0.1', 8080)` would get the address
information for your local host, not the server you want to contact; so this
statement seems unnecessary.
|
Using reduce, map or other function to avoid for loops in python
Question: I have a program working for calculating the distance and then apply the
k-means algorithm. I tested on a small list and it's working fine and fast,
however, my original list is very big (>5000), so it's taking forever and I
ended it up terminating the running. Can I use outer() or any other parallel
function and apply it to the distance function to make this faster?? On the
small set that I have:
strings = ['cosine cos', 'cosine', 'cosine???????', 'l1', 'l2', 'manhattan']
And its distance 3D array returns like this:
[[[ 0. 0.25 0.47826087 1. 1. 0.89473684]
[ 0.25 0. 0.36842105 1. 1. 0.86666667]
[ 0.47826087 0.36842105 0. 1. 1. 0.90909091]
[ 1. 1. 1. 0. 0.5 1. ]
[ 1. 1. 1. 0.5 0. 1. ]
[ 0.89473684 0.86666667 0.90909091 1. 1. 0. ]]]
Each line of the array above represents the distance for one item in the
strings list. My way of doing it using the for loops is:
strings = ['cosine cos', 'cosine', 'cosine???????', 'l1', 'l2', 'manhattan']
data1 = []
for j in range(len(np.array(list(strings)))):
for i in range(len(strings)):
data1.append(1-Levenshtein.ratio(np.array(list(strings))[j], np.array(list(strings))[i]))
#n =(map(Levenshtein.ratio, strings))
#n =(reduce(Levenshtein.ratio, strings))
#print(n)
k=len(strings)
data2=np.asarray(data1)
arr_3d = data2.reshape((1,k,k))
print(arr_3d)
Where `arr_3d` is the array above. How can I use any of outer() or map() to
replace the for loops above, because when the list `strings` is big, it's
taking hours and never got the results even. I appreciate the help.
Levenshtein.ratio is a built in funciton in python.
Answer:
import numpy as np
strings = ['cosine cos', 'cosine', 'cosine???????', 'l1', 'l2', 'manhattan']
k=len(strings)
data = np.zeros((k,k))
for i,string1 in enumerate(strings):
for j,string2 in enumerate(strings):
data[i][j] = 1-Levenshtein.ratio(string1, string2)
print data
No gains to be had with `map` or `reduce` here, the loops need to be run as
@user2357112 mentions, however, this is cleaner and should run faster since it
avoids the `np.array(list(strings))` you were using throughout.
|
How can I use Theano with GPU on Ubuntu 16.04?
Question: I use the following script to test if GPU is working:
#!/usr/bin/env python
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time
vlen = 10 * 30 * 768 # 10 x #cores x # threads per core
iters = 1000
rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print f.maker.fgraph.toposort()
t0 = time.time()
for i in xrange(iters):
r = f()
t1 = time.time()
print 'Looping %d times took' % iters, t1 - t0, 'seconds'
print 'Result is', r
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
print('Used the cpu')
else:
print('Used the gpu')
When I run it, I get:
<http://pastebin.com/wM9jaGMF>
The interesting part is at the end:
ERROR (theano.sandbox.cuda): Failed to compile cuda_ndarray.cu: ('nvcc return status', 1, 'for cmd', 'nvcc -shared -O3 -m64 -Xcompiler -DCUDA_NDARRAY_CUH=c72d035fdf91890f3b36710688069b2e,-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION,-fPIC,-fvisibility=hidden -Xlinker -rpath,/home/moose/.theano/compiledir_Linux-4.4--generic-x86_64-with-Ubuntu-16.04-xenial-x86_64-2.7.11+-64/cuda_ndarray -I/home/moose/.local/lib/python2.7/site-packages/theano/sandbox/cuda -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -I/home/moose/.local/lib/python2.7/site-packages/theano/gof -o /home/moose/.theano/compiledir_Linux-4.4--generic-x86_64-with-Ubuntu-16.04-xenial-x86_64-2.7.11+-64/cuda_ndarray/cuda_ndarray.so mod.cu -L/usr/lib -lcublas -lpython2.7 -lcudart')
WARNING (theano.sandbox.cuda): CUDA is installed, but device gpu is not available (error: cuda unavailable)
## My system
* I use Ubuntu 16.04.
* I've installed CUDA through the standard repos (`V7.5.17`). `nvcc --version` works.
* I've installed Theano via pip
* I have CuDNN 4 (works with TensorFlow)
* I set `CUDA_ROOT=/usr/bin/` and `LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/` (I'm not sure if that is correct)
My `~/.theanorc` is
[global]
exception_verbosity=high
device=gpu
floatX=float32
[cuda]
root=/usr/bin/
## Paths
I think the installation from the standard repos might make things different
from a manual installation. Here are some paths which might uncover some
problems:
/usr/bin/nvcc
/usr/lib/x86_64-linux-gnu/libcuda.so
/usr/lib/x86_64-linux-gnu/libcudart.so
/usr/lib/nvidia-cuda-toolkit
/usr/include/cudnn.h
## Question
How can I make it work?
Answer: I'm not exactly sure what solved the issue, but one or both of the following
([source](http://deeplearning.net/software/theano/install_ubuntu.html))
sudo apt-get install python-numpy python-scipy python-dev python-pip python-nose g++ libopenblas-dev libblas-dev git
echo -e "\n[nvcc]\nflags=-D_FORCE_INLINES\n" >> ~/.theanorc
|
Functional/idiomatic way to express this Python in Clojure
Question: I have a data transformation that is leaving me a bit stymied. I wasn't able
to express myself in Clojure and even my Python, that I'm fluent in, still
feels quite gross.
I need a data structure like:
[1, 2, [3, 4], 5, 6]
to generate a structure like this:
[[1, 2, 3, 5, 6]
[1, 2, 4, 5, 6]]
where each sub-collection creates a new collection with the items accumulated
thus far. I only expect a single level of nesting.
My python attempt looks like this:
def foo(path, acc_list=[[]]):
for val in path:
if not isinstance(val, list):
for acc in acc_list:
acc.append(val)
else:
for subval in val:
new = acc_list[0][:]
new.append(subval)
acc_list.append(new)
del acc_list[0]
return acc_list
foo([1, 2, [3, 4], 5, 6])
# => [[1, 2, 3, 5, 6], [1, 2, 4, 5, 6]]
I'd like to know what a Clojure solution would be and (more importantly) the
thinking that led to that solution.
_update_
* The ints are just for example, they could be keywords or strings too and not necessarily ordered, although order must obviously be preserved.
* by nesting, I meant it won't be like `[1 [2 [3 [4 5] 6] 7] 8]` but more like `[1 [2 3] 4 [5] 6 [7 8 9]]` \- shallow.
Answer: An important feature of many of the Clojure core library functions is the
ability to handle lazy (potentially infinite) sequences; therefore, I would
think that a good (idiomatic) Clojure solution would be able to properly
expand an input containing subsequences that are infinite lazy sequences. For
example:
[:a :b (range) :c]
Should expand to
((:a :b 0 :c) (:a :b 1 :c) (:a :b 2 :c) (:a :b 3 :c) ...)
It would be great if the top-level sequence could also be infinite and handled
lazily, however, I don't think that is possible for this problem. (But if
someone else can think of a way to practically handle that, I'll be
delightfully surprised!)
Here's my solution:
(defn expand-subseqs [[x & xs]]
(when-not (nil? x)
(let [heads (if (sequential? x) x [x])
tails (expand-subseqs xs)]
(if-not tails (map vector heads)
(for [z tails, y heads] (cons y z))))))
The intuition here is that you recursively handle the tail of the input
sequence first, and then you prepend each possible value for the current head
onto each possible tail.
Some sample outputs:
user=> (expand-subseqs [1, 2, [3, 4], 5, 6])
((1 2 3 5 6) (1 2 4 5 6))
user=> (take 5 (expand-subseqs [:a :b (range) :c [true false]]))
((:a :b 0 :c true) (:a :b 1 :c true) (:a :b 2 :c true) (:a :b 3 :c true) (:a :b 4 :c true))
A nice benefit of this solution is that, by using `cons`, we actually reuse
the objects representing the tail sequences for each result, rather than
duplicating the whole sequence for each permutation. For example, in the last
sample above, the `(:c true)` tail sequence in every one of the five outputs
is actually the same object.
|
What arguments are available for the Python Tk() constructor?
Question: I'm trying to make a python tkinter application and I'm having a lot of
trouble finding a list of what arguments are available for creating a `Tk`
object.
example:
from tkinter import *
root = Tk(<args>)
root.mainloop()
Where can I find a full list of the arguments available?
For example I know I can give the window a title after it is already created
by saying `root.title("title")`, but can I give the window a title in the
constructor directly?
Answer: I used the documentation, which can be accessed via IDLE, Is this what you
looking for?
[](http://i.stack.imgur.com/vVNtR.png)
|
Matplotlib: how to add a base image to a 3D plot?
Question: This topic has been touched
[here](http://stackoverflow.com/questions/23785408/3d-cartopy-similar-to-
matplotlib-basemap), but no indications were given as to how to create a 3D
plot and insert an image in the `(x,y)` plane, at a specified `z` height.
So to come up with a simple and reproducible case, let's say that I create a
3D plot like this with `mplot3d`:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.winter,
linewidth=0, antialiased=True)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
plt.show()
Visually we have: [](http://i.stack.imgur.com/mnQTP.png)
**At the level`z=min(z)-1`**, where `-1` is a visual offset to avoid
overlapping, **I want to insert an image** representing the elements for which
the curve shows a certain value. **How to do it?**
In this example I don't care about a perfect matching between the element and
its value, so please feel free to upload any image you like. Also, is there a
way of letting that image rotate, in case one is not happy with the matching?
**EDIT**
This is a visual example of something similar made for a 3D histogram. The
grey shapes at the level `z=0` are the elements for which the bars show a
certain `z` value. [Source.](https://toeholds.wordpress.com/2010/03/26/3d-bar-
histogram-in-python/) [](http://i.stack.imgur.com/ENvTK.png)
Answer: Use `plot_surface` to draw image via `facecolors` argument.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
from matplotlib._png import read_png
from matplotlib.cbook import get_sample_data
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, .25)
Y = np.arange(-5, 5, .25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.winter,
linewidth=0, antialiased=True)
ax.set_zlim(-2.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fn = get_sample_data("./lena.png", asfileobj=False)
arr = read_png(fn)
# 10 is equal length of x and y axises of your surface
stepX, stepY = 10. / arr.shape[0], 10. / arr.shape[1]
X1 = np.arange(-5, 5, stepX)
Y1 = np.arange(-5, 5, stepY)
X1, Y1 = np.meshgrid(X1, Y1)
# stride args allows to determine image quality
# stride = 1 work slow
ax.plot_surface(X1, Y1, -2.01, rstride=1, cstride=1, facecolors=arr)
plt.show()
[](http://i.stack.imgur.com/A0GCd.png)
If you need to add values use `PathPatch`:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
from matplotlib.patches import PathPatch
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
x, y, z = xyz
if zdir == "y":
xy1, z1 = (x, z), y
elif zdir == "y":
xy1, z1 = (y, z), x
else:
xy1, z1 = (x, y), z
text_path = TextPath((0, 0), s, size=size, usetex=usetex)
trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])
p1 = PathPatch(trans.transform_path(text_path), **kwargs)
ax.add_patch(p1)
art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
# main
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, .25)
Y = np.arange(-5, 5, .25)
Xg, Yg = np.meshgrid(X, Y)
R = np.sqrt(Xg**2 + Yg**2)
Z = np.sin(R)
surf = ax.plot_surface(Xg, Yg, Z, rstride=1, cstride=1, cmap=cm.winter,
linewidth=0, antialiased=True)
ax.set_zlim(-2.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# add pathces with values
for i,x in enumerate(X[::4]):
for j,y in enumerate(Y[::4]):
text3d(ax, (x, y, -2.01), "{0:.1f}".format(Z[i][j]), zdir="z", size=.5, ec="none", fc="k")
plt.show()
[](http://i.stack.imgur.com/kjmc1.png)
|
Anaconda + Spark - changing python version for ipython notebooks
Question: I installed Anaconda, and try to work with spark on top. When I launch spark
with Ipython_OPTS="notebook", the python version is the one associated with
anaconda's version of python for the notebook.
$ conda search python
Using Anaconda Cloud api site https://api.anaconda.org
Fetching package metadata: ....
ipython 0.13 py26_0 defaults
* 4.1.2 py35_1 defaults
ipython-notebook 0.13.2 py27_0 defaults
4.0.4 py27_0 defaults
4.0.4 py34_0 defaults
4.0.4 py35_0 defaults
python 1.0.1 0 defaults
. 2.7.11 0 defaults
* 3.5.1 0 defaults
And if start spark-shell I can precise the environment version on which I am
interested (I want 2.7.11) :
$ PYSPARK_PYTHON=/Applications/anaconda/anaconda/envs/vingt-sept/bin/python pyspark
Python 2.7.11 |Continuum Analytics, Inc.| (default, Dec 6 2015, 18:57:58)
but if I start spark with the ipython notebook then it defaults back to the
python 3.5 version :-(
How can I link the default ipython version to the same version as the one of
my env "vingt-sept" ?
Answer: Similar to how you are setting the `PYSPARK_PYTHON` environment variable for
the `pyspark` shell, you can also set this environment variable in your
IPython/Jupyter notebook using:
import os
os.environ["PYSPARK_PYTHON"] = "/Applications/anaconda/anaconda/envs/vingt-sept/bin/python"
Refer to [this blog post](https://www.continuum.io/blog/developer-blog/using-
anaconda-pyspark-distributed-language-processing-hadoop-cluster) for more
information about setting `PYSPARK_PYTHON` and other Spark-related environment
variables from your notebook.
|
passing arguments to python script from command line
Question: I am really new to python and pandas, I am trying to execute a python script
using arguments in the command line but I got an error, here is my script
#!/usr/bin/python
import sys, pandas as pd
df1 = pd.read_table(sys.argv[0], sep="\t", header=0)
df2 = pd.read_table(sys.argv[1], sep="\t", header=0)
df_merge = pd.merge(left=df1, right=df2, left_on=sys.arg[2], right_on=sys.arg[3])
df_merge.to_csv(sys.arg[4], sep="\t")
And I got the following error: `KeyError: u'no item named file.out'`, any help
would be apreciated
My command line statement is: `merge_files.py file1.out file2.out col1 col3
test`
Answer: `sys.argv[0]` is the name of the script, i.e. `merge_files.py`. You can see
this by inserting `print(sys.argv)` at the beginning of your script. Try
increasing all your indices by 1.
|
ReviewBoard pip installation failure
Question: I am trying to install ReviewBoard on 14.04.1-Ubuntu and I get the error
below. I have used commands:
sudo apt-get install python-setuptools python-dev memcached patch libjpeg-dev
sudo pip install -U pip
sudo easy_install pip
sudo apt-get install python-mysqldb
sudo pip install ReviewBoard
File "/usr/lib/python2.7/distutils/command/build_ext.py", line 337, in run self.build_extensions()
File "/tmp/pip-build-84i3OO/Pillow/setup.py", line 512, in build_extensions' using --disable-%s, aborting' % (f, f))
ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting
* * *
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-84i3OO/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-5lU4Yb-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-84i3OO/Pillow/
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages
/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Are there any ideas why does it happen and how to solve it?
EDIT
Installed pillow (<https://discuss.erpnext.com/t/new-python-dependency-pillow-
if-you-get-error-during-update-see-this-post/7900>):
sudo apt-get install -y libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk
sudo pip install pillow
Now getting:
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 - Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/l ibffi -I/usr/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2 .7/c/_cffi_backend.o
c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory
#include <ffi.h>
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
* * *
Command "/usr/bin/python -u -c
"import setuptools, tokenize;__file__='/tmp/pip-build-hB90D2/cffi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-CCyW5e-record/install-record.txt --single-version-externally-managed --compile"
failed with error code 1 in /tmp/pip-build-hB90D2/cffi/
Answer: Have you tried to install `libffi-devel`
apt-get install libffi-dev
Sometime to fix pip issues its useful to install `build-essential` and
`python-dev`
apt-get install python-dev && apt-get install build-essential
Good luck!
|
Import working in console but not in pyCharm
Question: I had a python project with a lot of imports like:
from src.main.fr.some.module import someclass
and it was working good but my colleagues wanted the imports to be like:
from fr.some.module import someclass
Then I changed the `PYTHONPATH` in the `activate` script of my `virtualenv`
like:
export PYTHONPATH="/home/giffon/Documents/wopmars/src/main:/home/giffon/Documents/wopmars/src/test"
and replaced all the `src.main.fr.some.module` with `fr.some.module`.
Then I tried my code in the console and the output was good (note that I am
printing the `PYTHONPATH` at the beginning of my code and
`/home/giffon/Documents/wopmars/src/main` appears like expected).
(WopMars)giffon@CZC0507G5C-HP-Z400:~/Documents/wopmars/src/main/fr/tagc/wopmars/framework/parsing$ python3 Parser.py
PRINTING THE PYTHONPATH
/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/parsing
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/pyparsing-2.1.4-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/cycler-0.10.0-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/pytz-2016.4-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/python_dateutil-2.5.3-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/six-1.10.0-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/numpy-1.11.0-py3.4-linux-x86_64.egg
/home/giffon/Documents/wopmars/src/main
/home/giffon/Documents/wopmars/src/test
/home/giffon/virtualenvs/WopMars/lib/python3.4
/home/giffon/virtualenvs/WopMars/lib/python3.4/plat-x86_64-linux-gnu
/home/giffon/virtualenvs/WopMars/lib/python3.4/lib-dynload
/usr/lib/python3.4
/usr/lib/python3.4/plat-x86_64-linux-gnu
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages
Reading the definition file... -> done.
Checking whether the file is well formed... -> done.
Building the execution DAG... -> done.
Writing the dot file... -> done.
But, since I am working with pycharm, I wanted the IDE to take my changes into
account. And here comes the issues.
I read somewhere that I should modify the interpreter Python Path by doing the
following:
> File > Settings > Projet:wopmars > Projet Interpreter > "wheel" > More... >
> "Show path for the selected interpreter (WopMars interpreter selected)" > +
> > "Browse to /home/giffon/Documents/wopmars/src/main" > Ok > Ok > Apply > Ok
And then I execute the same code than above:
/home/giffon/virtualenvs/WopMars/bin/python3 /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/parsing/Parser.py
PRINTING THE PYTHONPATH
/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/parsing
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/pyparsing-2.1.4-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/cycler-0.10.0-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/pytz-2016.4-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/python_dateutil-2.5.3-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/six-1.10.0-py3.4.egg
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages/numpy-1.11.0-py3.4-linux-x86_64.egg
/home/giffon/Documents/wopmars/src/test
/home/giffon/Documents/wopmars/src/main
/home/giffon/virtualenvs/WopMars/lib/python3.4
/home/giffon/virtualenvs/WopMars/lib/python3.4/plat-x86_64-linux-gnu
/home/giffon/virtualenvs/WopMars/lib/python3.4/lib-dynload
/usr/lib/python3.4
/usr/lib/python3.4/plat-x86_64-linux-gnu
/home/giffon/virtualenvs/WopMars/lib/python3.4/site-packages
Traceback (most recent call last):
File "/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/parsing/Parser.py", line 12, in <module>
from fr.tagc.wopmars.framework.management.DAG import DAG
ImportError: No module named 'fr.tagc.wopmars.framework.management.DAG'
You probably noticed that the `/home/giffon/Documents/wopmars/src/main`
appears in the `PYTHONPATH` meaning that the configuration of pycharm
interpreter's path has been taken into account. So, the interpreter knows
where to find modules but can't see `fr`... any idea for solving this issue?
It is probably not interesting for solving this issue but the error-raising
code is:
print("PRINTING THE PYTHONPATH")
for p in sys.path:
print(p)
print("\n\n")
from fr.tagc.wopmars.framework.management.DAG import DAG
_Note: changing`PYTHONPATH` in `.profile` or `.bashrc` gave me the same
results_
_Note2: if I don't export PYTHONPATH, the console give me the same error than
pycharm_
Answer: I solved my issue thanks to Zulan's comment.
**TLDR:**
Put the `src/main/` directory before `src/test/` one in pycharm interpreter
`PYTHONPATH`.
* * *
Using the -v option for python interpreter in both pycharm and console, I have
got the following outputs:
Console output:
# /home/giffon/Documents/wopmars/src/main/fr/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/main/fr/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/main/fr/__pycache__/__init__.cpython-34.pyc'
import 'fr' # <_frozen_importlib.SourceFileLoader object at 0x7f384ce4b160>
# /home/giffon/Documents/wopmars/src/main/fr/tagc/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/main/fr/tagc/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/main/fr/tagc/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc' # <_frozen_importlib.SourceFileLoader object at 0x7f384ce4b358>
# /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc.wopmars' # <_frozen_importlib.SourceFileLoader object at 0x7f384ce4b400>
# /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc.wopmars.framework' # <_frozen_importlib.SourceFileLoader object at 0x7f384ce4b4a8>
# /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/management/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/management/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/management/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc.wopmars.framework.management' # <_frozen_importlib.SourceFileLoader object at 0x7f384ce4b550>
Pycharm output:
# /home/giffon/Documents/wopmars/src/test/fr/tagc/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/test/fr/tagc/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/test/fr/tagc/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc' # <_frozen_importlib.SourceFileLoader object at 0x7fb1532422e8>
# /home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc.wopmars' # <_frozen_importlib.SourceFileLoader object at 0x7fb153242390>
# /home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/framework/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/framework/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/framework/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc.wopmars.framework' # <_frozen_importlib.SourceFileLoader object at 0x7fb153242438>
# /home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/framework/management/__pycache__/__init__.cpython-34.pyc matches /home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/framework/management/__init__.py
# code object from '/home/giffon/Documents/wopmars/src/test/fr/tagc/wopmars/framework/management/__pycache__/__init__.cpython-34.pyc'
import 'fr.tagc.wopmars.framework.management' # <_frozen_importlib.SourceFileLoader object at 0x7fb1532424e0>
Traceback (most recent call last):
File "/home/giffon/Documents/wopmars/src/main/fr/tagc/wopmars/framework/parsing/Parser.py", line 12, in <module>
from fr.tagc.wopmars.framework.management.DAG import DAG
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked
ImportError: No module named 'fr.tagc.wopmars.framework.management.DAG'
You may have noticed the slight difference between the two output: console
interpreter search in `wopmars/src/main/` whereas pycharm interpreter search
in `wopmars/src/test/`.
Actually, if I look carefully at the printed `PYTHONPATH`, they are not the
same:
* In the console, `/home/giffon/Documents/wopmars/src/main` appears before `/home/giffon/Documents/wopmars/src/test` in the list `sys.path`
* In Pycharm, it's the opposite
Then, I put `/home/giffon/Documents/wopmars/src/test` **after**
`/home/giffon/Documents/wopmars/src/main` in pycharm and it worked perfectly.
I Think that python interpreter start finding the first part of the module
name in `src/test/` then he don't find the end and raise an error without
looking in other paths.
|
Sorting a list of IPv4Network and IPv6Network objects
Question: I have a list of IPv4 and IPv6 networks created with
[`ipaddress.ip_network()`](https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network),
which I want to sort (by family first, then value). What would be the best way
to do this? Apparently, a naive sort doesn't work:
>>> from ipaddress import ip_network
>>> L = [ip_network(x) for x in ['ff00::/8', 'fd00::/8', '172.16.0.0/12', '10.0.0.0/8']]
>>> L.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/ipaddress.py", line 652, in __lt__
self, other))
TypeError: 10.0.0.0/8 and fd00::/8 are not of the same version
Answer: Just use a [`key`
function](https://docs.python.org/3/library/stdtypes.html#list.sort) that
would allow to compare the values by type first, something like:
>>> from ipaddress import ip_network, IPv6Network
>>> L = [ip_network(x) for x in ['ff00::/8', 'fd00::/8', '172.16.0.0/12', '10.0.0.0/8']]
>>> L.sort(key=lambda x: (isinstance(x, IPv6Network), x))
>>> L
[IPv4Network('10.0.0.0/8'), IPv4Network('172.16.0.0/12'), IPv6Network('fd00::/8'), IPv6Network('ff00::/8')]
|
How do I use variables created in venv bash in my django app?
Question: If I create a variable in my venv like this
DJANGO_SERVER_TYPE=local
and on heroku I have
DJANGO_SERVER_TYPE=production
why won't my system recognize this
from .base import *
import os
if os.environ['DJANGO_SERVER_TYPE'] == 'local':
try:
from .local import *
except:
pass
if os.environ['DJANGO_SERVER_TYPE'] == 'production':
try:
from .production import *
except:
pass
I keep getting this error
File "/Users/ray/Desktop/myheroku/practice/src/gettingstarted/settings/__init__.py", line 3, in <module>
if os.environ['DJANGO_SERVER_TYPE'] == 'local':
File "/Users/ray/Desktop/myheroku/practice/bin/../lib/python3.5/os.py", line 683, in __getitem__
raise KeyError(key) from None
KeyError: 'DJANGO_SERVER_TYPE'
How do I use the local variable that I created?
Answer: The issue is that your environment variable does NOT exist locally. There are
a lot of ways to set environment variables locally.
I highly recommend using the
[autoenv](https://github.com/kennethreitz/autoenv) written by Kenneth Reitz.
This is a cool tool you can install locally on your computer. See [setting an
environment variable in
virtualenv](https://stackoverflow.com/questions/9554087/setting-an-
environment-variable-in-virtualenv) for more information.
The way it works is that you define a file called `.env` in your project
directory, and list all of your environment variables inside of it. For
instance:
export DJANGO_SERVER_TYPE=local
Everytime you enter that directory on the command line (like `cd
~/my_project`), autoenv will automatically set whatever environment variables
you've got in that folder as active. It's very useful.
Anyhow, wherever you're currently storing your environment variables, you'll
need to `export` them if you don't want to use something like autoenv.
So, let's say you've got a file (`env.sh`) that has your environment variables
defined in it like so:
DJANGO_SERVER_TYPE=local
You can 'run' this file by saying `sh env.sh`. Now, you might expect that this
would run, and you would now have `DJANGO_SERVER_TYPE` defined in your
environment variables, right?
Well, not exactly.
In `sh` (the scripting language you're actually using here), you need to put
the `export` keyword in front of a variable if you want the variable to be
exported OUTSIDE of the running script.
So, in order to actually set your variable, you would have to say:
export DJANGO_SERVER_TYPE=local
Then run that file as a script: `sh env.sh`. If you do that, you'll notice
that now your environment variable IS actually set.
Another useful thing to know while testing this out, is that if you run the
`env` command on the command line, it will output a list of all environment
variables currently set LOCALLY. This is useful for debugging, eg:
env | grep DJANGO_
|
How to find probability distribution and parameters for real data? (Python 3)
Question: I have a dataset from `sklearn` and I plotted the distribution of the
`load_diabetes.target` data (i.e. the values of the regression that the
`load_diabetes.data` are used to predict).
_I used this because it has the fewest number of variables/attributes of the
regression`sklearn.datasets`._
Using Python 3, **How can I get the distribution-type and parameters of the
distribution this most closely resembles?**
All I know the `target` values are all positive and skewed (positve skew/right
skew). . . Is there a way in Python to provide a few distributions and then
get the best fit for the `target` data/vector? OR, to actually suggest a fit
based on the data that's given? That would be realllllly useful for people who
have theoretical statistical knowledge but little experience with applying it
to "real data".
**Bonus** Would it make sense to use this type of approach to figure out what
your posterior distribution would be with "real data" ? If no, why not?
from sklearn.datasets import load_diabetes
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import pandas as pd
#Get Data
data = load_diabetes()
X, y_ = data.data, data.target
#Organize Data
SR_y = pd.Series(y_, name="y_ (Target Vector Distribution)")
#Plot Data
fig, ax = plt.subplots()
sns.distplot(SR_y, bins=25, color="g", ax=ax)
plt.show()
[](http://i.stack.imgur.com/ol9gk.png)
Answer: To the best of my knowledge, there is no automatic way of obtaining the
distribution type and parameters of a sample (as _inferring_ the distribution
of a sample is a statistical problem by itself).
In my opinion, the best you can do is:
(for each attribute)
* Try to fit each attribute to a reasonably large list of possible distributions (e.g. see [Fitting empirical distribution to theoretical ones with Scipy (Python)?](http://stackoverflow.com/questions/6620471/fitting-empirical-distribution-to-theoretical-ones-with-scipy-python?lq=1) for an example with Scipy)
* Evaluate all your fits and pick the best one. This can be done by performing a Kolmogorov-Smirnov test between your sample and each of the distributions of the fit (you have an implementation in Scipy, again), and picking the one that minimises D, the test statistic (a.k.a. the difference between the sample and the fit).
Bonus: It would make sense - as you'll be building a model on each of the
variables as you pick a fit for each one - although the goodness of your
prediction would depend on the quality of your data and the distributions you
are using for fitting. You are building a model, after all.
|
Python IRC ChatBot hangs on socket.recv after seemingly random time even though socket.settimeout is 8
Question: Hey so I decided to create an IRC ChatBot whose sole purpose it is to read
incoming messages from Twitch Chat and if a giveaway is recognized by a
keyword it's supposed to enter the giveaway by sending !enter in Chat.
I build the Bot upon this source: <https://github.com/BadNidalee/ChatBot>. I
only changed things in the Run.py so thats the only Code I'm going to post.
The unaltered ChatBot does work but it has no reconnect ability and regularly
stops receiving data because the socket closes or other reasons.
All I wanted to change was make it so that the ChatBot is stable and can just
stay in the IRC Chat constantly without disconnecting. I tried to achieve this
by setting a timeout of 8 seconds for my socket and catching timeout
exceptions that would occur and reconnect after they occur.
And all in all it does seem to work, my Bot does what it's supposed to even
when alot of messages are coming in, it recognizes when a Giveaway starts and
answers acordingly. IRC Server PING Messages are also handled and answered
correctly. If there is no message in Chat for over 8 seconds the Exception
gets thrown correctly and the Bot also reconnects correctly to IRC.
BUT heres my Problem: After seemingly random times the socket will literally
just Stop working. What I find strange is it will sometimes work for 20
minutes and sometimes for an hour. It doesn't occur when special events, like
lots of messages or something else happens in Chat, it really seems random. It
will not timeout there's just nothing happening anymore. If I cancel the
program with CTRL-C at this point the console sais the last call was
"readbuffer = s.recv(1024)" But why is it not throwing a timeout exception at
that point? If s.recv was called the socket should timeout if nothing is
received after 8 seconds but the program just stops and there is no more
output until you manually abort it.
Maybe I went about it the wrong way completely. I just want a stable 24/7-able
ChatBot that scans for one simple keyword and answers with one simple !enter.
This is also my first Time programming in Python so If I broke any conventions
or made any grave mistakes let me know.
The getUser Method returns the username of the line of chat that is scanned
currently.
The getMessage Method returns the message of the line of chat that is scanned.
The openSocket Method opens the Socket and sends JOIN NICK PASS etc to the IRC
#!/usr/bin/python
import string
import socket
import datetime
import time
from Read import getUser, getMessage
from Socket import openSocket, sendMessage
from Initialize import joinRoom
connected = False
readbuffer = ""
def connect():
print "Establishing Connection..."
irc = openSocket()
joinRoom(irc)
global connected
connected = True
irc.settimeout(8.0)
print "Connection Established!"
return irc
while True:
s = connect()
s.settimeout(8.0)
while connected:
try:
readbuffer = s.recv(1024)
temp = string.split(readbuffer, "\n")
readbuffer = temp.pop()
for line in temp:
if "PING" in line:
s.send(line.replace("PING", "PONG"))
timern = str(datetime.datetime.now().time())
timern = timern[0:8]
print timern + " PING received"
break
user = getUser(line)
message = getMessage(line)
timern = str(datetime.datetime.now().time())
timern = timern[0:8]
print timern +" " + user + ": " + message
if "*** NEW" in message:
sendMessage(s, "!enter")
break
except socket.timeout:
connected = False
print "Socket Timed Out, Connection closed!"
break
except socket.error:
connected = False
print "Socket Error, Connection closed!"
break
Answer: I think you've missunderstood how timeout work on the socket.
s.settimeout(8.0)
Will only set `s.connect(...)` to timeout if it can't reach the destination
host.
Further more, usually what you want to use instead if `s.setblocking(0)`
however this alone won't help you either (probably).
Instead what you want to use is:
import select
ready = select.select([s], [], [], timeout_in_seconds)
if ready[0]:
data = s.recv(1024)
What select does is check the buffer to see if any incoming data is available,
if there is you call `recv()` which in itself is a blocking operation. If
there's nothing in the buffer `select` will return empty and you should avoid
calling `recv()`.
If you're running everything on *Nix you're also better off using
[epoll](https://docs.python.org/3/library/select.html#select.epoll).
from select import epoll, EPOLLIN
poll = epoll()
poll.register(s.fileno(), EPOLLIN)
events = poll.poll(1) # 1 sec timeout
for fileno, event in events:
if event is EPOLLIN and fileno == s.fileno():
data = s.recv(1024)
This is a crude example of how epoll could be used.
But it's quite fun to play around with and you should [read more about
it](https://stackoverflow.com/questions/17355593/why-is-epoll-faster-than-
select)
|
Can you tell me why this web scraper isn't able to log in correctly?
Question: I'm trying to make a web scraper to get some information from the site
Colloquy.com, on which I have an account. I am having trouble getting my
scraper to log in to the site though. I'm using Python 2.7 with BeautifulSoup
and Requests.
[Here is a screenshot of my code](http://i.stack.imgur.com/hyFNE.png)
[and here is a screenshot of the relevant HTML for the
login](http://i.stack.imgur.com/G5Gah.png)
I've tried several variations of this code, including adding the authorization
key to the log-in info. However, no matter what I've tried, I always get the
"un-logged-in version" of the site when I get the HTML.
I have a suspicion that this has something to do with the site's use of
Javascript for the login (it uses a pop up box instead of a separate login
page). However, I don't know enough about Javascript to handle this properly,
and I haven't been able to find any sort of guide that's illuminating on this
particular issue.
So hopefully someone can tell me what is wrong with my code/process or where I
can find out how to deal with logins using Javascript.
Thanks! :)
Answer: Instead of attempting to scrape the login page where the javascript is, it
appears they `post` the information to
`https://colloquy.com/app/account/login`, so you could do something like the
following to try and login.
import requests
resp = requests.post("https://colloquy.com/app/account/login", data={"email":"[email protected]","password":"Password"})
You could then use the `resp.cookies` to scrape the pages that you are wanting
to get to.
cookies = resp.cookies
r = requests.get("https://colloquy.com/some-page", cookies=cookies)
# Get html etc
**Edit:** Usually in the case of a `login` page there will be a post action
behind the scenes that will send the required information to login. Usually
`username` and `password` etc. This can usually be found on Chrome using the
`Developer Tools` or Firefox with [Developer
Tools](https://developer.mozilla.org/en-US/docs/Tools) or
[Firebug](https://getfirebug.com/). In order to get where it will post the
information I bring up the tools and will then complete the login prompt.
Within the Network tab (Chrome--may vary for Firefox/Firebug) it will usually
show a request to some page (usually login or something similar) after you
have completed the login prompt/page and submitted your information. Clicking
on this action will allow you to see some of the information for this request
including the `Request Url` and `Request Method`. There will also be an area
which will show the `Form Data` posted to the `Request Url`. You should then
be able to use this information to make a similar `POST` to the `Request Url`
with the `Form Data`.
**Note:** There are cases where the web developer may attempt to block certain
[User-agents](http://www.useragentstring.com/pages/useragentstring.php) in
order to keep automated scripts and/or bots away, but you can usually just
change the `user-agent` to a normal agent to bypass this restriction.
requests.post(url, headers={"user-agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"})
|
How to use an existing Environment variable in subprocess.Popen()
Question: **Scenario**
In my python script I need to run an executable file as a subprocess with x
number of command line parameters which the executable is expecting.
Example:
* EG 1: myexec.sh param1 param2
* EG 2: myexec.sh param1 $MYPARAMVAL
The executable and parameters are not known as these are configured and
retrieved from external source (xml config) at run time.
My code is working when the parameter is a known value (EG 1) and configured,
however the expectation is that a parameter could be an environment variable
and configured as such, which should be interpreted at run time.(EG 2)
In the example below I am using echo as a substitute for myexec.sh to
demonstrate the scenario. This is simplified to demonstrate issue. 'cmdlst' is
built from a configuration file, which could be any script with any number of
parameters and values which could be a value or environment variable.
**test1.py**
import subprocess
import os
cmdlst = ['echo','param1','param2']
try:
proc = subprocess.Popen(cmdlst,stdout=subprocess.PIPE)
jobpid = proc.pid
stdout_value, stderr_value = proc.communicate()
except (OSError, subprocess.CalledProcessError) as err:
raise
print stdout_value
**RESULT TEST 1**
_python test1.py_
\--> param1 param2
**test2.py**
import subprocess
import os
cmdlst = ['echo','param1','$PARAM']
try:
proc = subprocess.Popen(cmdlst,stdout=subprocess.PIPE)
jobpid = proc.pid
stdout_value, stderr_value = proc.communicate()
except (OSError, subprocess.CalledProcessError) as err:
raise
print stdout_value
**RESULT TEST 2**
_export PARAM=param2_ _echo $PARAM_
\--> param2 _python test2.py_
\--> param1 $PARAM
I require Test 2 to produce the same result as Test 1, considering that $PARAM
would only be known at run-time and need to be retrieved from the current
environment.
I welcome your advice.
Answer: If you want to have the shell expand environment variables, you have to set
`shell=True`
subprocess.Popen('echo param1 $PARAM', shell=True, stdout=subprocess.PIPE)
Alternatively, you could just query the environment variable yourself when
constructing the command, and then there is no need for shell expansion
subprocess.Popen(['echo', 'param1', os.environ['PARAM']], stdout=subprocess.PIPE)
|
When using Oracle JDK 1.8.0_60 on two centos 7.1 systems one Jenkins slave fails to collect artifacts with NoClassDefFoundError
Question: Riddle me this:
How can two nearly identical jenkins slaves running with Oracle JDK 1.8 u60
Java have one fail to collect artifact with a classdef error while the other
is fine? In both case the following are identical
* system information shown from jenkins
* boot classpath
* jdk
* jdk files (these are deployed using SVN so we know they are identical)
* yum installed (mostly see below)
**Note** I can replicate this by going to script console and running the
following
import org.apache.tools.ant.Location
Location l = new Location()
works on the good and fails in same way as a real build on the bad.
**Error**
java.io.IOException: remote file operation failed:... at
hudson.remoting.Channel@35f2fb2:linengbld50: java.io.IOException:
Remote call on linengbld50 failed
...
Caused by: java.io.IOException: Remote call on linengbld50 failed
...
Caused by: java.lang.NoClassDefFoundError: Could not initialize class
org.apache.tools.ant.Location
...
**Yum difference**
Good v Bad
* hiera.noarch 1:1.3.4-5 vs 1.3.4-1
* net-snmp-* 1:5.7.2-24.el7_2.1 vs 1:5.7.2-24.el7
* ruby-augeas 0.5.0-1 vs 0.4.1-3
* zabbix 2.4.8 vs 2.4.7
Only ON Bad
* python-chardet.noarch 2.2.1-1.el7_1
* python-kitchen.noarch 1.1.1-5.el7
* lsof
* yum-utils.noarch 1.1.31-34.el
Answer: Using Script console was a great debugging tools as it executes in the right
environment. getting output of `which java` on each node showed a difference.
@mmasi found that bad showed a path whereas good returned null.
Even though we run slave using specific JDK java it used first java found on
path for its activities (archiving).
* modify alternatives to set java to 1.8 (centos)
sudo alternatives --install /usr/bin/java java \
/opt/tools/Java/jdk1.8.0_60/bin/java 1;java -version
* Disconnect and reconnect node (restart the slave)
* Repeat the tiny script console check _OK_
* Repeat Build test (tiny build that archives a file) _OK_
|
How to find the raw header of a website using python?
Question: I'm learning something about the website by myself. and I'm trying to fetch
the raw header followed by the 3-digit HTTP return code from a website. Here
is what I did so far:
import urllib.request
with urllib.request.urlopen('https://www.youtube.com/results?search_query=clippers+vs+lakers') as response:
html_text = response.read()
print(html_text)
It prints everything from the source. Then I use "Command + F" to search for
some key word like "raw header", but I cannot find something useful. Can
somebody help me get the raw header from the page source please? Is there some
library to do that? Thanks!
Answer: Try `response.info()` method to get the headers.
|
How to make statement `import datetime` bind the datetime type instead of the datetime module?
Question: After one too many times having accidentally typed `import datetime` when what
was really needed was `from datetime import datetime`, I wondered whether it
was possible to hack around and make the former do the latter.
That is, to recreate this behaviour (in a freshly opened interpreter session):
$ python -ic ''
>>> import datetime
>>> datetime(2016, 5, 27)
datetime.datetime(2016, 5, 27, 0, 0)
Came pretty close to faking a "callable module" below:
>>> import dt
>>> dt(2016, 5, 27)
datetime.datetime(2016, 5, 27, 0, 0)
Which was implemented like this:
# dt.py
import sys
import datetime
class CallableModule(object):
def __init__(self, thing):
self.thing = thing
def __call__(self, *args, **kwargs):
return self.thing.__call__(*args, **kwargs)
sys.modules['dt'] = CallableModule(datetime.datetime)
However it doesn't work if I try to use the filename `datetime.py` for the
module, and I could not yet find any hack to get at the built-in datetime
module when my own file was also called `datetime.py`.
How can we _temporarily unhide_ a built-in or site-packages module, from
within the shadowing module itself? Is there any indirect way to get at the
core `datetime` under this situation (perhaps similar to how we can still
access `sys.__stdout__` even when `sys.stdout` has been redirected)?
**Disclaimer** : In no way suggesting that this is a sane idea - just
interested if it's _possible_.
Answer: Here we go:
`datetime.py`:
import sys
import imp
import os
path = [p for p in sys.path if p != os.path.dirname(__file__)]
f, pathname, desc = imp.find_module('datetime', path)
std_datetime = imp.load_module('datetime', f, pathname, desc)
# if this^ is renamed to datetime, everything breaks!
f.close()
class CallableModule(object):
def __init__(self, module, fn):
self.module = module
self.fn = fn
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
def __getattr__(self, item):
try:
return getattr(self.fn, item)
except AttributeError:
return getattr(self.module, item)
sys.modules['datetime'] = CallableModule(std_datetime, std_datetime.datetime)
`test.py` (lives next to `datetime.py`):
import datetime
print(datetime(1, 2, 3))
print(datetime.timedelta(days=1))
print(datetime.now())
Run `test.py`, output:
0001-02-03 00:00:00
1 day, 0:00:00
2016-05-27 23:16:30.954270
It also works with `from datetime import datetime, timedelta` etc.
This is especially hacky and fragile and will depend on your distribution. For
example, apparently it doesn't work with IPython. You must import
`datetime.py` before the standard library module.
To understand just how weird things get with this, if the variable
`std_datetime` (the datetime module object) is renamed to `datetime`, then
`datetime.datetime` is no longer the class, but rather `datetime is
datetime.datetime is datetime.datetime.datetime ...`. If someone can explain
why this happens, I'd love to hear it.
(note that the first comment below is from before I got to the final version)
|
Converting a numpy.ndarray value from bytes to float
Question: I'm using numpy and Python 3.4 to read data from a .csv file.
Here is a sample of the CSV file:
"05/27/2016 09:45:37.816","187666432","7921470.8554087048","0","95.202655176457412","82.717061054954783","1.4626657999999999","158","5"
"05/27/2016 09:45:38.819","206884864","10692185.668858336","0","101.33018029563618","93.535551042125718","2.4649584999999998","158","5"
And here is my code sample used to extract data from the CSV above:
import os
import numpy as np
path = os.path.abspath('sample.csv')
csv_contents = np.genfromtxt(path, dtype=None, delimiter=',', autostrip=True, skip_header=0,
usecols=(1, 2, 3, 4, 5, 6, 7, 8))
num_cols = csv_contents.shape[1]
for x in np.nditer(csv_contents):
print('Original value: {0}'.format(x))
print('Decoded value: {0}'.format(x.tostring().decode('utf-8')))
val = x.tostring().decode('utf-8').replace('\x00', '').replace('"', '')
print('Without hex and ": {0}'.format(val))
try:
print('Float value:\t{0}\n'.format(float(val)))
except ValueError as e:
raise e
Sample output:
Original value: b'"187666432"'
Decoded value: "187666432"���������
Without hex and ": 187666432
Float value: 187666432.0
Original value: b'"7921470.8554087048"'
Decoded value: "7921470.8554087048"
Without hex and ": 7921470.8554087048
Float value: 7921470.855408705
Original value: b'"0"'
Decoded value: "0"�����������������
Without hex and ": 0
Float value: 0.0
In my `for` loop, to convert the `x` value to a float, I've had to do this:
val = x.tostring().decode('utf-8').replace('\x00', '').replace('"', '')
Which is not particularly elegant and prone to be faulty.
**Question 1:** Is there a better way to do this?
**Question 2:** Why does `x.tostring().decode('utf-8')` evaluate to something
like `"158"���������������` when dealing with integers? Where are the
hexadecimal coming from in `x.tostring()`?
Answer: To answer the first question:
I strongly recommend using [pandas to read in csv
files](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.read_csv.html):
In [11]: pd.read_csv(path, header=None)
Out[11]:
0 1 2 3 4 5 6 7 8
0 05/27/2016 09:45:37.816 187666432 7.921471e+06 0 95.202655 82.717061 1.462666 158 5
1 05/27/2016 09:45:38.819 206884864 1.069219e+07 0 101.330180 93.535551 2.464958 158 5
_It "sniffs out" whether you have quoted strings, an unquoted, though this can
be made explicit._
* * *
To answer the second question:
If you use flatten rather than nditer it doesn't add the `\x00`s (which make
the length of each string to length 20; the s20 dtype):
In [21]: a
Out[21]:
array([[b'"187666432"', b'"7921470.8554087048"', b'"0"',
b'"95.202655176457412"', b'"82.717061054954783"',
b'"1.4626657999999999"', b'"158"', b'"5"'],
[b'"206884864"', b'"10692185.668858336"', b'"0"',
b'"101.33018029563618"', b'"93.535551042125718"',
b'"2.4649584999999998"', b'"158"', b'"5"']],
dtype='|S20')
In [22]: [i.tostring() for i in np.nditer(a)]
Out[22]:
[b'"187666432"\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"7921470.8554087048"',
b'"0"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"95.202655176457412"',
b'"82.717061054954783"',
b'"1.4626657999999999"',
b'"158"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"5"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"206884864"\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"10692185.668858336"',
b'"0"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"101.33018029563618"',
b'"93.535551042125718"',
b'"2.4649584999999998"',
b'"158"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'"5"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00']
In [23]: [i.tostring() for i in a.flatten()]
Out[23]:
[b'"187666432"',
b'"7921470.8554087048"',
b'"0"',
b'"95.202655176457412"',
b'"82.717061054954783"',
b'"1.4626657999999999"',
b'"158"',
b'"5"',
b'"206884864"',
b'"10692185.668858336"',
b'"0"',
b'"101.33018029563618"',
b'"93.535551042125718"',
b'"2.4649584999999998"',
b'"158"',
b'"5"']
|
How to apply math operations to a row of a csv in python?
Question: I've been successful creating functions in python and reading/writing files.
However, I really need to apply certain functions to whole **rows** of data
(**not columns**) and can't find out anything about how to do this. The goals
are:
* Read a csv or txt file into python (can-do)
* Find a row of data and apply certain conditions and operations
* Do the same with a second row of data
* Then compare results from the rows to each other (done with a similarity function)
* Print the resulting data into a separate file (easy peasy)
Function parameters include "if/then" conditions for ratios, sums, and square
roots -- will not include whole function. For example, just use sum
Here's what I have so far (not much...):
import numpy as np
data = np.genfromtxt ('file_to_read.csv',
dtype=float,
delimiter=",",
names=True)
np.sum()
print(data)
np.savetxt('test.csv', data, delimiter=',')
file_to_read.csv is this:
0,2,1
0,2,2
0,2,3
0,1,0
0,2,0
0,3,0
1,0,0
2,0,0
3,0,0
Answer: you can transpose your matrix or data frame (if using pandas) and work with
columns.
Example (pandas):
Original DF
In [162]: df
Out[162]:
a b c
0 0 2 1
1 0 2 2
2 0 2 3
3 0 1 0
4 0 2 0
5 0 3 0
6 1 0 0
7 2 0 0
8 3 0 0
Transposed DF
In [163]: df.T
Out[163]:
0 1 2 3 4 5 6 7 8
a 0 0 0 0 0 0 1 2 3
b 2 2 2 1 2 3 0 0 0
c 1 2 3 0 0 0 0 0 0
Select rows where `b>0` and `c>1`:
In [166]: df[(df.b>0) & (df.c>1)]
Out[166]:
a b c
1 0 2 2
2 0 2 3
now calculate sum of cells for each found row:
In [167]: df[(df.b>0) & (df.c>1)].sum(axis=1)
Out[167]:
1 4
2 5
dtype: int64
or product:
In [169]: df[(df.b>0) & (df.c>1)].product(axis=1)
Out[169]:
1 0
2 0
dtype: int64
PS using `axis=1` instructs Pandas/Numpy to use rows instead of columns
|
Why am I getting an out of index error on my matrix?
Question: I'm currently trying to make code for a game, the game is a lot like checkers.
I'm representing my board as a 10 x 10 matrix. There exist two ways of moving
in this game, you can do a step where you check all the positions adjacent to
you and if any of them is empty you can move into them. Then if the position
right next to you is occupied but the space right next to that space is empty
you can hop on top of the player occupying said spot. So far I have three
important pieces of code to finish my game. My first piece of code is the
board, the second piece of code is two variables each one contains a list of
the coordinates of each player's chips and the third part is two functions,
one that allows me to hop and the other one that allows me to do steps.
This is my code:
import numpy as np
matrix = np.array([[1,1,1,1,1,0,0,0,0,0], #0 this is the board, it's represented by a 10x10 matrix
[1,1,1,1,0,0,0,0,0,0], #1 the 0s represent empty spaces
[1,1,1,0,0,0,0,0,0,0], #2 the 1s represent player 1's chips
[1,1,0,0,0,0,0,0,0,0], #3 the 2s represetn player 2's chips
[1,0,0,0,0,0,0,0,0,0], #4
[0,0,0,0,0,0,0,0,0,2], #5
[0,0,0,0,0,0,0,0,2,2], #6
[0,0,0,0,0,0,0,2,2,2], #7
[0,0,0,0,0,0,2,2,2,2], #8
[0,0,0,0,0,2,2,2,2,2]]) #9
chips1 = list(tuple(map(tuple,np.fliplr(np.argwhere(matrix == 1))))) #Finds all the positions that contain a 1
chips2 = list(tuple(map(tuple,np.fliplr(np.argwhere(matrix == 2))))) #Finds all the positions that contain a 2
print chips2
def step(x,y): #Finds the possible steps for a checker
listMoves = []
if x > 0 and matrix[x-1][y] == 0: #left
listMoves.append([x-1,y])
if x < 9 and matrix[x+1][y] == 0: #right
listMoves.append([x+1,y])
if y < 9: #up
if matrix[x][y+1] == 0:
listMoves.append([x,y+1])
if x>0 and matrix[x-1][y+1] == 0: #up + left
listMoves.append([x-1,y+1])
if x < 9 and matrix[x+1][y+1] == 0: #up + right
listMoves.append([x+1,y+1])
if y > 0: #down
if matrix[x][y-1] == 0:
listMoves.append([x,y-1])
if x > 0 and matrix[x-1][y-1] == 0: #down + left
listMoves.append([x-1,y-1])
if x<9 and matrix[x+1][y-1] == 0:
listMoves.append([x+1,y-1])
return listMoves
def hopper(x,y): #Finds the possible hops for a checker
listHops = []
if x > 1 and matrix[x-1][y] != 0 and matrix[x-2][y] == 0: #left
listHops.append([x-2,y])
if x < 8 and matrix[x+1][y] != 0 and matrix[x+2][y] == 0: #right
listHops.append([x+2,y])
if y > 1:
if matrix[x][y-1] != 0 and matrix[x][y-2] == 0: #down
listHops.append([x,y-2])
if x>1 and matrix[x-1][y-1] != 0 and matrix[x-2][y-2] == 0: #down + left
listHops.append([x-2,y-2])
if x < 8 and matrix[x+1][y+1] != 0 and matrix[x+2][y-2] == 0: #up + right
listHops.append([x+2,y-2])
if y < 8:
if matrix[x][y+1] != 0 and matrix[x][y+2] == 0: #up
listHops.append([x,y+2])
if x > 1 and matrix[x-1][y+1] != 0 and matrix[x-2][y+2] == 0: #up + left
listHops.append([x-2,y+2])
if x < 8 and matrix[x+1][y+1] != 0 and matrix[x+2][y+2] == 0: #up + right
listHops.append([x+2,y+2])
listHops = listHops + step(x,y)
return listHops
'''
def flipBoard():
global matrix
matrix = np.fliplr(np.flipud(matrix))
return matrix.tolist()
flipBoard()
'''
for i in range(0,len(chips2)): #loops through the list of positions to find all the possible steps and hops for
print hopper(chips2[i][0], chips2[i][1])#every single checker on the board
print matrix
The for loop is used to go through the list of all my chips and find all the
possible moves for all the chips. When I do this with the 1 chips which are at
the top left of the board it returns all the possible plays, which are 32 if
that's of any use. However when I run this same function with the 2 chips I
get the following error:
Traceback (most recent call last):
File "<ipython-input-21-3429014a2777>", line 80, in <module>
print hopper(chips2[i][0], chips2[i][1])#every single checker on the board
File "<ipython-input-21-3429014a2777>", line 59, in hopper
if x < 8 and matrix[x+1][y+1] != 0 and matrix[x+2][y-2] == 0: #up + right
IndexError: index 10 is out of bounds for axis 0 with size 10
So far I have managed to find out it only happens with hops and it only
happens when you're trying to hop to the right. I've tried changing it to x <
7 and x <=8 and it's still not working. On the left side it works perfectly
fine. Does anyone have any clue as to why this is happening? It's obviously a
logic problem on my side but I'm out of ideas as to how I can fix it.
Answer: You should print values of `x` and `y` in your `hopper` function. Since
`chips2` contains indices in the matrix with value 2, then the index `[9][9]`
will be contained in `chips2` implying `x = 9` or `y = 9` at some point.
Therefore `matrix[x+1][y+1]` would mean `matrix[10][10]` which does not exist.
You should review your code.
you should do:
if x < 8:
if matrix[x+1][y+1] != 0 and matrix[x+2][y-2] == 0: #up + right
. . .
In that way, you don't perform a check on an index that is out of range
|
Traceback(most recent call last): error
Question: I'm new to python and I'm writing a practice script that generates a random
number between 1 and 20, asks you to guess the number until you get it right
and then prints the amount of guesses once you get it right. The code all
works until I get the last number then I get this error:
Traceback (most recent call last):
File "C:\Users\James Brown\Desktop\guessnumber.py", line 20, in <module>
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 18, in guess
print("Good job! You guessed my number in " + tries)
TypeError: Can't convert 'int' object to str implicitly
Heres the code
import random
number = random.randint(1,20)
tries = 0
print ("I am thinking of a number between 1 and 20")
def guess():
print (number)
global tries
myGuess = int(input("Take a guess. "))
while (myGuess != number):
if (myGuess > number):
print ("Your guess is too high.")
else:
print ("Your guess is too low.")
tries = tries+1
guess()
print("Good job! You guessed my number in " + tries)
guess()
Can someone explain whats going on and how to prevent this? Thanks!
Answer: You need to convert your `int tries` to a string:
str(tries)
New code:
import random
number = random.randint(1,20)
tries = 0
print ("I am thinking of a number between 1 and 20")
def guess():
print (number)
global tries
myGuess = int(input("Take a guess. "))
while (myGuess != number):
if (myGuess > number):
print ("Your guess is too high.")
else:
print ("Your guess is too low.")
tries = tries+1
guess()
print("Good job! You guessed my number in " + str(tries))
guess()
**EDIT** As mentioned in the comments, this also works. The `print` function
will convert to you implicit.
print("Good job! You guessed my number in " , tries)
|
Python - Retrieve and replace based on a regex
Question: Basically I've imported a csv of about 17000 rows into a pandas dataframe.
There is a date column that has been imported as `int64` because data quality
is very poor. Examples of dates include `11969`, `12132001`, `1022013`, etc.
So I figure what I want to do is retrieve just the last 4 numbers from the
date column.
So the code I've used is:
test_str = str(df['Date'])
flags = re.MULTILINE
p = r'\d{4}$'
result = re.findall(p, test_str, flags)
When I `print(result)` only 60 of the 17000 values are returned. I'm assuming
it only assess uniques, but after a long bout of googling I can't figure it
out. Any ideas on how I can work around this?
Answer: It seems like your method actually does work (at least for the examples you
gave):
import pandas as pd
rng = pd.Series([11969, 12132001, 1022013, 1022013])
test_str = str(rng)
flags = re.MULTILINE
p = r'\d{4}$'
result = re.findall(p, test_str, flags)
print(result)
# ['1969', '2001', '2013', '2013'] # not just unique values
But this method of converting a `pandas` series into a string is a bizarre way
of doing it and doesn't take advantage of `pandas` inherent structure.
You might consider doing this:
df['year_int'] = df['Date'] % 10000
to get the last four digits if `df['Date']` is `int64`. Or this:
df['year_str'] = df['Date'].apply(lambda x: str(x)[-4:])
if you'd rather convert to a string and then take the last four characters.
print(df)
# Date year_int year_str
# 0 11969 1969 1969
# 1 12132001 2001 2001
# 2 1022013 2013 2013
# 3 1022013 2013 2013
|
Python find index of all dates between two dates
Question: I am trying to implement equivalent of `numpy.where` for dates as follows:
from datetime import date, timedelta as td, datetime
d1 = datetime.strptime('1/1/1995', "%m/%d/%Y")
d2 = datetime.strptime('12/31/2015', "%m/%d/%Y")
AllDays = []
while(d1<=d2):
AllDays.append(d1)
d1 = d1 + td(days=1)
validDate = AllDays
trainStDt = '1/1/1995'
trainEnDt = '12/31/2013'
testStDt = '1/1/2014'
testEnDt = '12/31/2015'
indTrain = (validDate >= datetime.strptime(trainStDt,'%m/%d/%Y')) & (validDate <=
datetime.strptime(trainEnDt,'%m/%d/%Y'))
indTest = (validDate >= datetime.strptime(testStDt,'%m/%d/%Y')) & (validDate <=
datetime.strptime(testEnDt,'%m/%d/%Y'))
trainDates = validDate[indTrain]
testDates = validDate[indTest]
print trainDates[0]
print trainDates[-1:]
print testDates[0]
print testDates[-1:]
However: (1) indTrain doesn't work as it is trying to compare list to datetime
(2) my solution is to loop through each element of validDates
Is there a better way to do it?
Answer: Just turn your list into an array. Add `import numpy as np` to the top of your
script, and after your `while` loop, add:
AllDays = np.array(AllDays)
|
Attribute system similar to HTTP Headers for local files
Question: I am in the process of writing a program and need some guidance. Essentially,
I am trying to determine if a file has some marker or flag attached to it.
Sort of like the attributes for a HTTP Header.
If such a marker exists, that file will be manipulated in some way (moved to
another directory).
My question is: Where exactly should I be storing this flag/marker? Do files
have a system similar to HTTP Headers? I don't want to access or manipulate
the contents of the file, just some kind of property of the file that can be
edited without corrupting the actual file--and it must be rather universal
among file types as my potential domain of file types is unbound. I have some
experience with Web APIs so I am familiar with HTTP Headers and json. Does any
similar system exist for local files in windows? I am especially interested in
anyone who has professional/industry knowledge of common techniques that
programmers use when trying to store 'meta data' in files in order to access
them later. Or if anyone knows of where to point me, as I am unsure to what I
should be researching.
For the record, I am going to write a program for Windows probably using
Golang or Python. And the files I am going to manipulate will be potentially
all common ones (.docx, .txt, .pdf, etc.)
Thanks in advanced!
Answer: Metadata you wish to add is best kept in a separate file or database for all
files.
Or in another file with same name and different extension or prefix, that you
can make hidden.
Relying on a file system is very tricky and your data will be bound by the
restrictions and capabilities of the file system your file is stored on. And,
you cannot count on your data remaining intact as any application may wish to
change these flags.
And some of those have very specific, clearly defined use, such as creation
time, modification time, access time...
See, if you need only flagging the document, you may wish to use creation
time, which will stay unchanged through out the live of this document (until
is copied) to store your flags. :D
Very dirty business, unprofessional, unreliable and all that.
But it's a solution. Poor one, but exists.
I do not know that FAT32 or NTFS file systems support any extra bits for
flagging except those already used by the OS. Unixes EXT family FS's do
support some extra bits. And even than you should be careful in case some
other important application makes use of them for something.
Mac OS may support some metadata by itself, but I am not 100% sure.
On Windows, you have one more option to associate more data with a file, but I
wouldn't use that as well.
Well, NTFS file system (FAT doesn't support that) has a feature called
streams.
In essential, same file can have multiple data streams under itself. I.e. You have more than one file contents under same file node.
To be more clear. Same file contains two different files.
When you open the file normally only main stream is visible to the
application. Applications must check whether the other streams are present and
choose the one they want to follow.
So, you may choose to store metadata under the second stream of the file.
But, what if all streams are taken?
Even more, anti-virus programs may prevent you access to the metadata out of
paranoya, or at least ask for a permission. I don't know why MS included that
option, probably for file duplication or something, but bad hackers made use
of the fact that you can store some data, under existing regular file, that
nobody is aware of.
Imagine a virus writing it's copy into another stream of one of programs
already there.
All that is needed for it to start, instead of your old program next time you
run it is a batch script added to task scheduler that flips two streams making
the virus data the main one.
Nasty trick! So when this feature started to be abused, anti-virus software
started restricting files with multiple streams, so it's like this feature
doesn't exist.
If you want to add some metadata using OS's technology, use Windows registry,
but even that is unwise.
What to tell you? Don't add metadata to files, organize a separate file, or
index your data in special files with same name as the file you are refering
to and in same folder.
|
How to read some contents of xml files and write them into a text file?
Question: I have a following xml file, I want to read the contents in `<seg>` and save
them into a plain text file with Python. And I used the DOM module.
<?xml version="1.0"?>
<mteval>
<tstset setid="default" srclang="any" trglang="TRGLANG" sysid="SYSID">
<doc docid="ntpmt-dev-2000/even1k.cn.seg.txt">
<seg id="1">therefore , can be obtained having excellent properties ( good stability and solubility of the balance of the crystal as a pharmaceutical compound is not possible to predict .</seg>
<seg id="3">compound ( I ) are preferably crystalline , in particular , has good stability and solubility equilibrium and suitable for industrial prepared type A crystal is preferred .</seg>
<seg id="4">method B included in the catalyst such as DMF , and the like in the presence of a compound of formula ( II ) with thionyl chloride or oxalyl chloride to give an acyl chloride , in the presence of a base of the acid chloride with alcohol ( IV ) ( O ) by reaction of esterification .</seg>
</doc>
</tstset>
</mteval>
from xml.dom.minidom import parse
import xml.dom.minidom
dom = xml.dom.minidom.parse(r"path_to_xml file")
file = dom.documentElement
seg = dom.getElementsByTagName("seg")
for item in seg:
sent = item.firstChild.data
print(sent,sep='')
file = open(r'file.txt','w')
file.write(sent)
file.close()
while running above codes, it print all the lines on the screen successfully,
but the file.txt only has one line of last `<seg>` (seg id=4), actually I want
to save all the sentences into the file. Is there something wrong with my
codes?
Answer: You're only calling `file.write(sent)` once, open the file before the loop,
and then add the following line to this code:
file = open(r'file.txt','w')
for item in seg:
sent = item.firstChild.data
print(sent,sep='')
file.write(sent) // <---- this line
file.close()
|
Why simple import of module in same directory is not allowed
Question: I've created two modules in the same directory:
.
├── mod1.py
├── mod2.py
There is no `__init__.py`, I don't want to create this as a package, I'm just
creating a simple script which I have modularized by breaking into different
modules.
My intention is to run `mod1.py` using `python mod1.py`
~/junk/imports$ cat mod1.py
from . import mod2
print(mod2.some_expr)
$ cat mod2.py
some_expr = 'hello world!'
Although I know that directly using `import mod1` will work, but I'm
deliberately not using it so that my module name doesn't clash with built in
modules (which I felt is a good practice)
I'm getting the following errors with `python2` and `python3`
~/junk/imports$ python3 --version
Python 3.4.3
kartik@kartik-lappy:~/junk/imports$ python3 mod1.py
Traceback (most recent call last):
File "mod1.py", line 1, in <module>
from . import mod2
SystemError: Parent module '' not loaded, cannot perform relative import
~/junk/imports$ python2 --version
Python 2.7.11
~/junk/imports$ python2 mod1.py
Traceback (most recent call last):
File "mod1.py", line 1, in <module>
from . import mod2
ValueError: Attempted relative import in non-package
Most of the questions like this on StackOverflow deal with packages, but I'm
not using packages. I just want to run it as a simple script.
My question is not about how to do it, but I want to know the reason behind
the above not working.
Answer: You shouldn't use relative, but absolute import:
import mod2
print(mod2.some_expr)
The [documentation](https://docs.python.org/3/reference/import.html) is pretty
good, and this [SO answers](http://stackoverflow.com/a/2349998/3077939) gives
an alternative using `importlib`.
If a handmade module clash with a builtin module, the proper way to go is
probably to rename it, eventually through addition of a {pre,suf}fix. Another
is to use `importlib`.
The motivation underlying these limitation can be found in the [PEP
328](https://www.python.org/dev/peps/pep-0328/#rationale-for-relative-
imports), and comes mainly from BDFL preferences, over all other solutions.
|
Tensorflow crashes when using sess.run()
Question: I'm using tensorflow 0.8.0 with Python v2.7. My IDE is PyCharm and my os is
Linux Ubuntu 14.04
I'm noticing that the following code causes my computer to freeze and/or
crash:
# you will need these files!
# https://www.kaggle.com/c/digit-recognizer/download/train.csv
# https://www.kaggle.com/c/digit-recognizer/download/test.csv
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# read in the image data from the csv file
# the format is: imagelabel pixel0 pixel1 ... pixel783 (there are 42,000 rows like this)
data = pd.read_csv('../train.csv')
labels = data.iloc[:,:1].values.ravel() # shape = (42000, 1)
labels_count = np.unique(labels).shape[0] # = 10
images = data.iloc[:,1:].values # shape = (42000, 784)
images = images.astype(np.float64)
image_size = images.shape[1]
image_width = image_height = np.sqrt(image_size).astype(np.int32) # since these images are sqaure... hieght = width
# turn all the gray-pixel image-values into percentages of 255
# a 1.0 means a pixel is 100% black, and 0.0 would be a pixel that is 0% black (or white)
images = np.multiply(images, 1.0/255)
# create oneHot vectors from the label #s
oneHots = tf.one_hot(labels, labels_count, 1, 0) #shape = (42000, 10)
#split up the training data even more (into validation and train subsets)
VALIDATION_SIZE = 3167
validationImages = images[:VALIDATION_SIZE]
validationLabels = labels[:VALIDATION_SIZE]
trainImages = images[VALIDATION_SIZE:]
trainLabels = labels[VALIDATION_SIZE:]
# ------------- Building the NN -----------------
# set up our weights (or kernals?) and biases for each pixel
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(.1, shape=shape, dtype=tf.float32)
return tf.Variable(initial)
# convolution
def conv2d(x, W):
return tf.nn.conv2d(x, W, [1,1,1,1], 'SAME')
# pooling
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# placeholder variables
# images
x = tf.placeholder('float', shape=[None, image_size])
# labels
y_ = tf.placeholder('float', shape=[None, labels_count])
# first convolutional layer
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
# turn shape(40000,784) into (40000,28,28,1)
image = tf.reshape(trainImages, [-1,image_width , image_height,1])
image = tf.cast(image, tf.float32)
# print (image.get_shape()) # =>(40000,28,28,1)
h_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)
# print (h_conv1.get_shape()) # => (40000, 28, 28, 32)
h_pool1 = max_pool_2x2(h_conv1)
# print (h_pool1.get_shape()) # => (40000, 14, 14, 32)
# second convolutional layer
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
#print (h_conv2.get_shape()) # => (40000, 14,14, 64)
h_pool2 = max_pool_2x2(h_conv2)
#print (h_pool2.get_shape()) # => (40000, 7, 7, 64)
# densely connected layer
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
# (40000, 7, 7, 64) => (40000, 3136)
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
#print (h_fc1.get_shape()) # => (40000, 1024)
# dropout
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
print h_fc1_drop.get_shape()
#readout layer for deep neural net
W_fc2 = weight_variable([1024,labels_count])
b_fc2 = bias_variable([labels_count])
print b_fc2.get_shape()
mull= tf.matmul(h_fc1_drop, W_fc2)
print mull.get_shape()
print
mull2 = mull + b_fc2
print mull2.get_shape()
y = tf.nn.softmax(mull2)
# dropout
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
sess = tf.Session()
sess.run(tf.initialize_all_variables())
print sess.run(mull[0,2])
The lase line causes the crash:
print sess.run(mull[0,2])
This is basically one location in a very big 2d array. Something about the
sess.run is causing it. I'm also getting a script issue popup... some sort of
google script (think maybe it's tensorflow?). I can't copy the link because my
computer is completely frozen.
Answer: I suspect the problem arises because `mull[0, 2]`--despite its small apparent
size--depends on a very large computation, including multiple convolutions,
max-poolings, and a large matrix multiplication; and therefore either your
computer becomes fully loaded for a long period of time, or it runs out of
memory. (You should be able to tell which by running `top` and checking what
resources are used by the `python` process in which you are running
TensorFlow.)
The amount of computation is so large because your TensorFlow graph is defined
in terms of the entire training dataset, `trainImages`, which contains 40000
images:
image = tf.reshape(trainImages, [-1,image_width , image_height,1])
image = tf.cast(image, tf.float32)
Instead, it would be more efficient to define your network in terms of a
`tf.placeholder()` to which you can _feed_ individual training examples, or
mini-batches of examples. See the [documentation on
feeding](https://www.tensorflow.org/versions/r0.8/how_tos/reading_data/index.html#feeding)
for more information. In particular, since you are only interested in the 0th
row of `mull`, you only need to feed the 0th example from `trainImages` and
perform computation on it to produce the necessary values. (In your current
program, the results for all other examples are also being computed, and then
discarded in the final slice operator.)
|
How to make a correct HTTP Post request with Meteor.js to Domino Datalab's Rest API
Question: In my server side Meteor.js method, I'm trying to correctly make a request to
Domino Data Lab's (DDL) Rest API.
DDL provides a platform for makes it possible to call a data science model via
a REST API. Their documentation on this API is here:
<http://support.dominodatalab.com/hc/en-us/articles/204173149-API-Endpoints-
Model-Deployment>
But, I doubt the documentation is helpful because I think an experienced
Meteor developer will see the request examples in CURL or Python and know how
to get the params correctly into the JSON format that DDL is looking for.
Domino Datalab provides the instructions for 4 methods, but not for Meteor.js.
I'll post the examples for Curl and Python:
**Examples**
_CURL Request_
curl -v -X POST \
https://app.dominodatalab.com/MYURL \
-H 'Content-Type: application/json' \
-H 'X-Domino-Api-Key: YOUR_API_KEY' \
-d '{"parameters": [ "FOO", "BAR", "ETC"]}'
_Python Request_
import requests
response =
requests.post("https://app.dominodatalab.com/MYURL",
headers = {
"X-Domino-Api-Key": "YOUR_API_KEY",
"Content-Type": "application/json"
},
json = {
"parameters": ["FOO", "BAR", "ETC"]
}
)
print(response.status_code)
print(response.headers)
print(response.json())
I've tried a few different ways (using both the `data`and `params`options)
based on the documentation for Meteor, but here is my best try:
Meteor.methods({
score_app: function(){
var test = HTTP.call("POST", "https://app.dominodatalab.com/MYURL",
{ headers: {
"Content-Type": "application/json",
"X-Domino-Api-Key": "YOUR_API_KEY"
},
// This is where the problem is. Have tried multiple syntax versions and tried using the `params`options for the HTTP call instead of `data`
data: {'params': [143]
}
},
function (error, result) {
// The syntax below should be if not an error, log the result (for testing etc, otherwise, log "http post error". I may have incorrectly switched this around, but the original version I got from an online example had it the console.log statements in the reverse order.
if (!error) {
console.log(result);
} else{
console.log("http post error");
};
});
}
});
I've been using this entry in the Meteor documentation to send the parameters
as a JSON object correctly: <http://docs.meteor.com/api/http.html>
The connection to Data Domino Lab (DDL) is made correctly, but it doesn't
recognize the parameters correctly because the request is not sending the
parameters in the JSON format that DDL wants.
result: 'You must provide a JSON object in your request body
with a parameters key containing an array of parameters.' } }
I'm on the DDL free plan, but I will email a link to this question to their
tech support. This is a niche issue, but it could be important to Meteor.js
developers in the future wishing to link to a data science model in DDL.
Answer: I'm one of the engineers at Domino who has worked on the API Endpoints feature
recently. The error message you're getting means that the JSON object you're
sending to our server doesn't contain the key "parameters". I'm not an expert
in Meteor, but it looks like you're using "params" where you should use
"parameters" in your JSON payload. Around line 9 can you change...
{'data': {'params': [143]}}
to
{'data': {'parameters': [143]}}
If my understanding of your code is correct, that'll work correctly.
Cheers!
|
'utf-8' codec can't decode byte 0x80 in position 0
Question: Ok when i'm in django I can run the website by the following command.
`sudo python manage.py runserver`
But when I try and use the greed arrow for running the project is gives me
like a dozen errors.
This happens straight away when i set up the project and was hoping if anyone
could help.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10484fbf8>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 22, in ready
self.module.autodiscover()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/admin.py", line 7, in <module>
from django.contrib.auth.forms import (
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/forms.py", line 264, in <module>
class SetPasswordForm(forms.Form):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/forms.py", line 275, in SetPasswordForm
help_text=password_validation.password_validators_help_text_html())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/password_validation.py", line 85, in password_validators_help_text_html
help_texts = password_validators_help_texts(password_validators)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/password_validation.py", line 74, in password_validators_help_texts
password_validators = get_default_password_validators()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/password_validation.py", line 21, in get_default_password_validators
return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/password_validation.py", line 32, in get_password_validators
validators.append(klass(**validator.get('OPTIONS', {})))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/password_validation.py", line 170, in __init__
common_passwords_lines = gzip.open(password_list_path).read().decode('utf-8').splitlines()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
I know…
Answer: I was getting a similar error for a different issue, but it turned out that it
was a problem with the way PyCharm handled Unicode/UTF-8 with Python 3. I
ended up doing the following to get the error to go away.
Add following line in the file "pycharm.exe.vmoptions":
-Dfile.encoding=UTF-8
> Source: [Why unicode string is not shown on PyCharm's
> console?](http://stackoverflow.com/questions/33512828/why-unicode-string-is-
> not-shown-on-pycharms-console)
Hope this helps!
|
User Defined Array formulas in DataNitro
Question: I have created a python function to exponentiate a matrix and imported it as a
user defined function in Excel using DataNitro. However, when I use this
formula I get the result as a python list in one cell.
Is it possible to create array formulas for excel using DataNitro similar in
lines to MMULT or MINVERSE?
Below is my python code and a snapshot of the excel sheet:
> functions.py
import numpy as np
def mat_expo(x,n):
if(n==2):
return mat_mult(x,x)
else:
return mat_mult(x,mat_expo(x,n-1))
def mat_mult(x,y):
return np.dot(x,y)
> Excel Sheet:
[my excel sheet](http://i.stack.imgur.com/oL0nW.jpg)
Answer: There's no way to return to multiple cells from one DataNitro function. You
can get the same result as follows:
def mat_expo_entry(x, n, i, j):
return mat_expo(x, n)[i][j]
Use `=mat_expo_entry($B$2:$D$4,3,ROW()-7,COLUMN()-2)` in your sample
spreadsheet in cells `B7:D9` to print the output correctly.
If this is slow, you can store the answer using Python's built-in lru cache:
from functools32 import lru_cache # use 'functools' in Python3
@lru_cache
def mat_expo(x,n):
if(n==2):
return mat_mult(x,x)
else:
return mat_mult(x,mat_expo(x,n-1))
Alternatively, you could use a DataNitro script to print the result directly
to the sheet.
|
Error importing numpy & graphlab after installing ipython
Question: I have got a strange issue.
I am now using graphlab/numpy to develop a project via Pycharm 5. OS is Mac OS
10.11.5. I created a p2.7 virtual environment for the project. Programme runs
well. But after I install ipython, I can no longer import graphlab and numpy
correctly.
Error message:
> AttributeError: 'module' object has no attribute 'core'
System keeps telling that attribute ‘core' and 'connect' are missing. But I am
pretty sure that they can be found in graphlab/numpy folders, and no
duplicates.
Project runs all right in terminal. Now I have to uninstall ipython. Then
everything is ok again.
Please kindly help.
Answer: Please remember that console applications and GUI application do not share the
same environment on OS X.
This also means that if you install a Python package from the console, this
would probably not be visible to PyCharm.
Usually you need to install packages using PyCharm in order to be able to use
them.
|
Django ) Postgresql model ERROR
Question: In models.py in my app of django, I have a model below :
from django.db import models
from django.contrib.postgres.fields import *
class lkmModel(models.Model):
#Profile Image
profileUrls = ArrayField(base_field=models.TextField,size=5)
#profileUrls = models.TextField()
"""profileUrl2 = models.TextField()
profileUrl3 = models.TextField()
profileUrl4 = models.TextField()
profileUrl5 = models.TextField()"""
#Profile Basic
name = models.CharField(max_length=20)
status = models.CharField(max_length=20)
age = models.IntegerField()
residence = models.CharField(max_length=20)
bloodType = models.CharField(max_length=20)
religion = models.CharField(max_length=20)
#KEY_WORD
personaltiy = models.TextField()
appearance = models.TextField()
hobby = models.TextField()
ability = models.TextField()
idealType = models.TextField()
career = models.TextField()
best = models.TextField()
badges = ArrayField(base_field=models.CharField(max_length=10))
manual = models.TextField()
def __str__(self):
return self.name
I'm trying to create an instance of lkmModel in models.py at lkm.py
Correspondent codes of lkm.py are below :
from myApp.models import lkmModel
def createModel(self,pictures,basics,keywords,badges,manual):
lkmModelOne = lkmModel(profileUrls = pictures, name = basics[0] , status = basics[1] ,
bloodType = basics[2] , age = basics[3] , religion = basics[4] , residence = basics[5],
personality= keywords[0], appearance = keywords[1] , hobby = keywords[2] , ability = keywords[3],
idealType = keywords[4], career = keywords[5] , best = keywords[6], badges = badges , manual = manual)
lkmModelOne.save()
When lkm.py is executed , I got an error below:
Traceback (most recent call last):
File "/Users/kyungmoon/projectDicrectory/project/myApp/lkm.py", line 8, in <module>
from myApp.models import lkmModel
File "/Users/kyungmoon/projectDicrectory/project/myApp/models.py", line 2, in <module>
from django.contrib.postgres.fields import *
File "/Users/kyungmoon/venv/myvenv/lib/python3.4/site-packages/django/contrib/postgres/fields/__init__.py", line 1, in <module>
from .array import * # NOQA
File "/Users/kyungmoon/venv/myvenv/lib/python3.4/site-packages/django/contrib/postgres/fields/array.py", line 207, in <module>
class ArrayLenTransform(Transform):
File "/Users/kyungmoon/venv/myvenv/lib/python3.4/site-packages/django/contrib/postgres/fields/array.py", line 209, in ArrayLenTransform
output_field = IntegerField()
File "/Users/kyungmoon/venv/myvenv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/Users/kyungmoon/venv/myvenv/lib/python3.4/site-packages/django/conf/__init__.py", line 55, in __getattr__
self._setup(name)
File "/Users/kyungmoon/venv/myvenv/lib/python3.4/site-packages/django/conf/__init__.py", line 41, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
As you see, the error is from postgresql and arrayField of postgresql. But in
models.py , I created a lkmModel in a right way, isn't it?
Why does this happen?
I did install postgresql in my local machine and created a db called lkmDB and
a table for this. My DATABASES setting in settings.py in project is below :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'lkmDB',
'USER': 'kyungmoon',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
Answer: None of this has anything whatsoever to do with the code you've posted.
You are presumably doing this in a plain Python shell; you should start up the
Django shell with `python manage.py shell` instead.
|
FLASK - Running Python Scripts
Question: I have made a webpage using bootstrap which is hosted on a raspberry pi. What
I would like to do is to, when a certain button is clicked, is to run a python
script. This is all being hosted/run/accessed through a FLASK hosting service.
Thank you for your time.
Answer: [Run python method in HTML web
page](http://stackoverflow.com/questions/36713877/run-python-method-in-html-
web-page/37512973#37512973)
I also encountered same issue, and I solved it really easily using this way.
(I answered on my own question in that link)
Just redirect button to go any link let's say button , and then in flask
python file, make a method something like
@app.route('/a')
def b(name=None):
import (python script that you want to import, it should be on same folder to do it easy)
return render_template('xxx.html',name=name)
|
No module named flask in virtualenv although installed
Question: I want to use Flask to develop a website but I am having already problems
getting a simple demo app running.
I followed the complete installation tutorial of [the flask
website](http://flask.pocoo.org/docs/)
Means:
* I created a project directory.
* Inside this directory I created my virtualenv folder like described in the tutorial.
* I started the virtual environment using _. venv/bin/activate_
* I installed flask inside the virtualenv by _pip install Flask_
If I now open the python console via _python_ (while running venv) and I try
_from flask import Flask_ I get the error:
> Traceback (most recent call last): File "", line 1, in ImportError: No
> module named 'flask'
Also running a simple Hello World app like the following gives the same error.
If I try to install flask again in venv, the following is shown in the
console: [](http://i.stack.imgur.com/fAM7r.png)
from flask import Flask
application = Flask(__name__)
@application.route("/")
def hello():
return "hello world"
if __name__ == "__main__":
application.run()
For completeness: I already searched a lot on SO and google but could not find
the same problem. Although I found a few related all of them had the problem
that the one asking either forgot installing flask inside venv or forgot
activating venv etc.
Also if I type which python it points correctly to the folder bin/python
inside my venv folder.
Answer: Okay, I solved the issue: If I use python3 instead of python to execute my
program or to open python console everything works as expected.
Still, this is weird, because (inside venv) doing _which python3_ points to
the python3 file inside the bin folder of my venv, but _which python_ points
to a symbolic link inside the same folder, which points again to exactly the
same python3 file.
|
Tkinter, custom widget and label updates
Question: **Description**
I want to make a custom `"Table Widget"` for Tkinter and so far it's almost as
I want.
The problem I have is that I want the table to consist of `"Labels"`, I have
only found that you have to use `"StringVar()'s"` in order to update the
labels.
I dont really want 1000 variables for 1000 labels so I have tried to solve
this issue for a week now. The only solution I've found is to use `"Dicts"`
but I dont think this is a good way to do it? I might be wrong but it feels
like it has to be a way to do something like this:
myLabel = Label(root, text='myText')
myLabel.pack()
myLabel.setText('new text')
The current widget code looks like this `(This is my first custom widget so if
this is horribly wrong or wrong in any way, please tell me)`
**Source**
"""
Description:
A TABLE WIDGET Extension for Tkinter
"""
try:
#Python 3.X
import tkinter #this is quite annoyng, without it (tkinter) wont be available....
from tkinter import * # even with this
from tkinter import ttk
from tkinter.ttk import *
except ImportError:
#python 2.X
import tkinter
from Tkinter import *
from Tkinter import ttk
from Tkinter.ttk import *
class ETable(tkinter.Frame):
def __init__(self, parent, *args, **kwargs):
tkinter.Frame.__init__(self, parent)
self.init_table(parent, *args, **kwargs)
def init_table(self, parent, *args, **kwargs):
row_settings = {
'anchor': CENTER,
'background': '#C5FFFF',
'bitmap': None,
'borderwidth': 5,
'compound': None,
'cursor': None,
'font': None,
'foreground': '#000000',
'image': None,
'relief': FLAT,
'rows': 1,
'state': NORMAL,
'text': None,
'textvariable': None,
'underline': -1,
'width': 20,
}
for kwarg in kwargs:
if kwarg in row_settings:
row_settings[kwarg] = kwargs[kwarg]
self.table_rows = self.init_row(parent, *args, **row_settings)
def init_row(self, parent, *args, **kwargs):
text_list = kwargs.pop('text')
row_list = []
cols = []
rows = kwargs.pop('rows')
for row in range(rows):
for col in range(len(text_list)):
tempLabel = Label(parent, text = text_list[col], *args, **kwargs)
tempLabel.grid(row=row, column=col)
cols.append(tempLabel)
row_list.append(cols)
return row_list
**Goal**
I want to be able to do something like this
table.getRow[0][0].setText('new text') #This would change col 1 in row 1 to "new text"
* * *
**Bonus Question**
(please tell me if I should make a new question for this)
As I said, I want to make a `"Table Widget"` for Tkinter but I also want to
add behaviours to the table, IE when a user clicks on a row, I want the row to
expand `"Downwards"` much like a `"Dropdown Menu"` but it will only close when
it looses focus, the goal here is to add `"Entry or Text boxes"` in order to
edit the columns.
The Question here is, is this possible with Tkinter?
Answer: > I have only found that you have to use "StringVar()'s" in order to update
> the labels.
This is not a true statement. You can update the attributes of any widget with
the `config` / `configure` method. Starting with your first example, it would
look like this:
myLabel = Label(root, text='myText')
myLabel.pack()
myLabel.configure(text='new text')
And, in your final example:
table.getRow[0][0].configure(text='new text')
As for the bonus question, yes, it's possible.You can bind any code you want
to a label just as you can any other widget, and in addition to bindings on
keys and mouse buttons, you can bind on gaining and losing focus.
|
event handling of balloon tip with win32gui
Question: I'm currently using a slightly modified version of the [common example of the
systemtray](http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html).
#!/usr/bin/env python
# Module : SysTrayIcon.py
# Synopsis : Windows System tray icon.
# Programmer : Simon Brunning - [email protected]
# Date : 11 April 2005
# Notes : Based on (i.e. ripped off from) Mark Hammond's
# win32gui_taskbar.py and win32gui_menu.py demos from PyWin32
'''TODO
For now, the demo at the bottom shows how to use it...'''
import os
import win32api
import win32con
import win32gui_struct
try:
import winxpgui as win32gui
except ImportError:
import win32gui
class SysTrayIcon(object):
'''TODO'''
QUIT = 'QUIT'
SPECIAL_ACTIONS = [QUIT]
FIRST_ID = 1023
def __init__(self,
icon,
hover_text,
menu_options,
on_quit=None,
default_menu_index=None,
window_class_name=None, ):
self.icon = icon
self.hover_text = hover_text
self.on_quit = on_quit
menu_options = menu_options + (('Quit', None, self.QUIT),)
self._next_action_id = self.FIRST_ID
self.menu_actions_by_id = set()
self.menu_options = self._add_ids_to_menu_options(list(menu_options))
self.menu_actions_by_id = dict(self.menu_actions_by_id)
del self._next_action_id
self.default_menu_index = (default_menu_index or 0)
self.window_class_name = window_class_name or "SysTrayIconPy"
message_map = {win32gui.RegisterWindowMessage("TaskbarCreated"): self.restart,
win32con.WM_DESTROY: self.destroy,
win32con.WM_COMMAND: self.command,
win32con.WM_USER + 20: self.notify,}
# Register the Window class.
window_class = win32gui.WNDCLASS()
hinst = window_class.hInstance = win32gui.GetModuleHandle(None)
window_class.lpszClassName = self.window_class_name
window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW;
window_class.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW)
window_class.hbrBackground = win32con.COLOR_WINDOW
window_class.lpfnWndProc = message_map # could also specify a wndproc.
classAtom = win32gui.RegisterClass(window_class)
# Create the Window.
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
self.hwnd = win32gui.CreateWindow(classAtom,
self.window_class_name,
style,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
0,
0,
hinst,
None)
win32gui.UpdateWindow(self.hwnd)
self.notify_id = None
self.refresh_icon()
win32gui.PumpMessages()
def _add_ids_to_menu_options(self, menu_options):
result = []
for menu_option in menu_options:
option_text, option_icon, option_action = menu_option
if callable(option_action) or option_action in self.SPECIAL_ACTIONS:
self.menu_actions_by_id.add((self._next_action_id, option_action))
result.append(menu_option + (self._next_action_id,))
elif non_string_iterable(option_action):
result.append((option_text,
option_icon,
self._add_ids_to_menu_options(option_action),
self._next_action_id))
else:
print 'Unknown item', option_text, option_icon, option_action
self._next_action_id += 1
return result
def refresh_icon(self):
# Try and find a custom icon
hinst = win32gui.GetModuleHandle(None)
if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
self.hicon = win32gui.LoadImage(hinst,
self.icon,
win32con.IMAGE_ICON,
0,
0,
icon_flags)
else:
print "Can't find icon file - using default."
self.hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
if self.notify_id:
message = win32gui.NIM_MODIFY
else:
message = win32gui.NIM_ADD
self.notify_id = (self.hwnd,
0,
win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP,
win32con.WM_USER + 20,
self.hicon,
self.hover_text)
win32gui.Shell_NotifyIcon(message, self.notify_id)
def restart(self, hwnd, msg, wparam, lparam):
self.refresh_icon()
def destroy(self, hwnd, msg, wparam, lparam):
if self.on_quit: self.on_quit(self)
nid = (self.hwnd, 0)
win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)
win32gui.PostQuitMessage(0) # Terminate the app.
def notify(self, hwnd, msg, wparam, lparam):
if lparam == win32con.WM_LBUTTONDBLCLK:
self.execute_menu_option(self.default_menu_index + self.FIRST_ID)
elif lparam == win32con.WM_RBUTTONUP:
self.show_menu()
elif lparam == win32con.WM_LBUTTONUP:
pass
return True
def show_menu(self):
menu = win32gui.CreatePopupMenu()
self.create_menu(menu, self.menu_options)
# win32gui.SetMenuDefaultItem(menu, 1000, 0)
pos = win32gui.GetCursorPos()
# See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/menus_0hdi.asp
win32gui.SetForegroundWindow(self.hwnd)
win32gui.TrackPopupMenu(menu,
win32con.TPM_LEFTALIGN,
pos[0],
pos[1],
0,
self.hwnd,
None)
win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
def create_menu(self, menu, menu_options):
for option_text, option_icon, option_action, option_id in menu_options[::-1]:
if option_icon:
option_icon = self.prep_menu_icon(option_icon)
if option_id in self.menu_actions_by_id:
item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text,
hbmpItem=option_icon,
wID=option_id)
win32gui.InsertMenuItem(menu, 0, 1, item)
else:
submenu = win32gui.CreatePopupMenu()
self.create_menu(submenu, option_action)
item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text,
hbmpItem=option_icon,
hSubMenu=submenu)
win32gui.InsertMenuItem(menu, 0, 1, item)
def prep_menu_icon(self, icon):
# First load the icon.
ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON)
hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE)
hdcBitmap = win32gui.CreateCompatibleDC(0)
hdcScreen = win32gui.GetDC(0)
hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y)
hbmOld = win32gui.SelectObject(hdcBitmap, hbm)
# Fill the background.
brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU)
win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush)
# unclear if brush needs to be feed. Best clue I can find is:
# "GetSysColorBrush returns a cached brush instead of allocating a new
# one." - implies no DeleteObject
# draw the icon
win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL)
win32gui.SelectObject(hdcBitmap, hbmOld)
win32gui.DeleteDC(hdcBitmap)
return hbm
def command(self, hwnd, msg, wparam, lparam):
id = win32gui.LOWORD(wparam)
self.execute_menu_option(id)
def execute_menu_option(self, id):
menu_action = self.menu_actions_by_id[id]
if menu_action == self.QUIT:
win32gui.DestroyWindow(self.hwnd)
else:
menu_action(self)
def show_notification(self, title, msg):
"""
show the shell notification with the title and message
:param title:
:param msg:
:return:
"""
win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY,
(self.hwnd, 0, win32gui.NIF_INFO, win32con.WM_USER + 20,
self.hicon, "", msg, 200, title))
def non_string_iterable(obj):
try:
iter(obj)
except TypeError:
return False
else:
return not isinstance(obj, basestring)
# Minimal self test. You'll need a bunch of ICO files in the current working
# directory in order for this to work...
if __name__ == '__main__':
import itertools, glob
icons = itertools.cycle(glob.glob('*.ico'))
hover_text = "SysTrayIcon.py Demo"
def hello(sysTrayIcon): print "Hello World."
def simon(sysTrayIcon): print "Hello Simon."
def switch_icon(sysTrayIcon):
sysTrayIcon.icon = icons.next()
sysTrayIcon.refresh_icon()
menu_options = (('Say Hello', icons.next(), hello),
('Show balloon tip', None, lambda x: x.show_notification("title", "message")),
('A sub-menu', icons.next(), (('Say Hello to Simon', icons.next(), simon),
('Switch Icon', icons.next(), switch_icon),
))
)
def bye(sysTrayIcon): print 'Bye, then.'
SysTrayIcon(icons.next(), hover_text, menu_options, on_quit=bye, default_menu_index=1)
I made the hicon variable accessible for the whole class and added the
function show_notification. What I'm currently trying to do is calling a
function if the notification is clicked. I found in the [win32gui perl
documentation](http://perl-win32-gui.sourceforge.net/cgi-
bin/docs.cgi?doc=notifyicon)(which should be essentially the same from the
functionality) that there are certain common events like Click or MouseEvent,
but so far I couldn't find any way to add an event handler to the
Shell_NotifyIcon.
I've checked the [NOTIFYICONDATA structure from
Microsoft](https://msdn.microsoft.com/en-
us/library/windows/desktop/bb773352\(v=vs.85\).aspx) and found this
interesting part:
> When the uVersion member is NOTIFYICON_VERSION_4, applications continue to
> receive notification events in the form of application-defined messages
> through the uCallbackMessage member
But I couldn't find any way to put this to any use. Lastly I tried to add an
eventhandler with win32com.client.DispatchWithEvents but I'm failing here with
the clsid already.
Answer: I ended up using the try, except block with a win32gui error exception.
Anywhere I was making a call to win32gui, I wrapped in the win32gui.error
exception block. AFAIK, that's the only method to obtain the exception.
` try: win32gui.<something> except win32gui.error as error:
logging.error(error) `
Additionally, you can use the traceback library to obtain a stack trace. That
helped me debug much of the Python wrapped version of the Windows API.
import traceback
try:
hicon = win32gui.LoadImage(self.hinst, self.icon, win32con.IMAGE_ICON, 0, 0, icon_flags)
except win32gui.error as error:
logging.error(self.hinst)
logging.error(self.icon)
logging.error(icon_flags)
logging.error(error)
logging.error(traceback.format_exc())
|
How can I replace Unicode characters with Turkish characters in a text file with Python
Question: I am working on Twitter. I got data from Twitter with Stream API and the
result of app is JSON file. I wrote tweets data in a text file and now I see
Unicode characters instead of Turkish characters. I don't want to do
find/replace in Notepad++ by hand. Is there any automatic option to replace
characters by opening txt file, reading all data in file and changing Unicode
characters with Turkish characters by Python?
Here are Unicode characters and Turkish characters which I want to replace.
* ğ - \u011f
* Ğ - \u011e
* ı - \u0131
* İ - \u0130
* ö - \u00f6
* Ö - \u00d6
* ü - \u00fc
* Ü - \u00dc
* ş - \u015f
* Ş - \u015e
* ç - \u00e7
* Ç - \u00c7
I tried two different type
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
dosya = open('veri.txt', 'r')
for line in dosya:
match = re.search(line, "\u011f")
if (match):
replace("\u011f", "ğ")
dosya.close()
and:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
f1 = open('veri.txt', 'r')
f2 = open('veri2.txt', 'w')
for line in f1:
f2.write=(line.replace('\u011f', 'ğ'))
f2.write=(line.replace('\u011e', 'Ğ'))
f2.write=(line.replace('\u0131', 'ı'))
f2.write=(line.replace('\u0130', 'İ'))
f2.write=(line.replace('\u00f6', 'ö'))
f2.write=(line.replace('\u00d6', 'Ö'))
f2.write=(line.replace('\u00fc', 'ü'))
f2.write=(line.replace('\u00dc', 'Ü'))
f2.write=(line.replace('\u015f', 'ş'))
f2.write=(line.replace('\u015e', 'Ş'))
f2.write=(line.replace('\u00e7', 'ç'))
f2.write=(line.replace('\u00c7', 'Ç'))
f1.close()
f2.close()
Both of these didn't work. How can I make it work?
Answer: JSON allows both "escaped" and "unescaped" characters. The reason why the
Twitter API returns only escaped characters is that it can use the ASCII
encoding, which increases interoperability. For Turkish characters you need
another encoding. Opening a file with the
[`open`](https://docs.python.org/3/library/functions.html#open) function opens
a file assuming your current locale encoding, which is probably what your
editor expects. If you want the output file to have e.g. the `ISO-8859-9`
encoding, you can pass `encoding='ISO-8859-9`' as an additional parameter to
the `open` function.
You can read a file containing a JSON object with the `json.load` function.
This returns a Python object with the escaped characters decoded. Writing it
again with `json.dump` and passing `ensure_ascii=False` as an argument writes
the object back to a file without encoding Turkish characters as escape
sequences. An example:
import json
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
in_as_obj = json.load(inp)
json.dump(in_as_obj, out, ensure_ascii=False)
Your file isn't really a JSON file, but instead a file containing multiple
JSON objects. If each JSON object is on its own line, you can try the
following:
import json
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
for line in inp:
if not line.strip():
out.write(line)
continue
in_as_obj = json.loads(line)
json.dump(in_as_obj, out, ensure_ascii=False)
out.write('\n')
But in your case it's probably better to write unescaped JSON to the file in
the first place. Try replacing your `on_data` method by (untested):
def on_data(self, raw_data):
data = json.loads(raw_data)
print(json.dumps(data, ensure_ascii=False))
|
pysftp connection to host with pem file raise exception paramiko.ssh_exception.BadAuthenticationType
Question: I have to connect to other server in python using the pysftp library, the
target server had a key value pair file (pem file), and I've got the following
exception:
paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey']) (allowed_types=[u'publickey'])
my Code:
import pysftp
pysftp.Connection(host="<IP address>", username="myUserName", password="no password", port=22, private_key="myPemFilePath.pem")
Please any help? and how can I fix such like this issue ?
Answer: From the documentation :
import pysftp
with pysftp.Connection('hostname', username='me', private_key='/path/to/keyfile') as sftp:
#
# ... do sftp operations
#
As you can see there is no `password= "no password"`, in ther. Try, by just
omitting that in your code, as it probably triggers the use of
username/password authentication, skipping your private_key.
|
regex backreference findall not working python
Question: I have recently been using regexes in a program. In this program I used them
to find words in a list of words that matched a certain RE. However, when i
tried backreferencing with this program, I got an interesting result.
Here is the code:
import re
pattern = re.compile(r"[abcgr]([a-z])\1[ldc]")
string = "reel reed have that with this they"
print(re.findall(pattern, string))
What I expected was the result `["reel","reed"]` (the regex matched these when
I used it with [Pythex](http://pythex.org/))
However, when I ran the code using python (I use 3.5.1) I got the following
result:
`['e','e']`
Please can someone with more experience with REs explain why I am getting this
problem and what I can do to resolve it.
Thank you.
Answer: The [`re.findall`](https://docs.python.org/2/library/re.html#re.findall) only
returns captured values captured with _capturing groups_ inside the regex
pattern.
Use [`re.finditer`](https://docs.python.org/2/library/re.html#re.finditer)
that will keep the zeroth group (the whole match):
import re
p = re.compile(r'[abcgr]([a-z])\1[ldc]')
s = "reel reed have that with this they"
print([x.group(0) for x in p.finditer(s)])
See the [IDEONE demo](http://ideone.com/pTZDxg)
|
Selenium on Anaconda 2 not opening firefox
Question: I'm a beginner python user and try to use selenium to open Firefox on Win 10
and Anaconda 2.5. I just downloaded Firefox and installed selenium on
Anaconda, so they are up to date. When I type the following:
from selenium import webdriver
browser = webdriver.Firefox()
Firefox open in the task bar for a second and disappears. But if I close the
cmd line, Firefox opens on the window. The cursor on the cmd prompt is
flickering so when I wait, then I get the error message. How can I solve this?
> Traceback (most recent call last): File "", line 1, in File
> "C:\Anaconda2\lib\site-packages\selenium\webdriver\firefox\webdriver.py",
> line 59, in **init** self.binary, timeout), File "C:\Anaconda2\lib\site-
> packages\selenium\webdriver\firefox\extension_connection.py", line 47, in
> **init** self.binary.launch_browser(self.profile) File
> "C:\Anaconda2\lib\site-
> packages\selenium\webdriver\firefox\firefox_binary.py", line 61, in
> launch_browser self._wait_until_connectable() File "C:\Anaconda2\lib\site-
> packages\selenium\webdriver\firefox\firefox_binary.py", line 105, in
> _wait_until_connectable self.profile.path, self._get_firefox_output()))
> selenium.common.exceptions.WebDriverException: Message: 'Can\'t load the
> profile. Profile Dir: c:\users\kwan\appdata\local\temp\tmplb0d6s Firefox
> output: 1464547978869\taddons.manager\tDEBUG\tLoaded provider scope for
> resource://gre/modules/addons/XPIProvider.jsm:
> ["XPIProvider"]\r\n1464547978870\taddons.manager\tDEBUG\tLoaded provider
> scope for resource://gre/modules/LightweightThemeManager.jsm:
> ["LightweightThemeManager"]\r\n1464547978873\taddons.manager\tDEBUG\tLoaded
> provider scope for
> resource://gre/modules/addons/GMPProvider.jsm\r\n1464547978874\taddons.manager\tDEBUG\tLoaded
> provider scope for
> resource://gre/modules/addons/PluginProvider.jsm\r\n1464547978875\taddons.manager\tDEBUG\tStarting
> provider:
> XPIProvider\r\n1464547978875\taddons.xpi\tDEBUG\tstartup\r\n1464547978876\taddons.xpi\tINFO\tMapping
> [email protected] to
> c:\users\kwan\appdata\local\temp\tmplb0d6s\extensions\[email protected]\r\n1464547978876\taddons.xpi\tINFO\tSystemAddonInstallLocation
> directory is missing\r\n1464547978876\taddons.xpi\tINFO\tMapping
> [email protected] to C:\Program Files (x86)\Mozilla
> Firefox\browser\features\[email protected]\r\n1464547978876\taddons.xpi\tINFO\tMapping
> [email protected] to C:\Program Files (x86)\Mozilla
> Firefox\browser\features\[email protected]\r\n1464547978877\taddons.xpi\tINFO\tMapping
> [email protected] to C:\Program Files (x86)\Mozilla
> Firefox\browser\features\[email protected]\r\n1464547978878\taddons.xpi\tINFO\tMapping
> {972ce4c6-7e08-4474-a285-3208198ce6fd} to C:\Program Files (x86)\Mozilla
> Firefox\browser\extensions\\{972ce4c6-7e08-4474-a285-3208198ce6fd}.xpi\r\n1464547978878\taddons.xpi\tDEBUG\tSkipping
> unavailable install location app-system-
> share\r\n1464547978878\taddons.xpi\tDEBUG\tSkipping unavailable install
> location app-system-local\r\n1464547978878\taddons.xpi\tINFO\tMapping
> [email protected] to C:\Program Files (x86)\Adobe\Acrobat
> 11.0\Acrobat\Browser\WCFirefoxExtn\r\n1464547978879\taddons.xpi\tDEBUG\tcheckForChanges\r\n1464547978879\taddons.xpi\tDEBUG\tLoaded
> add-on state from prefs: {"app-
> profile":{"[email protected]":{"d":"c:\\\users\\\kwan\\\appdata\\\local\\\temp\\\tmplb0d6s\\\extensions\\\[email protected]","e":false,"v":"2.40.0","st":1464547977236,"mt":1464547977189}},"app-
> system-defaults":{"[email protected]":{"d":"C:\\\Program Files
> (x86)\\\Mozilla
> Firefox\\\browser\\\features\\\[email protected]","e":true,"v":"1.0","st":1462246394000},"[email protected]":{"d":"C:\\\Program
> Files (x86)\\\Mozilla
> Firefox\\\browser\\\features\\\[email protected]","e":true,"v":"1.0","st":1462246394000},"[email protected]":{"d":"C:\\\Program
> Files (x86)\\\Mozilla
> Firefox\\\browser\\\features\\\[email protected]","e":true,"v":"1.2.6","st":1462246394000}},"app-
> global":{"{972ce4c6-7e08-4474-a285-3208198ce6fd}":{"d":"C:\\\Program Files
> (x86)\\\Mozilla
> Firefox\\\browser\\\extensions\\\\{972ce4c6-7e08-4474-a285-3208198ce6fd}.xpi","e":true,"v":"46.0.1","st":1462246394000}},"winreg-
> app-global":{"[email protected]":{"d":"C:\\\Program Files
> (x86)\\\Adobe\\\Acrobat
> 11.0\\\Acrobat\\\Browser\\\WCFirefoxExtn","e":false,"v":"2.0","st":1458012184487,"mt":1348422236000}}}\r\n1464547978880\taddons.xpi\tDEBUG\tExisting
> add-on [email protected] in app-
> profile\r\n1464547978880\taddons.xpi\tDEBUG\tgetModTime: Recursive scan of
> [email protected]\r\n1464547978881\taddons.xpi\tDEBUG\tExisting add-on
> [email protected] in app-system-
> defaults\r\n1464547978881\taddons.xpi\tDEBUG\tgetModTime: Recursive scan of
> [email protected]\r\n1464547978881\taddons.xpi\tDEBUG\tExisting add-on
> [email protected] in app-system-
> defaults\r\n1464547978881\taddons.xpi\tDEBUG\tgetModTime: Recursive scan of
> [email protected]\r\n1464547978882\taddons.xpi\tDEBUG\tExisting add-on
> [email protected] in app-system-
> defaults\r\n1464547978882\taddons.xpi\tDEBUG\tgetModTime: Recursive scan of
> {972ce4c6-7e08-4474-a285-3208198ce6fd}\r\n1464547978882\taddons.xpi\tDEBUG\tExisting
> add-on {972ce4c6-7e08-4474-a285-3208198ce6fd} in app-
> global\r\n1464547978882\taddons.xpi\tDEBUG\tExisting add-on
> [email protected] in winreg-app-global\r\n'
Answer: Thanks guys who viewed my posts. I figured out the solution. I googled
"anaconda selenium install" and there is a hit on top and I followed it. The
thing is its command installs Selenium 2.40 but the current version is 2.53.
Anaconda does not have Selenium package so "conda install selenium" does not
work. BUT you can still use "pip install selenium" and it will install the
latest selenium
|
Python Server socket.error: [Errno 92] Protocol not available
Question: I wanted to make a server, that recives an command from a client, in the form
of a String and send a String(or a List of Strings) back. The first time, I
run the server and the client, it works perfectly fine, but after the server
send the String to the client, the server crashes with the message:
socket.error: [Errno 92] Protocol not available
Here is the Server:
import socket
import errno
def Main():
host = '192.168.178.30'
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
s.bind((host, port))
s.listen(1)
while True:
c, addr = s.accept()
c.setblocking(0)
print "Connection from: " + str(addr)
command = c.recv(1024)
if command == 'GIVETEXT':
c.send('test')
try:
c.close()
s.setsockopt(socket.AF_INET, socket.SOCK_STREAM, 1)
except socket.error as e:
if e.errno != errno.ECONNRESET:
raise
pass
if __name__ == '__main__':
Main()
And Here is the client part:
import socket
class Client(object):
def __init__(self, *args):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def sent(self, host, port):
self.s.connect((host, port))
self.s.send('GIVETEXT')#sends command
self.Text = self.s.recv(1024)
print self.Text
self.s.close
return self.Text
Answer: In the server code, could you comment (or remove) the following line:
s.setsockopt(socket.AF_INET, socket.SOCK_STREAM, 1)
The setsockopt operation is to define the options of the socket. The level
should be SOL_SOCKET and the differents options can be found in setsockopt man
page: <http://linux.die.net/man/3/setsockopt>
An example would be:
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
|
Getting an error when trying to create a virtual env
Question: I want to learn django so I tried to create a virtual env and I am getting
this error:
mkvirtualenv djngo
Traceback (most recent call last):
File "/usr/local/bin/virtualenv", line 5, in <module>
from pkg_resources import load_entry_point
File "/Library/Python/2.7/site-packages/distribute-0.6.49-py2.7.egg/pkg_resources.py", line 2881, in <module>
parse_requirements(__requires__), Environment()
File "/Library/Python/2.7/site-packages/distribute-0.6.49-py2.7.egg/pkg_resources.py", line 596, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: virtualenv==1.8.2
I haven't used python in a while so not sure what the issue is.
virtualenv --version
Traceback (most recent call last):
File "/usr/local/bin/virtualenv", line 5, in <module>
from pkg_resources import load_entry_point
File "/Library/Python/2.7/site-packages/distribute-0.6.49-py2.7.egg/pkg_resources.py", line 2881, in <module>
parse_requirements(__requires__), Environment()
File "/Library/Python/2.7/site-packages/distribute-0.6.49-py2.7.egg/pkg_resources.py", line 596, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: virtualenv==1.8.2
Answer: You're using `mkvirtualenv` which is a `virtualenvwrapper` command. You
probably do not have `virtualenvwrapper` installed.
Type `virtualenvwrapper` in your command line and observe the input. If you
get something like `command not found`, then you should install it first.
You should install it with pip like so `pip install virtualenvwrapper`.
There are some post-installation steps, the most important one being `source
/usr/local/bin/virtualenvwrapper.sh` that makes commands like `mkvirtualenv,
rmvirtualenv` available.
See `virtualenvwrapper's`
[documentation](https://virtualenvwrapper.readthedocs.io/en/latest/).
Alternatively, you can also just make use of `virtualenv`. Check that you have
it installed like so
`virtualenv --version`
If you do not, you can install it with `pip`. Once you have it installed, you
can create your virtualenv like so `virtualenv <name>` in the directory of
your choice.
|
How do I convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores?
Question: I have a Pandas dataframe that resembles this:
sentence score
"This is a sentence." 5
"Another sentence?" 8
And I want one that resembles this:
word total_score count normalized_score
"sentence" 13 2 6.5
"this" 5 1 5
etc.
How should I go about doing this? My thought is to remove all non-alphanumeric
characters, then use
[split()](http://www.tutorialspoint.com/python/string_split.htm) on all of the
cells containing sentences, then combine those words into a set, then use that
set to iterate through the original dataframe, counting the number of times a
word is used and the corresponding scores. This, however, seems inelegant and
potentially incredibly inefficient. Is there a better way to do this?
Note: Don't worry about stop words and assume all words are separated by
spaces
Edit:
The head of the actual data (after applying `wide = df.apply(lambda x:
pd.Series(x['score'], index=x['sentence']), axis=1)` ) is:
score title
0 1 [javascript, kml, compressor, for, google, maps]
1 3 [ktbyte, challenge, programming, game, for, 9, 15, year, olds]
2 4 [worldometers, real, time, world, statistics]
3 1 [apple, s, sales, policies]
4 72 [report, suggests, 21, hours, is, the, ideal, work, week]
5 3 [new, paper, shows, how, to, get, control, without, injecting, new, code]
Strangely, unutbu's solution works for the first 5 rows, but not when the
sixth is added. When the sixth is added, Python returns `ValueError: cannot
reindex from a duplicate axis` (which seems to be Panda's vaguely defined
catch-all error for reindexing).
Answer: You could use `df.itertuples` to iterate through the rows of `df` and build a
long-format DataFrame of the form:
In [86]: longframe
Out[86]:
score word
0 5 This
1 5 is
2 5 a
3 5 sentence
4 8 Another
5 8 sentence
6 8 sentence
Once you have the data in this format, you could group by `word` and sum the
scores for each word, and use `value_counts` to count the frequency of each
word.
* * *
import pandas as pd
df = pd.DataFrame(
{'score': [5, 8], 'sentence': ["This is a sentence.", "Another sentence sentence?"]})
df['sentence'] = df['sentence'].str.findall(r'\w+')
longframe = pd.DataFrame([(row.score, word) for row in df.itertuples()
for word in row.sentence],
columns=['score', 'word'])
score = longframe.groupby('word')['score'].sum()
count = longframe['word'].value_counts()
result = pd.DataFrame({'score':score, 'count':count, 'normalized_score':score/count})
result = result.reset_index()
result = result.rename(columns={'index':'word'})
print(result)
yields
word count normalized_score score
0 Another 1 8.0 8
1 This 1 5.0 5
2 a 1 5.0 5
3 is 1 5.0 5
4 sentence 3 7.0 21
|
how to get the unique combination of columns and sort by them in python data frame?
Question: how to get the unique combination of columns and sort by them in python data
frame? I know I can use df.groupby(['col1','col2']).size() to get the unique
combination. However, I also want to have the result order by the ascending
order of col2, and then ascending order by col1. For example, if my dataframe
is like this:
col1 col2
0 A 1
1 B 3
2 C 2
3 D 1
4 A 1
5 F 2
I would like the final output look like this:
col1 col2
0 A 1
1 D 1
2 C 2
3 F 2
4 B 3
Answer: Use [`groupby`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.groupby.html) by `col2` and `col1`, but
then need [`swaplevel`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.swaplevel.html) (if order columns
`col1` and `col2` is important) with
[`reset_index`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.reset_index.html) \- solution use
default sorting in `groupby`:
df1 = df.groupby(['col2','col1']).size().swaplevel(0,1).reset_index(name='count')
print (df1)
col1 col2 count
0 A 1 2
1 D 1 1
2 C 2 1
3 F 2 1
4 B 3 1
Second solution need first [`sort_values`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.sort_values.html) in columns `col2` and
`col1` and then add parameter `sort=False` to
[`groupby`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.groupby.html), because by default
`sort=True`:
df = df.sort_values(['col2','col1'])
print (df)
col1 col2
0 A 1
4 A 1
3 D 1
2 C 2
5 F 2
1 B 3
print (df.groupby(['col1','col2'], sort=False).size())
col1 col2
A 1 2
D 1 1
C 2 1
F 2 1
B 3 1
dtype: int64
Another solution is first [`groupby`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.groupby.html) and then
[`sort_values`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.sort_values.html):
df1 = df.groupby(['col1','col2']).size().reset_index(name='count')
print (df1)
col1 col2 count
0 A 1 2
1 B 3 1
2 C 2 1
3 D 1 1
4 F 2 1
df1 = df1.sort_values(['col2','col1'])
print (df1)
col1 col2 count
0 A 1 2
3 D 1 1
2 C 2 1
4 F 2 1
1 B 3 1
|
How to scrape data from html which does not belong to any tag
Question: I want to scrape country name and date from the below website html example.
Here the name of the country and date are not inside any tag but just free
data. How to scrape it?
<div class="infos">
<p>
<span class="hidden-xs hidden-sm">Item offered for sale by:<br/></span>
<span class="slk" id="product_seller_firstname" title="#sl#members#sl#profile-1075689#sh#">Sophie</span> (Germany) <br/>
<span style="font-weight: normal; font-size: 12px;">Individual Seller</span>
<br/>
May 29, 2016 <br/>
4 items sold </p>
I have fetched the data for the class "infos" like this
`getinfo=soup.find_all("div",{"class":"infos"})` How to get the value
**"Germany"** and date **May 29,2016** from it?
Note I have already refered the related questions
[28075119](http://stackoverflow.com/questions/28075119/python-scraping-
beautiful-soup-to-obtain-data-from-this-html) and
[37475110](http://stackoverflow.com/questions/37475110/scrape-information-
from-challenging-website-with-no-guiding-html-structure). But I could not get
the answer from my problem.
Answer: You can try specifically filtering out the elements that are not tags:
import bs4
html = """<div class="infos">
<p>
<span class="hidden-xs hidden-sm">Item offered for sale by:<br/></span>
<span class="slk" id="product_seller_firstname" title="#sl#members#sl#profile-1075689#sh#">Sophie</span> (Germany) <br/>
<span style="font-weight: normal; font-size: 12px;">Individual Seller</span>
<br/>
May 29, 2016 <br/>
4 items sold </p>"""
soup = bs4.BeautifulSoup(html, "lxml")
text_nodes = [c.strip() for c in soup.find('p').children if not isinstance(c, bs4.element.Tag)]
# Remove empty strings (previously just whitespace)
text_nodes = [c for c in text_nodes if c]
print(text_nodes)
Output:
[u'(Germany)', u'May 29, 2016', u'4 items sold']
But I don't know how robust this is.
|
Set zlim in matplotlib scatter3d
Question: I have three lists xs, ys, zs of data points in Python and I am trying to
create a 3d plot with `matplotlib` using the `scatter3d` method.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.xlim(290)
plt.ylim(301)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(xs, ys, zs)
plt.savefig('dateiname.png')
plt.close()
The `plt.xlim()` and `plt.ylim()` work fine, but I don't find a function to
**set the borders in z-direction**. How can I do so?
Answer: Simply use the `set_zlim` function of the `axes` object (like you already did
with `set_zlabel`, which also isn't available as `plt.zlabel`):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
xs = np.random.random(10)
ys = np.random.random(10)
zs = np.random.random(10)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(xs, ys, zs)
ax.set_zlim(-10,10)
|
Pygame loads images with RGB values offset 1px, but not alpha values
Question: When attempting to load an image via Pygames image load functionality, a black
bar appears at the top of the loaded image. When slicing the tiles it became
apparent that this bar offset the content by 1px.
Attempting various file formats (gif, png, alpha, non-alpha etc.) have similar
effects with the offset, although notably png offsets everything except the
alpha when using convert_alpha.
[Example of the offest, and random colours when split into
tiles](http://i.stack.imgur.com/Yr470.png), and the [the tileset image being
used](http://i.stack.imgur.com/OBxZk.gif).
Even a simple blit of the whole image has the same problem present:
import pygame
import pygame.locals
pygame.init()
screen = pygame.display.set_mode((128, 128))
screen.fill((255,255,255))
screen.blit(pygame.image.load("src/tiles.gif"), (16,16))
pygame.display.flip()
I have also attempted using `convert()` and `convert_alpha()`, both with
similar effect.
Appreciate any help. I am running Pygame 1.9.1 in Python 3.5 on OS X 10.11.
Edit: I have tested it on both retina and non-retina displays, and it is the
same on both. When using alpha it appears only the rgb values are shifted down
1px while the alpha remains in place.
Answer: Try to set image alpha:
pygame.image.load("src/tiles.gif"), (16,16)).convert_alpha ()
|
Regex Multline Python
Question: i am currently trying to do a regex on pyhthon that should match multline.
([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4
is my regular expression, this is my python call
re.findall("([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4.*?", content, flags=re.M)
However when i use the Regex for example in Notepad++ it provides me with the
proper matches whereas in python it does not match anything at all (here is an
example string that is matched in npp but not in python)
19.04.2016 01:59:18 ASDF
\---- FG 3
--------------- ASDF
19.04.2016 01:59:21 ASDF
\---- FG 4
--------------- ASDF
19.04.2016 01:59:22 ASDF
\---- FG 4
--------------- ASDF
I am also sure that there in fact is a \r\n since npp provides me with
matches.
Since i am using the multiline flag i have absoultley no idea why my regex
wont work.
Answer: Note that in the corrected input shown, the part `FG\s{3,}?4`of the pattern
avoids a match as a single space does not match between `FG`and the `4`.
#! /usr/bin/env python
from __future__ import print_function
import re
content = "19.04.2016 05:31:03 ASDFASDF\r\n---- FG 4 "
pattern = (r'([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?'
r'\r\n-{1,}\sFG\s{1,}?4.*?')
print(re.findall(pattern, content, flags=re.M))
gives me (unmodified with python 2.7.11 and 3.5.1):
['19.04.2016 05:31:03']
**Edit** : Here a version for the updated amended input samples as transcribed
by @poke:
#! /usr/bin/env python
from __future__ import print_function
import re
content = ("19.04.2016 05:31:03 ASDFASDF\r\n---- FG 4"
"\r\n19.04.2016 05:31:03 ASDFASDF\r\n---- FG 4"
"\r\n19.04.2016 05:31:03 ASDFASDF\r\n---- FG 4"
"\r\n19.04.2016 05:31:03 ASDFASDF\r\n---- FG 4"
"\r\n19.04.2016 05:31:03 ASDFASDF\r\n---- FG 4")
pattern = (r'([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?'
r'\r\n-{1,}\sFG\s{1,}?4.*?')
print(re.findall(pattern, content, flags=re.M))
Gives (as to be expected):
['19.04.2016 05:31:03', '19.04.2016 05:31:03', '19.04.2016 05:31:03', '19.04.2016 05:31:03', '19.04.2016 05:31:03']
|
Error while importing matplotlib.pyplot Python
Question: I have a problem while importing matplotlib.pyplot , I have python2.7 windows
7 64bits
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
import matplotlib.pyplot as plt
File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 129, in <module>
from matplotlib.cbook import is_string_like
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 28, in <module>
import numpy as np
File "C:\Python27\lib\site-packages\numpy\__init__.py", line 180, in <module>
from . import add_newdocs
File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc
File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 4, in <module>
from type_check import *
File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 20, in <module>
import function_base
File "C:\Python27\lib\site-packages\numpy\core\function_base.py", line 6, in <module>
from .numeric import result_type, NaN, shares_memory, MAY_SHARE_BOUNDS, TooHardError
ImportError: cannot import name shares_memory
Please help
Answer: I soled the issue by uninstalling python27, reinstall it again and install
extension pip install matplotlib-1.5.0-cp27-none-win_amd64.whl
this will install automaticaly numpy extension
|
Sorting data from a table
Question: I'm working on a new version of a module and I need to create a new table for
that, but I'm facing a little issue that is driving me crazy.
Here is my relevant python code:
import psycopg2, sys, psycopg2.extras, time
order = 4419
try:
con = psycopg2.connect(host='localhost', database='DB01', user='odoo', password='******')
cur = con.cursor()
po_lines = 'SELECT pos_order_line.id FROM public.pos_order_line, public.product_template ' \
'WHERE pos_order_line.product_id = product_template.id AND pos_order_line.order_id = %s '\
'AND (product_template.pos_categ_id != 5 AND product_template.pos_categ_id != 6)' \
'ORDER BY pos_order_line.id ASC'
po_lines2 = 'SELECT pos_order_line.id, pos_order_line.order_id, product_template.name, pos_order_line.qty, product_template.pos_categ_id ' \
'FROM public.pos_order_line, public.product_template ' \
'WHERE pos_order_line.product_id = product_template.id AND pos_order_line.id = %s ' \
'ORDER BY pos_order_line.id ASC'
cur.execute(po_lines,[order]); fetch_lines = cur.fetchall()
dish = ''; instr = []; kot = 0; dp = 0
print fetch_lines
for line in fetch_lines:
cur.execute(po_lines2, [line]); pos_lines = cur.fetchone()
if pos_lines[2].startswith('#'):
instr.insert(1, pos_lines[2][2:]); kot = 1
elif pos_lines[2].startswith('----'):
dp = 1
else:
dish = pos_lines[2]
kot = 0; instr = []
if dp == 1:
instr.insert(0, '!SERVIR DEPOIS!'); dp = 0
if dish != pos_lines[2]:
print 'Ordem: ', order, ' - Prato:', dish, ' - Instr:', instr, 'qt: ', pos_lines[3],'kot: ', kot, 'dp status:', dp
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
Starting from a query I have:
ID ORDER PRODUCT QTY CAT
12811 4419 "Crudo GR" 1.0 1
12812 4419 "Salame e Grana GR" 1.0 1
12813 4419 "---- servir depois ----" 1.0 7
12814 4419 "Nutella Ban GR" 1.0 3
12815 4419 "# Cortar em dois" 1.0 7
Resuming all product line (pos_lines[2]) not starting with '#' or with '----'
need to be placed on a variable 'instr' until the var 'dish' changes. All the
line are correctly read because if I put a print statement at the end of all
IF cycles I can see how the variables are filled:
> 1 Ordem: 4419 - Prato: Crudo GR - Instr: [] qt: 1.0 kot: 0 dp status: 0
>
> 2 Ordem: 4419 - Prato: Salame e Grana GR - Instr: [] qt: 1.0 kot: 0 dp
> status: 0
>
> 3 Ordem: 4419 - Prato: Salame e Grana GR - Instr: [] qt: 1.0 kot: 0 dp
> status: 1
>
> 4 Ordem: 4419 - Prato: Nutella Ban GR - Instr: ['!SERVIR DEPOIS!'] qt: 1.0
> kot: 0 dp status: 0
>
> 5 Ordem: 4419 - Prato: Nutella Ban GR - Instr: ['!SERVIR DEPOIS!', 'Cortar
> em dois'] qt: 1.0 kot: 0 dp status: 0
I've numerated the lines just to show how the problem is: lines 2 and 4 should
be hidden because are just intermediate steps. Then the results I need should
be:
ID ORDER PRODUCT INSTR QTY
12811 4419 "Crudo GR" 1.0
12812 4419 "Salame e Grana GR" 1.0
12814 4419 "Nutella Ban GR" "!SERVIR DEPOIS! Cortar em dois" 1.0
Could someone gently tell me where is the error in my code and how to put the
correct print statement? Please note I'm relatively new on Python, have mercy.
Thanks.
**Edit: solved with a more simple approach based on the hints of Merlin.**
The code wrote by Merlin is complicated to setup for me due to the many
variant I have. I rewrote part of my script in a more basic way. In this
version I've reverted the lines of the fetch to grab and add to the respective
line all the instructions (#) I need after the product in a temp table. Then I
reversed again the lines to check if there is a line '----' before a product
and add to the respective product, last I wrote to the final table. This
script is much simple to read (for a newbie like me) and avoid the use of
'operator' module simply reversing a table with [::-1].
TableTemp = []; newTable = []; Instr = ''
for line in fetch_lines[::-1]:
if line[2].startswith('#') or line[2].startswith('----'):
if line[2].startswith('#'):
Instr = line[2][2:]+' | '+ Instr
if line[2].startswith('----'):
TableTemp.append((line[0], line[1], line[2], '', line[3], line[4]))
else:
TableTemp.append((line[0],line[1],line[2], Instr, line[3], line[4]))
Instr = ''
for line in TableTemp[::-1]:
if line[2].startswith('----'):
Instr = '!SERVIR DEPOIS! | '
else:
newTable.append((line[0],line[1],line[2], Instr+line[3][:-3], line[4], line[5]))
Instr = ''
Result:
Inner fetch:
(13264, 4558, 'Funghi GR', Decimal('1.0'), 'Mesa 11')
(13265, 4558, '# + Champinhons', Decimal('1.0'), 'Mesa 11')
(13266, 4558, '# + Alface', Decimal('1.0'), 'Mesa 11')
(13267, 4558, '# - R\xc3\xbacola', Decimal('1.0'), 'Mesa 11')
(13268, 4558, 'Formaggi GR', Decimal('1.0'), 'Mesa 11')
(13269, 4558, '# Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13270, 4558, '---- servir depois ----', Decimal('1.0'), 'Mesa 11')
(13271, 4558, 'Nutella GR', Decimal('1.0'), 'Mesa 11')
(13272, 4558, '# Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13273, 4558, '---- servir depois ----', Decimal('1.0'), 'Mesa 11')
(13274, 4558, 'Nutella Mor MD', Decimal('1.0'), 'Mesa 11')
(13275, 4558, '# Para Levar', Decimal('1.0'), 'Mesa 11')
Output table:
(13264, 4558, 'Funghi GR', '+ Champinhons | + Alface | - R\xc3\xbacola', Decimal('1.0'), 'Mesa 11')
(13268, 4558, 'Formaggi GR', 'Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13271, 4558, 'Nutella GR', '!SERVIR DEPOIS! | Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13274, 4558, 'Nutella Mor MD', '!SERVIR DEPOIS! | Para Levar', Decimal('1.0'), 'Mesa 11')
Answer: Its seems you have two tables. This way you only making 2 trips to the
database vs many.
Do a fetches -- to get data from tables
Table one
ID ORDER PRODUCT QTY CAT
12811 4419 "Crudo GR" 1.0 1
12812 4419 "Salame e Grana GR" 1.0 1
12813 4419 "---- servir depois ----" 1.0 7
12814 4419 "Nutella Ban GR" 1.0 3
12815 4419 "# Cortar em dois" 1.0 7
get the data as table,
newTable = []
Intr = ''
#Added something like
#http://www.saltycrane.com/blog/2007/12/how-to-sort-table-by-columns-in-python/
#import operator
#fetch_lines = sorted(fetch_lines, key=operator.itemgetter(col))
#Sort table so looks like this
# ID ORDER PRODUCT QTY CAT
# 12815 4419 "# Cortar em dois" 1.0 7
# 12813 4419 "---- servir depois ----" 1.0 7
# 12811 4419 "Crudo GR" 1.0 1
# 12812 4419 "Salame e Grana GR" 1.0 1
# 12814 4419 "Nutella Ban GR" 1.0 3
for i,line in enumerate(fetch_lines):
if line[2].startswith('#') or line[2].startswith('----'):
# Within this if statement you can make adjustment to text item
if line[2].startswith('#')
Intr = Intr + " Cortar em dois"
if line[2].startswith('----')
Intr = '!SERVIR DEPOIS!' + Intr
if i == len(fetch_lines) -1:
newTable.append([line[0], ....., Intr , ...])
if i < len(fetch_lines)
newTable.append([line[0], ....., '', ...])
print table
#Then sort by first column so table look right
#table = sorted( newTable, key=operator.itemgetter(col))
#ID ORDER PRODUCT INSTR QTY
#12811 4419 "Crudo GR" 1.0
#12812 4419 "Salame e Grana GR" 1.0
#12814 4419 "Nutella Ban GR" "!SERVIR DEPOIS! Cortar em dois" 1.0
Try This to place Intr in last row:
newTable = []
Intr = ''
LineCt = 0
for line in fetch_lines:
if line[2].startswith('#') or line[2].startswith('----'):
# Within this if statement you can make adjustment to text item
if line[2].startswith('#'):
Intr = Intr + " Cortar em dois"
LineCt +=1
if line[2].startswith('----'):
Intr = '!SERVIR DEPOIS!' + Intr
LineCt +=1
for i,line in enumerate(fetch_lines):
if line[2].startswith('#') or line[2].startswith('----'): pass
elif i == len(fetch_lines) - LineCt:
newTable.append([line[0],line[1], line[2], Intr , "" ])
Intr = ''
elif i < len(fetch_lines):
newTable.append([line[0],line[1],line[2], '', "" ])
print Intr
for e in newTable: print e
Output:
[12811, 4419, 'Crudo GR', '', '']
[12812, 4419, 'Salame e Grana GR', '', '']
[12814, 4419, 'Nutella Ban GR', '!SERVIR DEPOIS! Cortar em dois', ''
]
|
How to download a specific file type from all subdirectories of an FTP server?
Question: I am trying to download all `.laz` files from the FTP host `gis.arkansas.gov`
(more details [here](http://gis.arkansas.gov/?page_id=7813)). Looking at the
[`ftplib`](https://docs.python.org/2.7/library/ftplib.html) documentation, I
see that I can list all of the directories in the FTP server:
from ftplib import FTP
ftp = FTP('gis.arkansas.gov')
ftp.login()
ftp.cwd('Elevation')
ftp.retrlines('LIST')
* * *
Which yields the following:
>>> ftp.retrlines('LIST')
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 AGFC_RAW
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 AR State Parks
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 Bayou Meto Lidar Phase I
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 Bayou_Meto_Watershed
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 Beaver_Lake
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 Beaver_Tailwater
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 Black_River
drwxr-xr-x 1 ftp ftp 0 May 30 09:24 Blue_Mountain
# ... And so on ...
How can I download all of the files with a .laz extension from each of these
directories (some directories do not contain .laz files)?
Answer: There's no magic.
You have to:
* recurse into the subdirectories,
* list their contents one by one,
* filter all `.laz` files,
* call `retrbinary` for each.
|
Python: interpreter says "None" after parsing file
Question: I've written a simple interpreter with Python for a programming language I've
created. I have a little problem though: when I try to read a file, so the
code can be interpreted, Python says `None`.
Here's the interpreter code:
import sys
class Interpret:
def read(self, cmd):
tokens = cmd.split("\n")
for i in range(0, len(tokens)):
self.parse(tokens[i])
def parse(self, cmd):
if cmd.startswith("print(") and cmd.endswith(")"):
cmd = cmd[6:]
cmd = cmd[:-1]
return(cmd)
interpret = Interpret()
code = open(sys.argv[1], 'r')
print(interpret.read(str(code)))
Here's the code in the file I want to read: `print(Hi)\n` (Yes, there's a
newline there, not the characters `\n`)
So, here's what happened in CMD:
> python interpreter.py test.tl
None
It should output `Hi`, but it doesn't work properly. I think it has something
to do with the last two lines of the interpreter code, but I'm not completely
sure.
Answer: You're just _calling_ `self.parse` and not using its return value and, given
that `self.parse` doesn't output anything and `read` returns nothing (`None`),
you're getting `None` as a result.
You may want your `read` to `yield self.parse(tokens[i])` on each iteration,
thus making it a generator, and then do something like this:
for data in interpret.read(str(code)):
print(data)
|
Mock urlilb+json in Python
Question: looking for a way to correctly mock this piece of code:
import json
from urllib import urlopen
a_url = "http://blabla"
my_response= urlopen(a_url)
a_dict = json.loads(my_response.read())
It reads from an URL, then the response uses json.loads to store everything in
a dict. Ideas?
Answer: `urlopen` should return a mock object where `.read()` returns a string
containing JSON, e.g. `'{"a": "b"}'`.
Then throw it all away and use `requests`.
|
Subsets and Splits