text
stringlengths 226
34.5k
|
---|
Receiving unknown strings lengths?
Question: So I'm converting a Python program I wrote to Erlang, and it's been a long
time since I used Erlang. So I guest I'm moved back to beginner level. Anyways
from experience every language I use when dealing with sockets have send/recv
functions that always return the length of data sent/receive. In Erlangs
gen_tcp case however doesn't seem to do that.
So when I call send/recv/or inet:setopts it knows when the packet has ended?
Will I need to write a looping recvAll/sendAll function so I can find the
escape or \n in the packet(string) I wish to receive?
<http://erlang.org/doc/man/gen_tcp.html#recv-2>
Example code I'm using:
server(LS) ->
case gen_tcp:accept(LS) of
{ok,S} ->
loop(S),
server(LS);
Other ->
io:format("accept returned ~w - goodbye!~n",[Other]),
ok
end.
loop(S) ->
inet:setopts(S,[{active,once}]),
receive
{tcp,S,Data} ->
Answer = process(Data), % Not implemented in this example
gen_tcp:send(S,Answer),
loop(S);
{tcp_closed,S} ->
io:format("Socket ~w closed [~w]~n",[S,self()]),
ok
end.
Just from looking at examples and documentation it seems like Erlang just
knows. And I want to confirm, because the length of data being received can be
anywhere between to 20 bytes to 9216 bytes and or could be sent in chunks
since the client is a PHP socket library I'm writing.
Thank you,
Ajm.
Answer: TL;DR
> So when I call send/recv/or inet:setopts it knows when the packet has ended?
No, it doesn't.
> Will I need to write a looping recvAll/sendAll function so I can find the
> escape or \n in the packet(string) I wish to receive?
Yes, generally, you will. But erlang can do this job for you.
HOW?
Actually, you couldn't rely on TCP in sense of splitting messages into
packets. In general, TCP will split your stream to arbitrary sized chunks, and
you program have to assemble this chunks and parse this stream by own. So,
first, your protocol must be "self delimiting". For example you can:
1. In binary protocol - precede each packet with its length (fixed-size field). So, protocol frame will looks like this: `<<PacketLength:2/big-unsigned-integer, Packet/binary>>`
2. In text protocol - terminate each line with line feed symbol.
Erlang can help you with this deal. Take a look here
<http://erlang.org/doc/man/gen_tcp.html#type-option>. There is important
option:
{packet, PacketType}(TCP/IP sockets)
Defines the type of packets to use for a socket. The following values are valid:
raw | 0
No packaging is done.
1 | 2 | 4
Packets consist of a header specifying the number of bytes in the packet, followed by that number of bytes. The length of header can be one, two, or four bytes; containing an unsigned integer in big-endian byte order. Each send operation will generate the header, and the header will be stripped off on each receive operation.
In current implementation the 4-byte header is limited to 2Gb.
line
Line mode, a packet is a line terminated with newline, lines longer than the receive buffer are truncated.
Last option (`line`) is most interesting for you. If you'll set this option,
erlang will parse input stream internally and yeld packets splitted by lines.
|
NLTK: sentiment analysis: result one value
Question: So sorry for posting this, as the answer probably is in either this: [NLTK
sentiment analysis is only returning one
value](http://stackoverflow.com/questions/15106032/nltk-sentiment-analysis-is-
only-returning-one-value)
or this post: [Python NLTK not sentiment calculate
correct](http://stackoverflow.com/questions/19622538/python-nltk-not-
sentiment-calculate-correct)
but I don't get how to apply it to my code.
I'm a huge newbie at Python and NLTK and I hate that I have to bother you with
a huge block of code, so sorry once again.
With the code I use, I always get 'pos' as a result. I've tried doing the
classification by leaving the positive features out of the training set. Then
the return is always 'neutral'.
Can anybody tell me what I'm doing wrong? Thank you so much in advance! And
don't mind the random test sentence I used, it was just something that came up
while I was trying to figure out what was wrong.
import re, math, collections, itertools
import nltk
import nltk.classify.util, nltk.metrics
from nltk.classify import NaiveBayesClassifier
from nltk.metrics import BigramAssocMeasures
from nltk.probability import FreqDist, ConditionalFreqDist
from nltk.util import ngrams
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.stem.porter import *
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("english", ignore_stopwords = True)
pos_tweets = ['I love bananas','I like pears','I eat oranges']
neg_tweets = ['I hate lettuce','I do not like tomatoes','I hate apples']
neutral_tweets = ['I buy chicken','I am boiling eggs','I am chopping vegetables']
def uni(doc):
x = []
y = []
for tweet in doc:
x.append(word_tokenize(tweet))
for element in x:
for word in element:
if len(word)>2:
word = word.lower()
word = stemmer.stem(word)
y.append(word)
return y
def word_feats_uni(doc):
return dict([(word, True) for word in uni(doc)])
def tokenizer_ngrams(document):
all_tokens = []
filtered_tokens = []
for (sentence) in document:
all_tokens.append(word_tokenize(sentence))
return all_tokens
def get_bi (document):
x = tokenizer_ngrams(document)
c = []
for sentence in x:
c.extend([bigram for bigram in nltk.bigrams(sentence)])
return c
def get_tri(document):
x = tokenizer_ngrams(document)
c = []
for sentence in x:
c.extend([bigram for bigram in nltk.bigrams(sentence)])
return c
def word_feats_bi(doc):
return dict([(word, True) for word in get_bi(doc)])
def word_feats_tri(doc):
return dict([(word, True) for word in get_tri(doc)])
def word_feats_test(doc):
feats_test = {}
feats_test.update(word_feats_uni(doc))
feats_test.update(word_feats_bi(doc))
feats_test.update(word_feats_tri(doc))
return feats_test
pos_feats = [(word_feats_uni(pos_tweets),'pos')] + [(word_feats_bi(pos_tweets),'pos')] + [(word_feats_tri(pos_tweets),'pos')]
neg_feats = [(word_feats_uni(neg_tweets),'neg')] + [(word_feats_bi(neg_tweets),'neg')] + [(word_feats_tri(neg_tweets),'neg')]
neutral_feats = [(word_feats_uni(neutral_tweets),'neutral')] + [(word_feats_bi(neutral_tweets),'neutral')] + [(word_feats_tri(neutral_tweets),'neutral')]
trainfeats = pos_feats + neg_feats + neutral_feats
classifier = NaiveBayesClassifier.train(trainfeats)
print (classifier.classify(word_feats_test('I am chopping vegetables and boiling eggs')))
Answer: The solution is very simple. Your `word_feats_test` will return an empty
dictionary for the sentence `'I am chopping vegetables and boiling eggs'`;
thus the classifier is biased towards `pos` in case of no features.
I wrapped your sentence in a list:
print(classifier.classify(word_feats_test(
['I am chopping vegetables and boiling eggs'])))
and `neutral` is printed.
You ought to use the exact same function to calculate the features for all 3:
the training set, testing set and classification.
|
Is it possible to restrict access to globals for a block of code in python?
Question: I would like users of my program to be able to define custom scripts in python
without breaking the program. I am looking at something like this:
def call(script):
code = "access modification code" + script
exec(code)
Where "access modification code" defines a scope such that script can only
access variables it instantiates itself. Is it possible to do this or
something with similar functionality, such as creating a new python
environment with its own scope and then receiving output from it?
Thank you for your time :)
_Clarification Edit_ "I want to prevent both active attacks and accidental
interaction with the program variables outside the users script (hence hiding
all globals). The user scripts are intended to be small and inputted as text.
The return of the user script needs to be immediate, as though it were native
to the program."
Answer: There's two separate problems you want to prevent in this scenario:
* Prevent an outside attacker from running arbitrary code in the context of the OS user executing your program. This means preventing [arbitrary code execution](https://en.wikipedia.org/wiki/Arbitrary_code_execution) and [privilege escalation](https://en.wikipedia.org/wiki/Privilege_escalation).
* Preventing a legitimate user of your program from changing the program behavior in unintended ways.
* * *
For the first problem, **you need to make sure that the source of the python
code you execute is the user**. You shouldn't accept input from a socket, or
from a file that other users can write to. You need to make sure, somehow,
that it was the user who is running the program that provided the input.
Actual solutions will depend on your OS, but you may want to consider setting
up restrictive file permissions, if you're storing the code in a file.
**Don't ignore or downplay this problem, or your users will fall victim to
virus/malware/hackers thanks to your program.**
* * *
The way you solve the second problem depends on what exactly constitutes
_intended behaviour_ in your program. If you're happy with outputting simple
data structures, you can **run your user-inputted code in a separate process**
, and pass the result over a pipe in a serialization format such as JSON or
YAML.
Here's a very simple example:
#remember to set restrictive file permissions on this file. This is OS-dependent
USER_CODE_FILE="/home/user/user_code_file.py"
#absolute path to python binary (executable)
PYTHON_PATH="/usr/bin/python"
import subprocess
import json
user_code= '''
import json
my_data= {"a":[1,2,3]}
print json.dumps(my_data)
'''
with open(USER_CODE_FILE,"wb") as f:
f.write(user_code)
user_result_str= subprocess.check_output([PYTHON_PATH, USER_CODE_FILE])
user_result= json.loads( user_result_str )
print user_result
This is a fairly simple solution, and it has significant overhead. Don't use
this if you need to run the user code many times in a short period of time.
Ultimately, this solution is only effective against unsophisticated attackers
(users). Generally speaking, there's no way to protect any user process from
the user itself - nor would it make much sense.
If you really want more assurance, and want to mitigate the first problem too,
you should **run the process as a separate ("guest") user**. This, again, is
OS-dependent.
* * *
Finally a warning: avoid `exec` and `eval` to the best of your abilities. They
don't protect either your program or the user against the inputted code.
There's a lot of information about this on the web, just search for "python
secure eval"
|
What's wrong with maths script?
Question: Sorry if this is a beginner mistake but... I'm a beginner. Here's the script:
num1 = input("Num1:");
num2 = input("Num2:");
try:
val = int(num1)
except ValueError:
print("ERROR : Num1 is not a number!")
val2 = inf(num2)
except ValueError:
print("ERROR : Num2 is not a number!")
print("Maths");
print(num1 + num2);
What the script is meant to do is add the two numbers and if they typed in
something which isn't a number it says it's not a number. I keep getting
errors but I don't know why. NOTE: this is Python.
This is the error I got:
>
> File "<string>", line 10
> except ValueError:
> ^ SyntaxError: invalid syntax
>
Answer: programming is all about breaking a (bigger) problem into smaller problems
the first smaller problem you have is to get integer input. a useful way to do
this is abstracting the problem out
def get_integer(prompt=""):
while True:
try:
return int(raw_input(prompt))
except:
print "Invalid input. please try again"
now you can simply call this method when you want an integer from the user
n1 = get_integer("Enter the first integer:")
n2 = get_integer("Enter The second integer:")
next you must determine how to add those
import operator
def get_operation():
my_operators = {"+":operator.add,"-":operator.sub}
while True:
try:
return my_operators[raw_input("Enter a + or -:")]
except KeyError:
print "Invalid input!"
now you can combine the 2 easily
n1 = get_integer("Enter the first integer:")
n2 = get_integer("Enter The second integer:")
print get_operation()(n1,n2)
you should see something like
>>> n1 = get_integer("Enter the first integer:")
Enter the first integer:7
>>> n2 = get_integer("Enter The second integer:")
Enter The second integer:8
>>> print get_operation()(n1,n2)
Enter a + or -:+
15
|
Why is views method not being invoked?
Question: I have a web directory with `urls.py` in a directory (RazorWare_Web) as
follows:
from RazorWare_Web.views import home
urlpatterns = patterns('',
url('/', home.index, name="index"),
url(r'^razorware/', include("RazorCRM_App.urls")),
url(r'^admin/', include(admin.site.urls)),
)
So in my browser, `http://localhost:8000/razorware` navigates to the `home`
view's `index()` method. I'm a little confused by this. I would expect
`http://localhost:8000/` would navigate to `home`. Instead this produces a url
not found error page.
Aside from that, the real problem (and I suspect it is related to the above)
exists when I perform a `$.getJSON` call from my HTML page. First, the actual
app exists under the sibling directory, RazorCRM_App, with the following:
from RazorCRM_App.views import queries
urlpatterns = [
url(r'query_locale', queries.query_locales, name="query_locales"),
]
When I execute the following script:
function query_locale_by_zip(){
var post_code = txt_postal.val();
$.getJSON("query_locale", {post_code: post_code}, function(result){
console.log("[APP] query locale for: " + post_code + " [returned: " + result.success + "]")
});
}
... the `queries.query_locales` method is not being called. However, I do get
the following output from the console:
> [25/Feb/2015 15:20:51] "GET /razorware/query_locale?post_code=9 HTTP/1.1"
> 200
> [25/Feb/2015 15:20:51] "GET /razorware/query_locale?post_code=92 HTTP/1.1"
> 200
> [25/Feb/2015 15:20:51] "GET /razorware/query_locale?post_code=920 HTTP/1.1"
> 200
> [25/Feb/2015 15:20:52] "GET /razorware/query_locale?post_code=9205
> HTTP/1.1" 200
> [25/Feb/2015 15:20:52] "GET /razorware/query_locale?post_code=92058
> HTTP/1.1" 200
I might understand if there was a message stating that the url could not be
found. But this just seems odd.
Using Django version 1.7.1 and Python 3.4.2
Answer: Your root url should look like `url(r'^$', home.index, name="index")` and your
query_locale url should look like `url(r'^query_locale/$',
queries.query_locales, name="query_locales")`.
[url dispatcher](https://docs.djangoproject.com/en/1.7/topics/http/urls/) has
broad documentation about how urls work.
|
How can I get my Python script to work using bash?
Question: I am new to this site so hopefully this is the correct location to place this
question.
I am trying to write a script using python for Linux, that:
1. creates a file `file.txt`
2. appends the output of the `'lsof'` command to `file.txt`
3. read each line of the output and append them to an array.
4. then print each line.
I'm basically just doing this to familiarize myself with using python for
bash, I'm new to this area so any help would be great. I'm not sure where to
go from here. Also if there is a better way to do this I'm open to that!
#!/usr/bin/env python
import subprocess
touch = "touch file.txt"
subprocess.call(touch, shell=True)
xfile = "file.txt"
connection_count = "lsof -i tcp | grep ESTABLISHED | wc -l"
count = subprocess.call(connection_count, shell=True)
if count > 0:
connection_lines = "lsof -i tcp | grep ESTABLISHED >> file.txt"
subprocess.call(connection_lines, shell=True)
with open(subprocess.call(xfile, shell=True), "r") as ins:
array = []
for line in ins:
array.append(line)
for i in array:
print i
Answer: `subprocess.call` returns the return code for the process that was started
(`$?` in bash). This is almost certainly not what you want -- and explains why
this line almost certainly fails:
with open(subprocess.call(xfile, shell=True), "r") as ins:
(you can't open a number).
Likely, you want to be using `subprocess.Popen` with `stdout=subprocess.PIPE`.
Then you can read the output from the pipe. e.g. to get the count, you
probably want something like:
connection_count = "lsof -i tcp | grep ESTABLISHED"
proc = subprocess.POPEN(connection_count, shell=True, stdout=subprocess.PIPE)
# line counting moved to python :-)
count = sum(1 for unused_line in proc.stdout)
(you could also use `Popen.communicate` here)
Note, excessive use of `shell=True` is always a bit scary for me... It's much
better to chain your pipes together as demonstrated in the
[documentation](https://docs.python.org/2/library/subprocess.html#replacing-
shell-pipeline).
|
IPython notebook stops evaluating cells after plt.show()
Question: I am using iPython to do some coding. When I open the notebook and run some
codes by doing SHIFT+ENTER it runs. But after one or two times, it stops
giving any output. Why is that. I have to shutdown the notebook again open it
and then it runs for few times and same problem again.
Here is the code I have used.
Cell Toolbar:
Question 1: Rotational Invariance of PCA
I(1): Importing the data sets and plotting a scatter plot of the two.
In [1]:
# Channging the working directory
import os
os.getcwd()
path="/Users/file/"
os.chdir(path)
pwd=os.getcwd()
print(pwd)
# Importing the libraries
import pandas as pd
import numpy as np
import scipy as sp
# Mentioning the files to be imported
file=["2d-gaussian.csv","2d-gaussian-rotated.csv"]
# Importing the two csv files in pandas dataframes
XI=pd.read_csv(file[0],header=None)
XII=pd.read_csv(file[1],header=None)
#XI
XII
Out[5]:
0 1
0 1.372310 -2.111748
1 -0.397896 1.968246
2 0.336945 1.338646
3 1.983127 -2.462349
4 -0.846672 0.606716
5 0.582438 -0.645748
6 4.346416 -4.645564
7 0.830186 -0.599138
8 -2.460311 2.096945
9 -1.594642 2.828128
10 3.767641 -3.401645
11 0.455917 -0.224665
12 2.878315 -2.243932
13 -1.062223 0.142675
14 -0.698950 1.113589
15 -4.681619 4.289080
16 0.411498 -0.041293
17 0.276973 0.187699
18 1.500835 -0.284463
19 -0.387535 -0.265205
20 3.594708 -2.581400
21 2.263455 -2.660592
22 -1.686090 1.566998
23 1.381510 -0.944383
24 -0.085535 -1.697205
25 1.030609 -1.448967
26 3.647413 -3.322129
27 -3.474906 2.977695
28 -7.930797 8.506523
29 -0.931702 1.440784
... ... ...
70 4.433750 -2.515612
71 1.495646 -0.058674
72 -0.928938 0.605706
73 -0.890883 -0.005911
74 -2.245630 1.333171
75 -0.707405 0.121334
76 0.675536 -0.822801
77 1.975917 -1.757632
78 -1.239322 2.053495
79 -2.360047 1.842387
80 2.436710 -1.445505
81 0.348497 -0.635207
82 -1.423243 -0.017132
83 0.881054 -1.823523
84 0.052809 1.505141
85 -2.466735 2.406453
86 -0.499472 0.970673
87 4.489547 -4.443907
88 -2.000164 4.125330
89 1.833832 -1.611077
90 -0.944030 0.771001
91 -1.677884 1.920365
92 0.372318 -0.474329
93 -2.073669 2.020200
94 -0.131636 -0.844568
95 -1.011576 1.718216
96 -1.017175 -0.005438
97 5.677248 -4.572855
98 2.179323 -1.704361
99 1.029635 -0.420458
100 rows × 2 columns
The two raw csv files have been imported as data frames. Next we will concatenate both the dataframes into one dataframe to plot a combined scatter plot
In [6]:
# Joining two dataframes into one.
df_combined=pd.concat([XI,XII],axis=1,ignore_index=True)
df_combined
Out[6]:
0 1 2 3
0 2.463601 -0.522861 1.372310 -2.111748
1 -1.673115 1.110405 -0.397896 1.968246
2 -0.708310 1.184822 0.336945 1.338646
3 3.143426 -0.338861 1.983127 -2.462349
4 -1.027700 -0.169674 -0.846672 0.606716
5 0.868458 -0.044767 0.582438 -0.645748
6 6.358290 -0.211529 4.346416 -4.645564
7 1.010685 0.163375 0.830186 -0.599138
8 -3.222466 -0.256939 -2.460311 2.096945
9 -3.127371 0.872207 -1.594642 2.828128
10 5.069451 0.258798 3.767641 -3.401645
11 0.481244 0.163520 0.455917 -0.224665
12 3.621976 0.448577 2.878315 -2.243932
13 -0.851991 -0.650218 -1.062223 0.142675
14 -1.281659 0.293194 -0.698950 1.113589
15 -6.343242 -0.277567 -4.681619 4.289080
16 0.320172 0.261774 0.411498 -0.041293
17 0.063126 0.328573 0.276973 0.187699
18 1.262396 0.860105 1.500835 -0.284463
19 -0.086500 -0.461557 -0.387535 -0.265205
20 4.367168 0.716517 3.594708 -2.581400
21 3.481827 -0.280818 2.263455 -2.660592
22 -2.300280 -0.084211 -1.686090 1.566998
23 1.644655 0.309095 1.381510 -0.944383
24 1.139623 -1.260587 -0.085535 -1.697205
25 1.753325 -0.295824 1.030609 -1.448967
26 4.928210 0.230011 3.647413 -3.322129
27 -4.562678 -0.351581 -3.474906 2.977695
28 -11.622940 0.407100 -7.930797 8.506523
29 -1.677601 0.359976 -0.931702 1.440784
... ... ... ... ...
70 4.913941 1.356329 4.433750 -2.515612
71 1.099070 1.016093 1.495646 -0.058674
72 -1.085156 -0.228560 -0.928938 0.605706
73 -0.625769 -0.634129 -0.890883 -0.005911
74 -2.530594 -0.645206 -2.245630 1.333171
75 -0.586007 -0.414415 -0.707405 0.121334
76 1.059484 -0.104132 0.675536 -0.822801
77 2.640018 0.154351 1.975917 -1.757632
78 -2.328373 0.575707 -1.239322 2.053495
79 -2.971570 -0.366041 -2.360047 1.842387
80 2.745141 0.700888 2.436710 -1.445505
81 0.695584 -0.202735 0.348497 -0.635207
82 -0.994271 -1.018499 -1.423243 -0.017132
83 1.912425 -0.666426 0.881054 -1.823523
84 -1.026954 1.101637 0.052809 1.505141
85 -3.445865 -0.042626 -2.466735 2.406453
86 -1.039549 0.333189 -0.499472 0.970673
87 6.316906 0.032272 4.489547 -4.443907
88 -4.331379 1.502719 -2.000164 4.125330
89 2.435918 0.157511 1.833832 -1.611077
90 -1.212710 -0.122350 -0.944030 0.771001
91 -2.544347 0.171460 -1.677884 1.920365
92 0.598670 -0.072133 0.372318 -0.474329
93 -2.894802 -0.037809 -2.073669 2.020200
94 0.504119 -0.690281 -0.131636 -0.844568
95 -1.930254 0.499670 -1.011576 1.718216
96 -0.715406 -0.723096 -1.017175 -0.005438
97 7.247917 0.780923 5.677248 -4.572855
98 2.746180 0.335849 2.179323 -1.704361
99 1.025371 0.430754 1.029635 -0.420458
100 rows × 4 columns
Plotting two separate scatter plot of all the four columns onto one scatter diagram
In [ ]:
import matplotlib.pyplot as plt
# Fucntion for scatter plot
def scatter_plot():
# plots scatter for first two columns(Unrotated Gaussian data)
plt.scatter(df_combined.ix[:,0], df_combined.ix[:,1],color='red',marker='+')
# plots scatter for Rotated Gaussian data
plt.scatter(df_combined.ix[:,2], df_combined.ix[:,3] ,color='green', marker='x')
legend = plt.legend(loc='upper right')
# set ranges of x and y axes
plt.xlim([-12,12])
plt.ylim([-12,12])
plt.show()
# Function call
scatter_plot()
In [ ]:
def plot_me1():
# create figure and axes
fig = plt.figure()
# split the page into a 1x1 array of subplots and put me in the first one (111)
# (as a matter of fact, the only one)
ax = fig.add_subplot(111)
# plots scatter for x, y1
ax.scatter(df_combined.ix[:,0], df_combined.ix[:,1], color='red', marker='+', s=100)
# plots scatter for x, y2
ax.scatter(df_combined.ix[:,2], df_combined.ix[:,3], color='green', marker='x', s=100)
plt.xlim([-12,12])
plt.ylim([-12,12])
plt.show()
plot_me1()
In [ ]:
Answer: You should not use `plt.show()` in the notebook. This will open an external
window that blocks the evaluation of your cell.
Instead begin your notebooks with `%matplotlib inline` or the cool new
`%matplotlib notebook` (the latter is only possible with `matplotlib` >= 1.4.3
and `ipython` >= 3.0)
After the evaluation of each cell, the (still open) figure object is
automatically shown in your notebook.
This minimal code example works in notebook. Note that it does not call
`plt.show()`
%matplotlib inline
import matplotlib.pyplot as plt
x = [1,2,3]
y = [3,2,1]
_ = plt.plot(x,y)
`%matplotlib inline` simply displays the image.

`%matplotlib notebook` was added recently and offers many of the cool features
(zooming, measuring,...) of the interactive backends:

|
Python prime numbers generators in terminal
Question: I have this code:
# Developing a program to generate all prime numbers
def gen_primes():
n = 2
primes = set()
while True:
for p in primes:
if n%p == 0:
break
else:
primes.add(n)
yield n
n += 1
I may be way off but I assume the gen_primes().next () to begin with 2, then
move on to the next prime number 3, and so on and so forth until the end of
time. Yet when I access these values in terminal, they don't do that at all.
>>> for i in range(10):
... gen_primes().next()
...
2
2
2
2
2
2
2
2
2
2
and
>>> gen_primes().next()
2
>>> gen_primes().next()
2
>>> gen_primes().next()
2
>>> gen_primes().next()
2
What is going on here that I am unaware of? As a side note I am importing the
script (as a module) if it matters at all.
Answer: `gen_primes()` creates a new generator object every time. Instead, store it in
a variable and use `next`, like this
>>> primes = gen_primes()
>>> for _ in range(10):
... next(primes)
...
...
2
3
5
7
11
13
17
19
23
29
Instead of you iterating the iterable, leave that to the built-in
`itertools.islice` module, like this
>>> from itertools import islice
>>> for prime in islice(gen_primes(), 10):
... print(prime)
...
...
2
3
5
7
11
13
17
19
23
29
|
pattern to dictionary of lists Python
Question: I have a file like this
module1 instance1(.wire1 (connectionwire1), .wire2 (connectionwire2),.... ,wire100 (connectionwire100)) ; module 2 instance 2(.wire1 (newconnectionwire1), .wire2 (newconnectionwire2),.... ,wire99 (newconnectionwire99))
Ther wires are repeated along modules. There can be many modules. I want to
build a dictionary like this (not every wire in 2nd module is a duplicate).
[wire1:[(module1, instance1, connection1), (module2, instance2,newconnection1), wire2:[(module1 instance1 connection2),(module2, instance2,newconnection1)]... wire99:module2, instance2, connection99), ]
I am splitting the string on `;` then splitting on `,` and then `(` to get
wire and connectionwire strings . I am not sure how to fill the data structure
though so the wire is the key and module, instancename and connection are
elements.
Goal- get this datastructure- [ wire: (module, instance, connectionwire) ]
filedata=file.read()
realindex=list(find_pos(filedata,';'))
tempindex=0
for l in realindex:
module=filedata[tempindex:l]
modulename=module.split()[0]
openbracketindex=module.find("(")
closebracketindex=module.strip("\n").find(");")
instancename=module[:openbracketindex].split()[1]
tempindex=l
tempwires=module[openbracketindex:l+1]
#got to split wires on commas
for tempw in tempwires.split(","):
wires=tempw
listofwires.append(wires)
Answer: Using the `re` module.
import re
from collections import defaultdict
s = "module1 instance1(.wire1 (connectionwire1), .wire2 (connectionwire2), .wire100 (connectionwire100)) ; module2 instance2(.wire1 (newconnectionwire1), .wire2 (newconnectionwire2), wire99 (newconnectionwire99))'
d = defaultdict(list)
module_pattern = r'(\w+)\s(\w+)\(([^;]+)'
mod_rex = re.compile(module_pattern)
wire_pattern = r'\.(\w+)\s\(([^\)]+)'
wire_rex = re.compile(wire_pattern)
for match in mod_rex.finditer(s):
#print '\n'.join(match.groups())
module, instance, wires = match.groups()
for match in wire_rex.finditer(wires):
wire, connection = match.groups()
#print '\t', wire, connection
d[wire].append((module, instance, connection))
for k, v in d.items():
print k, ':', v
Produces
wire1 : [('module1', 'instance1', 'connectionwire1'), ('module2', 'instance2', 'newconnectionwire1')]
wire2 : [('module1', 'instance1', 'connectionwire2'), ('module2', 'instance2', 'newconnectionwire2')]
wire100 : [('module1', 'instance1', 'connectionwire100')]
|
How can python do imports after I clear sys.path - Import precedence
Question: I have a python module named Queue that conflicts with the default queue in
python.
While trying to force the import of the default queue, I tried to simply clear
sys.path.
I was of the understanding that the imports are looked up from sys.path. But
Python still seems to be able to import modules after I clear syspath.
Explain this please!
In [26]: sys.path
Out[26]: []
In [27]: import datetime
In [28]: datetime
Out[28]: <module 'datetime' from '/usr/local/python2.7/lib/python2.7/lib-dynload/datetime.so'>
In [31]: import xyz.Queue
In [32]: xyz.Queue
Out[32]: <module 'xyz.Queue' from '/public/abc/def/ghi/xyz/Queue/__init__.pyc'>
In [33]: sys.path
Out[33]: []
Also How to import native module queue instead of Queue.
I know that refactoring Queue is the solution this problem deserves, but it
not the one it needs right now.
Answer: Add `from __future__ import absolute_import` as the first line in your file.
This will force all imports to be absolute rather then relative. So `import
Queue` will import the standard module, to import a local module you'd use
`from . import foobar`
|
Connecting between existing .db to Postgres using pgAdmin
Question: Completely new to SQL.
I've created a db in Python using SQLAlchemy, now I want to connect/import it
to postgres, using pgAdmin III. How can I do it?
Answer: Postgres can restore databases from file by pg_restore. It can handle files
that is just a sequence of sql commands. And question - you want to import it
to use postgre with sqlalchemy or without?
|
Python Octal Escape String
Question: I'm doing a web application login automation. The web app prefix and suffix
few octal escaped character with password , make md5 hash of the password at
client side and send to server.
So when I Md5 encrypt the string using Java Script, I get below result.
The webapp uses <https://ideone.com/2C1b5> JS lib for client side MD5
conversion. **hexMD5()** belongs to that lib.

But when I am trying to do the same using python I get different result.
import hashlib
def getMd5(string):
m = hashlib.md5()
m.update(string)
return m.hexdigest()
prefix = "\051"
suffix = "\341\303\026\153\155\271\161\166\030\054\324\011\046\035\344\274"
prefix = unicode(prefix,'unicode-escape')
suffix = unicode(suffix,'unicode-escape')
salted = prefix+"HELLO"+suffix
print getMd5(salted.encode('utf8'))
**Result**
c7862e873e9bc54a93aec58c199cda37
Can any one please explain what I'm doing wrong here ?
Answer:
import hashlib
def getMd5(string):
m = hashlib.md5()
m.update(string)
return m.hexdigest()
prefix = "\051"
suffix ="\341\303\026\153\155\271\161\166\030\054\324\011\046\035\344\274"
salted = prefix+"HELLO"+suffix
print getMd5(salted)
37a0c199850b36090b439c3ac152fd70
Not using unicode gives the same output as your Javascript.
If I understand your comment correctly:
len(r"\051" == 4 # use raw string r
len("\051") == 1
|
Insert multiple images in a single PDF according to image.coordinates - Python
Question: I have a image path's and corresponding coordinates as a dict. Ex: {'coords':
[u'530,88,592,99'], 'filepath': 1.jpg}, {'coords': [u'7,12,152,85'],
'filepath': 2.jpg}, {'coords': [u'448,12,594,86'], 'filepath': 3.jpg} I would
like to generate a single PDF with all the images as per the relative-
coordinates of the images. I guess, it might be possible with reportlab, but
no initial luck. Thanks in advance.
Answer: You can use `reportlab` for this purpose. `drawImage` can be used for image
drawing in `Pdf`.
`drawImage` arguments.
drawImage(image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c')
* “image” may be an image filename or an ImageReader object.
* x and y define the lower left corner of the image you wish to draw
* If width and height are given, the image will be stretched to fill the given rectangle bounded by (x, y, x+width, y-height).
**Example program:**
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
c = canvas.Canvas("test.pdf")
# move the origin up and to the left
c.translate(inch,inch)
c.setFillColorRGB(1,0,1)
c.drawImage("image1.jpg", 10, 10, 50, 50)
c.drawImage("image2.jpg", 60, 60, 50, 50)
c.showPage()
c.save()
This program should generate a pdf `test.pdf` with two images in the
corresponding coordinates.Now you can parse coordinates and images from your
`coords` dictionary.
**Let:**
coords_dict = {'coords': [u'7,12,152,85'], 'filepath': 2.jpg}
Then `drawImage` for your dict should be
c.drawImage(
coords_dict["filepath"],
coords_dict["coords"][0],
coords_dict["coords"][1],
coords_dict["coords"][3]-coords_dict["coords"][0],
coords_dict["coords"][4]-coords_dict["coords"][2])
For more info please
[check](http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html)
|
Python: how to get a number followed by a specific key word from a string
Question: Let's say I have a string like this:
Benchmark\r\n\tRunning for engine innodb\r\n\tAverage number of seconds to run all queries: 0.374 seconds\r\n\tMinimum number of seconds to run all queries: 0.374 seconds\r\n\tMaximum number of seconds to run all queries: 0.374 seconds\r\n\tNumber of clients running queries: 1\r\n\tAverage number of queries per client: 2
If I'm only interested in the value followed by 'Average number of seconds to
run all queries:', how can I get it?
Answer: One overkill of this problem is to use the regular expression since the
regular expression is a general approach to deal with the patter matching.
For example, You can use the following code to solve your problem here:
import re
mystring = 'Your input'
float_pattern = '(\d*\.\d*)'
prefix = 'Average number of seconds to run all queries: '
postfix = ' seconds'
all_time = re.findall(prefix+float_pattern+postfix,mystring)
all_time_t = map(lambda x:float(x),all_time)
average_time = sum(all_time_t)/len(all_time_t)
Read the document for regular expression for more
information:<https://docs.python.org/2/library/re.html>
|
__init__ and instance show different values for instance attributes
Question: I am attempting to create a subclass of `Response` from the "Requests" library
for Python. When I execute the following with Python 2.7.6 and Requests 2.5.3:
import requests
class Page(requests.Response):
# A Page is a Response that reported itself to be OK (HTTP "200").
def __init__(self, url):
requests.Response.__init__(self)
self = requests.get(url)
assert self.status_code is 200
print "Status code according to __init__: " + str(self.status_code)
p = Page("http://www.google.com/")
print "Status code according to instance: " + str(p.status_code)
I get this output:
Status code according to __init__: 200
Status code according to instance: None
This is surprising to me. I thought those two calls were addressing the same
attribute of the same instance, and had therefore expected them to give the
same output.
Indeed, all of the instance's attributes show themselves to be populated when
called from `__init__` (i.e. not just `self.status_code` but also `self.text`,
etc). Yet, if I call the same attributes from the instance (e.g. `p.text`),
they yield `None` or suchlike, as though they had not been initialized.
Why this disparity between what `__init__` sees and what the instance sees?
Answer: Evidently those two calls were **not** addressing the same attribute of the
same instance. That is why they did not give the same output. This solves the
problem, by creating a Request object and then copying its attributes to the
Page object:
import requests
class Page(requests.Response):
# A Page is a Response that has been retrieved and found OK (HTTP "200").
def __init__(self, url):
requests.Response.__init__(self)
r = requests.get(url)
self.__dict__.update(r.__dict__)
assert self.status_code is 200
print "Status code according to __init__: " + str(self.status_code)
p = Page("http://www.google.com/")
print "Status code according to object: " + str(p.status_code)
I suspect there's a more elegant solution available (although I haven't come
up with one yet), so I'll not mark this question as "answered" for now. Please
submit a better solution if you have one!
|
Python: why is random.randint(1,100) returning two values?
Question: I'm trying to work through python assignments because I already know java and
C#, and managed to place out of the python class in my college with my AP
Computer Science score.
This is a SetTitle function that I have created. The Write function has
already been implemented in the given class.
class HTMLOutputFile:
def SetTitle( title ):
if not str(title):
return false
else:
Write("<TITLE>",title,"<TITLE>")
return true
This file is calling my SetTitle method to make sure it works properly.
from htmloutputfile import *
import random
MyHTMLOutputFile = HTMLOutputFile()
if MyHTMLOutputFile.SetTitle(random.randint(1,100)):
print('Error: SetTitle accepted non-string')
exit(0)
if not MyHTMLOutputFile.SetTitle('My Title'):
print('Error: SetTitle did not accept string')
exit(0)
But, when I run it, I receive the error
if MyHTMLOutputFile.SetTitle(random.randint(1,100)):
TypeError: SetTitle() takes exactly 1 argument (2 given)
Do you guys have any ideas why random.randint(1,100) might be considered as
two arguments instead of 1? I don't need a direct fix if you don't want to
give it to me, but I'd like a point in the right direction.
Thanks.
Answer: change
def SetTitle( title ):
to
def SetTitle(self, title ):
Each class method must have the first parameter the instance the method is
called on. It thinks it is two arguments because it automatically passes self
to the function.
[What is the purpose of self in
Python?](http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-
self-in-python)
|
Send python email using SMTP with a subject
Question: I am trying to send an email in Python using SMTP, with a From address, To
address, BCC address, subject, and message. I have the email sending, and it
even sends to the BCC as it should, the only issue is that the **message** of
the email says:
To: [email protected]
Subject: Subject goes here
this is the email that I’m sending
when I only want the message itself to show where the message belongs, and the
subject of the email isn't set, so there's a blank subject. Here is how I have
it set up:
def sendEmail(fromAddress, toAddress, bccAddress, appName, message):
subject = "Subject goes here"
BODY = string.join((
"From: %s\r\n" % fromAddress,
"To: %s\r\n" % toAddress,
"Subject: %s\r\n" % subject,
"\r\n",
message
), "\r\n")
#im using arbitrary values here, when I run it I use actual login info
username = '[email protected]'
password = 'password'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username,password)
toList = []
bccList = []
toList.append(toAddress)
bccList.append(bccAddress)
server.sendmail(fromAddress, toList + bccList, BODY)
server.quit()
Answer: Use the `email` package
([docs](https://docs.python.org/3.4/library/email.html)).
from email.mime.text import MIMEText
def send_mail(to, from_addr, subject, text):
msg = MIMEText(text)
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to
s = smtplib.SMTP_SSL("smtp.gmail.com")
s.login(smtp_user, smtp_pass)
# for Python 3
s.send_message(msg)
# OR
# for Python 2 (or 3, will still work)
s.sendmail(from_addr, [to], msg.as_string())
s.quit()
|
Difference between send(None) and Next()
Question: By redefining the yield statement to be an expression in [PEP 342-- Coroutines
via Enhanced Generators](https://www.python.org/dev/peps/pep-0342/) powerful
new functionality was added to Python. David Beasley has an excellent
presentation on Python coroutines [A Curious Course on Coroutines and
Concurrency](http://www.dabeaz.com/coroutines/).
As the PEP states, A yield expression's value is None whenever the generator
is resumed by a normal next() call. To instantiate the generator either next()
or send(None) must be called (i.e. cannot send non-None value initially).
Is there any advantage in calling next() vs send(None)? next() is a Built_in
function, so perhaps that's a factor, but there doesn't seem to be any other
differences. I'm somewhat surprised, it would seem more Pythonic to add an
optional variable to next than add a new function that does the same thing. Am
I missing something?
Here is a simple coroutine to keep a running total of numbers entered, by
sending them to the coroutine.
import numbers
def running_sum() :
g_in = 0
g_out = 0
while g_in is not None :
g_in = (yield g_out)
if isinstance(g_in, numbers.Number) :
g_out += g_in
print 'in_val =',g_in,'sum =',g_out
Answer: What you are missing is that [generators are a special case of
iterators](http://stackoverflow.com/questions/2776829/difference-between-
pythons-generators-and-iterators).
An iterator is anything which (correctly) implements the `__iter__()` and
`__next__()` methods. The `__iter__()` method, in this case, is simply
supposed to return the iterator itself. The `__next__()` method is called to
implement `next()`.
The key, however, is that `__next__()` _takes no arguments_ (besides `self`).
The `.send()` method is not part of the iteration protocol. In the general
case, an iterator is not required to implement `.send()`. Indeed, if you call
`iter([])`, you will get an object which lacks the method. Sending only works
on true generators (functions written using the `yield` syntax). By contrast,
`next()` works on any iterator.
|
Replace all the values in a certain column with certain values using csv reader Python
Question: This is the question continous from my previous question. Thank to many
people, I could modify my code as below.
import csv
with open("SURFACE2", "rb") as infile, open("output.txt", "wb") as outfile:
reader = csv.reader(infile, delimiter=" ")
writer = csv.writer(outfile, delimiter=" ")
for row in reader:
row[18] = "999"
writer.writerow(row)
I just change delimiter from "\t" to " ". Whiel with previous delimiter, the
code only worked upto row[0], with " " the code can work until row[18].
15.20000 120.60000 98327 get data information here. SURFACE DATA FROM ??????????? SOURCE FM-12 SYNOP 155.00000 1 0 0 0 0 T F F -888888 -888888 20020601030000 100820.00000
From the data line above, row[18] is just in the middle between 15.20000 and
120.60000.
I am not sure what happens in between these two values. Maybe delimiter
changes? However visually I can't notice any difference. Is there any way
which I can know the delimiter changed and if so, do you have any idea to
handle multiple delimiter for one code?
Any idea or help would be really appreciated.
Thank you, Isaac
* * *
The results from repr(next(infile)):
' 15.20000 120.60000 98327 get data information here. SURFACE DATA FROM ??????????? SOURCE FM-12 SYNOP 155.00000 1 0 0 0 0 T F F -888888 -888888 20020601030000 100820.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0\n'
' 99070.00000 0 155.00000 0 303.20001 0 297.79999 0 3.00000 0 140.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0\n'
'-777777.00000 0-777777.00000 0 1.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0\n'
' 1 0 0\n'
' 55.10000 -3.60000 03154 get data information here. SURFACE DATA FROM ??????????? SOURCE FM-12 SYNOP 16.00000 1 0 0 0 0 T F F -888888 -888888 20020601030000-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0\n'
'-888888.00000 0 16.00000 0 281.20001 0 279.89999 0 0.00000 0 0.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0\n'
'-777777.00000 0-777777.00000 0 1.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0\n'
' 1 0 0\n'
As you can see actually four first lines should be one line. For some reason,
full line seems divided into 4 parts. Do you have any idea? Thank you, Isaac
Answer: **N.B.** The file format is discussed on page 19 of this
[document](http://www2.mmm.ucar.edu/wrf/users/wrfda/Tutorials/2012_July/docs/WRFDA_obsproc.pdf).
This more-or-less agrees with the sample data.
**EDIT**
OK, after considering the various comments, additional answers, and reading
the [original question](http://stackoverflow.com/questions/28734402/replace-
all-values-in-a-certain-column-with-one-value-python) it would seem that the
file in question is not a CSV file. It is weather observation data formatted
as "little_r" which uses fixed width fields padded with spaces. There is not
much info available so I'm guessing, but each group of 4 lines seem to
comprise a single observation. From your previous question it seems that you
want to update the 3rd column in the first line? The other 3 lines would be
skipped. Then update the 3rd column in the first line of the next set of 4
lines, etc., etc.
An example from the OP:
15.20000 120.60000 98327 get data information here. SURFACE DATA FROM ??????????? SOURCE FM-12 SYNOP 155.00000 1 0 0 0 0 T F F -888888 -888888 20020601030000 100820.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0
99070.00000 0 155.00000 0 303.20001 0 297.79999 0 3.00000 0 140.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0
-777777.00000 0-777777.00000 0 1.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0-888888.00000 0
1 0 0
The first 2 columns of the first line are (I'm guessing) the latitude and
longitude for the observations. I have no idea what the 3rd column `98327` is,
but this is the column that the OP wants to update (based on previous
question).
It's not a CSV file, so don't process it as one. Instead, because there are
fixed width fields, we know the offset and width of the field that needs to be
updated. Based on the sample data the 3rd column occupies characters 41-46.
So, to update the data and write to a new file:
offset_col_3 = 41
length_col_3 = 5
with open('SURFACE2') as infile, open('output.txt', 'w') as outfile:
for line_no, line in enumerate(infile):
if line_no % 4 == 0: # every 4th line starting with the first
line = '{}{:>5}{}'.format(line[:offset_col_3], 999, line[offset_col_3+length_col_3:])
outfile.write(line)
* * *
**Original answer**
Try reading line 20 (row[19]) (assuming no header line in the CSV file,
otherwise line 21) from the file and inspecting it in Python:
with open("SURFACE2") as infile:
for i in range(20):
print repr(next(infile))
The last line displayed will be row 18. If, for example, tabs are delimiters
then you might see `\t` in between the columns of data. Compare the previous
line to the last line to see if there is a difference in the delimiter used.
If you find that your CSV file is mixing delimiters, then you might have to
split the fields manually.
|
Split string using regular expression, how to ignore apostrophe?
Question: I am doing a spell check tutorial in Python and it uses this regular
expression:
import re
def split_line(line):
return re.findall('[A-Za-z]+(?:\`[A-Za-z)+)?',line)
I was wondering if you could help me change this function so it will ignore
`'`, i.e. if I input the string `he's` i will get `['he's']` and not
`['he','s']`.
Answer: First you'll need to fix the original expression by replacing `)` with `]` as
mentioned by Marcin. Then simply add `'` to the list of allowed characters
(escaped by a back-slash):
import re
def split_line(line):
return re.findall('[A-Za-z\']+(?:\`[A-Za-z]+)?',line)
split_line("He's my hero")
#["He's", 'my', 'hero']
Of course, this will not consider any edge cases where the apostrophe is at
the beginning or at the end of a word.
|
import module from a different directory
Question: I have a project within which we write scripts for standalone utilities, in
whatever language possible.
These scripts are separated on a team basis; as I work for the feeds team we
keep everything in the feeds folder.
Now we are trying to take our frequently used module to create a sort of
library and for this we are trying to make it generic in nature.
So I created the structure as below and now I'm trying to import modules and
classes from lib but I'm getting error. Below is my dir structure. Can anyone
tell me what I'm doing wrong. Thanks for you help in advance
-- /u/user/qa-fo/bin/
|----- __init__.py
|----- pythonlib
|----- __init__.py
|----- linux_util.py
|----- feeds
|----- __init__.py
|----- test.py
linux_util.py -
#!/usr/local/bin/python
def test():
print "hello test from linux util"
test.py
#!/usr/local/bin/python
from bin.pythonlib.linux_util import test
print execute("date")
Here is the output on run
python feeds/test.py
Traceback (most recent call last):
File "feeds/test.py", line 6, in <module>
from bin.pythonlib.linux_util import test
ImportError: No module named bin.pythonlib.linux_util
Answer: You seem to be running this from inside the bin directory. So you'd need to
either have "/u/user/qa-fo/bin/" specifically on your PYTHONPATH, or just
import from pythonlib:
from pythonlib.linux_util import test
|
Python 2.7 : Remove elements from a multidimensional list
Question: Basically, I have a 3dimensional list (it is a list of tokens, where the first
dimension is for the text, second for the sentence, and third for the word).
Addressing an element in the list (lets call it mat) can be done for example:
mat[2][3][4]. That would give us the fifth word or the fourth sentence in the
third text.
But, some of the words are just symbols like '.' or ',' or '?'. I need to
remove all of them. I thought to do that with a procedure:
def removePunc(mat):
newMat = []
newText = []
newSentence = []
for text in mat:
for sentence in text:
for word in sentence:
if word not in " !@#$%^&*()-_+={}[]|\\:;'<>?,./\"":
newSentence.append(word)
newText.append(newSentence)
newMat.append(newText)
return newMat
Now, when I try to use that:
finalMat = removePunc(mat)
it is giving me the same list (mat is a 3 dimensional list). My idea was to
iterate over the list and remove only the 'words' which are actually
punctuation symbols.
I don't know what I am doing wrong but surely there is a simple logical
mistake.
Edit: I need to keep the structure of the array. So, words of the same
sentence should still be in the same sentence (just without the 'punctuation
symbol' words). Example:
a = [[['as', '.'], ['w', '?', '?']], [['asas', '23', '!'], ['h', ',', ',']]]
after the changes should be:
a = [[['as'], ['w']], [['asas', '23'], ['h']]]
Thanks for reading and/or giving me a reply.
Answer: I would suspect that your data are not organized as you think they are. And
although I am usually not the one to propose regular expressions, I think in
your case they may be among the best solutions. I would also suggest that
instead of eliminating non-alphabetic characters from words, you process
sentences
>>> import re
>>> non_word = re.compile(r'\W+') # If your sentences may
>>> sentence = '''The formatting sucks, but the only change that I've made to your code was shortening the "symbols" string to one character. The only issue that I can identify is either with the "symbols" string (though it looks like all chars in it are properly escaped) that you used, or the punctuation is not actually separate words'''
>>> words = re.split(non_word, sentence)
>>> words
['The', 'formatting', 'sucks', 'but', 'the', 'only', 'change', 'that', 'I', 've', 'made', 'to', 'your', 'code', 'was', 'shortening', 'the', 'symbols', 'string', 'to', 'one', 'character', 'The', 'only', 'issue', 'that', 'I', 'can', 'identify', 'is', 'either', 'with', 'the', 'symbols', 'string', 'though', 'it', 'looks', 'like', 'all', 'chars', 'in', 'it', 'are', 'properly', 'escaped', 'that', 'you', 'used', 'or', 'the', 'punctuation', 'is', 'not', 'actually', 'separate', 'words']
>>>
|
xlrd error message
Question: I'm trying to use `xlrd` to manipulate an `.xls` file as follows:
>>> import xlrd
>>> workbook = xlrd.open_workbook('6h.xls')
And I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/wayne-szalinsky/virt_env/virt_env/virt2/local/lib/python2.7/site-packages/xlrd/__init__.py", line 435, in open_workbook
ragged_rows=ragged_rows,
File "/home/wayne-szalinsky/virt_env/virt_env/virt2/local/lib/python2.7/site-packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/home/wayne-szalinsky/virt_env/virt_env/virt2/local/lib/python2.7/site-packages/xlrd/book.py", line 1230, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/home/wayne-szalinsky/virt_env/virt_env/virt2/local/lib/python2.7/site-packages/xlrd/book.py", line 1224, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '<?xml ve'
Answer: Your file is apparently an XML file with an incorrect filename extension of
`.xls`. If you wish to open it as an Excel file, it must first be saved as an
Excel file, not just named like one.
You might be able to open it in a text editor, observe how the XML document is
laid out, and write your code to parse the XML instead of using xlrd.
|
Passing a list of randomForest objects back to R with rpy2
Question: I am trying to combine a number of random forest models using rpy2. The
`combine` command in R looks fairly straight forward but I am not sure how to
pass the RF objects from python to R.
Simple example:
import pandas as pd
import numpy as np
import sys
if sys.version_info[0] < 3:
from string import lowercase
else:
from string import ascii_lowercase as lowercase
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r = robjects.r
r.library("randomForest")
df = pd.DataFrame(data=np.random.random(size=(100, 10)), columns=[a for a in lowercase[:10]])
cols = df.columns
RF = []
for _ in range(5):
df['train'] = np.random.random(size=100) < .75
rf = r.randomForest(robjects.Formula('a~.'), data=df[df.train][cols])
RF.append(rf)
When I try and `combine` RF models in R
RFall = r.combine(RF)
Returns the error:
Error in (function (...) :
Argument must be a list of randomForest objects
I have looked at other functions in `robjects` but can't find the one that
will do it.
Answer: The error message is originating from R, there the list expected is an R list.
Try using:
RFl = robjects.vectors.ListVector([('X%i' % i, x) for i, x in enumerate(RF)])
**edit:** the constructor for ListVector wants names for the list elements
** 2nd edit:** However, the real path to a solution is to notice that you were
not calling `combine()` correctly and the error message returned when calling
`combine()` is quite misleading. What you want(ed) is
RFall = r.combine(*RF)
|
How to use vcvarsall.bat in Python for NMake
Question: I'm trying to make a python script to make some generation of MakeFile with
CMake. I'm newbie in Python and just know the basic.
My script runs well but I can't use following command `"cmake
-DCMAKE_BUILD_TYPE=Debug -G"NMake Makefiles" ..\\..\\graphics"` because it
says :
> cmake must be run from a shell that can use the compiler cl from the command
> line.
I know the issue and normally I use call (`C:\Program Files (x86)\Microsoft
Visual Studio 12.0\VC\vcvarsall.bat`) and that's working. How I can reproduce
that in Python ?
Here is my script.py :
from os import *
from subprocess import *
path = "C:\\Users\\mea\\Documents\\repos\\corealpi\\cmake\\graphics_nmake"
chdir(path)
info = getcwd()
print(info)
call("C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\vcvarsall.bat")
system('cmake -DCMAKE_BUILD_TYPE=Debug -G"NMake Makefiles" ..\\..\\graphics')
system("pause")
path = "C:\\Users\\mea\\Documents\\repos\\corealpi\\cmake\\graphics_nmake"
chdir(path)
print (getcwd())
system('ls')
I have had some command path to verify I'm under the good directory.
Thanks for help.
Answer: You have a few options;
* You can change your system path to include the path exposed by `vcvars.bat`
* You can edit your shell's path initialization and add the paths you need
I usually do the first one so that I can also use the commands from a regular
windows CMD shell.
|
CertificateError: hostname doesn't match
Question: I'm using a proxy (behind corporate firewall), to login to an https domain.
The SSL handshake doesn't seem to be going well:
CertificateError: hostname 'ats.finra.org:443' doesn't match 'ats.finra.org'
I'm using Python 2.7.9 - Mechanize and I've gotten past all of the login,
password, security questioon screens, but it is getting hung up on the
certification.
Any help would be amazing. I've tried the monkeywrench found here: [Forcing
Mechanize to use SSLv3](http://stackoverflow.com/questions/17927339/forcing-
mechanize-to-use-sslv3)
Doesn't work for my code though.
If you want the code file I'd be happy to send.
Answer: This bug in ssl.math_hostname appears in v2.7.9 (it's not in 2.7.5), and has
to do with not stripping out the hostname from the hostname:port syntax. The
following rewrite of ssl.match_hostname fixes the bug. Put this before your
mechanize code:
import functools, re, urlparse
import ssl
old_match_hostname = ssl.match_hostname
@functools.wraps(old_match_hostname)
def match_hostname_bugfix_ssl_py_2_7_9(cert, hostname):
m = re.search(r':\d+$',hostname) # hostname:port
if m is not None:
o = urlparse.urlparse('https://' + hostname)
hostname = o.hostname
old_match_hostname(cert, hostname)
ssl.match_hostname = match_hostname_bugfix_ssl_py_2_7_9
The following mechanize code should now work:
import mechanize
import cookielib
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hang on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-Agent', 'Nutscrape 1.0')]
# Use this proxy
br.set_proxies({"http": "localhost:3128", "https": "localhost:3128"})
r = br.open('https://www.duckduckgo.com:443/')
html = br.response().read()
# Examine the html response from a browser
f = open('foo.html','w')
f.write(html)
f.close()
|
Trying to install virtualenvwrapperwith pip3
Question: I am working to set up a django project on ec2 with an Ubuntu 14.4 LTS
instance. I want to write my code using python 3 and django. I've been advised
that the best way to do this is to use virtualenvwrapper. I tried:
ubuntu:~$ sudo pip3 install virtualenvwrapper
Successfully uninstalled six
Successfully installed virtualenvwrapper virtualenv virtualenv-clone stevedore argparse pbr six
Cleaning up...
ubuntu:~$ mkvirtualenv env1
mkvirtualenv: command not found
What am I doing wrong?
edit:
I followed your directions, logged out and logged back in:
/usr/bin/python: No module named virtualenvwrapper
virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
set properly.
I'm suspecting that this is because I'm installing to python3 which is not the
default python interpreter
Answer: [From the
documentation](https://virtualenvwrapper.readthedocs.org/en/latest/install.html#shell-
startup-file)
> **Shell Startup File**
>
> Add three lines to your shell startup file (`.bashrc`, `.profile`, etc.) to
> set the location where the virtual environments should live, the location of
> your development project directories, and the location of the script
> installed with this package:
>
>
> export WORKON_HOME=$HOME/.virtualenvs
> export PROJECT_HOME=$HOME/Devel
> source /usr/local/bin/virtualenvwrapper.sh
>
In particular, sourcing the shell script above will allow you to run all of
the virtualenvwrapper commands.
|
Job scheduling for data scraping on Python
Question: I'm scraping (extracting) data from a certain website. The data contains two
values that I need, namely **(grid) frequency value** and **time**.
The data on the website is being updated every second. I'd like to
continuously save these values (append them) into a list or a tuple using
python. To do that I tried using _schedule_ library. The following job
schedule commands run the data scraping function (socket_freq) every second.
import schedule
schedule.every(1).seconds.do(socket_freq)
while True:
schedule.run_pending()
I'm facing two problems:
1. I don't know how to restrict the schedule to run during a chosen time interval. For example, i'd like to run it for 5 or 10 minutes. how do I define that? I mean how to I tell the schedule to stop after a certain time.
2. if I run this code and stop it after few seconds (using break), then I often get multiple entries, for example here is one result, where the first list[ ] in the tuple refers to the time value and the second list[ ] is the values of frequency:
out:
(['19:27:02','19:27:02','19:27:02','19:27:03','19:27:03','19:27:03','19:27:03','19:27:03','19:27:03','19:27:03','19:27:04','19:27:04','19:27:04', ...],
['50.020','50.020','50.020','50.018','50.018','50.018','50.018','50.018','50.018','50.018','50.017','50.017','50.017'...])
As you can see, the time variable is entered (appended) multiple times,
although I used a schedule that runs every 1 second. What i'd actually would
expect to retrieve is:
out:
(['19:27:02','19:27:03','19:27:04'],['50.020','50.018','50.017'])
Does anybody know how to solve these problems?
Thanks!
(I'm using python 2.7.9)
Answer: Ok, so here's how I would tackle these problems:
1. Try to obtain a timestamp at the start of your program and then simply check if it has been working long enough each time you execute piece of code you are scheduling.
2. Use [time.sleep()](https://docs.python.org/2/library/time.html?highlight=time.sleep#time.sleep) to put your program to sleep for a period of time.
Check my example below:
import schedule
import datetime
import time
# Obtain current time
start = datetime.datetime.now()
# Simple callable for example
class DummyClock:
def __call__(self):
print datetime.datetime.now()
schedule.every(1).seconds.do(DummyClock())
while True:
schedule.run_pending()
# 5 minutes == 300 seconds
if (datetime.datetime.now() - start).seconds >= 300:
break
# And here we halt execution for a second
time.sleep(1)
All refactoring is welcome
|
replace headers in csv file and writing selected columns using python 2.7
Question: On a weekly basis, I need to replace the header in a csv file (that has a date
dependent name) and delete two of the columns. I though the easiest way would
be to write a new csv file with the pertinent information(i.e. without columns
k and l). This is how my code looks like:
import csv
import calendar
import datetime
from datetime import date, timedelta
today = date.today()
tuesday = date.today() - timedelta(3)
p = tuesday.strftime('%Y%m%d')
us_csv = 'E:/' + "TEST_us_" + p + ".csv"
HIn = "a, b, c, d, e, f, g, h, k, l"
HOut = "A, B, C, D, E, F, G, H"
fIn= open ('us_csv', 'r')
HeaderIn = fIn.readline()
HeaderOut = HeaderIn.replace(HIn, HOut, 1)
fOut = open ('E:/Abase/usStats.csv', 'w')
fOut.write(HeaderOut + '\n')
for line in fIn
fOut.write(line)
fOut.close
The new csv is empty. I read most of the similar questions, but I simply can't
figure out how to do this. Any help would be greatly appreciated. Thank you.
Answer: This works for me. I like to use `writelines` so I can do all the writing at
once. It might be possible that you were running into trouble because you had
two files open. I'm not sure. To be safe I always open and close files
immediately using a block as shown.
This might not be necessary, but I tend to split up the rows into lists of
values so I can do the manipulations I need. I'm using the csv module to this
for me. You can see here I used list splicing to remove the last two columns
of each row. Then I join them back together.
import os
import argparse
import operator
import csv
def main():
p = argparse.ArgumentParser (description="Removes last two columns and renames headers.")
p.add_argument("origfile", help="Path of original file")
p.add_argument("newfile", help="Path of new file.")
args = p.parse_args()
with open(args.origfile) as f:
raw_rows = f.read().splitlines()
new_header_row = "A,B,C,D,E,F,G,H\n" # Don't put spaces
# for easier manipulation I like to split the row into a list values
# then rejoin them later after I've changed or removed what I needed
rows = csv.reader(raw_rows)
newfile_lines = [new_header_row]
newfile_lines.extend(",".join(row[:-2]) + "\n" for row in rows)
with open(args.newfile, 'w') as f:
f.writelines(newfile_lines)
if __name__ == '__main__':
main()
I ran this on:
a,b,c,d,e,f,g,h,i,j
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
And got:
A,B,C,D,E,F,G,H
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
|
Python relative import of an importable module not working
Question: I need to use the function MyFormatIO which is a part of the neo library. I
can successfully import neo and neo.io BUT I cannot use the MyFormatIO
function. `import neo.io` doesn't spit out any errors but `from neo.io import
MyFormatIO` returns `NameError: name 'MyFormatIO' is not defined`. How can
this be if MyFormatIO is a part of neo.io? I am running python2.7 on CentOS.
Answer: MyFormatIO is not a class in neo.io.
<http://pythonhosted.org/neo/io.html#module-neo.io>
> One format = one class
>
> The basic syntax is as follows. If you want to load a file format that is
> implemented in a generic MyFormatIO class:
>
>> > > from neo.io import MyFormatIO reader = MyFormatIO(filename =
"myfile.dat")
>
> you can replace MyFormatIO by any implemented class, see List of implemented
> formats
You have to replace 'MyFormatIO' with a class from this list:
<http://pythonhosted.org/neo/io.html#list-of-io>
A quick way to check this kind of thing in the interpreter is with dir.
import neo.io
dir(neo.io)
Those are the items that you can import or use from neo.io
|
How to get read excel data into an array with python
Question: In the lab that I work in, we process a lot of data produced by a 96 well
plate reader. I'm trying to speed up the process by writing a script that will
calculate the percent cytotoxicity from light absorbance (the easy part :])
and output a bar graph using matplotlib.
The problem is that the plate reader outputs data into a .xls file. I
understand that some modules like pandas have a read_excel function, can you
explain how I should go about reading the excel file and putting it into a 2D
array (matrix)?
Thanks
Data sample of a 24 well plate (for simplicity):
0.0868 0.0910 0.0912 0.0929 0.1082 0.1350
0.0466 0.0499 0.0367 0.0445 0.0480 0.0615
0.6998 0.8476 0.9605 0.0429 1.1092 0.0644
0.0970 0.0931 0.1090 0.1002 0.1265 0.1455
Answer: I'm not exactly sure what you mean when you say array, but if you mean into a
matrix, might you be looking for:
import pandas as pd
df = pd.read_excel([path here])
df.as_matrix()
This returns a numpy.ndarray type.
|
datetime.now in python different when running locally and on server
Question: I am using Heroku to run some python code.
The code that i have written uses a predefined time like example: **16:00**
and compares that with the current time and the calculates the difference like
this:
now = datetime.datetime.now()
starttime = datetime.datetime.combine(datetime.date.today(), datetime.time(int(hour), int(minute)))
dif = now - starttime
Running this locally ofc uses the time in my system i guess and everything is
correct. However when i post it on the server and run it there the time is one
hour back. So how can i fix this so it always uses the timezone that i am in?
I live in Sweden
Thank you all, Code examples would be deeply appreciated.
**EDIT1**
Rest of the code looks like this:
if dif < datetime.timedelta(seconds=0):
hmm = 3
elif dif < datetime.timedelta(seconds=45*60):
t = dif.total_seconds() / 60
time, trash = str(t).split(".")
time = time+"'"
elif dif < datetime.timedelta(seconds=48*60):
time = "45'"
elif dif < datetime.timedelta(seconds=58*60):
time = "HT"
elif dif < datetime.timedelta(seconds=103*60):
t = (dif.total_seconds() - 840) / 60
time, trash = str(t).split(".")
time = time+"'"
elif dif < datetime.timedelta(seconds=108*60):
time = "90'"
else:
time = "FT"
and using the imports that you provided i get this error now:
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
i tried to do like this but it did not help:
from datetime import datetime, time, timedelta
Answer: > So how can i fix this so it always uses the timezone that i am in?
Find your timezone in the tz database e.g., using [`tzlocal`
module](https://pypi.python.org/pypi/tzlocal). Run _on your local machine_ :
#!/usr/bin/env python
import tzlocal # $ pip install tzlocal
print(tzlocal.get_localzone().zone)
If `tzlocal` has been capable to get the timezone id then you should see
something like: `Europe/Paris`. Pass this string to the server.
_On the server_ :
#!/usr/bin/env python
from datetime import datetime, time
import pytz # $ pip install pytz
tz = pytz.timezone('Europe/Paris') # <- put your local timezone here
now = datetime.now(tz) # the current time in your local timezone
naive_starttime = datetime.combine(now, time(int(hour), int(minute)))
starttime = tz.localize(naive_starttime, is_dst=None) # make it aware
dif = now - starttime
|
py2neo: py2neo.packages.httpstream.http.SocketError: timed out - execute, stream or Transactions?
Question: First of all. I'm sorry if this is not complicity structured. I'm just not
sure where to start or end, but did my best to give you as many information as
possible.
I work on a AWS M3.large, py2neo 2.0.4 and neo4j-community-2.1.7
I am trying to import a large dataset into neo4j using py2neo. My problem is,
when I have read in around 150k, it just give me a:
`py2neo.packages.httpstream.http.SocketError: timed out`
I need to go up in the millions of inputs, so 150k should just work.
Whole error:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 322, in submit
response = send()
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 318, in send
return http.getresponse(**getresponse_args)
File "/usr/lib/python3.4/http/client.py", line 1147, in getresponse
response.begin()
File "/usr/lib/python3.4/http/client.py", line 351, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.4/http/client.py", line 313, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.4/socket.py", line 371, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 331, in submit
response = send("timeout")
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 318, in send
return http.getresponse(**getresponse_args)
File "/usr/lib/python3.4/http/client.py", line 1147, in getresponse
response.begin()
File "/usr/lib/python3.4/http/client.py", line 351, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.4/http/client.py", line 313, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.4/socket.py", line 371, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "transactions.py", line 221, in <module>
read_zip("data")
File "transactions.py", line 44, in read_zip
create_tweets(lines)
File "transactions.py", line 215, in create_tweets
tx.process()
File "/usr/local/lib/python3.4/dist-packages/py2neo/cypher/core.py", line 296, in process
return self.post(self.__execute or self.__begin)
File "/usr/local/lib/python3.4/dist-packages/py2neo/cypher/core.py", line 248, in post
rs = resource.post({"statements": self.statements})
File "/usr/local/lib/python3.4/dist-packages/py2neo/core.py", line 322, in post
response = self.__base.post(body, headers, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 984, in post
return rq.submit(**kwargs)
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 433, in submit
http, rs = submit(self.method, uri, self.body, self.headers)
File "/usr/local/lib/python3.4/dist-packages/py2neo/packages/httpstream/http.py", line 362, in submit
raise SocketError(code, description, host_port=uri.host_port)
py2neo.packages.httpstream.http.SocketError: timed out
Right now I use cypher. I write in batches of ~1000, but smaller batches don't
work either. My question, can I use something else to make it faster?
Right now, I do:
stagement = "match (p:person {id=123}) ON CREATE SET p.age = 132"
def add_names(names):
for-loop with batches of 1000:
tx = graph.cypher.begin()
for name in names:
tx.append(statement, {"N": name})
tx.process()
tx.commit()
But would it be better to use execute or stream, or anything else I can do to
make it work?
Useful link:
* [Neo4J / py2neo -- cursor-based query?](http://stackoverflow.com/questions/28559409/neo4j-py2neo-cursor-based-query)
Answer: Try adding
`from py2neo.packages.httpstream import http http.socket_timeout = 9999`
|
How to insert unescaped html fragment in Beautiful Soup 4
Question: I have to parse some nasty government created html
(<http://www.spokanecounty.org/detentionservices/inmateroster/detail2.aspx?sysid=84060>)
and to ease my pain I would like to insert some html fragments into the
document to wrap some content into more easily digested chunks.
BS4, however, escapes the html string fragment I'm trying to insert (`<div
class="case">`) and turns it into this:
<div class="case">
The relevant html I'm parsing is this:
<div style='float:left; width:100%;border-top:solid 1px #666;height:5px;'>
</div>
<div style='width:45%; float:left;'>
<h2 style='margin-top:0px;' rel=121018261>Case Number: 121018261</h2>
</div>
<div style='width:45%;float:right; text-align:right;'>
<div>Added: 10/22/2012</div>
</div>
<div style='width:100%;clear:both;'>
<b>Case Bond:</b> $2,000,000.00 <b style='margin-left:10px;'>Set By:</b> Spokane County Superior Court
</div>
<table class='bookinfo 121018261' style='width:100%;'>
<tr><td><b>Charge 1 <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=' target='_blank'>RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG <br /> <b>Report Number:</b> 120160423 <b style='margin-left:10px;'>Report Agency:</b> 002 - SPOKANE CITY</td></tr>
<tr><td><b>Charge 2 <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=' target='_blank'>RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG<br /><b>Report Number:</b> 120160423<b style='margin-left:10px;'>Report Agency:</b> 002 - SPOKANE CITY</td></tr>
</table>
<div style='float:left; width:100%;border-top:solid 1px #666;height:5px;'>
</div>
<div style='width:45%; float:left;'>
<h2 style='margin-top:0px;' rel=121037010>Case Number: 121037010</h2>
</div>
<div style='width:45%;float:right; text-align:right;'>
<div>Added: 10/21/2012</div>
</div>
<div style='width:100%;clear:both;'>
<b>Case Bond:</b> $150,000.00 <b style='margin-left:10px;'>Set By:</b> Spokane County Superior Court
</div>
<table class='bookinfo 121037010' style='width:100%;'>
<tr><td><b>Charge 1 <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=9A.44.050' target='_blank'>RCW: 9A.44.050(1)(A)</a>:</b> RAPE-2ND(FORCIBLE) <br /> <b>Report Number:</b> 120345597 <b style='margin-left:10px;'>Report Agency:</b> 001 - SPOKANE COUNTY</td></tr>
</table>
The Python code looks like this:
case_top = soup.find_all(style=re.compile("border-top:solid 1px #666"))
for c in case_top:
c.insert_before(soup.new_string('<div class="case">'))
case_bottom = soup.find_all("table", class_="bookinfo")
for c in case_bottom:
c.insert_after(soup.new_string('</div'))
The results look like this:
<div class="case"><div style="float:left; width:100%;border-top:solid 1px #666;height:5px;"> </div><div style="width:45%; float:left;"><h2 rel="121018261" style="margin-top:0px;">Case Number: 121018261</h2></div><div style="width:45%;float:right; text-align:right;"><div>Added: 10/22/2012</div></div><div style="width:100%;clear:both;"><b>Case Bond:</b> $2,000,000.00 <b style="margin-left:10px;">Set By:</b> Spokane County Superior Court</div><table class="bookinfo 121018261" style="width:100%;"><tr><td><b>Charge 1 <a href="http://apps.leg.wa.gov/rcw/default.aspx?cite=" target="_blank">RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG<br/><b>Report Number:</b> 120160423 <b style="margin-left:10px;">Report Agency:</b> 002 - SPOKANE CITY</td></tr><tr><td><b>Charge 2 <a href="http://apps.leg.wa.gov/rcw/default.aspx?cite=" target="_blank">RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG<br/><b>Report Number:</b> 120160423 <b style="margin-left:10px;">Report Agency:</b> 002 - SPOKANE CITY</td></tr></table></div><div class="case"><div style="float:left; width:100%;border-top:solid 1px #666;height:5px;"> </div><div style="width:45%; float:left;"><h2 rel="121037010" style="margin-top:0px;">Case Number: 121037010</h2></div><div style="width:45%;float:right; text-align:right;"><div>Added: 10/21/2012</div></div><div style="width:100%;clear:both;"><b>Case Bond:</b> $150,000.00 <b style="margin-left:10px;">Set By:</b> Spokane County Superior Court</div><table class="bookinfo 121037010" style="width:100%;"><tr><td><b>Charge 1 <a href="http://apps.leg.wa.gov/rcw/default.aspx?cite=9A.44.050" target="_blank">RCW: 9A.44.050(1)(A)</a>:</b> RAPE-2ND(FORCIBLE)<br/><b>Report Number:</b> 120345597 <b style="margin-left:10px;">Report Agency:</b> 001 - SPOKANE COUNTY</td></tr></table></div>
The question is then, how can I insert an unescaped html fragment into the
document?
Answer: You are telling BeautifulSoup to insert **string data** :
c.insert_before(soup.new_string('<div class="case">'))
Anything not safe for HTML string data will then indeed be escaped. You
instead want to insert a _tag object_ :
c.insert_before(soup.new_tag('div', **{'class': 'case'}))
This creates a new child element, which does not actually wrap anything.
If you wanted to wrap each individual element in that are, you'd use the
[`Element.wrap()`
method](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#wrap):
c.wrap(soup.new_tag('div', **{'class': 'case'}))
but this only works on one tag at a time.
For wrapping a _series_ of tags, the only thing that'll do is _moving_ the
tags over; inserting tags that were located in one place into another
effectively moves them over:
case_top = soup.find_all(style=re.compile("border-top:solid 1px #666"))
for case in case_top:
wrapper = soup.new_tag('div', **{'class': 'case'})
case.insert_before(wrapper)
while wrapper.next_sibling:
wrapper.append(wrapper.next_sibling)
if wrapper.find('table', class_='bookinfo'):
# moved over the bookinfo table, time to stop
break
This then moves everything from the `case_top` element all the way to the
`<table class="bookinfo">` element into the new `<div class="case">` element.
Demo:
>>> from bs4 import BeautifulSoup
>>> import re
>>> sample = '''\
... <body>
... <div style='float:left; width:100%;border-top:solid 1px #666;height:5px;'>
...
... </div>
... <div style='width:45%; float:left;'>
... <h2 style='margin-top:0px;' rel=121018261>Case Number: 121018261</h2>
... </div>
... <div style='width:45%;float:right; text-align:right;'>
... <div>Added: 10/22/2012</div>
... </div>
... <div style='width:100%;clear:both;'>
... <b>Case Bond:</b> $2,000,000.00 <b style='margin-left:10px;'>Set By:</b> Spokane County Superior Court
... </div>
... <table class='bookinfo 121018261' style='width:100%;'>
... <tr><td><b>Charge 1 <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=' target='_blank'>RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG <br /> <b>Report Number:</b> 120160423 <b style='margin-left:10px;'>Report Agency:</b> 002 - SPOKANE CITY</td></tr>
... <tr><td><b>Charge 2 <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=' target='_blank'>RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG<br /><b>Report Number:</b> 120160423<b style='margin-left:10px;'>Report Agency:</b> 002 - SPOKANE CITY</td></tr>
... </table>
...
... <div style='float:left; width:100%;border-top:solid 1px #666;height:5px;'>
...
... </div>
... <div style='width:45%; float:left;'>
... <h2 style='margin-top:0px;' rel=121037010>Case Number: 121037010</h2>
... </div>
... <div style='width:45%;float:right; text-align:right;'>
... <div>Added: 10/21/2012</div>
... </div>
... <div style='width:100%;clear:both;'>
... <b>Case Bond:</b> $150,000.00 <b style='margin-left:10px;'>Set By:</b> Spokane County Superior Court
... </div>
... <table class='bookinfo 121037010' style='width:100%;'>
... <tr><td><b>Charge 1 <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=9A.44.050' target='_blank'>RCW: 9A.44.050(1)(A)</a>:</b> RAPE-2ND(FORCIBLE) <br /> <b>Report Number:</b> 120345597 <b style='margin-left:10px;'>Report Agency:</b> 001 - SPOKANE COUNTY</td></tr>
... </table>
... </body>
... '''
>>> soup = BeautifulSoup(sample)
>>> case_top = soup.find_all(style=re.compile("border-top:solid 1px #666"))
>>> for case in case_top:
... wrapper = soup.new_tag('div', **{'class': 'case'})
... case.insert_before(wrapper)
... while wrapper.next_sibling:
... wrapper.append(wrapper.next_sibling)
... if wrapper.find('table', class_='bookinfo'):
... # moved over the bookinfo table, time to stop
... break
...
>>> soup.body
<body><div class="case"><div style="float:left; width:100%;border-top:solid 1px #666;height:5px;">
</div>
<div style="width:45%; float:left;">
<h2 rel="121018261" style="margin-top:0px;">Case Number: 121018261</h2>
</div>
<div style="width:45%;float:right; text-align:right;">
<div>Added: 10/22/2012</div>
</div>
<div style="width:100%;clear:both;">
<b>Case Bond:</b> $2,000,000.00 <b style="margin-left:10px;">Set By:</b> Spokane County Superior Court
</div>
<table class="bookinfo 121018261" style="width:100%;">
<tr><td><b>Charge 1 <a href="http://apps.leg.wa.gov/rcw/default.aspx?cite=" target="_blank">RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG <br/> <b>Report Number:</b> 120160423 <b style="margin-left:10px;">Report Agency:</b> 002 - SPOKANE CITY</td></tr>
<tr><td><b>Charge 2 <a href="http://apps.leg.wa.gov/rcw/default.aspx?cite=" target="_blank">RCW: 9A.56.210</a>:</b> ROBBERY-2ND DEG<br/><b>Report Number:</b> 120160423<b style="margin-left:10px;">Report Agency:</b> 002 - SPOKANE CITY</td></tr>
</table></div>
<div class="case"><div style="float:left; width:100%;border-top:solid 1px #666;height:5px;">
</div>
<div style="width:45%; float:left;">
<h2 rel="121037010" style="margin-top:0px;">Case Number: 121037010</h2>
</div>
<div style="width:45%;float:right; text-align:right;">
<div>Added: 10/21/2012</div>
</div>
<div style="width:100%;clear:both;">
<b>Case Bond:</b> $150,000.00 <b style="margin-left:10px;">Set By:</b> Spokane County Superior Court
</div>
<table class="bookinfo 121037010" style="width:100%;">
<tr><td><b>Charge 1 <a href="http://apps.leg.wa.gov/rcw/default.aspx?cite=9A.44.050" target="_blank">RCW: 9A.44.050(1)(A)</a>:</b> RAPE-2ND(FORCIBLE) <br/> <b>Report Number:</b> 120345597 <b style="margin-left:10px;">Report Agency:</b> 001 - SPOKANE COUNTY</td></tr>
</table></div>
</body>
|
How to decompress zip files across a Windows folder in Python
Question: I have a large folder having 900+ sub-folders, each of which has another
folder inside it which in turn has a zipped file. Its like -
-MyFolder
\-----MySubfolder
\---------MySubSubfolder
\-------------MyFile.zip
How can I decompress all the zipped files in their respective folder OR in a
separate folder elsewhere in Windows using Python?
Any help would be great!!
Answer: You could try something like:
import zipfile,os;
def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename) as zf:
for member in zf.infolist():
extract_allowed = True;
path = dest_dir;
words = member.filename.split('/');
for word in words:
if (word == '..'):
extract_allowed = False;
break;
if (extract_allowed == True):
zf.extract(member, dest_dir);
def unzipFiles(dest_dir):
for file in os.listdir(dest_dir):
if (os.path.isdir(dest_dir + '/' + file)):
return unzipFiles(dest_dir + '/' + file);
if file.endswith(".zip"):
print 'Found file: "' + file + '" in "' + dest_dir + '" - extracting';
unzip(dest_dir + '/' + file, dest_dir + '/');
unzipFiles('./MyFolder');
|
odeint from scipy.integrate in Python giving wrong result?
Question: I am trying to solve the ivp y'=-y-5 * exp(-t) * sin(5 t), y(0)=1, using the
following code:
%pylab inline
%matplotlib inline
from scipy.integrate import odeint
def mif(t, y):
return -y-5*exp(-t)*sin(5*t)
tspan = np.arange(0, 3, 0.000001)
y0 = 1.0
y_result = odeint(mif, y0, tspan)
y_result = y_result[:, 0] # convert the returned 2D array to a 1D array
plt.figure()
plt.plot(tspan, y_result)
plt.show()
However, the plot I get is wrong, it does not match what I obtain, say, with
Matlab or Mathematica. It is actually different from the following alternative
integration:
from scipy.integrate import ode
# initialize the 4th order Runge-Kutta solver
solver = ode(mif).set_integrator('dop853')
# initial value
y0 = 1.0
solver.set_initial_value(y0, 0)
values = 1000
t = np.linspace(0.0001, 3, values)
y = np.zeros(values)
for ii in range(values):
y[ii] = solver.integrate(t[ii])[0] #z[0]=u
which does yield correct result. What am I doing wrong with the odeint?
Answer: The function arguments change between ode and odeint. For odeint you need
def mif(y, t):
and for ode
def mif(t, y):
e.g.
%pylab inline
%matplotlib inline
from scipy.integrate import odeint
def mif(t,y):
return y
tspan = np.arange(0, 3, 0.000001)
y0 = 0.0
y_result = odeint(mif, y0, tspan)
plt.figure()
plt.plot(tspan, y_result)
plt.show()
and
from scipy.integrate import ode
def mif(y, t):
return y
# initialize the 4th order Runge-Kutta solver
solver = ode(mif).set_integrator('dop853')
# initial value
y0 = 0.000000
solver.set_initial_value([y0], 0.0)
values = 1000
t = np.linspace(0.0000001, 3, values)
y = np.zeros(values)
for ii in range(values):
y[ii] = solver.integrate(t[ii]) #z[0]=u
plt.figure()
plt.plot(t, y)
plt.show()
|
Load CSV file with Spark
Question: I'm new to Spark and I'm trying to read CSV data from a file with Spark.
Here's what I am doing :
sc.textFile('file.csv')
.map(lambda line: (line.split(',')[0], line.split(',')[1]))
.collect()
I would expect this call to give me a list of the two first columns of my file
but I'm getting this error :
File "<ipython-input-60-73ea98550983>", line 1, in <lambda>
IndexError: list index out of range
although my CSV file as more than one column.
Answer: **Spark 2.0.0+**
You can use csv data source directly:
spark.read.csv(
"some_input_file.csv", header=True, mode="DROPMALFORMED", schema=schema
)
**Spark < 2.0.0**:
Instead of manual parsing, which is far from trivial in a general case, I
would recommend [`spark-csv`](https://github.com/databricks/spark-csv):
Make sure that Spark CSV is included in the path (`--packages`, `--jars`,
`--driver-class-path`)
And load your data as follows:
(df = sqlContext
.read.format("com.databricks.spark.csv")
.option("header", "true")
.option("inferschema", "true")
.option("mode", "DROPMALFORMED")
.load("some_input_file.csv"))
It can handle loading, schema inference, dropping malformed lines and doesn't
require passing data from Python to the JVM.
If you know the schema, it is better to avoid schema inference and pass it to
`DataFrameReader`. Assuming you have three columns - integer, double and
string:
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
schema = StructType([
StructField("A", IntegerType()),
StructField("B", DoubleType()),
StructField("C", StringType())
])
(sqlContext
.read
.schema(schema)
.option("header", "true")
.option("mode", "DROPMALFORMED")
.load("some_input_file.csv"))
|
Displaying only the highest of a person's 3 most recent scores, saved in a .txt file
Question: I am trying to learn the fundamentals of using Python for a personal project.
I have created a program which asks the user ten geographical questions, and
then saves their score to a .txt file, in this format:
Imran - 8
Joeseph - 10
Test1 - 6
Test2 - 4
Joeseph - 5
Aaron - 4
Test1 - 1
Zzron - 1
Joeseph - 3
Test1 - 10
Joeseph - 4
I then created a new program, which can be used to display the highest score
of each person in alphabetical order:
with open("highscores.txt", "r+")as file:
file.seek(0)
scores = file.readlines()
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(' - ')
score = int(score)
if name not in user_scores or user_scores[name] < score:
user_scores[name] = score
for name in sorted(user_scores):
print(name, '-', user_scores[name])
I would like to alter this code, such that it only outputs the highest of a
person's 3 most recent scores. For example, from the .txt file given,
Joeseph's score would be displayed as:
Joeseph - 5
The program should omit all but the 3 most recent scores from each person.
Answer: This should do the trick
from collections import defaultdict, deque
with open("highscores.txt", "r+")as file:
file.seek(0)
scores = file.readlines()
user_scores = defaultdict(lambda:deque(maxlen=3))
for line in scores:
name, score = line.rstrip('\n').split(' - ')
score = int(score)
user_scores[name].append(score)
for name in user_scores:
print(name, '-', max(user_scores[name]))
By using defaultdict, we avoid ugly in checking. The deque keeps only the last
3 scores. Note this works even if the user has less than 3 scores.
If you need the high scores sorted, than the last loop can be replaced with:
user_scores=[(max(user_scores[user]), user) for user in user_scores]
for score, name in sorted(user_scores):
print(name, '-', score)
|
ImportError from different apps
Question: I am importing the models from different apps but I am getting this error and
I am not sure why this is occurring.
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Library/Python/2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Library/Python/2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/bli1/Development/Django/Spark/users/models.py", line 5, in <module>
from notifications.models import Notification
File "/Users/bli1/Development/Django/Spark/notifications/models.py", line 2, in <module>
from users.models import UserProfile
ImportError: cannot import name UserProfile
my notifications/models:
from django.db import models
from users.models import UserProfile
from restaurants.models import Restaurant
class Notification(models.Model):
user = models.ForeignKey(UserProfile)
name = models.CharField(max_length=100)
about = models.TextField(max_length=1024, blank=True)
restaurant = models.ForeignKey(Restaurant)
def __str__(self):
return self.name
my users/models.py:
from django.db import models
from django.contrib.auth.models import User
from notifications.models import Notification
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=1024, null=True, blank=True)
Answer: You are the victim of circular import dependency. In order to resolve this,
you need to tell Django the import path of the model in `ForeignKey` instead
of actually importing it:
class Notification(models.Model):
user = models.ForeignKey('users.UserProfile')
Also don't forget to delete import statement from `from users.models import
UserProfile` from _notifications/models.py_.
|
Print to an empty file in python 3
Question: can someone tell me why in python 3.4.2 when I try
import codecs
f = codecs.open('/home/filename', 'w', 'utf-8')
print ('something', file = f)
it gives me an empty file?
Previously it was working well, but only suddenly it stopped printing to file
Answer: File writing is buffered to avoid hitting the performance drain that is
writing to a disk. Flushing the buffer takes place when you reach a threshold,
flush explicitly or close the file.
You have not _closed_ the file, did not flush the buffer, and haven't written
enough to the file to auto-flush the buffer.
Do one of the following:
* Flush the buffer:
f.flush()
This can be done with the `flush` argument to `print()` as well:
print('something', file=f, flush=True)
but the argument requires Python 3.3 or newer.
* Close the file:
f.close()
or use the file as a context manager (using the `with` stamement):
with open('/home/filename', 'w', encoding='utf-8') as f:
print('something', file=f)
and the file will be closed automatically when the block is exited (on
completion, or an exception).
* Write more data to the file; how much depends on the buffering configuration.
|
Python/Django Calculate Expiration for Model
Question: I have been unsuccessfully trying to calculate an expiration hour/minute for a
Django model that I have. Here is the base code I am working with:
class Bribe(models.Model)
date_offered = models.DateTimeField()
def expiration(self):
[...]
return [Hours:Minutes until expiration]
My main goal is to calculate a countdown for how long a Bribe has until it
will expire, in this case 48 hours. For example, if a Bribe has a
`date_offered` value of `February 10th, 2015 @ 12:00PM`, I would like `def
expiration(self)` to return a string of `12 hours 10 minutes remaining until
expiration` if the current date is `February 11th 2015 @ 11:50PM`
If anyone can help me fill in what goes inside the function/method, I would
greatly appreciate it.
Answer: You can use the `timeuntil()` function which is used for the
[`timeuntil`](https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#timeuntil)
template filter:
from django.utils.timesince import timeuntil
def expiration(self):
return timeuntil(self.date_offered)
|
Tor Stem - To Russia With Love Connection Issues
Question: I am trying to get the [To Russia With Love
tutoial](https://stem.torproject.org/tutorials/to_russia_with_love.html) from
the Stem project working.
from io import StringIO
import socket
import urllib3
import time
import socks # SocksiPy module
import stem.process
from stem.util import term
SOCKS_PORT = 9150
# Set socks proxy and wrap the urllib module
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
socket.socket = socks.socksocket
# Perform DNS resolution through the socket
def getaddrinfo(*args):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo
def query(url):
"""
Uses urllib to fetch a site using SocksiPy for Tor over the SOCKS_PORT.
"""
try:
return urllib3.urlopen(url).read()
except:
return "Unable to reach %s" % url
# Start an instance of Tor configured to only exit through Russia. This prints
# Tor's bootstrap information as it starts. Note that this likely will not
# work if you have another Tor instance running.
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print (term.format(line, term.Color.BLUE))
print (term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
tor_cmd = "C:\Tor Browser\Browser\TorBrowser\Tor\\tor.exe", config = {
'SocksPort': str(SOCKS_PORT),
# 'ExitNodes': '{ru}',
},
init_msg_handler = print_bootstrap_lines,
)
print (term.format("\nChecking our endpoint:\n", term.Attr.BOLD))
print (term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE))
tor_process.kill() # stops tor
I have tweaked it a bit from the original to get it working with python 3.4
and I am also using pysocks instead of socksipy. I started with urllib instead
of urllib3 and I had the same issue. Currently I am getting:
C:\Python>python program1.py
←[1mStarting Tor:
←[0m
←[34mFeb 28 21:59:45.000 [notice] Bootstrapped 0%: Starting←[0m
←[34mFeb 28 21:59:45.000 [notice] Bootstrapped 5%: Connecting to directory server←[0m
←[34mFeb 28 21:59:45.000 [notice] Bootstrapped 80%: Connecting to the Tor network←[0m
←[34mFeb 28 21:59:45.000 [notice] Bootstrapped 85%: Finishing handshake with first hop←[0m
←[34mFeb 28 21:59:46.000 [notice] Bootstrapped 90%: Establishing a Tor circuit←[0m
←[34mFeb 28 21:59:47.000 [notice] Bootstrapped 100%: Done←[0m
←[1m
Checking our endpoint:
←[0m
←[34mUnable to reach https://www.atagar.com/echo.php←[0m
I have had similar code work outside of tor. I can connect my tor browser to
this site and I can browse to it with no problems. I have tried changing the
port numbers, but this is the one that is set up in Tor's proxy settings. One
thought I had is that this may be a timing issue. Is it possible that the code
is not waiting long enough to the site to respond?
Any help in getting this working would be greatly appreciated.
Answer: Here's a working version of [the stem
tutorial](https://stem.torproject.org/tutorials/to_russia_with_love.html) that
uses [`pysocks`](https://github.com/Anorov/PySocks) and its `sockshandler`
module to avoid monkey-patching the socket module:
#!/usr/bin/env python
"""
https://stem.torproject.org/tutorials/to_russia_with_love.html
Usage:
russian-tor-exit-node [<tor>] [--color] [--geoipfile=</path/to/file>]
russian-tor-exit-node -h | --help
russion-tor-exit-node --version
Dependencies:
- tor (packaged and standalone executables work)
- pip install stem
- pip install PySocks
- pip install docopt
: parse options
- pip install colorama
: cross-platform support for ANSI colors
- [optional] sudo apt-get tor-geoipdb
: if tor is bundled without geoip files; --geoipfile=/usr/share/tor/geoip
"""
import sys
from contextlib import closing
import colorama # $ pip install colorama
import docopt # $ pip install docopt
import socks # $ pip install PySocks
import stem.process # $ pip install stem
from sockshandler import SocksiPyHandler # see pysocks repository
from stem.util import term
try:
import urllib2
except ImportError: # Python 3
import urllib.request as urllib2
args = docopt.docopt(__doc__, version='0.2')
colorama.init(strip=not (sys.stdout.isatty() or args['--color']))
tor_cmd = args['<tor>'] or 'tor'
socks_port = 7000
config = dict(SocksPort=str(socks_port), ExitNodes='{ru}')
if args['--geoipfile']:
config.update(GeoIPFile=args['--geoipfile'], GeoIPv6File=args['--geoipfile']+'6')
def query(url, opener=urllib2.build_opener(
SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "localhost", socks_port))):
try:
with closing(opener.open(url)) as r:
return r.read().decode('ascii')
except EnvironmentError as e:
return "Unable to reach %s: %s" % (url, e)
# Start an instance of Tor configured to only exit through Russia. This prints
# Tor's bootstrap information as it starts. Note that this likely will not
# work if you have another Tor instance running.
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print(term.format(line, term.Color.BLUE))
else:
print(line)
print(term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
tor_cmd=tor_cmd,
config=config,
init_msg_handler=print_bootstrap_lines,
)
try:
print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD))
print(term.format(query("https://icanhazip.com"), term.Color.BLUE))
finally:
if tor_process.poll() is None: # still running
tor_process.terminate() # stops tor
tor_process.wait()
It works on both Python 2 and 3 on my Ubuntu machine.
`strace` shows data and dns requests are made via the tor proxy.
|
PyQt5 focusIN/Out events
Question: I am using Python 3.4 and Qt 5 for the first time. It's easy and I can
understand most of functionality which I need. But (there is always "but") I
don't understand how to use `focusOut`/`clearFocus`/`focusIn` events.
Am I right that old way:
QObject.connect(self.someWidget, QtCore.SIGNAL('focusOutEvent()'), self.myProcedure)
...does not work in Qt5?
I tried to understand
[this](http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html)
unsuccessfully. I'll be very thankful for a short example how to catch an
event when e.g some of many `QLineEdit` has lost focus.
Answer: The issue here is that `focusInEvent`/`clearFocus`/`focusOutEvent` are _not_
signals, they are _event handlers_. See for example [here](http://qt-
project.org/doc/qt-4.8/qwidget.html#focusInEvent). If you want to catch these
events you will need to re-implement the event handler on your object, for
example by subclassing QLineEdit.
class MyQLineEdit(QLineEdit):
def focusInEvent(self, e):
# Do something with the event here
super(MyQLineEdit, self).focusInEvent(e) # Do the default action on the parent class QLineEdit
In PyQt5 the syntax for signals themselves is considerably simpler. Taking for
example the `textEdited` signal from QLineEdit, you can use that as follows:
self.someWidget.textEdited.connect( self.myProcedure )
This will connect your `self.myProcedure` function to the `textEdited` signal.
The target function will need to accept the event outputs, for example:
void textEdited ( const QString & text )
So you could define your `self.myProcedure` in your class as follows and it
will receive the `QString` sent by that event:
def myProcedure(self, t):
# Do something with the QString (text) object here
You can also define custom events as follows:
from PyQt5.QtCore import QObject, pyqtSignal
class Foo(QObject):
an_event = pyqtSignal()
a_number = pyqtSignal(int)
In each of these cases `pyqtSignal` is used to define a property of the `Foo`
class which you can connect to like any other signal. So for example to handle
the above we could create:
def an_event_handler(self):
# We receive nothing here
def a_number_handler(self, i):
# We receive the int
You could then `connect()` and `emit()` the events as follows:
self.an_event.connect( self.an_event_handler )
self.a_number.connect( self.a_number_handler )
self.an_event.emit() # Send the event and nothing else.
self.a_number.emit(1) # Send the event an an int.
The link you posted gives [more information on custom
events](http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html), signal
naming and overloading with the new syntax.
|
Making Python game server sockets visible for outside world?
Question: How can i connect by my 80.xxx.xxx.xxx ip (from internet)
My ports are enabled but the game client just dont see any server on
80.xxx.xxx.xxx ip i think the problem is in the server code.
Note: The game client-server connection works perfect on LAN but not over the
internet.
Server:
import _thread as thread
import socket
import time
import pickle
import ipaddress
clients = {}
clientInfo = {}
connections = {}
def startServer(nPort):
IP = '192.168.0.10'
port = nPort
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSocket.bind((IP,port))
serverSocket.setblocking(0)
print("Server connected "+str(IP)+" port "+str(port))
return serverSocket
addSocketTransport
def runServer(server):
recv(server)
def recv(server):
end = time.time()
start = time.time()
ping = 0
r = ""
global clients
server.settimeout(0)
while(True):
for i in range(0,len(clients)+1):
try:
(r,address) = server.recvfrom(9293)
r = pickle.loads(r)
if address not in clients:
addClient(address)
clients[address] = r
ping = round((time.time()-start)*1000,3)
start = time.time()
clientInfo[address]['lastPing'] = time.time()
clientInfo[address]['ping'] = ping
clientInfo[address]['timeout'] = 0.0
except:
pass
for c in clients:
client = clientInfo[c]
client['timeout'] = round(float(time.time()-client['lastPing'])*1000,3)
if client['timeout'] > 5000:
print("the client timed out")
disconnectClient(c)
break
print("follow broke")
def send(clientSocket):
global clients
while(True):
time.sleep(.05)
for address in clients:
client = clients[address]
clientSocket.sendto(pickle.dumps(clients),address)
def addClient(address):
print(str("client add"))
clients[address] = {}
clientInfo[address] = {}
clientInfo[address]['timeout'] = 0.0
clientInfo[address]['lastPing'] = time.time()
print(str("clients:")+str(clients))
def disconnectClient(address):
print(str("disconnect ")+str(address))
del clients[address]
print("client disconnected")
go = False
print("What port should be used (Press enter for default 9293 port)")
while go == False:
port = input("Port: ")
try:
port = int(port)
if port >= 1024:
go = True
else:
print("the port might be bigger than 1024")
except:
pass
if port == "":
port = 9293
print("the gateway port 9293")
go = True
#thread.start_new_thread( print, ("Thread-2","Hello") )
try:
serverSocket = startServer(port)
thread.start_new_thread( recv, (serverSocket,) )
thread.start_new_thread( send, (serverSocket,) )
print("server started")
except Exception as e:
print (str(e))
killServer = input("Server shutdown? (y/n)")
#
#thread.start_new_thread( send), (serverSocket) )
Answer: '192.168.0.10' - this is private IP
(<http://en.wikipedia.org/wiki/IP_address#Public_and_Private_Addresses>) if
you want to make your server visible by internet you should configure NAT on
your router (only if your WAN adress is
public)(<http://en.wikipedia.org/wiki/Network_address_translation>)
How do it? Easy - you must login on your router by webrowser find NAT
configuration and "say" if any think from internet camo on port 1234 you
should send it to 192.168.0.10:nPort
|
Writing code to codes.db incorrectly
Question: I am trying to make a random code generator in python that writes to a
database. I have the codes generating and writing to the database, but instead
of adding full codes to the database it loops through letters. Here is my code
for the code generator:
import string
import random
import sqlite3
def id_generator():
db = sqlite3.connect('codes.db')
c = db.cursor()
number_of_codes = 10
stringLength = 9
id_code = input("what letter should this begin with: \n")
id_code = id_code.upper()
dict_ofcodes = []
for x in range(0, number_of_codes):
codez = (''.join(random.choice(string.ascii_uppercase) for i in range(stringLength)))
final_codez = (id_code + codez)
dict_ofcodes.insert(x, final_codez)
print (dict_ofcodes)
dict_ofcodes_tuple = tuple(dict_ofcodes)
print(dict_ofcodes_tuple)
for x in range(0, number_of_codes):
c.executemany(''' INSERT INTO codes(codes) VALUES(?)''', dict_ofcodes_tuple[x])
db.commit()
db.close()
id_generator()
Here is what it prints
['AALRRIULNC', 'AZTKZBKTLK', 'ATWMWYWICO', 'AWQJIJYEJH', 'AQFIONPUNJ', 'AMJRXUIJXM', 'AUDRLSBLSG', 'ABXYXDUMPD', 'AUAXRQURBH', 'ADQEVIRDFU']
('AALRRIULNC', 'AZTKZBKTLK', 'ATWMWYWICO', 'AWQJIJYEJH', 'AQFIONPUNJ', 'AMJRXUIJXM', 'AUDRLSBLSG', 'ABXYXDUMPD', 'AUAXRQURBH', 'ADQEVIRDFU')
It writes to the database single letters of the codes: A F Y and so on
The code I used to create the schema is contained in the a python file
import sqlite3
def writeDB():
db = sqlite3.connect('codes.db')
c = db.cursor()
# Create table
c.execute('''CREATE TABLE codes (codes TEXT)''')
# Save (commit) the changes
db.commit()
#can also close the connection if done with it.
# be sure any changes have been committed or they will be lost.
db.close()
writeDB()
I created the file with the mac terminal. How could I write the full codes to
the database?
Answer: The problem is with this line:
>
> c.executemany(''' INSERT INTO codes(codes) VALUES(?)''',
> dict_ofcodes_tuple[x])
>
`executemany` is used to iterate over a list of parameters and call the sql
statement for each parameter. So your dict_ofcodes_tupel[x] is treated as a
character array and the INSERT is called for each character.
If you want to insert the entire string as one, use execute() instead.
>
> c.execute(''' INSERT INTO codes(codes) VALUES(?)''',
> (dict_ofcodes_tuple[x],))
>
or
>
> c.execute(''' INSERT INTO codes(codes) VALUES(?)''',
> [dict_ofcodes_tuple[x]])
>
|
python connect to postgresql with libpq-pgpass
Question: I read there is a more secure way to connect to postgresql db without
specifying password in source code using
**<http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html>**. But
unfortunatelly I was not able to find any examples of how to import it to my
python program and how made my postgresql server to use this file. Please
help.
Answer: You don't import it into your _Python_ program. The point of `.pgpass` is that
it is a regular file subject to the system's file permissions, and the _libpq_
driver which libraries such as _psycopg2_ use to connect to _Postgres_ will
look to this file for the password instead of requiring the password to be in
the source code or prompting for it.
Also, this is not a server-side file, but a client-side one. So, on a *nix
box, you would have a `~/.pgpass` file containing the credentials for the
various connections you want to be able to make.
**Edit in response to comment from OP:**
Two main things need to happen in order for _psycopg2_ to correctly
authenticate via `.pgpass`:
1. Do _not_ specify a password in the string passed to `psycopg2.connect`
2. Make sure the correct entry is added to the `.pgpass` file for the user who will be connecting via _psycopg2_.
For example, to make this work for all databases for a particular user on
**localhost** port **5432** , you would add the following line to that user's
`.pgpass` file:
localhost:5432:*:<username>:<password>
And then the `connect` call would be of this form:
conn = psycopg2.connect("host=localhost dbname=<dbname> user=<username>")
The underlying _libpq_ driver that _psycopg2_ uses will then utilize the
`.pgpass` file to get the password.
|
Python Sqlite3 - Data get overwritten
Question: When ever i try to insert data to my database, it's like it simply just
overwrite whole file or not saving it correctly. My thoughts about this script
was that if i ran it multiple times it would output this:
(1, 126)
(2, 127)
(3, 126)
(4, 127)
I also now that if i doesn't create table within the script, it gives me an
error that the table doesn't exist, even though the table was created, last
time i ran the script.
import sqlite3
# Connecting to the database file
conn = sqlite3.connect("MyDB.db")
c = conn.cursor()
# Check if table exists
c.execute("DROP TABLE IF EXISTS t1")
# Create table
c.execute('''CREATE TABLE t1(
a INTEGER PRIMARY KEY,
b INTEGER);''')
# Insert value
c.execute('''INSERT INTO t1 VALUES(NULL,126);''')
c.execute('''INSERT INTO t1 VALUES(NULL,127);''')
# Save changes
conn.commit()
for row in c.execute('SELECT * FROM t1'):
print(row)
# Output:
# (1, 126)
# (2, 127)
conn.close()
I really want this to work, since i'm working on a school project where my
product is to make a functional store where you can add, remove products and
sort them by date they were added.
Answer: Two issues:
1. You are dropping the table if exists, this will always deletes the table:
c.execute("DROP TABLE IF EXISTS t1")
2. You are re-creating the table after dropping:
c.execute('''CREATE TABLE t1(
a INTEGER PRIMARY KEY,
b INTEGER);''')
You could comment above codes and re-run your script to get the output you
want. But, in the final version ensure to check db and table exists before
writing to it.
|
Passing results to depending on job - python rq
Question: How do I pass the result of a job to a job that depends on it?
What I currently do is passing id of the first job to the second,
first = queue.enqueue(firstJob)
second = queue.enqueue(secondJob, first.id, depends_on=first);
And inside `secondJob` fetching the first job to get the result
first = queue.fetch_job(previous_job_id)
print first.result
Is this the recomended way? Is there any other pattern that I can use to
directly pass first job's result to second?
Answer: You can access info about the current job and its dependencies from within the
job itself. This negates the need to explicitly pass the id of the first job.
Define your jobs:
from rq import Queue, get_current_job
from redis import StrictRedis
conn = StrictRedis()
q = Queue('high', connection=conn)
def first_job():
return 'result of the first job'
def second_job():
current_job = get_current_job(conn)
first_job_id = current_job.dependencies[0].id
first_job_result = q.fetch_job(first_job_id).result
assert first_job_result == 'result of the first job'
Enqueue your jobs:
first = queue.enqueue(first_job)
second = queue.enqueue(second_job, depends_on=first)
Note that the `current_job` can have multiple dependencies so
`current_job.dependencies` is a list.
|
Parse xml with python
Question: I'm trying to parse a XML document with Python, this is my code:
from xml.dom import minidom
xmldoc = minidom.parse("aula.xml")
hosts = xmldoc.getElementsByTagName("host")
for host in hosts:
address = host.getElementByTag("address")
ip = address.attributes["addr"]
IP = ip.value
print("IP:%s"%(IP))
this returns me:
Traceback (most recent call last):
File "simple.py", line 8, in <module>
address = host.getElementByTag("address")
AttributeError: Element instance has no attribute 'getElementByTag'
The XML file:
<?xml version="1.0"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/local/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 6.47 scan initiated Thu Feb 26 11:38:24 2015 as: nmap -oX aula.xml x.x.x.x/26 -->
<nmaprun scanner="nmap" args="nmap -oX aula.xml x.x.x.x/26" start="1424947104" startstr="Thu Feb 26 11:38:24 2015" version="6.47" xmloutputversion="1.04">
<scaninfo type="connect" protocol="tcp" numservices="1000" services="a lot of numbers"/>
<verbose level="0"/>
<debugging level="0"/>
<host starttime="1424947104" endtime="1424947111"><status state="up" reason="conn-refused" reason_ttl="0"/>
<address addr="x.x.x.x" addrtype="ipv4"/>
<hostnames>
</hostnames>
<ports>
<extraports state="closed" count="998">
<extrareasons reason="conn-refused" count="998"/>
</extraports>
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
<port protocol="tcp" portid="111"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="rpcbind" method="table" conf="3"/></port>
</ports>
<times srtt="1280" rttvar="264" to="100000"/>
</host>
</nmaprun>
Answer: There can be more than one `address`. So use
address = host.getElementsByTagName("address")[0]
to get the first `address`.
|
Bi-variant interactive function plotting using IPython
Question: I want to plot two functions, say sine and cosine, with different frequencies
--- so the first variable is the function to plot and the second is it
frequency. I want to have a selector widget that selects the function and a
slider that chooses the frequency. Is it possible to achieve this using
`interact` or do I need a more complicated setup?
Answer: Yes, this should be possible with `interact` For further reading there are a
couple of [`example
notebooks`](https://github.com/ipython/ipython/tree/master/examples/Interactive%20Widgets)
in the github repository that can be used as an introduction into interactive
widgets.
%matplotlib inline
from IPython.html import widgets
import numpy as np
import matplotlib.pyplot as plt
fun_map = {
"sin": np.sin,
"cos": np.cos
}
func_name = widgets.Dropdown(
options=['sin', 'cos'],
value='sin',
description='Function:',
)
freq = widgets.FloatSlider(
min=1,
max=5,
value=1,
description='Parameter:'
)
def plot_fun(func_name, freq, fun_map):
f = fun_map[func_name]
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, f(freq * x))
res = widgets.interact(plot_fun, freq=freq, func_name=func_name,
fun_map=widgets.fixed(fun_map))
This is the result:

|
Maya, PYTHON: how do i select all but one in a list?
Question: # how do i deselect all objects except for my last selection?
When I'm working with 2 objects there's no problem because all i have to do is
toggle list[0] which would be first object that i selected (this is how i have
it working below).
import maya.cmds as mc
sel_objs = mc.ls(sl = True)
mc.select(sel_objs[0], tgl = True)
thanks
Answer: You can replace the selection entirely with the last element of the list:
mc.select(sel_objs[-1], replace=True)
`replace` is the equivalent to clicking on it rather than ctrl-clicking or
shift-clicking. The selection is cleared in the action of selecting the new
object.
`sel_objs[-1]` returns the last object in the list, just as `sel_objs[0]`
returns the first object.
|
Can't get my sprites to collide?
Question: I feel like I've tried everything, and I'm getting pretty freaking tired of
this now.... I'm a python and pygame noob trying to make my own game from
scratch without looking at tutorials, but i don't know how to solve this, i
must have missed something.
Here is my statement that checks for collision:
for c in cakes:
if pygame.sprite.collide_rect(jake, c) and c.eaten == False:
c.is_eaten()
score += 1
print score
c.draw()
c.update_pos()
So the game is basically a "catch the falling thing"-game. I have no idea what
i have missed...
Here is the Cake-class, it looks pretty much the same as the player-class:
class Cake(pygame.sprite.Sprite):
def load_image(self, image_name):
try:
image = pygame.image.load(image_name)
except pygame.error as message:
print ("Cannot load image: " + image_name)
raise SystemExit(message)
return image.convert_alpha()
def __init__(self, screen, x, y, speed):
self.image = self.load_image("cake.png")
self.screen = screen
self.x = x
self.y = y
self.rect = self.image.get_rect()
self.w, self.h = self.image.get_size()
self.rect.move(self.x, self.y)
self.rect.topleft = (self.x, self.y)
self.rect.bottomright = (self.x + self.w, self.y + self.h)
self.eaten = False
self.speed = speed
def draw(self):
if self.eaten == False:
self.screen.blit(self.image, (self.x, self.y))
def is_eaten(self):
self.eaten = True
def update_pos(self):
if self.eaten == False:
self.y += self.speed
I'm not looking for a clear or direct answer, just a nudge in the right
direction, thanks in advance.
Answer: Since you mention you're new to python, I'll go out on a limb and assume
you're new to programming in general.
When a problem appears and you've invested some effort on it and are still not
quite sure what's wrong, it's probably time to delve into **debugging**.
There's multiple debugging techniques for different languages, but the general
theory is to **verify that the program is working as you expect it to be** .
Very often a program will be failing for reasons completely unrelated to the
initially visible problem.
Here are some basic steps to help you debug a program:
* **Reproduce the problem reliably** \- and, preferably, automatically.
* **Approach the problem in a structured way**. Make educated assumptions as to why the program is failing, then test them with...
* **Prints**. Print the content of your variables, the values of function arguments, the results of function calls. Check carefully the output, and see if it matches your expectations. As soon as something doesn't, _stop_ and figure out why it doesn't. In python, you can use the excellent [`logging` module](https://docs.python.org/2/howto/logging.html) to separate your debugging prints from your normal output.
* **Run your program step by step in a interactive debugger**. This will help you inspect your data structures more deeply than you can comfortably do with printing. For python, you can use [pdb](https://docs.python.org/2/library/pdb.html)
* * *
Let's see how to put this theory into practice in your particular problem.
While you don't mention it, your question implies that collisions are not
happening. I'll further assume that you can reproduce the problem reliably -
since you mention it never works.
Something you might want to do next is to **setup the game such that it always
starts with the same initial conditions**. If you have any calls to random,
setup the random number generator to use a fixed seed, and setup a seed that
can reproduce your problem quickly - and preferably, without user input.
You've already isolated the code where the problem is happening.
Next, you should **print the contents of the involved variables: the positions
of the sprites, the value of`eaten`**. Then, run your program again and watch
the prints to make sure everything is as you'd expect. If it is, figure out
_when_ (as in the number of pygame main loops) it starts to fail. You can then
**put a conditional in your code to launch the debugger** , `pdb`:
if number_of_pygame_loop_iterations==PROBLEMATIC_ITERATION:
import pdb; pdb.set_trace()
From there, you can then call `pygame.sprite.collide_rect` with the sprites in
their current position, and check what's amiss.
|
Send message to a Python Script
Question: I'm trying to write a little python program for shutdown or Reboot my
Raspberry PI, drived by a button connected to an GPIO. The program can show
the current status of the raspberry PI (Booting,Running,Halting,Rebooting) via
two leds. The python program is executed as daemon, started by a init.d bash
script (written using the /etc/init.d/skeleton).
Now I can start/stop/verify the status of the daemon, and the daemon can check
the input where the button is connected, to perform the command "shutdown -h
now" or "shutdown -r now" .
For show the current status of the raspberry PI, I had thought of send
messages to the daemon, using some script in the runlevels directorys, for
change the status of the leds. But I don't know how receive message in the
python program.
Someone can help me?
Thanks.
Answer: There are several methods to send a message from one script/app to another:
For you application a valid method is to use a named pipe. Create it using
[os.mkfifo](https://docs.python.org/2/library/os.html), open it read-only in
your python app and then wait for messages on it.
If you want your app to do another things while waiting, I reccomend you open
the pipe in non-blocking mode to look for data availability without blocking
your script as in following example:
import os, time
pipe_path = "/tmp/mypipe"
if not os.path.exists(pipe_path):
os.mkfifo(pipe_path)
# Open the fifo. We need to open in non-blocking mode or it will stalls until
# someone opens it for writting
pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)
with os.fdopen(pipe_fd) as pipe:
while True:
message = pipe.read()
if message:
print("Received: '%s'" % message)
print("Doing other stuff")
time.sleep(0.5)
Then you can send messages from bash scripts using the command
`echo "your message" > /tmp/mypipe`
**EDIT:** I can not get select.select working correctly (I used it only in C
programs) so I changed my recommendation to a non-bloking mode.
|
Stitching images together Opencv -Python
Question: My program takes in an image and crops the image into seperate images
according to the scale parameter, e.g. scale = 3 produces 9 images of equal
size. I then work out mean rgb of each cropped image and set all pixel values
in the image equal to the mean rgb value.
I am wondering how I can stich the cropped images back together to output one
image? Which in this case would be a grid of nine different colours.
Here is my code:
# import packages
import numpy as np
import cv2
import dateutil
import llist
from matplotlib import pyplot as plt
import argparse
#Read in image
img = cv2.imread('images/0021.jpg')
scale = 3
#Get x and y components of image
y_len,x_len,_ = img.shape
mean_values = []
for y in range(scale):
for x in range(scale):
#Crop image 3*3 windows
cropped_img=img[(y*y_len)/scale:((y+1)*y_len)/scale,
(x*x_len)/scale:((x+1)*x_len)/scale]
mean_val=cv2.mean(cropped_img)
mean_val=mean_val[:3]
#Set cropped img pixels equal to mean RGB
cropped_img[:,:,:] = mean_val
cv2.imshow('cropped',cropped_img)
cv2.waitKey(0)
#Print mean_values array
#mean_values.append([mean_val])
#mean_values=np.asarray(mean_values)
#print mean_values.reshape(3,3,3)
As it stands the nested for loop iterates over the image and outputs the
images (which are just blocks of one colour) in the order that I want to
stitch them together, but im not sure how to achieve this.
Answer: I don't know if such things exist in OpenCV, but in ImageMagick you can simply
resize the image down to the tile-size (which will implicitly average the
pixels) and the re-scale the image back up to the original size without
interpolation - also called _Nearest Neighbour Resampling_. Like this:

# Get original width and height
identify -format "%wx%h" face1.jpg
500x529
# Resize down to, say 10x10 and then back up to the original size
convert face1.jpg -resize 10x10! -scale "${geom}"! out.jpg

Per your original, 3x3 becomes:
convert face1.jpg -resize 3x3! -scale "${geom}"! out.jpg

and 3x5 becomes:
convert face1.jpg -resize 3x5! -scale "${geom}"! out.jpg

|
Compiling .py-file to .exe in Python 3.3
Question: I can't figure get py2exe working.
I wish to convert this test.py to test.exe:
test.py code:
print("Hello World!")
**EDIT:**
Apparently I used python 2.x approach. When I instead used the 3.3 command:
py -3.3 -m py2exe.build_exe test.py
I got the new error:
D:\program\python\lib\distutils\dist.py:257: UserWarning: Unknown distribution o
ption: 'console'
warnings.warn(msg)
invalid command name 'test.py'
Feels as if I am just running into walls constantly. Any insight on this new
error?
**Old part of post:**
I have created a setup.py with the following code:
from distutils.core import setup
import py2exe
setup(console=['test.py'])
I installed py2exe (ver 0.9.2.2) with pip. When I move to the folder
containing setup.py and test.py and run the command:
python setup.py py2exe
I run into the error:
D:\program\python\lib\distutils\dist.py:257: UserWarning: Unknown distribution o
ption: 'console'
warnings.warn(msg)
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'py2exe'
Answer: The python documentation discourages the use of the `distutils` module.
Instead use `setuptools` as follows
from setuptools import setup
import py2exe
setup(scripts=['test.py'])
Under python 3 though, you can't use `py2exe` see the
[FAQ](https://docs.python.org/3/faq/windows.html?#how-do-i-make-an-executable-
from-a-python-script) for details.
|
python :- can't start new thread
Question: i need to know why when i run the below code it gives me this error
Traceback (most recent call last):
File "C:\Users\moksh\Desktop\moksh.py", line 29, in <module>
server_B_thread.start()
error: can't start new thread
Code:
#!/usr/bin/python
import threading
import time
import SocketServer
import socket
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.allow_reuse_address = True
self.data = self.request.recv(1024).strip()
print "%s wrote: " % self.client_address[0]
print 'Connection from',self.client_address[0]
print self.data
self.request.send(self.data.upper())
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
HOST = '0.0.0.0'
PORT = 1000
while PORT <1900:
server_B = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
server_B_thread = threading.Thread(target=server_B.serve_forever)
server_B_thread.setDaemon(True)
server_B_thread.start()
PORT +=1
while 1:
time.sleep(1)
Answer: You're trying to start 900 threads, and probably hitting a limit on the OS. I
don't know what you're trying to do, but I would look into
[Twisted](https://twistedmatrix.com/trac/), which will probably have more
options for running a high volume TCP server.
|
Getting the index information of a specific string in a nested list? In python 3
Question: So I have a list with lots of nested lists in which include a students name
and their test score, I was wondering how to retrieve the index (position) of
the sub list that contains a specific students scores by searching with the
variable 'name' that the user enters when the quiz starts. The lists sub list
are created from the import of a text file, the code i used for that is:
with open('class1quizscoreboard.txt') as scoreboard:
for line in scoreboard:
importedscores.append(line.strip().split(',')
This works and the list looks like this:
[['EmilyScott ', ' 3'], ['Student Name ', ' 2'], ['Another Student ', ' 1'], ['Third Student ', ' 10']]
So I want to find the sublist by searching with the variable name, then find
the position of that sublist IF the name is already in the list of scores. I
would then add another test score into the list, but if it is not there just
create another list.
I thought of approaching this with an IF with FOR loop, but didn't work
for sublist in importedscores:
if sublist[0] == search:
print ("Found it!"), sublist
Returned 'not found' even though I used a name I knew was definitely in the
list
I am probably approaching this in the complete wrong way but the end goal is
to be able to add the students new score to their existing list if they
already have one
Thank you for any help
Answer: **By dictionary:**
1. Read txt file by `csv` module because file have well define structure.
2. Create dictionary from the file content where key is name and value is integer number i.e. score
3. Add new score for existing student.
4. Create new entry for new sequent.
Demo:
import csv
import pprint
p = "input34.txt"
with open(p, "rb") as fp:
root = csv.reader(fp, delimiter=',')
result = {}
for i in root:
result[i[0].strip()] = int(i[1].strip())
print "Debug1 result:"
pprint.pprint (result)
serach_key = "Test student"
add_value = 5
if serach_key in result:
result[serach_key] = result[serach_key] + add_value
else:
result[serach_key] = add_value
print "Debug2 result:"
pprint.pprint (result)
serach_key = "Another Student"
add_value = 5
if serach_key in result:
result[serach_key] = result[serach_key] + add_value
else:
result[serach_key] = add_value
print "Debug3 result:"
pprint.pprint (result)
Output:
vivek@vivek:~/Desktop/stackoverflow$ python 34.py
Debug1 result:
{'Another Student': 1,
'Emily Scott': 3,
'Student Name': 2,
'Third Student': 10}
Debug2 result:
{'Another Student': 1,
'Emily Scott': 3,
'Student Name': 2,
'Test student': 5,
'Third Student': 10}
Debug3 result:
{'Another Student': 6,
'Emily Scott': 3,
'Student Name': 2,
'Test student': 5,
'Third Student': 10}
* * *
**By list:**
Demo:
mport csv
import pprint
p = "input34.txt"
with open(p, "rb") as fp:
root = csv.reader(fp, delimiter=',')
result = []
for i in root:
result.append([i[0].strip(), int(i[1].strip())])
print "Debug1 result:"
pprint.pprint (result)
serach_key = "Test student"
add_value = 5
add_flag = False
for i,j in enumerate(result):
if serach_key==j[0]:
j[1] = j[1] + add_value
add_flag = True
break
if add_flag==False:
result.append([serach_key, add_value])
print "Debug2 result:"
pprint.pprint (result)
serach_key = "Another Student"
add_value = 5
add_flag = False
for i,j in enumerate(result):
if serach_key==j[0]:
j[1] = j[1] + add_value
add_flag = True
break
if add_flag==False:
result.append([serach_key, add_value])
print "Debug3 result:"
pprint.pprint (result)
Output:
vivek@vivek:~/Desktop/stackoverflow$ python 34.py
Debug1 result:
[['Emily Scott', 3],
['Student Name', 2],
['Another Student', 1],
['Third Student', 10]]
Debug2 result:
[['Emily Scott', 3],
['Student Name', 2],
['Another Student', 1],
['Third Student', 10],
['Test student', 5]]
Debug3 result:
[['Emily Scott', 3],
['Student Name', 2],
['Another Student', 6],
['Third Student', 10],
['Test student', 5]]
* * *
Use `collection.defaultdict` to optimize code. So no need to check key is in
dictionary or not.
e.g.:
>>> import collections
>>> result = collections.defaultdict(int)
>>> result["student 1"] = 10
>>> result["student 2"] = 20
>>> print result
defaultdict(<type 'int'>, {'student 1': 10, 'student 2': 20})
>>> result["student 2"] = result["student 2"] + 2
>>> print result
defaultdict(<type 'int'>, {'student 1': 10, 'student 2': 22})
>>> result["student 3"] = result["student 3"] + 5
>>> print result
defaultdict(<type 'int'>, {'student 1': 10, 'student 2': 22, 'student 3': 5})
>>>
|
Can you change the color of the turtle pen in a while loop using a list?
Question: I want to know if you could change the color of the python turtle pen when a
while loop iterates and continue to change everytime the while loop iterates.
So far I have this but want to make it change color too.
from turtle import *
w = 10
# Number of steps to take
x = 40
# Number of sides to make
y = 2
# Size of turtle pen
z = x
# Same variable as x but not manipulated
speed ('fastest')
# Speed of pen
for i in range(10):
while x > 0:
pensize (y)
forward (w)
left (360/z)
x = x-1
y = y+1
while x < z:
pensize (y)
forward (w)
right (360/z)
x = x+1
y = y-1
print (i)
Any suggestions?
Answer: There is a `pencolor` function, so, yes, you can change the color.
If your problem is not turtle, but taking the values elegantly out of a too
short list, I suggest `itertools`, and the `next()` method.
from itertools import cycle
color_sequence = cycle([4,5,6])
for i in range(10): print color_sequence.next()
And if you don't want to to have an extra command for every stroke, you just
replace the call to `forward()` by a call to your own
`list_colored_forward()`.
|
Count occurrences of item in JSON element
Question: I'm using Python to parse the UK police API. What I want is to analyse the
JSON response I'm getting in order to calculate how many times a certain
offence occurs. This is an example of a response from the API.
{
category: "anti-social-behaviour",
location_type: "Force",
location: {
latitude: "53.349920",
street: {
id: 583315,
name: "On or near Evenwood Close"
},
longitude: "-2.657889"
},
context: "",
outcome_status: null,
persistent_id: "",
id: 22687179,
location_subtype: "",
month: "2013-03"
},
Using this code
from json import load
from urllib2 import urlopen
import json
url = "http://data.police.uk/api/crimes-street/all-crime?lat=53.396246&lng=-2.646960&date=2013-03"
json_obj = urlopen(url)
player_json_list = load(json_obj)
for player in player_json_list:
crimeCategories = json.dumps(player['category'], indent = 2, separators=(',', ': '))
print crimeCategories
I get a response like this
"anti-social-behaviour"
"anti-social-behaviour"
"anti-social-behaviour"
"anti-social-behaviour"
"drugs"
"drugs"
"burglary"
If I changed my for loop to
for player in player_json_list:
crimeCategories = json.dumps(player['category'], indent = 2, separators=(',', ': '))
print crimeCategories.count("drugs")
I then get a response like
0
0
0
0
1
1
0
Searching forums for hours hasn't helped me! Any ideas?
Answer: You can use a collections.Counter dict with requests which becomes a couple of
concise lines of code:
import requests
from collections import Counter
url = "http://data.police.uk/api/crimes-street/all-crime?lat=53.396246&lng=-2.646960&date=2013-03"
json_obj = requests.get(url).json()
c = Counter(player['category'] for player in json_obj)
print(c)
Output:
Counter({'anti-social-behaviour': 79, 'criminal-damage-arson': 12, 'other-crime': 11, 'violent-crime': 9, 'vehicle-crime': 7, 'other-theft': 6, 'burglary': 4, 'public-disorder-weapons': 3, 'shoplifting': 2, 'drugs': 2})
If you prefer having a normal dict then simply call dict on the Counter dict:
from pprint import pprint as pp
c = dict(c)
pp(c)
{'anti-social-behaviour': 79,
'burglary': 4,
'criminal-damage-arson': 12,
'drugs': 2,
'other-crime': 11,
'other-theft': 6,
'public-disorder-weapons': 3,
'shoplifting': 2,
'vehicle-crime': 7,
'violent-crime': 9}
You then simply access by key `c['drugs']` etc..
Or iterate over the items to print crime and count in the format you want:
for k, v in c.items():
print("{} count: {}".format(k, v)
Output:
drugs count: 2
shoplifting count: 2
other-theft count: 6
anti-social-behaviour count: 79
violent-crime count: 9
criminal-damage-arson count: 12
vehicle-crime count: 7
public-disorder-weapons count: 3
other-crime count: 11
burglary count: 4
|
How print python method documentation using inspect or __doc__ method
Question: I have following code :
import os
import imp
import sys
import inspect
import urlparse
from cgi import escape
def get_module(ClassName, Path):
fp, pathname, description = imp.find_module(ClassName, [Path])
module_loaded = imp.load_module(ClassName, fp, pathname, description)
return module_loaded
def get_class_members(className):
print "Members of "+str(className)
member_functions = inspect.getmembers(className, predicate=inspect.ismethod)
for each_item in member_functions:
print each_item[0].__doc__
def get_all_classes(path, module):
module_loaded = None
sys.path.append(path)
module_loaded = get_module(module, path)
if None != module_loaded:
class_list = module_loaded.get_all_classes()
print "classes are "+str(class_list)
return class_list
def main():
class_list = get_all_classes('.', 'Class_Interface_File')
for each_class in class_list:
temp_module = get_module(each_class, '.')
my_class = getattr(temp_module, each_class)
instance = my_class()
get_class_members(instance)
print "-----------"
if __name__ == "__main__":
main()
Class_Interface_file returns a list of classnames example ['Social', 'Audio']
I have issue here in method get_class_members. I want to print the comments
for each member function I discover through inspect.getmembers. I dono how to
concat className with value of each_item.
or is it possible to directly print documentation of member functions which
comes from each_item ?
please help on this.
Answer: Okay, did some playing around with your code....
I have a class Triangle in a module triangle with some methods.
>>>import inspect
>>>import triangle
>>>mems = inspect.getmembers(triangle.Triangle)
>>>mems
[('__doc__', None), ('__init__','<unboound method.....>), etc)]
`getmembers()` returns a list of tuples. So in your code, looping through
this, you're asking for `each_item[0].__doc__`, [0] refers to the string
containing the name of the function. So that line returns just the `__doc__`
of string objects. Changing this to [1] will return the `__doc__` for the
actual method:
>>>mems[3][0] #the name of the function itself
'drawEquilateral'
>>>#here I reference the second tuple element of the fourth member
...
>>>mems[3][1].__doc__
'draw an equilateral triangle'
>>>"Method %s: %s" %(mems[3][0], mems[3][1].__doc__)
'Method drawEquilateral: draw an equilateral triangle'
Hope this helps.
|
How to get around the pickling error of python multiprocessing without being in the top-level?
Question: I've researched this question multiple times, but haven't found a workaround
that either works in my case, or one that I understand, so please bear with
me.
Basically, I have a hierarchical organization of functions, and that is
preventing me from multiprocessing in the top-level. Unfortunately, I don't
believe I can change the layout of the program - because I need all the
variables that I create after the initial inputs.
For example, say I have this:
import multiprocessing
def calculate(x):
# here is where I would take this input x (and maybe a couple more inputs)
# and build a larger library of variables that I use further down the line
def domath(y):
return x * y
pool = multiprocessing.Pool(3)
final= pool.map(domath, range(3))
calculate(2)
This yields the following error:
Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
I was thinking of globals, but I'm afraid that I'd have to define too many and
that may slow my program down quite a bit. Is there any workaround without
having to restructure the whole program?
Answer: The problem you encountered is actually a feature. The pickle source is
actually designed to prevent this sort of behavior in order to prevent
malicious code from being executed. Please consider that when addressing any
applicable security implementation.
First off we have some imports.
import marshal
import pickle
import types
Here we have a function which takes in a function as an argument, pickles the
parts of the object, then returns a tuple containing all the parts:
def pack(fn):
code = marshal.dumps(fn.__code__)
name = pickle.dumps(fn.__name__)
defs = pickle.dumps(fn.__defaults__)
clos = pickle.dumps(fn.__closure__)
return (code, name, defs, clos)
Next we have a function which takes the four parts of our converted function.
It translates those four parts, and creates then returns a function out of
those parts. You should take note that globals are re-introduced into here
because our process does not handle those:
def unpack(code, name, defs, clos):
code = marshal.loads(code)
glob = globals()
name = pickle.loads(name)
defs = pickle.loads(defs)
clos = pickle.loads(clos)
return types.FunctionType(code, glob, name, defs, clos)
Here we have a test function. Notice I put an import within the scope of the
function. Globals are not handled through our pickling process:
def test_function(a, b):
from random import randint
return randint(a, b)
Finally we pack our test object and print the result to make sure everything
is working:
packed = pack(test_function)
print((packed))
Lastly, we unpack our function, assign it to a variable, call it, and print
its output:
unpacked = unpack(*packed)
print((unpacked(2, 20)))
Comment if you have any questions.
|
Selenium (from Python) hangs if I close my browser window
Question: If I start Selenium from Python and close the browser window, my script hangs
the next time I try to get the WebDriver to do something. Note that I'm
closing the browser _window_ while leaving the browser itself open--I'm on a
Mac, and it's possible for the browser (Chrome, in my case) to remain open
even without any windows. Here's an example:
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.stackoverflow.com/")
time.sleep(5) # Let's say we close Chrome window during this time
print "Trying to open second page"
driver.get("http://www.python.org/")
print "You won't get here if you closed the Chrome window"
Ideally I'd like Selenium to either make a new window for me or let me tell
that there's no open window and let me create one myself.
Answer: That is not what is going to happen. The browser windows you see are not all
able to get talked to by selenium.
Selenium spawns a browser with the w3c component running and able to be talked
to. This is kind of like a mini http server that lives in the web browser,
that selenium talks to to click on things and do it's business. It's called
WebDriver. <http://www.w3.org/TR/webdriver/>
When you close the browser opened and interfaced with selenium... you are
breaking the socket connections selenium made, and it can not find it.
AFAIK: Selenium is just talking to the webdriver interface of the browser.
Your program would have to look for active browsers, get their memory address,
open a new selenium-webdriver and point it at it... this would take a bit of
re-writing the selenium source as calling a webdriver now initiates a new
browser instance.
|
ImportError: Module use of python27.dll conflicts with this version of Python
Question: Im currently trying to make a python script for Harris Corner Detection, and I
keep getting this error no matter what other articles/fixes I find. Thanks for
any help you can give.
Edit: Its the first line of the code that gives the error
Code:
import cv2
import numpy as np
filename = 'chessboard.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv2.imshow('dst',img)
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Answer: I had this issue occur also. In my environment settings I had a variable
PYTHONPATH pointing to the directory of my Python 2.7 version of cv2.pyd.
Updating this to the Python 3.4 version of the cv2.pyd directory fixed it.
|
Run python behave from python instead of command line
Question: Is there any way to run python behave from within python and not via command
line?
default usage: run behave command in base folder with features/steps
desired usage: call a function (or have a certain import) which executes the
behave tests in a specified folder
Answer: Found the solution by working through the behave source code:
from behave.__main__ import main as behave_main
behave_main("path/to/tutorial")
The main method of behave enumerates and processes all paths it finds in its
arguments.
|
Python, not able to append to a list from a recursive function
Question: I am in the mid-way of writing a code to find all possible solutions of a
input similar like `"a&b|c!d|a"`, where a,b,c,d all are booleans and &-`and`,
|-`or` !-`not` are the operators. By solution I mean the set of values of
these variables which makes the input expression give `True`.
I am able to print all possible combinations of the variables, but I am not
able to retain them (in this case, in a list) for later use.
What's wrong in the way I am doing it? Are there better ways to store them?
`generate_combination` is the method in which I am trying to do this.
**Code:**
import operator
# global all_combinations
all_combinations=[]
answers=[]
def solve(combination, input, rank):
try:
substituted_str=""
for i in input:
if i in combination:
substituted_str+=combination[i]
else:
substituted_str+=i
print substituted_str
# for item in rank:
except:
pass
def generate_combination(variables,comb_dict, length, current_index):
if len(comb_dict)==length:
print comb_dict #Each combination , coming out right
all_combinations.append(comb_dict)
print all_combinations,"\n" #This is not working as expected
else:
for i in [1,0]:
comb_dict[variables[current_index]]=i
generate_combination(variables,comb_dict, length,current_index+1)
comb_dict.pop(variables[current_index], None)
def main(input,variables,order):
rank=sorted(order.items(), key=operator.itemgetter(1))
generate_combination(variables, {}, len(variables), 0)
for combination in all_combinations:
print combination
ans=solve(combination, input, rank)
ans=[]
answers.extend(ans)
# for answer in answers:
# print answer
def nothing():
pass
if __name__ == '__main__':
# print "Enter your symbols for :\n"
# And=raw_input("And = ")
# Or=raw_input("Or = ")
# Not=raw_input("Not = ")
# input_str=raw_input("Enter the expression :")
And,Or,Not,input_str='&','|','!','a&b|c!d|a'
input_str=input_str.replace(" ","")
mapping={And:"&", Or:"|", Not:"!"}
order={"&":3, "|":2, "!":1}
variables=[]
processed_str=""
for i in input_str:
if i in mapping:
processed_str+=mapping[i]
else:
processed_str+=i
variables.append(i)
variables=list(set(variables))
print "Reconstituted string : ",processed_str
print "Variables : ",variables,"\n"
main(processed_str,variables,order)
**Current Output:**
Reconstituted string : a&b|c!d|a
Variables : ['a', 'c', 'b', 'd']
{'a': 1, 'c': 1, 'b': 1, 'd': 1}
[{'a': 1, 'c': 1, 'b': 1, 'd': 1}]
{'a': 1, 'c': 1, 'b': 1, 'd': 0}
[{'a': 1, 'c': 1, 'b': 1, 'd': 0}, {'a': 1, 'c': 1, 'b': 1, 'd': 0}]
{'a': 1, 'c': 1, 'b': 0, 'd': 1}
[{'a': 1, 'c': 1, 'b': 0, 'd': 1}, {'a': 1, 'c': 1, 'b': 0, 'd': 1}, {'a': 1, 'c': 1, 'b': 0, 'd': 1}]
{'a': 1, 'c': 1, 'b': 0, 'd': 0}
[{'a': 1, 'c': 1, 'b': 0, 'd': 0}, {'a': 1, 'c': 1, 'b': 0, 'd': 0}, {'a': 1, 'c': 1, 'b': 0, 'd': 0}, {'a': 1, 'c': 1, 'b': 0, 'd': 0}]
{'a': 1, 'c': 0, 'b': 1, 'd': 1}
[{'a': 1, 'c': 0, 'b': 1, 'd': 1}, {'a': 1, 'c': 0, 'b': 1, 'd': 1}, {'a': 1, 'c': 0, 'b': 1, 'd': 1}, {'a': 1, 'c': 0, 'b': 1, 'd': 1}, {'a': 1, 'c': 0, 'b': 1, 'd': 1}]
{'a': 1, 'c': 0, 'b': 1, 'd': 0}
[{'a': 1, 'c': 0, 'b': 1, 'd': 0}, {'a': 1, 'c': 0, 'b': 1, 'd': 0}, {'a': 1, 'c': 0, 'b': 1, 'd': 0}, {'a': 1, 'c': 0, 'b': 1, 'd': 0}, {'a': 1, 'c': 0, 'b': 1, 'd': 0}, {'a': 1, 'c': 0, 'b': 1, 'd': 0}]
{'a': 1, 'c': 0, 'b': 0, 'd': 1}
[{'a': 1, 'c': 0, 'b': 0, 'd': 1}, {'a': 1, 'c': 0, 'b': 0, 'd': 1}, {'a': 1, 'c': 0, 'b': 0, 'd': 1}, {'a': 1, 'c': 0, 'b': 0, 'd': 1}, {'a': 1, 'c': 0, 'b': 0, 'd': 1}, {'a': 1, 'c': 0, 'b': 0, 'd': 1}, {'a': 1, 'c': 0, 'b': 0, 'd': 1}]
{'a': 1, 'c': 0, 'b': 0, 'd': 0}
[{'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}, {'a': 1, 'c': 0, 'b': 0, 'd': 0}]
{'a': 0, 'c': 1, 'b': 1, 'd': 1}
[{'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}, {'a': 0, 'c': 1, 'b': 1, 'd': 1}]
{'a': 0, 'c': 1, 'b': 1, 'd': 0}
[{'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}, {'a': 0, 'c': 1, 'b': 1, 'd': 0}]
{'a': 0, 'c': 1, 'b': 0, 'd': 1}
[{'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}, {'a': 0, 'c': 1, 'b': 0, 'd': 1}]
{'a': 0, 'c': 1, 'b': 0, 'd': 0}
[{'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}, {'a': 0, 'c': 1, 'b': 0, 'd': 0}]
{'a': 0, 'c': 0, 'b': 1, 'd': 1}
[{'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}, {'a': 0, 'c': 0, 'b': 1, 'd': 1}]
{'a': 0, 'c': 0, 'b': 1, 'd': 0}
[{'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}, {'a': 0, 'c': 0, 'b': 1, 'd': 0}]
{'a': 0, 'c': 0, 'b': 0, 'd': 1}
[{'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}, {'a': 0, 'c': 0, 'b': 0, 'd': 1}]
{'a': 0, 'c': 0, 'b': 0, 'd': 0}
[{'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}, {'a': 0, 'c': 0, 'b': 0, 'd': 0}]
Answer: I think the problem is that all the items in your _all_combinations_ list are
pointed to the same _comb_dict_ , you are overwriting each element in every
call of _generate_combination_. Try to make a copy of the _comb_dict_ :
`all_combinations.append(comb_dict.copy())`
|
How do I correctly write a CSV file on individual rows and columns?
Question: I am producing a small recipe input and output program in **Python** , however
I am having trouble writing the ingredients to a **CSV** file. I am trying to
print each item of a list to a comma separated file, using this code:
with open('recipes/' + recipeName + '.csv', 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.write(ingredientList[0])
recipewriter.write(ingredientList[1])
recipewriter.write(ingredientList[2])
In the list, there are three items. For example, this could be a list I am
trying to save to a file:
ingredientList = ['flour', '500', 'g']
And I want the data to appear like this in a CSV file:
flour,
500,
g,
Instead it is appearing like this:
f,l,o,u,r,
5,0,0,
g,
How do I get it to appear in my desired format?
Here is my source code:
#Python 3.3.3
import sys #Allows use of the 'exit()' function
import csv #Allows use of the CSV File API
def mainMenu():
print("########################################################")
print("# Welcome to the recipe book, please select an option: #")
print("# 1. Add new recipe #")
print("# 2. Lookup existing recipe #")
print("# 3. Exit #")
print("########################################################")
selectedOption = None
inputtedOption = input()
try:
inputtedOption = int(inputtedOption)
except ValueError:
print("Invalid option entered")
if inputtedOption == 1:
selectedOption = inputtedOption
elif inputtedOption == 2:
selectedOption = inputtedOption
elif inputtedOption == 3:
print("Exiting...")
sys.exit(0)
return selectedOption
def validateInput(inputtedData):
try: #Test if data is an integer greater than 1
inputtedData = int(inputtedData)
if int(inputtedData) < 1: #Recipes cannot contain less than 1 ingredient
print("Sorry, invalid data entered.\n('%s' is not valid for this value - positive integers only)" % inputtedData)
return False
return int(inputtedData)
except ValueError:
print("Sorry, invalid data entered.\n('%s' is not valid for this value - whole integers only [ValueError])\n" % inputtedData)
return False
def addRecipe():
print("Welcome to recipe creator! The following questions will guide you through the recipe creation process.\nPlease enter the name of your recipe (e.g. 'Pizza'):")
recipeName = input()
print("Recipe Name: %s" % recipeName)
print("Please enter the amount of people this recipe serves (e.g. '6'):")
recipeServingAmount = input()
if validateInput(recipeServingAmount) == False:
return
else:
recipeServingAmount = validateInput(recipeServingAmount)
print("Recipe serves: %s" % recipeServingAmount)
print("Please enter the number of ingredients in this recipe (e.g. '10'):")
recipeNumberOfIngredients = input()
if validateInput(recipeNumberOfIngredients) == False:
return
else:
recipeNumberOfIngredients = validateInput(recipeNumberOfIngredients)
print("Recipe contains: %s different ingredients" % recipeNumberOfIngredients)
ingredientList = {}
i = 1
while i <= recipeNumberOfIngredients:
nthFormat = "st"
if i == 2:
nthFormat = "nd"
elif i == 3:
nthFormat = "rd"
elif i >= 4:
nthFormat = "th"
ingredientNumber = str(i) + nthFormat
print("Please enter the name of the %s ingredient:" % ingredientNumber)
ingredientName = input()
print("Please enter the quantity of the %s ingredient:" % ingredientNumber)
ingredientQuantity = input()
print("Please enter the measurement value for the %s ingredient (leave blank for no measurement - e.g. eggs):" % ingredientNumber)
ingredientMeasurement = input()
print("%s ingredient: %s%s %s" % (ingredientNumber, ingredientQuantity, ingredientMeasurement, ingredientName))
finalIngredient = [ingredientName, ingredientQuantity, ingredientMeasurement]
print(finalIngredient[1])
ingredientList[i] = finalIngredient
with open('recipes/' + recipeName + '.csv', 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.write(ingredientList[0])
recipewriter.write(ingredientList[1])
recipewriter.write(ingredientList[2])
i = i + 1
def lookupRecipe():
pass # To-do: add CSV reader and string formatter
#Main flow of program
while True:
option = mainMenu()
if option == 1:
addRecipe()
elif option == 2:
lookupRecipe()
Answer: `csv.writer`s don't have a `write()` method. In Python 3 you could do it like
this:
with open('recipes/' + recipeName + '.csv', 'w', newline='') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.writerow([ingredientList[0]])
recipewriter.writerow([ingredientList[1]])
recipewriter.writerow([ingredientList[2]])
|
Maya Python: OptionMenu Selection With Button
Question: I'm new to python in Maya and I'm trying to build a UI which can generate
shapes and transform them. The problem I think lies in the ObjectCreation
function but I'm not to sure. So far this what I've got:
import maya.cmds as cmds
#check to see if window exists
if cmds.window("UserInterface", exists = True):
cmds.deleteUI("UserInterface")
#create actual window
UIwindow = cmds.window("UserInterface", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
mainLayout = cmds.columnLayout(w = 300, h =500)
def SceneClear(*args):
cmds.delete(all=True, c=True) #Deletes all objects in scene
cmds.button(label = "Reset", w = 300, command=SceneClear)
polygonSelectMenu = cmds.optionMenu(w = 250, label = "Polygon Selection:")
cmds.menuItem(label = " ")
cmds.menuItem(label = "Sphere")
cmds.menuItem(label = "Cube")
cmds.menuItem(label = "Cylinder")
cmds.menuItem(label = "Cone")
def ObjectCreation(*args):
if polygonSelectMenu.index == 2: #tried referring to index
ma.polySphere(name = "Sphere")
elif polygonSelectMenu == "Cube":
ma.polyCube(name = "Cube")
elif polygonSelectMenu == "Cylinder":
ma.polyCylinder(name = "Cylinder")
elif polygonSelectMenu == "Cone":
ma.polyCone(name = "Cone")
cmds.button(label = "Create", w = 200, command=ObjectCreation)
def DeleteButton(*args):
cmds.delete()
cmds.button(label = "Delete", w = 200, command=DeleteButton)#Deletes selected object
cmds.showWindow(UIwindow) #shows window
What I'm after is for the user to select one of the options from the option
menu then to press the create button to generate that shape. I've tried to
refer to it by name and index but I don't know what I'm missing. Like I said
I'm new to python so when I tried searching for an answer myself I couldn't
find anything and when I did find something similar I couldn't understand it.
Plus for some reason the SceneClear function/Reset button doesn't seem to work
so if there is answer to that please let me know.
Answer: `polygonSelectMenu` contains the path to your `optionMenu` UI element. In my
case it is: `UserInterface|columnLayout7|optionMenu4`. This is just a string
and not a reference to a UI element.
To access it's current value you must use this:
`currentValue = cmds.optionMenu(polygonSelectMenu, query=True, value=True)`
All optionMenu's flags are listed [here (Maya 2014 commands
doc)](http://download.autodesk.com/global/docs/maya2014/en_us/CommandsPython/index.html),
queryable ones have a little green Q next to them.
* * *
As a result, here is your `ObjectCreation(*args)` function:
def ObjectCreation(*args):
currentValue = cmds.optionMenu(polygonSelectMenu, query=True, value=True)
if currentValue == "Sphere": #tried referring to index
cmds.polySphere(name = "Sphere")
elif currentValue == "Cube":
cmds.polyCube(name = "Cube")
elif currentValue == "Cylinder":
cmds.polyCylinder(name = "Cylinder")
elif currentValue == "Cone":
cmds.polyCone(name = "Cone")
* * *
## Off-topic:
Avoid declaring functions between lines of code (in your case, the UI creation
code), try instead putting the UI creation code inside a function and call
this function at the end of your script.
It is readable as you have only few UI elements right now. But once you start
having 20 or more buttons/labels/inputs it can be a mess quickly.
Also, I prefer giving an object name to the UI elements, just like you did
with your window (`"UserInterface"`). To give you a concrete example:
`cmds.optionMenu("UI_polygonOptionMenu", w = 250, label = "Polygon
Selection:")` This optionMenu can be then accessed anywhere in you code using:
`cmds.optionMenu("UI_polygonOptionMenu", query=True, value=True)`
Here is the full modified script if you want:
import maya.cmds as cmds
def drawUI(): #Function that will draw the entire window
#check to see if window exists
if cmds.window("UI_MainWindow", exists = True):
cmds.deleteUI("UI_MainWindow")
#create actual window
cmds.window("UI_MainWindow", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
cmds.columnLayout("UI_MainLayout", w = 300, h =500)
cmds.button("UI_ResetButton", label = "Reset", w = 300, command=SceneClear)
cmds.optionMenu("UI_PolygonOptionMenu", w = 250, label = "Polygon Selection:")
cmds.menuItem(label = " ")
cmds.menuItem(label = "Sphere")
cmds.menuItem(label = "Cube")
cmds.menuItem(label = "Cylinder")
cmds.menuItem(label = "Cone")
cmds.button("UI_CreateButton", label = "Create", w = 200, command=ObjectCreation)
cmds.button("UI_DeleteButton", label = "Delete", w = 200, command=DeleteButton)#Deletes selected object
cmds.showWindow("UI_MainWindow") #shows window
def SceneClear(*args):
cmds.delete(all=True, c=True) #Deletes all objects in scene
def ObjectCreation(*args):
currentValue = cmds.optionMenu("UI_PolygonOptionMenu", query=True, value=True)
if currentValue == "Sphere":
cmds.polySphere(name = "Sphere")
elif currentValue == "Cube":
cmds.polyCube(name = "Cube")
elif currentValue == "Cylinder":
cmds.polyCylinder(name = "Cylinder")
elif currentValue == "Cone":
cmds.polyCone(name = "Cone")
def DeleteButton(*args):
cmds.delete()
drawUI() #Calling drawUI now at the end of the script
Hope this will help you.
|
Python Debugging Using Pdb
Question: I'm using a interactive graphical Python debugger with ipdb under the hood
(Canopy's graphical debugger). The script I am working on has multiple
imported modules and several calls to their respective functions. Whenever I
attempt a debugging run, execution gets stuck somewhere within a call to an
imported module's function (specifically subprocess). My two main questions
are:
1) Does running in debug mode slow things down considerably? Is the code not
actually stuck, but just running at a painfully slow rate?
2) Is there a way to completely pass over bits of code and run them as if I
were not even debugging? I want to prevent the debugger from diving into
subprocess and just execute it as if it were a normal run.
I might toss the graphical debugger and do everything from a terminal, but I
would like to avoid that if I can because the graphical interface is really
convenient and saves a lot of typing.
Answer:
import pdb
a = "aaa"
pdb.set_trace()
b = "bbb"
c = "ccc"
final = a + b + c
print final
Your output when you run the code then it will start debugging and control
will stop after `a="aaa"`
$ python abc.py
(Pdb) p a
'aaa'
(Pdb)
Thanks, Shashi
|
Multilevel JSON diff in python
Question: Please link me to answer if this has already been answered, my problem is i
want to get diff of multilevel json which is unordered.
x=json.loads('''[{"y":2,"x":1},{"x":3,"y":4}]''')
y=json.loads('''[{"x":1,"y":2},{"x":3,"y":4}]''')
z=json.loads('''[{"x":3,"y":4},{"x":1,"y":2}]''')
import json_tools as jt
import json_delta as jd
print jt.diff(y,z)
print jd.diff(y,z)
print y==z
print x==y
output is
[{'prev': 2, 'value': 4, 'replace': u'/0/y'}, {'prev': 1, 'value': 3, 'replace': u'/0/x'}, {'prev': 4, 'value': 2, 'replace': u'/1/y'}, {'prev': 3, 'value': 1, 'replace': u'/1/x'}]
[[[2], {u'y': 2, u'x': 1}], [[0]]]
False
True
my question is how can i get y and z to be equal or if there are actual
differences depending on non-order of the JSON.
kind of unordered List of dictionaries but i am looking for something which is
level-proof that is list/dict of dictionaries of list/dictionaries ...
Answer: solved it partially with following function
def diff(prev,lat):
p=prev
l=lat
prevDiff = []
latDiff = []
for d1 in p[:]:
flag = False
for d2 in l:
if len(set(d1.items()) ^ set(d2.items())) == 0:
p.remove(d1)
l.remove(d2)
flag = True
break
if not flag:
prevDiff.append(d1)
p.remove(d1)
prevDiff = prevDiff + p
latDiff = latDiff + l
resJSONdata=[]
if len(prevDiff) != 0:
resJSONdata.append({'prevCount':len(prevDiff)})
resJSONdata.append({'prev':prevDiff})
if len(latDiff) != 0:
resJSONdata.append({'latestCount':len(latDiff)})
resJSONdata.append({'latest':latDiff})
# return json.dumps(resJSONdata,indent = 4,sort_keys=True)
return resJSONdata
it's not doing it recursively into level into levels but for my purpose this
solved the issue
|
PHP calling python not working
Question: I'm having issues getting a python script to run through PHP. I can run my
python script manually with no problems, but cannot run it through PHP. I am
calling the PHP script from a web page that I want to execute a python script.
I have searched all over to try and figure this out, but I can not manage to
get it to work. I have tried exec(), system(), shell_exec(), etc. to run the
script without success. I have also done a chmod +x on the python script. I
have tried things like
<?php
exec('/usr/bin/python /root/Desktop/ledtest.py');
?>
Does anyone have any other suggestions?
Edit: I'm trying to give more information but sadly I can't. I just came into
this company as an intern and I'm trying to pick up where the previous intern
left off (it's a huge mess and no one seems to know whats going on here).
Sorry for the lack of information
Answer: What error message you are getting as PHP has some kind of limit, like 30sec,
you may easily find from calling phpinfo() and searching for
max_execution_time in the output. it's possible to change this from the script
to a higher value, if you need, using ini_set('max_execution_time', 1200);,
and you may get another details about max_execution_time from this question:
stackoverflow.com/questions/4220413/…
Additionally,
Whatever error python is raising would be going to the child's stderr. Try
either telling php to read from stderr, or (in python) do this:
import sys sys.stderr = sys.stdout
|
Calculating distance between two elements only in the array in python
Question: So I have two questions: First I'm trying to print my array that contains 1004
elements but it's printing only the first 29 elements and then jumping to 974
to continue printing. How can I get the full array of 1004 elements?
This is my code
paired_data = []
for x in data:
closest, ignored = pairwise_distances_argmin_min(x, result)
paired_data.append([x, result[closest]])
#print paired_data
S = pd.DataFrame(paired_data, columns=['x','center'])
print S
# distance
Y = pdist(S, 'euclidean')
print Y
Also I want to calculate the distance between each two elements of the array.
for example
0 [5, 4] [3, 2]
1 [22, -10] [78, 90]
I want to calculate the distance( Euclidean ) between [5, 4] and [3, 2] and so
on for all the rest of the array.
Answer: Another solution to #1:
print(S.to_string()) # print the entire table
and to get distances
# assumes Python 3
from functools import partial
def dist(row, col1, col2):
return sum((c2 - c1)**2 for c1,c2 in zip(row[col1], row[col2])) ** 0.5
# compose a function (name the columns it applies to)
s_dist = partial(dist, col1="x", col2="center")
# apply it
S["dist"] = S.apply(s_dist, axis=1)
|
python mysql connector query returns none
Question: I am having an issue with mysql connector. I did search for quite a while, but
have found nothing.
If I execute the first file that just has the query, it works as expected. But
if I try to make a db class and put the query in there, it returns None. I
have taken out the location variable and it's the same. No matter what I try
to query on, it returns None. I even tried to do a "SHOW TABLES", and it
returned None.
Also, I have run this in a debugger and looked at the cursor object to be
sure, as well as the mysql general log. The query is correct and everything
looks as it should to me.
This is my first try with python and I am hoping the solution is some simple
newbie mistake.
The query that works: **test.py**
import mysql.connector
_config = {
'user': 'user',
'password': 'password',
'host': '127.0.0.1',
'database': 'testdb',
'raise_on_warnings': True,
}
cnx = mysql.connector.connect(**_config)
cursor = cnx.cursor()
query = ("SELECT * FROM testtbl WHERE location=%s")
location='HERE'
cursor.execute(query, (location, ))
print("--- " + str(cursor) + " ----")
for (stuff) in cursor:
print("stuff: '" + stuff[0] + "', more stuff: '" + stuff[1] + "'")
cursor.close()
cnx.close()
The ones that do not work: **somedb.py**
import mysql.connector
class SomeDB(object):
def __init__(self):
_config = {
'user': 'user',
'password': 'password',
'host': '127.0.0.1',
'database': 'testdb',
'raise_on_warnings': True,
}
self.conn = mysql.connector.connect(**_config)
self.cur = self.conn.cursor()
def get_stuff(self):
query = ("SELECT * FROM testtbl WHERE location=%s")
location="HERE"
result = self.cur.execute(query, (location, ))
return result
def __del__(self):
self.conn.close()
Following the advice from Alu, I changed the get_stuff method to this:
def get_nodes(self):
query = ("SELECT * FROM testtbl WHERE location=%s")
location="HERE"
cursor = self.cur.execute(query, (location, ))
list = []
for (thing) in cursor:
list.append(([thing[0],thing[1]]))
return list
**test2.py**
import somedb
db = somedb.SomeDB()
cursor = db.get_stuff()
print("--- " + str(cursor) + " ----")
for (stuff) in cursor:
print("stuff: '" + stuff[0] + "', more stuff: '" + stuff[1] + "'")
# UPDATE
Ok, I cannot get this to work. I have gone through this code with a debugger,
and class abstraction aside, all else appears to be equal. So let me refine my
question: is this possible with any mysql driver? This is what I want to do:
<http://programmers.stackexchange.com/questions/200522/how-to-deal-with-
database-connections-in-a-python-library-module>
# UPDATE2
I found it!
result = self.cur.execute(query, (location, ))
return result
Needs to be, simply:
self.cur.execute(query, (location, ))
return self.cur
Answer: As far as i remember you have to commit on the connection after every
transaction.
You can try to use this as an example. It's my database class.
<https://github.com/CatCookie/DomainSearch/blob/master/src/additional/database.py>
|
PythonNet FileNotFoundException: Unable to find assembly
Question: I am trying to execute a Python script that uses Python For .Net
(<https://github.com/pythonnet/pythonnet>) to load a C# library called
"Kratos_3.dll" which is in the same folder as the script but the file cannot
be found.
I have installed clr using "pip install pythonnet".
This is my script:
import clr
import sys
sys.path.insert(0,"C:\\dev\\proj_1\\")
clr.AddReference("Kratos_3")
I keep getting the error
FileNotFoundException: Unable to find assembly 'Kratos_3. at Python.Runtime.CLRModule.AddReference(String name)
When I run this using IronPython it works, but I would like to get this to
work using regular Python 2.7, what do I need to do?
Answer: It turns out that even though I added the path through
sys.path.insert(0,"C:\\dev\\proj_1\\")
it still couldn't find the file because the .dll because Windows was not
enabling it to load from "external sources". To fix this:
1. Right-click on the .dll
2. "Properties"
3. Under "General", click "Unblock"
|
Python script not iterating through array
Question: So, I recently got into learning python and at work we wanted some way to make
the process of finding specific keywords in our log files easier, to make it
easier to tell what IPs to add to our block list.
I decided to go about writing a python script that would take in a logfile,
take in a file with a list of key terms, and then look for those key terms in
the log file and then write the lines that matched the session IDs where that
key term was found; to a new file.
import sys
import time
import linecache
from datetime import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.now().strftime(fmt).format(fname=fname)
importFile = open('rawLog.txt', 'r') #pulling in log file
importFile2 = open('keyWords.txt', 'r') #pulling in keywords
exportFile = open(timeStamped('ParsedLog.txt'), 'w') #writing the parsed log
FILE = importFile.readlines()
keyFILE = importFile2.readlines()
logLine = 1 #for debugging purposes when testing
parseString = ''
holderString = ''
sessionID = []
keyWords= []
j = 0
for line in keyFILE: #go through each line in the keyFile
keyWords = line.split(',') #add each word to the array
print(keyWords)#for debugging purposes when testing, this DOES give all the correct results
for line in FILE:
if keyWords[j] in line:
parseString = line[29:35] #pulling in session ID
sessionID.append(parseString) #saving session IDs to a list
elif importFile == '' and j < len(keyWords): #if importFile is at end of file and we are not at the end of the array
importFile.seek(0) #goes back to the start of the file
j+=1 #advance the keyWords array
logLine +=1 #for debugging purposes when testing
importFile2.close()
print(sessionID) #for debugging purposes when testing
importFile.seek(0) #goes back to the start of the file
i = 0
for line in FILE:
if sessionID[i] in line[29:35]: #checking if the sessionID matches (doing it this way since I ran into issues where some sessionIDs matched parts of the log file that were not sessionIDs
holderString = line #pulling the line of log file
exportFile.write(holderString)#writing the log file line to a new text file
print(holderString) #for debugging purposes when testing
if i < len(sessionID):
i+=1
importFile.close()
exportFile.close()
It is not iterating across my keyWords list, I probably made some stupid
rookie mistake but I am not experienced enough to realize what I messed up.
When I check the output it is only searching for the first item in the
keyWords list in the rawLog.txt file.
The third loop does return the results that appear based on the sessionIDs
that the second list pulls and does attempt to iterate (this gives an out of
bounds exception due to i never being less than the length of the sessionID
list, due to sessionID only having 1 value).
The program does write to and name the new logfile sucessfully, with a
DateTime followed by ParsedLog.txt.
Answer: If the elif is never True you never increase `j` so you either need to
increment always or check that the `elif` statement is actually ever
evaluating to `True`
for line in FILE:
if keyWords[j] in line:
parseString = line[29:35] #pulling in session ID
sessionID.append(parseString) #saving session IDs to a list
elif importFile == '' and j < len(keyWords): #if importFile is at end of file and we are not at the end of the array
importFile.seek(0) #goes back to the start of the file
j+=1 # always increase
Looking at the above loop, you create the file object with `importFile =
open('rawLog.txt', 'r')` earlier in your code so comparing `elif importFile ==
''` will never be `True` as `importFile` is a file object not a string.
You assign `FILE = importFile.readlines()` so that does exhaust the iterator
creating the FILE list, you `importFile.seek(0)` but don't actually use the
file object anywhere again.
So basically you loop one time over `FILE`, `j` never increases and your code
then moves to the next block.
What you actually need are nested loops, using `any` to see if any word from
keyWords is in each line and forget about your elif :
for line in FILE:
if any(word in line for word in keyWords):
parseString = line[29:35] #pulling in session ID
sessionID.append(parseString) #saving session IDs to a list
The same logic applies to your next loop:
for line in FILE:
if any(sess in line[29:35] for sess in sessionID ): #checking if the sessionID matches (doing it this way since I ran into issues where some sessionIDs matched parts of the log file that were not sessionIDs
exportFile.write(line)#writing the log file line to a new text file
`holderString = line` does nothing bar refer to the same object line so you
can simply `exportFile.write(line)` and forget the assignment.
On a sidenote use lowercase and underscores for variables etc.. `holderString
-> holder_string` and using `with` to open your files would be best as it also
closes them for.
with open('rawLog.txt') as import_file:
log_lines = import_file.readlines()
I also changed `FILE` to `log_lines`, using more descriptive names makes your
code easier to follow.
|
NoReverseMatch at /rango/ newbie got stuck in tango w django tutorial
Question: The error message debug mode:
> NoReverseMatch at /rango/ Reverse for 'category' with arguments '('other-
> frameworks',)' and keyword arguments '{}' not found. 1 pattern(s) tried:
> ['rango/category/(?P\w+)/$'] Request Method: GET Request URL:
> <http://127.0.0.1:8000/rango/> Django Version: 1.7.4 Exception Type:
> NoReverseMatch Exception Value: Reverse for 'category' with arguments
> '('other-frameworks',)' and keyword arguments '{}' not found. 1 pattern(s)
> tried: ['rango/category/(?P\w+)/$'] Exception Location:
> C:\Users\Beheerder\Desktop\venv\lib\site-
> packages\django\core\urlresolvers.py in _reverse_with_prefix, line 468
> Python Executable: C:\Users\Beheerder\Desktop\venv\Scripts\python.exe Python
> Version: 3.4.2
Error during template rendering
> Reverse for 'category' with arguments '('other-frameworks',)' and keyword
> arguments '{}' not found. 1 pattern(s) tried: ['rango/category/(?P\w+)/$']
1 {% if cats %}
2 <ul class="nav nav-sidebar">
3 {% for c in cats %}
4 <li><a href="{% url 'category' c.slug %}">{{ c.name }}</a></li>
5 {% endfor %}
6
7 {% else %}
8 <li> <strong >There are no category present.</strong></li>
9
10 </ul>
11 {% endif %}
I ( as a newbie ) have no idea what is going wrong here,
This is the link to the specific tutorial part:
<http://www.tangowithdjango.com/book17/chapters>
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_slug>\w+)/add_page/$', views.add_page, name='add_page'),
url(r'^restricted/$', views.restricted, name='restricted'),
url(r'^add_page/$', views.add_page, name="add_page"),
)
Answer: The `-` dash in the `other-frameworks` string does not match the (alphanumeric
and underscore) `\w`.
Change the regex in the url to the `[\w-]+`:
url(r'^category/(?P<category_name_url>[\w-]+)/$', views.category,
name='category'),
|
Installing pygame for python 3.x, getting difficulties
Question: I have just installed the latest version of python, 3.4.3 32 bit and the
corresponding pygame. I get this error when importing pygame
>>> import pygame
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import pygame
File "C:\Python34\lib\site-packages\pygame\__init__.py", line 127, in <module>
from pygame.base import *
ImportError: DLL load failed: The specified module could not be found.
Please help fix the error
Answer: Try uninstalling Python 3.4 and installing Python 3.2, then reinstall the 3.2
version of pygame. I could not see a python 3.4 version of pygame when I
looked on the pygame website and unless you specifically need the features of
3.4 pygame for Python 3.2 should work fine.
|
Python script for EC2 snapshots, use datetime to delete old snapshots
Question: I am a beginner with Python and I have written a python script which takes a
snaphot of a specified volume and then retains only the number of snapshots
requested for that volume.
#Built with Python 3.3.2
import boto.ec2
from boto.ec2.connection import EC2Connection
from boto.ec2.regioninfo import RegionInfo
from boto.ec2.snapshot import Snapshot
from datetime import datetime
from functools import cmp_to_key
import sys
aws_access_key = str(input("AWS Access Key: "))
aws_secret_key = str(input("AWS Secret Key: "))
regionname = str(input("AWS Region Name: "))
regionendpoint = str(input("AWS Region Endpoint: "))
region = RegionInfo(name=regionname, endpoint=regionendpoint)
conn = EC2Connection(aws_access_key_id = aws_access_key, aws_secret_access_key = aws_secret_key, region = region)
print (conn)
volumes = conn.get_all_volumes()
print ("%s" % repr(volumes))
vol_id = str(input("Enter Volume ID to snapshot: "))
keep = int(input("Enter number of snapshots to keep: "))
volume = volumes[0]
description = str(input("Enter volume snapshot description: "))
if volume.create_snapshot(description):
print ('Snapshot created with description: %s' % description)
snapshots = volume.snapshots()
print (snapshots)
def date_compare(snap1, snap2):
if snap1.start_time < snap2.start_time:
return -1
elif snap1.start_time == snap2.start_time:
return 0
return 1
snapshots.sort(key=cmp_to_key(date_compare))
delta = len(snapshots) - keep
for i in range(delta):
print ('Deleting snapshot %s' % snapshots[i].description)
snapshots[i].delete()
What I want to do now is rather than use the number of snapshots to keep I
want to change this to specifying the date range of the snapshots to keep. For
example delete anything older than a specific date & time. I kind of have an
idea where to start and based on the above script I have the list of snapshots
sorted by date. What I would like to do is prompt the user to specify the date
and time from where snapshots would be deleted eg 2015-3-4 14:00:00 anything
older than this would be deleted. Hoping someone can get me started here
Thanks!!
Answer: First, you can prompt user to specify the date and time from when snapshots
would be deleted.
import datetime
user_time = str(input("Enter datetime from when you want to delete, like this format 2015-3-4 14:00:00:"))
real_user_time = datetime.datetime.strptime(user_time, '%Y-%m-%d %H:%M:%S')
print real_user_time # as you can see here, user time has been changed from a string to a datetime object
Second, delete anything older than that
SOLUTION ONE:
for snap in snapshots:
start_time = datetime.datetime.strptime(snap.start_time[:-5], '%Y-%m-%dT%H:%M:%S')
if start_time > real_user_time:
snap.delete()
SOLUTION TWO:
Since snapshots is sorted, you only find the first snap older than
real_user_time and delete all the rest of them.
snap_num = len(snapshots)
for i in xrange(snap_num):
# if snapshots[i].start_time is not the format of datetime object, you will have to format it first like above
start_time = datetime.datetime.strptime(snapshots[i].start_time[:-5], '%Y-%m-%dT%H:%M:%S')
if start_time > real_user_time:
for n in xrange(i,snap_num):
snapshots[n].delete()
break
Hope it helps. :)
|
import matplotlib.pyplot gives ImportError: dlopen(…) Library not loaded libpng15.15.dylib
Question: [I am aware that this exact same question has been asked
before.](http://stackoverflow.com/questions/27281943/import-matplotlib-pyplot-
gives-importerror-dlopen-library-not-loaded-libpn) I did follow the
instructions given in the answer there, and it didn't solve my problem (and I
don't have enough reputation to just comment on the Q or A in that thread).
Anyway, here's what's going on:
I try to do:
import matplotlib.pyplot
And in return I get:
Traceback (most recent call last):
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3032, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-eff513f636fd>", line 1, in <module>
import matplotlib.pyplot as plt
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 27, in <module>
import matplotlib.colorbar
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/colorbar.py", line 34, in <module>
import matplotlib.collections as collections
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/collections.py", line 27, in <module>
import matplotlib.backend_bases as backend_bases
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 56, in <module>
import matplotlib.textpath as textpath
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/textpath.py", line 22, in <module>
from matplotlib.mathtext import MathTextParser
File "/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/mathtext.py", line 63, in <module>
import matplotlib._png as _png
ImportError: dlopen(/Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2): Library not loaded: libpng15.15.dylib
Referenced from: /Users/russellrichie/anaconda/lib/python2.7/site-packages/matplotlib/_png.so
Reason: image not found
My Python version:
2.7.7 |Anaconda 2.0.1 (x86_64)| (default, Jun 2 2014, 12:48:16) [GCC 4.0.1 (Apple Inc. build 5493)]
EDIT:
cel's suggestion worked! I just tried "conda remove matplotlib", "pip install
matplotlib", and then "conda install matplotlib", and presto! Man, you have no
idea how long this problem has vexed me. Bless you all.
Answer: Some python packages link dynamically against native c libraries. After an
update of one of those libraries, links can break and give you weird error
messages about missing dynamic libraries, as seen in the error message in the
question.
Basically, after an update of a native library sometimes you also have to
rebuild python packages (here `matplotlib`).
The above statement is true in general. If you are using `conda` as your
python distribution things are usually less complicated:
For extension packages `conda` also maintains required c libraries. As long as
you use only `conda install` and `conda update` for installing those packages
you should not run into these issues.
For `numpy`, `scipy`, `matplotlib` and many more I would suggest to try `conda
search <library name>` first to see if there's a `conda` recipe that matches
your needs. For most users `conda install <library name>` will be a better
option than `pip install`.
To make sure that only `conda`'s version is installed you can do
conda remove matplotlib
pip uninstall matplotlib
conda install matplotlib
Afterwards this issue should not appear anymore.
|
charmap codec cant encode characters in position xx - xx
Question: I am trying to use unicodecsv python library in python 2.7.x
import codecs
import unicodecsv
def read(self, path):
with codecs.open(path, "rb", encoding = "utf-8") as f:
r = unicodecsv.reader(f, encoding = 'utf-8')
row = r.next()
print row
read("unicode.csv")
**Error:** charmap codec cant encode characters in position xx - xx
I have manually converted my csv file to utf-8 using txt editors so i am sure
the input file is fine
Answer: I see few problems with your code:
def read(self, path):
You using `self` no within `class`
after opening file with `codecs.open`you can use standard python `csv` reader.
With some modifications:
f = "/home/dzagorulkin/workspace/zont/file.txt"
import codecs
#import unicodecsv
def read(path):
with codecs.open(path, "rb", encoding = "utf-8") as f:
for line in f:
print line
read(f)
i used none ASCII file and output:
> Меня Дима зовут! Меня Дима зовут!
|
Python: Mocking a context manager
Question: I don't understand why I can't mock NamedTemporaryFile.name in this example:
from mock import Mock, patch
import unittest
import tempfile
def myfunc():
with tempfile.NamedTemporaryFile() as mytmp:
return mytmp.name
class TestMock(unittest.TestCase):
@patch('tempfile.NamedTemporaryFile')
def test_cm(self, mock_tmp):
mytmpname = 'abcde'
mock_tmp.__enter__.return_value.name = mytmpname
self.assertEqual(myfunc(), mytmpname)
Test results in:
AssertionError: <MagicMock name='NamedTemporaryFile().__enter__().name' id='140275675011280'> != 'abcde'
Answer: You are setting the wrong mock: `mock_tmp` is not the context manager but
**return** a context manager. Replace your setup line by
mock_tmp.return_value.__enter__.return_value.name = mytmpname
and your test will work.
|
Build STASM with OpenCV for iOS
Question: I'm trying to build stasm for iOS for facial recognition, using OpenCV.
The steps I'm doing are:
* Build OpenCV for iOS (python opencv/platforms/ios/build_framework.py ios)
* Download the build script from here: <https://github.com/juan-cardelino/stasm>, and edit the CMakeCache.txt to: OpenCV_DIR:PATH=/Users/xxx/opencv-2.4.9/ios/build/iPhoneOS-armv7s
* Open the Xcode project generated and compile.
* Use cmake, everything works fine.
* Use make, get this error:
>
> [ 44%] Building CXX object CMakeFiles/minimal.dir/apps/minimal.cpp.o
> Linking CXX executable minimal
> ld: warning: directory not found for option '-L/Release'
> ld: framework not found CoreImage
> clang: error: linker command failed with exit code 1 (use -v to see
> invocation)
> make[2]: *** [minimal] Error 1
> make[1]: *** [CMakeFiles/minimal.dir/all] Error 2
> make: *** [all] Error 2
>
What am I doing wrong? And, is this the way to build it for iOS?
Thanks.
Answer: You will find `CoreImage.framework` within `QuartzCore.framework`, just import
it
Library/Frameworks/QuartzCore.framework
|
Running background tasks in Meteor.js
Question: This is my scenario:
1. Scrape some data every X minutes from example.com
2. Insert it to Mongodb database
3. Subscribe for this data in Meteor App.
Because, currently I am not very good at Meteor this is what I am going to do:
1. Write scraper script for example.com in Python or PHP.
2. Run script every X minutes with cronjob.
3. Insert it to Mongodb.
Is it possible to do it completely with Meteor without using Python or PHP?
How can I handle task that runs every X minutes?
Answer: There are Cron like systems such as [percolate:synced-
cron](https://github.com/percolatestudio/meteor-synced-cron) for Meteor.
There, you could register a job using
[Later.js](http://bunkat.github.io/later/) syntax similar to this example
taken from the percolate:synced-cron readme file:
SyncedCron.add({
name: 'Crunch some important numbers for the marketing department',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('every 2 hours');
},
job: function() {
var numbersCrunched = CrushSomeNumbers();
return numbersCrunched;
}
});
If you want to rely on an OS level cron job, you could just provide an HTTP
endpoint in your Meteor.js application [that you could then access through
curl at the chosen time](http://stackoverflow.com/questions/17850967/run-a-
curl-command-using-cron-jobs).
|
Python 2.7: Running a python file within a package
Question: I have three folders:
/main
__init__.py
main.py
/p1
__init__.py
p1.py
/p2
__init__.py
p2.py
However some parts of `p1` depend on `p2` and the way in which I import `p2`
from `p1` is by using an absolute package and not a relative one:
from main.p2.p2 import p2class
The problem arises when I want to run `p1` individually by typing in:
cd main\p1
python p1.py
However, it says:
ImportError: No module named main.p2.p2
How can I run it individually?
Sources for the files are shown below:
`main\p1\p1.py`:
from main.p2.p2 import p2print
def p1print():
print "p1 printing"
if __name__ == "__main__":
p2print()
p1print()
`main\p2\p2.py`:
def p2print():
print "p2 printing"
if __name__ == "__main__":
p2print()
Answer: From outside of the /main directory, run it using `python -m`.
➜ python -m main.p1.p1
p2 printing
p1 printing
|
numpy array casting ruled not 'safe'
Question: Indexing one numpy array with another - both are defined as dtype='uint32'.
Using numpy.take to index and get an unsafe casting error. Not come across
this before. Any idea what is going on?
Python 2.7.8 |Anaconda 2.1.0 (32-bit)| (default, Jul 2 2014, 15:13:35) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import numpy
>>> numpy.__version__
'1.9.0'
>>> a = numpy.array([9, 7, 5, 4, 3, 1], dtype=numpy.uint32)
>>> b = numpy.array([1, 3], dtype=numpy.uint32)
>>> c = a.take(b)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
c = a.take(b)
TypeError: Cannot cast array data from dtype('uint32') to dtype('int32') according to the rule 'safe'
Answer: This is quite common when working NumPy functions that require indexes or
lengths to be specified (it's not just `take`, see for example
[here](https://github.com/numpy/numpy/issues/4384)).
The problem is that, for indexing purposes, NumPy would like to treat your
`uint32` array as an `int32` array (which is probably the "pointer" integer
type on your 32 bit system,
[`np.intp`](http://docs.scipy.org/doc/numpy/user/basics.types.html)) and wants
to cast it down to that type.
It can't do this safely - some of the integers in an unsigned array might not
be representable as a signed 32 bit integer. The error you see reflects this.
This means that you'll get the same error if `b` has dtype `int64` or a float
dtype, but not if it is `int32` or a smaller integer dtype.
For what it's worth, this isn't an immediate problem for the indexing notation
`a[b]` which allows the unsafe casting (but will raise an error if the index
is out of bounds). Try for example `a[2**31]` \- NumPy casts to `int32` but
then complains that the index `-2147483648` is out of bounds.
|
Extended APDUs and T=0/1 communication protocols
Question: I have a JCOP V2.4.2 R3 java card that it is mentioned in its datasheet "The
card support both `T=1` and `T=0` communication protocols"
I have also an ACR38 smart card reader that it support both T=0 and T=1
protocols. (I have T=0 communication with one card successfully and T=1
communication with this card successfully.)
I wrote the below program and upload it on the card to send and receive
extended APDUs:
package extAPDU;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISOException;
import javacardx.apdu.ExtendedLength;
public class ExAPDU extends Applet implements ExtendedLength {
private ExAPDU() {
}
public static void install(byte bArray[], short bOffset, byte bLength)
throws ISOException {
new ExAPDU().register();
}
public void process(APDU arg0) throws ISOException {
short number = arg0.setIncomingAndReceive();
arg0.setOutgoingAndSend((short)0, (short)(number+7));
}
}
In the CAD-side I used python scripts to send different APDUs to card. The
questions is:
**1- Why I can't start communication with T=0 protocol(While it is mentioned
that the card support this protocol):**
The python script:
from smartcard.scard import *
import smartcard.util
from smartcard.System import readers
from smartcard.CardConnection import CardConnection
r=readers()
print r
connection =r[0].createConnection()
connection.connect(CardConnection.T0_protocol)
normalCommand=[0x00,0xa4,0x04,0x00,0x06,0x01,0x02,0x03,0x04,0x05,0x06]
data,sw1,sw2=connection.transmit(normalCommand)
print "SW for Normal Command:"
print data,hex(sw1),hex(sw2)
Output:
>>> ================================ RESTART ================================
>>>
['ACS CCID USB Reader 0']
Traceback (most recent call last):
File "C:\extAPDU.py", line 13, in <module>
connection.connect(CardConnection.T0_protocol)
File "D:\PythonX\Lib\site-packages\smartcard\CardConnectionDecorator.py", line 54, in connect
self.component.connect(protocol, mode, disposition)
File "D:\PythonX\Lib\site-packages\smartcard\pcsc\PCSCCardConnection.py", line 118, in connect
raise CardConnectionException('Unable to connect with protocol: ' + dictProtocol[pcscprotocol] + '. ' + SCardGetErrorMessage(hresult))
CardConnectionException: Unable to connect with protocol: T0. The requested protocols are incompatible with the protocol currently in use with the smart card.
>>>
**2- Why the card doesn't work fine with the Select APDU commands in the
extended form on the T=1 protocol :**
The python script:
from smartcard.scard import *
import smartcard.util
from smartcard.CardConnection import CardConnection
from smartcard.System import readers
r=readers()
print r
connection =r[0].createConnection()
connection.connect(CardConnection.T1_protocol)
normalCommand=[0x00,0xa4,0x04,0x00,0x00,0x00,0x06,0x01,0x02,0x03,0x04,0x05,0x06]
data,sw1,sw2=connection.transmit(normalCommand)
print "SW for Normal Command:"
print data,hex(sw1),hex(sw2)
Output :
>>> ================================ RESTART ================================
>>>
['ACS CCID USB Reader 0']
SW for Normal Command:
[] 0x67 0x0
>>>
I think I misunderstood this concept and I mixed up Extended APDUs with `T=1`
and `T=0` protocols!
Every `T=1` compatible smart card, can send and receive Extended APDUs? and we
can't send and receive extended APDUs over `T=0` protocols? If we want to send
Extended SELECT APDU commands to the Security Domain, the SD must implement
`ExtendedLength` interface?
For an Extended APDU transmission what are the requirements?
1. A T=1 compatible card reader
2. A T=1 compatible smart card
3. An applet that implemented `ExtendedLength` interface
Is it right?
I am really confused about Extended compatibility and `T=0/1` compatibility in
smart cards. Any light will appreciated.
Note that, I can successfully send Extended APDUs to the above applet with
`T=1` protocol!
Answer: **Q1:** Changing Protocol is possible. Information which protocols are
supported by hte card is transceived via ATR/ATS. The terminal then can decide
which one to use. So it is dependend from your Terminal shell if protocols are
selectable or not. For JCOP Shell this is `/change-protocol`. However is do
not recommend T=0 in general.
**Q2:** If you start the card via sending ATR/ATS the Card Manager is active
which only supports Global Platform commands. Global Platform does not support
Extended Length what so ever. By sending a Select command(which must be simple
length because of that) the applet gets selected and that actual Select
commands is also forwarded into your Applet's `process()` method (and can be
detected by the `selectingApplet()` method). Now that you are in your Applet
you can send as many Extended Length commands as you want. You can bypass the
initial Non-Extended-Length-Select by installing your applet as default
selected.
|
Unit testing bottle py application that uses request body results in KeyError: 'wsgi.input'
Question: When unit testing a bottle py route function:
from bottle import request, run, post
@post("/blah/<boo>")
def blah(boo):
body = request.body.readline()
return "body is %s" % body
blah("booooo!")
The following exception is raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in blah
File "bottle.py", line 1197, in body
self._body.seek(0)
File "bottle.py", line 166, in __get__
if key not in storage: storage[key] = self.getter(obj)
File "bottle.py", line 1164, in _body
read_func = self.environ['wsgi.input'].read
KeyError: 'wsgi.input'
The code will work if running as a server via bottle's `run` function, it's
purely when I call it as a normal Python function e.g. in a unit test.
What am I missing? How can I invoke this as a normal python func inside a unit
test?
Answer: I eventually worked out what the problem is. I needed to "fake" the request
environment for bottle to play nicely:
from bottle import request, run, post, tob
from io import BytesIO
body = "abc"
request.environ['CONTENT_LENGTH'] = str(len(tob(body)))
request.environ['wsgi.input'] = BytesIO()
request.environ['wsgi.input'].write(tob(body))
request.environ['wsgi.input'].seek(0)
# Now call your route function and assert
|
Why some eigen vector signs from C++ Armadillo are different from Python and R
Question: I was wondering why the sign of the elements in the eigen vectors from
Armadillo is the opposite from other languages like Python (i.e. numpy) and R.
For example:
C++
using namespace arma;
vec eigval;
mat eigvec;
// C++11 initialization
mat A = { 1, -1, 0, -1, 2, -1, 0, -1, 1};
eig_sym(eigval, eigvec, A);
eigvec.print("Eigen Vectors");
Output
Eigen Vectors
-5.7735e-01 -7.071068e-01 0.4082483
-5.7735e-01 9.714451e-e17 -0.8164966
-5.7735e-01 7.017068e-01 0.4082483
Python
import numpy as np
w,v = np.linalg.eig(np.array([[1,-1,0],[-1,2,-1],[0,-1,1]]))
v
Output
array([[ -4.08248290e-01, -7.07106781e-01, 5.77350269e-01],
[ 8.16496581e-01, 2.61214948e-16, 5.77350269e-01],
[ -4.08248290e-01, 7.07106781e-01, 5.77350269e-01]])
R
eigen(matrix(c(1,-1,0,-1,2,-1,0,-1,1), 3, byrow=TRUE)$vectors
Output
-4.082483e-01 -7.071068e-01 5.773503e-01
8.164966e-01 9.420555e-16 5.773503e-01
-4.082483e-01 7.071068e-01 5.773503e-01
You can see that Python and R provide the same eigen vectors (excluding
rounding errors). The armadillo result does provide the same numbers (the
order is a simple fix) but the sign on the first and third columns are
opposite from the corresponding columns in Python and R. Am I overlooking
something here?
Answer: That is answered by `help(eigen)` in R:
Value:
The spectral decomposition of ‘x’ is returned as components of a
list with components
values: a vector containing the p eigenvalues of ‘x’, sorted in
_decreasing_ order, according to ‘Mod(values)’ in the
asymmetric case when they might be complex (even for real
matrices). For real asymmetric matrices the vector will be
complex only if complex conjugate pairs of eigenvalues are
detected.
vectors: either a p * p matrix whose columns contain the eigenvectors
of ‘x’, or ‘NULL’ if ‘only.values’ is ‘TRUE’. The vectors
are normalized to unit length.
Recall that the eigenvectors are only defined up to a
constant: even when the length is specified they are still
only defined up to a scalar of modulus one (the sign for real
matrices).
So the sign is a 'free' parameter, and the result is truly equivalent. If it
were me, I'd follow R and Python but Conrad generally knows what he is doing.
|
Pexpect eats bash prompt
Question: This expect script launches a bash shell that includes the prompt:
#! /usr/bin/env expect
spawn -noecho "bash"
expect "$ "
send "echo 'Hello, "
interact
e.g. `user@host:/path/to/working/directory$ echo 'Hello,`
I tried doing the same thing with
[Pexpect](http://pexpect.readthedocs.org/en/latest/):
#! /usr/bin/env python
import pexpect
child = pexpect.spawn('bash')
index = child.expect("\$ ")
child.send("echo 'Hello, ")
child.interact()
However, it swallows the prompt and only shows `echo 'Hello,`. I can force
`bash` to repaint with `child.sendcontrol('l')`, but this only works for some
shells; [`dash`](http://gondor.apana.org.au/~herbert/dash/), for example, does
not support it.
$ python
Python 2.7.9 (default, Dec 11 2014, 08:58:12)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pexpect
>>> pexpect.__version__
'3.2'
Answer: As J.F. Sebastian indicated, there is an alternative:
#! /usr/bin/env python
import pexpect
import sys
child = pexpect.spawn('bash')
child.logfile_read = sys.stdout
index = child.expect_exact("$ ")
child.interact()
|
Qt 5.4 Ctrl+Z shortcut conflict in Python? Doesn't work until its button has been pressed
Question: In Qt Designer 5.4, I have a QPushButton and have set its shortcut to
`Ctrl`+`Z`. I'm using pyuic5 to turn it into Python code. This is the
resulting line in the Python code:
self.quickTextUndoButton.setShortcut(_translate("newEntryDialog", "Ctrl+Z"))
When running the application, pressing `Ctrl`+`Z` does not call the slot as
expected, until the QPushButton has been pressed (which does call the slot);
thereafter, pressing `Ctrl`+`Z` DOES call the slot as expected.
This 'initializing' behavior does not happen with other buttons with shortcuts
`F1` thru `F12`.
Is this a conflict with the existing interpretation of `Ctrl`+`Z`? If so, is
there an easy way to avoid that conflict? Maybe just setting the
ShortcutContext appropriately?
Answer: Clicking on the button will give it the keyboard focus, and, more importantly,
remove focus from any other widget which has the same shortcut set.
All of the editable input widgets (such as `QLineEdit`, `QTextEdit`, etc) have
hard-coded [default key
bindings](http://doc.qt.io/qt-5/qlineedit.html#details) for various actions,
including `Ctrl+Z` (which undoes the last action). If such a widget has the
keyboard focus, its shortcut will get priority over the one you set for the
button (and vice versa).
When more than one widget has the same shortcut, you can set an event-filter
and use `ShortcutOverride` to disambiguate them:
self.lineEdit.installEventFilter(self)
...
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.ShortcutOverride and
event.modifiers() == QtCore.Qt.ControlModifier and
event.key() == QtCore.Qt.Key_Z):
# eat the shortcut on the line-edit
return True
return super(Window, self).eventFilter(source, event)
However, as a user, I really **hate** applications that do this kind of thing.
When I use a standard input widget, I expect to be able to use all the
standard keyboard bindings. If they don't work as expected, it just looks like
a bug.
|
Code signing in Mac with Perl scripts compiled with PAR::Packer fails
Question: Does anyone have experience getting compiled Perl binaries to code sign on
OSX? When trying to compile a Perl script in PAR, it returns an error when I
try to code sign it. I've gotten around this error by not trying to code sign
it as a binary (e.g., inside the "Resources" folder within a .app), but if I
put it in the proper MacOS directory it fails on the signature.
I've seen numerous fixes for python scripts
(<https://github.com/kamillus/py2app-pyqt-codesign-fix-os-x>), but not any for
Perl!
The error message reported by codesign -s is "main executable failed strict
validation". I've tried the --deep option as well with no success.
Answer: I've figured out how to fix this. It's a solution that I adapted based on the
Python solution written here:
<https://github.com/pyinstaller/pyinstaller/wiki/Recipe-OSX-Code-Signing>
It's a problem caused by the Mach-O headers. Hopefully this helps someone
else. After running this python script on the PAR executable, it will
codesign.
Some modifications are still required to PAR to get this to run, however,
since PAR looks for the `\nPAR.pm\n` signature at the end of the file... which
now contains the code signature. I have a working solution for that as well,
and can share if others are interested.
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
from macholib._cmdline import main as _main
from macholib.MachO import MachO
from macholib.mach_o import *
ARCH_MAP={
('<', '64-bit'): 'x86_64',
('<', '32-bit'): 'i386',
('>', '64-bit'): 'ppc64',
('>', '32-bit'): 'ppc',
}
def print_file(fp, path):
print(path, file=fp)
exe_data = MachO(path)
for header in exe_data.headers:
seen = set()
if header.MH_MAGIC == MH_MAGIC_64:
sz = '64-bit'
else:
sz = '32-bit'
arch = CPU_TYPE_NAMES.get(header.header.cputype,
header.header.cputype)
print(' [%s endian=%r size=%r arch=%r]' % (header.__class__.__name__,
header.endian, sz, arch), file=fp)
for idx, name, other in header.walkRelocatables():
if other not in seen:
seen.add(other)
print('\t' + other, file=fp)
print('', file=fp)
cmds = exe_data.headers[0].commands # '0' - Exe contains only one architecture.
file_size = exe_data.headers[0].size
linkedit = cmds[3][1] # __LINKEDIT
new_segsize = file_size - linkedit.fileoff
linkedit.filesize = new_segsize
alignment = 4096
linkedit.vmsize = new_segsize + (alignment - (new_segsize % alignment)) # alignment
data = cmds[4][1] # LC_SYMTAB
new_strsize = file_size - data.stroff
data.strsize = new_strsize
# Write changes back.
fp = open(exe_data.filename, 'rb+')
exe_data.write(fp)
fp.close()
print ("Successfully modified headers.\n")
def main():
_main(print_file)
if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
pass
|
Matrix multiplication using slicing. Python
Question: I have the following code:
from numpy import *
a = random.rand(3,4)
b = random.rand(4,2)
c = linspace(0,0,6)
c.shape = (3,2)
for i in range(a.shape[0]):
for j in range(b.shape[1]):
for k in range(b.shape[0]):
c[i][j] += a[i][k] * b[k][j]
for r in c:
print "C = ", r
But I need to change the last (innermost) loop and I need to use slicing. As I
understood I have to do something like this:
for i in range(a.shape[0]):
for j in range(b.shape[1]):
c[i][j] += a[i][0:l-1] * b[0:l-1][j]
But, unfortunately, it doesn't work. Could somebody help me and give a hint
how to do it?
Answer: What you're trying to do here is the dot product of the row vector from `a`,
and the column vector from `b`:
c[i][j] += a[i][0:l-1] * b[0:l-1][j]
which would be
c[i][j] = np.dot(a[i], b[:][j])
which is the same as
sum([a_*b_ for a_,b_ in zip(a[i],b[:][j])])
or
sum(a[i]*b[:][j])
but faster.
However, if you're using `np.dot`, anyways:
c = np.dot(a,b)
is definitely faster.
|
Why I only get the last output in my output file?
Question: I tried to find particular columns based on a list of column's name by using
pandas in python 2.7. For example,
>>>df = pd.read_csv('database.csv')
A,B,C,D,E,F,G # A to G columns in database
1,2,3,4,5,6,7
>>>name_list = pd.read_csv('column_name.csv')
Name # 'Name' is set as index
B # I need B, E and F column
E
F
# code used to select particular columns
result = pd.DataFrame()
for col in df.columns:
if col in name_list.index:
result = df[[col]] # select column based on the given list
result.to_csv('result.csv') # write my result to csv file
The `print result` is fine, I can see column B, E and F, however, the
result.csv file only has the last output (column F)? I have tried to move
`result.to_csv` to different positions but it was still the same.
Does anyone know why?
Answer: You overwrite `result` every time hence the reason you only get the last
result, also you don't need to use a loop this will work:
df[name_list.index].to_csv('result.csv')
Example:
In [21]:
import pandas as pd
import io
temp="""A,B,C,D,E,F,G
1,2,3,4,5,6,7"""
temp1="""Name
B
E
F"""
df = pd.read_csv(io.StringIO(temp))
print(df)
name = pd.read_csv(io.StringIO(temp1), index_col=[0])
name
A B C D E F G
0 1 2 3 4 5 6 7
Out[21]:
Empty DataFrame
Columns: []
Index: [B, E, F]
In [20]:
df[name.index]
Out[20]:
B E F
0 2 5 6
The above shows that it's not necessary to create another df just to get the
columns of interest to write out, once you read in your names you can pass the
index to sub-select the columns of interest from the original df and then
write them out to a csv.
**EDIT**
If you have duplicated entries in your index you can call
[`unique`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.Index.unique.html?highlight=unique#pandas.Index.unique)
to de-duplicate the values:
In [24]:
temp1="""Name
B
B
E
F"""
name = pd.read_csv(io.StringIO(temp1), index_col=[0])
print(name)
df[name.index.unique()]
Empty DataFrame
Columns: []
Index: [B, B, E, F]
Out[24]:
B E F
0 2 5 6
|
AppEngine urlfetch validate_certificate=False/None not being respected
Question: In the AppEngine developer appserver I am getting an error like this:
SSLCertificateError: Invalid and/or missing SSL certificate for URL ...
when I am making a fetch like this to an `https` server with a self-signed
certificate (almost always `localhost` port-forwarded over ssh to a vm):
result = urlfetch.fetch(url=url, method=method, payload=payload,
deadline=DEADLINE, validate_certificate=None)
One would not expect SSL failures for invalid certificates where
`validate_certificate` is `False`, though this is quite possibly a side-effect
of the 2.7.9 policy in Python to always validate ssl certificates.
Note that passing `False` (instead of `None`) for `validate_certificate` does
not work either.
This problem happens on Python 2.7.9-10 via Homebrew/XCode on OS X 10.10.2-4
with AppEngine 1.9.18 through 1.19.26.
There are issues (e.g.
[12096](https://code.google.com/p/googleappengine/issues/detail?id=12096))
about this on Google App Engine, but I am looking for a workaround.
Here's what I've tried to work around this:
1. Add the certificate to the Mac's login keychain (works in the browser, not from Python)
2. Add the certificate to `app-engine-python/lib/cacerts/cacerts.txt` and/or `./lib/cacerts/urlfetch_cacerts.txt` (though this probably requires turning verification _on_ for it to work, since that appears to be the only case where they are used) with e.g.
> $ echo >> /usr/local/share/app-engine-
> python/lib/cacerts/urlfetch_cacerts.txt
>
> $ openssl x509 -subject -in server.crt >> /usr/local/share/app-engine-
> python/lib/cacerts/urlfetch_cacerts.txt
3. Disable ssl HTTPs checking with the [PEP-0476](https://www.python.org/dev/peps/pep-0476/) workaround i.e.
`ssl._create_default_https_context = ssl._create_unverified_context`
at or after `import ssl` (around line 1149) of
[`google/appengine/dist27/python_std_lib/httplib.py`](https://github.com/GoogleCloudPlatform/appengine-
python-vm-
runtime/blob/master/python_vm_runtime/google/appengine/dist27/python_std_lib/httplib.py#L1149)
This is particularly problematic on Mac since downgrading as of XCode 7/OS X
El Capital is no longer a practical option.
A preferable workaround would not involve monkey-patching the AppEngine code
proper every time the development appserver is updated.
* * *
**EDIT**
Note that the Mac builtin OpenSSL certificates are stored in
`/System/Library/OpenSSL`, which is protected with
[SIP/rootlessness](http://apple.stackexchange.com/a/193379/5522), which
frankly is a pain to muck with and a worthwhile feature to keep if we can.
I have verified that the certificate validates by using `openssl s_client
-connect localhost:7500 -CAfile server.pem`.
It's been added to the Keychain and to `/usr/local/etc/openssl/certs` with the
`hash.#` format where the hash comes from `openssl x509 -subject_hash -in
server.pem` (or the homebrew ssl, namely
`/usr/local/Cellar/openssl/1.0.2d_1/bin/openssl`). In which case
`/usr/local/Cellar/openssl/1.0.2d_1/bin/openssl s_client -connect
localhost:7500` verifies the certificate (but python still does not).
I have tried using the homebrew version of python and openssl, but to no
avail. Running the following in Python seems to always fail;
./pve/bin/python -c "import requests; requests.get('https://localhost:7500')"
This also fails where `SSL_CERT_FILE` is set to the server's certificate (i.e.
for added measure one might expect it to work since the `openssl` command
essentially works like this), and also fails where `SSL_CERT_PATH` is set to
`/usr/local/etc/openssl/certs`.
Note, `pve` is a virtual env where `help(ssl)` shows a `FILE` of
`/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py`
Further verifying that homebrew Python's `_ssl.so` links to homebrew's openssl
I ran:
xcrun otool -L
/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-
dynload/_ssl.so
which returns
>
> ./Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-
> dynload/_ssl.so:
>
> /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (compatibility version 1.0.0,
> current version 1.0.0)
>
> /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib (compatibility version
> 1.0.0, current version 1.0.0)
>
> /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version
> 1225.1.1)
If one runs `brew info openssl` it remarks under `CAVEATS`:
> A CA file has been bootstrapped using certificates from the system keychain.
> To add additional certificates, place .pem files in
> /usr/local/etc/openssl/certs
but clearly for some reason python is not using homebrew's openssl algorithm
for finding certificates.
So I remain at a loss as to why Python standard library is not validating
certificates that are in the OpenSSL directory specified in the documents as
well as the Keychain (in both `.pem` and `.p12` formats, with "always trust"
for `Secure Sockets Layer (SSL)`).
Answer: This is a `dev_appserver` bug caused by a `httplib.HTTPSConnection` behavior
change (certificate check turned on by default) in some recent Python release
(I belive 2.7.9).
As the bug is in internal `dev_appserver` code (file
`google_appengine/google/appengine/api/urlfetch_stub.py` of the appengine SDK)
that is run independently of the tested application, there is no way to make a
fix that will survive a SDK update.
The only permanent workaround I can think of will be to enable
`validate_certificate` and add **CA** certificate to the
`urlfetch_cacerts.txt` file. As a temporary fix, you can patch
`urlfetch_stub.py` with workaround #3.
|
Django. ImportError. Cannot import Model
Question: This is weird. I can't find the error. I can't run the server (or anything)
cause I get an error:
ImportError: cannot import name Libro
So these are the models:
perfiles.models.py-
from django.db import models
from django.contrib.auth.models import User
from libros.models import Libro <- WEIRD ERROR ??¡?
class Perfil(models.Model):
usuario = models.OneToOneField(User, null=True)
actualmente_leyendo = models.ForeignKey(Libro, related_name="actualmente_leyendo")
...
libros.models.py -
from django.db import models
from perfiles.models import Perfil
class Libro(models.Model):
titulo = models.CharField(max_length=255, blank=True)
autor = models.CharField(max_length=255, blank=True)
imagen = models.CharField(max_length=255, blank=True)
So, both "libros" and "perfiles" are apps registered on my settings.py and ,
when I open a ´python manage.py shell´ and run ´from libros.models import
Libro´, it works correctly and gives me
(InteractiveConsole)
>>> from libros.models import Libro
>>> Libro
<class 'libros.models.Libro'>
So, where could the error be? and why can the python shell import the model
and the other model can't? Any ideas will be helpfull. Thanks.
Answer: You are having a circular import error. You are trying to import `Libro` in
perfiles.model and you are trying to import `Perfil` in libros.model.
You could use `django.db.models.loading.get_model` to solve this.
You could do something like
from django.db.models.loading import get_model
Libro = get_model('libros', 'Libro')
class Perfil(models.Model):
usuario = models.OneToOneField(User, null=True)
actualmente_leyendo = models.ForeignKey(Libro, related_name="actualmente_leyendo")
Or better yet, don't import the model and just pass a string with the format
`<app>.<model_name>` when referencing models from other apps
class Perfil(models.Model):
usuario = models.OneToOneField(User, null=True)
actualmente_leyendo = models.ForeignKey('libros.Libro', related_name="actualmente_leyendo")
|
python3 - can't pass through autorization
Question: I need to build webcrawler for internal usage and I need to login into
administration area. I'm trying to use requests lib, tried this ways:
import urllib.parse
import requests
base_url = "https://target.url"
data = ({'login': 'login', 'pass': 'password'})
params = urllib.parse.urlencode(data)
r = requests.post(base_url, data=params)
print(r.text)
and
import requests
base_url = "https://target.url"
r = requests.post(base_url, auth=('login', 'password')
print(r.text)
but in both cases r.text returns me login page content same as if I try to get
any other page after auth code:
req = requests.get("https://target.url/smth")
What I lose sight of? I have ideas:
1. chain of hidden redirections from <https://target.url> to real login page, so I send auth info to wrong url
2. I don't send additional required info (like cookies e.g.)
Could you please comment? How can I gather required for login information?
Answer: In my case problem was in 'Referer' parameter in headers, which is required
but wasn't specified
|
Assigning variables and sending to database once all values assigned python
Question: This is my first python script. I am trying to get data from an Arduino, read
it on a Raspberry Pi and save it to the database. The code works separately (I
can assign the variable correctly and send the data to the database but can't
seem to get them both to work. I'm not sure my logic works (setting variables
to null and then saving once they all have values). Thanks for the input.
import re
import serial
import MySQLdb
import time
db =MySQLdb.connect(host = "localhost",user = "root",passwd = "example", db = "arduino")
ser =serial.Serial('/dev/ttyACM0',9600)
humidityPattern = "Humidity\:(\d\d\.\d\d)"
tempDhPattern = "TemperatureDH\:(\d\d\.\d\d)"
barometerPattern = "PressureBMP\:(\d\d\.\d\d)"
tempBmpPattern = "TemperatureBMP\:(\d\d\.\d\d)"
tempTmpPattern = "TemperatureTMP\:(\d\d\.\d\d)"
blLightPattern = "BLLight\:(\d+)"
brLightPattern = "BRLight\:(\d+)"
frLightPattern = "FRLight\:(\d+)"
flLightPattern = "FLLight\:(\d+)"
while 1:
line = ser.readline()
humidity = None
tempDh = None
pressure = None
tempBmp = None
tempTmp = None
blLight = None
brLight = None
frLight = None
flLight = None
#Humidity Sensor
m = re.match(humidityPattern, line)
if m is not None:
humidity = m.group(1)
print "Humidity is "+humidity
m = re.match(tempDhPattern, line)
if m is not None:
tempDh= m.group(1)
print "Humidity Temp is "+tempDh
#Pressure Sensor
m = re.match(barometerPattern, line)
if m is not None:
pressure = m.group(1)
print "Pressure is "+tempDh
m = re.match(tempBmpPattern, line)
if m is not None:
tempBmp= m.group(1)
print "Pressure Temp is "+tempBmp
#Temp Sensor
m = re.match(tempTmpPattern, line)
if m is not None:
tempTmp= m.group(1)
print "Temp is "+tempTmp
#Light Sensors
m = re.match(blLightPattern, line)
if m is not None:
blLight= m.group(1)
print "BL Light is "+ blLight
m = re.match(brLightPattern, line)
if m is not None:
brLight= m.group(1)
print "BR Light is "+ brLight
m = re.match(frLightPattern, line)
if m is not None:
frLight = m.group(1)
print "FR Light is "+ frLight
m = re.match(flLightPattern, line)
if m is not None:
flLight = m.group(1)
print "FL Light is "+ flLight
if humidity and tempDh and pressure and tempBmp and tempTmp and blLight and brLight and frLight and flLight is not None:
with db:
cur = db.cursor()
cur.execute('insert into weather(humidity, temp_dh, pressure,temp_bmp, temp_tmp, bl_light, br_light, fr_light, fl_light) values("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")'%(humidity, tempDh, pressure, tempBmp, tempTmp, blLight, brLight, frLight, flLight ))
time.sleep(5)
print 'upload'
Answer: One problem is in the test:
if humidity and tempDh and pressure and tempBmp and tempTmp and blLight and brLight and frLight and flLight is not None:
which only tests for `None` the very last variable, `flLight`. However if, as
it seems, all the others are either `None` or a non-empty string, this
**should** accidentally work because `None` is falsy and every non-empty
string is truthy.
So a bigger problem is that every time through the loop you're throwing away
every value you've previously read, whether you've saved them or not.
To fix **that** , add a boolean flag `must_init` and change the logic to
something like, at the start of your loop:
must_init = True while True: line = ser.readline() if must_init: humidity =
None tempDh = None pressure = None tempBmp = None tempTmp = None blLight =
None brLight = None frLight = None flLight = None must_init = False
and set `must_init = True` again only at the very end within the `with`
statement right after the now-final `print 'upload'`.
This way, you will null out all variables only (A) the first time or (B) right
after saving their previous values to the DB, which seems to be more correct
logic.
Other simplifying improvements are possible (e.g keep the variables as items
in a dict, so you don't have to enumerate them in the `any` check; have the RE
expression also in a dict keyed by the same name you use in the variables dict
to enormously compact and simplify your code) but the key point is that the
code with the addition of the `must_init` boolean flag as I suggest before
should **work** \-- you can improve it after!-)
|
Merge multiple csv files and add a new column
Question: I have a bunch of csv files that i need to merge into one file but with an
additional date column
xxxxx20150216.csv
xxxxx20130802.csv
xxxxx20130803.csv
xxxxx20130804.csv
I am using the following code from
(<http://cbrownley.wordpress.com/2014/03/09/pythons-voracious-glob-module/>)
to merge them
import csv
import glob
import os
import sys
data_path = ""
outfile_path = "alldata.csv"
filewriter = csv.writer(open(outfile_path,'wb'))
file_counter = 0
for input_file in glob.glob(os.path.join(data_path,'*.csv')):
with open(input_file,'rU') as csv_file:
filereader = csv.reader(csv_file)
if file_counter < 1:
for row in filereader:
filewriter.writerow(row)
else:
header = next(filereader,None)
for row in filereader:
filewriter.writerow(row)
file_counter += 1
But now I need to extract the date from the filename and add it as column
along with the other rows. What could be the easiest way to accomplish this?
Answer: What about...:
with open(input_file,'rU') as csv_file:
filereader = csv.reader(csv_file)
name, ext = os.path.splitext(input_file)
date = name[-8:]
if file_counter < 1:
for i, row in enumerate(filereader):
if i==0: row.append('Date')
else: row.append(date)
filewriter.writerow(row)
else:
header = next(filereader,None)
for row in filereader:
row.append(date)
filewriter.writerow(row)
The only tricky part is taking the headers from the first CSV file!-)
|
Python program that stops looping and gets stuck randomly
Question: I've been trying hard to learn Python for some time now and I'm stuck trying
to make this simple program work.
As you can see, what I'm trying to do is get 4 values to 'battle' until one is
left. It goes fine and dandy until anywhere from loop #11 to #22, and then it
just stops. I'm a complete beginner, and dont know what I'm doing wrong.
import random
import math
import os
print ' ----------------------------------'
print ' UNIVERSAL ALL-STARS DEATHMATCH'
print ' ----------------------------------'
print ''
print 'CHOOSE FOUR CHARACTERS TO FIGHT IN AN FFA DEATHMATCH!'
print ''
#User input for character names.
characterInputted = False
while characterInputted == False:
character1 = raw_input('Input Character 1 Name:')
character2 = raw_input('Input Character 2 Name:')
character3 = raw_input('Input Character 3 Name:')
character4 = raw_input('Input Character 4 Name:')
if character1 == character2:
print 'Cannot have any characters with identical names!'
characterInputted = False
elif character1 == character3:
print 'Cannot have any characters with identical names!'
characterInputted = False
elif character1 == character4:
print 'Cannot have any characters with identical names!'
characterInputted = False
elif character2 == character3:
print 'Cannot have any characters with identical names!'
characterInputted = False
elif character2 == character4:
print 'Cannot have any characters with identical names!'
characterInputted = False
elif character3 == character4:
print 'Cannot have any characters with identical names!'
characterInputted = False
else:
characterInputted = True
def combat_roll():
combatValid = False
while combatValid == False:
rollAtk = random.randint(1, 4)
rollDef = random.randint(1, 4)
if rollAtk == rollDef:
combatValid = False
#Roll for char1
elif rollAtk == character1_Number:
if character1_Dead == True:
combatValid = False
elif rollDef == character2_Number:
if character2_Dead == True:
combatValid = False
else:
rollAttacker = character1
rollDefender = character2
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character3_Number:
if character3_Dead == True:
combatValid = False
else:
rollAttacker = character1
rollDefender = character3
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character4_Number:
if character4_Dead == True:
combatValid = False
else:
rollAttacker = character1
rollDefender = character4
combatValid = True
return rollAttacker, rollDefender
#Roll for char2
elif rollAtk == character2_Number:
if character2_Dead == True:
combatValid = False
elif rollDef == character1_Number:
if character1_Dead == True:
combatValid = False
else:
rollAttacker = character2
rollDefender = character1
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character3_Number:
if character3_Dead == True:
combatValid = False
else:
rollAttacker = character2
rollDefender = character3
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character4_Number:
if character4_Dead == True:
combatValid = False
else:
rollAttacker = character2
rollDefender = character4
combatValid = True
return rollAttacker, rollDefender
#Roll for char3
elif rollAtk == character3_Number:
if character1_Dead == True:
combatValid = False
elif rollDef == character1_Number:
if character2_Dead == True:
combatValid = False
else:
rollAttacker = character3
rollDefender = character1
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character2_Number:
if character2_Dead == True:
combatValid = False
else:
rollAttacker = character3
rollDefender = character2
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character4_Number:
if character4_Dead == True:
combatValid = False
else:
rollAttacker = character3
rollDefender = character4
combatValid = True
return rollAttacker, rollDefender
#Roll for char4
elif rollAtk == character4_Number:
if character1_Dead == True:
combatValid = False
elif rollDef == character1_Number:
if character1_Dead == True:
combatValid = False
else:
rollAttacker = character4
rollDefender = character1
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character2_Number:
if character2_Dead == True:
combatValid = False
else:
rollAttacker = character4
rollDefender = character2
combatValid = True
return rollAttacker, rollDefender
elif rollDef == character3_Number:
if character3_Dead == True:
combatValid = False
else:
rollAttacker = character4
rollDefender = character3
combatValid = True
return rollAttacker, rollDefender
else:
combatValid = False
#Roundtick set to zero
roundNumber = 0
#Characters randomly generated stats.
character1_Attackbonus = random.randint(0, 2)
character1_Number = 1
character1_Dead = False
character1_LifeCount = 1
character2_Attackbonus = random.randint(0, 2)
character2_Number = 2
character2_Dead = False
character2_LifeCount = 1
character3_Attackbonus = random.randint(0, 2)
character3_Number = 3
character3_Dead = False
character3_LifeCount = 1
character4_Attackbonus = random.randint(0, 2)
character4_Number = 4
character4_Dead = False
character4_LifeCount = 1
gameover = False
while gameover == False:
os.system('cls')
lifeCount_Total = [character1_LifeCount +
character2_LifeCount + character3_LifeCount +
character4_LifeCount]
roundNumber = roundNumber + 1
print 'Round #%d!' % roundNumber
raw_input('Press ENTER to continue.')
attackChance = random.randint(0, 10)
if lifeCount_Total > 2 == True:
gameover = True
elif attackChance < 3:
print "No one attacked this round!"
elif attackChance > 3:
Attacker, Defender = combat_roll()
print Attacker + ' attacked ' + Defender + '.'
Attackbase = random.randint(0, 10)
#Combat calculations!
combatCalc = False
while combatCalc == False:
if Attacker == character1:
AttackTotal = Attackbase + character1_Attackbonus
if Defender == character2:
if AttackTotal > 5:
character2_Dead = True
character2_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character3:
if AttackTotal > 5:
character3_Dead = True
character3_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character4:
if AttackTotal > 5:
character4_Dead = True
character4_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Attacker == character2:
AttackTotal = Attackbase + character2_Attackbonus
if Defender == character1:
if AttackTotal > 5:
character1_Dead = True
character1_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character3:
if AttackTotal > 5:
character3_Dead = True
character3_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character4:
if AttackTotal > 5:
character4_Dead = True
character4_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Attacker == character3:
AttackTotal = Attackbase + character3_Attackbonus
if Defender == character1:
if AttackTotal > 5:
character1_Dead = True
character1_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character2:
if AttackTotal > 5:
character2_Dead = True
character2_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character4:
if AttackTotal > 5:
character4_Dead = True
character4_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Attacker == character4:
AttackTotal = Attackbase + character4_Attackbonus
if Defender == character1:
if AttackTotal > 5:
character1_Dead = True
character1_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character2:
if AttackTotal > 5:
character2_Dead = True
character2_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
elif Defender == character3:
if AttackTotal > 5:
character3_Dead = True
character3_LifeCount = 0
print '%s killed %s!' % (Attacker, Defender)
combatCalc = True
else:
print '%s failed to kill %s!' % (Attacker, Defender)
combatCalc = True
else:
combatCalc = False
else:
gameover = False
print character1
print character2
print character3
print character4
Answer: I tested your code and it seems that it doesn't stop but enter in the function
`combat_roll()` and is stuck in it. If I print `combatValid`, I obtain :
`false
false
false
...
|
Creating a line plot in python using data from a-for loop
Question: I have some previous code which will print out
'The number for january is x' - etc, throughout one year.
I'm trying to plot the x vs the months using this:
import matplotlib.pyplot as plt
for m, n in result.items():
print 'The number for', m, "is", n
plt.plot([n])
plt.ylabel('Number')
plt.xlabel('Time (Months)')
plt.title('Number per month')
plt.show()
Where m is the month (also the file name it reads from and n is the x value
(number).
However when I run this I just get a blank graph - I think I may be missing
somethhing major out?
Result contains:
{'apr': 13, 'jun': 13, 'jul': 13, 'aug': 13, 'sep': 13, 'oct': 13} x 6 times
For practical purposes I made each file have a number of 13 as the real files
are enormous
Answer:
import matplotlib.pyplot as plt
import numpy as np
result = {'apr': 13, 'jun': 13, 'jul': 13, 'aug': 13, 'sep': 13, 'oct': 13}
for m, n in result.items():
print 'The number for', m, "is", n
plt.plot(result.values())
plt.ylabel('Number')
plt.xlabel('Time (Months)')
plt.title('Number per month')
plt.xticks(range(len(result)), result.keys())
plt.show()
So what I have done here is to just remove the plotting section outside the
`for` loop. Now you will get your results printed as you have been doing
previously, but the plotting will be done for all the values once.
You can take out the values from a dictionary using `dict.values`, in our case
gives us all the many values which are `13`.

|
'utf-8' codec can't decode byte reading a file in Python3.4 but not in Python2.7
Question: I was trying to read a file in python2.7, and it was readen perfectly. The
problem that I have is when I execute the same program in Python3.4 and then
appear the error:
'utf-8' codec can't decode byte 0xf2 in position 424: invalid continuation byte'
Also, when I run the program in Windows (with python3.4), the error doesn't
appear. The first line of the document is: `Codi;Codi_lloc_anonim;Nom`
and the code of my program is:
def lectdict(filename,colkey,colvalue):
f = open(filename,'r')
D = dict()
for line in f:
if line == '\n': continue
D[line.split(';')[colkey]] = D.get(line.split(';')[colkey],[]) + [line.split(';')[colvalue]]
f.close
return D
Traduccio = lectdict('Noms_departaments_centres.txt',1,2)
Answer: In Python2,
f = open(filename,'r')
for line in f:
reads lines from the file _as bytes_.
In Python3, the same code reads lines from the file _as strings_. Python3
strings are what Python2 call `unicode` objects. These are bytes decoded
according to some encoding. The default encoding in Python3 is `utf-8`.
The error message
'utf-8' codec can't decode byte 0xf2 in position 424: invalid continuation byte'
shows Python3 is trying to decode the bytes as `utf-8`. Since there is an
error, the file apparently does not contain _`utf-8` encoded bytes_.
To fix the problem you need to **specify the correct encoding** of the file:
with open(filename, encoding=enc) as f:
for line in f:
If you do not know the correct encoding, you could run this program to simply
try all the encodings known to Python. If you are lucky there will be an
encoding which turns the bytes into recognizable characters. Sometimes more
than one encoding may _appear_ to work, in which case you'll need to check and
compare the results carefully.
# Python3
import pkgutil
import os
import encodings
def all_encodings():
modnames = set(
[modname for importer, modname, ispkg in pkgutil.walk_packages(
path=[os.path.dirname(encodings.__file__)], prefix='')])
aliases = set(encodings.aliases.aliases.values())
return modnames.union(aliases)
filename = '/tmp/test'
encodings = all_encodings()
for enc in encodings:
try:
with open(filename, encoding=enc) as f:
# print the encoding and the first 500 characters
print(enc, f.read(500))
except Exception:
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.