text
stringlengths 226
34.5k
|
---|
python read text from table scraping
Question: I need a value from table with website
My Python Code
import sys
import getopt
import linecache
import string
import ftplib
import os
import requests
from lxml import html
import datetime
page = requests.get(URL)
tree = html.fromstring(page.content)
all_id = tree.xpath('//td[@style="display:none> >"]/text()')
print 'Wszystkie ID:', all_id
website Code
<td style="display:none">id>277918954,id32>c14f940e3eed6a3871e1e3376048303f,level>0,key_left>0,key_right>0,name>file.png,type>File png,size>139.27 KB,hash>538dd38791b76170ab71feec9ef6fed5</td>
I'm view only error, where is problem?
Answer: > `//td[@style="display:none> >"]/text()`
This would not match the presented element, this would:
//td[@style="display:none"]/text()
Though, this expression does not seem reliable.
To provide you with a reliable locator, we would need to see the complete HTML
of the page, but, given what we have, how about checking that the text _starts
with_ `id`:
//td[starts-with(., "id")]/text()
|
TypeError: coercing to Unicode: need string or buffer, file found?
Question: I am having problems with a very early prototype of a simple chat bot that
will use the conversation that it is having to add to a database of responses
that it can use later.
import sys,time,random, os.path
typing_speed = 50 #wpm
def slow_type(t):
for l in t:
sys.stdout.write(l)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print ''
slow_type("Hello! My name is TUTAI, or Turing Test Artificial Intelligance")
slow_type("Currently I am in training, so my features arent fully complete.")
slow_type("If you say something I don't understand yet, I will repeat it back to you in order for me to learn and build a databace of responces!")
talk = raw_input()
talk = talk + ".txt"
existance = True
try:
talk = open(talk, "r")
except:
existance = False
talk.close()
if existance == True:
talkBack = open(talk, "r")
print talkBack.read()
However, when I run the program, I get this response(yes I checked that the
file exists).
Hello! My name is TUTAI, or Turing Test Artificial Intelligence
Currently I am in training, so my features aren't fully complete.
If you say something I don't understand yet, I will repeat it back to you in order for me to learn and build a database of responses!
(I type)Hello
Traceback (most recent call last):
File "H:\TUTAI\firstPythonScript.py", line 31, in <module>
talkBack = open(talk, "r")
TypeError: coercing to Unicode: need string or buffer, file found
Thank You! (I know I imported a bunch of stuff I don't need. Pls don't mention
that.)
Answer: My guess is that by that point in the program, the 'talk' variable is a file
handle, not a string. I would discourage the kind of variable re-use seen here
as it leads to exactly the problem you are having.
Your code progression:
talk = raw_input() #string
talk = talk + '.txt' #string
talk = open(talk, 'r') #file handle
talkBack = open(talk, "r") #error, talk is still file handle
|
Unable to automate git fetch && git checkout using python
Question: I have automated the process of git checkout a particular branch which a user
want to enter. I am using the following python code with subprocess to do so ,
from bitbucket.bitbucket import Bitbucket
from sys import argv
import subprocess
prompt = '> '
print "Enter the name of branch you need to clone: "
user_branch = raw_input(prompt)
print "You Entered: ",user_branch
print "this will do a git status"
cmd = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE)
output = cmd.communicate()[0]
print output
#for line in output: # output.split("\n"):
if ("Untracked files:" or "Changes not staged for commit") in output:
print "Need to do a Git stash"
subprocess.Popen(["git", "stash"])
subprocess.Popen(["git fetch && git checkout"+(user_branch)])
else:
print "simply do git checkout userbranch"
subprocess.Popen(["git","pull"])
subprocess.Popen(["git fetch && git checkout"+(user_branch)])
This throws :
Enter the name of branch you need to clone:
> release_4_0
You Entered: release_4_0
this will do a git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
simply do git checkout userbranch
Traceback (most recent call last):
File "git_updater.py", line 25, in <module>
subprocess.Popen(["git fetch && git checkout"+(user_branch)])
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I want to input just the branch name that user wants to checkout . Does this
makes sense ?
Answer:
subprocess.Popen(["git fetch && git checkout"+(user_branch)])
should be
subprocess.Popen("git fetch && git checkout %s"%user_branch,shell=True)
or you could do somehting like
subprocess.Popen(["git", "fetch"]).communicate()
subprocess.Popen(["git", "checkout", user_branch])
the problem is if the argument is a list it expects comma separated file and
arguments (and im not sure how the && would work)
|
How to configure Sphinx auto flask to document flask-restful API?
Question: I have a flask app that I want to use Sphinx's autoflask directive to document
a flask-restful API.
<https://pythonhosted.org/sphinxcontrib-httpdomain/#module-
sphinxcontrib.autohttp.flask>
I have installed the module via pip and run sphinx-quickstart, which gives me
a conf.py and index.rst.
I've tried putting the extension into conf.py:
extensions = ['sphinxcontrib.autohttp.flask']
and the directive into index.rst as per the documentation:
.. autoflask:: autoflask_sampleapp:app
:undos-static:
But I can't get the app:module (autoflask_sampleapp:app) part correct. As a
result, when I run sphinx-build I get an error that either the app or the
module are not found.
My app trees looks like this:
.
├── admin
├── apis
├── app
│ ├── static
│ └── templates
and from the app's root directory, I can say:
from apis import profile
How do I configure auto flask in the index.rst to correctly find and load my
app's API modules?
Answer: My code structure, where application.py file with flask app, I run my server
python appllication.py runserver
├── application.py
├── _build
│ ├── doctrees
│ │ ├── environment.pickle
│ │ └── index.doctree
│ └── html
│ ├── genindex.html
│ ├── http-routingtable.html
│ ├── index.html
│ ├── objects.inv
│ ├── search.html
│ ├── searchindex.js
│ ├── _sources
│ │ └── index.txt
│ └── _static
├── conf.py
├── index.rst
In conf.py you should include extensions and include abs path to you
application.py or any other main flask app file in your project.
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinxcontrib.autohttp.flask',
'sphinxcontrib.autohttp.flaskqref'
]
After you can use blueprints, views from your flask app
My documentation!
=======================================
.. qrefflask:: application:application
:undoc-static:
=======================================
Api details!
=======================================
.. autoflask:: application:application
:undoc-static:
In other words, before run make html, you should add abs path to you root
application folder via python sys path sys.path.insert(0,
os.path.abspath('/home/myproject/')), where /home/myproject folder with your
source code.
|
Sound output is present in sound input even with no mic in linux
Question: I'm trying to simultaneously play a sound and record voltage output from a
piezo sensor. For this, I connect my sound board analog outputs to speakers,
and my sound board analog input to a piezo sensor.
When I record signal from the sensor but playing no sound, it works perfectly.
But, when I play a sound during the recording, I can see the sound I'm playing
in the sensor's signal, as if the output and input of the sound board were
connected. The most strange is that even when I unplug the sensor, the output
signal is still present in the recording.
In other words, the problem is: I start recording, when I start playing the
sound it appears in the sensor's signal (even with speakers turned off).
I'm using only ALSA, pulseaudio is not installed. I'm using python (and
pyaudio) to generate sound signal, write the signal to sound board outputs and
read data from sound board input. I also tested in Audacity, but the result
was the same. I also tested with arecord:
$ arecord --channel=1 --rate=128000 --format=S32_LE Test.wav
And then:
$ mplayer Audio/Alarms/Annoying_Alien_Buzzer-Kevan-1659966176.mp3
And then stopped the recording. When I play Test.wav, all the sound signal
from the played file is there.
I know it may sound obvious, but I want to say that there is NO MIC connected
anywhere in the setup.
Here is some info:
====================
Box:
$ uname -a
Linux MalfattiTux 4.1.12-gentoo #3 SMP Thu Jan 21 17:24:27 BRST 2016 x86_64 Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz GenuineIntel GNU/Linux
Audio boards:
$ lspci | grep -i audio
00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)
00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 05)## Heading ##
Output devices:
$ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: HDMI [HDA Intel HDMI], device 3: HDMI 0 [HDMI 0]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 0: HDMI [HDA Intel HDMI], device 7: HDMI 1 [HDMI 1]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 0: HDMI [HDA Intel HDMI], device 8: HDMI 2 [HDMI 2]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 1: PCH [HDA Intel PCH], device 0: ALC3239 Analog [ALC3239 Analog]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 1: PCH [HDA Intel PCH], device 1: ALC3239 Digital [ALC3239 Digital]
Subdevices: 1/1
Subdevice #0: subdevice #0
Input devices:
$ arecord -l
**** List of CAPTURE Hardware Devices ****
card 1: PCH [HDA Intel PCH], device 0: ALC3239 Analog [ALC3239 Analog]
Subdevices: 1/1
Subdevice #0: subdevice #0
Python code to play and record (minimal working example):
import array
import pyaudio
import random
Rate = 128000
SoundPulseDur = 5 # in seconds
print('Generating sound pulse...')
SoundNoise = [random.random() for _ in range(round(Rate*SoundPulseDur))]
SoundPulse = [SoundNoise[ElI]*2-1 for ElI,ElV in enumerate(SoundNoise)]
SoundPulse[-1] = 0
print('Interleaving channels...')
SoundList = [0]*(2*len(SoundPulse))
for _ in range(len(SoundPulse)):
SoundList[_ *2] = SoundPulse[_]
SoundList[_ *2+1] = 0
Sound = array.array('f')
Sound.fromlist(SoundList)
Sound = bytes(Sound)
print('Generating sound objects...')
# Output
p = pyaudio.PyAudio()
Stimulation = p.open(format=pyaudio.paFloat32,
channels=2,
rate=Rate,
output=True)
# Input
q = pyaudio.PyAudio()
InOn = False
RecStop = True
def InCallBack(in_data, frame_count, time_info, status):
if InOn:
global SoundRec
SoundRec.append(in_data)
if RecStop:
InFlag = pyaudio.paComplete
else:
InFlag = pyaudio.paContinue
return(None, InFlag)
Reading = q.open(format=pyaudio.paFloat32,
channels=1,
rate=Rate,
input=True,
output=False,
stream_callback=InCallBack)
SoundRec = []
Reading.start_stream()
RecStop = False; InOn = True
Stimulation.write(Sound)
InOn = False; RecStop = True
Reading.stop_stream()
Answer: This sound like electric noise from your sound-card. I take it you're using an
onboard card? If so, there's not much you can do to avoid recording the noise,
unless you want to buy a better/external sound-card.
As to an actual solution; **Personally, I would record my audio output, and
use that audio data to cancel the noise from the piezo sensor data.**
This should theoretically also be possible to do live, if you can read your
sound output to the piezo recording script with for example
[PyAudio](http://people.csail.mit.edu/hubert/pyaudio/ "PyAudio")
|
Trying to set a variable from a value in a dictionary
Question: I'm learning python and am creating a rock paper scissors game.
I'm stuck on one part.
I have 4 variables currently (Although I would like to get it down to 2)
* pKey
* pChoice
* comKey
* comChoice
They look up the the Key and Value respectively in a dictionary.
choice = {1:'rock', 2:'paper', 3:'scissors'}
The problem I'm having is getting the keys from the dictionary using the
variables.
Here's the code snippet that's giving me trouble
print('--- 1 = Rock 2 = Paper 3 = Scissors --- ')
pKey = input() # this is sets the key to the dictionary called choice
while turn == 1: # this is the loop to make sure the player makes a valid choice
if pKey == 1 or 2 or 3:
pChoice = choice.values(pKey) # this calls the value from choice dict and pKey variable
break
else:
print('Please only user the numbers 1, 2 or 3 to choose')
comKey = random.randint(1, 3) # this sets the computer choices
comChoice = choice.values(comKey)
Specifically the troublesome part is
pChoice = choice.values(pKey)
and
comChoice = choice.values(comKey)
I've tried everything I know from using brackets, trying different methods,
and using different formats.
Would love to learn this! Thanks!
Answer: Sounds like you're just trying to do a dictionary lookup
pKey = 1
pChoice = choices[pKey] # rock
`dict.values` is used to create a list (actually a `dict_values` object) with
all the values of the dictionary. It's not used as a lookup.
* * *
As far as your code structure goes, it could use some work. The
rock/paper/scissors choice is perfect for an `Enum`, but that might be a bit
beyond you right now. Let's just try as a toplevel module constant.
ROCK = "rock"
PAPER = "paper"
SCISSORS = "scissors"
def get_choice():
"""get_choice asks the user to choose rock, paper, or scissors and
returns their selection (or None if the input is wrong).
"""
selection = input("1. Rock\n2. Paper\n3. Scissors\n>> ")
return {"1": ROCK, "2": PAPER, "3": SCISSORS}.get(selection)
Addressing them as constants makes sure they're the same everywhere in your
code, or else you get a very clear NameError (instead of an if branch not
executing because you did `if comChoice == "scisors"`)
* * *
A minimal example with an enum looks like:
from enum import Enum
Choices = Enum("Choices", "rock paper scissors")
def get_choice():
selection = input(...) # as above
try:
return Choices(int(selection))
except ValueError:
# user entered the wrong value
return None
You could extend this by using the more verbose definition of the Enum and
teach each Choice instance how to calculate the winner:
class Choices(Enum):
rock = ("paper", "scissors")
paper = ("scissors", "rock")
scissors = ("rock", "paper")
def __init__(self, loses, beats):
self._loses = loses
self._beats = beats
@property
def loses(self):
return self.__class__[self._loses]
@property
def beats(self):
return self.__class__[self._beats]
def wins_against(self, other):
return {self: 0, self.beats: 1, self.loses: -1}[other]
s, p, r = Choices["scissors"], Choices["paper"], Choices["rock"]
s.wins_against(p) # 1
s.wins_against(s) # 0
s.wins_against(r) # -1
Unfortunately there's no great way to lose the abstraction in that
(abstracting out "paper" to Choices.paper every time it's called) since you
don't know what `Choices["paper"]` is when `Choices.rock` gets instantiated.
|
Pandas Merge vs. Boolean Indexing
Question: I'm using pandas in Python 3.4 to identify matches between two data frames.
Matches are based on strict equality except for the last column, where close
matches (+/- 5) are fine.
One data frame contains many rows, and the second is just a single row in this
case. The desired result is a data frame containing a subset of the first data
frame which match the row, as mentioned.
I went with the concrete solution of boolean indexing first, but this took a
while to chug through all of the data, so I tried out the pandas merge
function. However, my implementation of merge is even slower on my test data.
It runs between 2 and 4 times slower than the boolean indexing.
Here is a test run:
import pandas as pd
import random
import time
def make_lsts(lst, num, num_choices):
choices = list(range(0,num_choices))
[lst.append(random.choice(choices)) for i in range(0,num)]
return lst
def old_way(test, data):
t1 = time.time()
tmp = data[(data.col_1 == test.col_1[0]) &
(data.col_2 == test.col_2[0]) &
(data.col_3 == test.col_3[0]) &
(data.col_4 == test.col_4[0]) &
(data.col_5 == test.col_5[0]) &
(data.col_6 == test.col_6[0]) &
(data.col_7 == test.col_7[0]) &
(data.col_8 >= (test.col_8[0]-5)) &
(data.col_8 <= (test.col_8[0]+5))]
t2 = time.time()
print('old time:', t2-t1)
def new_way(test, data):
t1 = time.time()
tmp = pd.merge(test, data, how='inner', sort=False, copy=False,
on=['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7'])
tmp = tmp[(tmp.col_8_y >= (test.col_8[0] - 5)) & (tmp.col_8_y <= (test.col_8[0] + 5))]
t2 = time.time()
print('new time:', t2-t1)
if __name__ == '__main__':
t1 = time.time()
data = pd.DataFrame({'col_1':make_lsts([], 4000000, 7),
'col_2':make_lsts([], 4000000, 3),
'col_3':make_lsts([], 4000000, 3),
'col_4':make_lsts([], 4000000, 5),
'col_5':make_lsts([], 4000000, 4),
'col_6':make_lsts([], 4000000, 4),
'col_7':make_lsts([], 4000000, 2),
'col_8':make_lsts([], 4000000, 20)})
test = pd.DataFrame({'col_1':[1], 'col_2':[1], 'col_3':[1], 'col_4':[4], 'col_5':[0], 'col_6':[1], 'col_7':[0], 'col_8':[12]})
t2 = time.time()
old_way(test, data)
new_way(test, data)
print('time building data:', t2-t1)
On my most recent run I see the following:
# old time: 0.2209608554840088
# new time: 0.9070699214935303
# time building data: 75.05818915367126
Note that even the new method with the merge function uses boolean indexing on
the last column dealing with the range of values, but I thought the merge
might be able to do the heavy lifting in the problem. This is clearly not the
case since the merge on the first columns takes up almost all of the time used
in the new method.
Is it possible to optimize my implementation of the merge function? (Coming
from R and data.table, I spent 30 minutes unsuccessfully searching for a way
to set the key in a pandas data frame.) Is this just a problem that merge
isn't good at handling? Why is boolean indexing faster than merge in this
example?
I don't fully understand the memory backend of these approaches, so any
insight is appreciated.
Answer: While you can merge on any set of columns, the performance of the merge is
going to be best when you are merging on indexes.
If you replace
tmp = pd.merge(test, data, how='inner', sort=False, copy=False,
on=['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7'])
with
cols = ['col_%i' % (i+1) for i in xrange(7)]
test.set_index(cols, inplace=True)
data.set_index(cols, inplace=True)
tmp = pd.merge(test, data, how='inner', left_index=True, right_index=True)
test.reset_index(inplace=True)
data.reset_index(inplace=True)
Does that run faster? I haven't tested it, but I think that should help...
By indexing the columns you want to merge, the DataFrame will organize the
data under the hood in such a way that it knows where to finds values much
more quickly than if the data is simply in ordinary columns.
|
sFrame into scipy.sparse csr_matrix
Question: I have a sframe like:
x = sf.SFrame({'users': [{'123': 1.0, '122': 5},
{'134': 3.0, '123': 10}]})
I want to convert into scipy.sparse csr_matrix without invoking graphlab
create, but only using sframe and Python.
How to do it?
Answer: Assuming you want the row number to be the row index in the output sparse
matrix, the only tricky step is using `SFrame.stack` \- from there you should
be able to construct a `csr_matrix` directly.
import sframe as sf
from scipy.sparse import csr_matrix
x = sf.SFrame({'users': [{'123': 1.0, '122': 5},
{'134': 3.0, '123': 10}]})
x = x.add_row_number('row_id')
x = x.stack('users')
A = csr_matrix((x['X3'], (x['row_id'], x['X2'])),
shape=(2, 135))
I'm also hard-coding the dimension of the matrix here, but that's probably
something you'd want to figure out programmtically.
|
Attempting to run multiple simulations of the Gillespie algorithm for a set of stochastic chemical reactions, in Python, in less than 10 minutes
Question: I have written Python code that generates a plot. In the code below, when I
set `maxtime = 0.1`, the program takes ~50s and when I set `maxtime = 1`, it
takes ~420s. I need to run it for `maxtime = 1000`.
I am familiar with Python syntax and writing "Matlabic" code, but am lost in
writing natively "Pythonic" code. As a result, I need help in **optimizing
this code for runtime, specifically in the two outer`for` loops and inner
`while` loop.**
1. How can I make the code suitable for use with Numba or Cython?
2. If that's not possible, do I need to use functions, or `map`, or `lambda` statements?
Unfortunately, my Spyder IDE for Python is freezing up everytime I try to
profile the code. I would include those details if I could!
The code is below. Thanks.
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
import math
maxtime = 1
Qpvec = np.logspace(-2,1,101,10)
lenQp = len(Qpvec)
delta = 1e-3
P0vec = Qpvec/delta
SimNum = 100
PTotStoch = np.zeros((SimNum,lenQp))
k_minus = 1e-3
k_cat = 1-1e-3
k_plus = 1e-3
zeta = 1e-4
D0 = 10000
kappa_M = (k_cat+k_minus)/zeta
QpDeg = np.true_divide(1000*D0*Qpvec*k_cat,1000*Qpvec + kappa_M)
for lenQpInd in range(0,lenQp):
for SimNumInd in range(0,SimNum):
Qp = Qpvec[lenQpInd]
P0 = P0vec[lenQpInd]
DP0 = 0
P = math.floor(P0)
DP = DP0
D = D0
time = 0
while time < maxtime:
u_time = pl.rand()
u_event = pl.rand()
rates=np.array([Qp,zeta*P*D,k_minus*DP,k_cat*DP])
PTot = P + DP
kT = np.sum(rates)
tot = np.cumsum(rates)
deltaT = -np.log(1-u_time)/kT
time += deltaT
if time > maxtime:
PTotStoch[SimNumInd,lenQpInd] = PTot
break
elif u_event*kT < tot[0]:
P += 1
elif u_event*kT < tot[1]:
P -= 1
DP += 1
D -= 1
elif u_event*kT < tot[2]:
P += 1
DP -= 1
D += 1
elif u_event*kT < tot[3]:
DP -= 1
D += 1
PMean = PTotStoch.mean(axis=0)
PStd = PTotStoch.std(axis=0)
plt.figure(0)
plt.plot(Qpvec,PMean,marker=".")
plt.errorbar(Qpvec,PMean,yerr = 2*PStd, xerr = None)
plt.show()
Answer: You can try compiling with [PyPy](http://pypy.org/). It doesn't look like
matplotlib is supported so you may have to include this part in a separate
file.
|
Setting x axis label to bottom in openpyxl
Question: The label on the x axis that is the years, I want to set the years to the
bottom of the chart.[](http://i.stack.imgur.com/oxz6R.png)
The data for the chart above is:
>>> plot_data
[[1901, 0.41391], [1902, -0.58147], [1903, -0.52587], [1904, -0.48694], [1905, 1.23691], [1906, -0.55923], [1907, -0.12549], [1908, 1.35925], [1909, 0.82541], [1910, 0.44728], [1911, 1.01448], [1912, 0.55293], [1913, -0.58147], [1914, -0.58147], [1915, 0.91439], [1916, -0.58147], [1917, -0.57591], [1918, -0.18666], [1919, -0.24783], [1920, -0.00315], [1921, 1.34257], [1922, -0.24783], [1923, -0.58147], [1924, 0.49732], [1925, -0.58147], [1926, -0.35904], [1927, -0.58147], [1928, -0.15329], [1929, -0.54811], [1930, 1.72626], [1931, -0.58147], [1932, -0.58147], [1933, -0.57035], [1934, 0.94219], [1935, 1.00336], [1936, -0.53699], [1937, -0.58147], [1938, -0.51474], [1939, -0.54811], [1940, 0.4862], [1941, 0.13031], [1942, 0.13587], [1943, 1.58724], [1944, 0.3583], [1945, 0.45284], [1946, -0.58147], [1947, -0.44801], [1948, 1.17574], [1949, -0.58147], [1950, -0.53699], [1951, -0.49806], [1952, -0.55923], [1953, 1.03116], [1954, -0.47026], [1955, 0.02465], [1956, -0.57591], [1957, 2.03767], [1958, -0.53143], [1959, -0.35348], [1960, -0.53699], [1961, 0.56405], [1962, 0.89214], [1963, -0.17553], [1964, -0.58147], [1965, -0.58147], [1966, -0.58147], [1967, -0.58147], [1968, 0.85322], [1969, -0.57035], [1970, -0.54811], [1971, -0.42021], [1972, 0.30826], [1973, -0.37016], [1974, -0.57035], [1975, -0.52587], [1976, -0.58147], [1977, 0.06358], [1978, -0.58147], [1979, 0.08026], [1980, -0.58147], [1981, -0.35904], [1982, 0.21372], [1983, 0.32494], [1984, -0.52031], [1985, 0.21372], [1986, -0.19778], [1987, -0.25895], [1988, -0.38685], [1989, -0.42021], [1990, -0.58147], [1991, 8.16013], [1992, -0.13105], [1993, -0.58147], [1994, 1.11457], [1995, 0.70307], [1996, -0.58147], [1997, -0.58147], [1998, -0.58147], [1999, -0.15329], [2000, -0.15329], [2001, -0.54811], [2002, 0.3305], [2003, 0.36386], [2004, -0.2089], [2005, -0.58147], [2006, -0.58147], [2007, -0.58147], [2008, -0.58147], [2009, -0.58147], [2010, 0.33606], [2011, -0.58147], [2012, 0.77536], [2013, -0.33124]]
And the code for displaying the chart above is as following:
import arcpy
from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference
wb = Workbook()
ws = wb.create_sheet()
for row in plot_data:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Rainfall anomaly"
chart1.y_axis.title = "Rainfall"
chart1.x_axis.title = "Years"
chart1.y_axis.scaling.min = -3
chart1.y_axis.scaling.max = 3
dataxl = Reference(ws, min_col=2, min_row=1, max_row=data.shape[0], max_col=2)
cats = Reference(ws, min_col=1, min_row=1, max_row=data.shape[0])
chart1.add_data(dataxl)
chart1.set_categories(cats)
ws.add_chart(chart1, "A10")
wb.save("D:/RainfallAnomaly/PythonScript/ScriptOutput/testingv11.xlsx")
I want the output to look somewhat like below:
[](http://i.stack.imgur.com/IO8Fv.png)
Answer: This is an interesting question. There are so many possibilities for
formatting charts in Excel that we can't cover them all in the documentation.
However, openpyxl does expose nearly all the possibilities of the format. So,
as long as you're prepared to spend a little time looking at the source of the
chart, then you should be able to create similar charts with openpyxl.
First things first: the x-axis. Formatting axes in Excel is quite simply
weird. First of all I had too lookup how to do this in the first place because
the options on offer didn't suggest it. Once you know this, it's quite easy:
chart1.x_axis.tickLblPos = "low"
chart1.x_axis.tickLblSkip = 3 # whatever you like
Secondly, highlighting negative values. This is done using the
"invertIfNegative" property. The formatting for individual series or even
individual data points is possible. Series are accessed by index from the
chart's series object.
chart1.series[0].invertIfNegative = True
However, using a second colour for the negative values requires an extension
to the specification and these are currently not supported by openpyxl. Or
indeed by many clients (it's not possible to set this option in Excel 2011 for
Mac for example, though it can read it. The relevant XML, for reference.
Almost all of it is registering the extension "invertSolidFillFmt".
<c:extLst xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart">
<c:ext xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart" uri="{6F2FDCE9-48DA-4B69-8628-5D25D57E5C99}">
<c14:invertSolidFillFmt>
<c14:spPr xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<a:solidFill xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<a:srgbClr val="FF0000" />
</a:solidFill>
</c14:spPr>
</c14:invertSolidFillFmt>
</c:ext>
</c:extLst>
|
Embedding Python within C++ (CPython API)
Question: I'm trying to embed Python within my C++ project (Qt5). My project looks like
this:
python_test.pro:
QT += core
QT -= gui
TARGET = python_test
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
INCLUDEPATH += C:\Tools\Python\Python35_64\include
LIBS += -LC:\Tools\Python\Python35_64\ -lpython3
main.cpp:
#include <Python.h>
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
Py_Finalize();
return a.exec();
}
When compiling I get a linker error telling me this: `main.cpp:-1: Error:
undefined reference to `__imp_PyRun_SimpleStringFlags'`.
The funny thing is that `Py_Initialize()` and `Py_Finalize()` can be found. I
read something about the define `Py_LIMITED_API` which hides the function
PyRun_SimpleStringFlags. But I don't get it.
How am I supposed to run a Python script/file/string without these functions
being available within the C API?
Setup:
* Win7 Prof 64 bit
* Qt 5.5.1
* g++.exe (Rev1, Built by MSYS2 project) 5.3.0
* Python 3.5.1 64-bit (prebuilt from <https://www.python.org/downloads/release)/python-351/>)
Answer: I tested this on my computer (without Qt though), with `-lpython35` compiling
succeeded and with `-lpython3` it did not.
So
LIBS += -LC:\Tools\Python\Python35_64\ -lpython35
instead of
LIBS += -LC:\Tools\Python\Python35_64\ -lpython3
|
Java import statement not at the beginning of the file
Question: In python, the import statement can be placed everywhere in the file, even
inside a _class_ , or an _if_.
Is there a way to accomplish the same thing in _Java_? I understand that it
could be a bad practice not to put all the imports at the top of the file, I'm
just wondering if it is possible in some way or not.
Answer: The very first statement in a Java file must be (if there is one) the package
statement, followed by the import statements.
They can not be placed in another location.
However, it is possible to use an alternative way (which I personally don't
recommend)
import myPackage.MyClass;
public class Test{
private MyClass instance = new MyClass();
}
can be rewritten as:
public class Test{
private myPackage.MyClass instance = new myPackage.MyClass();
}
There is no import statement needed anymore (which comes in handy if you need
to use two classes with the same name within one Java file), but you put the
entire path to the class, including package in the declaration/initialization
of the variables.
In this way, they can be about anywhere in the code.
|
How to have Pyramid invoke_subrequest to go through view_config context routing for error handling
Question: We are using
[`request.invoke_subrequest()`](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/subrequest.html)
to run a view from Python code.
We would like the `subrequests` responses to go through the views defined for
errors (`context routing`).
For example, if we define several error views like this one:
@view_config(context=requests.exceptions.HTTPError)
def response_error(context, request):
if context.response.status_code == 412:
return httpexceptions.HTTPPreconditionFailed()
# [...]
How do you execute it when using `subrequests` for each kind of `context`
without having to add an except close for each kind?
Ideally, we'd like to obtain something like that (e.g. imaginary
`view_lookup()` function):
try:
subresp = request.invoke_subrequest(subrequest)
except Exception as e:
subresp = view_lookup(e)(subrequest)
Using `use_tweens=True` in `invoke_subrequest()` doesn't seem to execute the
error views either.
Is there a way to explicitly call a `view lookup` so that we obtain the
`subresponse` as if it would have gone through `view_config` errors handlers?
Answer: What you are looking for is probably: `pyramid.view.render_view_to_response`
from pyramid.view import render_view_to_response
try:
subresp = request.invoke_subrequest(subrequest)
except Exception as e:
subresp = render_view_to_response(e, subrequest)
|
Python command line argument defaults
Question: I just wondered if there was a simple way to set a python command-line
argument using sys.argv as a default. For example;
sys.argv[2] = "defaultValue"
I know that in some other languages, you can do the following if it's blank;
var myVar = "someValue" | "";
I am fairly new to Python but would love a simple solution to this. Thanks in
advance ;)
Answer: You can top up the argument list so you have at least two arguments and then
assign the correct value to `argsv[2]`:
import sys
sys.argv= sys.argv + ["" for x in range(2) ]
sys.argv[2]="defaultValue"
print sys.argv
|
Reading table data (card images), with format specifier given, into Python
Question: I am trying to read in a ascii-table into Numpy/Pandas/Astropy
array/dataframe/table in Python. Each row in the table looks something like
this:
329444.6949 0.0124 -6.0124 3 97.9459 15 32507 303 7 3 4 8 2 7 HDC-13-O
The problem is that there is no clear separator/delimiter between the columns,
so for some rows there is no space between two columns, like this:
332174.9289 0.0995 -6.3039 3 1708.1601219 30501 30336 333 37 136 H2CO
From the web page it says these are called "card images". The information on
the table format is described as this:
> The catalog data files are composed of 80-character card images, with one
> card image per spectral line. The format of each card image is: FREQ, ERR,
> LGINT, DR, ELO, GUP, TAG, QNFMT, QN', QN" (F13.4,F8.4, F8.4, I2,F10.4, I3,
> I7, I4, 6I2, 6I2)
I would really like a way where I just use the format specifier given above.
The only thing I found wasNumpy's genfromtxt function. However, the following
does not work.
np.genfromtxt('tablename', dtype='f13.4,f8.4,f8.4,i2,f10.4,i3,i7,i4,6i2,6i2')
Anyone knows how I could read this table into Python with the use of the
format specification of each column that was given?
Answer: You can use the fixed-width reader in Astropy. See:
<http://astropy.readthedocs.org/en/latest/io/ascii/fixed_width_gallery.html#fixedwidthnoheader>.
This does still require you to count the columns, but you could probably write
a simple parser for the `dtype` expression you showed.
Unlike the pandas solution above (e.g. `df['FREQ'] = df.data.str[0:13]`), this
will automatically determine the column type and give float and int columns in
your case. The pandas version results in all `str` type columns, which is
presumably not what you want.
To quote the doc example there:
>>> from astropy.io import ascii
>>> table = """
... #1 9 19 <== Column start indexes
... #| | | <== Column start positions
... #<------><--------><-------------> <== Inferred column positions
... John 555- 1234 192.168.1.10
... Mary 555- 2134 192.168.1.123
... Bob 555- 4527 192.168.1.9
... Bill 555-9875 192.255.255.255
... """
>>> ascii.read(table,
... format='fixed_width_no_header',
... names=('Name', 'Phone', 'TCP'),
... col_starts=(1, 9, 19),
... )
<Table length=4>
Name Phone TCP
str4 str9 str15
---- --------- ---------------
John 555- 1234 192.168.1.10
Mary 555- 2134 192.168.1.123
Bob 555- 4527 192.168.1.9
Bill 555-9875 192.255.255.255
|
I can't print from Python IDLE in Windows 10
Question: Since upgrading to Windows 10 I can no longer print from the IDLE Python IDE.
The "print to default printer" box comes up as usual, but nothing is sent to
the print queue ... I checked in Devices & Printers.
Printing from other applications works fine.
Answer: I confirmed on my Win10 machine. However for me, the problem is not with Win
10. It is a stupid bug that I introduced in 2.7.11, 3.4.4, and 3.5.1. I am
assuming that you must have upgraded Python also. You can test if you have the
same cause by running `python -m idlelib` (or `idlelib.idle` on 2.7) in a
console. After IDLE starts, try to print and you should see a traceback ending
with `NameError: name 'idleConf' is not defined`.
My apologies for the blunder. I will fix this for future releases as soon as I
finish improving the test so it would have caught this.
To fix it in the meanwhile, carefully edit `<python-
dir>/Lib/idlelib/IOBinding.py`. Move this line
from idlelib.configHandler import idleConf
from about line 530, after a `tkinter` import, to line 13, after an
`askstring` import. Remove the indent when you do so.
|
Replacing masked values (--) with a Null or None value using fiil_value from ma numpy in Python
Question: Is there a way to replace a masked value in a numpy masked array as a null or
None value? This is what I have tried but does not work.
for stars in range(length_masterlist_final):
....
star = customSimbad.query_object(star_names[stars])
#obtain stellar info.
photometry_dataframe.iloc[stars,0] = star_IDs[stars]
photometry_dataframe.iloc[stars,1] = star_names[stars]
photometry_dataframe.iloc[stars,2] = star['FLUX_U'][0]
#Replace "--" masked values with a Null (i.e., '') value.
photometry_dataframe.iloc[stars,2] = ma.filled(photometry_dataframe.iloc[stars,2], fill_value=None)
.....
photometry_dataframe.to_csv(output_dir + "simbad_photometry.csv", index=False, header=True, na_rep='NaN')
specifically
(photometry_dataframe.iloc[stars,2] = ma.filled(photometry_dataframe.iloc[stars,2], fill_value=None))
produces
'MaskedConstant' object has no attribute '_fill_value'
I want to replace masked values '--' with '' when I output the dataframe as a
csv file. One work around is to read the outputted csv file back into python
and replace '--' with '', but this is a horrible solution. There must be a
better solution. I don't want masked values printed as '--' in the csv file.
Answer: Use Astropy:
>>> from pandas import DataFrame
>>> from astropy.table import Table
>>> import numpy as np
>>>
>>> df = DataFrame()
>>> df['a'] = [1, np.nan, 2]
>>> df['b'] = [3, 4, np.nan]
>>> df
a b
0 1 3
1 NaN 4
2 2 NaN
>>> t = Table.from_pandas(df)
>>> t
<Table masked=True length=3>
a b
float64 float64
------- -------
1.0 3.0
-- 4.0
2.0 --
>>> t.write('photometry.csv', format='ascii.csv')
>>>
(astropy)neptune$ cat photometry.csv
a,b
1.0,3.0
,4.0
2.0,
You can specify arbitrary transformations from table values to output values
using the `fill_values` parameter
(<http://docs.astropy.org/en/stable/io/ascii/write.html#parameters-for-
write>).
|
How can I get the data from the CSV file and declare a variable for each column using python?
Question: I have a csv file that might look like this (contents variable-format not):
"Red","House","1/1/2010","Green Eggs and Ham",1,10
The csv file that will always have just one row of data and 6 columns
How can I get the data from the cvs file and declare a variable for each
column value using python?
ie.
var1 = Column1
Var2 = Column2
var3 = Column3
etc.
so that when I type "print var3", the following value would appear.
"1/1/2010"
I thought the following would work but I got an error message saying
NameError: name var3 is not defined.
f = csv.reader(open("C:\Test\Test.csv", "rb"))
for row in f:
var1, var2, var3, var4, var5, var6 = row
print var3
I need to use these values later on the script. Ideas anyone. Super new to
this. Python 2.7
Answer: Each row is treated as a list in Python. So, if 'line' contains your 6
elements, 'line[0]' is your first column element.
Also, I changed the 'rt' to 'r' as I was getting some other sort of error, but
try this:
import csv
with open('C:\\test.csv', 'r') as csvfile:
f = csv.reader(csvfile)
for line in f:
print (line[2])
|
Python create excel readable csv from list of float values in single column
Question: I would like to be able to create a csv file from a list of floating point
values in a single column. Not sure how to achieve this...
mylist = [1.11, 2.22, 3.33, 4.44, ...]
with open('myfile.csv', "wb") as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(mylist)
When I open this csv in excel all of the values are printed with each value in
its own column, but I need them to be all in one column. How can I do this in
python? Or how do I need to format my list of numbers to achieve this?
Answer: Iterate through your list to add rows:
import csv
mylist = [1.11, 2.22, 3.33, 4.44]
with open('myfile.csv', "wb") as f:
writer = csv.writer(f, delimiter=',')
for elem in mylist:
writer.writerow([elem])
|
There is a way to change wpf components in another thread with ironpython 2.7?
Question: So, I'm trying to make some function run without freezing the GUI. There is
some way to change the text from a textblock in another thread? For example:
import wpf
import thread
from System.Windows import Application, Window
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'WpfApplication2.xaml')
def setText(self):
self.textblock.Text = "Hiiii!"
def button_Click(self, sender, e):
thread.start_new_thread(self.setText,())
if __name__ == '__main__':
Application().Run(MyWindow())
and my wpf:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WpfApplication2" Height="300" Width="300">
<Grid>
<TextBlock x:Name="textblock" Text="Oi" VerticalAlignment="Center" HorizontalAlignment="Center" FontWeight="Bold" FontSize="32" TextAlignment="Center" />
<Button x:Name="button" Content="Change" HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="100" Height="50" Click="button_Click"/>
</Grid>
</Window>
I can't in any way that I try to change the text block in another thread.
There is no way to make, for example, a infinite while loop to update data,
without freezing the GUI?
Answer: I have no clue about python but I use C#. I will tell you how I do it in C#
and I'm sure it will hit the bell in your head :)
The thing is that GUI runs in the main thread, so if something else is running
in the main thread it will freeze the UI. In the other hand, things that don't
run in the main thread, cannot affect the UI which is kind of annoying but
makes all the sense.
The solution is to use threads. In C# I recommend the usage of
BackgroundWorker but I'm sure you have thread facilities in python as well.
then you can use events in your thread to tell the UI about updates in the
status (for loading bars for instance) or when it is finished. Catch those
events from the GUI thread (the main one) and update any component as needed.
The other approach is to access the main thread from the secondary thread. For
doing this in C# you use the expression:
Dispatcher.Invoke((Action) delegate
{
here your code accessing controls in the UI as if you
where in the main thread
}
Hope this helps you finding your way.
|
Unable to make a http get request to SO
Question: I have a piece of code in python that can make http get requests. I can
successfully make request to URL like <http://google.com> and download their
page. But I can't make a get request to <http://stackoverflow.com> . It shows
HTTP 403 forbidden ERROR. However I can access stackoverflow from my browser.
So what could be the reason for this error?
**code:**
import urllib2
c=urllib2.urlopen('<http://stackoverflow.com/>')
contents=c.read()
print contents[0:50]
**error:** HTTPError: HTTP Error 403: Forbidden
Answer: Same here, I'm using Python 3.
`urllib.request.urlopen('http://stackoverflow.com')` failed with HTTP error
403.
I changed User-Agent, and then it worked:
import urllib.request
urllib.request.urlopen(urllib.request.Request('http://stackoverflow.com/',headers={'User-Agent':'Mozilla/5.0'}))
So it seems stackoverflow.com filters requests based on User-Agent, and
google.com doesn't do so.
> urllib2‘s default user agent string is "Python-urllib/2.6" (on Python 2.6)
Source: <https://docs.python.org/2/library/urllib2.html>
|
How to modify a tag text value based on its sibling tag text value in xml with python?
Question: For Eg:
<parameterDefinitions>
<hudson.model.StringParameterDefinition>
<name>name</name>
<description></description>
<defaultValue>abc</defaultValue>
</hudson.model.StringParameterDefinition>
<hudson.model.BooleanParameterDefinition>
<name>branch</name>
<description></description>
<defaultValue>true</defaultValue>
</hudson.model.BooleanParameterDefinition>
</parameterDefinitions>
Above given is the small part of XML file which am getting from the Jenkins
server. I need to modify the default value(abc and true for the above eg) of
the parameters based on its respective name(name and branch).
Have read about MiniDom, Element and ElementTree but couldn't figure out the
exact api. Can anyone help me out with this. Thanks in advance.
Answer: Simplest try may be using `lxml.etree` and grabbing the node by `xpath` (i.e.
`//hudson.model.StringParameterDefinition/defaultValue` here) to be changed as
below and changing properly-
from lxml import etree as et
data = """<parameterDefinitions>
<hudson.model.StringParameterDefinition>
<name>name</name>
<description></description>
<defaultValue>abc</defaultValue>
</hudson.model.StringParameterDefinition>
<hudson.model.BooleanParameterDefinition>
<name>branch</name>
<description></description>
<defaultValue>true</defaultValue>
</hudson.model.BooleanParameterDefinition>
</parameterDefinitions>"""
tree = et.fromstring(data)
w = tree.xpath("//hudson.model.StringParameterDefinition/defaultValue")
w[0].text = "changed"# here w is a list
print et.tostring(tree,pretty_print=True)
Output-
<parameterDefinitions>
<hudson.model.StringParameterDefinition>
<name>name</name>
<description/>
<defaultValue>changed</defaultValue>
</hudson.model.StringParameterDefinition>
<hudson.model.BooleanParameterDefinition>
<name>branch</name>
<description/>
<defaultValue>true</defaultValue>
</hudson.model.BooleanParameterDefinition>
</parameterDefinitions>
|
Python histograms: Manually normalising counts and re-plotting as histogram
Question: I tried searching for something similar, and the closest thing I could find
was [this](http://stackoverflow.com/questions/17966093/is-there-a-way-to-
return-same-length-arrays-in-numpy-hist) which helped me to extract and
manipulate the data, but now I can't figure out how to re-plot the histogram.
I have some array of voltages, and I have first plotted a histogram of
occurrences of those voltages. I want to instead make a histogram of events
per hour ( so the y-axis of a normal histogram divided by the number of hours
I took data ) and then re-plot the histogram with the manipulated **`y`**
data.
I have an array which contains the number of events per hour ( composed of the
original `y` axis from `pyplot.hist` divided by the number of hours data was
taken ), and the bins from the histogram. I have composed that array using the
following code ( taken from the answer linked above ):
import numpy
import matplotlib.pyplot as pyplot
mydata = numpy.random.normal(-15, 1, 500) # this seems to have to be 'uneven' on either side of 0, otherwise the code looks fine. FYI, my actual data is all positive
pyplot.figure(1)
hist1 = pyplot.hist(mydata, bins=50, alpha=0.5, label='set 1', color='red')
hist1_flux = [hist1[0]/5.0, 0.5*(hist1[1][1:]+hist1[1][:-1])]
pyplot.figure(2)
pyplot.bar(hist1_flux[1], hist1_flux[0])
This code doesn't exactly match what's going on in my code; my data is
composed of 1000 arrays of 1000 data points each ( voltages ). I have made
histograms of that, which gives me number of occurrences of a given voltage
range ( or bin width ). All I want to do is re-plot a histogram of the number
of events per hour (so **`yaxis`** _of the histogram_ / 5 hours) with the same
original bin width, but when I divide **`hist1[0]/5`** and replot in the above
way, the 'bin width' is all wrong.
I feel like there must be an easier way to do this, rather than manually
replotting my own histograms.
Thanks in advance, and I'm really sorry if I've missed something obvious.
The problem, illustrated in the output of my sample code AND my original data
is as follows:
**Upper plots** : code snippet output.
**Lower plots** : My actual data. 
Answer: It's because the `bar` function takes an argument `width`, which is by default
`0.8` (`plt.bar(left, height, width=0.8, bottom=None, hold=None, **kwargs)`),
so you need to change it to the distance between two bars:
pyplot.bar(hist1_flux[1], hist1_flux[0],
width=hist1_flux[1][1] - hist1_flux[1][0])
|
line interpolation on grid with python3
Question: I am very new to python(say 1 week) and numpy/scipy but not new to programming
at all but wondering how to do the following correctly (preferably with
numpy/scipy):
So say I have an 150x200 ndarray with float values. I want to interpolate a
line from 20:40 to 100:150 with 500 points in between.
Getting the x:y interpolation I have with:
xValues = numpy.linspace(20,100,500)
yValues = numpy.linspace(40,150,500)
But now how i get the values(on that line only) interpolated using
numpy/scipy?
PS I use python3
Answer: Check out
[Scipy.interpolate](http://docs.scipy.org/doc/scipy/reference/interpolate.html)
import numpy as np
from scipy.interpolate import interp1d
xValues = numpy.linspace(20,100,500)
yValues = numpy.linspace(40,150,500)
f = interpolate.interp1d(x, y)
xnew = np.arange(20, 30, 0.1)
ynew = f(xnew)
|
Python - order dictionary data
Question: My knowledge about Python is really low. I am trying to order data from a
dictionary and I do not know how. I have tried OrderedDict, Sort and
variable.sorted but I only got errors.
What I have tried:
textos_informativos = []
for t in c.producto.textos:
textos_informativos.append(dict(orden=t.orden,
tipo=t.tipo.nombre,
informacion=t.informacion))
I would like to order the data based on "t.orden" data (int).
Answer: Thanks,
I've tryied:
from collections import OrderedDict
textos_informativos = []
for t in c.producto.textos:
textos_informativos.append(OrderedDict(orden=t.orden,
tipo=t.tipo.nombre,
informacion=t.informacion))
Nothing happened.
* * *
textos_informativos = []
for t in c.producto.textos:
textos_informativos.append(dict(orden=t.orden,
tipo=t.tipo.nombre,
informacion=t.informacion))
sorted (textos_informativos, key= t.orden)
Error 'int' object is not callable
* * *
textos_informativos = []
for t in c.producto.textos:
textos_informativos.append(dict(orden=t.orden,
tipo=t.tipo.nombre,
informacion=t.informacion))
t.orden.sort()
Error 'int' object has no attribute 'sort'
* * *
|
Installing numpy with pypy on mac osx
Question: I'm unable to install numpy with pypy on mac. I have installed pypy using brew
and when I try to execute:
pip_pypy install numpy
I get this error:
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE/numpy
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE/numpy/numpy
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE/numpy/numpy/_build_utils
creating build/temp.macosx-10.11-x86_64-2.7/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE/numpy/numpy/_build_utils/src
compile options: '-DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=3 -DHAVE_CBLAS -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -Inumpy/core/include -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/usr/local/Cellar/pypy/4.0.1/libexec/include -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -c'
extra options: '-msse3 -I/System/Library/Frameworks/vecLib.framework/Headers'
cc: numpy/core/src/multiarray/alloc.c
In file included from numpy/core/src/multiarray/alloc.c:8:
In file included from numpy/core/include/numpy/arrayobject.h:4:
In file included from numpy/core/include/numpy/ndarrayobject.h:27:
build/src.macosx-10.11-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h:28:12: error: visibility does not match previous declaration
extern NPY_NO_EXPORT PyTypeObject PyArray_Type;
^
numpy/core/include/numpy/ndarraytypes.h:10:31: note: expanded from macro 'NPY_NO_EXPORT'
#define NPY_NO_EXPORT NPY_VISIBILITY_HIDDEN
^
build/src.macosx-10.11-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h:25:46: note: expanded from macro 'NPY_VISIBILITY_HIDDEN'
#define NPY_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/pypy_decl.h:611:1: note: previous attribute is here
PyAPI_DATA(PyTypeObject) PyArray_Type;
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/Python.h:15:35: note: expanded from macro 'PyAPI_DATA'
# define PyAPI_DATA(RTYPE) extern PyAPI_FUNC(RTYPE)
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/Python.h:14:43: note: expanded from macro 'PyAPI_FUNC'
# define PyAPI_FUNC(RTYPE) __attribute__((visibility("default"))) RTYPE
^
numpy/core/src/multiarray/alloc.c:109:30: error: use of undeclared identifier 'PyMem_MALLOC'
&PyArray_malloc);
^
numpy/core/include/numpy/ndarraytypes.h:335:24: note: expanded from macro 'PyArray_malloc'
#define PyArray_malloc PyMem_Malloc
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/pymem.h:8:22: note: expanded from macro 'PyMem_Malloc'
#define PyMem_Malloc PyMem_MALLOC
^
2 errors generated.
In file included from numpy/core/src/multiarray/alloc.c:8:
In file included from numpy/core/include/numpy/arrayobject.h:4:
In file included from numpy/core/include/numpy/ndarrayobject.h:27:
build/src.macosx-10.11-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h:28:12: error: visibility does not match previous declaration
extern NPY_NO_EXPORT PyTypeObject PyArray_Type;
^
numpy/core/include/numpy/ndarraytypes.h:10:31: note: expanded from macro 'NPY_NO_EXPORT'
#define NPY_NO_EXPORT NPY_VISIBILITY_HIDDEN
^
build/src.macosx-10.11-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h:25:46: note: expanded from macro 'NPY_VISIBILITY_HIDDEN'
#define NPY_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/pypy_decl.h:611:1: note: previous attribute is here
PyAPI_DATA(PyTypeObject) PyArray_Type;
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/Python.h:15:35: note: expanded from macro 'PyAPI_DATA'
# define PyAPI_DATA(RTYPE) extern PyAPI_FUNC(RTYPE)
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/Python.h:14:43: note: expanded from macro 'PyAPI_FUNC'
# define PyAPI_FUNC(RTYPE) __attribute__((visibility("default"))) RTYPE
^
numpy/core/src/multiarray/alloc.c:109:30: error: use of undeclared identifier 'PyMem_MALLOC'
&PyArray_malloc);
^
numpy/core/include/numpy/ndarraytypes.h:335:24: note: expanded from macro 'PyArray_malloc'
#define PyArray_malloc PyMem_Malloc
^
/usr/local/Cellar/pypy/4.0.1/libexec/include/pymem.h:8:22: note: expanded from macro 'PyMem_Malloc'
#define PyMem_Malloc PyMem_MALLOC
^
2 errors generated.
error: Command "cc -arch x86_64 -O2 -fPIC -Wimplicit -O2 -fPIC -Wimplicit -O2 -fPIC -Wimplicit -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=3 -DHAVE_CBLAS -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -Inumpy/core/include -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/usr/local/Cellar/pypy/4.0.1/libexec/include -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -Ibuild/src.macosx-10.11-x86_64-2.7/numpy/core/src/private -c numpy/core/src/multiarray/alloc.c -o build/temp.macosx-10.11-x86_64-2.7/numpy/core/src/multiarray/alloc.o -msse3 -I/System/Library/Frameworks/vecLib.framework/Headers" failed with exit status 1
----------------------------------------
Command "/usr/local/Cellar/pypy/4.0.1/bin/pypy -u -c "import setuptools, tokenize;__file__='/private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE/numpy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-fCQrIA-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-build-RBCHFE/numpy
And when I am trying to follow instructions from
<http://pypy.org/download.html> I get even more confusing error about pypy
version 4.1:
Cloning https://bitbucket.org/pypy/numpy.git to /var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-59hKzA-build
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-59hKzA-build/setup.py", line 33, in <module>
('.'.join(map(str, MIN_PYPY_VERSION)),))
RuntimeError: PyPy version >= 4.1 required
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /var/folders/9p/_t441dx15ddcx5ycrjxrxmyh0000gn/T/pip-59hKzA-build
Dose anyone know what am I doing wrong and how can I fix it?
Answer: NumPy is being ported to pypy and so only an experimental version is available
for now. According to the official site, the command to install that version
of NumPy to pypy is:
`pypy -m pip install git+https://bitbucket.org/pypy/numpy.git`
<http://pypy.org/download.html#installing-numpy>
The command you tried will probably try to install normal NumPy from PyPI
which is not ready for pypy.
(edit)
I just followed the instructions given at <https://bitbucket.org/pypy/numpy>
and I could install numpy 1.9.0 to pypy on Linux Mint 17.
Basically create a new env for pypy-numpy
`virtualenv -p /path/to/pypy/bin/pypy /directory/to/try/pypy-numpy`
`/path/to/pypy/bin/pypy` here is the path to your PyPy 4.0.1.
`/directory/to/try/pypy-numpy` is up to you. I created in home/pypy-numpy
Then I cloned NumPyPy source by
`git clone https://bitbucket.org/pypy/numpy.git`
then I moved to this clone directory 'numpy' and did
`git checkout pypy-4.0.1`
This fetched the version of NumPyPy we need for PyPy 4.0.1
Now I can
`~/pypy-numpy/bin/pypy setup.py install`
which worked without problems.
Hope this helps on Mac as well.
|
Efficiently save to disk (heterogeneous) graph of lists, tuples, and NumPy arrays
Question: I am regularly dealing with large amounts of data (order of several GB), which
are stored in memory in NumPy arrays. Often, I will be dealing with nested
lists/tuples of such NumPy arrays. How should I store these to disk? I want to
preserve the list/tuple structure of my data, the data has to be compressed to
conserve disk space, and saving/loading needs to be fast.
(The particular use case I'm facing right now is a 4000-element long list of
2-tuples `x` where `x[0].shape = (201,)` and `x[1].shape = (201,1000)`.)
I have tried several options, but all have downsides:
* [`pickle`](https://docs.python.org/3.5/library/pickle.html) storage into a `gzip` archive. This works well, and results in acceptable disk space usage, but is extremely slow and consumes a lot of memory while saving.
* [`numpy.savez_compressed`](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.savez_compressed.html). Is much faster than `pickle`, but unfortunately only allows either a sequence of numpy arrays (not nested tuples/lists as I have) or a dictionary-style way of specifying the arguments.
* Storing into HDF5 through [`h5py`](http://www.h5py.org/). This seems too cumbersome for my relatively simple needs. More importantly, I looked a lot into this, and also there does not seem to be a straightforward way to store heterogeneous (nested) lists.
* [`hickle`](https://github.com/telegraphic/hickle) seems to do exactly what I want, however unfortunately it's incompatible with Python 3 at the moment (which is what I'm using).
I was thinking of writing a wrapper around `numpy.savez_compressed`, which
would determine the nested structure of the data, store this structure in some
variable `nest_structure`, flatten the full graph, and store both
`nest_structure` and all the flattened data using `numpy.savez_compressed`.
Then, the corresponding wrapper around
[`numpy.load`](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.load.html)
would understand the `nest_structure` variable, and re-create the graph and
return it. However, I was hoping there is something like this already out
there.
Answer: You may like the [`shelve`](https://docs.python.org/3/library/shelve.html
"shelve") package. It effectively wraps heterogeneous pickled objects in a
convenient file. `shelve` is oriented more toward a "persistent storage" than
classic save-to-file model.
The main benefit of using `shelve` is that you can conveniently save most
kinds of structured data. The main disadvantage of using `shelve` is that it
is Python-specific. Unlike HDF-5 or saved Matlab files or even simple CSV
files, it isn't so easy to use other tools with your data.
Example of saving (Out of habit, I created objects and copy them to `df`, but
you don't need to do this. You could just save directly to items in `df`):
import shelve
import numpy as np
a = np.arange(0, 1000, 12)
b = "This is a string"
class C(object):
alpha = 1.0
beta = [3, 4]
c = C()
class C(object):
alpha = 1.0
beta = [3, 4]
c = C()
df = shelve.open('test.shelve', 'c')
df['a'] = a
df['b'] = b
df['c'] = c
df.sync()
exit()
Following the above example, recovering data:
import shelve
import numpy as np
class C():
alpha = 1.0
beta = [3, 4]
df = shelve.open('test.shelve')
print(df['a'])
print(df['b'])
print(df['c'].alpha)
|
Why apache throws Target WSGI script not found or unable to stat on Flask app?
Question: I want to setup my flask app for apache on my ubuntu server using wsgi. But
after my setup, I get the following browser error:
Not Found
The requested URL / was not found on this server.
The apache error log throws:
Target WSGI script not found or unable to stat:
/var/www/html/appname/appname.wsgi
My wsgi file looks like this:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/html/appname/")
from IdeaHound import app as application
application.secret_key = 'here_the_key'
and my apache config file looks like this:
<VirtualHost *:80>
ServerName server_ip_here
WSGIScriptAlias / /var/www/html/appname/appname.wsgi
<Directory /var/www/html/appname/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel info
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
The **appname** folder has the following structure: appname
--application.py
--appname.wsgi
--LICENSE
--README.md
--requirements.txt
--db_manage.py
--appname
----frontend
----__inity__.py
----__init__.pyc
----models
----__pycache__
----socket_interface
--AppName
----__init__.py
----static
----templates
--instance
----config.py
What am I missing here to make the webserver run correctly with Flask?
Answer: Please read the following link of Digital Ocean. Do as describe in it. And
your app will be up and running in just 5 mins.
<https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-
application-on-an-ubuntu-vps>
Also do check the apache error logs for more information if it still throws an
error.
/var/log/apache2/error.log
|
Chr() arg not in range python
Question: I have been creating a program, and part of it involves modifying a list of
characters at random:
while rel>0:
pos = random.randint(0,len(out)-1)
change = random.randint(-1*rel,rel)
if (change+ord(out[pos]))>=255:
change = 255-ord(out[pos])
elif ((ord(out[pos]))-change)<=0:
change = -1*(ord(out[pos]))
out[pos] = chr(ord(out[pos])+change)
rel -= abs(change)
Here, rel is the 'currency' the program is using to modify the list of
characters out. It first chooses a random position in the list, and a random
amount of change for that position between -rel and +rel, then changes the
value of that character using chr(ord(out[pos])+change). This was giving me
the error that this new modified value for the character was out of the
range(256), so I added the 2 if statements to be executed before changing the
character, however it still occasionally returns this error, especially for
large values of rel. How can I stop this?
Answer: The problem is in your choice of translation checks.
elif ((ord(out[pos]))-change)<=0:
Why is this difference meaningful? All of the other operations are on the
_sum_ of the char and change. You get the error when **change <
-ord(out[pos])**: neither the **if** nor the **elif** condition is True, so
you wind up taking the **chr** of a negative number.
Change that minus to a plus, and you should be fine, until you get values of
rel beyond 512. If this is possible, please consider using modulus (%) instead
of a simple subtraction.
It took me a couple of minutes to trace this. I cleaned up the program and
added a pair of tracing **print** s to find out what's going on.
import random
out = list("Now is the time for all good parties")
rel = 500
while rel > 0:
pos = random.randint(0, len(out)-1)
chord = ord(out[pos])
change = random.randint(-rel, rel)
print "A", chord, change
if change + chord >= 255:
change = 255 - chord
elif chord + change <= 0:
change = -chord
print "B", chord, change
out[pos] = chr(chord + change)
rel -= abs(change)
print ''.join(out)
|
SQLAlchemy InvalidRequestError: failed to locate name happens only on gunicorn
Question: Okay, so I have the following. In `user/models.py`:
class User(UserMixin, SurrogatePK, Model):
__tablename__ = 'users'
id = Column(db.Integer, primary_key=True, index=True)
username = Column(db.String(80), unique=True, nullable=False)
email = Column(db.String(80), unique=False, nullable=False)
password = Column(db.String(128), nullable=True)
departments = relationship("Department",secondary="user_department_relationship_table", back_populates="users")
and in `department/models.py`:
user_department_relationship_table=db.Table('user_department_relationship_table',
db.Column('department_id', db.Integer,db.ForeignKey('departments.id'), nullable=False),
db.Column('user_id',db.Integer,db.ForeignKey('users.id'),nullable=False),
db.PrimaryKeyConstraint('department_id', 'user_id') )
class Department(SurrogatePK, Model):
__tablename__ = 'departments'
id = Column(db.Integer, primary_key=True, index=True)
name = Column(db.String(80), unique=True, nullable=False)
short_name = Column(db.String(80), unique=True, nullable=False)
users = relationship("User", secondary=user_department_relationship_table,back_populates="departments")
Using the flask development server locally this works totally fine. However,
once I deploy to the standard python buildpack on heroku, the `cpt/app.py`
loads both modules to register their blueprints:
from cpt import (
public, user, department
)
...
def register_blueprints(app):
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
app.register_blueprint(department.views.blueprint)
return None
and eventually errors out with the following:
> sqlalchemy.exc.InvalidRequestError: When initializing mapper
> Mapper|User|users, expression 'user_department_relationship_table' failed to
> locate a name ("name 'user_department_relationship_table' is not defined").
> If this is a class name, consider adding this relationship() to the class
> after both dependent classes have been defined.
I'd like to know if there's a better way to organize these parts to avoid this
error obviously, but I'm more curious why this organization works fine on the
development server but blows up something fierce on gunicorn/heroku.
Answer: Well I can't explain the discrepancy between heroku and the dev server, but I
got the error to go away by changing the Department mode from
users = relationship("Department",secondary="user_department_relationship_table", back_populates="users")
to
users = relationship("User", secondary=user_department_relationship_table, backref="departments")
which sets up the User model automatically which in turn means I can delete
any mention of Department and the relationship table on that end.
¯\\_(ツ)_/¯
|
bzt 1.1.0 says DistributionNotFound: selenium
Question: I just installed bzt 1.1.0 on my MacOSX but it won't run, it gives this
message:
Traceback (most recent call last):
File "/usr/local/bin/bzt", line 5, in <module>
from pkg_resources import load_entry_point
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2603, in <module>
working_set.require(__requires__)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 666, in require
needed = self.resolve(parse_requirements(requirements))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 565, in resolve
raise DistributionNotFound(req) # XXX put more info here
pkg_resources.DistributionNotFound: selenium
The thing is, selenium 2.49.2 was installed along with bzt. How can I fix
this?
Answer: Turns out it was a Python package management issue. Selenium was installed in
/Library/Python/2.7/site-packages with a `selenium-2.49.2.dist-info`
directory, not the `.egg-info` directory that `pkg_resources.py` expected.
Upgrading to a newer version of pkg_resources helped, as explained in [this
answer](http://stackoverflow.com/a/21175750/584846):
sudo pip install --upgrade setuptools
Then, reinstalling selenium finally fixed the problem:
sudo pip uninstall selenium
sudo pip install selenium
Thanks to Andrey Pohilko on the [Google Groups
forum](https://groups.google.com/forum/#!topic/codename-taurus/xPBj3YJqRUw)
for helping out.
|
Create unique ID from the existing two columns, python
Question: My question is: how to efficiently sign data unique id numbers from existing
id columns? For example: I have two columns [household_id], and [person_no]. I
try to make a new column, the query would be: household_id + '_' + person_no.
here is a sample:
hh_id pno
682138 1
365348 1
365348 2
try to get:
unique_id
682138_1
365348_1
365348_2
and add this unique_id as a new column. I am applying Python. My data is very
large. Any efficient way to do it would be great. Thanks!
Answer: You can use [pandas](http://pandas.pydata.org/).
Assuming your data is in a csv file, read in the data:
import pandas as pd
df = pd.read_csv('data.csv', delim_whitespace=True)
Create the new id column:
df['unique_id'] = df.hh_id.astype(str) + '_' + df.pno.astype(str)
Now `df` looks like this:
hh_id pno unique_id
0 682138 1 682138_1
1 365348 1 365348_1
2 365348 2 365348_2
Write back to a csv file:
df.to_csv('out.csv', index=False)
The file content looks like this:
hh_id,pno,unique_id
682138,1,682138_1
365348,1,365348_1
365348,2,365348_2
|
Building a CSV file to import into sql, how to handle relationships?
Question: I have a very large set of data where each row in table A point to a lot of
rows in table B. In generating a CSV file, I would need to somehow show this
relation, but I don't have an integer based pkey. Each of the items in A have
a unique username, and the same goes for table B (that is, table B has its own
unique set of names).
I am working with Python and Postgres if that matters. Another note, both
tables are 50-100M+ rows long, about 8 columns each.
Is there a good strategy for building out this CSV file?
Answer: You say each row has a unique name. If they truly are unique then you can use
them as keys for your tables. You don't need integer-based keys.
For example, the path to a file can be considered a unique identifier (for
files that are all in the same directory/repository.) So that could be the
file's key.
* Advantages: Easier to import. All references to that file are human readable.
* Disadvantages: each reference to that file uses more database space than an integer key. If a file is renamed it looks like a new file; the name can't change without changing the key. (Although, there are workarounds.)
The import will be much easier without assigning unique integer keys. I
suggest you import first, then optionally add integer keys afterwards.
Import: put the data in the CSV files, one file per table. Then import them
into the destination database in the correct order. (If I understand your
structure correctly the first one would be the Repository table, as Commits
and Changes both refer to it.)
Adding integer keys to existing tables: Add an autonumbering column to each
table that needs an integer key. So each parent row now has it's original
unique name and an integer ID. Then you can use SQL commands to replace each
parent name in a child table with it's respective internal key, then drop the
extra name columns once they are no longer needed.
|
phyton3 pip and pyautogui install mac -remove broken python
Question: having jumped into java development a year ago, i now struggle myself thru
terminal commands and try to get the red line in it.
I now want to set up python3 and pyautogui following this tutorial:
<https://automatetheboringstuff.com/chapter18/>
unfortunately I keep failing setting up the needed module:
Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-ct_f0rph/pyobjc-core
if you please could help me out removing old python installations, and linking
python command to python3 i´d be very happy :)
thanks a lot!
EDIT: my problem was due to missing xcode, installing it and agreeing license
made it work with below answer
still had a problem after installing pip, here is the solve for all who still
get problems:
download recommended file and run the setup inside, had to punch in many
commands to run it from appropiate directory but it finally works when
importing pyautogui:
<https://www.reddit.com/r/learnpython/related/3z5h0b/trouble_importing_pyautogui_os_x/>
ps: i only downloaded the tar ball and used the setup.py inside
Answer: Download proper installer of python 3:
[Python3](https://www.python.org/ftp/python/3.5.1/python-3.5.1-macosx10.6.pkg)
Install `Xcode` (get it from [Xcode](http://developer.apple.com/xcode)) if you
don't have it yet.
Point `xcode-select` to the `Xcode Developer` directory using the following
command:
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
Open command line and navigate to `python3` directory:
/Library/Frameworks/Python.framework/Versions/3.5/bin
Run:
sudo pip3 install pyobjc-framework-Quartz
sudo pip3 install pyobjc-core
sudo pip3 install pyobjc
pip3 install pyautogui
Try your installation from the command line, type:
python3
import pyautogui
If everything is fine you won't have an import error. I hope it helps.
|
Python: Download multiple .gz files from single URL
Question: I am having trouble downloading multiple network files from an online
directory. I am using a virtual Linux environment (Lubuntu) over VMware. My
aim is to access a subfolder and download all the .gz files it contains into a
new local directory that is different from the home directory. I tried
multiple solutions and this is the closest I got.
import os
from urllib2 import urlopen, URLError, HTTPError
def dlfile(url):
# Open the url
try:
f = urlopen(url)
print "downloading " + url
# Open our local file for writing
with open(os.path.basename(url), "wb") as local_file:
local_file.write(f.read())
#handle errors
except HTTPError, e:
print "HTTP Error:", e.code, url
except URLError, e:
print "URL Error:", e.reason, url
def main():
# Iterate over image ranges
for index in range(100, 250,5):
url = ("http://data.ris.ripe.net/rrc00/2016.01/updates20160128.0%d.gz"
%(index))
dlfile(url)
if __name__ == '__main__':
main()
The online directory needs no authentication, a link can be found
[here](http://data.ris.ripe.net/rrc00/2016.01/).
I tried string manipulation and using a loop over the filenames, but it gave
me the following error:
HTTP Error: 404 http://data.ris.ripe.net/rrc00/2016.01/updates20160128.0245.gz
Answer: Look at the url
Good url: `http://data.ris.ripe.net/rrc00/2016.01/updates.20160128.0245.gz`
Bad url (your code):
`http://data.ris.ripe.net/rrc00/2016.01/updates20160128.0245.gz`
A dot between updates and 2016 is missing
|
Ctypes Text Input Box Help Using Python
Question: How to make a popup window with an text input box in Ctypes using python 3 or
using MessageBoxW,if possible?
Answer: It works!
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
MessageBox(None, 'Hello', 'Window title', 0)
|
Django - Did you forget to register or load this tag?
Question: I've created a custom tag that I want to use, but Django can't seem to find
it. My `templatetags` directory is set up like this:
[](http://i.stack.imgur.com/FMI2O.png)
**pygmentize.py**
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from django import template
from pygments.formatters.other import NullFormatter
register = template.Library()
@register.tag(name='code')
def do_code(parser,token):
code = token.split_contents()[-1]
nodelist = parser.parse(('endcode',))
parser.delete_first_token()
return CodeNode(code,nodelist)
class CodeNode(template.Node):
def __init__(self,lang,code):
self.lang = lang
self.nodelist = code
def render(self,context):
code = self.nodelist.render(context)
lexer = get_lexer_by_name('python')
return highlight(code,lexer,NullFormatter())
I am trying to use this tag to render code in `gameprofile.html`.
**gameprofile.html**
(% load pygmentize %}
{% block content %}
<title>{% block title %} | {{ game.title }}{% endblock %}</title>
<div id="gamecodecontainer">
{% code %}
{{game.code}}
{% endcode %}
</div>
{% endblock content %}
When I navigate to `gameprofile.html`, I get an error:
> Invalid block tag on line 23: 'code', expected 'endblock'. Did you forget to
> register or load this tag?
Answer: did you try this
{% load games_tags %}
at the top instead of pygmentize?
|
How do I send connection objects using Pipe() in python?
Question: I am not able to send pipe objects between processes.
pipe_i.send(diff_connection_object)
I know connection objects are not pickalable. As send() only takes as argument
picklable objects thus I am not able to send the connection object. So how can
I do this ?
Answer: If you use a fork of `multiprocessing` called `multiprocess` then it should
work for almost any connection object you want to send. The fork uses `dill`
instead of `pickle`, to provide better serialization. For example, here's a
`sqlite3.Connection` object.
>>> import sqlite3
>>> c = sqlite3.connect(':memory:')
>>> c
<sqlite3.Connection object at 0x1046134b8>
>>> import multiprocess
>>> p1,p2 = multiprocess.Pipe()
>>> p1.send(c)
>>> c_ = p2.recv()
>>> c_
<sqlite3.Connection object at 0x104af8200>
It's unclear which connection object is **the** connection object being asked
about. So here's a `_multiprocess.Connection` object being passed with the
`Pipe` from `multiprocess`.
>>> c = p1.__class__
>>> p1.send(c)
>>> c_ = p2.recv()
>>> c_
<type '_multiprocess.Connection'>
However, in trying to pass the `_multiprocess.Connection` object instance,
instead of the `_multiprocess.Connection` object class… the `send` works just
fine, but the `recv` will unfortunately fail to unpickle the object.
>>> p3,p4 = multiprocess.Pipe()
>>> p1.send(p3)
>>> p3_ = p2.recv()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mmckerns/lib/python2.7/site-packages/dill-0.2.5.dev0-py2.7.egg/dill/dill.py", line 259, in loads
return load(file)
File "/Users/mmckerns/lib/python2.7/site-packages/dill-0.2.5.dev0-py2.7.egg/dill/dill.py", line 249, in load
obj = pik.load()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 864, in load
dispatch[key](self)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1089, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: Required argument 'handle' (pos 1) not found
>>>
If the last case worked, you could do some pretty cool stuff, I think. Maybe
it's worth submitting a ticket to `dill` or `multiprocess`, and requesting it
work?
|
How to judge bmp pictures from clipboard whether they are same using wxpython?
Question: Function that I want to realize: when the bmp picture get from clipboard is
changed, refresh window. If not, nothing will be done.
Question that I meet: every time my program goes into function
UpdateMsgShownArea(), self.oldBmp will be diff with self.bmp, but I have
already let self.oldBmp = self.bmp if they are different, and it prints
"111111". While next time the program goes into UpdateMsgShownArea(),
self.oldBmp will be diff with self.bmp again. It confuses me.
[](http://i.stack.imgur.com/b4j9B.png)
code as follows:
#!/usr/bin/env python
import wx
import os, sys
#----------------------------------------------------------------------------
# main window
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(600,480))
self.panel = MyPanel(self)
self.CreateStatusBar() # A StatusBar in the bottom of the window
# Setting up the menu.
filemenu= wx.Menu()
# wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets.
menuAbout = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
# Set events.
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
self.Close(True) # Close the frame.
#----------------------------------------------------------------------------
# main panel
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
# shared path boxsizer, DirPickerCtrl is alternative and better realization for textCtrl + btn
sharedPathStaticText = wx.StaticText(self, -1, 'Shared Dir:')
self.sharedPathTextCtrl = wx.TextCtrl(self, -1, 'Please choose a dir', style = wx.TE_READONLY|wx.TE_RICH)
sharedPathBtn = wx.Button(self, -1, 'Browse', name = 'Shared dir button')
box1 = wx.BoxSizer(wx.HORIZONTAL)
box1.Add(sharedPathStaticText, 0, wx.ALIGN_CENTER)
box1.Add(self.sharedPathTextCtrl, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5) # proportion = 1, border = 5
box1.Add(sharedPathBtn, 0)
self.Bind(wx.EVT_BUTTON, self.OnOpen, sharedPathBtn)
# local path boxsizer
localPathStaticText = wx.StaticText(self, -1, 'Local Dir: ')
self.localPathTextCtrl = wx.TextCtrl(self, -1, 'Please choose a dir', style = wx.TE_READONLY|wx.TE_RICH)
localPathBtn = wx.Button(self, -1, 'Browse', name = 'local dir button')
box2 = wx.BoxSizer(wx.HORIZONTAL)
box2.Add(localPathStaticText, 0, wx.ALIGN_CENTER)
box2.Add(self.localPathTextCtrl, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5) # proportion = 1, border = 5
box2.Add(localPathBtn, 0)
self.Bind(wx.EVT_BUTTON, self.OnOpen, localPathBtn)
# message show area
messageShowStaticText = wx.StaticText(self, -1, 'Sync info shown area: ')
box5 = wx.BoxSizer(wx.HORIZONTAL)
box5.Add(messageShowStaticText, 0, wx.ALIGN_LEFT)
# size (200,200) don't take effect
#msgShowAreaID = wx.NewId()
#print msgShowAreaID
self.msgShowArea = wx.ScrolledWindow(self, -1, size = (200,200), style = wx.SIMPLE_BORDER)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box3.Add(self.msgShowArea, 1, wx.ALIGN_CENTER, 10)
# sync ctrl buttons
stopSyncBtn = wx.Button(self, -1, 'Stop Sync', name = 'Stop Sync button')
resumeSyncBtn = wx.Button(self, -1, 'Resume Sync', name = 'Resume Sync button')
box4 = wx.BoxSizer(wx.HORIZONTAL)
box4.Add(stopSyncBtn, 0, wx.ALIGN_CENTER|wx.RIGHT, 20)
box4.Add(resumeSyncBtn, 0, wx.ALIGN_CENTER|wx.LEFT, 20)
# sizer
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(box1, 0, wx.EXPAND|wx.ALL, 10)
sizer.Add(box2, 0, wx.EXPAND|wx.ALL, 10)
sizer.Add(box5, 0, wx.EXPAND|wx.ALL, 10)
sizer.Add(box3, 0, wx.EXPAND|wx.ALL, 10)
sizer.Add(box4, 0, wx.ALIGN_CENTER, 10)
self.SetSizer(sizer)
self.SetAutoLayout(True)
# clipboard
self.clip = wx.Clipboard()
self.x = wx.BitmapDataObject()
self.bmp = None
self.oldBmp = None
self.msgShowArea.Bind(wx.EVT_IDLE, self.UpdateMsgShownArea)
self.msgShowArea.Bind(wx.EVT_PAINT, self.OnPaint)
def OnOpen(self, e):
""" Open a file"""
button = e.GetEventObject()
dlg = wx.DirDialog(self, "Choose a dir", "", wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
if button.GetName() == 'Shared dir button':
self.sharedPathTextCtrl.SetValue(path)
if button.GetName() == 'local dir button':
self.localPathTextCtrl.SetValue(path)
dlg.Destroy()
def UpdateMsgShownArea(self, e):
print "UpdateMsgShownArea"
self.clip.Open()
self.clip.GetData(self.x)
self.clip.Close()
self.bmp = self.x.GetBitmap()
if self.oldBmp == self.bmp:
print "same pic"
return
else:
print "diff pic"
self.oldBmp = self.bmp
if self.oldBmp == self.bmp:
print "111111"
else:
print "222222"
print "abcd"
#self.Refresh()
#self.msgShowArea.Refresh()
def OnPaint(self, evt):
if self.bmp:
dc = wx.PaintDC(self.msgShowArea)
dc.DrawBitmap(self.bmp, 20, 20, True)
#----------------------------------------------------------------------------
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame(None, "EasySync")
app.MainLoop()
Answer: There is no support for clipboard change notifications in wxWidgets,
unfortunately. Under MSW it would be relatively simple to add it, but I'm less
sure about the other platforms.
In any case, right now your only choice is to poll the clipboard for changes,
i.e. set up a timer and check the clipboard contents every time it fires. This
is ugly and inefficient, but should work.
|
HUE on AWS : Hive Editor needs HiveServer2 - Error creating table sample_07
Question: I deployed a Cloudera EDH cluster on AWS using Quickstart and the cloudera-
director executable. I followed the instructions in here :
<http://docs.aws.amazon.com/quickstart/latest/cloudera/welcome.html> and I
used the aws.reference.conf file that comes with the Cloudera launcher.
Everything works fine during the deployment, but I am having problems with
HUE/Hive editor. When I go to the HUE UI I see the screen below :
[](http://i.stack.imgur.com/3NS0f.png)
And when I try to open the Hive Editor I get :
[](http://i.stack.imgur.com/IIRO9.png)
It seems to me that the source of the problem could be here :
InvalidConfigurationException hive.server2.authentication can't be none in non-testing mode
The nodes connect with each other using the auto-generated key pair file
during the AWS CloudFormation launch, so there is no password configured for
ssh.
I logged in to the node running hive and looked at the hive log file says this
:
ERROR org.apache.hadoop.hdfs.KeyProviderCache: [pool-6-thread-2]: Could not find uri with key [dfs.encryption.key.provider.uri] to create a keyProvider !!
and the hue log file says :
[28/Jan/2016 17:22:02 -0800] models ERROR error syncing beeswax
Traceback (most recent call last):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/core/src/desktop/models.py", line 297, in sync
for job in find_jobs_with_no_doc(SavedQuery):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/query.py", line 96, in __iter__
self._fetch_all()
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/backends/sqlite3/base.py", line 452, in execute
return Database.Cursor.execute(self, query, params)
OperationalError: no such column: beeswax_savedquery.is_redacted
[28/Jan/2016 17:22:02 -0800] models ERROR error syncing search
Traceback (most recent call last):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/core/src/desktop/models.py", line 315, in sync
from search.models import Collection
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/search/src/search/models.py", line 34, in <module>
from libsolr.api import SolrApi
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/libs/libsolr/src/libsolr/api.py", line 46, in <module>
class SolrApi(object):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/libs/libsolr/src/libsolr/api.py", line 50, in SolrApi
def __init__(self, solr_url, user, security_enabled=SECURITY_ENABLED.get()):
AttributeError: 'Config' object has no attribute 'get'
[28/Jan/2016 17:33:52 -0800] views ERROR Error in config validation by liboozie: <html><head><title>Apache Tomcat/6.0.44 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:w
hite;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#
525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sa
ns-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - </h1><HR size="1" noshade="noshade"><p><b>type</
b> Exception report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>java.lang.Uns
upportedOperationException
org.apache.oozie.util.MetricsInstrumentation.getVariables(MetricsInstrumentation.java:333)
org.apache.oozie.servlet.BaseAdminServlet.instrToJson(BaseAdminServlet.java:339)
org.apache.oozie.servlet.BaseAdminServlet.sendInstrumentationResponse(BaseAdminServlet.java:396)
org.apache.oozie.servlet.BaseAdminServlet.doGet(BaseAdminServlet.java:127)
javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
org.apache.oozie.servlet.JsonRestServlet.service(JsonRestServlet.java:289)
javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
org.apache.oozie.servlet.AuthFilter$2.doFilter(AuthFilter.java:171)
org.apache.hadoop.security.authentication.server.AuthenticationFilter.doFilter(AuthenticationFilter.java:589)
org.apache.hadoop.security.authentication.server.AuthenticationFilter.doFilter(AuthenticationFilter.java:552)
org.apache.oozie.servlet.AuthFilter.doFilter(AuthFilter.java:176)
org.apache.oozie.servlet.HostnameFilter.doFilter(HostnameFilter.java:86)
</pre></p><p><b>note</b> <u>The full stack trace of the root cause is available in the Apache Tomcat/6.0.44 logs.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.44</h3></body></html> (error 500)
Traceback (most recent call last):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/core/src/desktop/views.py", line 445, in _get_config_errors
for confvar, error in validator(request.user):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/libs/liboozie/src/liboozie/conf.py", line 86, in config_validator
intrumentation = api.get_instrumentation()
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/libs/liboozie/src/liboozie/oozie_api.py", line 304, in get_instrumentation
resp = self._root.get('admin/instrumentation', params)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/core/src/desktop/lib/rest/resource.py", line 97, in get
return self.invoke("GET", relpath, params, headers=headers, allow_redirects=True)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/core/src/desktop/lib/rest/resource.py", line 78, in invoke
urlencode=self._urlencode)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/desktop/core/src/desktop/lib/rest/http_client.py", line 161, in execute
raise self._exc_class(ex)
RestException: <html><head><title>Apache Tomcat/6.0.44 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>java.lang.UnsupportedOperationException
org.apache.oozie.util.MetricsInstrumentation.getVariables(MetricsInstrumentation.java:333)
org.apache.oozie.servlet.BaseAdminServlet.instrToJson(BaseAdminServlet.java:339)
org.apache.oozie.servlet.BaseAdminServlet.sendInstrumentationResponse(BaseAdminServlet.java:396)
org.apache.oozie.servlet.BaseAdminServlet.doGet(BaseAdminServlet.java:127)
javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
org.apache.oozie.servlet.JsonRestServlet.service(JsonRestServlet.java:289)
javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
org.apache.oozie.servlet.AuthFilter$2.doFilter(AuthFilter.java:171)
org.apache.hadoop.security.authentication.server.AuthenticationFilter.doFilter(AuthenticationFilter.java:589)
org.apache.hadoop.security.authentication.server.AuthenticationFilter.doFilter(AuthenticationFilter.java:552)
org.apache.oozie.servlet.AuthFilter.doFilter(AuthFilter.java:176)
org.apache.oozie.servlet.HostnameFilter.doFilter(HostnameFilter.java:86)
</pre></p><p><b>note</b> <u>The full stack trace of the root cause is available in the Apache Tomcat/6.0.44 logs.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.44</h3></body></html> (error 500)
[28/Jan/2016 17:33:53 -0800] conf ERROR The application won't work without a running HiveServer2.
Traceback (most recent call last):
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/conf.py", line 185, in config_validator
server.get_databases()
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/server/dbms.py", line 151, in get_databases
handle = self.execute_and_wait(query, timeout_sec=timeout)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/server/dbms.py", line 548, in execute_and_wait
handle = self.client.query(query)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/server/hive_server2_lib.py", line 923, in query
return self._client.execute_async_query(query, statement)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/server/hive_server2_lib.py", line 703, in execute_async_query
return self.execute_async_statement(statement=query_statement, confOverlay=configuration)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/server/hive_server2_lib.py", line 721, in execute_async_statement
res = self.call(self._client.ExecuteStatement, req)
File "/opt/cloudera/parcels/CDH-5.5.1-1.cdh5.5.1.p0.11/lib/hue/apps/beeswax/src/beeswax/server/hive_server2_lib.py", line 597, in call
raise QueryServerException(Exception('Bad status for request %s:\n%s' % (req, res)), message=message)
QueryServerException: Bad status for request TExecuteStatementReq(confOverlay={}, sessionHandle=TSessionHandle(sessionId=THandleIdentifier(secret='r\x94N\xc0\xac\x99D\xd9\xad\xe1\xb7\x15?N\xd4B', guid='o\x1c\xe77\x06\x7fJ\x19\xaa\xd9N\xf0.\xcd[\xc2')), runAsync=True, statement="SHOW DATABASES LIKE '*'"):
TExecuteStatementResp(status=TStatus(errorCode=40000, errorMessage="Error while compiling statement: FAILED: InvalidConfigurationException hive.server2.authentication can't be none in non-testing mode", sqlState='42000', infoMessages=["*org.apache.hive.service.cli.HiveSQLException:Error while compiling statement: FAILED: InvalidConfigurationException hive.server2.authentication can't be none in non-testing mode:17:16", 'org.apache.hive.service.cli.operation.Operation:toSQLException:Operation.java:326', 'org.apache.hive.service.cli.operation.SQLOperation:prepare:SQLOperation.java:102', 'org.apache.hive.service.cli.operation.SQLOperation:runInternal:SQLOperation.java:171', 'org.apache.hive.service.cli.operation.Operation:run:Operation.java:268', 'org.apache.hive.service.cli.session.HiveSessionImpl:executeStatementInternal:HiveSessionImpl.java:410', 'org.apache.hive.service.cli.session.HiveSessionImpl:executeStatementAsync:HiveSessionImpl.java:397', 'org.apache.hive.service.cli.CLIService:executeStatementAsync:CLIService.java:258', 'org.apache.hive.service.cli.thrift.ThriftCLIService:ExecuteStatement:ThriftCLIService.java:509', 'org.apache.hive.service.cli.thrift.TCLIService$Processor$ExecuteStatement:getResult:TCLIService.java:1313', 'org.apache.hive.service.cli.thrift.TCLIService$Processor$ExecuteStatement:getResult:TCLIService.java:1298', 'org.apache.thrift.ProcessFunction:process:ProcessFunction.java:39', 'org.apache.thrift.TBaseProcessor:process:TBaseProcessor.java:39', 'org.apache.hive.service.auth.TSetIpAddressProcessor:process:TSetIpAddressProcessor.java:56', 'org.apache.thrift.server.TThreadPoolServer$WorkerProcess:run:TThreadPoolServer.java:285', 'java.util.concurrent.ThreadPoolExecutor:runWorker:ThreadPoolExecutor.java:1145', 'java.util.concurrent.ThreadPoolExecutor$Worker:run:ThreadPoolExecutor.java:615', 'java.lang.Thread:run:Thread.java:745', "*org.apache.sentry.binding.hive.conf.InvalidConfigurationException:hive.server2.authentication can't be none in non-testing mode:32:16", 'org.apache.sentry.binding.hive.authz.HiveAuthzBinding:validateHiveServer2Config:HiveAuthzBinding.java:167', 'org.apache.sentry.binding.hive.authz.HiveAuthzBinding:validateHiveConfig:HiveAuthzBinding.java:135', 'org.apache.sentry.binding.hive.authz.HiveAuthzBinding:<init>:HiveAuthzBinding.java:83', 'org.apache.sentry.binding.hive.authz.HiveAuthzBinding:<init>:HiveAuthzBinding.java:79', 'org.apache.sentry.binding.hive.HiveAuthzBindingHook:<init>:HiveAuthzBindingHook.java:109', 'sun.reflect.NativeConstructorAccessorImpl:newInstance0:NativeConstructorAccessorImpl.java:-2', 'sun.reflect.NativeConstructorAccessorImpl:newInstance:NativeConstructorAccessorImpl.java:57', 'sun.reflect.DelegatingConstructorAccessorImpl:newInstance:DelegatingConstructorAccessorImpl.java:45', 'java.lang.reflect.Constructor:newInstance:Constructor.java:526', 'java.lang.Class:newInstance:Class.java:374', 'org.apache.hadoop.hive.ql.hooks.HookUtils:getHooks:HookUtils.java:60', 'org.apache.hadoop.hive.ql.Driver:getHooks:Driver.java:1294', 'org.apache.hadoop.hive.ql.Driver:compile:Driver.java:407', 'org.apache.hadoop.hive.ql.Driver:compile:Driver.java:305', 'org.apache.hadoop.hive.ql.Driver:compileInternal:Driver.java:1110', 'org.apache.hadoop.hive.ql.Driver:compileAndRespond:Driver.java:1104', 'org.apache.hive.service.cli.operation.SQLOperation:prepare:SQLOperation.java:100'], statusCode=3), operationHandle=None)
The sentry log file shows no errors. I also checked in the web ui and
HiveServer2 is running.
Answer: This Hive error is about not setting 'hive.server2.authentication'
<https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-Authentication/SecurityConfiguration>,
but this is porbably related to your AWS security settings, as None should
work by default.
Other errors in Hue can be ignored, these are more warnings because some apps
like the Search app were disabled.
|
Pydev setup not recognizing undefined value
Question: I have PyDev setup in eclipse.I think I did everything to configure my
workspace to show python files in PyDev perspective. It still does not show
the files in Python format.
Steps tried
* installed PyDev in eclipse,
* Configured PythonPATH
* Associated file types.
* Opened in PyDev perspective.
* Closed and opened the project.
Still the files show in normal Text format..not in the python format.
Answer: After too many trials , I was able to get to something-- \- I changed the
PyDev-> Code Analysis -> Undefined to warning \- same with Imports as per in
this link --[How do I fix PyDev "Undefined variable from import"
errors?](http://stackoverflow.com/questions/2112715/how-do-i-fix-pydev-
undefined-variable-from-import-errors/2248987#2248987)
-I stopped and started eclipse again.
These steps took care of the issue. Hope it helps for anyone stuck like this.
|
Error importing python-igraph
Question: I'm trying to install python-igraph package. Installation works without any
warning nor error, but then, when I try to import the module, I get an error:
In [1]: import igraph
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-8e950eb5d8d8> in <module>()
----> 1 import igraph
/usr/local/lib/python2.7/site-packages/igraph/__init__.py in <module>()
32 # pylint: disable-msg=W0401
33 # W0401: wildcard import
---> 34 from igraph._igraph import *
35 from igraph._igraph import __version__, __build_date__
36 from igraph.clustering import *
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/igraph/_igraph.so, 2): Library not loaded: /usr/local/opt/gmp/lib/libgmp.10.dylib
Referenced from: /usr/local/opt/glpk/lib/libglpk.36.dylib
Reason: Incompatible library version: libglpk.36.dylib requires version 14.0.0 or later, but libgmp.10.dylib provides version 13.0.0
I can't manage to solve this problem. I saw [this
post](http://stackoverflow.com/questions/30505490/error-importing-igraph) and
tried their solutions but it did not work (the problem there was that glpk was
not installed, whereas for me it is installed).
To install it I did the following:
brew tap homebrew/science
brew install igraph
sudo pip install python-igraph
And I checked that gmp and glpk were installed with `brew install igraph`
Does anybody have an idea of how I could manage to install it?
I'm working on Mac os x el capitan, with python2.7
Thanks for your help
## Edit from Tamás answer:
I checked, and gmp and glpk do come from homebrew. In fact,
`/usr/local/opt/gmp` is a symlink to `<path_to_>Cellar/gmp/6.0.0a`and
`/usr/local/opt/glpk` to `<path_to_>Cellar/glpk/4.57`.
I tried anyway to uninstall igraph (`brew uninstall igraph`), move somewhere
else the files in `/usr/local/opt` for gmp and glpk, and reinstall igraph. But
I get exactely the same error while importing the python module...
Answer: It seems like GMP and GLPK are not coming from Homebrew and they are not
compatible with each other. You have to fix the installation of GMP and GLPK.
Alternatively, you can uninstall `igraph`, then temporarily move GMP's and
GLPK's directories from `/usr/local/opt` to somewhere else, then install
`igraph` again. `igraph` will then "think" that GLPK and GMP are not available
on your machine and compiles itself without GLPK and GMP support (and disable
some features that require GLPK and GMP).
|
How to import a module from the root dir having another with same name in a descendent package?
Question: I'm using python 2.7.10.
I understand that there is many questions related to this. I'm starting this
question because none of answers I found in StackOverflow answers my doubts.
My goal here is to clarify my understanding about the Python import machinery
with the help of the community.
I have a project with a structure like this:
./
./config.py
./modules
./modules/__init__.py
./modules/config.py
**config.py**
VALUE = 1
**modules/config.py**
import config
print(config.VALUE)
In this module, I want to get the VALUE constant from the module in the root
dir and print it. When I run the config in modules package I get the following
error:
$ python modules/config.py
Traceback (most recent call last):
File "modules/config.py", line 1, in <module>
import config
File "/test/modules/config.py", line 2, in <module>
print(config.VALUE)
AttributeError: 'module' object has no attribute 'VALUE'
I understand that the **import config** statement imports the module in the
current directory instead the one in the root dir. So I need to add a _kind of
hack_ to allow it import the module in the root dir:
**modules/config.py**
def import_from_root(name):
import os
import imp
root_path = os.path.dirname(os.path.abspath(__name__))
root_module = os.path.join(root_path, '{}.py'.format(name))
return imp.load_source('root_'.format(name), root_module)
print(import_from_root('config').VALUE)
Now it works:
$ python modules/config.py
1
But I'm wondering if this is the best way to do this. So, I have the following
questions:
1. Is there a more pythonic way to solve this?
2. To move to Python 3.x will improve this?
Please, consider that I don't want to change the directory structure or the
names of the modules.
Answer: This works if you'd rather change your current working directory than your sys
path:
from os import chdir
chdir('/')
import config
this might be better if you have other resources in root. Both this and the
above solution are more parsimonious and pythonic than your current solution.
|
Getting VS2015 to work with arcpy
Question: I am taking a course on programming ESRI's ArcGIS using Python. Although the
course content shows us how to work with various IDE's, I would like to do my
homework in Visual Studio 2015 (Community Edition). But I am having trouble
getting it to work on my laptop and would like some advice.
I have successfully installed ArcGIS. I have successfully run some Python
scripts which include the use of the arcpy module. One IDE that recognizes
arcpy, pycharm, shows me path information about the environment. For example,
PyCharm's External Libraries window shows C:\Python27\ArcGIS10.3 .
In Visual Studio, when I open a .py file known to run under the other
interpreters, the IDE marks import arcpy as an unknown package. So in Visual
Studio I am attempting to set up a new Python Enviornment, "ArcGIS-enabled",
to get it to recognize that package. So far I have not been successful. Here I
what I have tried so far:
I set
Prefix Path = C:\Python27\ArcGIS10.3\
Interpreter Path = C:\Python27\ArcGIS10.3\python.exe
Windowed Interpreter = C:\Python27\ArcGIS10.3\pythonw.exe
Library Path = C:\Python27\ArcGIS10.3\lib
Can someone please help me figure this out?
Answer: VS probably just needs a minute or two to recognize/load the arcpy package. So
after importing arcpy, just let it sit.
Further to that, if you want to add PYT (PythonToolboxes) as a supported type
to edit, do: **Tools** > **Options** > **Text Editor** > **File Extension**.
Type **pyt** into the text box and choose **Python Editor** from the dropdown
list.
[Reference link](https://cindygeodev.wordpress.com/2015/09/28/enable-
intellisense-in-pyt-files-in-ptvs/)
|
How to set a secondary y-axis in Python
Question: I'm currently trying to change the secondary y-axis values in a matplot graph
to `ymin = -1` and `ymax = 2`. I can't find anything on how to change the
values though. I am using the `secondary_y = True` argument in `.plot()`, so I
am not sure if changing the secondary y-axis values is possible for this. I've
included my current code for creating the plot.
df.plot()
df.plot(secondary_y = "Market")
Answer: From your example code, it seems you're using Pandas built in ploting
capabilities. One option to add a second layer is by using matplotlib directly
like in the [example
"two_scales.py"](http://matplotlib.org/examples/api/two_scales.html).
It uses
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot(df["..."])
# ...
ax2 = ax1.twinx()
ax2.plot(df["Market"])
ax2.set_ylim([0, 5])
where you can change the y-limits.
|
Python: Count uniq line(s) between 2 files
Question:
First File | Second File
bob | greg
bob | larry
mark | mark
larry | bruce
tom | tom
With the code bellow I get output: **bob** , but I need to get **bob x 2**
with open('some_file_1.txt', 'r') as file1:
with open('some_file_2.txt', 'r') as file2:
diff = set(file1).difference(file2)
with open('some_output_file.txt', 'w') as file_out:
for line in same:
file_out.write(line)
Answer: Sounds like you want the difference of two `collections.Counter` objects.
import collections
with open("file1.txt") as f1, open("file2.txt") as f2:
c1, c2 = collections.Counter(f1), collections.Counter(f2)
result = c1 - c2
# Counter({"bob": 2})
with open("output.txt", "w") as outf:
for line, count in result.items():
outf.write("{} x {}".format(line, count))
|
Down sampling in pandas and spline interpolation
Question: I am working with a hourly time series data in datetime format on x-axis and
pressure on y-axis.
I want to downsample the data to 3-minute intervals and then do a spline
interpolation on the y-axis data. I don't know how and if ipython notebook
(pandas or numpy) can handle this. I have like 5136 rows of data. Thanks in
advance.
2015/03/01 00:00:00 100.69
2015/03/01 01:00:00 100.48
2015/03/01 02:00:00 100.30
Answer: It looks like your data are sampled every hour, so when you say "downsample to
3 minutes interval," I think you mean "interpolate [somehow] between the
hourly measurements and then evaluate the interpolation at 3-minute
intervals." Is this right?
If so, try making your datetime index (or column) into a float like so:
import datetime
df['time_as_float'] = df.index.apply(datetime.timestamp())
Then start by taking a look at
[`scipy.interpolate.splrep`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splrep.html)
and its cousin
[`.splev`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html)
to generate, then evaluate, the splines.
[See also here. (Related SO
question).](http://stackoverflow.com/questions/13930367/interpolating-time-
series-in-pandas-using-cubic-spline?rq=1)
|
python how to loop through csv several times from top?
Question: I have a csv file (yy.csv) that looks like this:
term,country,score,week
aa,USA,26.17,11/22/15-11/28/15
bb,USA,16.5,11/15/15-11/21/15
cc,UK,31.36,11/22/15-11/28/15
dd,UK,21.24,11/15/15-11/21/15
ee,FR,19.2,11/22/15-11/28/15
I also have a list called country_list:
country_list=['USA','UK','FR']
I am looping through the CSV file for each country in the country list to get
the term value if country in country list == col2 and week ==
11/22/15-11/28/15.
Here is my code:
with open("yy.csv") as infile:
reader = csv.reader(infile)
next(reader, None)
for index,country in enumerate(country_list):
print country
last_week_dict[country] = []
for reader_row in reader:
if ((reader_row[1] == country) and (reader_row[3] == "11/22/15-11/28/15")):
last_week_dict[country].append(reader_row[0])
else:
continue
print last_week_dict[country]
The output i should be getting from the `print` statement:
last_week_dict['USA']=['aa']
last_week_dict['UK']=['cc']
last_week_dict['FR']=['ee']
However i only got value appended to the USA key:
last_week_dict['USA']=['aa']
last_week_dict['UK']=[]
last_week_dict['FR']=[]
Could it be because when i loop through the csv file, it doesnt start from the
top of the file after it goes through USA?
Answer: Your suspicion is correct: the `reader` object is an iterator, and iterators
may only be read in the forward direction. They can't be reset.
You can avoid doing two loops from the file - it seems that your goal is to
make sure that you get data for the specific countries. However, you can make
sure that happens in a single loop:
import collections
import csv
# If this were a much longer collection of items it
# would be better to use a set than a list.
country_list = ['USA', 'UK', 'FR']
# The defauldict(list) allows us to just start appending
# rather than checking whether the key is already in the
# dict.
last_week_dict = collections.defaultdict(list)
with open('yy.csv') as infile:
reader = csv.reader(infile)
__ = next(reader) # Skip the header
for term, country, score, week in reader:
if country not in country_list:
continue
if week != '11/22/15-11/28/15':
continue
last_week_dict[country].append(term)
print(last_week_dict)
|
Long elif chains vs dictionary with exec()
Question: I am a novice to python and I have read a lot of tutorials on how to properly
code. One thing that keep popping up is to never write the same line of code
multiple times. I am unsure if long elif arguments count for that, but to me
it just looks like bad code.
for exaple:
class answers(object):
def __init__(self):
self.x = 'hello world'
def knight(self):
print('Neee!')
def bunny(self):
print('Rawwww!')
def pesant(self):
print('Witch!')
def dingo(self):
print('Bad, wicked, naughty Zoot!')
foo = answers()
egg = input("Sounds:")
if egg == "knight":
foo.knight()
elif egg == 'bunny':
foo.bunny()
elif egg == 'pesant':
foo.pesant()
elif egg == 'dingo':
foo.dingo()
else:
print("I don't know?")
That works but I think the following code is looks cleaner.
class answers(object):
def __init__(self):
self.x = 'hello world'
def knight(self):
print('Neee!')
def bunny(self):
print('Rawwww!')
def pesant(self):
print('Witch!')
def dingo(self):
print('Bad, wicked, naughty Zoot!')
foo = answers()
responce = {'knight': 'foo.knight()', 'bunny': 'foo.bunny()', 'pesant': 'foo.pesant()', 'dingo': 'foo.dingo()'}
while True:
try:
egg = input('sounds:')
exec(responce[egg])
except KeyError:
print("I don't know")
Both lines of code do the same thing, does it really matter which I use or is
one better then the other?
side note, I know that exec() should not normally be used but I could not find
another way to assign a function to a string.
Answer: You can assign function name to variable if you skip `()` and arguments
responce = {
'knight': foo.knight,
'bunny': foo.bunny,
'pesant': foo.pesant,
'dingo': foo.dingo,
}
And then you can run it using `()` (with expected arguments)
responce[egg]()
#responce[egg](arg1, arg2, ...) # if function require arguments
Full code
class Answers(object): # CamelCase name for class - see PEP8 document
def __init__(self):
self.x = 'hello world'
def knight(self):
print('Neee!')
def bunny(self):
print('Rawwww!')
def pesant(self):
print('Witch!')
def dingo(self):
print('Bad, wicked, naughty Zoot!')
foo = Answers()
responce = {
'knight': foo.knight,
'bunny': foo.bunny,
'pesant': foo.pesant,
'dingo': foo.dingo,
}
while True:
try:
egg = input('sounds:')
responce[egg]() # call function
except KeyError:
print("I don't know")
* * *
**BTW:** This way you can even use function name as argument for another
function.
It is use in Tkinter to assign function to Button
Button( ..., text="knight", command=foo.knight)
or to assign function to event
bind('<Button-1>', foo.knight)
* * *
If you need to assign function with arguments then you can use `lambda`
function.
Version for Python3:
responce = {
'knight': lambda:print('Neee!'),
'bunny': lambda:print('Rawwww!'),
'pesant': lambda:print('Witch!'),
'dingo': lambda:print('Bad, wicked, naughty Zoot!'),
}
Version for Python2:
`print` in Python2 is not a function so `lambda` will not work with `print` \-
so you have to create function.
def show(text):
print text
responce = {
'knight': lambda:show('Neee!'),
'bunny': lambda:show('Rawwww!'),
'pesant': lambda:show('Witch!'),
'dingo': lambda:show('Bad, wicked, naughty Zoot!'),
}
* * *
**EDIT:** But I would do this without functions in dictionary :)
# --- classes ---
class Answers(object):
def __init__(self):
# TODO: read it from file CSV or JSON
#
# import json
#
# with open("data.json") as f:
# self.data = json.load(f)
self.data = {
'knight': 'Neee!',
'bunny': 'Rawwww!',
'pesant': 'Witch!',
'dingo': 'Bad, wicked, naughty Zoot!',
}
def response(self, text):
try:
return self.data[text]
except KeyError:
return "I don't know"
# --- functions ---
# empty
# --- main ---
foo = Answers()
while True:
egg = input('sounds: ').lower()
if egg == 'exit':
break
print(foo.response(egg))
# ---
print("Good Bye!")
|
How can I open a docx file, find a particular string occurring at multiple places and add two lines after that in the whole document using python?
Question: As I am new to the python programming, I want to open a .docx file, parse it,
find occurrence of particular string in multiple places and then adding two
lines after that in whole document. How can i do these thing using python
script?
Answer: You could do this as follows using `win32com`:
import win32com.client
search_for = "This is some text in my file"
add_lines = "^pLine1^pLine2^pLine3" # ^p creates a new line
word = win32com.client.Dispatch("Word.Application")
word.Visible = False
word.DisplayAlerts = False
doc = word.Documents.Open(r'c:\my_folder\my_file.docx')
const = win32com.client.constants
find = doc.Content.Find
find.ClearFormatting()
find.Replacement.ClearFormatting()
find.Execute(Forward=True, Replace=const.wdReplaceAll, FindText=search_for, ReplaceWith=search_for+add_lines)
word.ActiveDocument.SaveAs(r'c:\my_folder\my_file_output.docx')
word.Quit()
To change the colour of the replacement text you could also add the following
before the `find.Execute`:
find.Replacement.Font.Color = 255 # wdColorRed
A full list of standard Word colours is listed on the [Microsoft
site](https://msdn.microsoft.com/en-us/library/office/ff196272.aspx).
|
Softlayer Python API:multiple local properties of billing item are not returned
Question: Calling the billing_Item Python API, a billing_item is returned BUT a lot of
(interesting) local properties are not returned. The local properties of my
interest all have to do with uptime and fees (e.g. laborFee, oneTimeFee,
hoursUsed, recurringFee, ...), but they are not returned.
What I do:
import SoftLayer
conn = SoftLayer.create_client_from_env(username='',api_key='')
allParents = conn.call('Account','getAllTopLevelBillingItems') #allParents is a list with billing_Items
allParents[0] # returns the first billing_Item as a dict but without a lot of relevant parameters
Also, the children billing items of each parent billing item lack a lot of
local properties.
Answer: The below python script displays the local properties that you need. Also, if
your script doesn't return the properties that you need, please apply object
masks, like this example:
import SoftLayer
# For nice debug output:
from pprint import pprint as pp
apiUsername = 'set me'
apiKey = 'set me'
client = SoftLayer.Client(
username=apiUsername,
api_key=apiKey
)
objectMask = 'mask[id,laborFee,oneTimeFee,recurringFee]'
try:
result = client['SoftLayer_Account'].getAllTopLevelBillingItems(mask=objectMask)
pp(result)
except Exception as e:
pp('Failed ............', e)
I hope it helps you.
|
Using a loop to make a dictionary
Question: I'm trying to make a binary2acii and vise versa `Dictonary` via Python shell.
I'm a bit stuck:
1. I make a new `Dictonary`
2. I need to declare, that it goes from 0-127
3. Make a loop to go through all options
I'm new to this.
binary2ascii = {},
format (127,"08b")
for i in range(0,127): chr(i)
Answer: It sounds like you need to spend a little more time learning Python
essentials.
Anyway, here's a way to make a dictionary that handles both converting a
bitstring to a character and vice versa. I just loop over `range(65, 70)` to
keep the output small.
from pprint import pprint
binary2ascii = {}
for i in range(65, 70):
bits = format(i, "08b")
char = chr(i)
binary2ascii[bits] = char
binary2ascii[char] = bits
pprint(binary2ascii)
**output**
{'01000001': 'A',
'01000010': 'B',
'01000011': 'C',
'01000100': 'D',
'01000101': 'E',
'A': '01000001',
'B': '01000010',
'C': '01000011',
'D': '01000100',
'E': '01000101'}
|
Python pandas plot time-series with gap
Question: I am trying to plot a pandas DataFrame with TimeStamp indizes that has a time
gap in its indizes. Using pandas.plot() results in linear interpolation
between the last TimeStamp of the former segment and the first TimeStamp of
the next. I do not want linear interpolation, nor do I want empty space
between the two date segments. Is there a way to do that?
Suppose we have a DataFrame with TimeStamp indizes:
>>> import numpy as np
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> df = pd.DataFrame(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
>>> df = df.cumsum()
Now lets take two time chunks of it and plot it:
>>> df = pd.concat([df['Jan 2000':'Aug 2000'], df['Jan 2001':'Aug 2001']])
>>> df.plot()
>>> plt.show()
The resulting plot has an interpolation line connecting the TimeStamps
enclosing the gap. I cannot figure out how to upload pictures on this machine,
but these pictures from [Google
Groups](https://groups.google.com/forum/#!msg/pydata/x46E9Gpac68/oO2w2TiYR4w)
show my problem (interpolated.jpg, no-interpolation.jpg and no gaps.jpg). I
can recreate the first as shown above. The second is achievable by replacing
all gap values with NaN (see also [this
question](http://stackoverflow.com/questions/27266987/python-matplotlib-avoid-
plotting-gaps)). How can I achieve the third version, where the time gap is
omitted?
Answer: Try:
df.plot(x=df.index.astype(str))
[](http://i.stack.imgur.com/1Rb14.png)
You may want to customize ticks and tick labels.
**EDIT**
That works for me using pandas 0.17.1 and numpy 1.10.4.
All you really need is a way to convert the `DatetimeIndex` to another type
which is not datetime-like. In order to get meaningful labels I chose `str`.
If `x=df.index.astype(str)` does not work with your combination of
pandas/numpy/whatever you can try other options:
df.index.to_series().dt.strftime('%Y-%m-%d')
df.index.to_series().apply(lambda x: x.strftime('%Y-%m-%d'))
...
I realized that resetting the index is not necessary so I removed that part.
|
Python: How to compute the top X most frequently used words in an NLTK corpus?
Question: I'm unsure if I've understood correctly how the FreqDist functions works on
Python. As I am following a tutorial, I am led to believe that the following
code constructs a frequency distribution for a given list of words and
calculates the top x frequently used words. (In the example below let corpus
be an NLTK corpus and file to be a filename of a file in that corpus)
words = corpus.words('file.txt')
fd_words = nltk.FreqDist(word.lower() for word in words)
fd_words.items()[:x]
However, when I go through the following commands on Python, it seems to
suggest otherwise:
>>> from nltk import *
>>> fdist = FreqDist(['hi','my','name','is','my','name'])
>>> fdist
FreqDist({'my': 2, 'name':2, 'is':1, 'hi':1}
>>> fdist.items()
[('is',1),('hi',1),('my',2),('name',2)]
>>> fdist.items[:2]
[('is',1),('hi',1)]
The fdist.items()[:x] method is in fact returning the x least common words?
Can someone tell me if I have done something wrong or if the mistake lies in
the tutorial I am following?
Answer: By default a `FreqDist` is not sorted. I think you are looking for
`most_common` method:
from nltk import FreqDist
fdist = FreqDist(['hi','my','name','is','my','name'])
fdist.most_common(2)
Returns:
[('my', 2), ('name', 2)]
|
AppRegistryNotReady: Apps aren't loaded yet. Django
Question: I'm trying to run django 1.9 on google app engine. Got the below error when
trying to access API's through Google API Explorer.
Traceback (most recent call last):
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject
__import__(cumulative_path)
File "/home/gemini/projects/cityguide-backend/src/cityguide/api/services.py", line 9, in <module>
from cityguide.api.internal.categories import Categories
File "/home/gemini/projects/cityguide-backend/src/cityguide/api/internal/categories.py", line 10, in <module>
from cityguide.models import Category
File "/home/gemini/projects/cityguide-backend/src/cityguide/models.py", line 8, in <module>
class ContactDetails(models.Model):
File "/home/gemini/projects/cityguide-backend/src/lib/django/db/models/base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/gemini/projects/cityguide-backend/src/lib/django/apps/registry.py", line 239, in get_containing_app_config
self.check_apps_ready()
File "/home/gemini/projects/cityguide-backend/src/lib/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
AppRegistryNotReady: Apps aren't loaded yet.
I already added
builtins:
- deferred: on
- remote_api: on
- django_wsgi: on
handlers:
- url: .*
script: mysite.wsgi.application
env_variables:
DJANGO_SETTINGS_MODULE: 'mysite.settings'
inside `app.yaml` file.
`wsgi.py` looks like
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
I tried adding `django.setup()` line on the top of `models.py` but it shows a
different error.
ERROR 2016-02-01 10:03:02,918 wsgi.py:263]
Traceback (most recent call last):
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject
__import__(cumulative_path)
File "/home/gemini/projects/cityguide-backend/src/cityguide/api/services.py", line 9, in <module>
from cityguide.api.internal.categories import Categories
File "/home/gemini/projects/cityguide-backend/src/cityguide/api/internal/categories.py", line 10, in <module>
from cityguide.models import Category
File "/home/gemini/projects/cityguide-backend/src/cityguide/models.py", line 6, in <module>
django.setup()
File "/home/gemini/projects/cityguide-backend/src/lib/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/gemini/projects/cityguide-backend/src/lib/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/gemini/projects/cityguide-backend/src/lib/django/contrib/admin/apps.py", line 22, in ready
self.module.autodiscover()
File "/home/gemini/projects/cityguide-backend/src/lib/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/gemini/projects/cityguide-backend/src/lib/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/gemini/projects/cityguide-backend/src/cityguide/admin.py", line 2, in <module>
from cityguide.models import Category
ImportError: cannot import name Category
ERROR 2016-02-01 10:03:02,919 wsgi.py:263]
Traceback (most recent call last):
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/home/gemini/softwares/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject
__import__(cumulative_path)
File "/home/gemini/projects/cityguide-backend/src/cityguide/api/services.py", line 9, in <module>
from cityguide.api.internal.categories import Categories
File "/home/gemini/projects/cityguide-backend/src/cityguide/api/internal/categories.py", line 10, in <module>
INFO 2016-02-01 10:03:03,000 module.py:794] default: "POST /_ah/spi/BackendService.getApiConfigs HTTP/1.1" 500 -
from cityguide.models import Category
INFO 2016-02-01 10:03:03,001 module.py:794] default: "POST /_ah/spi/BackendService.getApiConfigs HTTP/1.1" 500 -
File "/home/gemini/projects/cityguide-backend/src/cityguide/models.py", line 6, in <module>
INFO 2016-02-01 10:03:03,001 module.py:794] default: "GET /_ah/api/discovery/v1/apis HTTP/1.1" 500 60
django.setup()
INFO 2016-02-01 10:03:03,001 module.py:794] default: "GET /_ah/api/discovery/v1/apis HTTP/1.1" 500 60
File "/home/gemini/projects/cityguide-backend/src/lib/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/gemini/projects/cityguide-backend/src/lib/django/apps/registry.py", line 78, in populate
raise RuntimeError("populate() isn't reentrant")
RuntimeError: populate() isn't reentrant
**Temporary solution for this problem:**
Seems like I need to open the home page first. So that it would loads the db
since I made the homepage to return all the db table contents . Once the db
lists shown on the home page, we are ready to call the Google API Explorer.
Is there any way to refine this solution?
Answer: You should first initiate django this way in your script:
import django
django.setup()
See <https://docs.djangoproject.com/en/1.9/ref/applications/#django.setup>
You can also look at the Troubleshooting section of the link to see other
possibilities to solve this aprticular exception.
By adding the above two lines at the top of `services.py` file solves this
problem for me..
|
How to make googlemaps python library detect SSL certificates?
Question: **The problem**
Make to work:
import googlemaps
gmaps = googlemaps.Client(key='AIza...')
# Geocoding an address
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
**Tried so far ...**
I fixed all requests library relevant issues:
>>> requests.__version__
'2.9.1'
I have requests installed through pip.
Also I tried to expose the problem by trying another case:
import requests
import certifi
r = requests.get('https://graph.facebook.com/spotify', verify=certifi.where())
r = requests.get('https://graph.facebook.com/spotify')
All works without any problems.
Then:
openssl s_client -connect graph.facebook.com:443 -CAfile $(python -m certifi)
Works without any problem.
But:
import googlemaps
gmaps = googlemaps.Client(key='AIza...')
# Geocoding an address
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
Returns:
Traceback (most recent call last):
File "get_times.py", line 7, in <module>
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
File "/usr/local/lib/python2.7/dist-packages/googlemaps/geocoding.py", line 68, in geocode
return client._get("/maps/api/geocode/json", params)["results"]
File "/usr/local/lib/python2.7/dist-packages/googlemaps/client.py", line 205, in _get
raise googlemaps.exceptions.TransportError(e)
googlemaps.exceptions.TransportError: bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)
What's double weird - it seems to work this way (I cut out the long hex-
codes):
$ openssl s_client -connect maps.googleapis.com:443 -CAfile $(python -m certifi)
CONNECTED(00000003)
depth=3 C = US, O = Equifax, OU = Equifax Secure Certificate Authority
verify return:1
depth=2 C = US, O = GeoTrust Inc., CN = GeoTrust Global CA
verify return:1
depth=1 C = US, O = Google Inc, CN = Google Internet Authority G2
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = *.googleapis.com
verify return:1
---
Certificate chain
0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.googleapis.com
i:/C=US/O=Google Inc/CN=Google Internet Authority G2
1 s:/C=US/O=Google Inc/CN=Google Internet Authority G2
i:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
2 s:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
i:/C=US/O=Equifax/OU=Equifax Secure Certificate Authority
---
Server certificate
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
subject=/C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.googleapis.com
issuer=/C=US/O=Google Inc/CN=Google Internet Authority G2
---
No client certificate CA names sent
---
SSL handshake has read 3820 bytes and written 431 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1.2
Cipher : ECDHE-RSA-AES128-GCM-SHA256
Session-ID: ...
Session-ID-ctx:
Master-Key: ...
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 100800 (seconds)
TLS session ticket:
0000 - ... ....
Start Time: 1454060879
Timeout : 300 (sec)
Verify return code: 0 (ok)
---
No idea if this is a valid approach, but when I tried:
import requests
import certifi
API_KEY = "AIza..."
url = ("https://maps.googleapis.com/maps/api/directions/json?"
"origin=75+9th+Ave+New+York,+NY&"
"destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&"
"key=%s") % (API_KEY)
r = requests.get(url, verify=certifi.where())
The result was:
Traceback (most recent call last):
File "get_times.py", line 10, in <module>
r = requests.get(url, verify=certifi.where())
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 67, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 53, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 447, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)
I'm not running this on any server or hosting... I'm just trying to make it
work as a simple CLI script on my PC...
Answer: Thanks to Liam Horne for his answer here:
<http://stackoverflow.com/a/34665344/552621>
> I found a solution. There seems to be a major issue in the version of
> `certifi` that was running. I found this out from this (very long) GitHub
> issue: <https://github.com/certifi/python-certifi/issues/26>
>
> **TL;DR**
>
> `pip uninstall -y certifi && pip install certifi==2015.04.28`
|
Python regular expression simple OR condition doesn't work?
Question: I am trying to write a simple regular expression in Python that recognizes
either a comma or a newline, to be used as a delimiter and split() text.
I have tried the following:
delim = r'[,\n]'
delim = r'[\n,]'
delim = r',|\n'
delim = r'[,|\n]'
delim = r'(,\n)'
None of these work. The split() works fine if I make it just one or the other,
such as...
delim = r','
delim = r'\n'
But not if I try and do both.
What am I missing here?
Thank you for your input.
Whole code:
data = "abc,def\nghi"
delim = r'[,\n]'
values = data.split(delim)
print(values)
Answer: You are using `str.split()`, which doesn't take a regex as an argument.
Try using `re.compile` on your regex string, and then using that object for
the split:
import re
data = "abc,def\nghi"
delim = re.compile(r'[,\n]')
values = delim.split(data)
print(values)
Yields:
['abc', 'def', 'ghi']
|
Python-ONVIF PTZ control -- Absolute and Relative Move
Question: I am developing an application in Python to control ONVIF-compatible cameras.
Software: Debian Wheezy, Python 2.7, Quatanium python-onvif client
Hardware: Raspberry Pi 2 B, IP camera on local router, wifi/VNC for
development
The required PTZ functions include Absolute Move, Relative Move, Continuous
Move, Stop and using Preset positions. With the extracted test code below, I
have all of that working except Absolute and Relative Moves. All of this code
executes without any errors but the camera does not move for the Absolute or
Relative Moves. I hope someone can suggest the problem with those two
functions. The example is a bit long but I have tried to include enough code
to show the contrast between working and non-working (with upper-case
comments) portions for reference and test.
**A test sketch:**
#!/usr/bin/python
#-------------------------------------------------------------------------------
#Test of Python and Quatanium Python-ONVIF with NETCAT camera PT-PTZ2087
#ONVIF Client implementation is in Python
#For IP control of PTZ, the camera should be compliant with ONVIF Profile S
#The PTZ2087 reports it is ONVIF 2.04 but is actually 2.4 (Netcat said text not changed after upgrade)
#------------------------------------------------------------------------------
import onvifconfig
if __name__ == '__main__':
#Do all setup initializations
ptz = onvifconfig.ptzcam()
#*****************************************************************************
# IP camera motion tests
#*****************************************************************************
print 'Starting tests...'
#Set preset
ptz.move_pan(1.0, 1) #move to a new home position
ptz.set_preset('home')
# move right -- (velocity, duration of move)
ptz.move_pan(1.0, 2)
# move left
ptz.move_pan(-1.0, 2)
# move down
ptz.move_tilt(-1.0, 2)
# Move up
ptz.move_tilt(1.0, 2)
# zoom in
ptz.zoom(8.0, 2)
# zoom out
ptz.zoom(-8.0, 2)
#Absolute pan-tilt (pan position, tilt position, velocity)
#DOES NOT RESULT IN CAMERA MOVEMENT
ptz.move_abspantilt(-1.0, 1.0, 1.0)
ptz.move_abspantilt(1.0, -1.0, 1.0)
#Relative move (pan increment, tilt increment, velocity)
#DOES NOT RESULT IN CAMERA MOVEMENT
ptz.move_relative(0.5, 0.5, 8.0)
#Get presets
ptz.get_preset()
#Go back to preset
ptz.goto_preset('home')
exit()
**The referenced class:**
#*****************************************************************************
#IP Camera control
#Control methods:
# rtsp video streaming via OpenCV for frame capture
# ONVIF for PTZ control
# ONVIF for setup selections
#
# Starting point for this code was from:
# https://github.com/quatanium/python-onvif
#*****************************************************************************
import sys
sys.path.append('/usr/local/lib/python2.7/dist-packages/onvif')
from onvif import ONVIFCamera
from time import sleep
class ptzcam():
def __init__(self):
print 'IP camera initialization'
#Several cameras that have been tried -------------------------------------
#Netcat camera (on my local network) Port 8899
self.mycam = ONVIFCamera('192.168.1.10', 8899, 'admin', 'admin', '/etc/onvif/wsdl/')
#This is a demo camera that anyone can use for testing
#Toshiba IKS-WP816R
#self.mycam = ONVIFCamera('67.137.21.190', 80, 'toshiba', 'security', '/etc/onvif/wsdl/')
print 'Connected to ONVIF camera'
# Create media service object
self.media = self.mycam.create_media_service()
print 'Created media service object'
print
# Get target profile
self.media_profile = self.media.GetProfiles()[0]
# Use the first profile and Profiles have at least one
token = self.media_profile._token
#PTZ controls -------------------------------------------------------------
print
# Create ptz service object
print 'Creating PTZ object'
self.ptz = self.mycam.create_ptz_service()
print 'Created PTZ service object'
print
#Get available PTZ services
request = self.ptz.create_type('GetServiceCapabilities')
Service_Capabilities = self.ptz.GetServiceCapabilities(request)
print 'PTZ service capabilities:'
print Service_Capabilities
print
#Get PTZ status
status = self.ptz.GetStatus({'ProfileToken':token})
print 'PTZ status:'
print status
print 'Pan position:', status.Position.PanTilt._x
print 'Tilt position:', status.Position.PanTilt._y
print 'Zoom position:', status.Position.Zoom._x
print 'Pan/Tilt Moving?:', status.MoveStatus.PanTilt
print
# Get PTZ configuration options for getting option ranges
request = self.ptz.create_type('GetConfigurationOptions')
request.ConfigurationToken = self.media_profile.PTZConfiguration._token
ptz_configuration_options = self.ptz.GetConfigurationOptions(request)
print 'PTZ configuration options:'
print ptz_configuration_options
print
self.requestc = self.ptz.create_type('ContinuousMove')
self.requestc.ProfileToken = self.media_profile._token
self.requesta = self.ptz.create_type('AbsoluteMove')
self.requesta.ProfileToken = self.media_profile._token
print 'Absolute move options'
print self.requesta
print
self.requestr = self.ptz.create_type('RelativeMove')
self.requestr.ProfileToken = self.media_profile._token
print 'Relative move options'
print self.requestr
print
self.requests = self.ptz.create_type('Stop')
self.requests.ProfileToken = self.media_profile._token
self.requestp = self.ptz.create_type('SetPreset')
self.requestp.ProfileToken = self.media_profile._token
self.requestg = self.ptz.create_type('GotoPreset')
self.requestg.ProfileToken = self.media_profile._token
print 'Initial PTZ stop'
print
self.stop()
#Stop pan, tilt and zoom
def stop(self):
self.requests.PanTilt = True
self.requests.Zoom = True
print 'Stop:'
#print self.requests
print
self.ptz.Stop(self.requests)
print 'Stopped'
#Continuous move functions
def perform_move(self, timeout):
# Start continuous move
ret = self.ptz.ContinuousMove(self.requestc)
print 'Continuous move completed', ret
# Wait a certain time
sleep(timeout)
# Stop continuous move
self.stop()
sleep(2)
print
def move_tilt(self, velocity, timeout):
print 'Move tilt...', velocity
self.requestc.Velocity.PanTilt._x = 0.0
self.requestc.Velocity.PanTilt._y = velocity
self.perform_move(timeout)
def move_pan(self, velocity, timeout):
print 'Move pan...', velocity
self.requestc.Velocity.PanTilt._x = velocity
self.requestc.Velocity.PanTilt._y = 0.0
self.perform_move(timeout)
def zoom(self, velocity, timeout):
print 'Zoom...', velocity
self.requestc.Velocity.Zoom._x = velocity
self.perform_move(timeout)
#Absolute move functions --NO ERRORS BUT CAMERA DOES NOT MOVE
def move_abspantilt(self, pan, tilt, velocity):
self.requesta.Position.PanTilt._x = pan
self.requesta.Position.PanTilt._y = tilt
self.requesta.Speed.PanTilt._x = velocity
self.requesta.Speed.PanTilt._y = velocity
print 'Absolute move to:', self.requesta.Position
print 'Absolute speed:',self.requesta.Speed
ret = self.ptz.AbsoluteMove(self.requesta)
print 'Absolute move pan-tilt requested:', pan, tilt, velocity
sleep(2.0)
print 'Absolute move completed', ret
print
#Relative move functions --NO ERRORS BUT CAMERA DOES NOT MOVE
def move_relative(self, pan, tilt, velocity):
self.requestr.Translation.PanTilt._x = pan
self.requestr.Translation.PanTilt._y = tilt
self.requestr.Speed.PanTilt._x = velocity
ret = self.requestr.Speed.PanTilt._y = velocity
self.ptz.RelativeMove(self.requestr)
print 'Relative move pan-tilt', pan, tilt, velocity
sleep(2.0)
print 'Relative move completed', ret
print
#Sets preset set, query and and go to
def set_preset(self, name):
self.requestp.PresetName = name
self.requestp.PresetToken = '1'
self.preset = self.ptz.SetPreset(self.requestp) #returns the PresetToken
print 'Set Preset:'
print self.preset
print
def get_preset(self):
self.ptzPresetsList = self.ptz.GetPresets(self.requestc)
print 'Got preset:'
print self.ptzPresetsList[0]
print
def goto_preset(self, name):
self.requestg.PresetToken = '1'
self.ptz.GotoPreset(self.requestg)
print 'Going to Preset:'
print name
print
@Ottavio, Sorry that I did not make it clear that the camera I used for this
test, a Netcat PT-PTZ2084XM-A reported via ONVIF query that it did support
Absolute and Relative moves. I have subsequently verified via the onvif.org
site that this camera has not been tested and verified to meet onvif
standards. I also have verified that the above code does work correctly with a
Amcrest IP2M-841B ptz camera. The upshot of all of this is to never trust the
claim that a camera is ONVIF 2.x compatible without testing it. Even the
Amcrest has problems with both ONVIF and cgi commands for zoom. Neither Netcat
nor Amcrest have been very helpful in resolving these technical problems.
Answer: `AbsoluteMake` and `RelativeMove` in the [Profile S
specifications](http://www.onvif.org/Portals/0/documents/op/ONVIF_Profile_%20S_Specification_v1-1-1.pdf)
are `CONDITIONAL MANDATORY`, thus it is not guaranteed a-priori that they are
supported.
You need to check the camera's features.
|
Connect to dynamic database parameters sqlalchemy
Question: I am using sqlalchemy to connect to my database for my python API like so:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'
My problem is that other developers in this project have different database
username/passwords. Whenever we push pull with git we have to reset the values
to accommodate the developers database. Is there a way we can have sqlalchemy
pull from a file? This way we could just add it to .gitignore.
Or is there an easier way to achieve this?
Answer: You want to set an environment variable for this. Since each environment is
unique to the machine it's running on, each team member will have their own
connection string picked up from their respective environment. I'll show an
example for Zsh shell, but Bash or other shells should be equivalent.
Create a file (if one doesn't exist already) called ~/.zshenv
In this file, add the line:
export DB_CONNECTION_STRING="mysql://username:password@localhost/dbname"
Note that there should be **no spaces** between the variable definition and
its value (namely the equal sign has no spaces around it). This was an issue
for me on Zsh.
To apply this variable run `source ~/.zshenv`. It will automatically load on restart, but we don't want to logout/login every time when changing an environment varialble. Verify the variable was defined by running `printenv | grep DB_CONNECTION_STRING`.
In flask, simply define the following (remembering to `import os` on top):
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING')
_Using environment variables is really the way to go_. I used to hard-code
stuff, which is bad practice and as you can see, would be a problem for even
something trivial like multiple users connecting to the same database.
**EDIT** : please see @rmn's comment about instance folder flask
functionality; seems like a solid alternative to environment variables (of
course, this is limited to the Flask application, environment variables can be
used for anything)
|
Attempting to extract text that is within tags <*word word word*> n times in each line via Python
Question:
text = 'the text stuff <*to test*> to find a way to extract all text'\
'that is <*included in special tags*> less than star and greater'\
'than star'
I've tried using: [Adding up re.finditer
results](http://stackoverflow.com/questions/20404552/adding-up-re-finditer-
results%20using%20yield%20in%20Python%202.7).
I've attempted many regex import re combinations.
I've tried variations of `\w+`.
I can print text with `'<* .... *>'` and replace `'<*'` and `'*>'` with blanks
using `.replace`, but I cannot use a DictReader to extract only the words
within the tags, since the tags appear to be special characters in Python.
Using the DictReader I pull the entire line of text, but not just with words
within the control character tags.
`.split` does work on the text for replace, but not for finding text within a
tag with unusual characters such as `<*...*>`.
I've tried escaping the characters `<`, `*` and `>` as in `\<|*.*?+\*\>` to
find all text within the tags or markers, but this doesn't work.
Python doesn't like these characters being escaped.
I've thought about finding them characters within octal tags for `<`, `*` and
`>` but that may be a distortion of how Python works.
Found good advice from Wes McKinney's and Beazley/Jones' books on Python.
Have tested start and end text, but these special characters don't substitute
well.
Apologize in advance for the complexity of the solutions attempted. Hope I'm
in the ballpark for the approach.
1. import and register csv
csv.register_dialect('piper', delimiter = '|', quoting=csv.QUOTE_NONE)
2. use a DictReader to read each row
with open('text') as csvfle:
for row in csv.DictReader(csvfile, dialect='piper'):
row["specialtext"] = row["text"].replace("<*", "").replace("*>", "").decode('windows-1252').encode('utf-8').strip()
print row['specialtext']
all this above works, but any attempt to find the text within the tags,
doesn't.
Answer: Consider using `re.findall()` to extract all matched text into a list and for
any special characters (like asterisk, `*`) escape with backslash:
import re
text = 'the text stuff <*to test*> to find a way to extract all text'\
'that is <*included in special tags*> less than star and greater'\
'than star'
txtsearch = re.findall('<\*(.*?)\*>', text)
if txtsearch:
print(txtsearch)
# ['to test', 'included in special tags']
|
Python Tools for Visual Studio Inline Graphics
Question: This one should be simple, but I've been searching all over and it seems to be
so simple that nobody else has encountered the problem yet :)
I just installed Python (2.7 Anaconda distribution) and Python Tools for
Visual Studio with Visual Studio 2015 Community. It all appears to be working,
but I would like to use the inline graphics feature and can't get it to work.
This code should (I think) do it, but instead shows nothing in the interactive
window and pulls up a new blank window for the plot.
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X,C)
plt.plot(X,S)
Do I need to configure something else before the inline graphics will work?
Answer: I had just about given up on this when I stumbled onto the solution on the
GitHub page for PTVS: <https://github.com/Microsoft/PTVS/wiki/Using-IPython-
with-PTVS>
After installing ipython and matplotlib (which I already had), you need to
click "Configure interactive window" within the Visual Studio "Python
Environments" window and then set the Interactive Mode to IPython instead of
Standard.
|
Failed with pip install chompack
Question: I'm trying to install chompack with pip to use in a Support Vector Machine
algorithm with cvxopt. However it gives me an error for which I haven't found
a clear answer. There is a [related
question](http://stackoverflow.com/q/12511815/2297475) but the answer provided
is very specific to the package the person is trying to install. In my case,
there's no binary package that I can download or even a _.whl_ file.
The specific error seems to be
error: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' failed with exit status 2
Here's what I typed in the command prompt (Windows 10 PC) and the full result.
pip install chompack
I get
Collecting chompack
Using cached chompack-2.2.1.tar.gz
Requirement already satisfied (use --upgrade to upgrade): cvxopt>=1.1.7 in c:\python27\lib\site-packages (from chompack)
Building wheels for collected packages: chompack
Running setup.py bdist_wheel for chompack ... error
Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\my_username\\appdata\\local\\temp\\pip-build-o8y8d4\\chompack\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d c:\users\my_username\appdata\local\temp\tmpv64_u4pip-wheel- --python-tag cp27:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd2 ...]
or: -c --help-commands
or: -c cmd --help
error: option --python-tag not recognized
----------------------------------------
Failed building wheel for chompack
Running setup.py clean for chompack
Failed to build chompack
Installing collected packages: chompack
Running setup.py install for chompack ... error
Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\my_username\\appdata\\local\\temp\\pip-build-o8y8d4\\chompack\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\my_username\appdata\local\temp\pip-fkqebc-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build\lib.win32-2.7
creating build\lib.win32-2.7\chompack
copying src\python\base.py -> build\lib.win32-2.7\chompack
copying src\python\conversion.py -> build\lib.win32-2.7\chompack
copying src\python\maxchord.py -> build\lib.win32-2.7\chompack
copying src\python\mcs.py -> build\lib.win32-2.7\chompack
copying src\python\misc.py -> build\lib.win32-2.7\chompack
copying src\python\pfcholesky.py -> build\lib.win32-2.7\chompack
copying src\python\symbolic.py -> build\lib.win32-2.7\chompack
copying src\python\__init__.py -> build\lib.win32-2.7\chompack
creating build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\cholesky.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\completion.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\edmcompletion.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\hessian.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\llt.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\plot.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\projected_inverse.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\psdcompletion.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\trmm.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\trsm.py -> build\lib.win32-2.7\chompack\pybase
copying src\python\pybase\__init__.py -> build\lib.win32-2.7\chompack\pybase
running build_ext
building 'cbase' extension
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
creating build\temp.win32-2.7\Release\src
creating build\temp.win32-2.7\Release\src\C
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Ic:\python27\include -Ic:\python27\PC /Tcsrc/C\cbase.c /Fobuild\temp.win32-2.7\Release\src/C\cbase.obj
cbase.c
c:\users\my_username\appdata\local\temp\pip-build-o8y8d4\chompack\src\c\cvxopt.h(31) : fatal error C1083: Cannot open include file: 'complex.h': No such file or directory
error: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' failed with exit status 2
----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\my_username\\appdata\\local\\temp\\pip-build-o8y8d4\\chompack\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\my_username\appdata\local\temp\pip-fkqebc-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\my_username\appdata\local\temp\pip-build-o8y8d4\chompack
Answer: I do not know the precise reason but you should use python itself to install
packages as `chompack`:
python -m pip install chompack
For further informations read the manual:
<https://docs.python.org/3/installing/>
PS: I have seen the same message but it installed it anyway.
|
Change spacing of dashes in dashed line in matplotlib
Question: In Python, using matplotlib, is there a way to change the distance of the
dashes for different linestyles, for example, using the following command:
plt.plot(x,y,linestyle='--')
Answer: You can directly specify the dashes length/space using the `dashes=(length,
interval space)` argument inside the plot command.
import matplotlib.pyplot as pet
fig,ax = plt.subplots()
ax.plot([0, 1], [0, 1], linestyle='--', dashes=(5, 1)) #length of 5, space of 1
ax.plot([0, 1], [0, 2], linestyle='--', dashes=(5, 5)) #length of 5, space of 5
ax.plot([0, 1], [0, 3], linestyle='--', dashes=(5, 10)) #length of 5, space of 10
ax.plot([0, 1], [0, 4], linestyle='--', dashes=(5, 20)) #length of 5, space of 20
[](http://i.stack.imgur.com/tOpf5.jpg)
|
Error with the command onkey()
Question: I'm trying to create a shooter-like game in Python turtle (it's basically a
copy of the game `Boom dots`). But I'm having a lot of issues, because I'm
kind of new to programming. This time the command onkey() doesn't work. I
tried everything but nothing seems to be of help. I don't get any traceback
errors. It's just that defined command doesn't work when I press the button
which is assigned to the command.
Part of code in which I suspect the problem is:
def cannon_left():
cannon_x = cannon_x - 10
cannon.goto(cannon_x, 0)
def cannon_right():
cannon_x = cannon_x + 10
cannon.goto(cannon_x, 0)
def reset1():
live_score = 0
The whole code:
import random
import turtle
#images
image_coconut = "Coconut.png"
image_banana = "Banana.png"
image_pineapple = "Pineapple.png"
image_cannon = "Cannon.png"
#definitions
live_score = 0
screen = turtle.Screen()
wn = turtle.Screen()
cannon = turtle.Turtle()
enemy = turtle.Turtle()
score = turtle.Turtle()
background = turtle.Turtle()
reset = turtle.Turtle()
bullet = turtle.Turtle()
enemy_x = enemy.xcor()
enemy_y = enemy.ycor()
cannon_x = 0
move_speed = 2
enemy1 = 0
def cannon_shooting(x, y):
bullet.showturtle()
bullet.forward(280)
if bullet.ycor() == enemy_y - 10:
if not bullet.xcor() == enemy_x - 10:
if live_score == 0:
live_score = 0
else:
live_score = live_score + 1
if bullet.xcor() == enemy_x - 10:
live_score = live_score + 1
enemy1 = random.randint(1, 3)
bullet.hideturtle()
#image adding
screen.addshape(image_coconut)
screen.addshape(image_banana)
screen.addshape(image_pineapple)
screen.addshape(image_cannon)
def cannon_left():
cannon_x = cannon_x - 10
cannon.goto(cannon_x, 0)
def cannon_right():
cannon_x = cannon_x + 10
cannon.goto(cannon_x, 0)
def reset1():
live_score = 0
#setup
bullet.hideturtle()
bullet.speed(50)
bullet.penup()
bullet.shape('circle')
bullet.goto(0, -140)
bullet.left(90)
enemy.speed(0)
enemy.penup()
enemy.hideturtle()
enemy.goto(0, 140)
screen.addshape(image_coconut)
enemy.shape(image_coconut)
enemy.showturtle()
cannon.speed(0)
cannon.penup()
cannon.hideturtle()
cannon.goto(0, -140)
screen.addshape(image_cannon)
cannon.shape(image_cannon)
cannon.showturtle()
cannon.left(90)
score.speed(0)
score.penup()
score.hideturtle()
score.goto(90, -190)
score.color('white')
score.write("Your score: %s" % live_score, font=(None, 11, "bold"))
reset.speed(0)
reset.penup()
reset.hideturtle()
reset.goto(-185, -190)
reset.color('white')
reset.write("Reset (R)", font=(None, 11, "bold"))
#movement
while True:
enemy.forward(move_speed)
if enemy.xcor() == 140:
enemy.left(180)
enemy.forward(move_speed)
if enemy.xcor() == -140:
enemy.right(180)
enemy.forward(move_speed)
if enemy1 == 1:
screen.addshape(image_banana)
enemy.shape(image_banana)
if enemy1 == 2:
screen.addshape(image_pineapple)
enemy.shape(image_pineapple)
if enemy1 == 3:
enemy.shape(image_coconut)
#key presses
wn.onkey(cannon_right, "D")
wn.onkey(cannon_left, "A")
wn.onkey(cannon_right, "Right")
wn.onkey(cannon_left, "Left")
wn.onkey(cannon_shooting, "SPACE")
wn.onkey(reset1, "R")
#others
wn.listen()
wn.mainloop()
**Note:** I'm creating the game in `Trinket.io`. Click
[here](https://trinket.io/python/ed2c612824 "Trinket.io") to go to the
`Trinket.io` version.
Answer: Python is an imperative programming language. This means that _order matters_.
What appears to be the main logic of your game is declared before the `onkey`
initialization part as an infinite loop:
#movement
while True:
enemy.forward(move_speed)
...
As this loop runs forever, it means that will start executing and the code
will never reach the part where you set up the key mapping.
You need the code that is in the loop put this code in a function, and decide
when exactly it needs to be called by Turtle. You should not put the `while
True` as part of the function, as there already exists a main loop managed by
Turtle.
|
Fortran version of python loop giving incorrect answer
Question: I've been working on an international trade model and the model has gotten
really slow (sometimes taking weeks at a time to finish). Mostly, there was a
big for loop that was slowing the process down, as shown here (in Python):
for s in xrange(self.S-1):
c_matrix[:,s+1,s+1:self.T+s+1] = ((self.beta * (1-self.MortalityRates[:,s,s:self.T+s]) * (1 + r_path[s+1:self.T+s+1] - self.delta)\
* psi[:,s+1,s+1:self.T+s+1])/psi[:,s,s:self.T+s])**(1/self.sigma) * c_matrix[:,s,s:self.T+s]*np.exp(-self.g_A)
a_matrix[:,s+1,s+1:self.T+s+1] = ( (we[:,s,s:self.T+s] + (1 + r_path[s:self.T+s] - self.delta)*a_matrix[:,s,s:self.T+s] + bqvec_path[:,s,s:self.T+s])\
-c_matrix[:,s,s:self.T+s]*(1+we[:,s,s:self.T+s]*(self.chi/we[:,s,s:self.T+s])**self.rho) )*np.exp(-self.g_A)
I won't go into too much detail about each piece, but I decided to make a
Fortran module that, in theory, should do the exact same thing but should run
significantly faster. I'm using Cython and distutils to wrap the Fortran
module. Here is the .f90 file (focusing specifically on the a_matrix part of
the for loop above) for your reference:
MODULE FILLA
USE ISO_C_BINDING, ONLY: C_DOUBLE, C_INT
IMPLICIT NONE
CONTAINS
SUBROUTINE
FILLASSETS(A_MATRIX,WE,R_PATH,BQ_VECPATH,C_MATRIX,I,S,T,DELTA,CHI,RHO,G_A) BIND(C)
INTEGER(C_INT), INTENT(IN) :: I,S,T
INTEGER :: X, E, L
REAL(C_DOUBLE), INTENT(IN) :: DELTA, CHI, RHO, G_A
REAL(C_DOUBLE), DIMENSION(0:I-1,0:S-1,0:T+S-1),INTENT(IN) :: C_MATRIX, WE, BQ_VECPATH
REAL(C_DOUBLE), DIMENSION(0:T+S-1), INTENT(IN) :: R_PATH
REAL(C_DOUBLE), DIMENSION(0:I-1,0:S,0:T+S-1), INTENT(INOUT) :: A_MATRIX
REAL(C_DOUBLE), DIMENSION(0:I-1,0:S-1,0:T+S-1):: R_PATHM
DO E = 0, I-1
DO L = 0, S-1
R_PATHM(E,L,:)=R_PATH(:)
ENDDO
ENDDO
DO X = 0, S-2
A_MATRIX(:,X+1,X+1:T+X+1) = ((WE(:,X,X:T+X)+(1.0D0+R_PATHM(:,X,X:T+X)-DELTA)&
&*A_MATRIX(:,X,X:T+X)+BQ_VECPATH(:,X,X:T+X))&
&-C_MATRIX(:,X,X:T+X)*(1.0D0+WE(:,X,X:T+X)*(CHI/WE(:,X,X:T+X))&
&**RHO))*EXP(-G_A)
ENDDO
END SUBROUTINE FILLASSETS
END MODULE
And this .pyx file is how the arrays from python get passed into Fortran:
from numpy cimport ndarray as ar
cdef extern from "filla.h":
void fillassets(double* A_Matrix, double* we, double* r_path, double* bq_vecpath, double* c_matrix, int* I, int* S, int* T, double* delta, double* chi, double* rho, double* g_A)
cpdef f_filla(ar[double, ndim=3] A_Mat, ar[double, ndim=3] w_e, ar[double, ndim=1] r_path, ar[double, ndim=3] bq_vecpath, ar[double,ndim=3] c_mat, double delta, double chi, double rho, double g_A):
cdef int I,S,T,Q
if A_Mat.flags['C_CONTIGUOUS'] and w_e.flags['C_CONTIGUOUS'] and r_path.flags['C_CONTIGUOUS'] and bq_vecpath.flags['C_CONTIGUOUS'] and c_mat.flags['C_CONTIGUOUS']:
I=c_mat.shape[0]
S=c_mat.shape[1]
Q=c_mat.shape[2]
T=Q-S
fillassets(&A_Mat[0,0,0],&w_e[0,0,0],&r_path[0],&bq_vecpath[0,0,0],&c_mat[0,0,0],&I,&S,&T,&delta,&chi,&rho,&g_A)
else:
raise ValueError("Input array U is not C-contiguous")
So I've set it up without any errors, but when I run them side by side, the
Fortran module returns incorrect values in the asset matrix, for some reason.
I think it's something relating to how Fortran and Python handle arrays, but I
haven't found a straightforward explanation and hope that I could find some
help here. I'm very unfamiliar with Fortran and so it's probably something
simple that I'm missing. I tried to keep this as brief as possible, so if
there are details I've left out, let me know.
EDIT: I'm using Mac OS X El Capitan and the gfortran complier.
Answer: Fortran uses the opposite layout of array elements: if you have an array of
dimensions (m,n) then elements would be laid out column by column, that is,
the second dimension varies slowest. C (and maybe python?) do it the other way
around, laying out row after row, so the first dimension varies slowest. Thus,
if you have a C matrix of size (m,n) and pass it to Fortran, you'd need to
tell it the dimensions are (n,m).
|
Recover from sudo rm -R /System/Library/Frameworks/Python.framework/Versions/2.7
Question: I was following this
[tutorial](https://wolfpaulus.com/journal/mac/installing_python_osx/) for
removing older versions/symlinks of Python, so I could use python 3.5, and
have it be my default version
The command:
> sudo rm -R /System/Library/Frameworks/Python.framework/Versions/2.7
appears to have broken my entire development environment. I started
experiencing errors with `homebrew`, `git`, `Xcode`, `sublime text 2`, etc. I
partially fixed it by re-downloading `python 2.7` and running `brew doctor &&
brew prune`
However, I still cannot get sublime text 2 to open. I believe I need to
restore my `/System/Library/Frameworks/Python.framework/Versions/` directory
to have 2.7, but I do not know how to do this
I also ran `brew install python` as a potential solution but this did not
work.
I am by no means an expert in the terminal, but I'm trying to get better. I am
often following tutorials like the one I reference to install new software. my
questions are as follows:
1. How can I recover from this?
2. What are some good tips for avoiding future issues like this?
3. Where can I learn more about important things to know in the terminal, so I can become a terminal boss.
4. Should I just start using home-brew for all developer-related installations?
Answer: You deleted a component of the operating system. Don't do that -- leave
`/System` alone. (Mac OS X 10.10 and later enforce this by preventing you from
modifying that directory at all by default, even with root access.)
There is no supported way to restore this. Back up your data and reinstall the
OS.
|
create a symmetric matrix from a pairwise list python for clustering scikit, DBSCAN
Question: My goal is to perform clustering using DBSCAN from scikit with a precomputed
similarity matrix. I have a list with features. I do a pairwise to generate
unique pairs for the list and have a function that calculates similarity
between pairs. Now I want to transform it to a symmetric matrix that can be
used as an input for the clustering algorithm. I think groupby may be helpful,
but I am not sure how to go about it. Here is a sample code that gives a list
of pairs with distance measure.The id field in the original list is the unique
row identifier.
def add_similarity(listdict):
random.seed(10)
newlistdist=[]
for tup_dict in listdict:
newdict={}
tup0=tup_dict[0]
tup1=tup_dict[1]
for key,value in tup0.items():
newdict[key +"_1"]=value
for key,value in tup1.items():
newdict[key+"_2"]=value
newdict["similarity"]=random.random()
newlistdist.append(newdict)
return newlistdist
def generatesymm():
listdict =[{'feature1': 4, 'feature2':2,"id": 100},{'feature1': 3, 'feature2': 2,"id":200},{'feature1': 4, 'feature2':2,"id": 300}]
pairs=list(itertools.combinations(listdict, 2) )
newlistdict=add_similarity(pairs)
If I run this code this gives
[{'id_2': 200, 'feature1_2': 3, 'feature2_2': 2, 'feature2_1': 2, 'feature1_1': 4, 'similarity': 0.571, 'id_1': 100},
{'id_2': 300, 'feature1_2': 4, 'feature2_2': 2, 'feature2_1': 2, 'feature1_1': 4, 'similarity': 0.42, 'id_1': 100},
{'id_2': 300, 'feature1_2': 4, 'feature2_2': 2, 'feature2_1': 2, 'feature1_1': 3, 'similarity': 0.578, 'id_1': 200}]
The output I need
100 200 300
100 1 0.571 0.42
200 0.571 1 0.578
300 0.428 0.578 1
Answer: It is not clear to me where `id_3` comes from, but below is one way to make
your dataframe. The trick is to use numpy to index into the upper and lower
triangular portions of the matrix.
In [679]:
import numpy as np
import pandas as pd
similarities = [x["similarity"] for x in newlistdict]
names = ['id_'+str(x) for x in range(1,4)]
n = len(similarities)
iuu = np.mask_indices(3, np.triu, 1)
iul = np.mask_indices(3, np.tril, -1)
mat = np.eye(n)
mat[iuu] = similarities
mat[iul] = similarities
df = pd.DataFrame(mat,columns=names)
df.index = names
df
Out[679]:
id_1 id_2 id_3
id_1 1.000000 0.896082 0.897818
id_2 0.896082 1.000000 0.186298
id_3 0.897818 0.186298 1.000000
(The values differ from your question because I don't know the random seed you
used.)
|
Python 3 - Upload PIL Binary to FTP server
Question: im new to python and i try to upload a image to FTP in python 3.
I'm taking the pic with the raspberry camera modul and write it to a binary.
After this i do some actions with PIL. This part works already fine. I also
can store it to a JPEG file. I wanna skip the file storage and upload the
image directly from memory. I found the following code
[here](http://stackoverflow.com/questions/15715940/pil-image-save-to-an-ftp-
server):
import StringIO
f = StringIO()
image.save(f, 'PNG')
f.seek(0) # return the StringIO's file pointer to the beginning of the file
# again this assumes you already connected and logged in
ftp.storbinary("STOR remote_filename.png", f)
Based on this i created my code (only the important lines):
stream = io.BytesIO()
camera.capture(stream, format='jpeg') # take pic, streaming method
stream.seek(0) # "Rewind" the stream to the beginning so we can read its content
img_web = Image.open(stream)
size=[web_width, web_height] # some PIL editing
img_web=img_web.resize(size) # resize
session = ftplib.FTP(ftp_server, ftp_user, ftp_pwd) # ftp upload
img_web.seek(0)
temp = io.StringIO() # this is a file object
img_web.save(temp, format='JPEG') # save the content to temp
temp.seek(0)
session.storbinary('STOR /home/www/test.jpg' , temp)
But this does not work and i get the following error:
img_web.save(temp, format='JPEG') # save the content to temp
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1685, in save
save_handler(self, fp, filename)
File "/usr/lib/python3/dist-packages/PIL/PngImagePlugin.py", line 657, in _save
fp.write(_MAGIC)
TypeError: string argument expected, got 'bytes'
How can i solve this problem? Thanks.
Answer: I just played a bit with the code and i found the solution. It's so simple.
Instead of
temp = io.StringIO()
i only had to use:
temp = io.BytesIO()
|
Error with npm install opencv
Question: When running "npm install opencv" this is what I get
> if not defined npm_config_node_gyp (node "C:\Users\Shaun\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\.
.\node_modules\node-gyp\bin\node-gyp.js" configure --fallback-to-build --module=C:\Users\Shaun\node_modules\opencv\bui
ld\opencv\v4.0.0\Release\node-v46-win32-ia32\opencv.node --module_name=opencv --module_path=C:\Users\Shaun\node_module
s\opencv\build\opencv\v4.0.0\Release\node-v46-win32-ia32 --python=python2.7 --msvs_version=2015 ) else (node configu
re --fallback-to-build --module=C:\Users\Shaun\node_modules\opencv\build\opencv\v4.0.0\Release\node-v46-win32-ia32\ope
ncv.node --module_name=opencv --module_path=C:\Users\Shaun\node_modules\opencv\build\opencv\v4.0.0\Release\node-v46-wi
n32-ia32 --python=python2.7 --msvs_version=2015 )
Shaun@SHAUN-PC C:\Users\Shaun\node_modules\opencv
> if not defined npm_config_node_gyp (node "C:\Users\Shaun\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\.
.\node_modules\node-gyp\bin\node-gyp.js" build --fallback-to-build --module=C:\Users\Shaun\node_modules\opencv\build\o
pencv\v4.0.0\Release\node-v46-win32-ia32\opencv.node --module_name=opencv --module_path=C:\Users\Shaun\node_modules\op
encv\build\opencv\v4.0.0\Release\node-v46-win32-ia32 ) else (node build --fallback-to-build --module=C:\Users\Shaun\
node_modules\opencv\build\opencv\v4.0.0\Release\node-v46-win32-ia32\opencv.node --module_name=opencv --module_path=C:\
Users\Shaun\node_modules\opencv\build\opencv\v4.0.0\Release\node-v46-win32-ia32 )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Users\Shaun\node_modules\opencv\build\opencv.vcxproj(20,3): error MSB4019: The imported project "C:\Microsoft.Cpp.
Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists
on disk.
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Users\Shaun\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\l
ib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\Shaun\\AppData\\Roaming\\npm\\node_modules\\n
pm\\node_modules\\node-gyp\\bin\\node-gyp.js" "build" "--fallback-to-build" "--module=C:\\Users\\Shaun\\node_modules\\
opencv\\build\\opencv\\v4.0.0\\Release\\node-v46-win32-ia32\\opencv.node" "--module_name=opencv" "--module_path=C:\\Us
ers\\Shaun\\node_modules\\opencv\\build\\opencv\\v4.0.0\\Release\\node-v46-win32-ia32"
gyp ERR! cwd C:\Users\Shaun\node_modules\opencv
gyp ERR! node -v v4.2.4
gyp ERR! node-gyp -v v3.2.1
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute 'node-gyp.cmd build --fallback-to-build --module=C:\Users\Shaun\node_
modules\opencv\build\opencv\v4.0.0\Release\node-v46-win32-ia32\opencv.node --module_name=opencv --module_path=C:\Users
\Shaun\node_modules\opencv\build\opencv\v4.0.0\Release\node-v46-win32-ia32' (1)
node-pre-gyp ERR! stack at ChildProcess.<anonymous> (C:\Users\Shaun\node_modules\opencv\node_modules\node-pre-gyp\
lib\util\compile.js:83:29)
node-pre-gyp ERR! stack at emitTwo (events.js:87:13)
node-pre-gyp ERR! stack at ChildProcess.emit (events.js:172:7)
node-pre-gyp ERR! stack at maybeClose (internal/child_process.js:818:16)
node-pre-gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
node-pre-gyp ERR! System Windows_NT 6.1.7601
node-pre-gyp ERR! command "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\Shaun\\node_modules\\opencv\\node_mo
dules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd C:\Users\Shaun\node_modules\opencv
node-pre-gyp ERR! node -v v4.2.4
node-pre-gyp ERR! node-pre-gyp -v v0.6.17
node-pre-gyp ERR! not ok
Failed to execute 'node-gyp.cmd build --fallback-to-build --module=C:\Users\Shaun\node_modules\opencv\build\opencv\v4.
0.0\Release\node-v46-win32-ia32\opencv.node --module_name=opencv --module_path=C:\Users\Shaun\node_modules\opencv\buil
d\opencv\v4.0.0\Release\node-v46-win32-ia32' (1)
npm WARN optional Skipping failed optional dependency /node-inspector/biased-opener/x-default-browser/default-browser-
id:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Shaun\package.json'
npm WARN Shaun No description
npm WARN Shaun No repository field.
npm WARN Shaun No README data
npm WARN Shaun No license field.
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\Shaun\\AppData\\Roaming\\npm\\node_modules\\npm\
\bin\\npm-cli.js" "install" "opencv"
npm ERR! node v4.2.4
npm ERR! npm v3.5.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-pre-gyp install --fallback-to-build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the opencv package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-pre-gyp install --fallback-to-build
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs opencv
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls opencv
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\Shaun\npm-debug.log
I've been trying bit by bit to work through each error and I seriously just
cannot figure out what's wrong here.
I'm using OpenCV as part of a College project to use in a web app. It anyone
can help me with this please do.
Thank you.
Answer: I had the same issue. I solved it by using OpenCV 2.4
|
How to graph nodes on a grid in networkx
Question: Just started learning Network Science and I'm a novice in Python so I've been
having a hard time figuring this out even after reading a good bit of the
networkx documentation. I need to compare the distance between all the nodes
and generate an edge in the event the distance is less than d.
1) How to I compare node 1 to nodes (2...99) and then compare node 2 to nodes
(3...99), etc. If there's a better way to do it than O(n^2) please show me.
2) How can I use the x,y coordinates stored in node_loc{} to graph each node
to a coordinate plane?
import random, math
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import pylab
# Calc distance given (x1,x2,y1,y2)
def distance(x1,x2,y1,y2):
return math.sqrt(((x2-x1)**2)+((y2-y1)**2))
# Generate coordinate value
def coord_val():
# node needs x and y coordinates (floats) from 0->100
return random.uniform(0.0,100.0)
def main():
# The distance that applies to link generation
d = 20
# Make a graph and name it
g = nx.Graph(name = "100x100 Field Random Network")
# Generate 100 nodes
for num in range(0,100):
# generate a dict with the node's location
node_loc = {'x': coord_val(), 'y': coord_val()}
# Add node with x,y dict
g.add_node(num,node_loc)
# Check node n against node n+1
for n,d in g.nodes(data=True):
if n == 99:
break
# I don't think this loop is correct
for rl in g.nodes(data=True):
# Don't go out of bounds on the loop
if n == 99:
break
# grab coordinates from nodes
y1=g.node[n]['y']
x1=g.node[n]['x']
y2=g.node[n+1]['y']
x2=g.node[n+1]['x']
# Check the distance, if < d, generate edge
if distance(x1,x2,y1,y2) < d:
# add edge
g.add_edge(n,n+1)
# plot
# draw_random draws it on a plane, but randomly :(
nx.draw_random(g,node_size=50)
plt.show()
if __name__ == '__main__':
main()
Answer: Take a look at the networkx random geometric graph generator for an
implementation of a graph like you are looking for
<https://github.com/networkx/networkx/blob/master/networkx/generators/geometric.py#L36>
There is an example that shows the output and how to draw it here
<https://networkx.github.io/documentation/latest/examples/drawing/random_geometric_graph.html>
|
Elasticsearch very unreliable in returning results with NGINX and UWSGI
Question: **Summary** : _I have a website with a search-as-you type search through Flask
and Elasticsearch. This works perfectly on my local machine, and on my server
(a Vultr droplet) when I run flask directly. However, when I run the website
through Nginx and uWSGI it suddenly becomes unreliable, returning some results
but not others. I have no idea how to troubleshoot this and could use some
suggestions or pointers!_
I'll try to provide as much info as possible with regards to my setup:
## Elasticsearch
Server health:
{
"cluster_name" : "elasticsearch",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 1,
"number_of_data_nodes" : 1,
"active_primary_shards" : 1,
"active_shards" : 1,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0
}
Here is pastebin with [info from my index](http://pastebin.com/gTurY1wG)
## Javascript, AJAX and Flask
As the user starts typing, jQuery autocomplete sends out an AJAX request that
gets forwarded to elasticsearch (through Flask), where a query is run. The
results are returned to javascript and added to the HTML.
I doubt there's a problem here since it works perfectly until I use Nginx, but
regardless here is the info:
* [This is the javascript that uses jQuery autocomplete and AJAX with GET](http://pastebin.com/UgFJByrj).
* This calls get_search_results() in the [views.py class](http://pastebin.com/XHfPJ1ye) with an AJAX call
* Lastly get_search_results() gets autocomplete results through the [search_database() function](http://pastebin.com/6Bz51XtC)
## Working correctly
When I run my flask application through my debugging script it works
perfectly:
#!flask/bin/python
from app import application
application.run(host='0.0.0.0', debug=True)
Whenever I start typing autocomplete works promptly and returns the correct
results.
## The problem
However, when I run the website as a service through Nginx and uWSGI search
results work sometimes, but not others times. Some names are returned, but
most are not. Partial strings are almost never returned. I have my server
setup in the following way (I basically followed [this
tutorial](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-
applications-with-uwsgi-and-nginx-on-ubuntu-14-04)):
This runs the **flask** application:
#!flask/bin/python
from app import application
if __name__ == "__main__":
application.run()
This module gets called by the following **uWSGI** .ini that creates a socket:
[uwsgi]
module = run_wsgi
master = true
processes = 5
socket = transfer_website.sock
chmod-socket = 660
vacuum = true
die-on-term = true
uWSGI gets launched with this .ini by an **upstart script** :
description "uWSGI server instance configured to serve Transfer Website"
start on runlevel [2345]
stop on runlevel [!2345]
setuid admin
setgid www-data
env PATH=/home/admin/transfer_website/transfer-virt-env/bin
chdir /home/admin/transfer_website
exec uwsgi --ini transfer_website.ini
Lastly the server accepts requests through **Nginx** that forwards requests to
the website socket. This file is in /etc/nginx/sites (I've redacted the IP
address of the website):
server {
listen 80;
server_name /*my.server.ip.address*/;
location / {
include uwsgi_params;
uwsgi_pass unix:/home/admin/transfer_website/transfer_website.sock;
}
}
I've checked the elasticsearch logs and there does not seem to be anything
related to this problem at all. My guess is that the problem lies somewhere in
the forwarding and AJAX calls but I have no idea how to debug this.
Sorry if this post is vague or if I left our crucial information, I'd be happy
to provide it.
Answer: Alright I finally solved it.
First I isolated the problem by looking at the chrome inspect -> network tab.
The results that weren't returned were producing a 500 error.
After some quick googling, I then [found a
way](https://www.digitalocean.com/community/questions/how-to-check-error-logs-
for-flask-uwsgi-nginx-app) to debug and log the uwsgi run flask application
(and the 500 error). I added the following line to my uwsgi .ini file:
#location of log files
logto = file_name.log
This logs all the output from the Flask application to this logfile.
However I still wasn't getting the error, instead the application seemed to
ignore it and continue. [This was ultimately
fixed](http://stackoverflow.com/a/18063897/4772958) by setting
`PROPAGATE_EXCEPTIONS` to `True` in my config file.
If `Debug = False` the exceptions don't propagate in the interest of not
crashing the server. So it has to be explicitly set to force the errors to
show up in the log.
Turns out I had some silly error where I tried printing a string that was
giving a unidecode error because of encoding problems. Why this wasn't a
problem on the local version I'll never know
|
ImportError: cannot import name inspect OpenShift
Question: Trying to deploy my application on OpenShift I'm stuck with this error:
Traceback (most recent call last):
File "app.py", line 35, in <module>
application = imp.load_source('app', 'flaskapp.py')
File "flaskapp.py", line 2, in <module>
from flask_sqlalchemy import SQLAlchemy
File "/var/lib/openshift/56ad93df7628e163fa00003a/python/virtenv/lib/python2.7/site-packages/
Flask_SQLAlchemy-2.1-py2.7.egg/flask_sqlalchemy/__init__.py", line 25, in <module>
from sqlalchemy import orm, event, inspect
ImportError: cannot import name inspect
Searching for answer I learned that the reason is that my Python environment
is somehow broken, but I have no idea how can I fix the OpenShift environment.
What should I do?
Answer: You have a very old version of SQLAlchemy. The `inspect` system was added in
version 0.8, in 2012. The current version is 1.0. Recent Flask-SQLAlchemy
changes dropped support for very old versions of SQLAlchemy. Upgrade to a
newer version.
pip install -U sqlalchemy
|
PTVS 2015 Numpy Install
Question: I am attempting to use the dialog box to install numpy in a VS2015 Python 2.7
project like so:
[](http://i.stack.imgur.com/MXg6z.png)
When I run it, I get the following message:
You are using pip version 6.1.1, however version 8.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
C:\Python27\lib\site-packages\pip-6.1.1-py2.7.egg\pip\_vendor\requests\packages\urllib3\util\ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Command "C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\dixon\\appdata\\local\\temp\\pip-build-rmjkhk\\numpy\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\dixon\appdata\local\temp\pip-fxbttw-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\dixon\appdata\local\temp\pip-build-rmjkhk\numpy
'numpy' failed to install. Exit code: 1
I am not sure why I would need a different SSL context? Do I need to install
another cert?
Answer: ~~`numpy` does not currently `pip install` on Windows for a huge range of
reasons, none of which PTVS can fix for you.~~
**Edit** : `numpy` recently uploaded wheels for Windows, so `pip install` will
work. However, you will need to be careful when installing other prebuilt
packages that depend on `numpy`, as there are strict compatibility constraints
that will not be enforced by pip. The general recommendation is _still_ to
install [Anaconda](http://continuum.io) instead of python.org Python if you
need _a full set of_ scientific packages.
The SSL warning probably indicates that you have Python 2.7.8 or earlier.
Later versions of 2.7 included improved (i.e. working) SSL support that helps
ensure your connections are not being hijacked.
|
Failing to print query using Overpass API with Python
Question: This is my code so far, I am using the flickrapi to obtain images with lat and
lon, then using the overpass api in flickr to find info about the nodes at
this location.
import flickrapi
import overpy
api_key = "xxxxxxxxxxxxxxxxxxx"
secret_api_key = "xxxxxxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)
def obtainImages():
photo_list = flickr.photos.search(api_key=api_key, accuracy = 15, has_geo=1, per_page = 100, extras = 'tags, url_s')
for photo in photo_list[0]:
id = str(photo.attrib['id'])
url = str(photo.attrib['url_s'])
title = (photo.attrib['title']).encode('utf-8')
photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])
lat = float(photo_location[0][0].attrib['latitude'])
lon = float(photo_location[0][0].attrib['longitude'])
max_lat = lat + 0.25
min_lat = lat - 0.25
max_lon = lon + 0.25
min_lon = lon - 0.25
print lat
print min_lat
api = overpy.Overpass()
query = "node(%s, %s, %s, %s);out;" % ( min_lat, min_lon, max_lat, max_lon )
result = api.query(query)
print query
print len(result.nodes)
obtainImages()
The flickr api aspect is working perfectly, if I try to print any of the
variables it all works. Also min_lat and min_lon all work when printed.
However although there are no errors, my query is returning no results.Lat and
min_lat print once and only once and then the program continues running but
does nothing else and prints nothing else
Has anyone any suggestions as to why this may be? Any help would be greatly
appreciated as I am a newbie!
Answer: The problem is that you are querying **huge** datasets, this will make the
query take a lot of time.
For example, I queried just one image from flickr, and your script produced
this query:
node(20.820875, -87.027648, 21.320875, -86.527648);out;
There are **51162** results. You are querying every available node in a 2890
square kilometers box, see here for an illustration:
<http://bl.ocks.org/d/3d4865b71194101b9473>
To get a better understanding of how changes (even "little" ones like +/-
0.25) to longitude and latitude affect the outcome I suggest that you take a
look at this post over at GIS Stackexchange:
<http://gis.stackexchange.com/a/8655/12310>
|
Reading Text File From Webpage by Python3
Question:
import re
import urllib
hand=urllib.request.urlopen("http://www.pythonlearn.com/code/mbox-short.txt")
qq=hand.read().decode('utf-8')
numlist=[]
for line in qq:
line.rstrip()
stuff=re.findall("^X-DSPAM-Confidence: ([0-9.]+)",line)
if len(stuff)!=1:
continue
num=float(stuff[0])
numlist.append(num)
print('Maximum:',max(numlist))
The variable `qq` contains all the strings from the text file. However, the
`for` loop doesn't work and `numlist` is still empty.
When I download the text file as a local file then read it, everything is ok.
Answer: Use the regex on qq using the multiline flag `re.M`, you are iterating over a
string so going _character by character_ , not _line by line_ so you are
calling findall on single characters:
In [18]: re.findall("^X-DSPAM-Confidence: ([0-9.]+)",qq, re.M)
Out [18]: ['0.8475', '0.6178', '0.6961', '0.7565', '0.7626', '0.7556', '0.7002', '0.7615', '0.7601', '0.7605', '0.6959', '0.7606', '0.7559', '0.7605', '0.6932', '0.7558', '0.6526', '0.6948', '0.6528', '0.7002', '0.7554', '0.6956', '0.6959', '0.7556', '0.9846', '0.8509', '0.9907']
What you are doing is equivalnet to:
In [13]: s = "foo\nbar"
In [14]: for c in s:
....: stuff=re.findall("^X-DSPAM-Confidence: ([0-9.]+)",c)
print(c)
....:
f
o
o
b
a
r
If you want floats, you can cast with `map`:
list(map(float,re.findall("^X-DSPAM-Confidence: ([0-9.]+)",qq, re.M)))
But if you just want the max, you can pass a key to `max`:
In [22]: max(re.findall("^X-DSPAM-Confidence: ([0-9.]+)",qq, re.M),key=float)
Out[22]: '0.9907'
So all you need is three lines:
In [28]: hand=urllib.request.urlopen("http://www.pythonlearn.com/code/mbox-short.txt")
In [29]: qq = hand.read().decode('utf-8')
In [30]: max(re.findall("^X-DSPAM-Confidence: ([0-9.]+)",qq, re.M),key=float)
Out[30]: '0.9907'
If you wanted to go line by line, iterate directly over `hand` :
import re
import urllib
hand = urllib.request.urlopen("http://www.pythonlearn.com/code/mbox-short.txt")
numlist = []
# iterate over each line like a file object
for line in hand:
stuff = re.search("^X-DSPAM-Confidence: ([0-9.]+)", line.decode("utf-8"))
if stuff:
numlist.append(float(stuff.group(1)))
print('Maximum:', max(numlist))
|
Python 3 Get and parse JSON API
Question: How would I parse a json api response with python? I currently have this:
import urllib.request
import json
url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
def response(url):
with urllib.request.urlopen(url) as response:
return response.read()
res = response(url)
print(json.loads(res))
I'm getting this error: TypeError: the JSON object must be str, not 'bytes'
What is the pythonic way to deal with json apis?
Answer: I would usually use the `requests` package with the `json` package. The
following code should be suitable for your needs:
import requests
import json
url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
r = requests.get(url)
print(json.loads(r.content))
**Output**
[11008076,
11006915,
11008202,
....,
10997668,
10999859,
11001695]
|
python list.pop() modifies original list (not just copy)
Question: Situation: After making a copy of the original list I use pop to modify said
copy. As it turns out, the original list gets affected by the change.
I even after checking the original list and the copy are not the same object,
poping an element of the copy will will pop the same element in the original.
See below for an example of the script. Thanks in advance for your help.
l = [['1412898', 'Jack', 'headache med', '8ET-500'],
['1423859', 'Sonny', 'prostate med', '8ET-800'],
['1413836', 'Paco', 'headache med', '8ET-500']]
class App(object):
def __init__(self, info):
self.fp_rows= info
def sortbyauditor(self):
self.fp_rows_copy = self.fp_rows[:]
print self.fp_rows is self.fp_rows_copy
for i in self.fp_rows_copy:
i.pop(1)
print self.fp_rows_copy
print self.fp_rows
app= App(l)
app.sortbyauditor()
Answer: `some_list[:]` is only a shallow copy. You seem to need a deep copy
from copy import deepcopy
copy = deepcopy(some_list)
**Edit**
To understand why "one objects affects the other" take a look at the `id` of
each list:
original = [[1, 2], [3, 4]]
shallow = original[:]
deep = deepcopy(original)
print([id(l) for l in original])
# [2122937089096, 2122937087880]
print([id(l) for l in shallow])
# [2122937089096, 2122937087880]
print([id(l) for l in deep])
# [2122937088968, 2122937089672]
You can see that the `id`s of the lists in `original` are the same as the
`id`s in `shallow`. That means the nested lists are the exact same objects.
When you modify one nested list the changes are also in the other list.
The `id`s for `deep` are different. That are just copies. Changing them does
not affect the original list.
|
Open .dat and .atr file types with Python
Question: I'm trying to read in .dat and .atr files with Python; from Physionet, [these
for example](https://www.physionet.org/physiobank/database/mitdb/). I've tried
the standard context manager opening method:
with open("path/to/files/101.dat", "rb") as f:
for line in f: print f
But I get uninterpretable results like `D"D ?C?C?C!?C?C?C?C?C` for the lines.
These lines should be like `3.0000000e-003 4.9950000e+000 4.3400000e+000` (I
know this from published studies with this dataset). Any ideas how I can read
in this data?
Answer: You can try to open it [using
`numpy`](http://stackoverflow.com/a/11798898/5687152)
import numpy as np
myarray = np.fromfile("path/to/files/101.dat",dtype=float)
|
Properly using Foreign Key references in search_fields, Django admin
Question: I've got a weird conundrum that I need some help with in Django 1.8.4 using
python 3.4 in a virtual-env.
I've got 2 models in 2 different apps... as follows with multiple Foreign Key
references.
**Inventory App**
class InventoryItem(models.Model):
item_unique_code = models.CharField(max_length=256, blank=False, null=False)
category = models.CharField(max_length=256, blank=False, null=False,choices=[('RAW','Raw Material'),('FG','Finished Good'),('PKG','Packaging')])
name = models.CharField(max_length=64, blank=False, null=False)
supplier = models.CharField(max_length=96, blank=False,null=False)
approved_by = models.CharField(max_length=64, editable=False)
date_approved = models.DateTimeField(auto_now_add=True, editable=False)
comments = models.TextField(blank=True, null=True)
def __str__(self):
return "%s | %s | %s" % (self.item_unique_code,self.name,self.supplier)
class Meta:
managed = True
unique_together = (('item_unique_code', 'category', 'name', 'supplier'),)
**Recipe App**
class RecipeControl(models.Model):
#recipe_name choice field needs to be a query set of all records containing "FG-Finished Goods"
recipe_name = models.ForeignKey(items.InventoryItem, related_name='recipe_name', limit_choices_to={'category': 'FG'})
customer = models.ForeignKey(customers.CustomerProfile, related_name='customer')
ingredient = models.ForeignKey(items.InventoryItem, related_name='ingredient')
min_weight = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
max_weight = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
active_recipe = models.BooleanField(default=False)
active_by = models.CharField(max_length=64, editable=False)
revision = models.IntegerField(default=0)
last_updated = models.DateTimeField(auto_now_add=True, editable=False)
def __str__(self):
return "%s" % (self.recipe_name)
class Meta:
managed = True
unique_together = (('recipe_name', 'customer', 'ingredient'),)
I've been getting some weird results in my Recipe's Admin class...
from django.contrib import admin
from django.contrib.auth.models import User
from .models import RecipeControl
from Inventory import models
class RecipeView(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.active_by = request.user.username
obj.save()
fieldsets = [
('Recipe Information', {'fields': ['recipe_name', 'customer']}),
('Ingredients', {'fields': ['ingredient','min_weight','max_weight','active_recipe']}),
('Audit Trail', {'fields': ['active_by','revision','last_updated'],'classes':['collaspe']}),
]
list_select_related = ['recipe_name','customer','ingredient']
search_fields = ['recipe_name','customer','ingredient','active_by']
readonly_fields = ('last_updated','active_by')
list_display = ['recipe_name','customer','ingredient','min_weight','max_weight','last_updated','active_by', 'active_recipe']
admin.site.register(RecipeControl, RecipeView)
The issue I've come across is if I try to do a search on any ForeignKey field,
Django throws this error...
Exception Type: TypeError at /admin/Recipe/recipecontrol/
Exception Value: Related Field got invalid lookup: icontains
According to the [Django Admin
Doc's](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields)
and other older questions on stackoverflow on the subject it says I should be
doing something along the lines of _search_fields = ['inventoryitem__name']_
but I think this is in reference to FK's in the same app model.py. Is there a
more correct way of referencing/importing other models from other apps that
I'm missing or do I have to use some kind of callable method magic to get the
search function to look up correctly? I've tried a multitude of different
combinations and nothing seems to work. I'm relatively new to Django so I'm
confident it's something simple.
Answer: You should use the double underscore notation to search a field on a related
object. However, you should use the name of the foreign key field (e.g.
`recipe_name`), not the name of the model (e.g. `InventoryItem`). It doesn't
matter whether or not the foreign key's model is in the same app. For example:
search_fields = ['recipe_name__name']
Note that if you want to search the recipe_name and ingredient fields, you
need to include both fields, even though they are foreign keys to the same
model.
search_fields = ['recipe_name__name', 'ingredient__name']
|
How to I check that a string contains only digits and / in python?
Question: I am trying to check that a string contains only / and digits, to use as a
form of validation, however I cannot find and way to do both. ATM I have this:
if Variable.isdigit() == False:
This works for the digits but I have not found a way to check also for the
slashes.
Answer: You could use the following regex.
import re
matched = re.match(r'^-?[0-9/]+$', '01/02/2016')
if matched:
print 'Matched integers with slashes'
|
Failing hard at OOP in python
Question: This represents a simple class, that I have made to try and practice OOP.
import csv
import logging
class LoaderCSV:
def __init__(self, file):
self.file = file
if file is None:
logging.warning('Missing input file.')
def load(self):
with open(self.file) as f:
holder = csv.reader(f)
file_data = list(holder)
return file_data
What happens is when I call this class with:
data = LoaderCSV.load(input_file)
I get
line 14, in load
with open(self.file) as f:
AttributeError: 'str' object has no attribute 'file'
I must be messing something up, but can't understand what. My previous attempt
worked just fine this way. I just don't understand why
self.file
does not pass the value, assigned to the argument, when it is defined under
`__init__`
Answer: The problem is you're calling an instance method as a static method, so your
filename is being passed in instead of `self`. The proper way to do this would
be like:
loader = LoaderCSV(input_file)
data = loader.load()
This will pass in `loader` as the `self` parameter, allowing you to access the
file name in the object's `file` field.
Check out the Python documentation on
[classes](https://docs.python.org/3/tutorial/classes.html) for more
information.
|
Is there a way to write a pandas SQL query across multiple lines with comments?
Question: When writing a regular expression, it is possible to write the expression
across multiple lines and including annotation, then compile the expression
using the `re.VERBOSE` option before passing the compiled version. I'd like to
do something similar with a `pandas.read_sql_query`.
For example, instead of:
result = pd.read_sql_query('select a.gvkey, a.tic, a.datadate as fyearend, year(a.datadate) as year, month(a.datadate) as fyrc, b.datadate, month(b.datadate) as month, b.trt1m from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate) where a.TIC = "IBM" and a.datafmt = "STD" and a.consol="C" and a.indfmt = "INDL" and year(a.datadate)>1980', engine)
I would like to write something like:
q = """select a.gvkey,
a.tic, #COMMENTS
a.datadate as fyearend, #COMMENTS
year(a.datadate) as year, #COMMENTS
month(a.datadate) as fyrc, b.datadate,
month(b.datadate) as month,
b.trt1m
from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate)
where a.TIC = "IBM"
and a.datafmt = "STD"
and a.consol="C"
and a.indfmt = "INDL"
and year(a.datadate)>1980
"""
result = p.read_sql_query(q ,engine)
My question is related to
[this](https://stackoverflow.com/questions/33944522/is-it-possible-to-split-a-
sequence-of-pandas-commands-across-multiple-lines) question about splitting
python commands across multiple lines, but I'd like to add comments inside the
query.
As I mentioned, what I'd like to do in the pandas/SQL case is similar to what
can be done in the regular expression case with `re.VERBOSE`. Here is an
example with regex:
pattern = r'''\s(shares?| #COMMENTS
warrants?| #COMMENTS
stock| #AND SO ON...
(non)?vest(ed)?
)\b
'''
crit = re.compile(pattern_nopt, re.VERBOSE)
match=re.search(crit, string)
This would make the query more readable and I find it important to annotate
queries exhaustively when sharing code with coauthors.
Answer: Yes it will works but you have to use the right [comment delimiter for
SQLite](https://www.sqlite.org/lang_comment.html) :
`--` for an inline comment
`/* foo.. */` (as in C) for a multi-lines comment
So it will looks like :
q = """select a.gvkey,
a.tic, -- COMMENTS
a.datadate as fyearend, -- COMMENTS
year(a.datadate) as year, /* Another very long
and multi-lines comment... */
month(a.datadate) as fyrc, b.datadate,
month(b.datadate) as month,
b.trt1m from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate)
where a.TIC = "IBM"
and a.datafmt = "STD"
and a.consol="C"
and a.indfmt = "INDL"
and year(a.datadate)>1980
"""
result = p.read_sql_query(q, conn)
|
Regex between quotes look ahead - Python
Question: I have this:
myText = str(^123"I like to"^456&U"play video games and"$"eat cereal")
I want to extract everything in between (and including) quotation marks, split
everything before and after the `$` sign, and append them into a nested list.
E.g.
myTextList = [["I like to","play video games and"],["eat cereal"]]
This is what I tried:
tempTextList = []
for text in re.findall('(?<=\$)"[^"]*"(?<!\^)',myText,re.DOTALL)
tempTextList.append(text)
myTextList.append(tempTextList)
I used the website <https://www.regex101.com/#python> and tried almost
everything I could think of...
`(?!\$)"(?!\^\00\+\-\&)[^"].*"` etc...
The re.findall part doesn't really work the way I want it to.
Can someone point me in the right direction?
Thanks
Answer: You can use `"[^"]*"` regex with `re.findall`:
import re
s = 'myText = str(^123"I like to"^456&U"play video games and"$"eat cereal")'
print(re.findall(r'"[^"]*"', s))
See [demo](http://ideone.com/2EmIcf)
It matches the double quoted substrings you need with double quotes: `['"I
like to"', '"play video games and"', '"eat cereal"']`.
Note that `"[^"]*"` matches `"` followed by zero or more characters other than
`"` followed with `"`.
If you need to get the contents inside `"..."` without the double quotes, you
can use _capturing_ mechanism:
r'"([^"]*)"'
The [`re.findall`](https://docs.python.org/2/library/re.html#re.findall) will
only return the captures in Group 1. See [another
demo](http://ideone.com/aidLq5).
|
Python 2.7 cannot find module when running py. But can find module in terminal
Question: OSX, PyCharm, with brew-installed python 2.7, simply trying to import
from azure.mgmt.common import SubscriptionCloudCredentials
import azure.mgmt.compute
import azure.mgmt.network
import azure.mgmt.resource
import azure.mgmt.storage
Got error:
/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/bin/python2.7 XXX/pythonCode/p2.1/azure.py
Traceback (most recent call last):
File "XXX/pythonCode/p2.1/azure.py", line 9, in <module>
from azure.mgmt.common import SubscriptionCloudCredentials
File "XXX/pythonCode/p2.1/azure.py", line 9, in <module>
from azure.mgmt.common import SubscriptionCloudCredentials
ImportError: No module named mgmt.common
Tried:
* Reinstall azure from source
<https://github.com/Azure/azure-sdk-for-python>
* Running
`python -c "import site; print(site.getsitepackages())"`
I get
`['/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages',
'/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/site-
python', '/Library/Python/2.7/site-packages']`
In which
`/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages` contains azure
* Running `python -c "import sys; print(sys.path)"`
I get
'', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/usr/local/Cellar/numpy/1.10.4/libexec/nose/lib/python2.7/site-packages', '/Library/Python/2.7/site-packages'
* * *
Remarkably Running
`python -c "from azure.mgmt.common import SubscriptionCloudCredentials"`
in terminal does not error at all.
Can anyone explain where the problems are?
Answer: The problem is that the file in which you wrote your script in is called
`azure.py`. This file is getting imported instead of the module `azure` that
you installed, and it doesn't have the necessary attributes, resulting in this
error.
Renaming the file your code is in to something else will fix this problem.
|
Access next sibling <li> element with BeautifulSoup
Question: I am completely new to web parsing with Python/BeautifulSoup. I have an HTML
that has (part of) the code as follows:
<div id="pages">
<ul>
<li class="active"><a href="example.com">Example</a></li>
<li><a href="example.com">Example</a></li>
<li><a href="example1.com">Example 1</a></li>
<li><a href="example2.com">Example 2</a></li>
</ul>
</div>
I have to visit **each link** (basically each `<li>` element) until there are
no more `<li>` tags present. Each time a link is clicked, its corresponding
`<li>` element gets class as 'active'. My code is:
from bs4 import BeautifulSoup
import urllib2
import re
landingPage = urllib2.urlopen('somepage.com').read()
soup = BeautifulSoup(landingPage)
pageList = soup.find("div", {"id": "pages"})
page = pageList.find("li", {"class": "active"})
This code gives me the first `<li>` item in the list. My logic is I am keeping
on checking if the `next_sibling` is not None. If it is not None, I am
creating an HTTP request to the `href` attribute of the `<a>` tag in that
sibling `<li>`. That would get me to the next page, and so on, till there are
no more pages.
But I can't figure out how to get the `next_sibling` of the `page` variable
given above. Is it `page.next_sibling.get("href")` or something like that? I
looked through the documentation, but somehow couldn't find it. Can someone
help please?
Answer: Use
[`find_next_sibling()`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-
next-siblings-and-find-next-sibling) and be explicit about what sibling
element do you want to find:
next_li_element = page.find_next_sibling("li")
`next_li_element` would become `None` if the `page` corresponds to the last
active `li`:
if next_li_element is None:
# no more pages to go
|
Working with "unclean" text in python
Question: Please forgive my ignorance I am new at this. I have searched for this and
tried several of the examples, but I think I am finding most things that might
work in python2.7 but I am required to use python3.5 for work. I am trying to
extract just the cities from this list on Wikipedia
[Cities in
Oklahoma](https://en.wikipedia.org/wiki/List_of_towns_and_cities_in_Oklahoma_by_population)
The tag names are different or I would try and use requests, which is actually
ideal because we need to keep our list updated as Wikipedia updates. Instead I
copied the data and pasted it into a txt document so that I can build the
proof of concept and get approval for this project. I end up with something
that looks like this:
1. Oklahoma City 1,012,389
2. Tulsa 609,450
3. Norman 110,925
4. Broken Arrow 98,850
5. Lawton (town) 96,867
6. Edmond 81,405
7. Moore 55,081
8. Midwest City 54,371
I have found several things that I have tried several different methods
thinking that if I found the right way to split the file I could just get all
lines that have content. Then I could split them again and return the line
items with index 1.
I was trying:
file = open('cities_oklahoma.txt', 'r')
s = file.readline()
for line in s:
line_has_txt = line.split() # I have no clue what should be here
print([line_has_txt.split(' ')[1])
Am I even getting close to what I want to do here? Also please note I
manipulated line 5 in my example to show some possible deviation of the data
that happens. Also as you can see from line 1 some city names actually have
the word city which kind of breaks my theory
Answer: If you want the list of cities:
import requests
r = requests.get("https://en.wikipedia.org/wiki/List_of_towns_and_cities_in_Oklahoma_by_population#Largest_10_cities_by_population")
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content)
for p in soup.find("div",{"class":"mw-content-ltr"}).find_all("p"):
print(p.text)
That gives you all the cities and the title:
The following list of towns and cities in Oklahoma, shows the incorporated places in the U.S. state of Oklahoma, in order of population according to the 2010 United States Census:[1]
1. Oklahoma City 1,012,389
2. Tulsa 609,450
3. Norman 110,925
4. Broken Arrow 98,850
5. Lawton 96,867
6. Edmond 81,405
7. Moore 55,081
8. Midwest City 54,371
9. Enid 49,379
10. Stillwater 45,688
11. Muskogee 39,223
12. Bartlesville 35,750
13. Shawnee 29,857
14. Owasso 28,915
.......................
359. Greenfield (town) 93
360. Roosevelt (town) 25
361. Cooperton (town) 12
You can skip the title and the empty strings, you have to be more careful what
you filter but this is the general idea:
soup = BeautifulSoup(r.content)
ps = soup.find("div", {"class": "mw-content-ltr"}).find_all("p")
city_data = dict(p.text.lstrip("0123456789. ").rsplit(None, 1) for p in ps[3:])
from pprint import pprint as pp
pp(city_data)
Which gives you:
{'Achille town, Bryan County': '492',
'Ada': '16,810',
'Adair (town)': '790',
'Afton (town)': '1,049',
'Agra (town)': '339',
'Alex (town)': '550',
'Allen (town)': '932',
'Altus': '19,813',
'Alva': '4,945',
'Amber town, Grady County': '419',
'Anadarko': '6,762',
'Antlers': '2,453',
'Apache (town)': '1,444',
'Arapaho (town)': '796',
'Ardmore': '24,283',
'Arkoma (town)': '1,989',
'Arnett (town)': '524',
'Asher town, Pottawatomie County': '393',
'Atoka': '3,107',
'Avant (town)': '320',
'Barnsdall': '1,243',
'Bartlesville': '35,750',
'Beaver (town)': '1,515',
'Beggs': '1,321',
'Bernice (town)': '562',
'Bethany': '19,051',
'Bethel Acres (town)': '2,895',
'Billings (town)': '509',
'Binger (town)': '672',
'Bixby': '20,884',
'Blackwell': '7,092',
'Blair (town)': '818',
'Blanchard': '7,670',
'Boise City': '1,266',
'Bokchito (town)': '632',
'Bokoshe (town)': '512',
'Boley (town)': '1,184',
'Boswell (town)': '709',
'Bowlegs town, Seminole County': '405',
'Bray (town)': '1,209',
'Bristow': '4,222',
'Broken Arrow': '98,850',
'Broken Bow': '4,120',
'Buffalo (town)': '1,299',
'Burns Flat (town)': '2,057',
'Butler (town)': '287',
'Byng (town)': '1,175',
'Cache': '2,796',
'Caddo (town)': '997',
'Calera (town)': '2,164',
'Calumet (town)': '507',
'Canton (town)': '625',
'Canute (town)': '541',
'Carmen (town)': '355',
'Carnegie (town)': '1,723',
'Carney (town)': '647',
'Cashion (town)': '802',
'Catoosa': '7,151',
'Cement (town)': '501',
'Central High (town)': '1,199',
'Chandler': '3,100',
'Chattanooga town, Comanche County': '461',
'Checotah': '3,335',
'Chelsea (town)': '1,964',
'Cherokee': '1,498',
'Cheyenne (town)': '801',
'Chickasha': '16,036',
'Choctaw': '11,146',
'Chouteau (town)': '2,097',
'Claremore': '18,581',
'Clayton (town)': '821',
'Cleveland': '3,251',
'Clinton': '9,033',
'Coalgate': '1,967',
'Colbert (town)': '1,140',
'Colcord (town)': '815',
'Cole (town)': '555',
'Collinsville': '5,606',
'Comanche': '1,663',
'Commerce': '2,473',
'Cooperton (town)': '12',
'Copan (town)': '733',
'Corn (town)': '503',
'Covington (town)': '527',
'Coweta': '9,943',
'Coyle town, Logan County': '325',
'Crescent': '1,411',
'Crowder town, Pittsburg County': '430',
'Cushing': '7,826',
'Custer City (town)': '375',
'Cyril (town)': '1,059',
'Davenport (town)': '814',
'Davidson (town)': '315',
'Davis': '2,683',
'Del City': '21,332',
'Delaware town, Nowata County': '417',
'Depew (town)': '476',
'Dewar (town)': '888',
'Dewey': '3,432',
'Dickson (town)': '1,207',
'Dill City (town)': '562',
'Dover town, Kingfisher County': '464',
'Drummond (town)': '455',
'Drumright': '2,907',
'Duncan': '23,431',
'Durant': '15,856',
'Dustin town, Hughes County': '395',
'Earlsboro (town)': '628',
'East Duke (town)': '424',
'Edmond': '81,405',
'El Reno': '16,749',
'Eldorado town, Jackson County': '446',
'Elgin': '2,156',
'Elk City': '11,693',
'Elmore City (town)': '697',
'Empire City (town)': '955',
'Enid': '49,379',
'Erick': '1,052',
'Eufaula': '2,813',
'Fairfax (town)': '1,380',
'Fairland (town)': '1,057',
'Fairview': '2,579',
'Fanshawe (town)': '419',
'Fletcher (town)': '1,177',
'Forest Park (town)': '998',
'Forgan (town)': '547',
'Fort Cobb (town)': '634',
'Fort Coffee town, Le Flore County': '424',
'Fort Gibson (town)': '4,154',
'Fort Supply (town)': '330',
'Fort Towson (town)': '519',
'Francis (town)': '315',
'Frederick': '3,940',
'Gage (town)': '442',
'Garber': '822',
'Geary': '1,280',
'Geronimo (town)': '1,268',
'Glencoe (town)': '601',
'Glenpool': '10,808',
'Goldsby (town)': '1,801',
'Goodwell (town)': '1,293',
'Gore (town)': '977',
'Grandfield': '1,038',
'Granite (town)': '2,065',
'Greenfield (town)': '93',
'Grove': '6,623',
'Guthrie': '10,191',
'Guymon': '11,442',
'Haileyville': '813',
'Hammon (town)': '568',
'Harrah': '5,095',
'Hartshorne': '2,125',
'Haskell (town)': '2,007',
'Haworth (town)': '297',
'Healdton': '2,788',
'Heavener': '3,414',
'Helena (town)': '1,403',
'Hennessey (town)': '2,131',
'Henryetta': '5,927',
'Hinton (town)': '3,196',
'Hobart': '3,756',
'Holdenville': '5,771',
'Hollis': '2,060',
'Hominy': '3,565',
'Hooker': '1,918',
'Howe (town)': '802',
'Hugo': '5,301',
'Hulbert (town)': '590',
'Hydro (town)': '969',
'Idabel': '7,010',
'Indiahoma (town)': '344',
'Inola (town)': '1,788',
'Jay': '2,448',
'Jenks': '16,924',
'Jennings town, Pawnee County': '363',
'Jones (town)': '2,692',
'Kansas (town)': '802',
'Kaw City city, Kay County': '375',
'Kellyville (town)': '1,150',
'Keota (town)': '564',
'Ketchum Town, Craig County': '442',
'Keyes (town)': '324',
'Kiefer (town)': '1,685',
'Kingfisher': '4,633',
'Kingston (town)': '1,601',
'Kiowa (town)': '731',
'Konawa': '1,298',
'Krebs': '2,053',
'Lahoma (town)': '611',
'Lamont town, Grant County': '417',
'Langley (town)': '819',
'Langston (town)': '1,724',
'Laverne (town)': '1,344',
'Lawton': '96,867',
'Lexington': '2,152',
'Lindsay': '2,840',
'Locust Grove (town)': '1,423',
'Lone Grove': '5,054',
'Lone Wolf town, Kiowa County': '438',
'Luther (town)': '1,221',
'Madill': '3,770',
'Mangum': '3,010',
'Mannford (town)': '3,076',
'Mannsville (town)': '863',
'Marietta': '2,626',
'Marlow': '4,662',
'Maud': '1,048',
'Maysville (town)': '1,232',
'McAlester': '18,383',
'McCurtain (town)': '516',
'McLoud (town)': '4,044',
'Medford': '996',
'Medicine Park (town)': '382',
'Meeker (town)': '1,144',
'Miami': '13,570',
'Midwest City': '54,371',
'Mill Creek (town)': '319',
'Millerton (town)': '320',
'Minco': '1,632',
'Moore': '55,081',
'Mooreland (town)': '1,190',
'Morris': '1,479',
'Morrison (town)': '733',
'Mounds (town)': '1,168',
'Mountain Park town, Kiowa County': '409',
'Mountain View (town)': '795',
'Muldrow (town)': '3,466',
'Muskogee': '39,223',
'Mustang': '17,395',
'New Cordell': '2,915',
'Newcastle': '7,685',
'Newkirk': '2,317',
'Nichols Hills': '3,710',
'Nicoma Park': '2,393',
'Ninnekah (town)': '1,002',
'Noble': '6,481',
'Norman': '110,925',
'North Enid (town)': '860',
'North Miami town, Ottawa County': '374',
'Nowata': '3,731',
'Oakland town, Marshall County': '1,057',
'Oaks (town)': '288',
'Ochelata town, Washington County': '424',
'Oilton': '1,013',
'Okarche (town)': '1,215',
'Okay (town)': '620',
'Okeene (town)': '1,204',
'Okemah': '3,223',
'Oklahoma City': '1,012,389',
'Okmulgee': '12,321',
'Oktaha town, Muskogee County': '390',
'Olustee (town)': '607',
'Oologah (town)': '1,146',
'Owasso': '28,915',
'Paden (town)': '461',
'Panama (town)': '1,413',
'Paoli (town)': '610',
'Pauls Valley': '6,187',
'Pawhuska': '3,584',
'Pawnee': '2,196',
'Perkins': '2,831',
'Perry': '5,126',
'Piedmont': '5,720',
'Pink (town)': '2,058',
'Pocola (town)': '4,056',
'Ponca City': '25,387',
'Pond Creek': '856',
'Porter (town)': '566',
'Porum (town)': '727',
'Poteau': '8,520',
'Prague': '2,386',
'Prue town, Osage County': '465',
'Pryor': '9,539',
'Purcell': '5,884',
'Quapaw (town)': '906',
'Quinton (town)': '1,051',
'Ralston (town)': '330',
'Ramona (town)': '535',
'Randlett (town)': '438',
'Ravia (town)': '528',
'Red Oak (town)': '549',
'Ringling (town)': '1,037',
'Ringwood (town)': '497',
'Ripley town, Payne County': '403',
'Rock Island (town)': '646',
'Roff (town)': '725',
'Roland (town)': '3,169',
'Roosevelt (town)': '25',
'Rush Springs (town)': '1,231',
'Ryan (town)': '816',
'Salina (town)': '1,396',
'Sallisaw': '8,880',
'Sand Springs': '18,906',
'Sapulpa': '20,544',
'Savanna (town)': '686',
'Sayre': '4,375',
'Schulter (town)': '509',
'Seiling': '860',
'Seminole': '7,488',
'Sentinel (town)': '901',
'Shady Point (town)': '1,026',
'Shattuck (town)': '1,356',
'Shawnee': '29,857',
'Shidler': '441',
'Skiatook': '7,397',
'Slaughterville (town)': '4,137',
'Snyder': '1,394',
'Soper (town)': '261',
'South Coffeyville (town)': '785',
'Spavinaw (town)': '437',
'Spencer': '3,912',
'Sperry (town)': '1,206',
'Spiro (town)': '2,164',
'Springer (town)': '700',
'Sterling (town)': '793',
'Stigler': '2,685',
'Stillwater': '45,688',
'Stilwell': '3,949',
'Stonewall (town)': '470',
'Stratford (town)': '1,525',
'Stringtown town, Atoka County': '410',
'Stroud': '2,690',
'Sulphur': '4,929',
'Taft (town)': '250',
'Tahlequah': '15,753',
'Talihina (town)': '1,114',
'Taloga (town)': '299',
'Tecumseh': '6,457',
'Temple (town)': '1,002',
'Terral town, Jefferson County': '382',
'Texhoma (town)': '926',
'Thackerville town, Love County': '445',
'The Village': '8,929',
'Thomas': '1,181',
'Tipton (town)': '847',
'Tishomingo': '3,034',
'Tonkawa': '3,216',
'Tryon town, Lincoln County': '491',
'Tulsa': '609,450',
'Tupelo': '329',
'Tushka town, Atoka County': '312',
'Tuttle': '6,019',
'Tyrone (town)': '762',
'Union City (town)': '1,645',
'Valley Brook (town)': '765',
'Valliant (town)': '754',
'Velma (town)': '620',
'Verden (town)': '530',
'Verdigris (town)': '3,993',
'Vian (town)': '1,466',
'Vici (town)': '699',
'Vinita': '5,743',
'Wagoner': '8,323',
'Wakita town, Grant County': '344',
'Walters': '2,551',
'Wanette town, Pottawatomie County': '350',
'Wapanucka town, Johnston County': '438',
'Warner (town)': '1,641',
'Warr Acres': '10,043',
'Washington (town)': '618',
'Watonga': '5,111',
'Waukomis (town)': '1,286',
'Waurika': '2,064',
'Wayne (town)': '688',
'Waynoka': '927',
'Weatherford': '10,833',
'Webbers Falls (town)': '616',
'Welch (town)': '619',
'Weleetka (town)': '998',
'Wellston (town)': '788',
'West Siloam Springs (town)': '846',
'Westville (town)': '1,639',
'Wetumka': '1,282',
'Wewoka': '3,430',
'Wilburton': '2,843',
'Wilson': '1,724',
'Winchester (town)': '516',
'Wister (town)': '1,102',
'Woodward': '12,051',
'Wright City (town)': '762',
'Wyandotte (town)': '333',
'Wynnewood': '2,212',
'Wynona (town)': '437',
'Yale': '1,227',
'Yukon': '22,709'}
If you plan on analysing the data, you might find pandas useful::
city_data =(p.text.lstrip("0123456789. ").rsplit(None, 1) for p in ps[3:])
import pandas as pd
df = pd.DataFrame(city_data,columns=["City", "Population"])
print(df)
Output:
City Population
0 Oklahoma City 1,012,389
1 Tulsa 609,450
2 Norman 110,925
3 Broken Arrow 98,850
4 Lawton 96,867
5 Edmond 81,405
6 Moore 55,081
7 Midwest City 54,371
8 Enid 49,379
9 Stillwater 45,688
10 Muskogee 39,223
11 Bartlesville 35,750
12 Shawnee 29,857
13 Owasso 28,915
14 Ponca City 25,387
15 Ardmore 24,283
16 Duncan 23,431
17 Yukon 22,709
18 Del City 21,332
19 Bixby 20,884
20 Sapulpa 20,544
21 Altus 19,813
22 Bethany 19,051
23 Sand Springs 18,906
24 Claremore 18,581
25 McAlester 18,383
26 Mustang 17,395
27 Jenks 16,924
28 Ada 16,810
29 El Reno 16,749
.. ... ...
You might want to convert the population column to ints for any calculations:
import locale
locale.setlocale(locale.LC_NUMERIC, '')
df["Population"] = df["Population"].apply(locale.atoi)
print(df["Population"])
0 1012389
1 609450
2 110925
3 98850
4 96867
5 81405
6 55081
7 54371
8 49379
9 45688
10 39223
11 35750
12 29857
..................
|
how to start and run downloaded python web application that has many files on linux (virtualbox)
Question: i have downloaded a open source python web app(for link click
[here](https://github.com/mustafatasdemir/apkinspector)) on github and i do
all of its steps .its apkinspector web application
i got confused . how can i start it on my ubuntu linux server because it has
many files .
i tried to run **init**.py files but i got errors like
Traceback (most recent call last):
File "__init__.py", line 16, in <module>
from flask import Flask, render_template
File "/usr/local/lib/python2.7/dist-packages/flask/__init__.py", line 17, in <module>
from werkzeug.exceptions import abort
File "/usr/local/lib/python2.7/dist-packages/werkzeug/__init__.py", line 152, in <module>
__import__('werkzeug.exceptions')
File "/usr/local/lib/python2.7/dist-packages/werkzeug/exceptions.py", line 71, in <module>
from werkzeug.wrappers import Response
File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 26, in <module>
from werkzeug.http import HTTP_STATUS_CODES, \
File "/usr/local/lib/python2.7/dist-packages/werkzeug/http.py", line 24, in <module>
from email.Utils import parsedate_tz
File "/home/ironstone/Desktop/apkinspector/webapp/app/email.py", line 16, in <module>
from flask import current_app, render_template
ImportError: cannot import name current_app
it has venv for python and i dont know how to work with.
pls if anyone can work with it or just download it and telling me how can i
run it ?
Answer: You should be able to run the webapp with
cd webapp
python manage.py run_in_debug
But you might experience more problems. The developer seems to be a newcomer
to releasing Python code. The project is packaged in an unusual way. Most
likely you will have to install dependencies to get it running.
pip install -r req
would be helpful, that requires `pip` on your system. It might be installed
with package manager of the OS.
|
Alternatives to Selenium/Webdriver for filling in fields when scraping headlessly with Python?
Question: With Python 2.7 I'm scraping with **urllib2** and when some Xpath is needed,
**lxml** as well. It's **_fast_** , and because I rarely have to navigate
around the sites, this combination works well. On occasion though, usually
when I reach a page that will only display some valuable data when a short
form is filled in and a submit button is clicked
([example](http://apply.ovoenergycareers.co.uk/vacancies/#results)), the
scraping-only approach with urllib2 is not sufficient.
Each time such a page were encountered, I could invoke `selenium.webdriver` to
refetch the page and do the form-filling and clicking, but this will slow
things down considerably.
**NOTE:** This question is not about the merits or limitations of **urllib2**
, about which I aware there have been many discussions. It's instead focussed
only on finding a fast, headless approach to form-filling etc. (one that will
also allow for XPath queries if needed).
Answer: In addition to the ones [alecxe
mentioned](http://stackoverflow.com/a/35143170/190597), another alternative is
to use a GUI browser tool such as Firefox's Web Console to inspect the POST
that is made when you click the submit button. Sometimes you can find the POST
data and simply spoof it. For example, using the example url you posted, if
you
* Use Firefox to go to <http://apply.ovoenergycareers.co.uk/vacancies/#results>
* Click Tools > Web Developer > Web Console
* Click Net > Log Request and Response Bodies
* Fill in the form, click Search
* Left-click the (first) POST in the Web Console
* Right-click the (first) POST, select COPY POST Data
* Paste the POST data in a text editor
you will obtain something like
all
field_36[]=73
field_37[]=76
field_32[]=82
submit=Search
(Note that the Web Console menus vary a bit depending on your version of
Firefox, so YMMV.) Then you can spoof the POST using code such as:
import urllib2
import urllib
import lxml.html as LH
url = "http://apply.ovoenergycareers.co.uk/vacancies/#results"
params = urllib.urlencode([('field_36[]', 73), ('field_37[]', 76), ('field_32[]', 82)])
response = urllib2.urlopen(url, params)
content = response.read()
root = LH.fromstring(content)
print('\n'.join([tag.text_content() for tag in root.xpath('//dl')]))
which yields
Regulatory Data Analyst
Contract Type
Permanent
Contract Hours
Full-time
Location
Bristol
Department
Business Intelligence
Full description
If you inspect the HTML and search for `field_36[]` you'll find
<div class="multiwrapper">
<p class="sidenote multi">(Hold the ctrl (pc) or cmd (Mac) keys for multi-selects) </p>
<select class="select-long" multiple size="5" name="field_36[]" id="field_36"><option value="0">- select all -</option>
<option selected value="73" title="Permanent">Permanent</option>
<option value="74" title="Temporary">Temporary</option>
<option value="75" title="Fixed-term">Fixed-term</option>
<option value="81" title="Intern">Intern</option></select>
</div>
from which it is easy to surmise that `field_36[]` controls the `Contract
Type` and value `73` corresponds to "Permanent", `74` corresponds to
"Temporary", etc. Similarly you can figure out the options for `field_37[]`,
`field_32[]` and `all` (which can be any search term string). If you have a
good understanding of HTML, you may not even need the browser tool to
construct the POST.
|
Python - How to special sort list
Question: can anyone advise me how to sort the array by column 'age'?
student = {
0 : {'name' : 'jane', 'age' : 40},
1 : {'name' : 'pool', 'age' : 11},
2 : {'name' : 'dave', 'age' : 28}
}
print(student[0])
print(student[1])
print(student[2])
results screen
{'name': 'jane', 'age': 40}
{'name': 'pool', 'age': 11}
{'name': 'dave', 'age': 28}
I tried
student = sorted(student, key=lambda student: student[2]) # sort by age not work
But it does not work nothing :-( Thank you for your help
\-- EDIT -- Correct sort list (sorting age)
print(student[0])
print(student[1])
print(student[2])
results screen
{'name': 'pool', 'age': 11}
{'name': 'dave', 'age': 28}
{'name': 'jane', 'age': 40}
Answer: These are all `dict`s, not `list`s, so they don't have order; for the inner
`dict`s, they don't have numerical keys, so indexing them is an error. That
said, you can convert the outer `dict` to a sorted `list` to get the result
you want:
from operator import itemgetter
students = {
0: {'name': 'jane', 'age': 40},
1: {'name': 'pool', 'age': 11},
2: {'name': 'dave', 'age': 28}
}
# Sort the sub-dicts by age and print
for student in sorted(students.values(), key=itemgetter('age')):
print(student)
Note: Because the sub-`dict`s are also unordered, there is no guarantee that
`name` appears before `age` in the output for each student. But this will
output the students in the correct order.
|
Python Matplotlib Twinx() cursor values
Question: I want to use the cursor (x,y values get displayed at the bottom left of
figure) to measure the y and x distance between two points, however this only
works for the data plotted on the second axis.
Is there a way to switch back an forth between the second axis and first
y-axis?
Please note: I do not want a programmatic way of getting distance between
points, just to use the cursor when I am viewing data in the figure plot.
Not sure if this helps but my code is literally the example for plotting two
axes from the matplotlib page:
fig, ax1 = plt.subplots()
ax1.plot(sensor1, 'b-')
ax1.set_xlabel('(time)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
ax2.plot(sensor2, 'r.')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
plt.show()
Answer: You can use the excellent answer
[here](http://stackoverflow.com/questions/21583965/matplotlib-cursor-value-
with-two-axes) to get both coordinates displayed at the same time. In order to
get distance between two points, you can then combine this idea with ginput to
map from one to the other and add the result as a title,
import matplotlib.pyplot as plt
import numpy as np
#Provide other axis
def get_othercoords(x,y,current,other):
display_coord = current.transData.transform((x,y))
inv = other.transData.inverted()
ax_coord = inv.transform(display_coord)
return ax_coord
#Plot the data
fig, ax1 = plt.subplots()
t = np.linspace(0,2*np.pi,100)
ax1.plot(t, np.sin(t),'b-')
ax1.set_xlabel('(time)')
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
ax2.plot(t,3.*np.cos(t),'r-')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
#Get user input
out = plt.ginput(2)
#2nd axis from input
x2b, x2t = out[0][0], out[1][0]
y2b, y2t = out[0][1], out[1][1]
#Draw line
ax2.plot([x2b, x2t],[y2b, y2t],'k-',lw=3)
#1st axis from transform
x1b, y1b = get_othercoords(x2b,y2b,ax2,ax1)
x1t, y1t = get_othercoords(x2t,y2t,ax2,ax1)
plt.title("Distance x1 = " + str(x1t-x1b) + " y1 = " + str(y1t-y1b) + "\n"
"Distance x2 = " + str(x2t-x2b) + " y2 = " + str(y2t-y2b))
plt.draw()
plt.show()
which gives something like,
[](http://i.stack.imgur.com/9uDh9.png)
|
What's wrong with this if elif else code in python?
Question: I'm making a simple Rock, Paper, Scissor game. As you can see in the code
snippet, the program asks the user if they want to play best out of 3 or 5.
If the input is `'five', '5'` or `'cinco'` the function `best_out_of_five()`
executes (which prints `'5555555'` to console for now). Similarly, an input of
`'three', '3',` or `'tres'` prints `'3333333'`
My problem is that whatever input is read, it just executes the
`best_out_of_five()` function (even if the input is 'three'). I thought the
if, elif and else would be the easiest part of my code since I have done it
many times before, but I must be missing something that I just can't notice.
import time
def best_out_of_three():
print('333333333')
def best_out_of_five():
print('555555555')
name = input("Hi, what's your name?\n")
print('Alright %s, lets play a quick game of Rock, Paper,'
'Scissors. Do you want to play best out of 3 or 5?' % name)
game_type = input().lower()
if game_type in ['five', '5', 'cinco']:
best_out_of_five()
elif game_type in ['three', '3', 'tres']:
best_out_of_three()
else:
print("That is not a valid answer. Try again later.")
time.sleep(5)
exit()
Answer: Included this in edit, but your if check should check all options. One way to
do that quickly is to use a list:
if game_type in ['five', '5', 'cinco']:
best_out_of_five()
elif game_type in ['three', '3', 'tres']:
best_out_of_three()
If your input is in the list (a linear check against all values in the list),
then it will return true.
|
Python issue when returning function from another file
Question: I'm having a bit of an issue when trying to return a function from another
file.
main.py:
from master_input import load_input
class Vera(object):
def __init__(self):
masterinput = load_input()
self.masterinput = masterinput
def load_masterinput(self):
return self.masterinput
master_input.py:
import sys
def load_input():
if sys.version_info <= (3,0,0):
masterinput = raw_input()
elif sys.version_info >= (2,7,11):
masterinput = input()
return masterinput
There seems to be no output when running the first file. I want it to return
`masterinput` in the second file because if I were to end the function with
`load_input()`, in the second file, it would just output without even
returning `self.masterinput` in the first file.
Answer: You don't show an example of instantiated one of the **Vera()** options nor to
you show any methods that would be using (displaying/printing or otherwise
manipulating) this **masterinput** attribute of your **Veta()** instance.
So it seems quite likely that your code doesn't seem to be "doing" anything.
You'd declared what the objects look like, how to instantiate them and how to
respond to a (poorly named) _load_masterinput()_ method call.
Also your module isn't returning a function. When an object is instantiated
it, that could will be returning a string, the result of calling either the
_input()_ or _raw_input()_ built-in function.
By the way, the smart way, in my opinion, to handle the change from Python2.x
_raw_input()_ to Python3 _input()_ is to use code like this:
#!python
if 'raw_input' in dir(__builtins__):
input = raw_input
Note that I'm assigning the function _raw_input_ to the name _input_ ... I'm
NOT calling the function and assigning the results of its evaluation here.
Then all my code can use _input()_ and we can forget that the Python2
(evaluated) _input()_ semantics ever existed.
If I want to actually return a function from a function here's one way to do
so:
#!python
# filename: my_input.py
def get_input_function():
if 'raw_input' in dir(__builtins__):
# Python2.x and earlier
return raw_input
else:
# Python3
return input
... I would then call this something like so:
#!python
import my_input
input = my_input.get_input_function()
This is unnecessarily obtuse. There's no reason to do something like this for
something so trivial. There are cases where you might imagine calling some
function, with certain arguments and returning different functions based on
those arguments. However, in most cases, you'd still be better off creating a
**_class_** and instantiating an instance of that.
|
Data Frame in Python
Question: I am trying to download Apple's stock price in Python. I noticed that the data
however wasn't in a data frame. It was jumbled when I viewed it in my Spyder
IDE. How do I turn coerce it into a data frame/matrix format and how do I
reference data columns such as "Volume" "Adjusted Close"? I would appreciate
your help.
import ystockquote as ys
aapl=ys.get_historical_prices("aapl","2010-01-01","2015-01-01")
Answer: Not sure what the format of the data you have is, but you can create data
frames with something like this:
import pandas as pd
df = pd.DataFrame(data={'Volume': aapl['Volume'],
'Adjusted Close': aapl['Adjusted Close']})
The keys of the dictionary will be the column names of the data frame, and the
corresponding entries will become the columns.
Have a look at the [DataFrame documentation](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.html), it might give you some clues.
|
targeting one word in the response of an input command python
Question: I have been trying to make an artificial intelligence on python. What I have
been trying to do is make input command responses target one word. So for
example, if the user types in "whats your name" it will have the same response
as "name" by targeting the word "name". how can I do this?
Answer: What you're looking for is a library for handling [Parts of
Speech](https://en.wikipedia.org/wiki/Part_of_speech). Luckily it's pretty
well trodden ground, and there are libraries for lots of different languages -
including Python. Have a look at [Stanford's Natural Language
Toolkit](http://textminingonline.com/dive-into-nltk-part-v-using-stanford-
text-analysis-tools-in-python) (NLTK). Here's an example from the linked
article:
>>> from nltk.tag.stanford import POSTagger
>>> english_postagger = POSTagger(‘models/english-bidirectional-distsim.tagger’, ‘stanford-postagger.jar’)
>>> english_postagger.tag(‘this is stanford postagger in nltk for python users’.split())
[(u’this’, u’DT’),
(u’is’, u’VBZ’),
(u’stanford’, u’JJ’),
(u’postagger’, u’NN’),
(u’in’, u’IN’),
(u’nltk’, u’NN’),
(u’for’, u’IN’),
(u’python’, u’NN’),
(u’users’, u’NNS’)]
The `NN`, `VBZ`, etc. you can see are [speech
tags](https://cs.nyu.edu/grishman/jet/guide/PennPOS.html). It looks like
you're looking for nouns (`NN`).
|
How to assign settings base on testing and production env in flask?
Question: I would like to assign different settings base on various condition such as
testing and production. Therefore I want `create_app` accept an argument
indicating settings and make `create_app` load different settings as follows.
app.py
def create_app(config_file):
app.config['setting'] = config_file['setting']
if __name__ == "__main__":
app = create_app(production_setting)
app.run(host='0.0.0.0', port=config.SERVER_PORT, threaded=True, debug=True)
views.py
import stuff
if app.config['setting'] == 'testing':
print app.config['setting']
test_views.py
@pytest.fixture
def client():
testing_setting['setting'] = 'stuff'
app = create_app(testing_setting)
client = app.test_client()
return client
But I get this error when I run python app.py:
AttributeError: 'module' object has no attribute 'config'
Is there any way to pass arguments from `app` to `views`?
Answer: Here is how I'd do it:
def create_app(config=None):
app = Flask(__name__)
if not config:
config = 'your_app.config.Production'
app.config.from_object(config)
config.py, peered with the file containing `create_app`:
class BaseConfig(object):
SOME_BASE_SETTINGS = 'foo'
DEBUG = False
class Development(BaseConfig):
DEBUG = True
class Production(BaseConfig):
pass
This allows your app to default to production but for instance you could pass
a different configuration name when creating the app for development:
create_app('your_app.config.Development')
For more information on this and a similar example, check out the
documentation: <http://flask.pocoo.org/docs/0.10/config/#development-
production>
|
Using Django Rest Framework as security layer for file system processing
Question: I'm trying to protect my remote server file system from unauthorized users. I
have a remote storage on a different server that store and process PDF's and
PNG's from all kind of processes.
I'm using Python 2.7 with Django 1.8 and Django Rest Framework.
I trying to implement very basic, "Proxy Layer" that will give my control on
who ever use file system.
This is my `view.py`:
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
import requests
class Reports(APIView):
permission_classes = (permissions.AllowAny,) #Thats only for now...
def get(self, request, ssn, validity, file):
response = requests.get(settings.PROXY_BASE_URL + "/reports/" + ssn + "/" + validity + "/" + file)
return Response(response)
This concept works for any other `GET` `POST` `PUT` `DELETE` request that is
text based response (For example json response from the remote server).
My problem is when I call this view, I get in the browser the default REST
method definition page.
[This is the response screenshot](http://prntscr.com/9xz06z)
Answer: As @AlexMorozov said in his comment, you should revert back to `HttpResponse`.
You can see by exploring this [Django
Snippet](https://djangosnippets.org/snippets/1967/).
Here is the code as I see it:
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from django.http import HttpResponse
import requests
import mimetypes
class Reports(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request, ssn, validity, file):
response = requests.get(settings.PROXY_BASE_URL + "/reports/" + ssn + "/" + validity + "/" + file)
mimetype = mimetypes.guess_type(settings.PROXY_BASE_URL + "/reports/" + ssn + "/" + validity + "/" + file) #Return an array
return HttpResponse(response, content_type=mimetype[0])
Give it a go. Good luck :)
|
'TypeError' while using NSGA2 to solve Multi-objective prob. from pyopt-sparse in OpenMDAO 1.x
Question: I am trying to solve a multi-objective optimization problem using openMDAO's
pyopt-sparse driver with NSGA2 algorithm. Following is the code:
from __future__ import print_function
from openmdao.api import IndepVarComp, Component, Problem, Group, pyOptSparseDriver
class Circ2(Component):
def __init__(self):
super(Circ2, self).__init__()
self.add_param('x', val=10.0)
self.add_param('y', val=10.0)
self.add_output('f1', val=40.0)
self.add_output('f2', val=40.0)
def solve_nonlinear(self, params, unknowns, resids):
x = params['x']
y = params['y']
unknowns['f1'] = (x - 0.0)**2 + (y - 0.0)**2
unknowns['f2'] = (x - 1.0)**2 + (y - 1.0)**2
def linearize(self, params, unknowns, resids):
J = {}
x = params['x']
y = params['y']
J['f1', 'x'] = 2*x
J['f1', 'y'] = 2*y
J['f2', 'x'] = 2*x-2
J['f2', 'y'] = 2*y-2
return J
if __name__ == "__main__":
# Defining Problem & Root
top = Problem()
root = top.root = Group()
# Adding in-present variable values and model
startVal = 50.0
root.add('p1', IndepVarComp('x', startVal))
root.add('p2', IndepVarComp('y', startVal))
root.add('p', Circ2())
# Making Connections
root.connect('p1.x', 'p.x')
root.connect('p2.y', 'p.y')
# Configuring Driver
top.driver = pyOptSparseDriver()
top.driver.options['optimizer'] = 'NSGA2'
# Setting bounds for the optimizer
top.driver.add_desvar('p1.x', lower=-600, upper=600)
top.driver.add_desvar('p2.y', lower=-600, upper=600)
# Setting Objective Function(s)
top.driver.add_objective('p.f1')
top.driver.add_objective('p.f2')
# # Setting up constraints
# top.driver.add_constraint('con.c', lower=1.0)
top.setup()
top.run()
and I am getting the following error -
Traceback (most recent call last):
File "/home/prasad/DivyaManglam/Python Scripts/Pareto Testing/Basic_Sphere.py", line 89, in <module>
top.run()
File "/usr/local/lib/python2.7/dist-packages/openmdao/core/problem.py", line 1038, in run
self.driver.run(self)
File "/usr/local/lib/python2.7/dist-packages/openmdao/drivers/pyoptsparse_driver.py", line 280, in run
sol = opt(opt_prob, sens=self._gradfunc, storeHistory=self.hist_file)
File "/usr/local/lib/python2.7/dist-packages/pyoptsparse/pyNSGA2/pyNSGA2.py", line 193, in __call__
self.optProb.comm.bcast(-1, root=0)
File "MPI/Comm.pyx", line 1276, in mpi4py.MPI.Comm.bcast (src/mpi4py.MPI.c:108819)
File "MPI/msgpickle.pxi", line 620, in mpi4py.MPI.PyMPI_bcast (src/mpi4py.MPI.c:47164)
File "MPI/msgpickle.pxi", line 143, in mpi4py.MPI.Pickle.load (src/mpi4py.MPI.c:41248)
TypeError: only length-1 arrays can be converted to Python scalars
Kindly tell if you can make anything of the above error and how to fix it.
Also, in what form would the output of the multi-objective problem's solution
be returned. I intend to generate a pareto-optimal front for this. Thank you
all.
Answer: It turns out this is not an OpenMDAO bug, but rather a bug in the Pyopt sparse
wrapper for NSGA2. The fix wasn't terrible, and I've submitted a [pull
request](https://bitbucket.org/mdolab/pyoptsparse/pull-requests/26/fixed-an-
mpi-related-bug-in-nsga2-wrapper/diff) to the pyoptsparse repo for it. In the
meantime it would be easy enough to patch your local copy of pyoptsparse.
You asked how the results will be reported. The current NSGA2 wrapper doesn't
do anything with the results. It just lets NSGA2 write them all out to a
series of text files such as `nsga2_best_pop.out` that look like this:
# This file contains the data of final feasible population (if found)
# of objectives = 1, # of constraints = 0, # of real_var = 2, # of bits of bin_var = 0, constr_violation, rank, crowding_distance
-1.000000e+00 3.190310e+01 -2.413640e+02 0.000000e+00 1 1.000000e+14
-1.000000e+00 -5.309160e+02 2.449727e+02 0.000000e+00 1 0.000000e+00
-1.000000e+00 -3.995119e+02 -1.829071e+02 0.000000e+00 1 0.000000e+00
As a side note, in your example, you implemented a linearize method for the
component in your example. That method is used when you need to compute
gradients, but NSGA2 is a gradient free optimizer and won't use it at all. So
unless you're also planning to test out some gradient based methods you can
leave that method out of your components.
|
How to draw bar chart using Plotly Offline mod in python?
Question: I have some features and values like
food 3.4
service 4.2
environment 4.3
and i want to draw a bar chart using plotLy offline mode (not registering and
authentication ). so far i have the code for drawing a scaterred line using
offline mode of plotly
import plotly
print (plotly.__version__)
from plotly.graph_objs import Scatter, Layout
plotly.offline.plot({
"data": [
Scatter(x=[1, 2, 3, 4], y=[4, 1, 3, 7])
],
"layout": Layout(
title="hello world"
)
})
the above code open html page and draw a scatered line, How to modify the code
for my above needs.. anyone can help ?
Answer:
import plotly
import plotly.graph_objs
plotly.offline.plot({
"data": [
plotly.graph_objs.Bar(x=['food','service','environment'],y=[3.4,4.2,4.3])
]
})
|
python __init__.py proved to be irrelevant in 3.4?
Question: I am running python 3.4 on the main.py file in the same directory. /root
directory is not in python path. It is simply the current directory that the
script is executing in. All pycache folders were deleted after each test
So why exactly is init.py important? I thought it was necessary as stated in
this post:
[What is __init__.py for?](http://stackoverflow.com/questions/448271/what-is-
init-py-for)
> If you remove the init.py file, Python will no longer look for submodules
> inside that directory, so attempts to import the module will fail.
Right now, it seems to me that init.py is nothing more than a **optional**
constructor where we do housekeeping and other optional things like specifying
the "all" variable, etc. But not a critical item to have
mage showing the results of the test:
[](http://i.stack.imgur.com/TQd2Z.png)
What is going on here?
Answer: * * *
## Answer
**essentially we dont need init.py and its purpose is for legacy and optional
housekeeping things (2.7 vs 3) you may or may not want to do or need. But at
the same time, they have slightly different behavior during more complex
parsing which should also be accounted for if you are building something more
complex**
refer to the following links for more reading material
<https://www.python.org/dev/peps/pep-0420/#namespace-packages-today>
[How do I create a namespace package in
Python?](http://stackoverflow.com/questions/1675734/how-do-i-create-a-
namespace-package-in-python)
[What's the difference between a Python module and a Python
package?](http://stackoverflow.com/questions/7948494/whats-the-difference-
between-a-python-module-and-a-python-package)
<http://programmers.stackexchange.com/questions/276888/python-namespace-vs-
module-with-underscores>
|
image segmentation using kmeans clustering python opencv
Question: I've been trying to achieve similar results to this [MATLAB
code](http://www.mathworks.com/help/images/examples/color-based-segmentation-
using-k-means-clustering.html) which gives me the result I am looking for,
however, I am trying to achieve that using OpenCV 3 + Python.
Here's a similar implementation in OpenCV 3 + Python:
import cv2
import numpy as np
class Segment:
def __init__(self,segments=5):
#define number of segments, with default 5
self.segments=segments
def kmeans(self,image):
image=cv2.GaussianBlur(image,(7,7),0)
vectorized=image.reshape(-1,3)
vectorized=np.float32(vectorized)
criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv2.kmeans(vectorized,self.segments,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
res = center[label.flatten()]
segmented_image = res.reshape((image.shape))
return label.reshape((image.shape[0],image.shape[1])),segmented_image.astype(np.uint8)
def extractComponent(self,image,label_image,label):
component=np.zeros(image.shape,np.uint8)
component[label_image==label]=image[label_image==label]
return component
if __name__=="__main__":
import argparse
import sys
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
ap.add_argument("-n", "--segments", required = False, type = int,
help = "# of clusters")
args = vars(ap.parse_args())
image=cv2.imread(args["image"])
if len(sys.argv)==3:
seg = Segment()
label,result= seg.kmeans(image)
else:
seg=Segment(args["segments"])
label,result=seg.kmeans(image)
cv2.imshow("segmented",result)
result=seg.extractComponent(image,label,2)
cv2.imshow("extracted",result)
cv2.waitKey(0)
What I'm looking for is being able to extract A by itself and rectangle around
it by itself and the background by itself so I can manipulate them seperately.
Here you can see the original image + current output + desired output:
[](http://i.stack.imgur.com/INlbZ.jpg)
Any idea how I can achieve that?
Answer: I can't do this right now, but there are some differences between your
implementation and Matlab's one that you should review:
* **Color space** : Matlab's example works on L*a*b* and your implementation on BGR, specifically on 'a*' and 'b*' channels
* **nClusters** : as you are not hard-coding it, I'm assuming you are using `segments=3` just like Matlab's examples does, right? Your default is 5...
* **GaussianBlur** : I can't see any blur being applied on Matlab's example
* **Attempts** : you are using `attempts=10`, while Matlab is only 3
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.