title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Extracting specific information from data | 39,928,277 | <p>How can i convert a data format like: </p>
<pre><code>James Smith was born on November 17, 1948
</code></pre>
<p>into something like </p>
<pre><code>("James Smith", DOB, "November 17, 1948")
</code></pre>
<p>without having to rely on positional index of strings</p>
<p>I have tried the following </p>
<pre><code>from nltk import word_tokenize, pos_tag
new = "James Smith was born on November 17, 1948"
sentences = word_tokenize(new)
sentences = pos_tag(sentences)
grammar = "Chunk: {<NNP*><NNP*>}"
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentences)
print(result)
</code></pre>
<p>How to proceed further to get the output in desired fromat.</p>
| 2 | 2016-10-08T03:06:32Z | 39,928,842 | <p>Split the string with 'was born on' after that trim the spaces and assign to name and dob</p>
| 2 | 2016-10-08T05:00:18Z | [
"python",
"python-3.x",
"nltk",
"stanford-nlp",
"information-retrieval"
] |
Extracting specific information from data | 39,928,277 | <p>How can i convert a data format like: </p>
<pre><code>James Smith was born on November 17, 1948
</code></pre>
<p>into something like </p>
<pre><code>("James Smith", DOB, "November 17, 1948")
</code></pre>
<p>without having to rely on positional index of strings</p>
<p>I have tried the following </p>
<pre><code>from nltk import word_tokenize, pos_tag
new = "James Smith was born on November 17, 1948"
sentences = word_tokenize(new)
sentences = pos_tag(sentences)
grammar = "Chunk: {<NNP*><NNP*>}"
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentences)
print(result)
</code></pre>
<p>How to proceed further to get the output in desired fromat.</p>
| 2 | 2016-10-08T03:06:32Z | 39,930,029 | <p>You could always use a regular expressions.
The regex <code>(\S+)\s(\S+)\s\bwas born on\b\s(\S+)\s(\S+),\s(\S+)</code> will match and return data from specifically the string format above.</p>
<p>Here's it in action: <a href="https://regex101.com/r/W2ykKS/1" rel="nofollow">https://regex101.com/r/W2ykKS/1</a></p>
<p>Regex in python:</p>
<pre><code>import re
regex = r"(\S+)\s(\S+)\s\bwas born on\b\s(\S+)\s(\S+),\s(\S+)"
test_str = "James Smith was born on November 17, 1948"
matches = re.search(regex, test_str)
# group 0 in a regex is the input string
print(matches.group(1)) # James
print(matches.group(2)) # Smith
print(matches.group(3)) # November
print(matches.group(4)) # 17
print(matches.group(5)) # 1948
</code></pre>
| 1 | 2016-10-08T07:50:26Z | [
"python",
"python-3.x",
"nltk",
"stanford-nlp",
"information-retrieval"
] |
printing HTML and inserting variables using python-flask | 39,928,289 | <p>Im trying to print html code that will also include variables, in this case its data from database with this code:</p>
<pre><code>def displayHot():
myCursor = mongo.db.posts.find()
for result_object in myCursor:
print'''
Content-Type: text/html
<div class="card-header">
<h3 %s
</h3>
</div>
<div class="card-block">
<p> %s
</p>
<a class="panel-google-plus-image" href="{{url_for('Images', filename = 'Images/%s')}}"
</a>
</div"
''' % (result_object['uploader'], result_object['description'], result_object['file_name'])
</code></pre>
<p>and rendering it here:</p>
<pre><code>@app.route('/', methods=['POST','GET'])
def home():
if request.method == 'GET':
return render_template('index.html', function = displayHot())
</code></pre>
<p>when i run it, i get the printed data in my cmd.. so my question is how can i print the html code so it will act as html code and not just a print command in cmd</p>
| 0 | 2016-10-08T03:08:00Z | 39,929,939 | <p>It looks like you would be better served by doing your looping in a jinja template, and just sending the template the data for the loop. Something like this is what I'm thinking:</p>
<h3>Python code</h3>
<pre><code>@app.route('/', methods=['POST','GET'])
def home():
if request.method == 'GET':
myCursor = mongo.db.posts.find()
return render_template('index.html', cursor = myCursor)
</code></pre>
<h3>index.html</h3>
<pre><code><!-- your other code here -->
{% for result_object in cursor %}
<div class="card-header">
<h3> {{result_object['uploader']}}
</h3>
</div>
<div class="card-block">
<p> {{result_object['description']}}
</p>
<a class="panel-google-plus-image" href="{{url_for('Images', filename = '''Images/result_object['file_name']''')}}"
</a>
</div>
{% endfor %}
<!-- the rest of your html -->
</code></pre>
<p>This is simplified, and you would likely need to do more in order to get <code>myCursor</code> set up properly before sending it to the template, but I hope that gets the idea across.</p>
| 0 | 2016-10-08T07:37:11Z | [
"python",
"html",
"flask",
"pymongo"
] |
How to subtract a constant from members of a sublist? | 39,928,297 | <p>I know I can subtract a constant from all members of a simple list like this:</p>
<pre><code>l = [ 123, 124, 125, 126 ]
l = [v - 100 for v in l]
</code></pre>
<p>But how can I subtract a constant from one or more specific members of each sublist within a list?</p>
<p>Suppose I have:</p>
<pre><code>l = [ [101, 102, 103], [111, 122, 133], [222, 333, 444] ]
</code></pre>
<p>I want to subtract, say, 100 from the 2nd and 3rd elements of each sublist, to give me:</p>
<pre><code>[ [101, 2, 3], [111, 22, 33], [222, 233, 344] ]
</code></pre>
<p>Is there a straightforward Pythonic way to do this?</p>
| 0 | 2016-10-08T03:10:49Z | 39,928,335 | <p>In a simplest form, you can unpack the sublists and apply the operation to the desired items:</p>
<pre><code>In [1]: l = [ [101, 2, 3], [111, 22, 33], [222, 233, 344] ]
In [2]: [[x, y - 100, z - 100] for x, y, z in l]
Out[2]: [[101, -98, -97], [111, -78, -67], [222, 133, 244]]
</code></pre>
<p>Or, a bit more scalable approach would be to have a nested list comprehension:</p>
<pre><code>In [3]: [[item[0]] + [x - 100 for x in item[1:]] for item in l]
Out[3]: [[101, -98, -97], [111, -78, -67], [222, 133, 244]]
</code></pre>
| 1 | 2016-10-08T03:19:10Z | [
"python",
"list-comprehension"
] |
How to subtract a constant from members of a sublist? | 39,928,297 | <p>I know I can subtract a constant from all members of a simple list like this:</p>
<pre><code>l = [ 123, 124, 125, 126 ]
l = [v - 100 for v in l]
</code></pre>
<p>But how can I subtract a constant from one or more specific members of each sublist within a list?</p>
<p>Suppose I have:</p>
<pre><code>l = [ [101, 102, 103], [111, 122, 133], [222, 333, 444] ]
</code></pre>
<p>I want to subtract, say, 100 from the 2nd and 3rd elements of each sublist, to give me:</p>
<pre><code>[ [101, 2, 3], [111, 22, 33], [222, 233, 344] ]
</code></pre>
<p>Is there a straightforward Pythonic way to do this?</p>
| 0 | 2016-10-08T03:10:49Z | 39,928,365 | <p>If you really want a one-liner, try:</p>
<pre><code>l = map(lambda x : x[0:1]+map(lambda y: y-100, x[1:3])+x[3:], l)
</code></pre>
<p>Python has some nice syntax for very simple things, but for something like this you're best off using functionals or loops.</p>
| 0 | 2016-10-08T03:24:39Z | [
"python",
"list-comprehension"
] |
How to subtract a constant from members of a sublist? | 39,928,297 | <p>I know I can subtract a constant from all members of a simple list like this:</p>
<pre><code>l = [ 123, 124, 125, 126 ]
l = [v - 100 for v in l]
</code></pre>
<p>But how can I subtract a constant from one or more specific members of each sublist within a list?</p>
<p>Suppose I have:</p>
<pre><code>l = [ [101, 102, 103], [111, 122, 133], [222, 333, 444] ]
</code></pre>
<p>I want to subtract, say, 100 from the 2nd and 3rd elements of each sublist, to give me:</p>
<pre><code>[ [101, 2, 3], [111, 22, 33], [222, 233, 344] ]
</code></pre>
<p>Is there a straightforward Pythonic way to do this?</p>
| 0 | 2016-10-08T03:10:49Z | 39,928,382 | <pre><code>map(lambda x:map(lambda y: y if x.index(y)==0 else y-100,x),l)
</code></pre>
| 0 | 2016-10-08T03:28:21Z | [
"python",
"list-comprehension"
] |
python error TypeError: not all arguments converted during string formatting | 39,928,298 | <p>Been starring at this too long and I think I missed something dumb..
Writing a script to write information to a file. All the variables are strings being passed in from another function to write a file.</p>
<p>Here's my code: </p>
<pre><code> 53 def makeMainTF():
54 NameTag,mcGroupTag,mcIPTag = makeNameMCTag()
55 yourName = getAccessSecretName()
56 instanceType ="t2.micro"
57 with open ("vlslabMain.tf","w") as text_file:
58 text_file.writelines(['provider \"aws\" {\n',
59 ' ',
60 'access_key = \"${var.access_key}\"\n',
61 ' ',
62 'secret_key = \"${var.secret_key}\"\n',
63 ' ',
64 'region = \"${var.access_key}\"\n',
65 '}\n\n\n',
66 'resource \"aws_instance\" \"example\" {\n',
67 ' ',
68 'ami = \"${lookup(var.amis, var.region)}\"\n',
69 ' ',
70 'instance_type = \"%s\" \n}' % instanceType,
71 '\n\n\n\n',
72 'tags {\n',
73 ' ',
74 'Name = \"%s\"\n' % NameTag,
75 ' ',
76 'Multicast = \"%s,%s\"' % (mcGroupTag,mcIPTag),
77 ' ',
78 'Owner = \"%s\"' % yourName,
79 '\n}'])
</code></pre>
<p>Not sure why I'm getting this error :</p>
<pre><code>Enter Access Key: asd
Enter Secret Key: asd
Enter your name: asd
Access Key: asd
Secret Key: asd
Your full name is: asd
Traceback (most recent call last):
File "terraTFgen.py", line 86, in <module>
makeMainTF()
File "terraTFgen.py", line 78, in makeMainTF
'Owner = \"%s\"' % yourName,
TypeError: not all arguments converted during string formatting
</code></pre>
<p>Maybe I've been starring at it too long but I dont see the syntax mistake.</p>
<p>It actually wrote out </p>
<pre><code>Enter Access Key: asd
Enter Secret Key: asd
Enter your name: asd
Access Key: asd
Secret Key: asd
Your full name is: asd
</code></pre>
<p>But the error is causing the script not to write to the actual file.</p>
<p>Thanks for the help!
****edit***</p>
<p>This is the function I used to get the yourName variable</p>
<pre><code> 3 def getAccessSecretName():
4 access_key = raw_input("Enter Access Key: ")
5 secret_key = raw_input("Enter Secret Key: ")
6 yourName = raw_input("Enter your name: ")
7 print "Access Key: %s" % access_key
8 print "Secret Key: %s" % secret_key
9 print "Your full name is: %s" % yourName
10 return access_key, secret_key, yourName
</code></pre>
| 1 | 2016-10-08T03:10:55Z | 39,928,369 | <p>Replace line 78 with the following and try - </p>
<pre><code>'Owner = \"%s\"' % " ".join(yourName),
</code></pre>
<p>Effectively, yourname seems to be a tuple.<br>
The above code will convert it to a string value.</p>
<p>EDIT :- (Answer to the OP's last comment) </p>
<p>Look at line 10 of <code>getAccessSecretName()</code> function - </p>
<pre><code>return access_key, secret_key, yourName
</code></pre>
<p>It returns a <strong><em>tuple</em></strong> of <em>access_key, secret_key, and yourName</em>.</p>
<p>So if you want only <code>yourName</code> to be written to your file, </p>
<p>(Option 1)</p>
<p>Replace line 55 in function <code>getAccessSecretName()</code> with</p>
<pre><code>access_key, secret_key, yourName = getAccessSecretName()
</code></pre>
<p>This way you the three values are unpacked to different variables,</p>
<p>and replace line 78 with the following -</p>
<pre><code>'Owner = \"%s\"' % yourName
</code></pre>
<p>EDIT 2 (Option II)</p>
<p>If you are only interested in <code>yourName</code> variable you can also do
something like </p>
<pre><code>yourName = getAccessSecretName()[2]
</code></pre>
<p>Replace line 55 with the above line. Here you will be copying the value of the tuple at a specific position to the variable <code>yourName</code> and ignoring other values.</p>
| 1 | 2016-10-08T03:25:35Z | [
"python"
] |
How can I add some strings to a list that already exists in Python? | 39,928,316 | <pre><code>list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
</code></pre>
<p>the out put I want is</p>
<pre><code>print(list1)
>> ['1','2','3','4','5']
>> ['1','2','3','4','6']
</code></pre>
<p>I tried many other things, but I couldn't get the result I want..
I also searched other Q&As to find the way, but I couldn't find as well..
Thanks for your help!</p>
| -3 | 2016-10-08T03:15:49Z | 39,928,360 | <p>Use extend to add a list to another list, append to add a element to a list.</p>
<pre><code>list1.extend(input_list)
list1.append('5')
list1.append('6')
</code></pre>
| 1 | 2016-10-08T03:23:41Z | [
"python",
"arrays",
"list"
] |
How can I add some strings to a list that already exists in Python? | 39,928,316 | <pre><code>list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
</code></pre>
<p>the out put I want is</p>
<pre><code>print(list1)
>> ['1','2','3','4','5']
>> ['1','2','3','4','6']
</code></pre>
<p>I tried many other things, but I couldn't get the result I want..
I also searched other Q&As to find the way, but I couldn't find as well..
Thanks for your help!</p>
| -3 | 2016-10-08T03:15:49Z | 39,928,373 | <p>You can just concatenate two lists by adding them <code>[1,2]+[3]</code> will result in <code>[1,2,3]</code> you can use the extend or append methods as well </p>
| 1 | 2016-10-08T03:26:38Z | [
"python",
"arrays",
"list"
] |
How can I add some strings to a list that already exists in Python? | 39,928,316 | <pre><code>list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
</code></pre>
<p>the out put I want is</p>
<pre><code>print(list1)
>> ['1','2','3','4','5']
>> ['1','2','3','4','6']
</code></pre>
<p>I tried many other things, but I couldn't get the result I want..
I also searched other Q&As to find the way, but I couldn't find as well..
Thanks for your help!</p>
| -3 | 2016-10-08T03:15:49Z | 39,928,510 | <p>How about this</p>
<pre><code>import copy
list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
output = []
for e in input_list:
l = copy.copy(list1)
l.append(e)
output.append(l)
print(output)
</code></pre>
<p>Result</p>
<pre><code>[['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '6']]
</code></pre>
<p>The trick is <code>copy()</code> to make a new list</p>
| 1 | 2016-10-08T03:54:49Z | [
"python",
"arrays",
"list"
] |
How can I add some strings to a list that already exists in Python? | 39,928,316 | <pre><code>list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
</code></pre>
<p>the out put I want is</p>
<pre><code>print(list1)
>> ['1','2','3','4','5']
>> ['1','2','3','4','6']
</code></pre>
<p>I tried many other things, but I couldn't get the result I want..
I also searched other Q&As to find the way, but I couldn't find as well..
Thanks for your help!</p>
| -3 | 2016-10-08T03:15:49Z | 39,928,662 | <p>As an alternitive to @Kenji's soultion, you could use a simple one-liner:</p>
<pre><code>res = [list1+[i] for i in input_list]
</code></pre>
<p>Full program:</p>
<pre><code>list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
res = [list1+[i] for i in input_list]
print(res) # prints: [['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '6']]
</code></pre>
| 1 | 2016-10-08T04:25:08Z | [
"python",
"arrays",
"list"
] |
TkInter: Can't fill a Frame with another widget | 39,928,343 | <p>First time with TkInter. According to what I've read, you can use Frame widgets to hold other widgets. So, I laid down some preview Frames as such:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
TextFrame = tk.Frame(root, width=200, height=600, bg="red")
TextFrame.pack(side="left")
ListFrame = tk.Frame(root, width=800, height=600, bg="blue")
ListFrame.pack(side="right")
</code></pre>
<p>However, when I add a widget and tell it to fill the Frame, it simply replaces the frame instead of expanding to fill the area. Test code used:</p>
<pre><code>ListBox = tk.Listbox(ListFrame, selectmode="single", bg="#545454", fg="#d9d9d9")
for X in range(20):
ListBox.insert('end', X)
ListBox.pack(fill='both', expand=True)
</code></pre>
<p>The same test code expands properly if I set the parent to the main 'root' object. Example:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
root.geometry("1000x600")
ListBox = tk.Listbox(root, selectmode="single", bg="#545454", fg="#d9d9d9")
for X in range(20):
ListBox.insert('end', X)
ListBox.pack(side="right", fill='both', expand=True)
TextBox = tk.Message(root, text="A bunch of text", width=100)
TextBox.pack(side="left", fill="y")
</code></pre>
<p>Am I doing something wrong, here?</p>
| 0 | 2016-10-08T03:21:23Z | 39,929,031 | <p>Frames are like elastics, they grip their content.
You could add:</p>
<pre><code>ListFrame.pack_propagate(False)
</code></pre>
<p>to switch off that behavior</p>
| 0 | 2016-10-08T05:31:48Z | [
"python",
"tkinter"
] |
TkInter: Can't fill a Frame with another widget | 39,928,343 | <p>First time with TkInter. According to what I've read, you can use Frame widgets to hold other widgets. So, I laid down some preview Frames as such:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
TextFrame = tk.Frame(root, width=200, height=600, bg="red")
TextFrame.pack(side="left")
ListFrame = tk.Frame(root, width=800, height=600, bg="blue")
ListFrame.pack(side="right")
</code></pre>
<p>However, when I add a widget and tell it to fill the Frame, it simply replaces the frame instead of expanding to fill the area. Test code used:</p>
<pre><code>ListBox = tk.Listbox(ListFrame, selectmode="single", bg="#545454", fg="#d9d9d9")
for X in range(20):
ListBox.insert('end', X)
ListBox.pack(fill='both', expand=True)
</code></pre>
<p>The same test code expands properly if I set the parent to the main 'root' object. Example:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
root.geometry("1000x600")
ListBox = tk.Listbox(root, selectmode="single", bg="#545454", fg="#d9d9d9")
for X in range(20):
ListBox.insert('end', X)
ListBox.pack(side="right", fill='both', expand=True)
TextBox = tk.Message(root, text="A bunch of text", width=100)
TextBox.pack(side="left", fill="y")
</code></pre>
<p>Am I doing something wrong, here?</p>
| 0 | 2016-10-08T03:21:23Z | 39,932,656 | <p>It's impossible to say what the right answer is since your question doesn't explain exactly the look and behavior that you're wanting to achieve.</p>
<p>By default, widgets shrink or expand to fit their contents. 99.9% of the time this is exactly the right thing, and lets to UIs that are very responsive to the change (different fonts, different resolutions, different window sizes, etc.). In your case, the listbox doesn't <em>replace</em> the frame. Instead, the frame is simply shrinking to fit the listbox.</p>
<p>It is doing this because you didn't tell it to do anything different. When you placed the frame in the root window, you didn't tell tkinter that you wanted the frame to fill the window. You've just sort-of left it to float at the top, which gives it the freedom to grow or shrink to fit its contents.</p>
<p>By giving proper attributes to <code>TextFrame.pack(side="left")</code> you can have that frame fill the window, and therefore prevent it from shrinking to fit its children.</p>
<pre><code>TextFrame.pack(side="left". fill="both", expand=True)
</code></pre>
<p>Of course, that assumes you want the frame (and thus, the text widget it contains) to fill the window. If you are putting other windows around it, that may change which options you want to use. </p>
| 0 | 2016-10-08T12:59:17Z | [
"python",
"tkinter"
] |
Python member variable as parameter | 39,928,345 | <p>I have a class A with a member function a. I have a parameter p with default value. I want this default value to be the member variable of the class.</p>
<pre><code>class A:
def a(self, p = self.b):
print p
</code></pre>
<p>However it crashed with the information:</p>
<pre><code><ipython-input-2-a0639d7525d3> in A()
1 class A:
----> 2 def a(self, p = self.b):
3 print p
4
NameError: name 'self' is not defined
</code></pre>
<p>I want to know whether I can pass a member variable as a default parameter to the member function?</p>
| 1 | 2016-10-08T03:21:27Z | 39,928,371 | <p>One option would be to set the default <code>p</code> value as <code>None</code> and check its value in the method itself:</p>
<pre><code>class A:
def __init__(self, b):
self.b = b
def a(self, p=None):
if p is None:
p = self.b
print(p)
</code></pre>
<p>Demo:</p>
<pre><code>In [1]: class A:
...: def __init__(self, b):
...: self.b = b
...:
...: def a(self, p=None):
...: if p is None:
...: p = self.b
...: print(p)
...:
In [2]: a = A(10)
In [3]: a.a()
10
In [4]: a.a(12)
12
</code></pre>
| 3 | 2016-10-08T03:25:50Z | [
"python",
"function",
"class",
"variables",
"default-value"
] |
sqlalchemy JSON query rows without a specific key (Key existence) | 39,928,463 | <p>When using sqlalchemy with postgresql, I have the following table and data:</p>
<pre><code> id | data
----+----------
1 | {}
2 | {"a": 1}
(2 rows)
</code></pre>
<p>How do I find row(s) that does not have a key. e.g. "a" or data["a"]?</p>
<pre><code>Give me all objects that does not have the key a.
id | data
----+----------
1 | {}
(1 row)
</code></pre>
<hr>
<pre><code>self.session.query(Json_test).filter(???)
</code></pre>
| 0 | 2016-10-08T03:47:06Z | 39,933,596 | <p>If the column type is <code>jsonb</code> you can use <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB" rel="nofollow"><code>has_key</code></a>:</p>
<pre><code>session.query(Json_test).filter(sqlalchemy.not_(Json_test.data.has_key('a')))
</code></pre>
<p>For both <code>json</code> and <code>jsonb</code> types this should work:</p>
<pre><code>session.query(Json_test).filter(Json_test.data.op('->')('a')==None)
</code></pre>
| 0 | 2016-10-08T14:32:02Z | [
"python",
"postgresql",
"sqlalchemy"
] |
How to enable drag selection in UI Maya Python | 39,928,511 | <p>I would like to know how to enable drag selection to select some buttons on my UI.</p>
<p>I have tried to use <code>cmds.selectPref(clickBoxSize=True)</code> but it doesn't work.</p>
| 2 | 2016-10-08T03:55:13Z | 39,959,650 | <pre><code>import maya.cmds as cmds
import shiboken
import maya.OpenMayaUI as omUI
from PySide import QtGui, QtCore
ui_btns = {}
win = cmds.window()
cmds.columnLayout(adjustableColumn=True)
ui_btns["btn_a"] = cmds.button(label="Burning")
ui_btns["btn_b"] = cmds.button(label="Man")
cmds.setParent("..")
cmds.showWindow(win)
draggerContext_id = "dga"
def dga():
cp = QtGui.QCursor().pos()
widget = QtGui.qApp.widgetAt(cp)
ui_id = omUI.MQtUtil.fullName(long(shiboken.getCppPointer(widget)[0]))
print "ui path :{0}".format([ui_id for k, v in ui_btns.iteritems() if ui_id in v])
cmds.draggerContext(draggerContext_id, dragCommand = "dga()", cursor="hand", space="screen")
cmds.setToolTo(draggerContext_id)
</code></pre>
<p>its a simple idea to get the ui path, you can also replace the draggerContext with a scriptjob or the threading.Timer().start() command, there are more solutions, depend on your UI and the workflow (post process eval or ui element dragcallback...it would be great to see some sections from your code)</p>
| 0 | 2016-10-10T13:38:37Z | [
"python",
"maya"
] |
Python, error with web driver (Selenium) | 39,928,515 | <pre><code> import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('http://arithmetic.zetamac.com/game?key=a7220a92')
element = driver.find_element_by_link_text('problem')
print(element)
</code></pre>
<p>I am getting the error:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver'
</code></pre>
<p>I am not sure whythis is happening, because I imported selenium already. </p>
| 0 | 2016-10-08T03:56:02Z | 39,929,034 | <p>Either you provide the ChromeDriver path in webdriver.Chrome or provide the path variable</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driverLocation = 'D:\Drivers\chromedriver.exe' #if windows
driver = webdriver.Chrome(driverLocation)
driver.get('http://arithmetic.zetamac.com/game?key=a7220a92')
element = driver.find_element_by_link_text('problem')
print(element)
</code></pre>
| 1 | 2016-10-08T05:32:09Z | [
"python",
"selenium"
] |
Random numbers do not change, repeats twice | 39,928,521 | <pre><code>import random
def main():
counter = StudentNames()
StudentName = StudentNames()
AverageRight = 0.0
Right = 0.0
numberone = Numbers(counter)
numbertwo = NumbersTwo(counter)
numberone = Equation(numberone, numbertwo)
numbertwo = Equation(numberone, numbertwo)
anwser = 0.0
def StudentNames():
print("Student Name")
StudentName = input("")
print("Pick a Numeral Between One And Ten")
counter = int(input(""))
return counter
return StudentName
def Equation(numberone, numbertwo):
print("Enter Total [A Number Between One And Ten]")
Total = int(input(""))
while Total > 10:
Total = Total + 1
print("What Is The Answer To This Equation")
print(numberone, "+", numbertwo)
answer = int(input(""))
answerOne = numberone + numbertwo
if answer == answerOne:
print("Correct")
Correct = range(1, 10)
Correct = Correct + 1
print(Correct)
else:
print("Incorrect")
incorrect = range(1, 10)
print(incorrect)
def Numbers(counter):
while counter > 10:
counter = counter + 1
numberone = random.randrange(1*2, 500*2)
return numberone
</code></pre>
<p>My random numbers won't change unless I restart the loop, the <code>StudentNames</code> module repeats exactly twice and I have no idea why.</p>
| -2 | 2016-10-08T03:57:49Z | 39,928,581 | <p>Try this ... You can only return one value from a function but you can return a "tuple" (a sequence of objects), and pick it up in main the same way:</p>
<pre><code>def main():
counter, StudentName = StudentNames()
def StudentNames():
... ... ...
return counter, StudentName
</code></pre>
<p>For the random numbers, you don't need a counter </p>
<pre><code>def Numbers():
n = random.randrange(1*2, 500*2)
return n
</code></pre>
<p>and call it like this - each call will generate a fresh random number</p>
<pre><code>numberone = Numbers()
numbertwo = Numbers()
</code></pre>
| 0 | 2016-10-08T04:09:16Z | [
"python",
"loops",
"random"
] |
Running py.test under pypy | 39,928,605 | <p>How do I run pytest using pypy? Travis does it, so it must be possible. This is related to similar <a href="http://stackoverflow.com/questions/39928317/running-py-test-on-micropython">question</a> how to run pytest using Micropython.</p>
<pre><code>arkadiusz@pc:~/Dokumenty/GitHub/construct$ pypy -m pytest
/usr/bin/pypy: No module named pytest
</code></pre>
| 0 | 2016-10-08T04:12:29Z | 39,943,906 | <p>Problem was fixed by installing pip on pypy as in</p>
<p><a href="http://askubuntu.com/questions/834466/installing-pytest-for-pypy">http://askubuntu.com/questions/834466/installing-pytest-for-pypy</a></p>
<p>Then it is just</p>
<pre><code>pypy -m pytest
</code></pre>
| 0 | 2016-10-09T12:59:59Z | [
"python",
"unit-testing",
"py.test",
"pypy"
] |
ImportError: No module named ImageFont | 39,928,682 | <p>I'm using the chemlab library for the first time. I'm trying to run some of the example programs but I keep getting the following error message:</p>
<blockquote>
<p>import ImageFont # From PIL</p>
<p>ImportError: No module named ImageFont</p>
</blockquote>
<p>Here is the code to one of the basic examples (<a href="https://github.com/chemlab/chemlab/blob/master/examples/nacl.py" rel="nofollow">https://github.com/chemlab/chemlab/blob/master/examples/nacl.py</a>):</p>
<pre><code>from chemlab.core import Atom, Molecule, crystal
from chemlab.graphics import display_system
# Molecule templates
na = Molecule([Atom('Na', [0.0, 0.0, 0.0])])
cl = Molecule([Atom('Cl', [0.0, 0.0, 0.0])])
s = crystal([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]], # Fractional Positions
[na, cl], # Molecules
225, # Space Group
cellpar = [.54, .54, .54, 90, 90, 90], # unit cell parameters
repetitions = [5, 5, 5]) # unit cell repetitions in each direction
display_system(s)
</code></pre>
<p>I've tried installing ImageFont, PIL and Pillow via pip (Pillow was the only one that actually installed) but no luck.</p>
| 1 | 2016-10-08T04:28:27Z | 39,930,411 | <p>Install <code>PIL</code>:</p>
<pre><code>pip install pillow
</code></pre>
<p>Correct import for <code>ImageFont</code> is:</p>
<pre><code>from PIL import ImageFont
</code></pre>
<p>Here is an example of <code>ImageFont</code>:</p>
<pre><code>from PIL import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
</code></pre>
| 1 | 2016-10-08T08:38:38Z | [
"python",
"importerror"
] |
Unable to parse through sqlite query using regular expressions | 39,928,690 | <p>I am trying to figure out a way to iterate through a database and match all rows that have 02 in them using regular expressions. When a match is made the count should reset to 0 and when there is not a match the count should accumulate by negative 1. The code works when I use a list. </p>
<pre><code>import sqlite3
import re
conn = sqlite3.connect('p34.db')
c = conn.cursor()
r = re.compile(r'\b[5-9]*(?:0[5-9]?2|2[5-9]?0)[5-9]*\b')
q = "SELECT Number FROM 'Pick 3'"
c.execute(q)
rez = c.fetchall()
count = 0
for i in rez:
if i == r:
count = 0
else:
count = count -1
print(count)
conn.close()
print (rez)
</code></pre>
| 2 | 2016-10-08T04:30:03Z | 39,928,725 | <p>You probably want to use <a href="https://docs.python.org/3/library/re.html#re.search" rel="nofollow"><code>r.search()</code></a> to execute a regular expression search:</p>
<pre><code>for i in rez:
if r.search(i[0]):
count = 0
else:
count -= 1
</code></pre>
<p>Note the use of <code>i[0]</code> to get the first value from each tuple returned by the query.</p>
<p>Using <code>i == r</code> simply <em>compares</em> the tuple <code>i</code> (as returned by the query) to the compiled regular expression patter <code>r</code> and will never be true. It does not execute any of the search methods of the given pattern.</p>
| 0 | 2016-10-08T04:37:49Z | [
"python",
"regex",
"sqlite3"
] |
why no tkinter distribution found | 39,928,710 | <p>while installing tkinter i am having problem ,i have version 2.7.11. i have entered the <code>pip install tkinter</code> on dos but it shows the following message : </p>
<blockquote>
<p>collecting tkinter </p>
<p>Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter</p>
</blockquote>
<p>i have installed flask with the same procedure , it did but for tkinter it is showing problem .how can i get rid of this problem ?</p>
| 1 | 2016-10-08T04:33:43Z | 39,929,501 | <p>The Tkinter library comes in default with every Python installation</p>
<p>Try this:</p>
<pre><code>import Tkinter as tk
</code></pre>
| 0 | 2016-10-08T06:40:21Z | [
"python",
"tkinter",
"module"
] |
How to delete Flask HTTP Sessions from the Database on session.clear() | 39,928,716 | <p>I implemented a server side Session in Flask with SQLAlchemy based on this <a href="http://flask.pocoo.org/snippets/110/" rel="nofollow">snippit</a>:</p>
<pre><code>class SqlAlchemySession(CallbackDict, SessionMixing):
...
class SqlAlchemySessionInterface(SessionInterface):
def __init__(self, db):
self.db = db
def open_session(self, app, request):
...
def save_session(self, app, session, response):
...
</code></pre>
<p>Everything works as expected. When the user logs in, a session is stored in the database, and the session id is placed in a cookie and returned to the user. When the user logs out, <code>session.clear()</code> is called, and the cookie is removed from the user.</p>
<p>However, the session is not deleted from the database. I was hoping that I could implement this logic in my <code>SqlAlchemySessionInterface</code> class, as opposed to defining a function and calling this instead of <code>session.clear()</code>.</p>
<p>Likewise, in the <a href="https://github.com/pallets/flask/blob/master/flask/sessions.py" rel="nofollow">sessions.py</a> code, there isn't any reference to <code>clear</code>, and the only time a cookie is deleted is <a href="https://github.com/pallets/flask/blob/master/flask/sessions.py" rel="nofollow">if the session was modified</a>.</p>
<p>The <a href="http://flask.pocoo.org/docs/0.11/api/#sessions" rel="nofollow">API documentation for sessions</a> also doesn't indicate how the <code>clear</code> method works.</p>
<p>Would anyone know of a way of accomplishing this, other than replacing all my calls to <code>session.clear()</code> with:</p>
<pre><code>def clear_session():
sid = session.get('sid')
if sid:
db.session.query(DBSession).filter_by(sid=sid).delete()
db.session.commit()
session.clear()
</code></pre>
| 3 | 2016-10-08T04:35:46Z | 39,930,787 | <p>If you want to remove duplication, you can define a function called <code>logout_user</code></p>
<p>In that function, you can remove the session record from your database as well as <code>session.clear()</code>.</p>
<p>Call this function when <code>\logout</code> or wherever suitable.</p>
| 0 | 2016-10-08T09:28:13Z | [
"python",
"flask"
] |
How to compare two rows of two pandas series? | 39,928,738 | <p>I have two python pandas series <code>df10</code> and <code>df5</code>. I want to compare their values.For example: <code>df10[-1:]< df5[-1:]</code> ,it returns true. <code>df10[-2:-1] > df5[-2:-1]</code> , it returns false.</p>
<p>But if I combine them together, <code>df10[-1:]< df5[-1:] and df10[-2:-1]>df5[-2:-1]</code>,it returns </p>
<blockquote>
<p>The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all()</p>
</blockquote>
<p>But I expect it returns false. How can I solve this problem?</p>
| 0 | 2016-10-08T04:39:42Z | 39,928,859 | <p>You can do this with the pandas Series <code>values</code> attribute:</p>
<pre><code>if (df10.values[-2:-1] > df5.values[-2:-1]) and\
(df10.values[-1:] < df5.values[-1:]):
print("we met the conditions!")
</code></pre>
| -2 | 2016-10-08T05:03:25Z | [
"python",
"pandas"
] |
How to compare two rows of two pandas series? | 39,928,738 | <p>I have two python pandas series <code>df10</code> and <code>df5</code>. I want to compare their values.For example: <code>df10[-1:]< df5[-1:]</code> ,it returns true. <code>df10[-2:-1] > df5[-2:-1]</code> , it returns false.</p>
<p>But if I combine them together, <code>df10[-1:]< df5[-1:] and df10[-2:-1]>df5[-2:-1]</code>,it returns </p>
<blockquote>
<p>The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all()</p>
</blockquote>
<p>But I expect it returns false. How can I solve this problem?</p>
| 0 | 2016-10-08T04:39:42Z | 39,929,677 | <p>Consider you have the two dataframes from this program:</p>
<pre><code># Python 3.5.2
import pandas as pd
import numpy as np
# column names for example dataframe
cats = ['A', 'B', 'C', 'D', 'E']
df5 = pd.DataFrame(data = np.arange(25).reshape(5, 5), columns=cats)
print("Dataframe 5\n",df5,"\n")
df10=pd.DataFrame(data = np.transpose(np.arange(25).reshape(5, 5)), columns=cats)
print("Dataframe 10\n",df10)
</code></pre>
<p>The resulting data frames are:</p>
<pre><code>Dataframe 5
A B C D E
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
4 20 21 22 23 24
Dataframe 10
A B C D E
0 0 5 10 15 20
1 1 6 11 16 21
2 2 7 12 17 22
3 3 8 13 18 23
4 4 9 14 19 24
</code></pre>
<p>Now let's look at the result of your first comparison:</p>
<pre><code>print(df5[-1:])
print(df10[-1:])
a=df10[-1:]< df5[-1:]
print("\n",a,"\n",type(a))
</code></pre>
<p>which results in:</p>
<pre><code> A B C D E
4 20 21 22 23 24
A B C D E
4 4 9 14 19 24
A B C D E
4 True True True True False
<class 'pandas.core.frame.DataFrame'>
</code></pre>
<p>Now the second comparison:</p>
<pre><code>print(df5[-2:-1])
print(df10[-2:-1])
b=df10[-2:-1]>df5[-2:-1]
print("\n",b,"\n",type(b))
</code></pre>
<p>which has results:</p>
<pre><code> A B C D E
3 15 16 17 18 19
A B C D E
3 3 8 13 18 23
A B C D E
3 False False False False True
<class 'pandas.core.frame.DataFrame'>
</code></pre>
<p><strong>The issue:</strong></p>
<p>If we evaluate: </p>
<pre><code>pd.Series([True, True, False, False]) and pd.Series([False, True, False, True])
</code></pre>
<p>What is the correct answer?:</p>
<ol>
<li>pd.Series([False, True, False, False])</li>
<li>False</li>
<li>True</li>
<li>All of the above</li>
<li>Any of the above</li>
<li>It depends</li>
</ol>
<p>The answer is: 6 - It depends. It depends on <em>what you want.</em></p>
<p>First, we have to create boolean series for the comparison:</p>
<pre><code>a_new = (df10[-1:] < df5[-1:]).any()
print(a_new,"\n",type(a_new))
b_new = (df10[-2:-1] > df5[-2:-1]).any()
print("\n",b_new,"\n",type(b_new))
</code></pre>
<p>The results are:</p>
<pre><code>A True
B True
C True
D True
E False
dtype: bool
<class 'pandas.core.series.Series'>
A False
B False
C False
D False
E True
dtype: bool
<class 'pandas.core.series.Series'>
</code></pre>
<p>Now, we can compute 3 cases.</p>
<p><strong>Case 1: a.any() and b.any()</strong></p>
<p>a.any() = True if any item in a is True</p>
<p>b.any() = True if any item in b is True</p>
<pre><code>print(a_new.any() and b_new.any())
</code></pre>
<p>The result is <strong>True.</strong></p>
<p><strong>Case 2: a.all() and b.all()</strong></p>
<p>a.all() = True if every item in a is True</p>
<p>b.all() = True if every item in b is True</p>
<pre><code>print(a_new.all() and b_new.all())
</code></pre>
<p>The result is <strong>False.</strong></p>
<p><strong>Case 3: Pairwise comparison</strong></p>
<p>For this, you have to compare every element to each other. </p>
<pre><code>result_pairwise = [a_new and b_new for a_new, b_new in zip(a_new,b_new)]
print(result_pairwise,"\n",type(result_pairwise))
</code></pre>
<p>The result is:</p>
<pre><code>[False, False, False, False, False]
<class 'list'>
</code></pre>
<p>For more details, see the <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#gotchas-truth/%22Pandas%20Gotchas%22" rel="nofollow">Pandas Gotchas</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#basics-compare" rel="nofollow">Boolean Reductions.</a></p>
| 1 | 2016-10-08T07:02:39Z | [
"python",
"pandas"
] |
Cofusing about lookup node with binary tree | 39,928,780 | <p>I build a binary tree with python code, now I could print it in order with <code>testTree.printInorder(testTree.root)</code>. I have tried to lookup some node ,and the function <code>findNode</code> doesn't work anymore . <code>print testTree.findNode(testTree.root,20)</code> whatever I put in just return None.</p>
<pre><code>class TreeNode:
def __init__(self, value):
self.left = None;
self.right = None;
self.data = value;
class Tree:
def __init__(self):
self.root = None
def addNode(self,node,value):
if node == None:
self.root = TreeNode(value)
else:
if value < node.data:
if node.left == None:
node.left = TreeNode(value)
else:
self.addNode(node.left,value)
else:
if node.right == None:
node.right = TreeNode(value)
else:
self.addNode(node.right,value)
def printInorder(self,node):
if node != None:
self.printInorder(node.left)
print node.data
self.printInorder(node.right)
def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
self.findNode(node.left,value)
elif value > node.data and node.right != None:
self.findNode(node.right,value)
else:
return None
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.addNode(testTree.root, 20)
#testTree.printInorder(testTree.root)
print testTree.findNode(testTree.root,20)
</code></pre>
| 1 | 2016-10-08T04:48:52Z | 39,928,818 | <p>When you recurse to children in <code>findNode</code> you need to return the result, otherwise the function will implicitly return <code>None</code>:</p>
<pre><code>def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
return self.findNode(node.left,value) # Added return
elif value > node.data and node.right != None:
return self.findNode(node.right,value) # Added return
else:
return None
</code></pre>
| 2 | 2016-10-08T04:57:08Z | [
"python",
"binary-search-tree"
] |
Cofusing about lookup node with binary tree | 39,928,780 | <p>I build a binary tree with python code, now I could print it in order with <code>testTree.printInorder(testTree.root)</code>. I have tried to lookup some node ,and the function <code>findNode</code> doesn't work anymore . <code>print testTree.findNode(testTree.root,20)</code> whatever I put in just return None.</p>
<pre><code>class TreeNode:
def __init__(self, value):
self.left = None;
self.right = None;
self.data = value;
class Tree:
def __init__(self):
self.root = None
def addNode(self,node,value):
if node == None:
self.root = TreeNode(value)
else:
if value < node.data:
if node.left == None:
node.left = TreeNode(value)
else:
self.addNode(node.left,value)
else:
if node.right == None:
node.right = TreeNode(value)
else:
self.addNode(node.right,value)
def printInorder(self,node):
if node != None:
self.printInorder(node.left)
print node.data
self.printInorder(node.right)
def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
self.findNode(node.left,value)
elif value > node.data and node.right != None:
self.findNode(node.right,value)
else:
return None
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.addNode(testTree.root, 20)
#testTree.printInorder(testTree.root)
print testTree.findNode(testTree.root,20)
</code></pre>
| 1 | 2016-10-08T04:48:52Z | 39,928,903 | <p>Any function without an explicit return will return None. </p>
<p>You have not returned the recursive calls within <code>findNode</code>. So, here. </p>
<pre><code>if value == node.data:
return node.data
elif value < node.data and node.left != None:
return self.findNode(node.left,value)
elif value > node.data and node.right != None:
return self.findNode(node.right,value)
</code></pre>
<hr>
<p>Now, I can't help but thinking this is a bit noisy. You'll always start adding from the root, yes?</p>
<pre><code>testTree.addNode(testTree.root, 200)
</code></pre>
<p>You could rather do this </p>
<pre><code>testTree.addNode(200)
</code></pre>
<p>And to do that, you basically implement your methods on the <code>TreeNode</code> class instead. So, for the <code>addNode</code>. </p>
<p>You could also "return up" from the recursion, rather than "pass down" the nodes as parameters. </p>
<pre><code>class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.data = value
def addNode(self,value):
if self.data == None: # Ideally, should never end-up here
self.data = value
else:
if value < self.data:
if self.left == None:
self.left = TreeNode(value)
else:
self.left = self.left.addNode(value)
else:
if self.right == None:
self.right = TreeNode(value)
else:
self.right = self.right.addNode(value)
return self # Return back up the recursion
</code></pre>
<p>Then, in the <code>Tree</code> class, just delegate the <code>addNode</code> responsibility to the root </p>
<pre><code>class Tree:
def __init__(self):
self.root = None
def addNode(self,value):
if self.root == None:
self.root = TreeNode(value)
else:
self.root = self.root.addNode(value)
</code></pre>
| 2 | 2016-10-08T05:10:13Z | [
"python",
"binary-search-tree"
] |
The field was declared on serializer , but has not been included error in django rest | 39,928,879 | <p>I created few serializers in my django REST API and stuck with weird problem. When i go to the <code>http://127.0.0.1:8000/api/register/</code> url i'm gets the error:</p>
<blockquote>
<p>Environment:</p>
<p>Request Method: GET Request URL: <a href="http://localhost:8000/api/users/" rel="nofollow">http://localhost:8000/api/users/</a></p>
<p>Django Version: 1.10.2 Python Version: 3.5.2 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'api'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']</p>
<p>Traceback:</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\exception.py"
in inner
39. response = get_response(request)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\base.py"
in _legacy_get_response
249. response = self._get_response(request)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\base.py"
in _get_response
217. response = self.process_exception_by_middleware(e, request)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\core\handlers\base.py"
in _get_response
215. response = response.render()</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\django\template\response.py"
in render
109. self.content = self.rendered_content</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\response.py"
in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\renderers.py"
in render
697. context = self.get_context(data, accepted_media_type, renderer_context)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\renderers.py"
in get_context
630. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\renderers.py"
in get_raw_data_form
553. content = renderer.render(serializer.data, accepted, context)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\serializers.py"
in data
508. ret = super(Serializer, self).data</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\serializers.py"
in data
244. self._data = self.get_initial()</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\serializers.py"
in get_initial
387. for field in self.fields.values()</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\serializers.py"
in fields
340. for key, value in self.get_fields().items():</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\serializers.py"
in get_fields
947. field_names = self.get_field_names(declared_fields, info)</p>
<p>File
"D:\code\active\Python\Django\photo-hub\photo-hub\env\lib\site-packages\rest_framework\serializers.py"
in get_field_names
1046. serializer_class=self.<strong>class</strong>.<strong>name</strong></p>
<p>Exception Type: AssertionError at /api/users/ Exception Value: The
field 'photos' was declared on serializer UserSerializer, but has not
been included in the 'fields' option.</p>
</blockquote>
<p>But my UserSerializer doesn't even have 'photos' field. I'm new in django, please, help me to understand source of this problem.</p>
<p>serializers.py</p>
<pre><code>from django.utils import timezone
from django.contrib.auth.models import User
from rest_framework import serializers
from api.models import Album, Photo
class PhotoSerializer(serializers.HyperlinkedModelSerializer):
#url = serializers.HyperlinkedIdentityField(view_name="photo-detail")
album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects)
owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects)
class Meta:
model = Photo
fields = ('url', 'name', 'image', 'creation_date', 'owner', 'album')
read_only_fields=('creation_date')
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
#url = serializers.HyperlinkedIdentityField(view_name="album-detail")
owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects)
photos = serializers.HyperlinkedRelatedField(view_name='photo-list', queryset=Photo.objects, many=True)
def get_validation_exclusions(self):
# Need to exclude `author` since we'll add that later based off the request
exclusions = super(AlbumSerializer, self).get_validation_exclusions()
return exclusions + ['user']
class Meta:
model = Album
fields = ('pk', 'name', 'creation_date', 'owner', 'photos')
read_only_fields=('creation_date')
class UserSerializer(serializers.HyperlinkedModelSerializer):
#url = serializers.HyperlinkedIdentityField(view_name="user-detail", read_only=True)
albums = serializers.HyperlinkedRelatedField(many=True, view_name='album-list', queryset=Album.objects)
password = serializers.CharField(write_only=True, required=True)
confirm_password = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = ('url', 'pk', 'username', 'email', 'password', 'is_staff', 'albums')
write_only_fields = ('password')
read_only_fiels = ('pk')
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
user = super(UserSerializer, self).update(instance, validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def validate(self, data):
if data['password']:
if data['password'] != data['confirm_password']:
raise serializers.ValidationError(
"The passwords have to be the same"
)
return data
</code></pre>
<p>AuthRegister view</p>
<pre><code>class AuthRegister(APIView):
serializer_class = UserSerializer
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>api/urls.py</p>
<pre><code>from django.conf.urls import include, url
from .views import AuthRegister
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'albums', views.AlbumViewSet)
router.register(r'photos', views.PhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^login/', obtain_jwt_token),
url(r'^token-refresh/', refresh_jwt_token),
url(r'^token-verify/', verify_jwt_token),
url(r'^register/$', AuthRegister.as_view()),
</code></pre>
| 0 | 2016-10-08T05:06:13Z | 40,026,977 | <p>Finally i found source of my stupid error. Reason was that earlier i had photo field in my model. But after making changes in model i forget to make migrations.</p>
| 0 | 2016-10-13T17:03:05Z | [
"python",
"django",
"django-rest-framework"
] |
When using PyMongo, No handlers could be found for logger "apscheduler.scheduler" | 39,928,970 | <p>The code works fine printing to screen <code>hello</code> every second. This is done using the <code>bar</code> method, which is added to the scheduler as a job.</p>
<p><strong>Problem:</strong> However when the line <code>self.db.animals.insert_one({'name': 'lion'})</code> is added to the <code>bar</code> method, running the script gives an error</p>
<pre><code>No handlers could be found for logger "apscheduler.scheduler"
</code></pre>
<p>and the script stalls. Any idea what happened and how we can solve it?</p>
<pre><code>from apscheduler.schedulers.blocking import BlockingScheduler
import pymongo
class Foo(object):
def __init__(self, db, interval=1):
self.interval = interval
self.db = db
self.sched = BlockingScheduler()
self.sched.add_job(self.bar, 'interval', seconds = interval)
def start(self):
self.sched.start()
def stop(self):
self.sched.shutdown()
def bar(self):
print 'hello'
self.db.animals.insert_one({'name': 'lion'})
client = pymongo.MongoClient("localhost", 27017)
db = client.earth
foo = Foo(db, 0.2)
foo.start()
</code></pre>
| 0 | 2016-10-08T05:21:37Z | 39,941,587 | <p>That's not an error, but a warning. Python's logging system is trying to tell you that it has no outlet for logging output because you haven't configured it. Try using <code>logging.basicConfig(level=logging.DEBUG)</code>.</p>
| 0 | 2016-10-09T08:33:45Z | [
"python",
"python-2.7",
"pymongo",
"apscheduler"
] |
Build a dictionary using select values from a different dictionary | 39,929,007 | <p>I have a dictionary with years as keys and other dictionaries as values (these inner dictionaries contain tuples (i, i+1) as keys). An example of the format would be:</p>
<pre><code>myDict = {2000: {(0,1):111.1, (1,2):222.2, (2,3):333.3, (3,4):444.4}
2001: {(0,1):11.1, (1,2):22.2, (2,3):33.3, (3,4):44.4}}
</code></pre>
<p>From this dictionary, I am trying to compile a dictionary, <code>secondDict</code>, that also has years for keys. The values will be the sum of the innermost values in <code>myDict</code> for only certain tuples (i.e. any tuple in that year whose 0th index is greater than 1). What I am going for is a dictionary that looks like this:</p>
<pre><code>secondDict = {2000: 777.7, 2001: 77.7}
</code></pre>
<p>The value in <code>secondDict</code> would be the sum of the values in <code>myDict[2000][tuple]</code> if the 1st number in the tuple was greater than or equal to <code>2</code>.</p>
<p>So far I have:</p>
<pre><code>years = [2000, 2001, 2002, 2003, 2011, 2012, 2013, 2014]
tuples = [(i, i+1) for i in range(65)]
for year in years:
for key in myDict[year]:
for value in myDict[year][key]:
if key[0] >= 30:
secondDict[year] += value
</code></pre>
<p>I have several problems with my method here, but can't think of another way to build the dictionary.</p>
<p>1) Firstly, I'm getting a <code>TypeError: 'float' object is not iterable</code> for the third line of the loop (<code>for value in</code> ...). All the values that I am trying to access are floats, so I'm not sure how to work around this.</p>
<p>2) Moving on to problems I anticipate but haven't been able to address due to the <code>TypeError</code>: In the line <code>if key[0] >= 30</code> I am trying to access the 0th index of the tuple; will this work / if not, how do I access it?</p>
<p>3) I am working with some fairly large dictionaries here and it seems like the running time for this many loops will be quite slow; however I'm pretty new to coding so my grasp of this is limited. Is it just <strong>O(n)</strong> for each loop, i.e. <strong>O(n^4)</strong> since there are four loops? How can I create a better, quicker algorithm to build a dictionary like this?</p>
<p><em><strong>EDIT:</strong></em></p>
<p>After more research and some finicking with the code, I now have:</p>
<pre><code>for year in years:
for key in myDict[year].keys():
if key[0] >= 30:
secondDict[year] += myDict[year][key]
</code></pre>
<p>This doesn't raise any errors, but upon printing it I find that it only compiles for one year:</p>
<pre><code>In[5]: secondDict
Out[5]:
defaultdict(None,
{2000: 0,
2001: 0,
2002: 0,
2003: 27162828.602349777,
2011: 0,
2012: 0,
2013: 0,
2014: 0})
</code></pre>
<p>Why is it not iterating fully over <code>years</code>? Any suggestions?</p>
| 1 | 2016-10-08T05:27:48Z | 39,929,711 | <p>Here's a dict comprehension that performs the action you specify at the start of your question, i.e., the values are the sum of the innermost values in <code>myDict</code> for tuples whose 0th index is greater than 1. </p>
<pre><code>myDict = {
2000: {(0,1):111.1, (1,2):222.2, (2,3):333.3, (3,4):444.4},
2001: {(0,1):11.1, (1,2):22.2, (2,3):33.3, (3,4):44.4},
}
secondDict = {y: sum(v for t, v in d.items() if t[0] > 1)
for y, d in myDict.items()}
print(secondDict)
</code></pre>
<p><strong>output</strong></p>
<pre><code>{2000: 777.7, 2001: 77.69999999999999}
</code></pre>
| 1 | 2016-10-08T07:06:15Z | [
"python",
"dictionary",
"iteration"
] |
why does function url_for() in Flask produced this error? | 39,929,028 | <p>When I use flask, in my first template(a.html) I wrote:</p>
<pre><code>{{url_for('auth.confirm', token=token, _external=True)}}
</code></pre>
<p>It gave the right site: <code>/auth/confirm/<token></code></p>
<p>But in another:<code>{{url_for('auth.forget', token=token, _external=True)}}</code></p>
<p>It gave me a site like this: <code>/auth/forget?token=<token></code></p>
<p>What makes the diffence?<br /></p>
<p>Codes here:</p>
<pre><code>@auth.route('/forget', methods=['GET', 'POST'])
def forget():
form=ForgetPasswordForm()
if form.validate_on_submit():
user=User.query.filter_by(email=form.email.data).first()
if user:
token=user.generate_forget_token()
send_email(user.email, 'Reset your password', 'auth/email/forget', token=token)
return redirect(url_for('main.index'))
flash("Email is not exist")
return render_template('auth/forget.html',form=form)
@auth.route('/forget/<token>', methods=['GET', 'POST'])
def forget_reset(token):
try:
email=User.confirm_forget(token)
except:
return render_template('404.html')
form=PasswordOnlyForm()
if form.validate_on_submit():
user=User.query.filter_by(email=email).first()
user.password=form.password.data
db.session.add(user)
db.session.commit()
flash('Succeed, now login!')
return redirect('auth/login')
return render_template('auth/PasswordOnly.html',form=form)
</code></pre>
| 0 | 2016-10-08T05:31:05Z | 39,929,066 | <p>The underlying functions are expecting different urls.</p>
<p>In the first case, the flask routing decorator looks like:</p>
<pre><code>@app.route('/auth/confirm/<token>')
def confirm(token):
</code></pre>
<p>In the second, the token is not specified, and therefore passed as a query parameter.</p>
<pre><code>@app.route('/auth/forget/')
def forget():
</code></pre>
<p>You'll also need to be careful about which function you are calling. In your example above, you have two functions: <code>forget</code> and <code>forget_reset</code> which have two different behaviors.</p>
<pre><code>@app.route('/auth/forget/')
def forget():
pass
@auth.route('/forget/<token>', methods=['GET', 'POST'])
def forget_reset(token):
pass
</code></pre>
<p>Now you call them slightly differently. If you call forget:</p>
<pre><code><a href="{{url_for('forget', token='hello')}}">Calling Forget</a>
http://127.0.0.1:5000/forget?token=hello
</code></pre>
<p>And if you call forget_reset:</p>
<pre><code><a href="{{url_for('forget_reset', token='hello')}}">Calling Forget Reset</a>
http://127.0.0.1:5000/forget/hello
</code></pre>
| 1 | 2016-10-08T05:36:17Z | [
"python",
"web",
"flask"
] |
Building Qt Gui from few classes together | 39,929,107 | <p>Below is a short example of my Gui. I am trying to split my Gui in few parts.
The elements of <em>InputAxis</em> should be on the same height (horizontal split) and <em>self.recipient</em> should be below them (vertical split).</p>
<p>In <em>InputAxis</em> I am trying to place a <em>QLineEdit</em> but in my Gui I don't see it.</p>
<pre><code>import sys
from PySide import QtCore
from PySide import QtGui
class InputAxis(object):
def __init__(self):
self.frame = QtGui.QFrame()
self.input_interface = QtGui.QLineEdit()
self.form_layout = QtGui.QFormLayout()
def genAxis(self):
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.form_layout.addRow('&Input:', self.input_interface)
return self.frame
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self, parent = None)
self.layout = QtGui.QVBoxLayout()
self.form_layout = QtGui.QFormLayout()
self.axes = list()
self.axes.append(InputAxis())
self.axes.append(InputAxis())
self.splitter1 = QtGui.QSplitter(QtCore.Qt.Horizontal)
for axis in self.axes:
self.splitter1.addWidget(axis.genAxis())
self.form_layout.addWidget(self.splitter1)
self.setMinimumWidth(400)
self.recipient = QtGui.QLineEdit(self)
# Add it to the form layout with a label
self.form_layout.addRow('&Recipient:', self.recipient)
# Add the form layout to the main VBox layout
self.layout.addLayout(self.form_layout, 0)
# Set the VBox layout as the window's main layout
self.setLayout(self.layout)
QtGui.QApplication.setStyle( QtGui.QStyleFactory.create('Cleanlooks') )
def run(self):
self.show()
def main():
qt_app = QtGui.QApplication(sys.argv)
window = Window()
window.run()
sys.exit(qt_app.exec_())
if __name__=="__main__":
main()
</code></pre>
| 0 | 2016-10-08T05:42:05Z | 39,931,251 | <p>the reason it did not work was this line:</p>
<pre><code>self.form_layout = QtGui.QFormLayout()
</code></pre>
<p>It should be:</p>
<pre><code>self.form_layout = QtGui.QFormLayout(self.frame)
</code></pre>
| 1 | 2016-10-08T10:24:17Z | [
"python",
"qt",
"pyqt",
"pyside"
] |
how would one sum a range of numbers within a certain value? | 39,929,113 | <p>I have an array of values like so</p>
<pre><code> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
</code></pre>
<p>Is there a pythonic way to sum all values within this array that are between a certain value? For example, if my range was 2.5-6, I would expect to get 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6 = 35.7. I'm also open to using numpy to solve this as well.</p>
| -1 | 2016-10-08T05:43:16Z | 39,929,138 | <pre><code>>>> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
>>> sum([n for n in nums if 2.5 <= n <= 6])
35.7
>>> 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6
35.7
</code></pre>
| 2 | 2016-10-08T05:47:17Z | [
"python",
"arrays",
"numpy",
"range"
] |
how would one sum a range of numbers within a certain value? | 39,929,113 | <p>I have an array of values like so</p>
<pre><code> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
</code></pre>
<p>Is there a pythonic way to sum all values within this array that are between a certain value? For example, if my range was 2.5-6, I would expect to get 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6 = 35.7. I'm also open to using numpy to solve this as well.</p>
| -1 | 2016-10-08T05:43:16Z | 39,929,157 | <pre><code>sum(filter(lambda x: x>=2.5 and x<=6,nums))
</code></pre>
| 0 | 2016-10-08T05:50:23Z | [
"python",
"arrays",
"numpy",
"range"
] |
how would one sum a range of numbers within a certain value? | 39,929,113 | <p>I have an array of values like so</p>
<pre><code> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
</code></pre>
<p>Is there a pythonic way to sum all values within this array that are between a certain value? For example, if my range was 2.5-6, I would expect to get 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6 = 35.7. I'm also open to using numpy to solve this as well.</p>
| -1 | 2016-10-08T05:43:16Z | 39,929,163 | <p>Well, lets assume you have your variables <code>min</code> and <code>max</code> set. Then you can type:</p>
<pre><code>min = 2.5
max = 6
sum = sum( i if i>=min and i<=max else 0 for i in nums )
</code></pre>
<p>Greets!</p>
| 1 | 2016-10-08T05:51:18Z | [
"python",
"arrays",
"numpy",
"range"
] |
how would one sum a range of numbers within a certain value? | 39,929,113 | <p>I have an array of values like so</p>
<pre><code> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
</code></pre>
<p>Is there a pythonic way to sum all values within this array that are between a certain value? For example, if my range was 2.5-6, I would expect to get 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6 = 35.7. I'm also open to using numpy to solve this as well.</p>
| -1 | 2016-10-08T05:43:16Z | 39,929,297 | <p>Since no one has offered a numpy solution yet, here you go:</p>
<pre><code>>>> nums = np.array([2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6])
>>> nums[(2.5 <= nums) & (nums <= 6)].sum()
35.700000000000003
</code></pre>
<p>Although, I tried some simple tests, and I'm not sure that there's much speed benefit.</p>
| 6 | 2016-10-08T06:14:37Z | [
"python",
"arrays",
"numpy",
"range"
] |
how would one sum a range of numbers within a certain value? | 39,929,113 | <p>I have an array of values like so</p>
<pre><code> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
</code></pre>
<p>Is there a pythonic way to sum all values within this array that are between a certain value? For example, if my range was 2.5-6, I would expect to get 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6 = 35.7. I'm also open to using numpy to solve this as well.</p>
| -1 | 2016-10-08T05:43:16Z | 39,929,305 | <p>It can also be done by sorting and then bisecting to find the slice of the list to sum:</p>
<pre><code>>>> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
>>> nums.sort()
>>> import bisect
>>> min = 2.5
>>> max = 6
>>> sum(nums[bisect.bisect_right(nums, min)-1:bisect.bisect_left(nums, max)+1])
35.7
</code></pre>
| 1 | 2016-10-08T06:16:01Z | [
"python",
"arrays",
"numpy",
"range"
] |
how would one sum a range of numbers within a certain value? | 39,929,113 | <p>I have an array of values like so</p>
<pre><code> nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
</code></pre>
<p>Is there a pythonic way to sum all values within this array that are between a certain value? For example, if my range was 2.5-6, I would expect to get 2.5 + 5.4 + 3.2 + 4.4 + 4 + 5.2 + 5 + 6 = 35.7. I'm also open to using numpy to solve this as well.</p>
| -1 | 2016-10-08T05:43:16Z | 39,932,335 | <p>Use <code>masked_outside()</code>:</p>
<pre><code>import numpy as np
nums = [2.5, 1, 9, 9.9, 1.6, 5.4, 3.2, 4.4, 4, 5.2, 5, 6]
np.ma.masked_outside(nums, 2.5, 6).sum()
</code></pre>
| 1 | 2016-10-08T12:26:52Z | [
"python",
"arrays",
"numpy",
"range"
] |
Get HTML file after Javascript executed with Scrapy + Splash | 39,929,244 | <p>I want to crawl page that includes javascript using Scrapy and Splash.</p>
<p>In page, <code><script type = text/javascript> JS_FUNCTIONS(generate html content) </script></code> exists, so I tried to get html file after running JS_FUNCTIONS like below.</p>
<pre><code>import scrapy
from scrapy_splash import SplashRequest
class FooSpider(scrapy.Spider):
name = 'foo'
start_urls = ["http://foo.com"]
def start_requests(self):
for url in self.start_urls:
yield SplashRequest(url, self.parse, args={'wait': 0.5})
def parse(self, response):
file_name = response.url.split("//")[-1]
with open(filename, 'wb') as f:
f.write(response.body)
</code></pre>
<p>when I execute command <code>scrapy crawl foo</code>, it returns html file that still including <code><script type = text/javascript> JS_FUNCTIONS(generate html content) </script></code> and doesn't contain html content, which should be generated by JS_FUNCTIONS.</p>
<p>How can I get html file including contents that is generated by javascript?</p>
<p>Thanks.</p>
| 0 | 2016-10-08T06:06:05Z | 39,931,547 | <p>Maybe try executing with the following lua code:</p>
<pre><code>lua_code = """
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(0.5))
return {
html = splash:html(),
}
end
"""
SplashRequest(url,self.parse, args={'lua_source': lua_code}, endpoint='execute')
</code></pre>
| 0 | 2016-10-08T10:57:16Z | [
"python",
"scrapy",
"web-crawler",
"scrapy-splash"
] |
Connection refused with postgresql using psycopg2 | 39,929,258 | <blockquote>
<p>psycopg2.OperationalError: could not connect to server: Connection refused</p>
</blockquote>
<p>Is the server running on host "45.32.1XX.2XX" and accepting TCP/IP connections on port 5432?</p>
<p>Here,I've open my sockets.</p>
<pre><code>tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 11516/postgres
tcp6 0 0 ::1:5432 :::* LISTEN 11516/postgres
</code></pre>
<p>I googled that I should modify this <code>pg_hba.conf</code>ï¼but in my <code>postgresql</code>root files, I didn't find this file at all.</p>
<p>Also I've succeed in connecting my another server.</p>
<p>Thanks.</p>
<p>Here,I've modified the <code>pg_hba.conf</code>,updated this<code>host all all 218.3.A.B trust</code> and reloaded.But it didn't work either.</p>
| 0 | 2016-10-08T06:07:46Z | 39,932,885 | <p>Your netstat output shows that postgres is listening on <code>127.0.0.1</code>, but your error suggests you are trying to connect to <code>45.32.1XX.2XX</code>. I am pretty sure you have already diagnosed your problem. </p>
<p>You will need to modify the <code>listen_addresses</code> setting your <code>postgresql.conf</code> file (<em>not</em> <code>pg_hba.conf</code>). The <code>postgresql.conf</code> file is found in your postgresql data directory, which is often something like <code>/var/lib/postgresql/data</code> or <code>/var/lib/pgsql/data</code>.</p>
<p>The <code>listen_addresses</code> parameter is documented <a href="https://www.postgresql.org/docs/9.5/static/runtime-config-connection.html" rel="nofollow">here</a>.</p>
| 0 | 2016-10-08T13:23:14Z | [
"python",
"postgresql",
"python-3.x"
] |
Python Flask not receiving AJAX post? | 39,929,262 | <p>I have run into a problem with my javascript/python script. What I am trying to do is pass a string to python flask so I can use it later. When I click the button to send the string, there are no errors but nothing happens. I am basically a self taught coder so I apologise if my script it not properly formatted! </p>
<p>Javascript:</p>
<pre><code>$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: data,
...
</code></pre>
<p>Python Flask:</p>
<pre><code>from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
string = request.args.get(data)
print(string)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>I want to be able to see the string printed to either the console or the command prompt, I assume print() is the right way to do this?
Any help would be welcome, thank you :) </p>
| 0 | 2016-10-08T06:08:16Z | 39,930,721 | <p>What you want is in <code>request.data</code>.</p>
<p><code>request.args</code> contains parameters in the URL.</p>
<p>Check this out for more details. <a href="http://flask.pocoo.org/docs/0.11/api/#incoming-request-data" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#incoming-request-data</a></p>
| 2 | 2016-10-08T09:20:29Z | [
"javascript",
"python",
"html",
"ajax",
"flask"
] |
Python Flask not receiving AJAX post? | 39,929,262 | <p>I have run into a problem with my javascript/python script. What I am trying to do is pass a string to python flask so I can use it later. When I click the button to send the string, there are no errors but nothing happens. I am basically a self taught coder so I apologise if my script it not properly formatted! </p>
<p>Javascript:</p>
<pre><code>$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: data,
...
</code></pre>
<p>Python Flask:</p>
<pre><code>from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
string = request.args.get(data)
print(string)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>I want to be able to see the string printed to either the console or the command prompt, I assume print() is the right way to do this?
Any help would be welcome, thank you :) </p>
| 0 | 2016-10-08T06:08:16Z | 39,957,470 | <p>If you data object in Ajax is json then you can use <code>request.get_json()</code></p>
<p>If it is form data of key value then you can <code>request.form.get('data')</code> but your ajax should be </p>
<pre><code>$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: {data: 'mystring'},
</code></pre>
| 0 | 2016-10-10T11:42:47Z | [
"javascript",
"python",
"html",
"ajax",
"flask"
] |
Python Flask not receiving AJAX post? | 39,929,262 | <p>I have run into a problem with my javascript/python script. What I am trying to do is pass a string to python flask so I can use it later. When I click the button to send the string, there are no errors but nothing happens. I am basically a self taught coder so I apologise if my script it not properly formatted! </p>
<p>Javascript:</p>
<pre><code>$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: data,
...
</code></pre>
<p>Python Flask:</p>
<pre><code>from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
string = request.args.get(data)
print(string)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>I want to be able to see the string printed to either the console or the command prompt, I assume print() is the right way to do this?
Any help would be welcome, thank you :) </p>
| 0 | 2016-10-08T06:08:16Z | 40,044,251 | <p>You can make an ajax POST request like this:</p>
<pre><code>$.ajax({
url: "/",
method: "POST",
data: { paramter : value },
});
</code></pre>
<p>The data send over this POST request can be accessed in flask app with<code>request.form['parameter']</code> </p>
<p>If you are sending raw json data, you can access the data by <code>request.json['parameter']</code></p>
<pre><code>$.ajax({
url: "/",
method: "POST",
data: JSON.stringify("{'paramter': 'value'}"),
contentType: 'application/json;charset=UTF-8'
});
</code></pre>
<p>And this should work.</p>
| 0 | 2016-10-14T13:20:51Z | [
"javascript",
"python",
"html",
"ajax",
"flask"
] |
extracting tuple values from list of tuples | 39,929,281 | <p>I have a list containg tuples of different types like:</p>
<pre><code>[(0, 1, 'BLANK', ''), (0, 2, 'PERSON', 'Deraj'), (3, 8, 'DOB', 'April 27 , 1834'), (9, 11, 'PERSON', 'David Deraj'), (11, 13, 'LOC', 'Pennsylvania'), (16, 19, 'PERSON', 'Mary Deraj')]
</code></pre>
<p>How do i get the following output</p>
<pre><code>('Deraj', 'David Deraj')
('Deraj', 'Mary Deraj')
</code></pre>
<p>i am trying to use for loop:</p>
<pre><code>for i in l:
if i[2] == 'PERSON':
m = list(i[3])
</code></pre>
<p>but this doesnt work.</p>
| 1 | 2016-10-08T06:11:27Z | 39,929,320 | <p>You probably can do it like this(if i understand correctly and you want first member of tuple to be second name of those peoples):</p>
<pre><code>l=[]
for i in l:
if i[2]=='PERSON':
temp=i[3].split()
if len(temp)>1:
l.append((temp[1],i[3]))
</code></pre>
| 1 | 2016-10-08T06:17:11Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
extracting tuple values from list of tuples | 39,929,281 | <p>I have a list containg tuples of different types like:</p>
<pre><code>[(0, 1, 'BLANK', ''), (0, 2, 'PERSON', 'Deraj'), (3, 8, 'DOB', 'April 27 , 1834'), (9, 11, 'PERSON', 'David Deraj'), (11, 13, 'LOC', 'Pennsylvania'), (16, 19, 'PERSON', 'Mary Deraj')]
</code></pre>
<p>How do i get the following output</p>
<pre><code>('Deraj', 'David Deraj')
('Deraj', 'Mary Deraj')
</code></pre>
<p>i am trying to use for loop:</p>
<pre><code>for i in l:
if i[2] == 'PERSON':
m = list(i[3])
</code></pre>
<p>but this doesnt work.</p>
| 1 | 2016-10-08T06:11:27Z | 39,931,737 | <p>Assuming that the first record <code>(0, 2, 'PERSON', 'Deraj')</code> has always the first item zero and the second item indicating the number of family members, you can do this in one line.</p>
<pre><code>print [ (entry[3].split()[1], entry[3])
for entry in data
if (entry[2] == 'PERSON' and entry[0] > 0) ]
</code></pre>
| 1 | 2016-10-08T11:19:43Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
Unable to print the files with special characters while using python | 39,929,412 | <p>I developed a web crawler to extract all the source codes in a wiki link. The program terminates after writing a few files.</p>
<pre><code> def fetch_code(link_list):
for href in link_list:
response = urllib2.urlopen("https://www.wikipedia.org/"+href)
content = response.read()
page = open("%s.html" % href, 'w')
page.write(content.replace("[\/:?*<>|]", " "))
page.close()
</code></pre>
<p><code>link_list</code> is an array, which has the extracted links from the seed page.</p>
<p>The error I get after executing is </p>
<pre><code>IOError: [Errno 2] No such file or directory: u'M/s.html'
</code></pre>
| 0 | 2016-10-08T06:27:14Z | 39,929,459 | <p>you cannot create a file with '/' in its name.</p>
<p>you could escape the filename as M%2Fs.html</p>
<p>/ is %2F</p>
<p>in python2, you could simply use urllib to escape the filename, example:</p>
<pre><code>import urllib
filePath = urllib.quote_plus('M/s.html')
print(filePath)
</code></pre>
<p>on the other hand, you could also save http response to hierarchy, for example, M/s.html means s.html file under directory named 'M'.</p>
| 1 | 2016-10-08T06:34:42Z | [
"python"
] |
importError: No module named 'django.db.backends.util' | 39,929,472 | <p>I am using MySql db.i made following changes but now i am getting following error </p>
<pre><code>DATABASES = {
'default': {
'NAME': 'test',
'ENGINE': 'sqlserver_ado',
'HOST':'127.0.0.1',
'USER': 'mssql',
'PASSWORD': 'mssql',
'PORT': '1434'
}
}
</code></pre>
<blockquote>
<p>"ImportError: No module named 'django.db.backends.util' "</p>
</blockquote>
| 0 | 2016-10-08T06:36:06Z | 39,929,892 | <p>You've probably installed <code>django-mssql</code> version 1.7 which supports <= Django 1.8.</p>
<p>You can try <code>django-mssql-1.8b2</code>:</p>
<pre><code>pip install django-mssql==1.8b2
</code></pre>
<p>Beware that this is probably a beta version, so it might not be suitable for you.</p>
| 0 | 2016-10-08T07:31:47Z | [
"python",
"sql-server",
"django"
] |
importError: No module named 'django.db.backends.util' | 39,929,472 | <p>I am using MySql db.i made following changes but now i am getting following error </p>
<pre><code>DATABASES = {
'default': {
'NAME': 'test',
'ENGINE': 'sqlserver_ado',
'HOST':'127.0.0.1',
'USER': 'mssql',
'PASSWORD': 'mssql',
'PORT': '1434'
}
}
</code></pre>
<blockquote>
<p>"ImportError: No module named 'django.db.backends.util' "</p>
</blockquote>
| 0 | 2016-10-08T06:36:06Z | 39,930,602 | <p>The error means that you don't have suitable db backends for <code>mssql</code>. You can install <a href="https://github.com/lionheart/django-pyodbc" rel="nofollow">https://github.com/lionheart/django-pyodbc</a> as db backend.</p>
| 0 | 2016-10-08T09:05:29Z | [
"python",
"sql-server",
"django"
] |
Create a list from titanic csv and chart using matplot.pyplot and savefig | 39,929,564 | <p>I'm playing around with the Kaggle Titanic train.csv to get more comfortable with lists, csv reader, and matplot charts. Nevermind that the list I'm creating isn't really necessary to display the data in a chart (or that the chart is a line...). I just want to make a simple chart and save it, but when I look for it in the current directory it's not there. Is there anything wrong with the code (besides not being very 'pythonic')?</p>
<p>I'm running Windows and executing in Powershell.</p>
<p>Element 1 in the csv determines survivors, element 4 specifies male/female, element 5 is age. I want the chart to display the number of male survivors of each age listed before I move on to something meaningful.</p>
<pre><code>import csv
import matplotlib.pyplot as plt
f = open("PATH/train.csv")
csv_f = csv.reader(f)
class survivordata:
def male_test(self, data):
for row in data:
tlist = list(row)
# now I have a list of tuples.
if tlist[4] == "male" and tlist[1] == 1:
males = []
males.append(row)
c = counter(males)
plt.plot(males[5], c[5], color = 'blue', marker = 'x',
linestyle = 'solid'
)
plt.title("Male Survivors")
plt.ylabel("Number Survivors")
plt.savefig("graph.png")
</code></pre>
<p>Appreciate the feedback.</p>
| 0 | 2016-10-08T06:49:17Z | 39,929,621 | <p><code>csv</code> module doesn't convert text into <code>int</code> so you have to compare <code>tlist[1]</code> with text <code>"1"</code>.</p>
<p>If this doesn't work then add many <code>print(some_usefull_message)</code> in code to see which part is executed. And print variable to see values. Mostly it helps to resolve problem.</p>
| 0 | 2016-10-08T06:55:52Z | [
"python",
"csv",
"matplotlib"
] |
PyQt application: Restore the original look & feel after changing some QSS elements | 39,929,618 | <p>I'm changing the look of some elements in my pyQt application using a QSS style sheet. This has the effect of overriding many other properties of those elements as well (as noted in the documentation and many tutorials).</p>
<p>Now, I would like to restore these overridden properties, but I haven't managed to find the "original" style sheets on my system where the default themes are defined. Using the information from these style sheets I could restore the rest of the original look.</p>
<p>Could somebody give me hint where to find these style sheets? Or is there a more elegant way to achieve my goals?</p>
| 1 | 2016-10-08T06:55:41Z | 39,934,361 | <p>There are no default stylesheets. All the default styling is done by <a href="http://doc.qt.io/qt-5/style-reference.html" rel="nofollow">style plugins</a>.</p>
<p>When a stylesheet is set, it creates an instance of <code>QStyleSheetStyle</code> (which is a subclass of <code>QWindowsStyle</code>) and passes it a reference to the current style. The <code>QStyleSheetStyle</code> will try to apply the QSS rules <em>on top of</em> the current style, but where this is not possible, it will fall back to the <code>QWindowsStyle</code>.</p>
<p>And this is where the problems start, because there is no simple way to determine what a particular QSS rule will do. Sometimes it will have a very precise effect, and other times it will completely clobber the normal styling. In addition, the exact outcome depends on what the current style is. So a QSS rule might look good on your own system, but there's no guarantee it will do so on others.</p>
<p>Using stylesheets is therefore always a compromise. Creating a custom <code>QStyle</code> would give you much more control, but stylesheets will usually be much easier to write and maintain. So it's a trade-off between convenience and precision.</p>
<p>However, there is a third option available. Do nothing. Respect the user's choice of widget styling - or at the very least, don't force them to accept yours.</p>
| 0 | 2016-10-08T15:53:13Z | [
"python",
"css",
"user-interface",
"pyqt",
"qss"
] |
Pygame: Collision of two images | 39,929,640 | <p>I'm working on my school project for which im designing a 2D game.</p>
<p>I have 3 images, one is the player and the other 2 are instances (coffee and computer). What i want to do is, when the player image collides with one of the 2 instances i want the program to print something.</p>
<p>I'm unsure if image collision is possible. But i know rect collision is possible. However, after several failed attempts, i can't manage to make my images rects. Somebody please help me. Here is my source code:</p>
<pre><code>import pygame
import os
black=(0,0,0)
white=(255,255,255)
blue=(0,0,255)
class Player(object):
def __init__(self):
self.image = pygame.image.load("player1.png")
self.image2 = pygame.transform.flip(self.image, True, False)
self.coffee=pygame.image.load("coffee.png")
self.computer=pygame.image.load("computer.png")
self.flipped = False
self.x = 0
self.y = 0
def handle_keys(self):
""" Movement keys """
key = pygame.key.get_pressed()
dist = 5
if key[pygame.K_DOWN]:
self.y += dist
elif key[pygame.K_UP]:
self.y -= dist
if key[pygame.K_RIGHT]:
self.x += dist
self.flipped = False
elif key[pygame.K_LEFT]:
self.x -= dist
self.flipped = True
def draw(self, surface):
if self.flipped:
image = self.image2
else:
im = self.image
for x in range(0, 810, 10):
pygame.draw.rect(screen, black, [x, 0, 10, 10])
pygame.draw.rect(screen, black, [x, 610, 10, 10])
for x in range(0, 610, 10):
pygame.draw.rect(screen, black, [0, x, 10, 10])
pygame.draw.rect(screen, black, [810, x, 10, 10])
surface.blit(self.coffee, (725,500))
surface.blit(self.computer,(15,500))
surface.blit(im, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((800, 600))#creates the screen
player = Player()
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
player.handle_keys() # movement keys
screen.fill((255,255,255)) # fill the screen with white
player.draw(screen) # draw the player to the screen
pygame.display.update() # update the screen
clock.tick(60) # Limits Frames Per Second to 60 or less
</code></pre>
| 1 | 2016-10-08T06:57:35Z | 39,929,752 | <p>Use <a href="http://pygame.org/docs/ref/rect.html" rel="nofollow">pygame.Rect()</a> to keep image size and position. </p>
<p>Image (or rather <code>pygame.Surface()</code>) has function <code>get_rect()</code> which returns <code>pygame.Rect()</code> with image size (and position).</p>
<pre><code>self.rect = self.image.get_rect()
</code></pre>
<p>Now you can set start position ie. <code>(0, 0)</code></p>
<pre><code>self.rect.x = 0
self.rect.y = 0
# or
self.rect.topleft = (0, 0)
# or
self.rect = self.image.get_rect(x=0, y=0)
</code></pre>
<p>(<code>Rect</code> use left top corner as (x,y)). </p>
<p>Use it to change position</p>
<pre><code>self.rect.x += dist
</code></pre>
<p>and to draw image</p>
<pre><code>surface.blit(self.image, self.rect)
</code></pre>
<p>and then you can test collision</p>
<pre><code>if self.rect.colliderect(self.rect_coffe):
</code></pre>
<hr>
<p>BTW: and now <code>class Player</code> looks almost like <a href="http://pygame.org/docs/ref/sprite.html" rel="nofollow">pygame.sprite.Sprite</a> :)</p>
| 0 | 2016-10-08T07:12:04Z | [
"python",
"python-2.7",
"pygame"
] |
How to find least-mean-square error quadratic upper bound? | 39,929,703 | <p>I have some data of the form</p>
<p><code>x1[i], x2[i], x3[i], z[i]</code>,</p>
<p>where <code>z[i]</code> is an unknown deterministic function of <code>x1[i], x2[i], and x3[i]</code>. I would like to find a quadratic function <code>u(x1, x2, x3)= a11*x1^2 + a22*x2^2 + a33*x3^2 + a12*x1*x2 + ... + a0</code> that overbounds the data, i.e., <code>u(x1[i], x2[i], x3[i]) >= z[i]</code> for all <code>i</code>, and that minimizes the sum of the squared errors subject to the constraints. </p>
<p>Is there a computationally efficient solution approach in either Python or Matlab?</p>
| 2 | 2016-10-08T07:05:26Z | 39,929,895 | <p>There is very simple solution. Just use polynomial regression in Mathlab (<a href="http://www.matrixlab-examples.com/polynomial-regression.html" rel="nofollow">http://www.matrixlab-examples.com/polynomial-regression.html</a>).
You will get a certain function P(x1[i],x2[i],x3[i]).
1. Then for each i compute expression Diff[i] = P(x1[i],x2[i],x3[i]) - z[i].
You will get some array Diff.
2. Select all the negative values.
3. Find the minimum value in Diff: M = Min(Diff).
4. The desired function is F(x1[i],x2[i],x3[i]) = P(x1[i],x2[i],x3[i]) + Abs(M), where Abs(M) - it's value excluding the sign of M.</p>
<p>But if you're not just limited to quadratic functions, you can vary the degree of the polynomial and eventually get a more precise solution.</p>
| 1 | 2016-10-08T07:32:01Z | [
"python",
"matlab",
"least-squares"
] |
How to find least-mean-square error quadratic upper bound? | 39,929,703 | <p>I have some data of the form</p>
<p><code>x1[i], x2[i], x3[i], z[i]</code>,</p>
<p>where <code>z[i]</code> is an unknown deterministic function of <code>x1[i], x2[i], and x3[i]</code>. I would like to find a quadratic function <code>u(x1, x2, x3)= a11*x1^2 + a22*x2^2 + a33*x3^2 + a12*x1*x2 + ... + a0</code> that overbounds the data, i.e., <code>u(x1[i], x2[i], x3[i]) >= z[i]</code> for all <code>i</code>, and that minimizes the sum of the squared errors subject to the constraints. </p>
<p>Is there a computationally efficient solution approach in either Python or Matlab?</p>
| 2 | 2016-10-08T07:05:26Z | 39,929,991 | <p>Your problem sounds like a <a href="https://en.wikipedia.org/wiki/Quadratic_programming" rel="nofollow">quadratic programming problem</a> with linear constraints. There are efficient algorithms to solve these and they are implemented in Matlab and Python as well; see <a href="https://www.mathworks.com/help/optim/ug/quadprog.html" rel="nofollow"><code>quadprog</code></a> and <a href="https://courses.csail.mit.edu/6.867/wiki/images/a/a7/Qp-cvxopt.pdf" rel="nofollow">CVXOPT</a> respectively.</p>
| 2 | 2016-10-08T07:43:59Z | [
"python",
"matlab",
"least-squares"
] |
Read and Append csv files in a folder without knowing the name of the files? | 39,929,777 | <p>Is it possible to have numpy look for CSV files in a folder where the code resides and appends couple of the CSV files together?</p>
<p>My current code does something like this:</p>
<pre><code>data = np.loadtxt('csv data file.csv', delimiter=',', skiprows=1)
</code></pre>
<p>Where I have to combine the csv file together and assign it a name.
I want to be able to do the above and put the complete file into one and assign it to data for some data manipulation and plotting without knowing the files names. </p>
<p>I know I can do it in panda like this:</p>
<pre><code>path =r'C:\DRO\DCL_rawdata_files'
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
df = pd.read_csv(file_,index_col=None, header=0)
list_.append(df)
frame = pd.concat(list_)
</code></pre>
<p>But I am trying to avoid any extra modules to add for simplicity. So can this be done with numpy?</p>
| 2 | 2016-10-08T07:15:18Z | 39,930,305 | <p><em>"Knowing the names of the files"</em> has nothing to do with the problem.</p>
<p>In the example with <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged 'pandas'" rel="tag">pandas</a>, the filenames are <em>known</em> after this line:</p>
<pre><code>allFiles = glob.glob(path + "/*.csv")
</code></pre>
<p>Now <code>allFiles</code> contains all filenames. Then, the loop goes through the filenames, loads each file and appends loaded data to <code>list_</code>. Exactly the same can be done with <a href="/questions/tagged/numpy" class="post-tag" title="show questions tagged 'numpy'" rel="tag">numpy</a>.</p>
<p>The only special thing is merging of all data into one data set:</p>
<pre><code>frame = pd.concat(list_)
</code></pre>
<p>Again, numpy has a similar function: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>numpy.concatenate</code></a>.</p>
<p>So, all together, with numpy:</p>
<pre><code>import numpy as np
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")
all_data = []
for filename in filenames:
data = np.loadtxt(filename, delimiter=',', skiprows=1)
all_data.append(data)
result = np.concatenate(all_data)
</code></pre>
| 0 | 2016-10-08T08:25:04Z | [
"python"
] |
Extract sub path from url with regex | 39,929,845 | <p>I have this url:</p>
<pre><code> http://www.example.com/en/news/2016/07/17/1207151/%D9%81%D8%AA%D9%88%D8%A7%DB%8C-%D8%B1%D9%87%D8%A8%D8%B1-
</code></pre>
<p>I am going to extract <code>1207151</code> here.</p>
<p>here is my regext:</p>
<pre><code>pattern = '(http[s]?:\/\/)?([^\/\s]+\/)+[^/]+[^/]+[^/]+[^/]/(?<field1>[^/]+)/'
</code></pre>
<p>but it's wrong!</p>
<p>what is my mistake?</p>
| 1 | 2016-10-08T07:25:35Z | 39,929,943 | <p>That will work for you :</p>
<pre><code>(?:http[s]?:\/\/)?(?:.*?)\/(?:.*?)\/(?:.*?)\/(?:.*?)\/(?:.*?)\/(?:.*?)\/(.*?)/
</code></pre>
<p><a href="https://regex101.com/r/uEfSJv/1" rel="nofollow">watch here</a></p>
| 0 | 2016-10-08T07:37:34Z | [
"python",
"regex",
"url"
] |
Extract sub path from url with regex | 39,929,845 | <p>I have this url:</p>
<pre><code> http://www.example.com/en/news/2016/07/17/1207151/%D9%81%D8%AA%D9%88%D8%A7%DB%8C-%D8%B1%D9%87%D8%A8%D8%B1-
</code></pre>
<p>I am going to extract <code>1207151</code> here.</p>
<p>here is my regext:</p>
<pre><code>pattern = '(http[s]?:\/\/)?([^\/\s]+\/)+[^/]+[^/]+[^/]+[^/]/(?<field1>[^/]+)/'
</code></pre>
<p>but it's wrong!</p>
<p>what is my mistake?</p>
| 1 | 2016-10-08T07:25:35Z | 39,929,952 | <p>You can use this regex in python code:</p>
<pre><code>>>> url = 'http://www.example.com/en/news/2016/07/17/1207151/%D9%81%D8%AA%D9%88%D8%A7%DB%8C-%D8%B1%D9%87%D8%A8%D8%B1-'
>>> re.search(r'^https?://(?:([^/]+)/){7}', url).group(1)
'1207151'
</code></pre>
<p><code>([^/]+)/){7}</code> will match 1 or more of any non-forward-slash and a <code>/</code> 7 times, giving us last match in captured group #1.</p>
| 2 | 2016-10-08T07:38:41Z | [
"python",
"regex",
"url"
] |
Extract sub path from url with regex | 39,929,845 | <p>I have this url:</p>
<pre><code> http://www.example.com/en/news/2016/07/17/1207151/%D9%81%D8%AA%D9%88%D8%A7%DB%8C-%D8%B1%D9%87%D8%A8%D8%B1-
</code></pre>
<p>I am going to extract <code>1207151</code> here.</p>
<p>here is my regext:</p>
<pre><code>pattern = '(http[s]?:\/\/)?([^\/\s]+\/)+[^/]+[^/]+[^/]+[^/]/(?<field1>[^/]+)/'
</code></pre>
<p>but it's wrong!</p>
<p>what is my mistake?</p>
| 1 | 2016-10-08T07:25:35Z | 39,929,955 | <p>You've got a couple things going on.</p>
<p>First you'll need to properly escape all of your <code>/</code>s. You've got most of them, but missed a couple:</p>
<pre><code>(http[s]?:\/\/)?([^\/\s]+\/)+[^\/]+[^\/]+[^\/]+[^\/]\/(?<field1>[^\/]+)\/
</code></pre>
<p>From here, you have a number of "1 or more not /" in a row that can be reduced:</p>
<pre><code>[^\/]+[^\/]+[^\/]+ ==> [^\/]{3,}
</code></pre>
<p>But that's not what you meant to do, you meant to have many blocks of "non /" followed by a "/" and based on your example, you want it 6 times before using your named capture group.</p>
<pre><code>([^\/]+\/){6}
</code></pre>
<p>Here's what works:</p>
<pre><code>http[s]?:\/\/([^\/]+\/){6}(?<field1>[^\/]+)\/
</code></pre>
<p>And you can see it in action here: <a href="https://regex101.com/r/kkqwRJ/2" rel="nofollow">https://regex101.com/r/kkqwRJ/2</a></p>
| 1 | 2016-10-08T07:38:55Z | [
"python",
"regex",
"url"
] |
Extract sub path from url with regex | 39,929,845 | <p>I have this url:</p>
<pre><code> http://www.example.com/en/news/2016/07/17/1207151/%D9%81%D8%AA%D9%88%D8%A7%DB%8C-%D8%B1%D9%87%D8%A8%D8%B1-
</code></pre>
<p>I am going to extract <code>1207151</code> here.</p>
<p>here is my regext:</p>
<pre><code>pattern = '(http[s]?:\/\/)?([^\/\s]+\/)+[^/]+[^/]+[^/]+[^/]/(?<field1>[^/]+)/'
</code></pre>
<p>but it's wrong!</p>
<p>what is my mistake?</p>
| 1 | 2016-10-08T07:25:35Z | 39,930,087 | <pre><code>import re
print re.search(r'.*/([^/]+)/.*',s).group(1)
</code></pre>
| 0 | 2016-10-08T07:56:30Z | [
"python",
"regex",
"url"
] |
Function works in python shell alone, but not when called to another function? | 39,929,874 | <p>I have a homework issue with one of my functions called function 4.
This is its code:</p>
<pre><code>def getSuit(n):
suits = []
if 1 <= n <= 13:
suits.append("Spades")
return suits
if 14 <= n <= 26:
suits.append("Hearts")
return suits
if 27 <= n <= 39:
suits.append("Clubs")
return suits
if 40 <= n <= 52:
suits.append("Diamonds")
return suits
</code></pre>
<p>Now the function works as it is if I call it into the shell like so:</p>
<pre><code>>>>getSuit(51)
>>>["Diamonds"]
</code></pre>
<p>However, I am making a new function that sets the value of the card and also calls function 4 to obtain the suit of the card, but when I call the function it only displays ["Spades"] no matter what number is chosen.</p>
<p>Here is the code for Function 5:</p>
<pre><code>def getCard(n):
n = (n-1) % 13 + 1
deckValue = []
grabSuit = getSuit(n) # Called Function 4 here. <---
if n == 1:
deckValue.append("Ace")
return deckValue + grabSuit
if 2 <= n <= 10:
deckValue.append(str(n))
return deckValue + grabSuit
if n == 11:
deckValue.append("Jack")
return deckValue + grabSuit
if n == 12:
deckValue.append("Queen")
return deckValue + grabSuit
if n == 13:
deckValue.append("King")
return deckValue + grabSuit
</code></pre>
<p>So now when I call it into the python shell this is my output:</p>
<pre><code>>>>getCard(52)
>>> ["King", "Spades"]
</code></pre>
<p>Whereas it should be:</p>
<pre><code>>>>getCard(52)
>>>["King", "Diamonds"]
</code></pre>
<p>Am I just not calling the functions variable correctly, or do I need to rewrite function 4? I can't seem to figure out as to why it won't display the other suits despite it working just fine alone.</p>
| 0 | 2016-10-08T07:29:55Z | 39,929,940 | <p>In <code>getCart</code> you change <code>n</code> before you use it with <code>getSuit()</code></p>
<pre><code>n = (n-1) % 13 + 1
grabSuit = getSuit(n)
</code></pre>
<p>change order</p>
<pre><code>grabSuit = getSuit(n)
n = (n-1) % 13 + 1
</code></pre>
| 1 | 2016-10-08T07:37:13Z | [
"python",
"list",
"function",
"python-3.x"
] |
Function works in python shell alone, but not when called to another function? | 39,929,874 | <p>I have a homework issue with one of my functions called function 4.
This is its code:</p>
<pre><code>def getSuit(n):
suits = []
if 1 <= n <= 13:
suits.append("Spades")
return suits
if 14 <= n <= 26:
suits.append("Hearts")
return suits
if 27 <= n <= 39:
suits.append("Clubs")
return suits
if 40 <= n <= 52:
suits.append("Diamonds")
return suits
</code></pre>
<p>Now the function works as it is if I call it into the shell like so:</p>
<pre><code>>>>getSuit(51)
>>>["Diamonds"]
</code></pre>
<p>However, I am making a new function that sets the value of the card and also calls function 4 to obtain the suit of the card, but when I call the function it only displays ["Spades"] no matter what number is chosen.</p>
<p>Here is the code for Function 5:</p>
<pre><code>def getCard(n):
n = (n-1) % 13 + 1
deckValue = []
grabSuit = getSuit(n) # Called Function 4 here. <---
if n == 1:
deckValue.append("Ace")
return deckValue + grabSuit
if 2 <= n <= 10:
deckValue.append(str(n))
return deckValue + grabSuit
if n == 11:
deckValue.append("Jack")
return deckValue + grabSuit
if n == 12:
deckValue.append("Queen")
return deckValue + grabSuit
if n == 13:
deckValue.append("King")
return deckValue + grabSuit
</code></pre>
<p>So now when I call it into the python shell this is my output:</p>
<pre><code>>>>getCard(52)
>>> ["King", "Spades"]
</code></pre>
<p>Whereas it should be:</p>
<pre><code>>>>getCard(52)
>>>["King", "Diamonds"]
</code></pre>
<p>Am I just not calling the functions variable correctly, or do I need to rewrite function 4? I can't seem to figure out as to why it won't display the other suits despite it working just fine alone.</p>
| 0 | 2016-10-08T07:29:55Z | 39,929,986 | <pre><code>def getCard(n):
grabSuit = getSuit(n) # Called Function 4 here. <--- Move to this line
n = (n-1) % 13 + 1
deckValue = []
</code></pre>
| -1 | 2016-10-08T07:43:22Z | [
"python",
"list",
"function",
"python-3.x"
] |
pexpect not executing command by steps | 39,929,970 | <p>I have this Python3 code which use Pexpect.</p>
<pre><code>import pexpect
import getpass
import sys
def ssh(username,password,host,port,command,writeline):
child = pexpect.spawn("ssh -p {} {}@{} '{}'".format(port,username,host,command))
child.expect("password: ")
child.sendline(password)
if(writeline):
print(child.read())
def scp(username,password,host,port,file,dest):
child = pexpect.spawn("scp -P {} {} {}@{}:{}".format(port,file,username,host,dest))
child.expect("password: ")
child.sendline(password)
try:
filename = sys.argv[1]
print("=== sendhw remote commander ===")
username = input("Username: ")
password = getpass.getpass("Password: ")
ssh(username,password,"some.host.net","22","mkdir ~/srakrnSRV",False)
scp(username,password,"some.host.net","22",filename,"~/srakrnSRV")
ssh(username,password,"some.host.net","22","cd srakrnSRV && sendhw {}".format(filename),True)
except IndexError:
print("No homework name specified.")
</code></pre>
<p>My aim is to:</p>
<ul>
<li>SSH into the host with the <code>ssh</code> function, create the directory <code>srakrnSRV</code>, then</li>
<li>upload a file into the <code>srakrnSRV</code> directory, which is previously created</li>
<li><code>cd</code> into <code>srakrnSRV</code>, and execute the <code>sendhw <filename></code> command. The <code>filename</code> variable is defined by command line parameteres, and print the result out.</li>
</ul>
<p>After running the entire code, Python prints out</p>
<pre><code>b'\r\nbash: line 0: cd: srakrnSRV: No such file or directory\r\n'
</code></pre>
<p>which is not expected, as the directory should be previously created.</p>
<p>Also, I tried manually creating the <code>srakrnSRV</code> folder in my remote host. After running the command again, it appears that <code>scp</code> function is also not running. The only runnning pexpect coomand was the last <code>ssh</code> function.</p>
<p>How to make it execute in order? Thanks in advance!</p>
| 0 | 2016-10-08T07:41:28Z | 40,005,934 | <p>You may lack permission for executing commands through ssh. Also there is possibility that your program sends scp before prompt occurs.</p>
| 0 | 2016-10-12T18:33:09Z | [
"python",
"ssh",
"pexpect"
] |
How to make exceptions during the iteration of a for loop in python | 39,930,022 | <p>Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an <code>if ______ in ____:</code> block into an existing <code>for</code> block.</p>
<p>For example, how would I change this block to iterate through each instance of <code>i</code>, omitting odd numbers. </p>
<pre><code>odds = '1 3 5 7 9'.split()
for i in range(x):
if i in odds:
continue
print(i)
</code></pre>
<p>this code works for <code>if i == y</code> but I cannot get it to work with a specific set of "y"s</p>
| 0 | 2016-10-08T07:49:32Z | 39,930,058 | <p>This has nothing to do with nesting. You are comparing apples to pears, or in this case, trying to find an <code>int</code> in a list of <code>str</code> objects.</p>
<p>So the <code>if</code> test never matches, because there is no <code>1</code> in the list <code>['1', '3', '5', '7', '9']</code>; there is no <code>3</code> or <code>5</code> or <code>7</code> or <code>9</code> either, because an integer is a different type of object from a string, even if that string contains digits that look, to you as a human, like digits.</p>
<p>Either convert your int to a string first, or convert your strings to integers:</p>
<pre><code>if str(i) in odds:
</code></pre>
<p>or</p>
<pre><code>odds = [int(i) for i in '1 3 5 7 9'.split()]
</code></pre>
<p>If you want to test for odd numbers, there is a much better test; check if the remainder of division by 2 is 1:</p>
<pre><code>if i % 2 == 1: # i is an odd number
</code></pre>
| 4 | 2016-10-08T07:53:35Z | [
"python",
"python-3.x",
"if-statement",
"for-loop",
"nested"
] |
How to make exceptions during the iteration of a for loop in python | 39,930,022 | <p>Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an <code>if ______ in ____:</code> block into an existing <code>for</code> block.</p>
<p>For example, how would I change this block to iterate through each instance of <code>i</code>, omitting odd numbers. </p>
<pre><code>odds = '1 3 5 7 9'.split()
for i in range(x):
if i in odds:
continue
print(i)
</code></pre>
<p>this code works for <code>if i == y</code> but I cannot get it to work with a specific set of "y"s</p>
| 0 | 2016-10-08T07:49:32Z | 39,930,076 | <p>If you are looking to iterate over a range of even numbers, then something like this should work. With X being an integer. The <code>2</code> is the step so this will omit odd numbers.</p>
<pre><code>for i in range(0,x,2):
print(i)
</code></pre>
<p>For more info check out the docs here:</p>
<p><a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">https://docs.python.org/2/library/functions.html#range</a></p>
<p>I ran in to a couple of problems with the code you provided, continue would just fall through to the print statement and the values in <code>odds</code> where chars not ints which meant the comparison failed.</p>
<p>Creating a list of integers and using <code>not in</code> instead of <code>in</code> will get around this.</p>
<pre><code>x = 10
odds = [1, 3, 5, 9]
for i in range(x):
if i not in odds:
print(i)
</code></pre>
| 0 | 2016-10-08T07:55:22Z | [
"python",
"python-3.x",
"if-statement",
"for-loop",
"nested"
] |
Why doesn't perceptron's implementation follow the formula in <python machine learning>? | 39,930,035 | <p>I'm beginner in machine learning. I begin my study with the book <a href="http://rads.stackoverflow.com/amzn/click/1783555130" rel="nofollow">python machine learning</a> and some videos online. </p>
<p>I'm confused by the implementation of Perceptron in "python machine learning". This is the formula:</p>
<p><a href="http://i.stack.imgur.com/LbiHK.png" rel="nofollow"><img src="http://i.stack.imgur.com/LbiHK.png" alt="enter image description here"></a></p>
<p>And this is the python implementation for the formula:
<a href="http://i.stack.imgur.com/ZpuLu.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZpuLu.png" alt="enter image description here"></a></p>
<p>But by the formula, it's W * X, not X * W in the implementation. They're not same for matrix.(For <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow">numpy dot</a>, if X is 2-D array, it's matrix multiplication.). Why does the implementation not follow the formula?</p>
<p>The actual values in above python codes from the Iris-example in the book are these:</p>
<pre><code>w[1:]: [-0.68 1.82]
X: [[ 3.3 0. ]
[ 3.32 0. ]
[ 3.34 0. ]
...,
[ 7.94 6.08]
[ 7.96 6.08]
[ 7.98 6.08]]
</code></pre>
<p>Thanks.</p>
| 1 | 2016-10-08T07:51:06Z | 39,930,268 | <p>A good question here. The answer should be two-fold.</p>
<h2>W dot X =?= X dot W</h2>
<p>You are perfectly right on that exchanging X and W yeilds different result for matrix multiplication. </p>
<p>However, in this situation, w and x are actually vectors, or m*1 matrix. The dot product results in a scalar. So in this situation, 'x dot w' and 'w dot x' are the same.</p>
<p>As you can see that x is interpreted as [x0, x1, x2, ..., xm], which indicates its vector nature.</p>
<p>What this function does is combining the inputs of a neuron with weight being <code>w</code>. These inputs are outputs from neurons from the previous layer. We know a neuron's output is a scalar.</p>
<h2>About the bias term W_[0]</h2>
<p>Actually the implementation <em>is</em> different in that a w_[0] is appended to the end of the polynomial. That is called a bias term, which modifies the result of linear combination of the inputs, or the <code>x</code>. It is a common practice in the implementations to use this bias term. But in math, we usually omit it since it doesn't change the linear nature of the combination. Of course in some situations this bias term is explicitly listed in the math representation.</p>
<h2>====== Update =======</h2>
<p>As the question has been updated, a further explain on the actual situation is added.</p>
<p>In this case, the first dimension is '<a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcast</a>' to the result. </p>
<p>Consider a simpler situation:</p>
<pre><code>w[1:]: [-0.68 1.82]
X: [ 3.3 0. ]
</code></pre>
<p>in which as @Peater and I explained, X and w are both vectors.</p>
<p>In the actual setup, X is not a matrix, but rather a vactor variable that changes on sampling, or time. Say X is of dimension [n * 2], that means x is a two-dimensional vector with n samples.</p>
<p>Here sample means different evaluations of a variable in different time frames, or different pixels. This dimension of X is broadcast to the result.</p>
| 1 | 2016-10-08T08:20:18Z | [
"python",
"machine-learning"
] |
Efficiently identifying ancestors/descendants within a given distance, in networkx | 39,930,083 | <p>Is there a function/method in networkx to identify all ancestors/descendants that are within a given (optionally weighted) distance?</p>
<p>For example, something that would efficiently produce the same result as the function below?</p>
<pre class="lang-py prettyprint-override"><code>import networkx
g = networkx.DiGraph()
edges_with_atts = [(1, 2, {'length':5}),
(1, 3, {'length':11}),
(2, 4, {'length':4}),
(2, 5,{'length':7})]
g.add_edges_from(edges_with_atts)
def descendants_within(graph, start_node=1, constraint=10, weight='length'):
result = set()
for node in networkx.descendants(graph, start_node):
if networkx.shortest_path_length(graph, start_node, node, weight) < constraint:
result.add(node)
return result
print(descendants_within(g))
#set([2, 4])
</code></pre>
| 0 | 2016-10-08T07:56:00Z | 39,932,770 | <p>There is a "cutoff" parameter for some of the NetworkX shortest path algorithms. For example, in your case you can run a "single source shortest path" calculation from your source node to all other nodes and limit the search to paths shorter than a specified cutoff length. In the example below Dijkstra's algorithm is used to compute the shortest paths for a weighed network. </p>
<pre><code>import networkx as nx
g = nx.DiGraph()
edges_with_atts = [(1, 2, {'length':5}),
(1, 3, {'length':11}),
(2, 4, {'length':4}),
(2, 5,{'length':7})]
g.add_edges_from(edges_with_atts)
lengths = nx.single_source_dijkstra_path_length(g, source=1, weight='length', cutoff=10)
print(dict(lengths).keys())
# [1, 2, 4]
</code></pre>
| 1 | 2016-10-08T13:12:17Z | [
"python",
"networkx",
"directed-graph"
] |
Convert CSV document to XML | 39,930,128 | <p>I know the question is redundant but I tried all the Python code that I found and modified for my file but they did not work. I need to find a way to convert my file <a href="http://opendata.paris.fr/explore/dataset/tournagesdefilmsparis2011" rel="nofollow">myData.csv</a> in to a XML format file which can be read by a navigator. </p>
<p>I just started to learn Python this month so I'm a beginner. This is my code:</p>
<pre><code>#! usr/bin/python
# -*- coding: utf-8 -*-
import csv, sys, os
from lxml import etree
csvFile = 'myData.csv' # création de la variable pour le fichier csv
reader= csv.reader(open(csvFile), delimiter=';', quoting=csv.QUOTE_NONE) # création d'une variable reader à qui on renvoie le tableau csv
print "<data>"
for record in reader:
if reader.line_num == 1:
header = record
else:
innerXml = ""
dontShow = False
type = ""
for i, field in enumerate(record):
innerXml += "<%s>" % header[i].lower() + field + "</%s>" % header[i].lower()
if i == 1 and field == "0":
type = "Next"
elif type == "" and i == 3 and field == "0":
type = "Next"
elif type == "" and i == 3 and field != "0":
type = "film"
if i == 1 and field == "X":
dontShow = True
if dontShow == False:
xml = "<%s>" % type
xml += innerXml
xml += "</%s>" % type
print xml
print "</data>"
</code></pre>
| 0 | 2016-10-08T08:00:13Z | 39,930,477 | <p>(posted as an answer so I can show a code block)</p>
<p>There are a lot of picky details when writing XML. In Python, you should probably use some version of ElementTree to help with that. One good tutorial is <a href="https://pymotw.com/2/xml/etree/ElementTree/create.html" rel="nofollow" title="PyMOTW">Creating XML Documents</a>. Quoting from there:</p>
<pre><code>from xml.etree.ElementTree import Element, SubElement, Comment, tostring
top = Element('top')
comment = Comment('Generated for PyMOTW')
top.append(comment)
child = SubElement(top, 'child')
child.text = 'This child contains text.'
child_with_tail = SubElement(top, 'child_with_tail')
child_with_tail.text = 'This child has regular text.'
child_with_tail.tail = 'And "tail" text.'
child_with_entity_ref = SubElement(top, 'child_with_entity_ref')
child_with_entity_ref.text = 'This & that'
print(tostring(top))
</code></pre>
<p>If you use this as an example of how to create a tree of XML elements, you should be able to translate your code into the XML structure you need.</p>
| 0 | 2016-10-08T08:50:05Z | [
"python",
"xml",
"csv"
] |
Convert CSV document to XML | 39,930,128 | <p>I know the question is redundant but I tried all the Python code that I found and modified for my file but they did not work. I need to find a way to convert my file <a href="http://opendata.paris.fr/explore/dataset/tournagesdefilmsparis2011" rel="nofollow">myData.csv</a> in to a XML format file which can be read by a navigator. </p>
<p>I just started to learn Python this month so I'm a beginner. This is my code:</p>
<pre><code>#! usr/bin/python
# -*- coding: utf-8 -*-
import csv, sys, os
from lxml import etree
csvFile = 'myData.csv' # création de la variable pour le fichier csv
reader= csv.reader(open(csvFile), delimiter=';', quoting=csv.QUOTE_NONE) # création d'une variable reader à qui on renvoie le tableau csv
print "<data>"
for record in reader:
if reader.line_num == 1:
header = record
else:
innerXml = ""
dontShow = False
type = ""
for i, field in enumerate(record):
innerXml += "<%s>" % header[i].lower() + field + "</%s>" % header[i].lower()
if i == 1 and field == "0":
type = "Next"
elif type == "" and i == 3 and field == "0":
type = "Next"
elif type == "" and i == 3 and field != "0":
type = "film"
if i == 1 and field == "X":
dontShow = True
if dontShow == False:
xml = "<%s>" % type
xml += innerXml
xml += "</%s>" % type
print xml
print "</data>"
</code></pre>
| 0 | 2016-10-08T08:00:13Z | 39,934,145 | <p>Consider building your XML with dedicated DOM objects and not a concatenation of strings which you can do with the <code>lxml</code> module. Using methods such as <code>Element()</code>, <code>SubElement()</code>, etc. you can iteratively build XML tree from reading CSV data:</p>
<pre><code>import csv
import lxml.etree as ET
headers = ['Titre', 'Realisateur', 'Date_Debut_Evenement', 'Date_Fin_Evenement', 'Cadre',
'Lieu', 'Adresse', 'Arrondissement', 'Adresse_complète', 'Geo_Coordinates']
# INITIALIZING XML FILE
root = ET.Element('root')
# READING CSV FILE AND BUILD TREE
with open('myData.csv') as f:
next(f) # SKIP HEADER
csvreader = csv.reader(f)
for row in csvreader:
data = ET.SubElement(root, "data")
for col in range(len(headers)):
node = ET.SubElement(data, headers[col]).text = str(row[col])
# SAVE XML TO FILE
tree_out = (ET.tostring(root, pretty_print=True, xml_declaration=True, encoding="UTF-8"))
# OUTPUTTING XML CONTENT TO FILE
with open('Output.xml', 'wb') as f:
f.write(tree_out)
</code></pre>
<p><strong>Output</strong></p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<root>
<data>
<Titre>1</Titre>
<Realisateur>BUS PALLADIUM</Realisateur>
<Date_Debut_Evenement>CHRISTOPHER THOMPSON</Date_Debut_Evenement>
<Date_Fin_Evenement>21 mai 2009</Date_Fin_Evenement>
<Cadre>21 mai 2009</Cadre>
<Lieu>EXTERIEUR</Lieu>
<Adresse>PLACE</Adresse>
<Arrondissement>PIGALLE</Arrondissement>
<Adresse_complète>75018</Adresse_complète>
<Geo_Coordinates>PLACE PIGALLE 75018 Paris France</Geo_Coordinates>
</data>
<data>
<Titre>2</Titre>
<Realisateur>LES INVITES DE MON PERE</Realisateur>
<Date_Debut_Evenement>ANNE LE NY</Date_Debut_Evenement>
<Date_Fin_Evenement>20 mai 2009</Date_Fin_Evenement>
<Cadre>20 mai 2009</Cadre>
<Lieu>DOMAINE PUBLIC</Lieu>
<Adresse>SQUARE</Adresse>
<Arrondissement>DU CLIGNANCOURT</Arrondissement>
<Adresse_complète>75018</Adresse_complète>
<Geo_Coordinates>SQUARE DU CLIGNANCOURT 75018 Paris France</Geo_Coordinates>
</data>
<data>
<Titre>3</Titre>
<Realisateur>DEMAIN, A L'AUBE</Realisateur>
<Date_Debut_Evenement>GAEL CABOUAT</Date_Debut_Evenement>
<Date_Fin_Evenement>17 avril 2009</Date_Fin_Evenement>
<Cadre>17 avril 2009</Cadre>
<Lieu>EXTERIEUR</Lieu>
<Adresse>RUE</Adresse>
<Arrondissement>QUINCAMPOIX</Arrondissement>
<Adresse_complète>75004</Adresse_complète>
<Geo_Coordinates>RUE QUINCAMPOIX 75004 Paris France</Geo_Coordinates>
</data>
...
</code></pre>
| 1 | 2016-10-08T15:29:52Z | [
"python",
"xml",
"csv"
] |
Best way to associate a player character with a server connection? | 39,930,167 | <p>I'm attempting to write a simple multiplayer type text game. I currently have a simple chat server right now. It's working just like it should, echoing the message to all the people connected.</p>
<p>I can't figure out how to take my next step. I want to associate the client connected with a player object. The player objects house the available commands someone can type in, so in order to move forward with parsing input I have to be able to do this - I just don't know how.</p>
<p>Currently the player object is just a standard object class with a few properties like 'name', 'id', 'location', that has a list of commands available to them. If you need a code example of that I can provide one.</p>
<p>Any ideas?</p>
<pre><code>import socket, select
from helpers.colorize import colorize
class Server(object):
def __init__(self, host, port):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((host, port))
self.server.listen(1)
self.clients = [self.server]
def start(self):
while True:
read_sockets,write_sockets,error_sockets = select.select(self.clients, [], [])
for sock in read_sockets:
#new conn
if sock == self.server:
sockfd, addr = self.server.accept()
self.clients.append(sockfd)
print "Connection from %s %s" % addr
#looks like a message
else:
#data recieved, lets try and do something
try:
data = sock.recv(4096)
if data: #we have something, parse it
self.sendall(sock, data) #give it to everyone for now
except: #disconnection, remove from our lists
self.sendall(sock, ("%s %s disconnected" % addr))
print "%s %s disconnected." % addr
socket.close()
self.clients.remove(sock)
continue
self.server.close()
def send(self, sock, message):
sock.send(colorize(message))
def sendall(self, sock, message):
#Do not send the message to master socket and the client who has send us the message
for socket in self.clients:
if socket != self.server:
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION_LIST.remove(socket)
if __name__ == "__main__":
s = Server('localhost', 2222)
s.start()
</code></pre>
| 0 | 2016-10-08T08:06:29Z | 39,930,417 | <p>You can use a dict to map <a href="https://docs.python.org/2/library/socket.html#socket.socket.fileno" rel="nofollow">fds of client sockets</a> to client objects.</p>
<p>When you receive some new messages, you can fetch the corresponding object from the dict and invoke methods on it.</p>
| 0 | 2016-10-08T08:39:49Z | [
"python",
"python-2.7"
] |
How to mock random.choice in python? | 39,930,244 | <p>I want <code>choice</code> to return the same value <code>1000</code> every time in my unittest. The following code doesn't work.</p>
<pre><code>import unittest
from random import choice
from mock import mock
def a():
return choice([1, 2, 3])
class mockobj(object):
@classmethod
def choice(cls, li):
return 1000
class testMock(unittest.TestCase):
def test1(self):
with mock.patch('random.choice', mockobj.choice):
self.assertEqual(a(), 1000)
</code></pre>
<p>The error message is as follows:</p>
<pre><code>Failure
Traceback (most recent call last):
File "test.py", line 15, in test1
self.assertEqual(a(), 1000)
AssertionError: 3 != 1000
</code></pre>
<p>How should I modify it to make it work? I'm using python2.7</p>
| 0 | 2016-10-08T08:16:33Z | 39,930,315 | <p>I don't know what is mockobj from tests but what you can do is.</p>
<pre><code> @mock.patch('random.choice')
def test1(self, choice_mock):
choice_mock.return_value = 1000
self.assertEqual(a(), 1000)
</code></pre>
| 3 | 2016-10-08T08:25:53Z | [
"python",
"unit-testing",
"mocking"
] |
How to mock random.choice in python? | 39,930,244 | <p>I want <code>choice</code> to return the same value <code>1000</code> every time in my unittest. The following code doesn't work.</p>
<pre><code>import unittest
from random import choice
from mock import mock
def a():
return choice([1, 2, 3])
class mockobj(object):
@classmethod
def choice(cls, li):
return 1000
class testMock(unittest.TestCase):
def test1(self):
with mock.patch('random.choice', mockobj.choice):
self.assertEqual(a(), 1000)
</code></pre>
<p>The error message is as follows:</p>
<pre><code>Failure
Traceback (most recent call last):
File "test.py", line 15, in test1
self.assertEqual(a(), 1000)
AssertionError: 3 != 1000
</code></pre>
<p>How should I modify it to make it work? I'm using python2.7</p>
| 0 | 2016-10-08T08:16:33Z | 39,930,639 | <p>The problem here is that <code>a()</code> is using an <em>unpatched</em> version of <code>random.choice</code>.</p>
<p>Compare functions <code>a</code> and <code>b</code>:</p>
<pre><code>import random
from random import choice
def a():
return choice([1, 2, 3])
def b():
return random.choice([1, 2, 3])
def choice1000(values):
return 1000
import unittest.mock as mock
with mock.patch('random.choice', choice1000):
print('a', a())
print('b', b())
</code></pre>
<p>It prints e.g.:</p>
<pre><code>a 3
b 1000
</code></pre>
<h1>Why?</h1>
<p>This line is the problem:</p>
<pre><code>from random import choice
</code></pre>
<p>It imported <code>random</code> and than stored <code>random.choice</code> into a new variable named <code>choice</code>.</p>
<p>Later, <code>mock.patch</code> patched the original <code>random.choice</code>, but not the local <code>choice</code>.</p>
<p>Can I patch the local one? Yes:</p>
<pre><code>with mock.patch('__main__.choice', choice1000):
print('a', a())
print('b', b())
</code></pre>
<p>Now it prints e.g.</p>
<pre><code>a 1000
b 1
</code></pre>
<p>(I used <code>'__main__'</code> because I put this code into the <a href="https://docs.python.org/3/library/__main__.html" rel="nofollow">top-level file</a> - it may be something else in your case)</p>
<h2>So what to do?</h2>
<p>Either patch everything, or take a different approach. For example, patch <code>a()</code> instead of <code>choice()</code>.</p>
<h1>Alternative Solution</h1>
<p>In this case, where you want to test behaviour of <code>random</code> functions, it may be better to use a <a href="https://docs.python.org/2/library/random.html#random.seed" rel="nofollow">seed</a></p>
<pre><code>def a():
return random.choice([1, 2, 3, 1000])
def test1(self):
random.seed(0)
self.assertEqual(a(), 1000)
</code></pre>
<p>You can't know beforehand what random values will be generated for a certain seed, but you can be sure that they will always be the same. Which is exactly what you need in tests.</p>
<p>In the last example above, I tested <code>a()</code> after <code>random.seed(0)</code> once and it returned 1000, so I can be sure it will do so every time:</p>
<pre><code>>>> import random
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
</code></pre>
| 3 | 2016-10-08T09:11:32Z | [
"python",
"unit-testing",
"mocking"
] |
python spark change dataframe column data type to int error | 39,930,266 | <p>I want to cast the column type to int and get the first 3 rows</p>
<pre><code> df.withColumn("rn", rowNumber().over(windowSpec).cast('int')).where("rn"<=3).drop("rn").show()
</code></pre>
<p>but I this error </p>
<pre><code>TypeError: unorderable types: str() <= int()
</code></pre>
| 2 | 2016-10-08T08:20:03Z | 39,931,934 | <p>The error is here:</p>
<pre><code>.where("rn"<=3)
</code></pre>
<p>And here's how you can figure that out if you ever encounter a similar problem in the future. Following</p>
<pre><code>TypeError: unorderable types: str() <= int()
</code></pre>
<p>is a Python exception and there is no <code>Py4JError</code>. This typically means you can dismiss JVM issues and focus on core Python. The only part of your code where you explicitly compare things is:</p>
<pre><code>"rn" <= 3
</code></pre>
<p>If you want it to be a SQL literal you should pass a string:</p>
<pre><code>.where("rn <= 3")
</code></pre>
<p>If you want <code>rn</code> to be resolved as a column use <code>col</code> function:</p>
<pre><code>from pyspark.sql.functions import col
.where(col("rn") <= 3)
</code></pre>
<p>Also <code>rowNumber</code> function has been removed in the latest release. You should use <code>row_number</code> for a forward compatibility.</p>
| 1 | 2016-10-08T11:42:46Z | [
"python",
"apache-spark",
"types",
"casting"
] |
Django: How do I get multiple values from checkboxes in dataTable | 39,930,273 | <p>In HTML, every form field needs a name attribute in order to be submitted to the server. But I used dataTable to display all data and pagination. The list checkbox just get the data of the current page not get data of next page or previous page. How can I get all the values of checkbox?</p>
<p>in the template</p>
<pre><code><input type="checkbox" name="orderId" value="{{ order_id }}" checked>
</code></pre>
<p>and in the view:</p>
<pre><code>order_list = request.POST.getlist('orderId')
</code></pre>
| 0 | 2016-10-08T08:20:57Z | 39,931,792 | <p>You can use a hidden input field(type hidden) containing the string (comma separated value), which can later be received on server side as string and further it's splited using split method which will result in desired list</p>
<pre><code> <form>
<input id="result" type="hidden" name="result">
<!--your data table goes here-->
</form>
<script>
$(document).ready(function(){
var resultarray=[];
$('form input:checkbox').on('change', function(){
var orderValue=$(this).val();
// if string already available then remove(uncheck operation)
if(resultarray.indexOf(orderValue)!=-1)
{
resultarray.splice(resultarray.indexOf(orderValue), 1);
}
else
{
//if sting is not available then add(check operation)
resultarray.push(orderValue);
}
var text="";
for(x in resultarray)
{
text+=x+",";
//you may add an extra condition for not adding comma at last element
}
$("#result").val(text);
});
});
</code></pre>
<p></p>
| 1 | 2016-10-08T11:26:34Z | [
"python",
"django",
"python-3.x"
] |
Attribute error with BeautifulSoup get method | 39,930,306 | <p>I'm trying to make a webscraper in Python using urllib and BeautifulSoup. My laptop works on Debian, so I don't use the latest version of urllib.</p>
<p>My goal is quite simple : extract values from a Wikipedia table <a href="https://fr.wikipedia.org/wiki/Liste_des_monuments_historiques_de_Chaumont" rel="nofollow">like this one</a>.</p>
<p>So I started my script with :</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
start ="https://fr.wikipedia.org/wiki/Liste_des_monuments_historiques_de_Strasbourg"
url = urllib.urlopen(start).read()
bsObj = BeautifulSoup(url)
table = bsObj.find("table", {"class":"wikitable sortable"})
lines = table.findAll("tr")
</code></pre>
<p>Then, I used a for loop to scrap specific values from each row of the Wikipedia table :</p>
<pre><code>for line in lines:
longitude = line.find("data", {"class":"p-longitude"})
print(longitude)
latitude = line.find("data", {"class":"p-latitude"})
print(latitude)
</code></pre>
<p>This gave for example :</p>
<pre><code><data class="p-longitude" value="7.764953">7° 45â²Â 54â³Â Est</data>
<data class="p-latitude" value="48.588848">48° 35â²Â 20â³Â Nord</data>
</code></pre>
<p>I thought that get() method would work fine, as :</p>
<pre><code>longitude = line.find("data", {"class":"p-longitude"}).get("value")
print(longitude)
</code></pre>
<p>But my terminal print this error :</p>
<pre><code>Traceback (most recent call last):
File "scraper_monu_historiques_wikipedia.py", line 14, in <module>
longitude = line.find("data", {"class":"p-longitude"}).get("value")
AttributeError: 'NoneType' object has no attribute 'get'
</code></pre>
<p>I didn't understand why, because my variables latitude and longitude are BeautifulSoup Tags (I checked with a type()), so the get methode should work...</p>
<p>Thanks in advance if you have the solution !</p>
| 0 | 2016-10-08T08:25:06Z | 39,930,357 | <p>In this loop:</p>
<pre><code>for line in lines:
longitude = line.find("data", {"class":"p-longitude"})
print(longitude)
latitude = line.find("data", {"class":"p-latitude"})
print(latitude)
</code></pre>
<p>For some of the lines, <code>longitude</code> and <code>latitude</code> are found, but for others the are not found, so they are set to <code>None</code>. You have to check whether it is found or not before performing any further operations, e.g.:</p>
<pre><code>for line in lines:
longitude = line.find("data", {"class":"p-longitude"})
latitude = line.find("data", {"class":"p-latitude"})
if longitude and latitude:
longitude_value = longitude.get('value')
latitude_value = latitude.get('value')
print(longitude_value, latitude_value)
</code></pre>
| 3 | 2016-10-08T08:32:16Z | [
"python",
"get",
"tags",
"beautifulsoup"
] |
using redis-py to bulk populate a redis list | 39,930,359 | <p>In a Django project, I'm using redis as a fast backend. </p>
<p>I can LPUSH multiple values in a redis list like so:</p>
<pre><code>lpush(list_name,"1","2","3")
</code></pre>
<p>However, I can't do it if I try</p>
<pre><code>values_list = ["1","2","3"]
lpush(list_name,values_list)
</code></pre>
<p>For the record, this doesn't return an error. Instead it creates a list <code>list_name</code> with a single value. E.g. <code>['["1","2","3"]']</code>. This is not usable if later one does <code>AnObject.objects.filter(id__in=values_list)</code>. Nor does it work if one does <code>AnObject.objects.filter(id__in=values_list[0])</code> (error: invalid literal for int() with base 10: '[').</p>
<p>What's the best way to LPUSH numerous values in bulk into a redis list (python example is preferred). </p>
| 0 | 2016-10-08T08:32:22Z | 39,930,371 | <p><code>lpush (list_name, *values_list)</code></p>
<p>This will unpack contents in value_list as parameters.</p>
<p>If you have enormous numbers of values to insert into db, you can pipeline them. Or you can use the command line tool <code>redis-cli --pipe</code> to populate a database</p>
| 0 | 2016-10-08T08:34:00Z | [
"python",
"django",
"redis"
] |
How to convert frozenset to normal sets or list? | 39,930,363 | <p>For example, I have a frozen set</p>
<pre><code>[frozenset({'a', 'c,'}), frozenset({'h,', 'a,'})]
</code></pre>
<p>I want to convert it to a normal list like</p>
<pre><code>[['a', 'c,'],['a,', 'd,']...]
</code></pre>
<p>What method should I use?</p>
| 0 | 2016-10-08T08:32:52Z | 39,930,454 | <pre><code>sets=[frozenset({'a', 'c,'}), frozenset({'h,', 'a,'})]
print([list(x) for x in sets])
</code></pre>
<p>The list comprehension will convert every frozenset in your list of sets and put them into a new list. That's probably what you want.</p>
<p>You can also you map, <code>map(list, sets)</code>. Please be aware, that in Python 3, if you want the result of <code>map</code> as list you need to manually convert it using <code>list</code>, otherwise, it's just a <code>map object</code> which looks like <code><map object 0xblahblah></code></p>
| 2 | 2016-10-08T08:46:35Z | [
"python",
"python-3.x"
] |
Remove a string that is a substring of other string in the list WITHOUT changing original order of the list | 39,930,434 | <p>I have a list.</p>
<pre><code>the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?']
</code></pre>
<p>I'd like to remove "Donald Trump has" from <code>the_list</code> because it's a substring of other list element.</p>
<p>Here is an important part. I want to do this without distoring the order of the original list.</p>
<p>The function I have (below) distorts the order of the original list. Because it sorts the list items by its length first. </p>
<pre><code>def substr_sieve(list_of_strings):
dups_removed = list_of_strings[:]
for i in xrange(len(list_of_strings)):
list_of_strings.sort(key = lambda s: len(s))
j=0
j=i+1
while j <= len(list_of_strings)-1:
if list_of_strings[i] in list_of_strings[j]:
try:
dups_removed.remove(list_of_strings[i])
except:
pass
j+=1
return dups_removed
</code></pre>
| 2 | 2016-10-08T08:42:52Z | 39,930,591 | <p>You can just recursively reduce the items.</p>
<p>Algorithm:</p>
<p>Loop over each item by popping it, decide if it needs to be kept or not.
Call the same function recursively with the reduced list.
Base condition is if the list has at-least one item (or two?).</p>
<p>Efficiency: It might not be the most efficient. I think some Divide and Conquer methods would be more apt?</p>
<pre><code>the_list = ['Donald Trump has', 'Donald Trump has small fingers',\
'What is going on?']
final_list = []
def remove_or_append(input):
if len(input):
first_value = input.pop(0)
found = False
for each in input:
if first_value in each:
found = True
break
else:
continue
for each in final_list:
if first_value in each:
found = True
break
else:
continue
if not found:
final_list.append(first_value)
remove_or_append(input)
remove_or_append(the_list)
print(final_list)
</code></pre>
<p>A slightly different version is:</p>
<pre><code>def substring_of_anything_else(item, list):
for idx, each in enumerate(list):
if idx == item[0]:
continue
else:
if item[1] in each:
return True
return False
final_list = [item for idx, item in enumerate(the_list)\
if not substring_of_anything_else((idx, item), the_list)]
</code></pre>
| 0 | 2016-10-08T09:03:33Z | [
"python",
"string",
"list"
] |
Remove a string that is a substring of other string in the list WITHOUT changing original order of the list | 39,930,434 | <p>I have a list.</p>
<pre><code>the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?']
</code></pre>
<p>I'd like to remove "Donald Trump has" from <code>the_list</code> because it's a substring of other list element.</p>
<p>Here is an important part. I want to do this without distoring the order of the original list.</p>
<p>The function I have (below) distorts the order of the original list. Because it sorts the list items by its length first. </p>
<pre><code>def substr_sieve(list_of_strings):
dups_removed = list_of_strings[:]
for i in xrange(len(list_of_strings)):
list_of_strings.sort(key = lambda s: len(s))
j=0
j=i+1
while j <= len(list_of_strings)-1:
if list_of_strings[i] in list_of_strings[j]:
try:
dups_removed.remove(list_of_strings[i])
except:
pass
j+=1
return dups_removed
</code></pre>
| 2 | 2016-10-08T08:42:52Z | 39,930,940 | <p>You can do this without sorting:</p>
<pre><code>the_list = ['Donald Trump has', "I've heard Donald Trump has small fingers",
'What is going on?']
def winnow(a_list):
keep = set()
for item in a_list:
if not any(item in other for other in a_list if item != other):
keep.add(item)
return [ item for item in a_list if item in keep ]
winnow(the_list)
</code></pre>
<p>Sorting may allow fewer comparisons overall, but that seems highly data-dependent, and could be a premature optimization.</p>
| 1 | 2016-10-08T09:45:22Z | [
"python",
"string",
"list"
] |
Remove a string that is a substring of other string in the list WITHOUT changing original order of the list | 39,930,434 | <p>I have a list.</p>
<pre><code>the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?']
</code></pre>
<p>I'd like to remove "Donald Trump has" from <code>the_list</code> because it's a substring of other list element.</p>
<p>Here is an important part. I want to do this without distoring the order of the original list.</p>
<p>The function I have (below) distorts the order of the original list. Because it sorts the list items by its length first. </p>
<pre><code>def substr_sieve(list_of_strings):
dups_removed = list_of_strings[:]
for i in xrange(len(list_of_strings)):
list_of_strings.sort(key = lambda s: len(s))
j=0
j=i+1
while j <= len(list_of_strings)-1:
if list_of_strings[i] in list_of_strings[j]:
try:
dups_removed.remove(list_of_strings[i])
except:
pass
j+=1
return dups_removed
</code></pre>
| 2 | 2016-10-08T08:42:52Z | 39,931,663 | <p>A simple solution.</p>
<p>But first, let's also add '<em>Donald Trump</em>', <em>'Donald'</em> and <em>'Trump'</em> in the end to make it a better test case.</p>
<pre><code>>>> forbidden_text = "\nX08y6\n" # choose a text that will hardly appear in any sensible string
>>> the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?',
'Donald Trump', 'Donald', 'Trump']
>>> new_list = [item for item in the_list if forbidden_text.join(the_list).count(item) == 1]
>>> new_list
['Donald Trump has small fingers', 'What is going on?']
</code></pre>
<p>Logic:</p>
<ol>
<li>Concatenate all list element to form a single string.
<strong><code>forbidden_text.join(the_list)</code>.</strong></li>
<li>Search if an item in the list has occurred only once. If it occurs more than once it is a sub-string.<strong><code>count(item) == 1</code></strong></li>
</ol>
<blockquote>
<p><a href="https://docs.python.org/2/library/stdtypes.html#str.count" rel="nofollow">str.count(sub[, start[, end]])</a></p>
<p>Return the number of non-overlapping occurrences of substring <code>sub</code> in the range <code>[start, end]</code>. Optional arguments <code>start</code> and <code>end</code> are interpreted as in slice notation.</p>
</blockquote>
<hr>
<p><code>forbidden_text</code> is used instead of <code> "" </code>(blank string), to handle a case like these :</p>
<p><code>>>> the_list = ['DonaldTrump', 'Donald', 'Trump']</code></p>
<hr>
<p>As correctly pointed by Nishant, above code fails for <code>the_list = ['Donald', 'Donald']</code></p>
<p>Using a <code>set(the_list)</code> instead of <code>the_list</code> solves the problem.<br>
<code>>>> new_list = [item for item in the_list if forbidden_text.join(set(the_list)).count(item) == 1]</code></p>
| 2 | 2016-10-08T11:11:48Z | [
"python",
"string",
"list"
] |
Read from binary file with Python 3.5 | 39,930,642 | <p>I use this piece of code:</p>
<pre><code>from struct import Struct
import struct
def read_chunk(fmt, fileobj):
chunk_struct = Struct(fmt)
chunk = fileobj.read(chunk_struct.size)
return chunk_struct.unpack(chunk)
def read_record(fileobj):
author_id, len_author_name = read_chunk('ii', f)
author_name, nu_of_publ = read_chunk(str(len_author_name)+'si', f) # 's' or 'c' ?
record = { 'author_id': author_id,
'author_name': author_name,
'publications': [] }
for pub in range(nu_of_publ):
pub_id, len_pub_title = read_chunk('ii', f)
pub_title, num_pub_auth = read_chunk(str(len_pub_title)+'si', f)
record['publications'].append({
'publication_id': pub_id,
'publication_title': pub_title,
'publication_authors': [] })
for auth in range(num_pub_auth):
len_pub_auth_name = read_chunk('i', f)
pub_auth_name = read_chunk(str(len_pub_auth_name)+'s', f)
record['publications']['publication_authors'].append({'name': pub_auth_name})
year_publ, nu_of_cit = read_chunk('ii', f)
# Finish building your record with the remaining fields...
for cit in range(nu_of_cit):
cit_id, len_cit_title = read_chunk('ii', f)
cit_title, num_cit_auth = read_chunk(str(len_cit_title)+'si', f)
for cit_auth in range(num_cit_auth):
len_cit_auth_name = read_chunk('i', f)
cit_auth_name = read_chunk(str(len_cit_auth_name)+'s', f)
year_cit_publ = read_chunk('i', f)
return record
def parse_file(filename):
records = []
with open(filename, 'rb') as f:
while True:
try:
records.append(read_record(f))
except struct.error:
break
</code></pre>
<p>to read this file:</p>
<p><a href="https://drive.google.com/open?id=0B3SYAHrxLP69NHlWc25KeXFHNVE" rel="nofollow">https://drive.google.com/open?id=0B3SYAHrxLP69NHlWc25KeXFHNVE</a></p>
<p>with this format:</p>
<p><a href="http://i.stack.imgur.com/qHVBs.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/qHVBs.jpg" alt="spec"></a></p>
<p>Inside the function read_record, it read correct variables author_id, len_author_name, author_name but the nu_of_publ and below variables aren't read correct.</p>
<p>Any idea what's wrong?</p>
<p>When i run this piece of code:</p>
<pre><code>author_id, len_author_name = read_chunk('LL', f)
author_name, nu_of_publ= read_chunk(str(len_author_name)+'sL', f)
#nu_of_publ = read_chunk('I', f)# 's' or 'c' ?
record = { 'author_id': author_id,
'author_name': author_name,
'publications': [] }
print (record, nu_of_publ)
for pub in range(nu_of_publ):
pub_id, len_pub_title = read_chunk('LL', f)
print (pub_id, len_pub_title)
</code></pre>
<p>i take this result:</p>
<p>{'author_name': b'Scott Shenker', 'author_id': 1, 'publications': []} 256
15616 1953384704</p>
<p>but it will print 200 instead 256, 1 instead 15616 etc.</p>
| 0 | 2016-10-08T09:11:46Z | 39,931,026 | <p>This format is not correct:</p>
<pre><code>author_name, nu_of_publ = read_chunk(str(len_author_name)+'si', f)
</code></pre>
<p>You are defining a structure of N characters and an integer. Those structures are <a href="https://docs.python.org/2/library/struct.html#byte-order-size-and-alignment" rel="nofollow">aligned</a>, the same way as they would if you had the structure defined in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a>:</p>
<pre><code>struct {
char author_name[N];
int nu_of_publ;
};
</code></pre>
<p>What alignment does is: it puts beginning of every int to a position which is a multiple of 4. This is done (in C) because CPUs are optimized for accessing such addresses.</p>
<p>So, if author's name's length is 6, the next two bytes will be skipped before reading the next integer.</p>
<p>One solution to separate the structures:</p>
<pre><code>author_name = read_chunk(str(len_author_name)+'s', f)
nu_of_publ, = read_chunk('i', f)
</code></pre>
<p><strong>Note:</strong> The comma after nu_of_publ (<code>nu_of_publ,</code>) is to unpack the tuple returned by <code>read_chunk</code>.</p>
<p>Another solution is to specify structure with <code>=</code> at the beginning, based on the <a href="https://docs.python.org/2/library/struct.html#byte-order-size-and-alignment" rel="nofollow">table from spec</a>:</p>
<pre><code>author_name, nu_of_publ = read_chunk('={}si'.format(len_author_name), f)
</code></pre>
| 0 | 2016-10-08T09:56:35Z | [
"python",
"python-3.x",
"binaryfiles"
] |
How do I catch an Interrupt signal in Python when inside a blocking boost c++ method? | 39,930,722 | <p>I have a toolset which has been written in C++, and given Boost bindings for Python.</p>
<p>Initially, this code was all C++, and I caught a <kbd>CTRL</kbd>+<kbd>C</kbd> interrupt with:</p>
<pre><code>signal( SIGINT, signalCallbackHandler );
</code></pre>
<p>and</p>
<pre><code>void signalCallbackHandler(int /*signum*/)
{
g_myObject->stop();
}
</code></pre>
<p>This worked fine.</p>
<p>However, now I've added the Python bindings in, I'm using Python to initialise the objects.</p>
<p>My initial thought was to do it like this:</p>
<pre><code>import signal
def handle_interrupt( signum, frame ) :
g_myObject.stop()
signal.signal( signal.SIGINT, handle_interrupt )
g_myObject = MyObject()
g_myObject.start()
</code></pre>
<p>However, this signal handler is never called.</p>
<p>How should I be handling an interrupt like this? Do I need to do it inside C++, and then call the Python function from there?</p>
| 1 | 2016-10-08T09:20:30Z | 39,936,134 | <p>I have <em>a</em> solution that works for this, although it'd be cleaner if I could get the signal caught in Python rather than C++.</p>
<p>One thing I didn't mention before is that MyObject is a singleton, so I'm getting it with <code>MyObject.getObject()</code></p>
<p>In Python, I've got:</p>
<pre><code>def signalHandler( signum ) :
if signum == signal.SIGINT :
MyObject.getObject().stop()
def main() :
signal.signal( signal.SIGINT, handle_interrupt )
myObject = MyObject.getObject()
myObject.addSignalHandler( signal.SIGINT, signalHandler )
myObject.start()
</code></pre>
<p>In my C++ code, in an area that shouldn't know anything about Python, I have:</p>
<pre><code>class MyObject
{
public :
void addSignalHandler( int signum, void (*handler)( int, void* ), void *data = nullptr );
void callSignalHandler( int signum );
private :
std::map<int, std::pair<void (*)( int, void* ), void*> > m_signalHandlers;
}
void signalCallbackHandler( int signum )
{
MyObject::getObject()->callSignalHandler( signum );
}
void MyObject::addSignalHandler( int signum, void (*handler)( int, void* ), void *data )
{
m_signalHandlers.insert( std::pair<int, std::pair<void (*)( int, void* ), void *> >( signum, std::make_pair( handler, data ) ) );
signal( signum, signalCallbackHandler );
}
void MyObject::callSignalHandler( int signum )
{
std::map<int, std::pair<void (*)( int, void* ), void*> >::iterator handler = m_signalHandlers.find( signum );
if( handler != m_signalHandlers.end() )
{
handler->second.first( signum, handler->second.second );
}
}
</code></pre>
<p>And then in my Python bindings:</p>
<pre><code>void signalHandlerWrapper( int signum, void *data )
{
if( nullptr == data )
{
return;
}
PyObject *func = (PyObject*)( data );
if( PyFunction_Check( func ) )
{
PyObject_CallFunction( func, "i", signum );
}
}
void addSignalHandlerWrapper( MyObject *o, int signum, PyObject *func )
{
Py_INCREF( func );
if( PyFunction_Check( func ) )
{
o->addSignalHandler( signum, &signalHandlerWrapper, func );
}
}
</code></pre>
<p>What I don't have, which I should add, is something in addSignalHandlerWrapper() that will check if there was already something fo that signal number, and if so, get it and decrement the reference before adding the new one. I haven't done this yet, as this functionality is only used for ending the program, but for completeness, it should be put in place.</p>
<p>Anyway, as I said at the start, this is more involved than it could be. It also only works as I have a singleton that can keep track of the function pointers.</p>
| 0 | 2016-10-08T18:53:36Z | [
"python",
"c++",
"boost"
] |
How do I catch an Interrupt signal in Python when inside a blocking boost c++ method? | 39,930,722 | <p>I have a toolset which has been written in C++, and given Boost bindings for Python.</p>
<p>Initially, this code was all C++, and I caught a <kbd>CTRL</kbd>+<kbd>C</kbd> interrupt with:</p>
<pre><code>signal( SIGINT, signalCallbackHandler );
</code></pre>
<p>and</p>
<pre><code>void signalCallbackHandler(int /*signum*/)
{
g_myObject->stop();
}
</code></pre>
<p>This worked fine.</p>
<p>However, now I've added the Python bindings in, I'm using Python to initialise the objects.</p>
<p>My initial thought was to do it like this:</p>
<pre><code>import signal
def handle_interrupt( signum, frame ) :
g_myObject.stop()
signal.signal( signal.SIGINT, handle_interrupt )
g_myObject = MyObject()
g_myObject.start()
</code></pre>
<p>However, this signal handler is never called.</p>
<p>How should I be handling an interrupt like this? Do I need to do it inside C++, and then call the Python function from there?</p>
| 1 | 2016-10-08T09:20:30Z | 39,938,987 | <p>Your python signal handler is not called because python defers execution of signal handlers until after the next bytecode instruction is to be executed - see <a href="https://docs.python.org/3.6/library/signal.html" rel="nofollow">the library documentation for signal</a>, section 18.8.1.1.</p>
<p>The reason for this is that a signal can arrive at any time, potentially half way through the execution of a python instruction. It would not be safe for the VM to begin executing the signal handler, because the VM is in an unknown state. Therefore, the actual signal handler installed by python merely sets a flag telling the VM to call the signal handler after the current instruction is complete.</p>
<p>If the signal arrives during execution of your C++ function, then the signal handler sets the flag and returns back to your C++ function.</p>
<p>If the main purpose of the signal handler is to allow the C++ function to be interrupted, then I suggestion you dispense with the python signal handler and install a C++ signal handler that sets a flag which triggers an early exit in your C++ code (presumably returning a value that indicates it was interrupted).</p>
<p>That approach would allow you to use the same code regardless of whether you are calling your code from python, C++ or perhaps another binding.</p>
| 0 | 2016-10-09T01:10:29Z | [
"python",
"c++",
"boost"
] |
Changing default keybinding in yhat's Rodeo IDE | 39,930,830 | <p>To comment out a block in Rodeo the <a href="http://rodeo.yhat.com/docs/#keyboard-shortcuts" rel="nofollow">docs</a> state to do <code>ctrl + /</code>. But on my machine thats not working, so I want to change a single keysetting. Where I am able to do this in Rodeo?</p>
| 0 | 2016-10-08T09:32:45Z | 39,930,917 | <p>You can edit key-bindings in preferences <a href="http://rodeo.yhat.com/docs/#preferences" rel="nofollow">http://rodeo.yhat.com/docs/#preferences</a></p>
<p>Changing the key bindings should avoid the use of <code>ctrl + /</code>, but if you just want to change a single setting, as far as I know, it's not possible. It's hardwired in <a href="https://github.com/yhat/rodeo/tree/master/src/browser/ace" rel="nofollow">https://github.com/yhat/rodeo/tree/master/src/browser/ace</a> . You can write some code and build your own IDE if necessary.</p>
| 1 | 2016-10-08T09:42:34Z | [
"python",
"key-bindings",
"rodeo"
] |
Make an exe which extracts multiple files | 39,930,855 | <p>I want to make an executable file which will extract multiple files into a specific location.
I've read about the 'extractall()' function, and using unzip, but how do I contain the multiple files inside the executable python file, so each time the user double click the exe file, it will extract these files into the hard coded location?</p>
| -2 | 2016-10-08T09:35:14Z | 39,931,080 | <p>Be aware that your archive will be (in most part) platform-specific -- it may not work on <code>Windows</code> if you make it on a <code>Unix-like</code> machine and vice versa, etc.</p>
<p>I would recommend that you check this <code>pymakeself</code> which is a pypi <a href="https://pypi.python.org/pypi/pymakeself" rel="nofollow">https://pypi.python.org/pypi/pymakeself</a></p>
<p>In fact, you may find the following codes immediately relevant.</p>
<p><strong>Self Extracting Archiver (Python recipe):</strong> <a href="http://code.activestate.com/recipes/577485-self-extracting-archiver/" rel="nofollow">http://code.activestate.com/recipes/577485-self-extracting-archiver/</a></p>
<p><strong>Build a compressed self-extracting executable script on UNIX (Python recipe):</strong> <a href="http://code.activestate.com/recipes/497000-build-a-compressed-self-extracting-executable-scri/" rel="nofollow">http://code.activestate.com/recipes/497000-build-a-compressed-self-extracting-executable-scri/</a></p>
| 0 | 2016-10-08T10:02:33Z | [
"python",
"zip",
"executable"
] |
Create new line in a python string that does NOT effect output? | 39,930,934 | <p>is it possible to create a new line in a string in one's python code that does NOT effect output?</p>
<p>Like:</p>
<pre><code>print "This
is
my
string"
</code></pre>
<p>But the output when the program is run would just be "This is my string"</p>
<p>Just for purposes of formatting the program in a more readable way for very long strings.</p>
| 0 | 2016-10-08T09:44:52Z | 39,930,964 | <p>You can invoke <a href="https://docs.python.org/2/reference/lexical_analysis.html#explicit-line-joining" rel="nofollow">explicit line joining</a>, adding a backslash at the end of each line:</p>
<pre><code>>>> print "this \
... is \
... my \
... string"
this is my string
</code></pre>
| 2 | 2016-10-08T09:47:44Z | [
"python",
"python-2.7"
] |
Create new line in a python string that does NOT effect output? | 39,930,934 | <p>is it possible to create a new line in a string in one's python code that does NOT effect output?</p>
<p>Like:</p>
<pre><code>print "This
is
my
string"
</code></pre>
<p>But the output when the program is run would just be "This is my string"</p>
<p>Just for purposes of formatting the program in a more readable way for very long strings.</p>
| 0 | 2016-10-08T09:44:52Z | 39,931,001 | <p>You could use implicit string joining too:</p>
<pre><code>print("this "
"is "
"my "
"string")
</code></pre>
| 4 | 2016-10-08T09:52:08Z | [
"python",
"python-2.7"
] |
Create new line in a python string that does NOT effect output? | 39,930,934 | <p>is it possible to create a new line in a string in one's python code that does NOT effect output?</p>
<p>Like:</p>
<pre><code>print "This
is
my
string"
</code></pre>
<p>But the output when the program is run would just be "This is my string"</p>
<p>Just for purposes of formatting the program in a more readable way for very long strings.</p>
| 0 | 2016-10-08T09:44:52Z | 39,932,128 | <p>You could also add a comma after every print statement to print the next output on the same line :</p>
<pre><code>print "This",
print "is",
print "my",
print "string"
</code></pre>
| 1 | 2016-10-08T12:05:10Z | [
"python",
"python-2.7"
] |
Python: How to convert google location timestaMps in a year-month-day-hour-minute-seconds format? | 39,930,950 | <p>I am playing around with my google location data (which one can download here <a href="https://takeout.google.com/settings/takeout" rel="nofollow">https://takeout.google.com/settings/takeout</a>). </p>
<p>The location data is a json file, of which one variable is 'timestaMps' (e.g. one observation is "1475146082971"). How do I convert this into a datetime? </p>
<p>Thanks!</p>
| -1 | 2016-10-08T09:46:17Z | 39,931,087 | <p>Use <a href="https://docs.python.org/2/library/datetime.html#datetime.date.fromtimestamp" rel="nofollow">fromtimestamp</a> method from datetime module.
To convert your 'timestaMps' to timestamp you need to convert it to int(). Formating of timestamp is done with <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow">strftime()</a>. </p>
<pre><code>from datetime import datetime
datetime.fromtimestamp(int("1475146082971")).strftime('%Y-%m-%d %H:%M:%S')
</code></pre>
| 0 | 2016-10-08T10:02:59Z | [
"python",
"google-maps",
"datetime",
"timestamp"
] |
Cannot import keras after installation | 39,930,952 | <p>I'm trying to setup <code>keras</code> deep learning library for <code>Python3.5</code> on Ubuntu 16.04 LTS and use <code>Tensorflow</code> as a backend. I have <code>Python2.7</code> and <code>Python3.5</code> installed. I have installed <code>Anaconda</code> and with help of it <code>Tensorflow</code>, <code>numpy</code>, <code>scipy</code>, <code>pyyaml</code>. Afterwards I have installed <code>keras</code> with command</p>
<blockquote>
<p>sudo python setup.py install</p>
</blockquote>
<p>Although I can see <code>/usr/local/lib/python3.5/dist-packages/Keras-1.1.0-py3.5.egg</code> directory, I cannot use <code>keras</code> library. When I try to import it in python it says</p>
<blockquote>
<p>ImportError: No module named 'keras'</p>
</blockquote>
<p>I have tried to install <code>keras</code> using<code>pip3</code>, but got the same result. </p>
<p>What am I doing wrong? Any Ideas?</p>
| 0 | 2016-10-08T09:46:36Z | 39,931,939 | <h2>Diagnose</h2>
<p>If you have <code>pip</code> installed (you should have it until you use Python 3.5), list the installed Python packages, like this:</p>
<pre><code>$ pip list | grep -i keras
Keras (1.1.0)
</code></pre>
<p>If you donât see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)</p>
<p>Consult the <code>pip.log</code> to see whatâs wrong.</p>
<p>You can also display your Python path like this:</p>
<pre><code>$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
</code></pre>
<p>Make sure the Keras library appears in the <code>/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages</code> path (the path is different on Ubuntu).</p>
<p>If not, try do uninstall it, and retry installation:</p>
<pre><code>$ pip uninstall Keras
</code></pre>
<h2>Use a virtualenv</h2>
<p>Itâs a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">guide</a>).</p>
<p>The best usage is to create a <code>virtualenv</code> directory (in your home, for instance), and store your virtualenvs in:</p>
<pre><code>cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel
</code></pre>
<p>Then install Keras:</p>
<pre><code>pip install keras
</code></pre>
<p>You get:</p>
<pre><code>$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)
</code></pre>
<p>But, you also need to install extra libraries, like Tensorflow:</p>
<pre><code>$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
...
ImportError: No module named 'tensorflow'
</code></pre>
<p>The installation guide of TesnsorFlow is here: <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation" rel="nofollow">https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation</a></p>
| 1 | 2016-10-08T11:43:22Z | [
"python",
"ubuntu",
"tensorflow",
"anaconda",
"keras"
] |
Cannot change python interpreter | 39,930,958 | <p>I imported a python project from github into pycharm. I developed this project in windows but now i am using mac. </p>
<p>I changed the project interpreter in the settings but when running it says: "error running the project" and the error message says that it points to the python interpreter of my old windows directory.</p>
<p>I have already tried to delete my /user/USR_NAME/Library/Caches but it didn't help. I also changed the project interpreter but it didn't help</p>
<p>I am using python2.7 with anaconda </p>
<p>Is there any project properties file with the old settings?</p>
| 0 | 2016-10-08T09:47:04Z | 39,931,237 | <p>I found the solution. There is a file under the project directory: .idea/workspace.xml which contains the older setting. Deleting this file caused pycharm to recreate it with the new settings.</p>
| 0 | 2016-10-08T10:23:22Z | [
"python",
"pycharm",
"anaconda"
] |
Using decorators inside a class | 39,931,089 | <p>I am trying to implement a simple logging feature within my app.</p>
<pre><code>class messages(object):
# Implement decorator here
def on(self):
def wrapper():
# Do something here
return wrapper
def off(self):
def wrapper():
# Do something here
return wrapper
class website(object):
@messages.on #This line can be switched on/off
def login(self):
# Do a whole bunch of stuff here
self.response = "[+] Login Succeeded!"
website = website()
website.login() # prints self.response based on @messages.on/off
</code></pre>
<p>But i am not sure what i need to apply in my decorator. I have tried creating instances and adding params but mostly receive TypeError. I am fairly new to decorators. Any help would be appreciated and i'd love to remember this for next time.</p>
| 0 | 2016-10-08T10:03:19Z | 39,931,211 | <p>Below is the sample decorator that you may use:</p>
<pre><code>class Utilities:
@staticmethod
def add_logger(func):
def wrapped_func(*args, **kwargs):
# Sample logic, feel free to update this
try:
func_response = func(*args, **kwargs)
except:
print 'I am error handled by logger'
func_response = None
return func_response
return wrapped_func
</code></pre>
<p>Let's define your class now:</p>
<pre><code>class Dog(object):
@Utilities.add_logger
def bark(self):
print 'In bark'
@Utilities.add_logger
def my_error_function(self):
print 'In my_error_function'
raise Exception # <--- Raises Exception
</code></pre>
<p>Now, let's check how it works:</p>
<pre><code>>>> dog = Dog()
>>> dog.bark()
In bark
>>> dog.my_error_function()
In my_error_function
I am error handled by logger # Content from logger in case of exception
</code></pre>
<p><strong><em>Note:</strong> You shouldn't really be creating a <code>class</code> here to store utility function. Create a separate utility file and write such functions over there.</em></p>
<p>Without class, your decorator should be like (let's say in <em>utility.py</em>):</p>
<pre><code>def add_logger(func):
def wrapped_func(*args, **kwargs):
# Sample logic, feel free to update this
try:
func_response = func(*args, **kwargs)
except:
print 'I am error handled by logger'
func_response = None
return func_response
return wrapped_func
</code></pre>
<p>For using it, simply do:</p>
<pre><code>import utility
class Dog(object):
@utility.add_logger
def bark(self):
print 'In bark'
</code></pre>
| 0 | 2016-10-08T10:20:59Z | [
"python",
"oop",
"decorator"
] |
Using decorators inside a class | 39,931,089 | <p>I am trying to implement a simple logging feature within my app.</p>
<pre><code>class messages(object):
# Implement decorator here
def on(self):
def wrapper():
# Do something here
return wrapper
def off(self):
def wrapper():
# Do something here
return wrapper
class website(object):
@messages.on #This line can be switched on/off
def login(self):
# Do a whole bunch of stuff here
self.response = "[+] Login Succeeded!"
website = website()
website.login() # prints self.response based on @messages.on/off
</code></pre>
<p>But i am not sure what i need to apply in my decorator. I have tried creating instances and adding params but mostly receive TypeError. I am fairly new to decorators. Any help would be appreciated and i'd love to remember this for next time.</p>
| 0 | 2016-10-08T10:03:19Z | 39,931,226 | <ol>
<li><p>If you just want Dog to bark (like in the example), there is no need for enabling a decorator</p>
<pre><code>class Dog(object):
def __init__(self):
self.sound = "Woof!"
def bark(self):
return self.sound
</code></pre></li>
<li><p>If you want to enable logging for some functions in class, here is a code that does that with explanation in comments</p>
<pre><code>from functools import wraps
class Utilities(object):
@staticmethod # no default first argument in logger function
def logger(f): # accepts a function
@wraps(f) # good practice https://docs.python.org/2/library/functools.html#functools.wraps
def wrapper(self, *args, **kwargs): # explicit self, which means this decorator better be used inside classes only
print("Before:", self.sound)
result = f(self, *args, **kwargs)
print("After:", self.sound)
return result
return wrapper
class Dog(object):
def __init__(self):
self.sound = "Woof!"
@Utilities.logger
def run(self):
"""Perform running movement"""
print("Running")
</code></pre></li>
</ol>
<p>Example:</p>
<pre><code>>>> dog = Dog()
>>> dog.run()
Before: Woof!
Running
After: Woof!
</code></pre>
<p>Though after all there is no need to store decorators functionality in the <code>Utilities</code> class - it is better to have a separate module (file) named <code>utils</code> and put decorator there as a standalone function</p>
| 1 | 2016-10-08T10:22:45Z | [
"python",
"oop",
"decorator"
] |
Selecting a rows from a panda frame based on a time that has been converted into datetime format and stripped from a POSIX time stamp, python | 39,931,243 | <p>I am using the code below to pull data from Google Finance. The timestamp is in POSIX form, so it is converted into data time. When I try to fiter it based on a time criteria <strong>(14:35:00)</strong>, it returns an empty table. I suspect it has to do with the POSIX/ datetime conversion, but have no idea how to resolve it.</p>
<pre><code>def get_intraday_data(symbol, interval_seconds=301, num_days=10):
# Specify URL string based on function inputs.
url_string = 'http://www.google.com/finance/getprices?q={0}'.format(symbol.upper())
url_string += "&i={0}&p={1}d&f=d,o,h,l,c,v".format(interval_seconds,num_days)
# Request the text, and split by each line
r = requests.get(url_string).text.split()
# Split each line by a comma, starting at the 8th line
r = [line.split(',') for line in r[7:]]
# Save data in Pandas DataFrame
df = pd.DataFrame(r, columns=['Datetime','Close','High','Low','Open','Volume'])
# Convert UNIX to Datetime format
df['Datetime'] = df['Datetime'].apply(lambda x: datetime.datetime.fromtimestamp(int(x[1:])))
#Seperate Date and Time
df['Time'],df['Date']= df['Datetime'].apply(lambda x:x.time()), df['Datetime'].apply(lambda x:x.date())
#Convert 'Close','High','Low','Open', deleting 'Volume'
''''df['Close'] = df['Close'].astype('float64')
df['High'] = df['High'].astype('float64')
df['Low'] = df['Low'].astype('float64')
df['Open'] = df['Open'].astype('float64')'''
del df['Volume']
del df['Datetime']
df[['Close','High','Low','Open']] = df[['Close','High','Low','Open']].astype('float64')
# Calculating %Change and Range
df['%pct'] = (df['Close'] - df['Open'])/df['Open']
df['Range'] = df['High'] - df['Low']
#Sort Columns
return df
</code></pre>
<p>I have stored the results of this function as <strong>NAS</strong></p>
<pre><code>NAS = get_intraday_data('IXIC', interval_seconds=301, num_days= 100)
</code></pre>
<p>The Filter Criteria is:</p>
<pre><code>NAS[NAS['Time'] == '14:35:00']
</code></pre>
<p>I will appreciate assistance on this.</p>
| 0 | 2016-10-08T10:23:51Z | 39,931,462 | <p>You can use this </p>
<pre><code>NAS.query('Datetime.dt.hour==14 and Datetime.dt.minute==35 and Datetime.dt.second==0')
</code></pre>
<p><strong>Edit:</strong>
Applied dt on datetime series instead of time series</p>
<pre><code>raw_data = {'Datetime': ['2015-05-01T14:35:00', '2016-07-04T02:26:00', '2013-02-01T04:41:00']}
df = pd.DataFrame(raw_data, columns = ['Datetime'])
df["Datetime"] = pd.to_datetime(df["Datetime"])
df['Time'],df['Date']= df['Datetime'].apply(lambda x:x.time()), df['Datetime'].apply(lambda x:x.date())
df = df.set_index(df["Datetime"])
df['hour']=df['Datetime'].dt.hour
df['minute']=df['Datetime'].dt.minute
df['second']=df['Datetime'].dt.second
df.query('Datetime.dt.hour==14 and Datetime.dt.minute==35 and Datetime.dt.second==0')
</code></pre>
| 1 | 2016-10-08T10:47:14Z | [
"python",
"python-3.x",
"datetime",
"pandas",
"posixlt"
] |
Selecting a rows from a panda frame based on a time that has been converted into datetime format and stripped from a POSIX time stamp, python | 39,931,243 | <p>I am using the code below to pull data from Google Finance. The timestamp is in POSIX form, so it is converted into data time. When I try to fiter it based on a time criteria <strong>(14:35:00)</strong>, it returns an empty table. I suspect it has to do with the POSIX/ datetime conversion, but have no idea how to resolve it.</p>
<pre><code>def get_intraday_data(symbol, interval_seconds=301, num_days=10):
# Specify URL string based on function inputs.
url_string = 'http://www.google.com/finance/getprices?q={0}'.format(symbol.upper())
url_string += "&i={0}&p={1}d&f=d,o,h,l,c,v".format(interval_seconds,num_days)
# Request the text, and split by each line
r = requests.get(url_string).text.split()
# Split each line by a comma, starting at the 8th line
r = [line.split(',') for line in r[7:]]
# Save data in Pandas DataFrame
df = pd.DataFrame(r, columns=['Datetime','Close','High','Low','Open','Volume'])
# Convert UNIX to Datetime format
df['Datetime'] = df['Datetime'].apply(lambda x: datetime.datetime.fromtimestamp(int(x[1:])))
#Seperate Date and Time
df['Time'],df['Date']= df['Datetime'].apply(lambda x:x.time()), df['Datetime'].apply(lambda x:x.date())
#Convert 'Close','High','Low','Open', deleting 'Volume'
''''df['Close'] = df['Close'].astype('float64')
df['High'] = df['High'].astype('float64')
df['Low'] = df['Low'].astype('float64')
df['Open'] = df['Open'].astype('float64')'''
del df['Volume']
del df['Datetime']
df[['Close','High','Low','Open']] = df[['Close','High','Low','Open']].astype('float64')
# Calculating %Change and Range
df['%pct'] = (df['Close'] - df['Open'])/df['Open']
df['Range'] = df['High'] - df['Low']
#Sort Columns
return df
</code></pre>
<p>I have stored the results of this function as <strong>NAS</strong></p>
<pre><code>NAS = get_intraday_data('IXIC', interval_seconds=301, num_days= 100)
</code></pre>
<p>The Filter Criteria is:</p>
<pre><code>NAS[NAS['Time'] == '14:35:00']
</code></pre>
<p>I will appreciate assistance on this.</p>
| 0 | 2016-10-08T10:23:51Z | 39,932,494 | <p>I see that you are converting <code>timestamp</code> to <code>datetime</code> incorrectly. You are calling <code>datetime</code> twice.</p>
<p>Replace</p>
<pre><code>df['Datetime'] = df['Datetime'].apply(lambda x: datetime.datetime.fromtimestamp(int(x[1:])))
</code></pre>
<p>with </p>
<pre><code>df['Datetime'] = df['Datetime'].apply(lambda x: datetime.fromtimestamp(int(x[1:])))
</code></pre>
<p>In 2nd part of your question:</p>
<pre><code>NAS = get_intraday_data('IXIC', interval_seconds=301, num_days= 100)
NAS[NAS['Time'] == '14:35:00']
</code></pre>
<p>You care comparing instance of <code>datetime.time</code> with string, which is not correct. Try</p>
<pre><code>NAS[NAS['Time'] == datetime.strptime('14:35:00', '%H:%M:%S').time()]
</code></pre>
<p>it should work as expected.</p>
<p><strong>Update:</strong></p>
<p>Running script with suggested changes will display data as:</p>
<p><code>
Close High Low Open Time Date %pct<br>
60 5162.448 5165.124 5162.448 5165.057 14:35:00 2016-07-29 -0.000505<br>
138 5181.768 5183.184 5181.193 5181.404 14:35:00 2016-08-01 0.000070<br>
216 5130.514 5131.933 5130.434 5131.893 14:35:00 2016-08-02 -0.000269<br>
294 5146.608 5146.608 5143.827 5144.788 14:35:00 2016-08-03 0.000354<br>
372 5163.854 5164.154 5162.997 5164.021 14:35:00 2016-08-04 -0.000032<br>
450 5221.624 5221.911 5220.658 5220.789 14:35:00 2016-08-05 0.000160<br>
528 5204.111 5204.240 5202.476 5202.865 14:35:00 2016-08-08 0.000239<br>
.
.
.
3648 5282.999 5283.017 5279.008 5279.340 14:35:00 2016-10-04 0.000693<br>
3726 5324.450 5325.375 5323.628 5324.129 14:35:00 2016-10-05 0.000060<br>
3804 5310.945 5311.454 5310.194 5310.558 14:35:00 2016-10-06 0.000073<br>
3882 5295.064 5295.080 5292.184 5292.327 14:35:00 2016-10-07 0.000517
</code></p>
| 1 | 2016-10-08T12:42:41Z | [
"python",
"python-3.x",
"datetime",
"pandas",
"posixlt"
] |
How to get mask from numpy array according to all values on third axis | 39,931,382 | <p>I have numpy array like:</p>
<pre><code>A = np.zeros((X,Y,Z))
</code></pre>
<p>Later I fill the array with values and I need to find x,y coordinates according to values in arrays on z axis to replace it with different array.</p>
<p>Example with<code>Z=2</code> I have array</p>
<pre><code>A = [ [ [1,2], [2,1], [0, 0] ],
[ [1,1], [1,1], [0, 0] ], ]
</code></pre>
<p>I need something like</p>
<pre><code>A[ where A[x,y,:] == [1,2] ] = [2,1]
</code></pre>
<p>What will produce array</p>
<pre><code>A = [ [ [2,1], [2,1], [0, 0] ],
[ [1,1], [1,1], [0, 0] ], ]
</code></pre>
<p>Is it possible to achieve that somehow simple? I would like to avoid iteration over the x,y coordinates.</p>
| 1 | 2016-10-08T10:40:41Z | 39,931,494 | <p>One vectorized approach -</p>
<pre><code>A[(A == [1,2]).all(-1)] = [2,1]
</code></pre>
<p>Sample run -</p>
<pre><code>In [15]: A
Out[15]:
array([[[1, 2],
[2, 1],
[0, 0]],
[[1, 1],
[1, 2],
[0, 0]]])
In [16]: A[(A == [1,2]).all(-1)] = [2,1]
In [17]: A
Out[17]:
array([[[2, 1],
[2, 1],
[0, 0]],
[[1, 1],
[2, 1],
[0, 0]]])
</code></pre>
| 3 | 2016-10-08T10:50:55Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
Creating Rest Api in python using JSON? | 39,931,557 | <p>I'm new to python REST API and so facing some particular problems. I want that when I enter the input as pathlabid(primary key), I want the corresponding data assigned with that key as output. When I run the following code i only get the data corresponding to the first row of table in database even when the id i enter belong to some other row.
This is the VIEWS.PY </p>
<pre><code>class pathlabAPI(View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
# dont worry about the CSRF here
return super(pathlabAPI, self).dispatch(*args, **kwargs)
def post(self, request):
post_data = json.loads(request.body)
Pathlabid = post_data.get('Pathlabid') or ''
lablist = []
labdict = {}
lab = pathlab()
labs = lab.apply_filter(Pathlabid = Pathlabid)
if Pathlabid :
for p in labs:
labdict["Pathlabid"] = p.Pathlabid
labdict["name"] = p.Name
labdict["email_id"] = p.Emailid
labdict["contact_no"] = p.BasicContact
labdict["alternate_contact_no"] = p.AlternateContact
labdict["bank_account_number"] = p.Accountnumber
labdict["ifsccode"] = p.IFSCcode
labdict["country"] = p.Country
labdict["homepickup"] = p.Homepickup
lablist.append(labdict)
return HttpResponse(json.dumps(lablist))
else:
for p in labs:
labdict["bank_account_number"] = p.Accountnumber
lablist.append(labdict)
return HttpResponse(json.dumps(lablist))
</code></pre>
| 0 | 2016-10-08T10:58:25Z | 39,932,091 | <p>You are return the response in for loop so that loop break on 1st entry </p>
<pre><code>import json
some_list = []
for i in data:
some_list.append({"key": "value"})
return HttpResponse(json.dumps({"some_list": some_list}), content_type="application/json")
</code></pre>
<p>Try above example to solve your problem</p>
| 0 | 2016-10-08T12:02:01Z | [
"python",
"json",
"django",
"rest",
"api"
] |
Creating Rest Api in python using JSON? | 39,931,557 | <p>I'm new to python REST API and so facing some particular problems. I want that when I enter the input as pathlabid(primary key), I want the corresponding data assigned with that key as output. When I run the following code i only get the data corresponding to the first row of table in database even when the id i enter belong to some other row.
This is the VIEWS.PY </p>
<pre><code>class pathlabAPI(View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
# dont worry about the CSRF here
return super(pathlabAPI, self).dispatch(*args, **kwargs)
def post(self, request):
post_data = json.loads(request.body)
Pathlabid = post_data.get('Pathlabid') or ''
lablist = []
labdict = {}
lab = pathlab()
labs = lab.apply_filter(Pathlabid = Pathlabid)
if Pathlabid :
for p in labs:
labdict["Pathlabid"] = p.Pathlabid
labdict["name"] = p.Name
labdict["email_id"] = p.Emailid
labdict["contact_no"] = p.BasicContact
labdict["alternate_contact_no"] = p.AlternateContact
labdict["bank_account_number"] = p.Accountnumber
labdict["ifsccode"] = p.IFSCcode
labdict["country"] = p.Country
labdict["homepickup"] = p.Homepickup
lablist.append(labdict)
return HttpResponse(json.dumps(lablist))
else:
for p in labs:
labdict["bank_account_number"] = p.Accountnumber
lablist.append(labdict)
return HttpResponse(json.dumps(lablist))
</code></pre>
| 0 | 2016-10-08T10:58:25Z | 39,962,089 | <p>There are a number of issues with the overall approach and code but to fix the issue you're describing, but as a first fix I agree with the other answer: you need to take the <code>return</code> statement out of the loop. Right now you're <code>return</code>ing your list as soon as you step through the loop one time, which is why you always get a list with one element. Here's a fix for that (you will need to add <code>from django.http import JsonResponse</code> at the top of your code):</p>
<pre><code>if Pathlabid:
for p in labs:
labdict["Pathlabid"] = p.Pathlabid
labdict["name"] = p.Name
labdict["email_id"] = p.Emailid
labdict["contact_no"] = p.BasicContact
labdict["alternate_contact_no"] = p.AlternateContact
labdict["bank_account_number"] = p.Accountnumber
labdict["ifsccode"] = p.IFSCcode
labdict["country"] = p.Country
labdict["homepickup"] = p.Homepickup
lablist.append(labdict)
else:
for p in labs:
labdict["bank_account_number"] = p.Accountnumber
lablist.append(labdict)
return JsonResponse(json.dumps(lablist))
</code></pre>
<p>As suggested in the comments, using Django Rest Framework or a similar package would be an improvement. As a general rule, in Django or other ORMs, you want to avoid looping over a queryset like this and adjusting each element. Why not serialize the queryset itself and do the logic that's in this loop in your template or other consumer?</p>
| 0 | 2016-10-10T15:52:41Z | [
"python",
"json",
"django",
"rest",
"api"
] |
Python socket recv() doesn't get every message if send too fast | 39,931,611 | <p>I send mouse coordinates from python server to python client via socket. Mouse coordinates are send every time when mouse movement event is catch on the server which means quite often (dozen or so per second).</p>
<p>Problem is when I use python server and python client on different hosts. Then only part of messages are delivered to the client.
e.g. 3 first messages are delivered, 4 messages aren't delivered, 4 messages are delivered etc...</p>
<p>Everything is fine when server and client are on the same host (localhost).</p>
<p>Everything is fine when server and client are on different hosts but instead of python client I use standard windows Telnet client to read messages from the server.</p>
<p>I noticed that when I use time.sleep(0.4) break between each message that is send then all messages are delivered. Problem is I need that information in real time not with such delay. Is it possible to achieve that in Python using sockets?</p>
<p>Below python client code that I use:</p>
<pre><code>import pickle
import socket
import sys
host = '192.168.1.222'
port = 8888
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Faile. Error:" + str(msg[0]), "Error message : " + msg[1]
sys.exit()
mySocket = socket.socket()
mySocket.connect((host,port))
while 1:
data = mySocket.recv(1024)
if not data: break
load_data = pickle.loads(data)
print 'parametr x: ' + str(load_data[0])
print 'parametr y : ' + str(load_data[1])
mySocket.close()
</code></pre>
| 1 | 2016-10-08T11:04:43Z | 39,931,786 | <p>You are using TCP (SOCK_STREAM) which is a reliable protocol which (contrary to UDP) does not loose any messages, even if the recipient is not reading the data fast enough. Instead TCP will reduce the sending speed.<br>
This means that the problem must be somewhere in your application code. </p>
<p>One possibility is that the problem is in your sender, i.e. that you use <code>socket.send</code> and do not check if all the bytes you've intended to send are really got send. But this check needs to be done since <code>socket.send</code> might only send part of the data if the socket buffer of the OS is full which can happen if the client does not read the data fast enough.</p>
<p>Another possibility is that your <code>socket.recv</code> call receives more data than your <code>pickle.loads</code> needs and that the rest of the data gets discarded (not sure if <code>pickle.loads</code> will throw an exception if too much data are provided). Note that TCP is not a message but a stream protocol so it might be that you have more that <code>socket.recv</code> will return a buffer which contains more than one pickled object but you only read the first. The chance that this will happen on a network is higher than on localhost because by default the TCP layer will try to concatenate multiple <code>send</code> buffers into a single TCP packet for better use of the connection (i.e. less overhead). And the chance is high that these will then be received within the same <code>recv</code> call. By putting a <code>sleep(0.4)</code> on the sender side you've effectively switch off this optimization of TCP, see <a href="https://en.wikipedia.org/wiki/Nagle%27s_algorithm" rel="nofollow">NAGLE algorithm</a> for details.</p>
<p>Thus the correct way to implement what you want would be:</p>
<ul>
<li>Make sure that all data are delivered at the server, i.e. check the return of <code>socket.send</code>.</li>
<li>Make sure that you unpack all messages you receive. To do this you probable need to add some message layer on top of the TCP stream to find out where the message boundary is.</li>
</ul>
| 2 | 2016-10-08T11:26:00Z | [
"python",
"sockets"
] |
Reverse Count after threshold | 39,931,757 | <p>I am feeding a number slider in RhinoPython to increment the y value. I wish to reverse the increment when y equals a certain value. I have figured out how to make it negative, but that is not what I'm after. Sorry, for the simplicity of this question and thank you. In short the number slider increments the variable and once it reaches 45, then it would count down with every increment of the number slider. </p>
<pre><code>len = 45
inc = float(.1)
if y >= len:
y *= -inc
print (y)
</code></pre>
| 0 | 2016-10-08T11:22:19Z | 39,931,880 | <p>First of all, don't call a variable <code>len</code>, because it is a name of standard library function.
If I understood the question correctly, the code would be</p>
<pre><code>threshold = 45
inc = .1
y = 0
while True: # goes forever, put your own code here
if y >= threshold:
inc *= -1
y += inc
print (y)
</code></pre>
<p>After y reaches 45, it start counting down. No stop condition when you count down though, it's an infinite cycle here</p>
| 2 | 2016-10-08T11:36:56Z | [
"python",
"rhino3d"
] |
Matplotlib and it's connection with tkinter | 39,931,797 | <p>I have a question, which may not be even related to the modules. </p>
<p>In the code below, there is a function update, which will create a canvas by matplotlib and assign it to the related frame from tkinter. Then it create an event handler Cursor, which should print the position of the mouse into the console. But it does not. However, everything works just fine, if you delete method update and use the lines for creating figure, cursor and connection just in the body of the module.</p>
<p>What am I missing? I guess it is a basic knowledge of Python, the visibility and passing the right instance, I don't know. </p>
<pre><code>import matplotlib.pyplot as plt
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class Cursor (object):
def __init__ (self, fig):
self.fig = fig
print ("initializing")
def mouse_move (self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
print (x, y)
def connect (self):
print ("Connecting")
self.conmove = self.fig.canvas.mpl_connect ('motion_notify_event', self.mouse_move)
def pyplot_f ():
fig = plt.figure(figsize=(6,4), dpi=100)
axes = fig.add_subplot (111)
axes.plot([1,2,3,4], [1,2,3,4])
Canvas = FigureCanvasTkAgg (fig, master=frame_output)
canvas = Canvas.get_tk_widget()
canvas.grid(row=0,column=0, padx=5, pady=5, sticky="nesw")
return fig
w_width = 1000
w_height = 600
root = Tk()
root.resizable(0,0)
frame_output = Frame (root, bg="", relief=SUNKEN, width=w_width*0.8, height=w_height*0.9)
frame_output.grid(row=0, column=0, padx=20, pady=20, sticky=W+N+E+S)
frame_input = Frame (root, bg="", relief=RAISED,width=w_width*0.2, height=w_height*0.9)
frame_input.grid(row=0, column=1, padx=20, pady=20, sticky=W+N+E+S)
def update ():
fig = pyplot_f()
cursor = Cursor(fig)
cursor.connect()
def on_closing():
print ("Exiting")
root.quit()
update()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
</code></pre>
| 1 | 2016-10-08T11:26:54Z | 39,932,733 | <p>Your problem appears to be one about variable scope and lifetime.</p>
<p>When your <code>update()</code> function ends, the variables <code>fig</code> and <code>cursor</code> declared within it go out of scope. The figure and cursor objects created within your <code>update()</code> have no further references pointing to them, and so they end up being garbage-collected. Your <code>update()</code> function is successfully creating the figure and the cursor, but it isn't preventing them from being deleted again.</p>
<p>When you move the three lines within <code>update()</code> to the body of the module, the variables <code>fig</code> and <code>cursor</code> then remain in scope and don't get garbage-collected until the program ends. Hence your figure and cursor are created and not immediately garbage-collected.</p>
<p>The simplest way to fix this is for the <code>update()</code> function to return the cursor, and then keep that in module scope:</p>
<pre><code>def update ():
fig = pyplot_f()
cursor = Cursor(fig)
cursor.connect()
return cursor
# ...
cursor = update()
</code></pre>
<p>This prevents the cursor from being garbage-collected, and as the cursor has a reference to the figure, the figure won't get garbage-collected either.</p>
| 2 | 2016-10-08T13:09:06Z | [
"python",
"matplotlib",
"tkinter"
] |
Issue with pattern program using loops | 39,931,798 | <p>I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring GO's. And each new line has to be indented 3 spaces more then the one before. And this is the program I've come up with:</p>
<pre><code>lines = input("Lines= ")
cheers = input("Cheers= ")
if cheers == 1:
i = 1
space = 0
S = ""
while i<=lines:
S=S+(" "*space)+"GO \n"
i += 1
space+=3
print S
else:
n = 1
cheer1 = "GO BUDDY "
cheer2 = "GO"
space = 0
while n<= cheers:
print (" "*space)+(cheer1*cheers)+cheer2
space+=3
n += 1
</code></pre>
<p>But the problem with this is that it doesn't print out the right number of GO's in the number of cheers. How can I modify my code to fix this problem? This is the output format I want to get :</p>
<p><a href="http://i.stack.imgur.com/7ynbB.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7ynbB.jpg" alt="This is the format of the ouput I want to get"></a></p>
| 0 | 2016-10-08T11:27:11Z | 39,931,879 | <pre><code>def greet(lines, cheers):
i = 0
line_str = ""
while i < cheers: # Build the line string
i += 1
line_str += "GO" if i == cheers else "GO BUDDY "
i = 0
while i < lines: #Print each line
print(" "*(i*3) + line_str)
i += 1
greet(2,1)
greet(4,3)
greet(2,4)
</code></pre>
| 1 | 2016-10-08T11:36:55Z | [
"python",
"python-2.7",
"design-patterns"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.