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 |
---|---|---|---|---|---|---|---|---|---|
How to parse dates for incomplete dates in Python
| 39,653,042 |
<p>I am using dateutil.parser to parse dates and I want to throw an exception if the date is incomplete i.e January 1 (missing year) or January 2016 (missing day). So far I have the following </p>
<pre><code>try:
parse(date)
return parse(date).isoformat()
except ValueError:
return 'invalid'
</code></pre>
| 0 |
2016-09-23T05:14:47Z
| 39,655,241 |
<p>Parse takes a default argument from which it takes the unspecified parts. So the easiest solution (apart from using a different library) would be to call the function with two <em>different</em> default parameters.</p>
<p>If both calls return the same value the datetime is valid, otherwise some default value was used - you can even find out what was unspecified this way.</p>
| 0 |
2016-09-23T07:36:59Z
|
[
"python"
] |
AES-CBC 128, 192 and 256 encryption decryption in Python 3 using PKCS#7 padding
| 39,653,074 |
<p>I have searched a lot on SO about complete encryption decryption example with my requirement. In fact, I've got many links and examples but None is working for me for AES-192-CBC mode and AES-256-CBC.</p>
<p>I have got following example which is supposed to be working with all types but it is working only with AES-128-CBC mode. I am new to Python. Can anyone help me where I am wrong?</p>
<p>I am using Python 3.4 on windows and I can not move to Python 2.7.</p>
<pre><code>import base64
from Crypto.Cipher import AES
class AESCipher:
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def __init__(self, key, block_size=16):
if block_size < 2 or block_size > 255:
raise AESCipher.InvalidBlockSizeError('The block size must be between 2 and 255, inclusive')
self.block_size = block_size
self.key = key
self.iv = bytes(key[0:16], 'utf-8')
print(self.key)
print(key[0:16])
def __pad(self, text):
text_length = len(text)
amount_to_pad = self.block_size - (text_length % self.block_size)
if amount_to_pad == 0:
amount_to_pad = self.block_size
self.pad = chr(amount_to_pad)
return text + self.pad * amount_to_pad
def __unpad(self, text):
#pad = ord(text[-1])
#return text[:-pad]
text = text.rstrip(self.pad)
return text
def encrypt( self, raw ):
raw = self.__pad(raw)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return base64.b64encode(cipher.encrypt(raw))
def decrypt( self, enc ):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
return self.__unpad(cipher.decrypt(enc).decode("utf-8"))
e = AESCipher('1234567812345678', 16)
#e = AESCipher('123456781234567812345678', 24)
#e = AESCipher('12345678123456781234567812345678', 32)
secret_data = "hi"
enc_str = e.encrypt(secret_data)
print('enc_str: ' + enc_str.decode())
dec_str = e.decrypt(enc_str)
print('dec str: ' + dec_str)
</code></pre>
<p>Though this code encrypts the data with 192 and 256 bit encryption and successfully decrypt that too but my other .Net and Ruby application only able to decrypt the data which was encrypted using 128 encryption.</p>
<p>Note .Net and Ruby application are successfully tested with each other and with online encryption tool with all encryption types.</p>
<p><strong>Note that my application requires AES-CBC mode and PKCS#7 padding and must be run on Python 3.4.</strong></p>
| 1 |
2016-09-23T05:17:15Z
| 39,657,872 |
<p>Made it working by padding of 16 bytes for any encryption types. For that I used AES.block_size which is 16 by default for AES.</p>
<pre><code>import base64
from Crypto.Cipher import AES
class AESCipher:
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def __init__(self, key):
self.key = key
self.iv = bytes(key[0:16], 'utf-8')
print(self.key)
print(key[0:16])
def __pad(self, text):
text_length = len(text)
amount_to_pad = AES.block_size - (text_length % AES.block_size)
if amount_to_pad == 0:
amount_to_pad = AES.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
def __unpad(self, text):
pad = ord(text[-1])
return text[:-pad]
def encrypt( self, raw ):
raw = self.__pad(raw)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return base64.b64encode(cipher.encrypt(raw))
def decrypt( self, enc ):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
return self.__unpad(cipher.decrypt(enc).decode("utf-8"))
e = AESCipher('1234567812345678', 16)
#e = AESCipher('123456781234567812345678', 24)
#e = AESCipher('12345678123456781234567812345678', 32)
secret_data = "hi"
enc_str = e.encrypt(secret_data)
print('enc_str: ' + enc_str.decode())
dec_str = e.decrypt(enc_str)
print('dec str: ' + dec_str)
</code></pre>
| 1 |
2016-09-23T09:55:17Z
|
[
"python",
"aes",
"pycrypto",
"pkcs#7",
"cbc-mode"
] |
Difficulty in defining a higher-order function to mimic if statement
| 39,653,296 |
<p>I have been hard pressed to answer a question we were recently asked as part of an exercise on higher-order functions in Python.</p>
<p>The question is to define two functions, one which takes no arguments, and passes three globally defined functions, c(), t() and f(), through if/else statements (if <code>c()</code> true, return <code>t()</code> else return <code>f()</code>). The other function is a higher-order function that we evaluate on <code>c()</code>, <code>t()</code> and <code>f()</code> that then passes them through the same if/else statements. </p>
<p>These functions are different and our task is to see how by defining three functions <code>c()</code>, <code>t()</code> and <code>f()</code> such that the first function returns 1 and the second returns something other than one.</p>
<p>So far I have come to the realization that the issue lies with the calling of the functions <code>c()</code>, <code>t()</code> and <code>f()</code> before passing them through the if/else statements. This however has not been enough to inspire a solution. Would anyone be able to steer me in the correct direction?</p>
<p>Here is the associated code:</p>
<pre><code>def if_function(condition, true_result, false_result):
if condition:
return true_result
else:
return false_result
def with_if_statement():
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
def c():
return []
def t():
return 1
def f():
return 1
</code></pre>
| -1 |
2016-09-23T05:36:28Z
| 39,666,014 |
<p>You may easily pass callable as function arguments, without calling them.</p>
<pre><code>def cond():
return True
def f():
return 2
def g():
time.sleep(60)
def if_function(condition_callable, call_if_true, call_if_false):
if condition_callable():
return call_if_true()
else:
return call_if_false()
if_function(cond, f, g) # evaluates immediately, does not sleep since g is never evaluated.
</code></pre>
| 0 |
2016-09-23T17:00:23Z
|
[
"python",
"if-statement",
"higher-order-functions"
] |
How to create key value data type in django 1.7 models
| 39,653,328 |
<p>I want to store key-value pair in one column.</p>
<p>Above >Django-1.7 provides hstore to do that.</p>
<p>But I want to same functionality in Django-1.7.</p>
<p>How can I create custom datatype to store key-value pair in one column.</p>
<p>I am using postgres-9.5 database.</p>
<p>I want to store below json in key value pair in one column.</p>
<p>Example:</p>
<pre><code>{
"prepared_date":"2016-08-08T02:04:34Z",
"date_0":"2016-08-08T02:04:34Z",
"status_0":true,
"date_1":"2016-08-08T02:04:34Z",
"status_1":true,
"date_2":"2016-08-08T02:04:34Z",
"status_2":true,
}
</code></pre>
| 0 |
2016-09-23T05:39:09Z
| 39,653,572 |
<p>There's a nice package exactly for this purpose:</p>
<p><a href="http://djangonauts.github.io/django-hstore/" rel="nofollow">http://djangonauts.github.io/django-hstore/</a></p>
<p>So just install using pip:</p>
<pre><code>pip install django-hstore
</code></pre>
| 3 |
2016-09-23T06:00:24Z
|
[
"python",
"django",
"postgresql",
"django-models",
"django-custom-field"
] |
Update a text file with python only if it has changed
| 39,653,608 |
<p>Ok, I have my raspberry pi hooked up to a magnetic sensor on my garage door. I have a python script that update a website (initailstate.com) every second and reports changes, but it costs money after 25k requests and I killed that very quickly lol.
I want to instead to update a text file every time the state of the door changes.(open/closed) I have a text file called data.txt. I have a web page that uses java script to read the txt file and uses ajax to update and check the file for changes. this all works as i want but how can i get python to update a text file if and only if the contents of the file are different? </p>
<p>I am looking to use python to update the text file once the door changes states. I could use a database but I figured a text file would be easier to start with.
Let me know what you need from me if i haven't been specific enough.</p>
| -2 |
2016-09-23T06:02:12Z
| 39,655,225 |
<p>Maybe you could try something like this:</p>
<pre><code>f = open("state.txt", "w+") # state.txt contains "True" or "False"
def get_door_status():
# get_door_status() returns door_status, a bool
return door_status
while True:
door_status = str(get_door_status())
file_status = f.read()
if file_status != door_status:
f.write(door_status)
</code></pre>
| 0 |
2016-09-23T07:36:16Z
|
[
"python",
"linux"
] |
Update a text file with python only if it has changed
| 39,653,608 |
<p>Ok, I have my raspberry pi hooked up to a magnetic sensor on my garage door. I have a python script that update a website (initailstate.com) every second and reports changes, but it costs money after 25k requests and I killed that very quickly lol.
I want to instead to update a text file every time the state of the door changes.(open/closed) I have a text file called data.txt. I have a web page that uses java script to read the txt file and uses ajax to update and check the file for changes. this all works as i want but how can i get python to update a text file if and only if the contents of the file are different? </p>
<p>I am looking to use python to update the text file once the door changes states. I could use a database but I figured a text file would be easier to start with.
Let me know what you need from me if i haven't been specific enough.</p>
| -2 |
2016-09-23T06:02:12Z
| 39,656,302 |
<p>When working with small files that are exclusive to you, simply cache their content. This is faster and healthier for your storage.</p>
<pre><code># start of the script
# load the current value
import ast
status, status_file = False, "state.txt"
with open(status_file) as stat_file:
status = ast.literal_eval(next(stat_file()))
# keep on looping, check against *known value*
while True:
current_status = get_door_status()
if current_status != status: # only update on changes
status = current_status # update internal variable
# open for writing overwrites previous value
with open(status_file, 'w') as stat_file:
stat_file.write(status)
</code></pre>
| 0 |
2016-09-23T08:35:03Z
|
[
"python",
"linux"
] |
How to make label and entry start blank
| 39,653,729 |
<p>Any idea on how to make all the entry and labels in my GUI start blank but then update when the calculate function happens? They currently start with a 0. I have tried many things but nothing has worked. </p>
<p>Here is code: </p>
<pre><code>from tkinter import *
root = Tk(className="Page Calculator")
root.title("PgCalc")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
def calculate(event=None):
try:
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
except ZeroDivisionError:
print("ZeroDivisionError")
else:
print()
root.bind('<Return>', calculate)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root, width=8, textvariable=read)
read_entry.grid(column=2, row=1)
read_entry.focus()
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root, width=8, textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= calculate)
calculate_button.grid(column=2, row=3)
percent_label = Label(root,text="Percent Finished:")
percent_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percentresult_label = Label(root,textvariable=percent)
percentresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
</code></pre>
| 0 |
2016-09-23T06:10:55Z
| 39,654,301 |
<p><code>IntVar()</code> has a default value of 0. Even though they are IntVar, you can <code>set</code> strings as their value (note that when you try to <code>get</code> its value, you'll get an error if they still contain strings). </p>
<p>So you can simply do</p>
<pre><code>read = IntVar()
read.set("")
</code></pre>
<p>But, since you are using Entry, you don't need any IntVar at all. You can directly get entry's value and cast it to an integer.</p>
<pre><code>def calculate(event=None):
try:
leftresult_label.config(text=str(int(total_entry.get()) - int(read_entry.get())))
except ValueError:
print("Please enter a number")
#You need to remove textvariables from entries as well like below
total_entry = Entry(root, width=8)
</code></pre>
| 1 |
2016-09-23T06:47:49Z
|
[
"python",
"tkinter",
"label",
"entry"
] |
i'm doing a project for class and i can't understand why the last line is being flaged as unindented?
| 39,653,784 |
<p>This is a class thing im doing and in the last line when i run my program it says unexpected unindent. I cant understand. Help.</p>
<pre><code>b = 0
maxpass = 68
minpass = 0
fn = "FNO123"
amount = 0
seatsremain = 68 - b
print ("Welcome to Flight Booking Program")
print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)")
flight = input()
while flight != "X":
seatsremain = 68 - b
while True:
if b >= minpass and b <= maxpass:
break
else:
print ("Sorry but the flight you want is currently fully booked. Sorry for Inconviniance")
if flight == fn:
print ("There are currently", seatsremain, "seats remaining")
print ("Would you like to book or cancel your flight?")
booking = input().lower()
else:
print ("ERROR")
print ("Not a valid flight number! Remember input is CASE SENSITIVE")
print ("Welcome to Flight Booking Program")
print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)")
flight = input()
while True:
if booking == "c" or booking == "cancel" or booking == "b" or booking == "book":
break
else:
print ("ERROR")
print ("You must cancel at least 1 seat and not exceed the minimum amount of seats avaliable")
print ("There are currently", seatsremain, "seats remaining")
print ("Would you like to book or cancel your flight?")
if booking == "b" or booking == "book":
print ("How many seats are you booking?")
while True:
try:
amount = int(input())
if amount <1 or amount >seatsremain:
print ("ERROR")
print ("You must book at least 1 seat and not exceed the maximum amount of seats avaliable")
print ("There are currently", seatsremain, "seats remaining")
print ("Would you like to book or cancel your flight?")
else:
b = b + amount
print ("Your flight has been Booked!")
print ("Welcome to Flight Booking Program")
print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)")
flight = input()
break
except ValueError:
print ("You must enter a valid number!")
elif booking == "c" or "cancel":
print ("How many seats are you canceling?")
while True:
try:
amount = int(input())
if amount <1 or amount >b:
print ("ERROR")
print ("You must cancel at least 1 seat and not exceed the minimum amount of seats avaliable")
print ("There are currently", seatsremain, "seats remaining")
print ("Would you like to book or cancel your flight?")
else:
b = b - amount
print ("Your flight has been Cancelled!")
print ("Welcome to Flight Booking Program")
print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)")
flight = input()
break
print("There are", b, "people booked on flight", fn)
</code></pre>
| -2 |
2016-09-23T06:14:36Z
| 39,653,896 |
<p>Your second 'try' doesn't have an 'except'. Because this is missing your final line is unexpectedly unindented. Python is trying to find something indented equal to the try statement since 'except' is required.</p>
<pre><code>while True:
try:
amount = int(input())
if amount <1 or amount >b:
print ("ERROR")
print ("You must cancel at least 1 seat and not exceed the minimum amount of seats avaliable")
print ("There are currently", seatsremain, "seats remaining")
print ("Would you like to book or cancel your flight?")
else:
b = b - amount
print ("Your flight has been Cancelled!")
print ("Welcome to Flight Booking Program")
print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)")
flight = input()
break
except ValueError: #<- Add something like this
print ("You must enter a valid number!")
</code></pre>
| 2 |
2016-09-23T06:23:19Z
|
[
"python"
] |
How to sort/ group a Pandas data frame by class label or any specific column
| 39,653,812 |
<pre><code>class col2 col3 col4 col5
1 4 5 5 5
4 4 4.5 5.5 6
1 3.5 5 6 4.5
3 3 4 4 4
2 3 3.5 3.8 6.1
</code></pre>
<p>I have used hypothetical data in the example. The shape of the real DataFrame is 6680x1900. I have clustered these data into <code>50</code> labeled classes (1 to 50). How can I sort this data in ascending order of <code>class</code> labels?</p>
<p>I have tried:</p>
<pre><code>df.groupby([column_name_lst])["class"]
</code></pre>
<p>But it fails with this error:</p>
<blockquote>
<p>TypeError: You have to supply one of 'by' and 'level'</p>
</blockquote>
<p>How to solve this problem? Expected output is:</p>
<pre><code>class col2 col3 col4 col5
1 4 5 5 5
1 3.5 5 6 4.5
2 3 3.5 3.8 6.1
3 3 4 4 4
4 4 4.5 5.5 6
</code></pre>
| 3 |
2016-09-23T06:16:50Z
| 39,653,849 |
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>DataFrame.sort_values</code></a> if <code>class</code> is <code>Series</code>:</p>
<pre><code>print (type(df['class']))
<class 'pandas.core.series.Series'>
print (df.sort_values(by='class'))
class col2 col3 col4 col5
0 1 4.0 5.0 5.0 5.0
2 1 3.5 5.0 6.0 4.5
4 2 3.0 3.5 3.8 6.1
3 3 3.0 4.0 4.0 4.0
1 4 4.0 4.5 5.5 6.0
</code></pre>
<p>Also if need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a>, use parameter <code>by</code>:</p>
<pre><code>print (df.groupby(by='class').sum())
col2 col3 col4 col5
class
1 7.5 10.0 11.0 9.5
2 3.0 3.5 3.8 6.1
3 3.0 4.0 4.0 4.0
4 4.0 4.5 5.5 6.0
</code></pre>
<hr>
<p>And if <code>class</code> is <code>index</code>, use <a href="http://stackoverflow.com/a/39653884/2901002"><code>Kartik solution</code></a>:</p>
<pre><code>print (df.index)
Int64Index([1, 4, 1, 3, 2], dtype='int64', name='class')
print (df.sort_index())
col2 col3 col4 col5
class
1 4.0 5.0 5.0 5.0
1 3.5 5.0 6.0 4.5
2 3.0 3.5 3.8 6.1
3 3.0 4.0 4.0 4.0
4 4.0 4.5 5.5 6.0
</code></pre>
<p>Also if need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a>, use parameter <code>level</code>:</p>
<pre><code>print (df.groupby(level='class').sum())
col2 col3 col4 col5
class
1 7.5 10.0 11.0 9.5
2 3.0 3.5 3.8 6.1
3 3.0 4.0 4.0 4.0
4 4.0 4.5 5.5 6.0
</code></pre>
<p>or <code>index</code>, but first solution is better, because is more general:</p>
<pre><code>print (df.groupby(df.index).sum())
col2 col3 col4 col5
class
1 7.5 10.0 11.0 9.5
2 3.0 3.5 3.8 6.1
3 3.0 4.0 4.0 4.0
4 4.0 4.5 5.5 6.0
</code></pre>
| 2 |
2016-09-23T06:19:54Z
|
[
"python",
"sorting",
"pandas",
"dataframe",
"group-by"
] |
How to sort/ group a Pandas data frame by class label or any specific column
| 39,653,812 |
<pre><code>class col2 col3 col4 col5
1 4 5 5 5
4 4 4.5 5.5 6
1 3.5 5 6 4.5
3 3 4 4 4
2 3 3.5 3.8 6.1
</code></pre>
<p>I have used hypothetical data in the example. The shape of the real DataFrame is 6680x1900. I have clustered these data into <code>50</code> labeled classes (1 to 50). How can I sort this data in ascending order of <code>class</code> labels?</p>
<p>I have tried:</p>
<pre><code>df.groupby([column_name_lst])["class"]
</code></pre>
<p>But it fails with this error:</p>
<blockquote>
<p>TypeError: You have to supply one of 'by' and 'level'</p>
</blockquote>
<p>How to solve this problem? Expected output is:</p>
<pre><code>class col2 col3 col4 col5
1 4 5 5 5
1 3.5 5 6 4.5
2 3 3.5 3.8 6.1
3 3 4 4 4
4 4 4.5 5.5 6
</code></pre>
| 3 |
2016-09-23T06:16:50Z
| 39,653,884 |
<p>If you are starting with the data in your question:</p>
<blockquote>
<pre><code>class col2 col3 col4 col5
1 4 5 5 5
4 4 4.5 5.5 6
1 3.5 5 6 4.5
3 3 4 4 4
2 3 3.5 3.8 6.1
</code></pre>
</blockquote>
<p>And want to sort that, then it depends on whether <code>'class'</code> is an index or column. If index:</p>
<pre><code>df.sort_index()
</code></pre>
<p>should give you the answer. If column, follow <a href="http://stackoverflow.com/a/39653849/3765319">answer by @jezarael</a></p>
| 0 |
2016-09-23T06:22:07Z
|
[
"python",
"sorting",
"pandas",
"dataframe",
"group-by"
] |
AttributeError: 'NoneType' object has no attribute 'data' Linked List
| 39,653,832 |
<p>Current code, I am trying to make a linked list and then sort the linked list in ascending order. </p>
<pre><code>import random
random_nums = random.sample(range(100), 10)
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
def insertNode(data, first_node):
current_node = first_node
while current_node !=None:
if data > current_node.data and data <= current_node.next.data:
new_node = Node(data, current_node.next)
last_node.next = new_node
print("Inserting node: " + str(data))
current_node = current_node.next
first_node = Node(random_nums[0], None)
for i in random_nums[1:]:
insertNode(i, first_node)
print("Linked list values:")
current_node = first_node
while current_node != None:
print (str(current_node.data) + " => ", end="")
current_node = current_node.next
input()
</code></pre>
<p>Currently getting the error</p>
<blockquote>
<p>File "python", line 25, in
File "python", line 16, in insertNode
AttributeError: 'NoneType' object has no attribute 'data'</p>
</blockquote>
<p>I am really new to python and trying to get this to work, any suggestions? </p>
| 0 |
2016-09-23T06:18:13Z
| 39,655,897 |
<p>While the lines of your posted code and error don't quite match, the issue is likely here:</p>
<pre><code> if data > current_node.data and data <= current_node.next.data:
</code></pre>
<p>While you check that <code>current_node</code> is not <code>None</code>, you never check that <code>current_node.next</code> isn't <code>None</code> either.</p>
<p>There are some other bugs, e.g. <code>last_node</code> is not defined, there is no concept for inserting at the <em>front</em>, and you always go through the entire list. This should work better:</p>
<pre><code>def insertNode(data, first_node):
current_node = first_node
new_node = Node(data, current_node.next)
if data <= current_node.data:
# insert at start
first_node = new_node
new_node.next = first_node
else:
while current_node is not None:
if current_node.next is None:
# insert at end
current_node.next = new_node
break
elif data > current_node.data and data <= current_node.next.data:
# insert in-between current and next node
new_node.next = current_node.next
current_node.next = new_node
break
current_node = current_node.next
print("Inserting node: " + str(data))
return first_node # must return first to avoid global variable!
</code></pre>
<p>To support changing <code>first_node</code>, you have to fill the list like this:</p>
<pre><code>rand_num_iter = iter(random_nums) # avoids making a copy in [1:]
first_node = Node(next(rand_num_iter), None)
for i in rand_num_iter:
first_node = insertNode(i, first_node)
</code></pre>
| 1 |
2016-09-23T08:13:26Z
|
[
"python"
] |
With inheritance and access to the parent is something wrong?
| 39,653,851 |
<p>With inheritance and access to the parent, widgets are some weird wrong. I Need to make three section with the same widget as shown in the code. </p>
<p>I don't know how could do that really makes sense. Have you an idea how could this be done in the smartest way ? </p>
<pre><code>import Tkinter as tk
class Interface(tk.Frame):
def __init__(self, parent,start, ver_part, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.start = start
self.ver_part = ver_part
parent.title("Interface Window")
self.frame = tk.LabelFrame(parent, text="Verification Part - %s"%ver_part)
self.button = tk.Button(self.frame, text="%s"%ver_part)
self.frame.grid(row=0+start)
self.button.grid(row=0+start)
class Main(Interface):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.button_run = tk.Button(parent, text="Run", command=self.on_run())
self.button_run.grid(row=3)
def on_run(self):
pass
if __name__ == "__main__":
root = tk.Tk()
int_a = Interface(root,0, "A")
int_b = Interface(root,1, "B")
int_c = Interface(root,2, "C")
root.mainloop()
</code></pre>
| 1 |
2016-09-23T06:20:06Z
| 39,660,159 |
<p>You are giving one of your widgets a parent of <code>parent</code> rather than <code>self</code>.</p>
<p>Change this line:</p>
<pre><code>self.frame = tk.LabelFrame(parent, text="Verification Part - %s"%ver_part)
</code></pre>
<p>to this:</p>
<pre><code>self.frame = tk.LabelFrame(self, text="Verification Part - %s"%ver_part)
</code></pre>
<p>Once you've done that you need to call <code>pack</code>, <code>place</code> or <code>grid</code> on the individual instances of <code>Interface</code>. </p>
<p>For example:</p>
<pre><code>if __name__ == "__main__":
...
int_a.pack(side="top", fill="both", expand=True)
int_b.pack(side="top", fill="both", expand=True)
int_c.pack(side="top", fill="both", expand=True)
</code></pre>
| 2 |
2016-09-23T11:54:38Z
|
[
"python",
"python-2.7",
"class",
"tkinter"
] |
Teardown action in Robot Framework
| 39,654,007 |
<p>I have a 3 test cases in robot framework and I need to run Teardown actions only Once at last after execution 3 test cases.
How to handle?</p>
<pre><code>*** Settings ***
Test Teardown Teardown Actions
Library abc.py
*** Variables ***
*** Test Cases ***
testcase1
Run Keyword func1
testcase2
Run Keyword func2
testcase3
Run Keyword func3
*** Keywords ***
Teardown Actions
Run Keyword clear
</code></pre>
| 0 |
2016-09-23T06:29:13Z
| 39,654,137 |
<p>There is "Suite Teardown" in robotframework which will run after the execution of all test cases.</p>
<p><a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#suite-setup-and-teardown" rel="nofollow">Check this link for more info.</a></p>
<p>Can be use like this.</p>
<pre><code>*** Settings ***
Library SSHLibrary
Library OperatingSystem
Library String
Suite Teardown Teardown Actions
*** Keywords ***
Teardown Actions
Run Keyword clear
*** Testcases ***
testcase1
Run Keyword func1
testcase2
Run Keyword func2
testcase3
Run Keyword func3
</code></pre>
<p>Please let me know if more info is required.</p>
| 2 |
2016-09-23T06:37:37Z
|
[
"python",
"python-2.7",
"robotframework"
] |
Trying to create a crude send/receive through TCP in python
| 39,654,060 |
<p>So far I can send files to my "fileserver" and retrieve files from there as well. But i can't do both at the same time. I have to comment out one of the other threads for them to work. As you will see in my code.</p>
<p>SERVER CODE
</p>
<pre class="lang-py prettyprint-override"><code>from socket import *
import threading
import os
# Send file function
def SendFile (name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send('ERROR')
sock.close()
def RetrFile (name, sock):
filename = sock.recv(1024)
data = sock.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
sock.send('OK')
f = open('new_' + filename, 'wb')
data = sock.recv(1024)
totalRecieved = len(data)
f.write(data)
while totalRecieved < filesize:
data = sock.recv(1024)
totalRecieved += len(data)
f.write(data)
sock.close()
myHost = ''
myPort = 7005
s = socket(AF_INET, SOCK_STREAM)
s.bind((myHost, myPort))
s.listen(5)
print("Server Started.")
while True:
connection, address = s.accept()
print("Client Connection at:", address)
# u = threading.Thread(target=RetrFile, args=("retrThread", connection))
t = threading.Thread(target=SendFile, args=("sendThread", connection))
# u.start()
t.start()
s.close()
</code></pre>
<p>CLIENT CODE</p>
<pre class="lang-py prettyprint-override"><code>from socket import *
import sys
import os
servHost = ''
servPort = 7005
s = socket(AF_INET, SOCK_STREAM)
s.connect((servHost, servPort))
decision = raw_input("do you want to send or retrieve a file?(send/retrieve): ")
if decision == "retrieve" or decision == "Retrieve":
filename = raw_input("Filename of file you want to retrieve from server: ") # ask user for filename
if filename != "q":
s.send(filename)
data = s.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
message = raw_input("File Exists, " + str(filesize)+"Bytes, download?: Y/N -> ")
if message == "Y" or message == "y":
s.send('OK')
f = open('new_' + filename, 'wb')
data = s.recv(1024)
totalRecieved = len(data)
f.write(data)
while totalRecieved < filesize:
data = s.recv(1024)
totalRecieved += len(data)
f.write(data)
print("{0: .2f}".format((totalRecieved/float(filesize))*100)) + "% Done" # print % of download progress
print("Download Done!")
else:
print("File does not exist!")
s.close()
elif decision == "send" or decision == "Send":
filename = raw_input("Filename of file you want to send to server: ")
if filename != "q":
s.send(filename)
if os.path.isfile(filename):
s.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = s.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
s.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
s.send(bytesToSend)
else:
s.send('ERROR')
s.close()
s.close()
</code></pre>
<p>I'm still new to programming, so this is quite tough for me. All in all i'm just trying to figure out how to send AND receive files without having to comment out the bottom threads in my SERVER CODE.</p>
<p>Please and thank you! </p>
| 2 |
2016-09-23T06:32:35Z
| 39,655,847 |
<p>On the serverside, you're trying to use the same connection for your two threads t and u.</p>
<p>I think it might work if you listened for another connection in your <code>while True:</code> loop on the server, after you started your first thread.</p>
<p>I always use the more high-level <code>socketserver</code> module (<a href="https://docs.python.org/3.6/library/socketserver.html#socketserver-tcpserver-example" rel="nofollow">Python Doc on socketserver</a>), which also natively supports Threading. I recommend checking it out!</p>
<p>By the way, since you do a lot of <code>if (x == 'r' or x == 'R')</code>: you could just do <code>if x.lower() == 'r'</code> </p>
| 0 |
2016-09-23T08:10:50Z
|
[
"python",
"tcp"
] |
Upper method doesn't make sense
| 39,654,133 |
<p><strong>Code</strong>:</p>
<pre><code>def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if len(sys.argv) == 1:
print "please input a port"
else:
port = solve_the_input(sys.argv[1])
</code></pre>
<p><strong>Input</strong></p>
<pre><code>python test.py 42328
</code></pre>
<p><strong>Actual Output</strong>:</p>
<pre><code>input port is a558
input port is a558
</code></pre>
<p><strong>Expected Output</strong>:</p>
<pre><code>input port is a558
input port is A558
</code></pre>
<p>I don't know why the upper() method is not working as expected.</p>
| 0 |
2016-09-23T06:37:29Z
| 39,654,234 |
<p>The upper method returns <em>new</em> string in uppercase. So use</p>
<pre><code>split_port = split_result[1].upper()
</code></pre>
| 2 |
2016-09-23T06:43:37Z
|
[
"python"
] |
Upper method doesn't make sense
| 39,654,133 |
<p><strong>Code</strong>:</p>
<pre><code>def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if len(sys.argv) == 1:
print "please input a port"
else:
port = solve_the_input(sys.argv[1])
</code></pre>
<p><strong>Input</strong></p>
<pre><code>python test.py 42328
</code></pre>
<p><strong>Actual Output</strong>:</p>
<pre><code>input port is a558
input port is a558
</code></pre>
<p><strong>Expected Output</strong>:</p>
<pre><code>input port is a558
input port is A558
</code></pre>
<p>I don't know why the upper() method is not working as expected.</p>
| 0 |
2016-09-23T06:37:29Z
| 39,654,319 |
<p>Couple of points </p>
<ul>
<li><code>split_port.upper()</code> return is not assigned back to <code>split_port</code></li>
<li>No need to split on <code>'0x'</code>. You can use <code>replace</code> function instead. Will be less complicated.</li>
</ul>
<p><strong>Code with replace function:</strong></p>
<pre><code>import sys
def solve_the_input(port):
port = hex(int(port))
result = port.replace("0x",'')
print 'input port is ',result
result = result.upper()
print 'input port is ',result
return result
if __name__ == "__main__":
if len(sys.argv) == 1:
print "please input a port"
else :
port = solve_the_input(sys.argv[1])
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py 1235
input port is 4d3
input port is 4D3
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 1 |
2016-09-23T06:48:36Z
|
[
"python"
] |
Upper method doesn't make sense
| 39,654,133 |
<p><strong>Code</strong>:</p>
<pre><code>def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if len(sys.argv) == 1:
print "please input a port"
else:
port = solve_the_input(sys.argv[1])
</code></pre>
<p><strong>Input</strong></p>
<pre><code>python test.py 42328
</code></pre>
<p><strong>Actual Output</strong>:</p>
<pre><code>input port is a558
input port is a558
</code></pre>
<p><strong>Expected Output</strong>:</p>
<pre><code>input port is a558
input port is A558
</code></pre>
<p>I don't know why the upper() method is not working as expected.</p>
| 0 |
2016-09-23T06:37:29Z
| 39,654,349 |
<p>Upper method returning new string but you need to store that string.</p>
<pre><code>split_port = split_result[1].upper()
</code></pre>
| 0 |
2016-09-23T06:49:42Z
|
[
"python"
] |
Can't figure out why this code runs perfect for input of 3 and breaks on 5. {homework}
| 39,654,153 |
<p>When I input 3 into the below code it prints perfectly in the shape I need. But when the input is > 3 the code seems to break as you can see in the pictures below. I think I've probably just been staring at this for too long and can't find the obvious stupid error. I'm somewhat new to python so please go easy. </p>
<pre><code>size = int(input("Size: "))
def middle1():
count_middle1 = 0
size_m1 = (size + 1)
mid_1 = 1
mid_2 = 1
dots_a = 2
bslsh = "\\"
fslsh = "/"
while (count_middle1 != size):
print("|"+("."*dots_a)+((fslsh+bslsh)*mid_1)+("."*size_m1)+((fslsh+bslsh)*mid_2)+("."*dots_a)+"|")
mid_1+=1
mid_2+=1
count_middle1+=1
dots_a-=1
size_m1-=2
middle1()
</code></pre>
<p><a href="http://i.stack.imgur.com/sQI3k.png" rel="nofollow">Input == 3</a></p>
<p><a href="http://i.stack.imgur.com/QjReC.png" rel="nofollow">Input == 5</a></p>
<p>Any help would be greatly appreciated!</p>
| 1 |
2016-09-23T06:38:34Z
| 39,654,664 |
<p>If I understand it correctly you want two trees next to each other.</p>
<pre><code>|........./\................../\.........|
|......../\/\................/\/\........|
|......./\/\/\............../\/\/\.......|
|....../\/\/\/\............/\/\/\/\......|
|...../\/\/\/\/\........../\/\/\/\/\.....|
|..../\/\/\/\/\/\......../\/\/\/\/\/\....|
|.../\/\/\/\/\/\/\....../\/\/\/\/\/\/\...|
|../\/\/\/\/\/\/\/\..../\/\/\/\/\/\/\/\..|
|./\/\/\/\/\/\/\/\/\../\/\/\/\/\/\/\/\/\.|
|/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\|
</code></pre>
<p>There is two problems, one that I mentioned in the comments which is the <code>dots_a</code>. The second problem is your <code>size_m1</code>. Try to think what you need to change it to so it works for any <code>size</code>.</p>
| 2 |
2016-09-23T07:06:15Z
|
[
"python",
"python-3.x",
"python-3.5",
"python-3.5.2"
] |
Can't figure out why this code runs perfect for input of 3 and breaks on 5. {homework}
| 39,654,153 |
<p>When I input 3 into the below code it prints perfectly in the shape I need. But when the input is > 3 the code seems to break as you can see in the pictures below. I think I've probably just been staring at this for too long and can't find the obvious stupid error. I'm somewhat new to python so please go easy. </p>
<pre><code>size = int(input("Size: "))
def middle1():
count_middle1 = 0
size_m1 = (size + 1)
mid_1 = 1
mid_2 = 1
dots_a = 2
bslsh = "\\"
fslsh = "/"
while (count_middle1 != size):
print("|"+("."*dots_a)+((fslsh+bslsh)*mid_1)+("."*size_m1)+((fslsh+bslsh)*mid_2)+("."*dots_a)+"|")
mid_1+=1
mid_2+=1
count_middle1+=1
dots_a-=1
size_m1-=2
middle1()
</code></pre>
<p><a href="http://i.stack.imgur.com/sQI3k.png" rel="nofollow">Input == 3</a></p>
<p><a href="http://i.stack.imgur.com/QjReC.png" rel="nofollow">Input == 5</a></p>
<p>Any help would be greatly appreciated!</p>
| 1 |
2016-09-23T06:38:34Z
| 39,654,967 |
<p>I think this would work for you.</p>
<pre><code>def middle1(size):
count_middle1 = 0
size_m1 = (size * 2)
mid_1 = 1
mid_2 = 1
dots_a = int(size_m1 / 2)
bslsh = "\\"
fslsh = "/"
while (count_middle1 != size):
print("|"+("."*dots_a)+((fslsh+bslsh)*mid_1)+("."*size_m1)+((fslsh+bslsh)*mid_2)+("."*dots_a)+"|")
mid_1+=1
mid_2+=1
count_middle1+=1
dots_a-=1
size_m1-=2
print("\n")
</code></pre>
<p>And this will give you output</p>
<pre><code>middle1(2)
middle1(3)
middle1(4)
middle1(5)
|../\..../\..|
|./\/\../\/\.|
|.../\....../\...|
|../\/\..../\/\..|
|./\/\/\../\/\/\.|
|..../\......../\....|
|.../\/\....../\/\...|
|../\/\/\..../\/\/\..|
|./\/\/\/\../\/\/\/\.|
|...../\........../\.....|
|..../\/\......../\/\....|
|.../\/\/\....../\/\/\...|
|../\/\/\/\..../\/\/\/\..|
|./\/\/\/\/\../\/\/\/\/\.|
</code></pre>
| 0 |
2016-09-23T07:22:38Z
|
[
"python",
"python-3.x",
"python-3.5",
"python-3.5.2"
] |
Can't figure out why this code runs perfect for input of 3 and breaks on 5. {homework}
| 39,654,153 |
<p>When I input 3 into the below code it prints perfectly in the shape I need. But when the input is > 3 the code seems to break as you can see in the pictures below. I think I've probably just been staring at this for too long and can't find the obvious stupid error. I'm somewhat new to python so please go easy. </p>
<pre><code>size = int(input("Size: "))
def middle1():
count_middle1 = 0
size_m1 = (size + 1)
mid_1 = 1
mid_2 = 1
dots_a = 2
bslsh = "\\"
fslsh = "/"
while (count_middle1 != size):
print("|"+("."*dots_a)+((fslsh+bslsh)*mid_1)+("."*size_m1)+((fslsh+bslsh)*mid_2)+("."*dots_a)+"|")
mid_1+=1
mid_2+=1
count_middle1+=1
dots_a-=1
size_m1-=2
middle1()
</code></pre>
<p><a href="http://i.stack.imgur.com/sQI3k.png" rel="nofollow">Input == 3</a></p>
<p><a href="http://i.stack.imgur.com/QjReC.png" rel="nofollow">Input == 5</a></p>
<p>Any help would be greatly appreciated!</p>
| 1 |
2016-09-23T06:38:34Z
| 39,655,255 |
<p>This will work for any input</p>
<pre><code>size = int(input("Size: "))
def middle1():
count_middle1 = 0
size_m1 = (size - 1)*2
mid_1 = 2
mid_2 = 2
dots_a = size-1
bslsh = "\\"
fslsh = "/"
while (count_middle1 < size):
print("|"+("."*(dots_a))+((fslsh+bslsh)*(mid_1-1))+("."*size_m1)+((fslsh+bslsh)*(mid_2-1))+("."*(dots_a))+"|")
mid_1+=1
mid_2+=1
count_middle1+=1
dots_a-=1
size_m1-=2
middle1()
</code></pre>
| 0 |
2016-09-23T07:37:29Z
|
[
"python",
"python-3.x",
"python-3.5",
"python-3.5.2"
] |
Add tag to cartridge admin panel
| 39,654,201 |
<p>I want to add one new field 'tag' in my Product class. I added that field and now I want to add that tag manually from cartridge admin panel. </p>
<p>So, to do that I am importing one admin class in my settings.py,</p>
<pre><code>from cartridge.shop.admin import ProductAdmin
</code></pre>
<p>When I am importing above class, I am getting error on terminal,</p>
<blockquote>
<p>django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.</p>
</blockquote>
<p>I wants to add that "tag" field in ProductAdmin class like below,but before I write below code in my project I am getting that "SECRET_KEY" error on import,</p>
<pre><code>ProductAdmin.list_display.append("tag")
</code></pre>
| 0 |
2016-09-23T06:41:21Z
| 39,654,847 |
<p><code>ProductAdmin</code> looks like it requires the secret key setting which it is unable to get since it is loaded before settings, so you cannot include this in settings (nor can I think of a reason you'd need to)</p>
<p>Whatever it is you're trying to do, you need to do it elsewhere.</p>
| 0 |
2016-09-23T07:16:21Z
|
[
"python",
"django",
"cartridge"
] |
How to concatenate strings in numpy (to create percentages)?
| 39,654,212 |
<p>I have a matrix created by the following code:</p>
<pre><code>import numpy as np
table_vals = np.random.randn(4,4).round(4) * 100
</code></pre>
<p>and I've tried to convert numbers into percentages like this:</p>
<pre><code>>>> table_vals.astype(np.string_) + '%'
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')
</code></pre>
<p>and like this:</p>
<pre><code>>>> np.str(table_vals) + '%'
"[[ 137.08 120.31 -55.73 43.6 ]\n [ -94.35 -105.27 -23.31 59.16]\n [-132.9 12.04 -36.69 106.52]\n [ 126.11 -91.38 -29.16 -138.01]]%"
</code></pre>
<p>but all of them failed. So what should I do?</p>
| 0 |
2016-09-23T06:42:22Z
| 39,654,378 |
<p>You can use the formatting as:</p>
<pre><code>[["%.2f%%" % number for number in row] for row in table_vals]
</code></pre>
<p>If you want it as a numpy array, then wrap it in <code>np.array</code> method so it becomes:</p>
<pre><code>np.array([["%.2f%%" % number for number in row] for row in table_vals])
</code></pre>
| 0 |
2016-09-23T06:51:38Z
|
[
"python",
"numpy"
] |
How to concatenate strings in numpy (to create percentages)?
| 39,654,212 |
<p>I have a matrix created by the following code:</p>
<pre><code>import numpy as np
table_vals = np.random.randn(4,4).round(4) * 100
</code></pre>
<p>and I've tried to convert numbers into percentages like this:</p>
<pre><code>>>> table_vals.astype(np.string_) + '%'
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')
</code></pre>
<p>and like this:</p>
<pre><code>>>> np.str(table_vals) + '%'
"[[ 137.08 120.31 -55.73 43.6 ]\n [ -94.35 -105.27 -23.31 59.16]\n [-132.9 12.04 -36.69 106.52]\n [ 126.11 -91.38 -29.16 -138.01]]%"
</code></pre>
<p>but all of them failed. So what should I do?</p>
| 0 |
2016-09-23T06:42:22Z
| 39,657,487 |
<p>The <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow"><code>np.char</code> module</a> can help here:</p>
<pre><code>np.char.add(table_vals.astype(np.bytes_), b'%')
</code></pre>
<p>Using an object array also works well:</p>
<pre><code>np.array("%.2f%%") % table_vals.astype(np.object_)
</code></pre>
| 0 |
2016-09-23T09:37:30Z
|
[
"python",
"numpy"
] |
Create a list from an existing list of key value pairs in python
| 39,654,224 |
<p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numerical values to it.</p>
<p>So, output should look like:</p>
<pre><code>alist = [1,2,3]
blist = [10,100]
clist = [99]
dlist = [-1,-2]
</code></pre>
<p>Is there a neat way of doing this in Python?</p>
| -1 |
2016-09-23T06:42:52Z
| 39,654,326 |
<pre><code>from collections import defaultdict
data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
if __name__ == '__main__':
result = defaultdict(list)
for alphabet, number in data:
result[alphabet].append(number)
</code></pre>
<p>or without collections module:</p>
<pre><code>if __name__ == '__main__':
result = {}
for alphabet, number in data:
if alphabet not in result:
result[alphabet] = [number, ]
continue
result[alphabet].append(number)
</code></pre>
<p>But i think, that first solution more effective and clear. </p>
| 2 |
2016-09-23T06:48:56Z
|
[
"python"
] |
Create a list from an existing list of key value pairs in python
| 39,654,224 |
<p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numerical values to it.</p>
<p>So, output should look like:</p>
<pre><code>alist = [1,2,3]
blist = [10,100]
clist = [99]
dlist = [-1,-2]
</code></pre>
<p>Is there a neat way of doing this in Python?</p>
| -1 |
2016-09-23T06:42:52Z
| 39,654,463 |
<p>You can use <code>defaultdict</code> from the <code>collections</code> module for this:</p>
<pre><code>from collections import defaultdict
l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
d = defaultdict(list)
for k,v in l:
d[k].append(v)
for k,v in d.items():
exec(k + "list=" + str(v))
</code></pre>
| -1 |
2016-09-23T06:56:27Z
|
[
"python"
] |
Create a list from an existing list of key value pairs in python
| 39,654,224 |
<p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numerical values to it.</p>
<p>So, output should look like:</p>
<pre><code>alist = [1,2,3]
blist = [10,100]
clist = [99]
dlist = [-1,-2]
</code></pre>
<p>Is there a neat way of doing this in Python?</p>
| -1 |
2016-09-23T06:42:52Z
| 39,654,740 |
<p>If you want to avoid using a <code>defaultdict</code> but are comfortable using <code>itertools</code>, you can do it with a one-liner</p>
<pre><code>from itertools import groupby
data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
grouped = dict((key, list(pair[1] for pair in values)) for (key, values) in groupby(data, lambda pair: pair[0]))
# gives {'b': [10, 100], 'a': [1, 2, 3], 'c': [99], 'd': [-1, -2]}
</code></pre>
| 1 |
2016-09-23T07:10:11Z
|
[
"python"
] |
Create a list from an existing list of key value pairs in python
| 39,654,224 |
<p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numerical values to it.</p>
<p>So, output should look like:</p>
<pre><code>alist = [1,2,3]
blist = [10,100]
clist = [99]
dlist = [-1,-2]
</code></pre>
<p>Is there a neat way of doing this in Python?</p>
| -1 |
2016-09-23T06:42:52Z
| 39,654,930 |
<p>After seeing the responses in the thread and reading the implementation of defaultdict, I implemented my own version of it since I didn't want to use the collections library. </p>
<pre><code> mydict = {}
for alphabet, value in data:
try:
mydict[alphabet].append(value)
except KeyError:
mydict[alphabet] = []
mydict[alphabet].append(value)
</code></pre>
| 0 |
2016-09-23T07:20:36Z
|
[
"python"
] |
string parameter passing not working in django1.9
| 39,654,265 |
<p>I am passing a string parameter in view but its not working.</p>
<pre><code>url(r'^users/(?P<user_type>\w+)/$', views.users, name='users'),
url(r'^users/$', views.users, name='users')
</code></pre>
<p><strong>view is:-</strong> </p>
<pre><code>def users(request, user_type=None):
</code></pre>
<p><strong>Link is:-</strong> </p>
<pre><code><a href="{% url 'users' %}">All Users</a>
<a href="{% url 'users' customers %}">Customers</a>
<a href="{% url 'users' promoters %}">Promoters</a>
</code></pre>
<p>But its giving error when i access view without parameter</p>
<pre><code>Reverse for 'users' with arguments '('',)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['administrator/users/$', 'administrator/users/(?P<user_type>\\w+)/$']
Exception Value: Reverse for 'users' with arguments '('',)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['administrator/users/$', 'administrator/users/(?P<user_type>\\w+)/$']
</code></pre>
| 0 |
2016-09-23T06:45:34Z
| 39,654,514 |
<p>Use this and check</p>
<pre><code>url(r'^users/(?P<user_type>\w+)/$', views.users, name='users_type'),
url(r'^users/$', views.users, name='users')
</code></pre>
<p>Link is:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="{% url 'users' %}">All Users</a>
<a href="{% url 'users_type' "customers" %}">Customers</a>
<a href="{% url 'users_type' "promoters" %}">Promoters</a></code></pre>
</div>
</div>
</p>
| 1 |
2016-09-23T06:58:37Z
|
[
"python",
"django"
] |
Python - Beautifulsoup count only outer tag children of a tag
| 39,654,376 |
<p>HTML of page:</p>
<pre><code><form name="compareprd" action="">
<div class="gridBox product " id="quickLookItem-1">
<div class="gridItemTop">
</div>
</div>
<div class="gridBox product " id="quickLookItem-2">
<div class="gridItemTop">
</div>
</div>
<!-- many more like this. -->
</code></pre>
<p>
I am using Beautiful soup to scrap a page. In that page I am able to get a form tag by its name.</p>
<pre><code>tag = soup.find("form", {"name": "compareprd"})
</code></pre>
<p>Now I want to count all immediate child divs but not all nested divs.
Say for example there are 20 immediate divs inside form.
I tried :</p>
<pre><code>len(tag.findChildren("div"))
</code></pre>
<p>But It gives 1500.</p>
<p>I think it gives all "div" inside "form" tag.</p>
<p>Any help appreciated.</p>
| 1 |
2016-09-23T06:51:35Z
| 39,658,013 |
<p>You can use a single <em>css selector</em> <code>form[name=compareprd] > div</code> which will find <em>div's</em> that are immediate children of the form:</p>
<pre><code>html = """<form name="compareprd" action="">
<div class="gridBox product " id="quickLookItem-1">
<div class="gridItemTop">
</div>
</div>
<div class="gridBox product " id="quickLookItem-2">
<div class="gridItemTop">
</div>
</div>
</form>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
print(len(soup.select("form[name=compareprd] > div")))
</code></pre>
<p>Or as commented pass <em>recursive=True</em> but use <em>find_all</em>, <a href="https://github.com/JinnLynn/beautifulsoup/blob/master/bs4/element.py#L1178" rel="nofollow">findChildren</a> goes back to the bs2 days and is only provided for backwards compatability.</p>
<pre><code> len(tag.find_all("div", recursive=False)
</code></pre>
| 1 |
2016-09-23T10:03:00Z
|
[
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Finding multiple repetitions of smaller lists in a large cumulative list
| 39,654,646 |
<p>I have a large list of strings, for eg:</p>
<pre><code>full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
</code></pre>
<p>and multiple small list of strings, for eg:</p>
<pre><code>tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
</code></pre>
<p>I want to find each of this smaller lists in the larger list maintaining the sequence, so that the output would be something like:</p>
<pre><code>tc2-tc1-Er-tc4-tc3
</code></pre>
<p>I want to know if there is any straight forward, pythonic way of dealing with this situation.</p>
| 3 |
2016-09-23T07:05:24Z
| 39,655,184 |
<p>You can use <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">Set</a> for pattern matching:</p>
<pre><code>from sets import Set
full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
set(full_log) & set(tc1)
</code></pre>
<p>output: <code>{'HG89', 'NS72'}</code></p>
<pre><code>#Finding index of set elements:
result=set(full_log) & set(tc1)
def all_indices(value, qlist):
indices = []
idx = -1
while True:
try:
idx = qlist.index(value, idx+1)
indices.append(idx)
except ValueError:
break
return indices
r=[]
for i in range(len(result)):
s=all_indices(list(result)[i], full_log)
r.append(s)
r
Output: [[2], [3]]
</code></pre>
| 0 |
2016-09-23T07:34:15Z
|
[
"python",
"list"
] |
Finding multiple repetitions of smaller lists in a large cumulative list
| 39,654,646 |
<p>I have a large list of strings, for eg:</p>
<pre><code>full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
</code></pre>
<p>and multiple small list of strings, for eg:</p>
<pre><code>tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
</code></pre>
<p>I want to find each of this smaller lists in the larger list maintaining the sequence, so that the output would be something like:</p>
<pre><code>tc2-tc1-Er-tc4-tc3
</code></pre>
<p>I want to know if there is any straight forward, pythonic way of dealing with this situation.</p>
| 3 |
2016-09-23T07:05:24Z
| 39,655,284 |
<p>You need to create a map (dictionary) of the elements of your small list:</p>
<pre><code>m = {k: v for k, v in zip(map(tuple, [tc1, tc2, tc3, tc4])), ["tc1", "tc2", "tc3", "tc4"])}
>>> {('KK02', 'FE34'): 'tc3', ('AB21', 'BG54'): 'tc2', ('CF54', 'SD62'): 'tc4', ('HG89', 'NS72'): 'tc1'}
</code></pre>
<p>You could then use an iterator to loop over the list:</p>
<pre class="lang-python prettyprint-override"><code>itr = iter(full_log)
for i in itr:
if i != "Error":
n = next(itr)
if n != "Error":
if (i, n) in m:
print m[(i, n)]
else:
print "Er"
else:
print "Er"
>>> tc2
tc1
Er
tc4
tc3
</code></pre>
<p>If you dont mind expanding your "Error" entries in the first list:</p>
<pre><code>full_log2 = [item for sublist in [[i] if i != "Error" else ["Error", "Error"] for i in full_log] for item in sublist]
>>> ['AB21', 'BG54', 'HG89', 'NS72', 'Error', 'Error', 'CF54', 'SD62', 'KK02', 'FE34']
</code></pre>
<p>Then you could use a list comprehension:</p>
<pre><code>print [m[(full_log2[i], full_log2[i+1])] if (full_log2[i], full_log2[i+1]) in m else "Er" for i in range(0, len(full_log2)-1, 2)]
>>> ['tc2', 'tc1', 'Er', 'tc4', 'tc3']
</code></pre>
| 3 |
2016-09-23T07:39:03Z
|
[
"python",
"list"
] |
Finding multiple repetitions of smaller lists in a large cumulative list
| 39,654,646 |
<p>I have a large list of strings, for eg:</p>
<pre><code>full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
</code></pre>
<p>and multiple small list of strings, for eg:</p>
<pre><code>tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
</code></pre>
<p>I want to find each of this smaller lists in the larger list maintaining the sequence, so that the output would be something like:</p>
<pre><code>tc2-tc1-Er-tc4-tc3
</code></pre>
<p>I want to know if there is any straight forward, pythonic way of dealing with this situation.</p>
| 3 |
2016-09-23T07:05:24Z
| 39,655,476 |
<p>In case all your short lists are equal length you could just create a <code>dict</code> where key is <code>tuple</code> of strings and value is one of the labels. The you could go through <code>full_log</code>, take a block with suitable length and see if that can be found from <code>dict</code>.</p>
<p>In case the short lists are different lengths the above approach won't work since the block length to take from <code>full_log</code> is not constant. In that case one possible solution is to add items from short lists to a tree structure where the leaf node is a label. Then for every index in <code>full_log</code> see if you can find a path from tree. If path is found jump it's length forward, otherwise try from next index:</p>
<pre><code>from collections import defaultdict
from itertools import islice
full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
# Construct a tree
dd = lambda: defaultdict(dd)
labels = defaultdict(dd)
labels['HG89']['NS72'] = 'tc1'
labels['AB21']['BG54'] = 'tc2'
labels['KK02']['FE34'] = 'tc3'
labels['CF54']['SD62'] = 'tc4'
# Find label, return tuple (label, length) or (None, 1)
def find_label(it):
length = 0
node = labels
while node and isinstance(node, dict):
node = node.get(next(it, None))
length += 1
return node, (length if node else 1)
i = 0
result = []
while i < len(full_log):
label, length = find_label(islice(full_log, i, None))
result.append(label if label else full_log[i])
i += length
print result # ['tc2', 'tc1', 'Error', 'tc4', 'tc3']
</code></pre>
<p>The tree used above is kind of <a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow">trie</a> with an exception that nodes can either contain children or a value (label).</p>
| 2 |
2016-09-23T07:50:00Z
|
[
"python",
"list"
] |
Checking a word starts with specific alphabets python
| 39,654,703 |
<p>I have a string test_file1. I want to check taking a string from user if the string he/she enters starts with 'test'. How to do this in python?
let args be =['test_file']</p>
<pre><code>for suite in args:
if suite.startswith('test'):
suite="hello.tests."+suite
print(suite) // prints hello.tests.test_file
print(args) //prints ['test.file]' and not ['hello.tests.test_file']
</code></pre>
| -1 |
2016-09-23T07:07:54Z
| 39,654,737 |
<p>you can use the regex.</p>
<pre><code>pat = re.compile(r'^test.*')
</code></pre>
<p>then you can use this pattern for checking each line.</p>
| 0 |
2016-09-23T07:10:02Z
|
[
"python"
] |
Checking a word starts with specific alphabets python
| 39,654,703 |
<p>I have a string test_file1. I want to check taking a string from user if the string he/she enters starts with 'test'. How to do this in python?
let args be =['test_file']</p>
<pre><code>for suite in args:
if suite.startswith('test'):
suite="hello.tests."+suite
print(suite) // prints hello.tests.test_file
print(args) //prints ['test.file]' and not ['hello.tests.test_file']
</code></pre>
| -1 |
2016-09-23T07:07:54Z
| 39,654,764 |
<p>Simply use:</p>
<pre><code>String.startswith(str, beg=0,end=len(string))
</code></pre>
<p>In your case, it'll be</p>
<pre><code>word.startswith('test', 0, 4)
</code></pre>
| 1 |
2016-09-23T07:11:07Z
|
[
"python"
] |
Checking a word starts with specific alphabets python
| 39,654,703 |
<p>I have a string test_file1. I want to check taking a string from user if the string he/she enters starts with 'test'. How to do this in python?
let args be =['test_file']</p>
<pre><code>for suite in args:
if suite.startswith('test'):
suite="hello.tests."+suite
print(suite) // prints hello.tests.test_file
print(args) //prints ['test.file]' and not ['hello.tests.test_file']
</code></pre>
| -1 |
2016-09-23T07:07:54Z
| 39,655,072 |
<p>Problem with code is you are not replacing the suite in args list with new created suite name .</p>
<p><strong>Check this out</strong></p>
<pre><code>args = ['test_file']
print "Before args are -",args
for suite in args:
#Checks test word
if suite.startswith('test'):
#If yes, append "hello.tests"
new_suite="hello.tests."+suite
#Replace it in args list
args[args.index(suite)]=new_suite
print "After args are -",args
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Before args are - ['test_file']
After args are - ['hello.tests.test_file']
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
<p>Above can be also implemented using <strong>list comprehension.</strong></p>
<pre><code>args = ['test_file',"file_test"]
print "Before args are -",args
args = ["hello.tests."+suite if suite.startswith('test') else suite for suite in args]
print "After args are -",args
</code></pre>
| 0 |
2016-09-23T07:28:25Z
|
[
"python"
] |
Making GUI with only python without framework?
| 39,654,954 |
<ol>
<li>Is it possible to create a user interface without the help of python framework (like tinker or pygame) and use only vanilla python code? If yes, how?</li>
<li>Can you briefly explain how python framework works?</li>
<li>Is the code of different python framework different?</li>
<li>If the computer did not have the framework installed, will the program still runnable if the program uses a framework?
Thanks very much</li>
</ol>
| 0 |
2016-09-23T07:21:51Z
| 39,655,710 |
<ol>
<li>Yes, after all tinker and pygame are just python classes packaged as modules.</li>
<li>Python frameworks are a bunch of pre-tested and reusable modules that allow you to use and extend upon so you don't have to reinvent the wheel. </li>
<li>Yes, frameworks will have differences in usability and code.</li>
<li>The computer will always need the dependencies, though you can package these in various ways aka create a package that has all your dependencies for the program to run. </li>
</ol>
| 1 |
2016-09-23T08:02:49Z
|
[
"python",
"user-interface",
"frameworks"
] |
Making GUI with only python without framework?
| 39,654,954 |
<ol>
<li>Is it possible to create a user interface without the help of python framework (like tinker or pygame) and use only vanilla python code? If yes, how?</li>
<li>Can you briefly explain how python framework works?</li>
<li>Is the code of different python framework different?</li>
<li>If the computer did not have the framework installed, will the program still runnable if the program uses a framework?
Thanks very much</li>
</ol>
| 0 |
2016-09-23T07:21:51Z
| 39,657,647 |
<p>If you want as few external dependencies as possible (but still a GUI) I would strongly suggest using a Web-Microframework like <a href="http://bottlepy.org/docs/dev/index.html" rel="nofollow">bottle</a> (single file) and utilize the user's browser for rendering.</p>
<ol>
<li>You can make a GUI without any external framework with HTML by setting up a webserver and using the user's browser to render it.</li>
<li>For a browser-GUI without an external Framework: Depending on whether you know JavaScript you can either use XML-RPC (<a href="https://docs.python.org/3/library/xmlrpc.server.html" rel="nofollow">xmlrpc.server</a>+<a href="https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler" rel="nofollow">http.server</a> with JS in the browser) or WSGI (<a href="https://docs.python.org/3/library/wsgiref.html" rel="nofollow">wsgiref</a>) (example on that page)</li>
<li>Yes, totally.</li>
<li>Of course the if you do not prepare for this case you cannot run a program without an integral part of it like a Framework - but you can distribute your program with the Framework included.</li>
</ol>
<p>For XML-RPC</p>
<pre><code>import xmlrpc.server
import http.server
class MyHandler(xmlrpc.server.SimpleXMLRPCRequestHandler,http.server.SimpleHTTPRequestHandler):
pass
</code></pre>
<p>This handler will serve files from the current working directory (your actual HTML-UI and JS for communication (there are several XMP-RPC libraries for JS)) but it can also be used like in the <a href="https://docs.python.org/3/library/xmlrpc.server.html#simplexmlrpcserver-example" rel="nofollow">XML-RPC-Server example</a> to glue your code and the UI together.</p>
| 0 |
2016-09-23T09:44:26Z
|
[
"python",
"user-interface",
"frameworks"
] |
Time complexity of zlib's deflate algorithm
| 39,654,986 |
<p>What is the time complexity of Zlib's deflate algorithm?</p>
<p>I understand that in Python this algorithm is made available via the <code>zlib.compress</code> function.</p>
<p>Presumably the corresponding decompression algorithm has the same or better complexity.</p>
| 1 |
2016-09-23T07:23:43Z
| 39,662,445 |
<p>Time complexity is how the processing time scales with the size of the input. For zlib, and any other compression scheme I know of, it is O(<em>n</em>) for both compression and decompression. The time scales linearly with the size of the input.</p>
<p>If you are thinking that the time complexity of decompression is less somehow, then perhaps you are thinking about the constant in front of the <em>n</em>, as opposed to the <em>n</em>. Yes, decompression is usually faster than compression, because that constant is smaller. Not because the time complexity is different, because it isn't.</p>
| 1 |
2016-09-23T13:47:49Z
|
[
"python",
"compression",
"complexity-theory",
"zlib"
] |
Accessing users groups through attributes / foreign keys in Django
| 39,655,053 |
<p>I'm trying to access my users groups in Django, but keep getting</p>
<pre><code>auth.Group.None
</code></pre>
<p>as the result.</p>
<p>When in the django shell I'll first create a group, then a user and add the user to the group. After this, I try to print the users groups, like so:</p>
<pre><code>from django.contrib.auth.models import User, Group
Artists = Group.objects.create(name="Artists")
Artists.save()
Rihanna = User.objects.create_user(username="Rihanna", password="newpassword")
Rihanna.save()
Artists.user_set.add(Rihanna)
# Save both of them again just to double check
Rihanna.save()
Artists.save()
# Now try to access Rihanna's groups through her attributes:
print Rihanna.groups, Rihanna.groups.name
</code></pre>
<p>and the results are</p>
<pre><code>>>> auth.Group.None None
</code></pre>
<p>What I'd like to happen is for it to print the groups name.</p>
<p>I know I can query the members of a group by the filter and get commands, but I'd like to access the groups straight through a users attributes/foreign keys. Any idea what I'm doing wrong?</p>
| 0 |
2016-09-23T07:27:25Z
| 39,655,200 |
<p>You added user to group in group object, but your user object does not have update state for this.</p>
<p>Try access groups like this:</p>
<pre><code>print Rihanna.groups.all()
</code></pre>
<p>or add group in user model:</p>
<pre><code>Rihanna.groups.add(Artists)
</code></pre>
| 0 |
2016-09-23T07:35:08Z
|
[
"python",
"django"
] |
Stuff spaces at end of lines in file
| 39,655,340 |
<p>I am trying to read a fixed with file that has lines/records of different lengths. I need to stuff spaces at the end of the lines which are less than the standard length specified.</p>
<p>Any help appreciated.</p>
<p><a href="http://i.stack.imgur.com/N5Kbd.png" rel="nofollow">enter image description here</a></p>
| -1 |
2016-09-23T07:42:11Z
| 39,655,568 |
<p>You can use <a href="https://docs.python.org/3.3/library/string.html" rel="nofollow">string.format</a> to pad a string to a specific length.</p>
<p>The documentation says that <code><</code> pads to the right so to pad a string with spaces to the right to a specific length you can do something like this:</p>
<pre><code>>>> "{:<30}".format("foo")
'foo '
</code></pre>
| 2 |
2016-09-23T07:55:32Z
|
[
"python",
"fixed-width"
] |
Stuff spaces at end of lines in file
| 39,655,340 |
<p>I am trying to read a fixed with file that has lines/records of different lengths. I need to stuff spaces at the end of the lines which are less than the standard length specified.</p>
<p>Any help appreciated.</p>
<p><a href="http://i.stack.imgur.com/N5Kbd.png" rel="nofollow">enter image description here</a></p>
| -1 |
2016-09-23T07:42:11Z
| 39,655,745 |
<p>You could consider to use ljust string method.
If line is a line read from your file:</p>
<pre><code>line = line.ljust(50)
</code></pre>
<p>will stuff the end of the line with spaces to get a 50 characters long line. If line is longer that 50, line is simply copied without any change.</p>
| 1 |
2016-09-23T08:04:58Z
|
[
"python",
"fixed-width"
] |
Calculate z-score in data bunch but excluding N.A
| 39,655,397 |
<p>So I got this bunch of data with N.A. values in them:</p>
<p><a href="http://i.stack.imgur.com/XVlKo.jpg" rel="nofollow">Data Dump</a></p>
<p>So how do I get the z-score of each column while excluding the N.A. values? Such that the z-score output looks like this?</p>
<p><a href="http://i.stack.imgur.com/S5XiW.jpg" rel="nofollow">Z-Score value output</a></p>
<p>So for this is what I have, which is based on previous questions:</p>
<pre><code>cols = list(df.columns)
df[cols]
for col in cols:
col_zscore = col + '_zscore'
df[col_zscore] = (df[col] - df[col].mean())/df[col].std(ddof="N.A.")
</code></pre>
<p>but I got TypeError. </p>
<p>Please help, I am really a beginner at this.</p>
| 0 |
2016-09-23T07:45:16Z
| 39,655,617 |
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> first <code>N.A.</code> to <code>NaN</code> and convert values to <code>float</code>:</p>
<pre><code>df = df.replace({'N.A.': np.nan}).astype(float)
for col in df.columns:
if col != 'PE Trail':
col_zscore = col + '_zscore'
df[col_zscore] = (df[col] - df[col].mean())/df[col].std()
print (df)
PE Trail PE fwd PB PE fwd_zscore PB_zscore
0 NaN 1.00 1.0 1.317465 0.707107
1 NaN 0.50 NaN 0.146385 NaN
2 NaN 0.00 0.5 -1.024695 -0.707107
3 NaN 0.25 NaN -0.439155 NaN
</code></pre>
<p>Also <code>type</code> of value in parameter <code>ddof</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.std.html" rel="nofollow"><code>std</code></a> is <code>int</code>.</p>
<hr>
<p>If use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>, parameter <code>na_values</code> causes converting <code>N.A.</code> to <code>NaN</code>:</p>
<pre><code>import pandas as pd
import numpy as np
import io
temp=u"""PE Trail;PE fwd;PB
N.A.;1;1
N.A.;0.5;N.A.
N.A.;0;0.5
N.A.;0.25;N.A."""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=";", na_values='N.A.')
print (df)
PE Trail PE fwd PB
0 NaN 1.00 1.0
1 NaN 0.50 NaN
2 NaN 0.00 0.5
3 NaN 0.25 NaN
</code></pre>
| 1 |
2016-09-23T07:57:58Z
|
[
"python",
"pandas"
] |
For half-hourly intervals can I use Pandas TimeDeltaIndex, PeriodIndex or DateTimeIndex?
| 39,655,448 |
<p>I have a table of data values that should be indexed with half-hourly intervals, and I've been processing them with Pandas and Numpy. Currently they're in CSV files and I import them using <code>read_csv</code> to a dataframe with only the interval-endpoint as an index. I am uncomfortable with that and want to have the intervals themselves as the index.</p>
<p>I do not know whether to use a <code>DateTimeIndex</code>, a <code>PeriodIndex</code> or a <code>TimedeltaIndex</code>... All of them seem very similar in practice, to me. My operations include </p>
<ul>
<li>Looking up a particular interval</li>
<li>Checking if a DateTime is contained in a particular interval</li>
<li>Intersection and (Set)Difference of intervals</li>
<li>Split and join intervals</li>
</ul>
<p>Can Pandas even do all of these? Is it advisable? I already am using <a href="https://pypi.python.org/pypi/interval/1.0.0" rel="nofollow">this interval library</a>, would using Pandas <code>tslib</code> and <code>period</code> be better?</p>
| 0 |
2016-09-23T07:48:14Z
| 39,707,398 |
<p>if you only need a series with time interval of 30 minutes you can do this:</p>
<pre><code>import pandas as pd
import datetime as dt
today = dt.datetime.date()
yesterday = dt.datetime.date()-dt.timedelta(days=1)
time_range = pd.date_range(yesterday,today, freq='30T')
</code></pre>
<p>now you could use it to set an index such has</p>
<pre><code>pd.DataFrame(0, index=time_range,columns=['yourcol'])
Out[35]:
yourcol
2016-09-25 00:00:00 0
2016-09-25 00:30:00 0
2016-09-25 01:00:00 0
2016-09-25 01:30:00 0
2016-09-25 02:00:00 0
</code></pre>
<p>this would be a DateTimeIndex</p>
<p>you can read more about time interval in pandas here: <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases</a></p>
| 0 |
2016-09-26T16:00:54Z
|
[
"python",
"datetime",
"pandas",
"intervals"
] |
What are the conversion rules in the SoftLayer_Virtual_Guest::getBillingCyclePublicBandwidthUsageâs return value?
| 39,655,607 |
<p>Iâm developing total usage for bandwidth. And I tried a lot of method to get total usage for bandwidth. The result always different from portal site while they are nearly. I donât know whether the rules is wrong or not. Because the return value of API SoftLayer_Virtual_Guest::getBillingCyclePublicBandwidthUsage(amountIn and amountOut) are decimal. So I did as following:</p>
<pre><code>result = bandwidth_mgt.sl_virtual_guest.getBillingCyclePublicBandwidthUsage(id=instance_id)
amountOut = Decimal(result['amountOut'])*1024 #GB to MB
amountIn = Decimal(result['amountIn'])*1024 #GB to MB
print 'amountOut=%s MB amountIn=%s MB' %(amountOut, amountIn)
</code></pre>
<p>The result is âamountOut=31.75424 MB amountIn=30.6176 MBâ.
But the portal siteâs result is 33.27 MB and 32.1 MB. There is 1.5MB different. why? regard~</p>
<p><a href="http://i.stack.imgur.com/Gf9z1.png" rel="nofollow">picture of portal site</a></p>
| 1 |
2016-09-23T07:57:29Z
| 39,662,304 |
<p>That is the expected behavior the values are not exactly the same, this is because the portal uses another method to get that value, if you want to get the same value you need to use the same method.</p>
<p>check out these related forums.</p>
<ul>
<li><a href="http://stackoverflow.com/questions/36308040/bandwidth-summary-per-server">Bandwidth summary per server</a></li>
</ul>
<p>you need to use the method: <a href="http://sldn.softlayer.com/reference/services/SoftLayer_Metric_Tracking_Object/getSummaryData" rel="nofollow">http://sldn.softlayer.com/reference/services/SoftLayer_Metric_Tracking_Object/getSummaryData</a> </p>
<p>The values returned by the method are the used to create the chart in control portal.</p>
<p>I made this code in Python</p>
<pre><code>#!/usr/bin/env python3
import SoftLayer
# Your SoftLayer API username and key.
USERNAME = 'set me'
API_KEY = 'set me'
vsId = 24340313
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
vgService = client['SoftLayer_Virtual_Guest']
mtoService = client['SoftLayer_Metric_Tracking_Object']
try:
idTrack = vgService.getMetricTrackingObjectId(id = vsId)
object_template = [{
'keyName': 'PUBLICIN',
'summaryType': 'sum'
}]
counters = mtoService.getSummaryData('2016-09-04T00:00:00-05:00','2016-09-26T23:59:59-05:00',object_template,600, id = idTrack)
totalIn = 0
for counter in counters:
totalIn = totalIn + counter["counter"]
object_template = [{
'keyName': 'PUBLICOUT',
'summaryType': 'sum'
}]
counters = mtoService.getSummaryData('2016-09-04T00:00:00-05:00','2016-09-26T23:59:59-05:00',object_template,600, id = idTrack)
totalOut = 0
for counter in counters:
totalOut = totalOut + counter["counter"]
print( "The total INBOUND in GB: ")
print(totalIn / 1000 / 1000 / 1000 )
print( "The total OUTBOUND in MB: ")
print(totalOut / 1000 / 1000 )
print( "The total GB")
print((totalOut + totalIn) / 1000 / 1000 / 1000 )
except SoftLayer.SoftLayerAPIError as e:
print("Unable get the bandwidth. "
% (e.faultCode, e.faultString))
</code></pre>
<p>regards</p>
| 0 |
2016-09-23T13:40:45Z
|
[
"python",
"api",
"bandwidth",
"result",
"softlayer"
] |
Uploading User Details from an excel file using pandas in python to postgres Database
| 39,655,688 |
<p>I am uploading user details(username,email,password) from a .csv file to postgres DB using pandas in python. It is all fine till the dataframe gets generated but once I run the code for uploading the user details the substring-"@gmail.com" from their emai-id gets converted to/stored as lowercase in postgres DB.
This is the code that I have written in python shell of a django application -</p>
<pre><code>>>>import sys
>>>from django.contrib.auth import authenticate
>>>from django.contrib.auth import get_user_model
>>>import pandas as pd
>>>User = get_user_model()
>>>df=pd.read_excel('set_A_results_748_web.xlsx',sheetname='Sheet1',parse_cols=(0,3,4))
</code></pre>
<p>df.head()</p>
<p><a href="http://i.stack.imgur.com/YIIgE.png" rel="nofollow">Dataframe First 10 rows Output Screenshot</a></p>
<pre><code>>>>users = [tuple(x) for x in df.values]
>>>for name, email, password in users:
try:
print ('Creating user {0}.'.format(name))
user = User.objects.create_user(name=name, email=email)
user.set_password(password)
user.save()
assert authenticate(name=name, password=password)
print ('User {0} successfully created.'.format(name))
except:
print ('There was a problem creating the user: {0}. Error: {1}.' \
.format(name, sys.exc_info()[1]))
</code></pre>
<p><a href="http://i.stack.imgur.com/M4vQi.png" rel="nofollow">Postgres User Table Data Screenshot After Uploading</a></p>
<p>As shown in the output (first 10 rows of dataframe df) the email ids of every user is acc to the data in excel file but when I upload them to auth_user table in my postgres DB the latter part of email gets converted to lowercase.</p>
<p>Example: The E-mail address of row 6 (Dipak Shah) would be stored as <code>DIPAK.13ME57@gmail.com</code> whereas it should be stored as is i.e. <code>DIPAK.13ME57@GMAIL.COM</code>. This creates a problem in application as the users scores alongwith other details are stored in another scores table which I upload separately through a Kettle transformation. So for records which have email mismatch because of case mismatch there would be no data in the scores table.</p>
<p>Any ideas where I might be going wrong or what can I do to avoid this.Any help would be much appreciated!</p>
| 0 |
2016-09-23T08:01:46Z
| 39,655,954 |
<p>This has nothing to do with postgres, it's django that is <a href="https://github.com/django/django/blob/1.10/django/contrib/auth/base_user.py#L23" rel="nofollow">normalizing the email address</a> when a new user <a href="https://github.com/django/django/blob/1.10/django/contrib/auth/models.py#L147" rel="nofollow">is created</a>, as the host part of an email address is case insensitive. Whether the name part is case sensitive usually depends on the mail server.</p>
<p>If you really need to use the email address as a matching criteria, then you should also apply the same normalization to those other addresses.</p>
<p>Edit:</p>
<p>It seems that this normalization is only applied in <code>create_user()</code>, if you later set the email address by using <code>user.email = 'SOMEBODY@EXAMPLE.ORG'</code> then it won't be applied. But I'd not rely too much on that, such a different behaviour could be seen as a bug and corrected in a future version.</p>
| 0 |
2016-09-23T08:16:36Z
|
[
"python",
"django",
"postgresql",
"pandas"
] |
Parameters like width, align, justify won't work in Tkinter Message
| 39,655,854 |
<p>I'm trying to change the width of a Message widget in Tkinter by using the width parameter. I couldn't get it to work so I tried align, justify and aspect which all produced the same result - the box remains centred and the width of the text.</p>
<p>Here is my code:</p>
<pre><code>console_Fetch = Message(text="test\ntest\ntest\ntest\ntest",bd=1,relief="sunken",width=300)
console_Fetch.grid(row=7,column=0,padx=5,pady=1,columnspan=2)
</code></pre>
<p>I'm obviously using .grid() to pack it into the window.</p>
<p>Here's a screenshot of my window:
<a href="http://i.stack.imgur.com/lgLoV.png" rel="nofollow"><img src="http://i.stack.imgur.com/lgLoV.png" alt="enter image description here"></a></p>
| -1 |
2016-09-23T08:11:07Z
| 39,656,549 |
<h3>Pragmatic answer</h3>
<p>Often setting <code>width</code> in widgets is not working as expected, depending on priority of other aspects, cell width, you name it. It gets easily overruled, or depends on other conditions.</p>
<p>What I always do is give the grid a "skeleton" of canvases in adjecent cells, with height (or width) of zero. Subsequently stretch the widget with <code>sticky</code> inside their cells. Just look at the example below:</p>
<p><a href="http://i.stack.imgur.com/LP3lX.png" rel="nofollow"><img src="http://i.stack.imgur.com/LP3lX.png" alt="enter image description here"></a></p>
<pre><code>from tkinter import *
win = Tk()
console_Fetch = Message(text="test\ntest\ntest\ntest\ntest",bd=1,relief="sunken",width=3000)
canvas = Canvas(width = 500, height = 0)
canvas.grid(row=0,column=0)
console_Fetch.grid(row=1,column=0,padx=5,pady=1,columnspan=2, sticky = N+W+E+S)
win.mainloop()
</code></pre>
<p>The same I did in shaping the grid in the minesweeper- matrix in <a href="http://stackoverflow.com/a/39449125/1391444">this answer</a>.</p>
| 2 |
2016-09-23T08:49:23Z
|
[
"python",
"tkinter"
] |
How to make a for loop with exception handling when key not in dictionary?
| 39,656,012 |
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
except KeyError:
print('Country not found, please try again! \n')
</code></pre>
| 0 |
2016-09-23T08:20:06Z
| 39,656,122 |
<p>Your break is not in the if scope... so it will break on the first attempt.</p>
| 0 |
2016-09-23T08:26:10Z
|
[
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary?
| 39,656,012 |
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
except KeyError:
print('Country not found, please try again! \n')
</code></pre>
| 0 |
2016-09-23T08:20:06Z
| 39,656,205 |
<p>There will be no <code>KeyError</code> here because your code never tires to access the dictionary, just checks if the key is in <code>keys</code>. You could simply do this to achieve the same logic:</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
else:
print('Country not found, please try again! \n')
</code></pre>
<p>Sample run:</p>
<pre><code>Please choose five stock exchanges to analyse,
just name the corresponding countries
Please enter country no. 1: sdf
Country not found, please try again!
Please enter country no. 1: USA
Found the corresponding stock index!
Please enter country no. 2: Aregtng
Country not found, please try again!
Please enter country no. 2: Argentina
Found the corresponding stock index!
Please enter country no. 3: United States
Found the corresponding stock index!
Please enter country no. 4: usa
Found the corresponding stock index!
Please enter country no. 5: usa
Found the corresponding stock index!
</code></pre>
<p>Note: <code>.keys()</code> is overkill: to check if a key is in a dictionary you only need <code>k in some_dict</code></p>
| 2 |
2016-09-23T08:29:51Z
|
[
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary?
| 39,656,012 |
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
except KeyError:
print('Country not found, please try again! \n')
</code></pre>
| 0 |
2016-09-23T08:20:06Z
| 39,656,223 |
<p>From the <a href="https://wiki.python.org/moin/KeyError" rel="nofollow">doc</a></p>
<blockquote>
<p>Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.</p>
</blockquote>
<p>In your piece of code if you want print a message when user inserts a key not present in the countries dict, you can simply add an else statement instead of catch exception.</p>
<p>You can change your code in this way:</p>
<pre><code>if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
else:
print('Country not found, please try again! \n')
</code></pre>
| 0 |
2016-09-23T08:30:26Z
|
[
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary?
| 39,656,012 |
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
except KeyError:
print('Country not found, please try again! \n')
</code></pre>
| 0 |
2016-09-23T08:20:06Z
| 39,656,268 |
<p>Couple of points:</p>
<ul>
<li>You code never going to hit exception since you are checking key existence using <code>if key in dict.keys()</code> </li>
<li><p>Also, there are so many loops. I think <code>for i in range(0,5)</code> is enough.Will be <strong>less complicated</strong>.</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
countr = raw_input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
else:
print('Country not found, please try again! \n')
</code></pre></li>
</ul>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Please choose five stock exchanges to analyse,
just name the corresponding countries
Please enter country no. 1: USA
Found the corresponding stock index!
Please enter country no. 2: asd
Country not found, please try again!
Please enter country no. 3: asd
Country not found, please try again!
Please enter country no. 4: USA
Found the corresponding stock index!
Please enter country no. 5: United states
Found the corresponding stock index!
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 0 |
2016-09-23T08:33:31Z
|
[
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary?
| 39,656,012 |
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
except KeyError:
print('Country not found, please try again! \n')
</code></pre>
| 0 |
2016-09-23T08:20:06Z
| 39,656,283 |
<p>I am assuming you want it to give you a message if the stock is not in the dictionary ex_dict, I have modified the code to do the same.</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr not in ex_dict.keys():
print ('Try again!')
else:
print('Found the corresponding stock index! \n')
countries.append(countr)
</code></pre>
| 0 |
2016-09-23T08:34:19Z
|
[
"python",
"for-loop",
"dictionary",
"exception"
] |
Pythonic way to wrap a subprocess call that takes a lot of parameters?
| 39,656,035 |
<p>I am writing a python script that provides a more user friendly API to a command line tool. Some of the necessary command calls take a lot of parameters (up to around 10 sometimes), but that is not good practice in Python. They can't just be defaults; it has to be possible to set all the parameters for a given call.</p>
<p>My current structure is an API class that has functions such as expose_image(), and then an interface class to handle the construction of the subprocess command and the call. I don't see that adding more classes will help, as the API class still has to generate and pass the parameters in some way.</p>
<p>One solution I have come up with is to fill a dictionary or namedtuple with the parameters and pass it as **kwargs, which makes things look a little nicer, but less explicit.</p>
<p>Is there a better way of handling this?</p>
<p>Thanks!</p>
| 1 |
2016-09-23T08:21:32Z
| 39,656,293 |
<p>It is commendable that you want to build a Pythonic API rather than just an API for this command.</p>
<p>I'm not sure why you disregard default parameters though? If the default is <code>None</code>, you could treat that as a guide to not add things to the command line.</p>
<p>For example, suppose you want to call the tree command. You could have something like:</p>
<pre><code>def my_tree(dirs_only=False, full_prefix=False, max_level=None, pattern=None):
cmd_line = ['tree']
if dirs_only:
cmd_line.append('-d')
if full_prefix:
cmd_line.append('-f')
if max_level is not None:
cmd_line.append('-L')
cmd_line.append(str(max_level))
if pattern is not None:
cmd_line.append('-P')
cmd_line.append(pattern)
subprocess.do_something_with(cmd_line)
</code></pre>
<p>Callers of <code>my_tree</code> could then interact with it like in the shell:</p>
<pre><code>my_tree()
my_tree(dirs_only=True)
my_tree(pattern='Foo*')
my_tree(pattern='Foo*', max_level=2, full_prefix=True)
</code></pre>
<p>In languages such as Java, C# or Dart, you often see "fluent" APIs, and perhaps those might help. It would result in code such as:</p>
<pre><code>my_tree().call()
my_tree().dirs_only().call()
my_tree().with_pattern('Foo*').call()
my_tree() \
.with_pattern('Foo*') \
.with_max_level(2) \
.full_prefix() \
.call()
</code></pre>
<p>Though the invocation looks nicer, there is a lot of boilerplate you need to write in order to obtain said niceity, which definitely feels a little bit un-Pythonic.</p>
| 2 |
2016-09-23T08:34:30Z
|
[
"python",
"subprocess",
"parameter-passing",
"args",
"kwargs"
] |
Pythonic way to wrap a subprocess call that takes a lot of parameters?
| 39,656,035 |
<p>I am writing a python script that provides a more user friendly API to a command line tool. Some of the necessary command calls take a lot of parameters (up to around 10 sometimes), but that is not good practice in Python. They can't just be defaults; it has to be possible to set all the parameters for a given call.</p>
<p>My current structure is an API class that has functions such as expose_image(), and then an interface class to handle the construction of the subprocess command and the call. I don't see that adding more classes will help, as the API class still has to generate and pass the parameters in some way.</p>
<p>One solution I have come up with is to fill a dictionary or namedtuple with the parameters and pass it as **kwargs, which makes things look a little nicer, but less explicit.</p>
<p>Is there a better way of handling this?</p>
<p>Thanks!</p>
| 1 |
2016-09-23T08:21:32Z
| 39,656,738 |
<p>Like you said, <code>**</code> of kvargs are convenient way to <em>pass</em> several arguments to your function, however it always better to declare arguments explicitly in the function definition:</p>
<pre><code>def store(data, database,
user, password,
host=DEFAULT_HOST,
port=PG_DEFAULT_PORT,
chunk_size=64,
flags=None):
pass
# call
params = {"data": generate_data(),
"database": "mydb",
"user": "guest",
"password": "guest",
"chunk_size": 128
}
store(**params)
</code></pre>
<p>Another way is to use "Parameters" class, like this (an example from <code>pika</code> library):</p>
<pre><code>class ConnectionParameters(Parameters):
def __init__(self,
host=None,
port=None,
virtual_host=None,
credentials=None,
channel_max=None,
frame_max=None,
heartbeat_interval=None,
ssl=None,
ssl_options=None,
connection_attempts=None,
retry_delay=None,
socket_timeout=None,
locale=None,
backpressure_detection=None):
super(ConnectionParameters, self).__init__()
# Create the default credentials object
if not credentials:
credentials = self._credentials(self.DEFAULT_USERNAME,
self.DEFAULT_PASSWORD)
...
# call
conn_params = pika.ConnectionParameters(host=self._host,
port=self._port,
credentials=cred)
conn = pika.BlockingConnection(parameters=conn_params)
</code></pre>
| 2 |
2016-09-23T08:58:56Z
|
[
"python",
"subprocess",
"parameter-passing",
"args",
"kwargs"
] |
Can't save and instantiate a child class in my django model
| 39,656,071 |
<p>Ok now I changed my models as follow:</p>
<pre><code>from django.contrib.auth.models import User
class Company(User):
company_name = models.CharField(max_length = 20)
class Employee(User):
pass
</code></pre>
<p>When I run from pytho manage.py shell the following commands:</p>
<pre><code>u = Employee(first_name = 'john', last_name = 'smith', password = 'test', email = 'smith@gmail.com')
u.save()
e = Employee(user = u)
e.save()
</code></pre>
<p>I get the following errors and can't really understand why.
Any help is appreciated, thanks in advance.</p>
| -1 |
2016-09-23T08:23:14Z
| 39,995,827 |
<p>when writing:</p>
<pre><code>class x(y)
</code></pre>
<p>in Python this means x extends (inherit from) y.</p>
<p>while</p>
<blockquote>
<p>class Employee(User):<br>
pass</p>
</blockquote>
<p>makes a little sense (an employee is a user), this</p>
<blockquote>
<p>class Company(User):</p>
</blockquote>
<p>makes no sense at all (Company is not a user).</p>
<p>If you want that a user will have the right to log in as a company, I'd advise to use foreign key:</p>
<pre><code>class Company(models.Model):
user_with_permissions_fk = models.ManyToManyField((User)
</code></pre>
<p><br><br><br>
As to this piece of code:</p>
<blockquote>
<p>u = Employee(first_name = 'john', last_name = 'smith', password = 'test', email = 'smith@gmail.com')<br>
u.save()<br>
e = Employee(user = u)<br>
e.save()</p>
</blockquote>
<p>Please provide your syntax error -or- please consider replacing with this code:</p>
<pre><code>new_records_to_insert = []
new_records_to_insert += Employee(first_name = 'john', last_name = 'smith', password = 'test', email = 'smith@gmail.com')
new_records_to_insert += Employee(first_name = 'john', last_name = 'smith', password = 'test', email = 'smith@gmail.com')
Employee.objects.bulk_create(new_records_to_insert)
# No need to .save()
</code></pre>
| 0 |
2016-10-12T10:02:27Z
|
[
"python",
"django",
"database",
"django-models"
] |
Python dropbox - Opening spreadsheets
| 39,656,180 |
<p>I was testing with the dropbox provided API for python..my target was to read a Spreadsheet in my dropbox without downloading it to my local storage. </p>
<pre><code>import dropbox
dbx = dropbox.Dropbox('my-token')
print dbx.users_get_current_account()
fl = dbx.files_get_preview('/CGPA.xlsx')[1] # returns a Response object
</code></pre>
<p>After the above code, calling the <code>fl.text()</code> method gives an HTML output which shows the preview that would be seen if opened by browser. And the data can be parsed.</p>
<p>My query is, if there is a built-in method of the SDK for getting any particular info from the spreadsheet, like the data of a row or a cell...preferrably in json format...I previously used butterdb for extracting data from a google drive spreadsheet...is there such functionality for dropbox?....could not understand by reading the docs: <a href="http://dropbox-sdk-python.readthedocs.io/en/master/" rel="nofollow">http://dropbox-sdk-python.readthedocs.io/en/master/</a></p>
| 0 |
2016-09-23T08:28:45Z
| 39,666,433 |
<p>No, the Dropbox API doesn't offer the ability to selectively query parts of a spreadsheet file like this without downloading the whole file, but we'll consider it a feature request.</p>
| 0 |
2016-09-23T17:27:34Z
|
[
"python",
"dropbox",
"xls"
] |
How to download outlook attachment from Python Script?
| 39,656,433 |
<p>I need to download incoming attachment without past attachment from mail using Python Script.</p>
<p>For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.</p>
<p>Please anyone help me to download attachment using python script or java.</p>
| 2 |
2016-09-23T08:42:59Z
| 39,872,935 |
<pre><code>import email
import imaplib
import os
class FetchEmail():
connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_server)
self.connection.login(username, password)
self.connection.select(readonly=False) # so we can mark mails as read
def close_connection(self):
"""
Close the connection to the IMAP server
"""
self.connection.close()
def save_attachment(self, msg, download_folder="/tmp"):
"""
Given a message, save its attachments to the specified
download folder (default is /tmp)
return: file path to attachment
"""
att_path = "No attachment found."
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
att_path = os.path.join(download_folder, filename)
if not os.path.isfile(att_path):
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
return att_path
def fetch_unread_messages(self):
"""
Retrieve unread messages
"""
emails = []
(result, messages) = self.connection.search(None, 'UnSeen')
if result == "OK":
for message in messages[0].split(' '):
try:
ret, data = self.connection.fetch(message,'(RFC822)')
except:
print "No new emails to read."
self.close_connection()
exit()
msg = email.message_from_string(data[0][1])
if isinstance(msg, str) == False:
emails.append(msg)
response, data = self.connection.store(message, '+FLAGS','\\Seen')
return emails
self.error = "Failed to retreive emails."
return emails
</code></pre>
<p>Above code works for me to download attachment.Hope this really helpful for any one.</p>
| 2 |
2016-10-05T11:37:04Z
|
[
"java",
"python",
"email",
"outlook"
] |
ValueError: I/O operation on closed file when using **generator** over **list**
| 39,656,437 |
<p>I have the two following functions to extract data from a csv file, one returns a list and the other a generator:</p>
<p>List:</p>
<pre><code>def data_extraction(filename,start_line,node_num,span_start,span_end):
with open(filename, "r") as myfile:
file_= csv.reader(myfile, delimiter=',') #extracts data from .txt as lines
return [filter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, node_num+1)]
</code></pre>
<p>Generator:</p>
<pre><code>def data_extraction(filename,start_line,node_num,span_start,span_end):
with open(filename, "r") as myfile:
file_= csv.reader(myfile, delimiter=',') #extracts data from .txt as lines
return (itertools.ifilter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, node_num+1))
</code></pre>
<p>I start my program by a call to one of the following functions to extract the data.
The next line is: <code>print [x in data]</code></p>
<p>When I use the function which returns a list it all works fine, when I use the generator I get : <code>ValueError: I/O operation on closed file</code></p>
<p>I gathered from other questions that it was due to the fact that the <code>with open</code> statement was probably lost once my <code>data_extraction</code> function <code>returns</code>.</p>
<p>The question is: Is there a workaround to be able to keep an independent function to extract the data so that I don't have to put all my code inside one function ? And secondly will I be able to reset the generator to use it multiple times ?</p>
<p>the reason for wanting to keep the generator over the list is that I am dealing with large datasets.</p>
| 0 |
2016-09-23T08:43:05Z
| 39,656,712 |
<p>Note that the <code>with</code> statement closes the file at its end. That means no more data can be read from it.</p>
<p>The list version actually reads in all data, since the list elements must be created.</p>
<p>The generator version instead never reads any data until you actual fetch data from the generator. Since you do that after closing the file, the generator will then fail because it <em>then</em> tries to fetch it.</p>
<p>You can only avoid this by actually reading in the data, e.g. as you did via creating the list. Trying not to hold all data (generator) but still wanting to have all data (closing the file) doesn't make sense.</p>
<p>The alternative is to open the file each time for reading - the file object acts like a generator for its values. If you want to avoid duplicating the filtering code, you can create a wrapper for this:</p>
<p>The straightforward way is to turn your generator-returning function into a generator function itself:</p>
<pre><code>def data_extraction(filename,start_line,node_num,span_start,span_end):
with open(filename, "r") as myfile:
file_= csv.reader(myfile, delimiter=',') #extracts data from .txt as lines
for item in (itertools.ifilter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, node_num+1)):
yield item
</code></pre>
<p>This has a bit of a problem: the <code>with</code> statement will only close once the generator is exhausted or collected. This brings you into the same situation as having an open file, which you must finish as well.</p>
<p>A safer alternative is to have a filter generator and feed it the file content:</p>
<pre><code>def data_extraction(file_iter, start_line, node_num, span_start, span_end):
file_= csv.reader(file_iter, delimiter=',') #extracts data from .txt as lines
for item in (itertools.ifilter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, node_num+1)):
yield item
# use it as such:
with with open(filename, "r") as myfile:
for line in data_extraction(mayflies):
# do stuff
</code></pre>
<p>If you need this often, you can also create your own class by implementing the context manager protocol. This can then be used in a <code>with</code> statement instead of <code>open</code>.</p>
<pre><code>class FileTrimmer(object):
def __init__(self, filename, start_line, node_num, span_start, span_end):
# store all attributes on self
def __enter__(self):
self._file = open(self.filename, "r")
csv_reader = csv.reader(self._file, delimiter=',') #extracts data from .txt as lines
return (
itertools.ifilter(
lambda a: a != '',
row[self.span_start:self.span_end])
for row in itertools.islice(
csv_reader,
self.start_line,
self.node_num+1
))
def __exit__(self, *args, **kwargs):
self._file.close()
</code></pre>
<p>You can now use it like this:</p>
<pre><code>with FileTrimmer('/my/file/location.csv', 3, 200, 5, 10) as csv_rows:
for row in csv_rows: # row is an *iterator* over the row
print('<', '>, <'.join(row), '>')
</code></pre>
| 1 |
2016-09-23T08:57:22Z
|
[
"python",
"list",
"python-2.7",
"csv",
"generator"
] |
Copying column from CSV to CSV with python
| 39,656,546 |
<p>I'm new with python and I would like to know if it's possible to copy the first column from a .csv file to another .csv file. The reason is that I have a lot of .csv and instead of opening each one manually and copying to only one .csv I would like to automate this step.</p>
<p>Thank you very much!</p>
| -1 |
2016-09-23T08:49:18Z
| 39,657,833 |
<p><strong>Code Snipet:</strong>
<strong>You need to configure source and destination</strong> </p>
<pre><code>import os
from os import listdir
from os.path import isfile, join
import csv
mypath="sourcePath"
newcsv="destination"
# for just files in a directory and not the subDirectory
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
print(onlyfiles)
for file in onlyfiles:
if file.endswith(".csv"):
with open(os.path.join(mypath,file ), newline='') as f:
reader = csv.reader(f)
for row1 in reader:
out = csv.writer(open(newcsv,"w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(row1);
</code></pre>
| 0 |
2016-09-23T09:53:03Z
|
[
"python"
] |
pyqtgraph - Background color loads only after reloading
| 39,656,627 |
<p>I see I'm not <a href="https://stackoverflow.com/questions/31567573/issue-in-setting-the-background-color-in-pyqtgraph">the only one</a> having a problem with background color in pyqtgraph - I'm writing a QGIS software plugin which has an additional dialog box with a graph. I'm trying to set the background color and it loads only after I reload the plugin using QGIS Plugin Reloader plugin (<em>this plugin is made for people developing plugins, so after any change in the code, you refresh and have a new one loaded into QGIS. It is not used by a common user</em>). </p>
<p>My piece of code below:</p>
<pre><code>import pyqtgraph
...
def prepareGraph(self): # loads on button click
self.graphTitle = 'Graph one'
# prepare data - simplified, but data display correctly
self.y = something
self.x = something_else
self.buildGraph()
def buildGraph(self):
""" Add data to the graph """
pyqtgraph.setConfigOption('background', (230,230,230))
pyqtgraph.setConfigOption('foreground', (100,100,100))
dataColor = (102,178,255)
dataBorderColor = (180,220,255)
barGraph = self.graph.graphicsView
barGraph.clear()
barGraph.addItem(pyqtgraph.BarGraphItem(x=range(len(self.x)), height=self.y, width=0.5, brush=dataColor, pen=dataBorderColor))
barGraph.addItem(pyqtgraph.GridItem())
barGraph.getAxis('bottom').setTicks([self.x])
barGraph.setTitle(title=self.graphTitle)
self.showGraph()
def showGraph(self):
self.graph.show()
</code></pre>
<p>Interesting thing is that <strong>all parts of <code>buildGraph()</code> load without any issue, (even the foreground color!)</strong> only the background color won't. </p>
<p>Is this a known bug or there is a difference between setting fore- and background color? Linked question didn't help me to solve this problem.</p>
<p><code>pyqtgraph==0.9.10
PyQt4==4.11.4
Python 2.7.3</code></p>
| 0 |
2016-09-23T08:52:59Z
| 39,658,042 |
<p>The <a href="http://www.pyqtgraph.org/documentation/style.html#default-background-and-foreground-colors" rel="nofollow">pyqtgraph documentation</a> says about <code>setConfigOption</code> settings, that:</p>
<blockquote>
<p>Note that this must be set before creating any widgets</p>
</blockquote>
<p>In my code I have</p>
<pre><code>def buildGraph(self):
pyqtgraph.setConfigOption('background', (230,230,230))
pyqtgraph.setConfigOption('foreground', (100,100,100))
barGraph = self.graph.graphicsView
</code></pre>
<p>and that's what I thought is the "before" place, but it's creation of an object, not widget. One should write <code>setConfigOption</code> inside a class, that is responsible for storing <code>pyqtgraph</code> object. In my case it was <code>__init__</code> function inside a separate file creating a separate dialog box:</p>
<p>from PyQt4 import QtGui, QtCore
from plugin4_plot_widget import Ui_Dialog
from plugin4_dialog import plugin4Dialog
import pyqtgraph</p>
<pre><code>class Graph(QtGui.QDialog, Ui_Dialog):
def __init__(self):
super(Graph, self).__init__()
pyqtgraph.setConfigOption('background', (230,230,230))
pyqtgraph.setConfigOption('foreground', (100,100,100))
self.setupUi(self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Graph()
main.show()
sys.exit(app.exec_())
</code></pre>
| 0 |
2016-09-23T10:04:15Z
|
[
"python",
"qgis",
"pyqtgraph"
] |
Python random while multiple conditions
| 39,656,722 |
<p>Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
v = random.randint(1, 3)
if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1
result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"
print (result)
</code></pre>
<p>I want to loop this until a is above 190 AND b above 140 AND c above 110 but it stops everytime after the first run.</p>
<p>Can someone help me there?</p>
| 0 |
2016-09-23T08:57:53Z
| 39,656,768 |
<p>You could change the logically slightly and use an infinite loop that you then <code>break</code> out of when your conditions are met:</p>
<pre><code>while True:
# do stuff
if a >= 190 and b >= 140 and c >=110:
break
</code></pre>
<p>Your original logic terminated if <em>any</em> of the conditions were met. For example, this loop exits because <code>a</code> is no longer <code>True</code> after the first iteration:</p>
<pre><code>a = True
b = True
while a and b:
a = False
</code></pre>
<p>This loop is infinite because <code>b</code> is always <code>True</code>:</p>
<pre><code>a = True
b = True
while a or b:
a = False
</code></pre>
<p>You could use <code>or</code> instead of <code>and</code> for your initial <code>while</code> loop, but I find the <code>break</code> logic far more intuitive.</p>
| 4 |
2016-09-23T09:00:36Z
|
[
"python",
"random",
"multiple-conditions"
] |
Python random while multiple conditions
| 39,656,722 |
<p>Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
v = random.randint(1, 3)
if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1
result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"
print (result)
</code></pre>
<p>I want to loop this until a is above 190 AND b above 140 AND c above 110 but it stops everytime after the first run.</p>
<p>Can someone help me there?</p>
| 0 |
2016-09-23T08:57:53Z
| 39,656,775 |
<p>You are resetting <code>a</code>, <code>b</code> and <code>c</code> in the body of the loop.
Try this:</p>
<pre><code>>>> count = 0
>>> while a < 190 and b < 140 and c < 110 and count < 10: # <-- This condition here
... count += 1
... a = 0
... b = 0
... c = 0
... print(count, a, b, c)
...
(1, 0, 0, 0)
(2, 0, 0, 0)
(3, 0, 0, 0)
(4, 0, 0, 0)
(5, 0, 0, 0)
(6, 0, 0, 0)
(7, 0, 0, 0)
(8, 0, 0, 0)
(9, 0, 0, 0)
(10, 0, 0, 0)
>>>
</code></pre>
| 1 |
2016-09-23T09:00:51Z
|
[
"python",
"random",
"multiple-conditions"
] |
Python random while multiple conditions
| 39,656,722 |
<p>Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
v = random.randint(1, 3)
if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1
result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"
print (result)
</code></pre>
<p>I want to loop this until a is above 190 AND b above 140 AND c above 110 but it stops everytime after the first run.</p>
<p>Can someone help me there?</p>
| 0 |
2016-09-23T08:57:53Z
| 39,657,141 |
<p>Actually you are only showing "a,b,c" when the while loop iterates and you incrementing in each loop 465 times. This means if your while loop works 4 times its gonna increment a, b, c randomly 465*4 times. and your values too way small for this kinda increment. As a solution you can decrease 465 number if you make it 250 you'll see it'll work until c reaches over 110 and finishes iterating.</p>
<pre><code>for i in range(1, 250):
v = random.randint(1, 3)
</code></pre>
<p>With 250 c reaches 114 and finishes iterating. This because that 250 / 3 ~= 83 . And when the numbers dispenses as randomly c is the most commonly reacher that it's limit. I think that you want something like this;</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
v = random.randint(1, 3)
if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1
result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"
print (result)
</code></pre>
<p>It will gonna show you each increment one by one and it will gonna stop when some of the requirements meets in while loop.</p>
| 0 |
2016-09-23T09:20:53Z
|
[
"python",
"random",
"multiple-conditions"
] |
Python Pandas Debugging on to_datetime
| 39,656,781 |
<p>Millions of records of data is in my dataframe. I have to convert of the string columns to datetime. I'm doing it as follows:</p>
<pre><code>allData['Col1'] = pd.to_datetime(allData['Col1'])
</code></pre>
<p>However some of the strings are not valid datetime strings, and thus I get a value error. I'm not very good at debugging in Python, so I'm struggling to find the reason why some of the data items are not convertible. </p>
<p>I need Python to show me the row number, as well as the value that is not convertible, instead of throwing out a useless error that tells me nothing. How can I achieve this?</p>
| 1 |
2016-09-23T09:01:04Z
| 39,656,810 |
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with condition where check <code>NaT</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a> created <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> with parameter <code>errors='coerce'</code> - it create <code>NaT</code> where are invalid datetime:</p>
<pre><code>allData1 = allData[pd.to_datetime(allData['Col1'], errors='coerce').isnull()]
</code></pre>
<p>Sample:</p>
<pre><code>allData = pd.DataFrame({'Col1':['2015-01-03','a','2016-05-08'],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (allData)
B C Col1 D E F
0 4 7 2015-01-03 1 5 7
1 5 8 a 3 3 4
2 6 9 2016-05-08 5 6 3
print (pd.to_datetime(allData['Col1'], errors='coerce'))
0 2015-01-03
1 NaT
2 2016-05-08
Name: Col1, dtype: datetime64[ns]
print (pd.to_datetime(allData['Col1'], errors='coerce').isnull())
0 False
1 True
2 False
Name: Col1, dtype: bool
allData1 = allData[pd.to_datetime(allData['Col1'], errors='coerce').isnull()]
print (allData1)
B C Col1 D E F
1 5 8 a 3 3 4
</code></pre>
| 1 |
2016-09-23T09:02:32Z
|
[
"python",
"string",
"datetime",
"debugging",
"pandas"
] |
Create SQL database from dict with different features in python
| 39,656,800 |
<p>I have the following dict:</p>
<pre><code>base = {}
base['id1'] = {'apple':2, 'banana':4,'coconut':1}
base['id2'] = {'apple':4, 'pear':8}
base['id3'] = {'banana':1, 'tomato':2}
....
base['idN'] = {'pineapple':1}
</code></pre>
<p>I want to create a SQL database to store it. I normally use <code>sqlite</code> but here the number of variables (features in the dict) is not the same for all ids and I do not know all of them thus I cannot use the standard procedure.</p>
<p>Does someone know an easy way to do it ? </p>
| 0 |
2016-09-23T09:02:00Z
| 39,656,907 |
<p>ids will get duplicated if you use the sql i would suggest use postgres as it has a jsonfield ypu can put your data there corresponding to each key. Assuming you are not constrained to use SQL.</p>
| 0 |
2016-09-23T09:06:59Z
|
[
"python",
"sqlite",
"dictionary"
] |
how to add href value in django view
| 39,656,843 |
<p>I am working on a project using django, in this i have a module which shows the listing of users in a table format, the data of users returns from django view to django template using ajax, so the action values with buttons also have to be returned from view to template in json response, as we usually do in bootstrap ajax datatables. </p>
<p>Now the problem is that i have to set href value in django view.</p>
<p><strong>Code in view is :-</strong> </p>
<pre><code>for user in users:
actionValues='<a title="Edit" class="btn btn-sm green margin-top-10" href="'"><i class="fa fa-edit"></i></a>
<a title="View" class="btn btn-sm blue margin-top-10" href="'"><i class="fa fa-view"></i></a>';
inner_data_list = [
i,
user['first_name'],
user['last_name'],
user['email'],
user_type,
'<div id=%s class="bootstrap-switch bootstrap-switch-%s bootstrap-switch-wrapper bootstrap-switch-animate toogle_switch"><div class="bootstrap-switch-container" ><span class="bootstrap-switch-handle-on bootstrap-switch-primary">&nbsp;Active&nbsp;&nbsp;</span><label class="bootstrap-switch-label">&nbsp;</label><span class="bootstrap-switch-handle-off bootstrap-switch-default">&nbsp;Inactive&nbsp;</span></div></div>'%(user['id'],checked),
user['date_joined'],
actionValues
]
datalist.append(inner_data_list)
</code></pre>
<p>As you can see in code there is a variable actionValues it contains two buttons, related to each listing , Now what i have to do is i have to link these two buttons to function edit_details and view_details respectively. So how can i link these two buttons to their respective function in view.</p>
| 0 |
2016-09-23T09:04:06Z
| 39,656,929 |
<p>Here you go..</p>
<pre><code><li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
</code></pre>
| 0 |
2016-09-23T09:08:44Z
|
[
"python",
"django"
] |
how to add href value in django view
| 39,656,843 |
<p>I am working on a project using django, in this i have a module which shows the listing of users in a table format, the data of users returns from django view to django template using ajax, so the action values with buttons also have to be returned from view to template in json response, as we usually do in bootstrap ajax datatables. </p>
<p>Now the problem is that i have to set href value in django view.</p>
<p><strong>Code in view is :-</strong> </p>
<pre><code>for user in users:
actionValues='<a title="Edit" class="btn btn-sm green margin-top-10" href="'"><i class="fa fa-edit"></i></a>
<a title="View" class="btn btn-sm blue margin-top-10" href="'"><i class="fa fa-view"></i></a>';
inner_data_list = [
i,
user['first_name'],
user['last_name'],
user['email'],
user_type,
'<div id=%s class="bootstrap-switch bootstrap-switch-%s bootstrap-switch-wrapper bootstrap-switch-animate toogle_switch"><div class="bootstrap-switch-container" ><span class="bootstrap-switch-handle-on bootstrap-switch-primary">&nbsp;Active&nbsp;&nbsp;</span><label class="bootstrap-switch-label">&nbsp;</label><span class="bootstrap-switch-handle-off bootstrap-switch-default">&nbsp;Inactive&nbsp;</span></div></div>'%(user['id'],checked),
user['date_joined'],
actionValues
]
datalist.append(inner_data_list)
</code></pre>
<p>As you can see in code there is a variable actionValues it contains two buttons, related to each listing , Now what i have to do is i have to link these two buttons to function edit_details and view_details respectively. So how can i link these two buttons to their respective function in view.</p>
| 0 |
2016-09-23T09:04:06Z
| 39,658,845 |
<p>Use <code>reverse()</code> function to get the url</p>
<p>If you have specified a url pattern name like</p>
<pre><code>url(r'^foo/bar/(?P<user_id>\d+)/$', some_viewfunc, name='some-view')
</code></pre>
<p><code>reverse('some-view', kwargs={'user_id': 100})</code> gives you <code>'/foo/bar/100/'</code></p>
<p>So use something like<br>
<code>'<a href="%s">Link Name</a>' % (reverse('some-view', kwargs={'user_id': 100}))</code></p>
| 0 |
2016-09-23T10:44:56Z
|
[
"python",
"django"
] |
How to get print data in text file ordered by date
| 39,656,974 |
<p>I have following code,</p>
<pre><code>import glob,os,win32com.client,datetime,time,email.utils,ctypes,sys
import Tkinter as tk
import tkFileDialog as filedialog
sys.path.append('C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_e163563597edeada')
root = tk.Tk()
root.withdraw()
file_path = filedialog.askdirectory()
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders('Paper & CD')
messages = inbox.Items
date_now = datetime.datetime.now()
#print date_now
date_before = (datetime.datetime.now() + datetime.timedelta(-30)).date()
#print date_before
#ctypes.windll.user32.MessageBoxA(0,'Current date is: '+str(date_now)+',It will fetch details from :'+str(date_before),"Information",0)
for msg in messages:
for att in msg.Attachments:
if att.FileName == 'list.csv':
att.SaveAsFile(file_path + "\\" + msg.subject + att.FileName)
att.SaveAsFile(file_path + "\\" + att.FileName)
ctypes.windll.user32.MessageBoxA(0,'Download is finished,Now select files to count',"Information",0)
root = tk.Tk()
root.withdraw()
file_path = filedialog.askdirectory()
os.chdir(file_path)
date_now = datetime.datetime.now().date()
date_before = (datetime.datetime.now() + datetime.timedelta(-30)).date()
of = open("Info.txt", 'w')
for file in glob.glob("*.csv"):
of.write("\n\nFile Name:")
of.write(file+"\n")
fi = open(file)
numline = len(fi.readlines())
of.write("\n"+"Number of records:")
of.write(str(numline-1)+"\n")
of.write(str("\nCreated time:"))
of.write(str(time.ctime(os.path.getctime(file)))+"\n")
of.write(str("\nModified time:"))
of.write(str(time.ctime(os.path.getmtime(file)))+"\n")
of.close()
</code></pre>
<p>Now, It take attachements from outlook and stored into local path.
And then It create text document and write attachement detail into text file.</p>
<p>My output text file is like below.</p>
<pre><code>File Name:CD file for xxxlist.csv
Number of records:4
Created time:Sun Sep 04 17:25:32 2016
Modified time:Sun Sep 04 17:25:32 2016
File Name:CD file for xxlist.csv
Number of records:2
Created time:Mon Sep 12 10:23:08 2016
Modified time:Mon Sep 12 10:23:08 2016
File Name:CD file for xxlist.csv
Number of records:8
Created time:Thu Sep 15 17:32:23 2016
Modified time:Thu Sep 15 17:32:23 2016
</code></pre>
<p>I want 2 changes in code.
1)Time here displays the received time of mail.I want to change that into sent time.I want time format like below,</p>
<pre><code>"9/6/2016 10:15:00 AM"
</code></pre>
<p>2) My output file is listed based on the file name(Ascending order).
I want it to be based on time in which mail sent.
for example: If I received two mails(1st on sep 14 and 2nd mail on sep 15). I want details of the attachments which is on sep 15 mail and then other one.</p>
<p>I am newbie to Python,Help is appreciated.</p>
| 1 |
2016-09-23T09:11:25Z
| 39,657,930 |
<p>You can use the <code>email</code> module to get the time you received the email. </p>
<pre><code>import email
# use email.message_from_string or email_message_from_file to make a email object
email_obj = email.message_from_file(my_file) # my_file is a file object
print email_obj.keys() # shows you all available properties of the email
print email_obj.get('Date') # print the time of the email
</code></pre>
<p>As noted in the comments, please inspect the output from <code>email_obj.keys()</code>, if you need to extract any other information from the email</p>
<p>Edit: (expanded to handle time from email as datetime)</p>
<p>You can use <code>parsedate_tz</code> function from email module to get a tuple representing the datetime components. You can then use <code>datetime.strftime</code> to print as you desire</p>
<pre><code>from email import parsedate_tz
from datetime import datetime
dt_tuple = parsedate_tz(email_obj.get('Date'))
# [:7] on the tuple to ignore the timezone info.
# If you need to process the timezone you need additional logic for that
datetime_obj = datetime(*dt_tuple[:7])
print datetime.strftime(datetime_obj, '%a %b %d %H:%M:%S %Y')
</code></pre>
| 0 |
2016-09-23T09:58:08Z
|
[
"python",
"email"
] |
Is the collection in tensorflow.get_collection() cleared?
| 39,657,063 |
<p>I'm learning about neural nets using Tensorflow through the Stanford course. I found this while implementing a RNN and did not quite understand why the losses are accumulated:</p>
<pre class="lang-python prettyprint-override"><code># This adds a loss operation to the Graph for batch training
def add_loss_op(self, output):
all_ones = [tf.ones([self.config.batch_size * self.config.num_steps])]
cross_entropy = sequence_loss(
[output], [tf.reshape(self.labels_placeholder, [-1])], all_ones, len(self.vocab))
tf.add_to_collection('total_loss', cross_entropy)
# Doesn't this increase in size every batch of training?
loss = tf.add_n(tf.get_collection('total_loss'))
return loss
</code></pre>
<p>The documentation for <code>get_collection()</code> <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Graph.get_collection" rel="nofollow">here</a> doesn't mention anything about clearing the variables. Since this is run for every training step, are the losses incremented every epoch / minibatch of training and carried over? </p>
<p>I am still new to NNs so do correct any misunderstanding I have on this!</p>
| 1 |
2016-09-23T09:16:32Z
| 39,678,543 |
<p>I believe the add_n here is actually just to make sure that any pre-existing losses in the 'total_loss' collection get added in for the final result. It's not changing any variables, just summing up its inputs and returning the total.</p>
| 0 |
2016-09-24T16:29:58Z
|
[
"python",
"neural-network",
"tensorflow",
"recurrent-neural-network"
] |
Python: Create an exception for a refused database conection with pymysql
| 39,657,106 |
<p>Today I has the problem with a down database when a programmed script were running. I would like to create an exception when this happend again to send me an email (I already create the function to do it). But I'm failing in trying to create an exception for it.</p>
<pre><code> import pymysql.cursors
#Conection Settings....
try:
with connection.cursor() as cursor:
# Read a single record
sql = "select count(*) as total_invoices, " \
"sum(e.Montant_vente - e.Montant_tva_recup) as total_amount " \
"from extrait_sapeig_stat e " \
"where e.montant_vente != 0 " \
"and e.numero_client = 1086 " \
"and e.activite != 11 " \
"and e.invoice_date = date_add(curdate(), Interval -1 DAY) " \
"and right(e.Numero_facture,7) not in (1182499) " \
print(sql)
cursor.execute(sql)
inv_counts_2 = cursor.fetchall()
finally:
connection.close()
</code></pre>
| 0 |
2016-09-23T09:19:13Z
| 39,657,387 |
<p>Because you haven't defined an exception.</p>
<pre><code> import pymysql.cursors
#Connection Settings....
try:
with connection.cursor() as cursor:
# Read a single record
sql = "select count(*) as total_invoices, " \
"sum(e.Montant_vente - e.Montant_tva_recup) as total_amount " \
"from extrait_sapeig_stat e " \
"where e.montant_vente != 0 " \
"and e.numero_client = 1086 " \
"and e.activite != 11 " \
"and e.invoice_date = date_add(curdate(), Interval -1 DAY) " \
"and right(e.Numero_facture,7) not in (1182499) " \
print(sql)
cursor.execute(sql)
inv_counts_2 = cursor.fetchall()
except Exception as e:
print (e)
finally:
connection.close()
</code></pre>
| 0 |
2016-09-23T09:32:58Z
|
[
"python",
"mysql",
"pymysql",
"try-except"
] |
Auto-fill Django OneToOneField
| 39,657,126 |
<p>This maybe a simple question, but I do not have any idea how to do this.
I have two models in Django.</p>
<pre><code>class ModelA(models.Model):
some_member = models.Charfield(...)
class ModelB(models.Model):
model = OneToOneField(ModelA)
other_member = models.Charfield(...)
</code></pre>
<p><code>ModelA</code> is filled in by a ModelForm and then redirect to the form for <code>ModelB</code>.
How can I Autofill the <code>OneToOneField</code> based on the previous form.
Thank you for helping.</p>
<hr>
<p>I am doing it like this now</p>
<pre><code>class ModelBView(CreateView):
.......
def form_valid(self, form):
model_b = form.save(commit=False)
model_a_form = ModelAForm(self.request.POST)
model_b.model = model_a_form.save(commit=False)
model_b.save()
return super(ModelBView, self).form_valid(form)
</code></pre>
<p>but get the error: "...could not be created because the data didn't validate."</p>
<p>So here the problem is, I simply can get the data from the previous form by request.POST.
How can I get this data.</p>
| 1 |
2016-09-23T09:20:15Z
| 39,658,134 |
<p>Maybe you can save the data from ModelForm for ModelA in request.session or request.get and redirect to the next page for ModelB, where you can get the data for model field in ModelB then fill it.</p>
| 0 |
2016-09-23T10:08:45Z
|
[
"python",
"django",
"forms"
] |
Auto-fill Django OneToOneField
| 39,657,126 |
<p>This maybe a simple question, but I do not have any idea how to do this.
I have two models in Django.</p>
<pre><code>class ModelA(models.Model):
some_member = models.Charfield(...)
class ModelB(models.Model):
model = OneToOneField(ModelA)
other_member = models.Charfield(...)
</code></pre>
<p><code>ModelA</code> is filled in by a ModelForm and then redirect to the form for <code>ModelB</code>.
How can I Autofill the <code>OneToOneField</code> based on the previous form.
Thank you for helping.</p>
<hr>
<p>I am doing it like this now</p>
<pre><code>class ModelBView(CreateView):
.......
def form_valid(self, form):
model_b = form.save(commit=False)
model_a_form = ModelAForm(self.request.POST)
model_b.model = model_a_form.save(commit=False)
model_b.save()
return super(ModelBView, self).form_valid(form)
</code></pre>
<p>but get the error: "...could not be created because the data didn't validate."</p>
<p>So here the problem is, I simply can get the data from the previous form by request.POST.
How can I get this data.</p>
| 1 |
2016-09-23T09:20:15Z
| 39,658,745 |
<p>It depends on what you want exactly.</p>
<p>If you want to auto-fill the field in the second form, then you can use the <code>initial</code> keyword argument when instantiating the form for ModelB (e.g. in your view); like this:</p>
<pre><code>def my_view(request):
"""
Save data to ModelA and show the user the form for ModelB
"""
if request.method == 'POST':
# Save ModelA instance
model_a_form = ModelFormA(request.POST)
if model_a_form.is_valid():
model_a_instance = model_a_form.save()
# Once saved, show the user the form for ModelB, prefilled
# with the result from the previous form
model_b_form = ModelFormB(initial={'model': model_a_instance})
# etc. Render the page as usual
else:
# ...
elif request.method == 'GET':
# ...
</code></pre>
<p>If, on the other hand, you don't want ModelA to appear in the second form as a field, but still link it to the resulting instance, you can do something like this when handling the response of the second form.</p>
<pre><code># ... instance of first model is saved in `model_a_instance`
# Initiate an empty instance of ModelB, with the value of `model` field set to model_a_instance
model_b_instance = ModelB(model=model_a_instance)
# Provide it as an instance to your model form
model_b_form = ModelFormB(request.POST, instance=model_b_instance)
if model_b_form.is_valid():
# Everything else should work fine.
</code></pre>
<p>Hope this helps.</p>
| 0 |
2016-09-23T10:39:12Z
|
[
"python",
"django",
"forms"
] |
Automatic tagging of words or phrases
| 39,657,146 |
<p>I want to automatically tag a word/phrase with one of the defined words/phrases from a list. My list contains about 230 words in columnA which are tagged in columnB. There are around 16 unique tags and every of those 230 words are tagged with one of these 16 tags.</p>
<p>Have a look at my list:</p>
<p><a href="http://i.stack.imgur.com/VQ2W2.jpg" rel="nofollow">The words/phrases in column A are tagged as words/phrases in column B.</a>
<a href="http://i.stack.imgur.com/VQ2W2.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/VQ2W2.jpg" alt="enter image description here"></a></p>
<p>From time to time, new words are added for which tag has to be given manually.
I want to build a predictive algorithm/model to tag new words automatically(or suggest). So if I write a new word, let say 'MIP Reserve' (A36), then it should predict the tag as 'Escrow Deposits'(B36) and not 'Operating Reserve'(B33). How should I predict the tags of new word precisely even if the words do not match with the words in its actual tag?
If someone is willing to see the full list, I can happily share.</p>
| 0 |
2016-09-23T09:20:59Z
| 39,662,787 |
<h1>Short version</h1>
<p>I think your question is a little ill-defined and doesn't have a short coding or macro answer. Given that each item contains such little information, I don't think it is possible to build a good predictive model from your source data. Instead, do the tagging exercise once and look at how you control tagging in the future.</p>
<h1>Long version</h1>
<p>Here are the steps I would take to create a predictive model and why I don't think you can do this.</p>
<ol>
<li><strong>Understand why you want to have a predictive program at all</strong></li>
</ol>
<p>Why do you need a predictive program? Are you sorting through hundreds or thousands of records, all of which are changing and need tagging? If so, I agree, you wouldn't want to do this manually.</p>
<p>If this is a one-off exercise, because over time the tags have become corrupted from their original meaning, your problem is that your tags have become corrupted, not that you need to somehow predict where each item should be tagged. You should be looking at controlling use of the tags, not at predicting how people in the future might mistag or misname something.</p>
<p>Don't forget that there are lots of tools in Excel to make the problem easier. Let's say you know for certain that all items with 'cash' definitely go to 'Operating Cash'. Put an AutoFilter on the list and filter on the word 'cash' - now just copy and paste 'Operating Cash' next to all of these. This way, you can quickly get rid of the obvious ones from your list and focus on the tricky ones.</p>
<ol start="2">
<li><strong>Understand the characteristics of the tags you want to use.</strong></li>
</ol>
<p>Take time to look at the tags you are using - what do each of them mean? What are the unique features or combinations of features that this tag is representing?</p>
<p>For example, your tag 'Operating Cash' carries the characteristics of being cash (i.e. not tied up so available for use fairly quickly) and as being earmarked for operations. From these, we could possibly derive further characteristics that it is held in a certain place, or a certain person has responsibility for it.</p>
<p>If you had more source data to go on, you could perhaps use fields such as 'year created', or 'customer' to help you categorise further.</p>
<ol start="3">
<li><strong>Understand what it is about the items you want to tag that could give you an idea of where they should go.</strong></li>
</ol>
<p>This is your biggest problem. A quick example - what in the string "MIP Reserve" gives any clues that it should be linked to "Escrow Deposits"? You have no easy way of matching many of the items in your list - many words appear in multiple items across multiple tags.</p>
<p>However, try and look for unique identifiers that will give you clues - for example, all items with the word 'developer' seem to be tagged to 'Developer Fee Note & Interest'. Do you have any more of those? Use these to reduce your problem, since they should be a straightforward mapping.</p>
<p>Any unique identifiers will allow you to set up rules for these strings. You don't even need to stick to one word - perhaps when you see several words, you can narrow down where it will end up e.g. when I see 'egg' this could go into 'bird' or 'reptile', but if 'egg' is paired with 'wing', I can be fairly confident it's 'bird'.</p>
<p>You need to match the characteristics of the items you want to tag with the unique identifiers of the tags you developed in step 1.</p>
<ol start="4">
<li><strong>Write a program or macro to look for the identifiers in step 2 and return the relevant tag from step 1.</strong></li>
</ol>
<p>This is the straightforward bit. Look for the identifiers you want (e.g. uses 'cash', contains tag 'Really Important Customer') and look for the best match in the tags you have earlier.</p>
<p>Ensure you catch any errors - what happens if no tag is found? Does it create a new one? Does it recommend contacting you for help? What happens if more than one tag is relevant? What are your tiebreaking criteria?</p>
<p>But be aware of...</p>
<ol start="5">
<li><strong>Understand how you will control use of these unique identifiers.</strong></li>
</ol>
<p>Imagine you somehow manage to come up with a list of unique identifiers. How will you control their use? If you have decided to send any item with the word 'cash' to the tag 'Operating Cash' and then in a year, someone comes along and makes an item 'Capital Cash', because they want somewhere to put cash that is about to be spent on capital items, how do you stop this? How are you going to control use of these words?</p>
<p>You will effectively need to take control of the item naming system and set up an agreed list of identifying words. Whenever anyone makes an item, they need to include your identifiers somewhere. I can tell you that this will not work. Either they will use the wrong words and you will end up manually doing it anyway, or they will ring you up confused and you will end up manually doing it anyway.</p>
<p>If you are the only person doing this, just do the exercise once, to your own standard (that you record) and stick to that standard. When you need to hand it over, it's clearly ordered and makes sense. If more than one person is doing this, do the exercise once between you and the team and then agree a way of controlling it.</p>
<p>Writing a predictive program sounds great and might save you some time. But consider why you are writing it. Are you likely to need to tag accounts constantly in the future? If so, control their naming centrally and make it so a tag is mandatory when they are made. If not, why are you writing a program to do this? Just do it once, manually.</p>
| 0 |
2016-09-23T14:05:11Z
|
[
"python",
"excel",
"nlp",
"data-modeling",
"prediction"
] |
Word2Vec: Using Gensim and Google-News dataset- Very Slow Execution Time
| 39,657,215 |
<p>The Code is in python. I loaded up the binary model into gensim on python, & used the "init_sims" option to make the execution faster. The OS is OS X.
It takes almost 50-60 seconds to load it up. And an equivalent time to find "most_similar". Is this normal? Before using the init_sims option, it took almost double the time! I have a feeling it might be an OS RAM allocation issue.</p>
<pre><code>model=Word2Vec.load_word2vec_format('GoogleNewsvectorsnegative300.bin',binary=True)
model.init_sims(replace=True)
model.save('SmallerFile')
#MODEL SAVED INTO SMALLERFILE & NEXT LOAD FROM IT
model=Word2Vec.load('SmallerFile',mmap='r')
#GIVE RESULT SER!
print model.most_similar(positive=['woman', 'king'], negative=['man'])
</code></pre>
| 0 |
2016-09-23T09:24:33Z
| 39,718,081 |
<p>Note that the memory-saving effect of <code>init_sims(replace=True)</code> doesn't persist across save/load cycles, because saving always saves the 'raw' vectors (from which the unit-normalized vectors can be recalculated). So, even after your re-load, when you call <code>most_similar()</code> for the 1st time, <code>init_sims()</code> will be called behind the scenes, and the memory usage will be doubled.</p>
<p>And, the GoogleNews dataset is quite large, taking 3+ GB to load even before the unit-normalization possibly doubles the memory usage. So depending on what else you've got running and the machine's RAM, you might be using swap memory by the time the <code>most_similar()</code> calculations are running â which is very slow for the calculate-against-every-vector-and-sort-results similarity ops. (Still, any <code>most_similar()</code> checks after the 1st won't need to re-fill the unit-normalized vector cache, so should go faster than the 1st call.)</p>
<p>Given that you've saved the model after <code>init_sims(replace=True)</code>, its raw vectors are already unit-normalized. So you can manually-patch the model to skip the recalculation, just after your <code>load()</code>:</p>
<pre><code>model.syn0norm = model.syn0
</code></pre>
<p>Then even your first <code>most_similar()</code> will just consult the (single, memory-mapped) set of vectors, without triggering an <code>init_sims()</code>.</p>
<p>If that's still too slow, you may need more memory or to trim the vectors to a subset. The GoogleNews vectors seem to be sorted to put the most-frequent words earliest, so throwing out the last 10%, 50%, even 90% may still leave you with a useful set of the most-common words. (You'd need to perform this trimming yourself by looking at the model object and source code.)</p>
<p>Finally, you can use a nearest-neighbors indexing to get faster top-N matches, but at a cost of extra memory and approximate results (that may miss some of the true top-N matches). There's an IPython notebook tutorial in recent gensim versions at <a href="https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/annoytutorial.ipynb" rel="nofollow">annoytutorial.ipynb</a> IPython notebook of the demo IPython notebooks, in the gensim <a href="https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/" rel="nofollow"><code>docs/notebooks</code></a> directory.</p>
| 0 |
2016-09-27T07:01:49Z
|
[
"python",
"gensim",
"word2vec"
] |
Python: how to count the access of an instance variable
| 39,657,260 |
<p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>How can I count how many time I accessed self.b variable on the invocation of meth2() or any method of class A. Is there any way, I can log the usage of self.b variable?</p>
| 1 |
2016-09-23T09:27:44Z
| 39,657,348 |
<p>You can use <a href="https://docs.python.org/2/howto/descriptor.html" rel="nofollow">descriptors</a> for this or just make a property which is basically is descriptor.</p>
<pre><code>class A(object):
def __init__(self, logger):
self._b = B()
self._b_counter = 0
self.logger = logger
@property
def b(self):
self._b_counter += 1
return self._b
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
</code></pre>
| 1 |
2016-09-23T09:31:25Z
|
[
"python",
"class"
] |
Python: how to count the access of an instance variable
| 39,657,260 |
<p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>How can I count how many time I accessed self.b variable on the invocation of meth2() or any method of class A. Is there any way, I can log the usage of self.b variable?</p>
| 1 |
2016-09-23T09:27:44Z
| 39,657,354 |
<p>make 'b' a property and and increase the counter corresponding to be in the setter.</p>
<pre><code>@property
def b(self):
self.b_counter += 1
return self._b
</code></pre>
<p>and in your class replace b with _b</p>
| 2 |
2016-09-23T09:31:40Z
|
[
"python",
"class"
] |
Python: how to count the access of an instance variable
| 39,657,260 |
<p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>How can I count how many time I accessed self.b variable on the invocation of meth2() or any method of class A. Is there any way, I can log the usage of self.b variable?</p>
| 1 |
2016-09-23T09:27:44Z
| 39,657,408 |
<p>You can use property, somtehing like:</p>
<pre><code>class A(object):
def __init__(self, logger):
self._b = B()
self._count = 0
self.logger = logger
@property
def b(self):
self._count += 1
return self._b
...
...
</code></pre>
| 0 |
2016-09-23T09:33:52Z
|
[
"python",
"class"
] |
Python: how to count the access of an instance variable
| 39,657,260 |
<p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>How can I count how many time I accessed self.b variable on the invocation of meth2() or any method of class A. Is there any way, I can log the usage of self.b variable?</p>
| 1 |
2016-09-23T09:27:44Z
| 39,657,527 |
<p>If you don't want to make a property, you can log the read/write access using <code>__getattribute__</code> (not <code>__getattr__</code> since <code>b</code> exists and would not be called) and <code>__setattr__</code>:</p>
<pre><code>class A(object):
def __init__(self):
# initialize counters first !
self.b_read_counter = 0
self.b_write_counter = 0
# initialize b
self.b = 12
def __getattribute__(self,attrib):
# log read usage
if attrib=="b":
self.b_read_counter+=1
# now return b value
return object.__getattribute__(self, attrib)
def __setattr__(self,attrib,value):
if attrib=="b":
self.b_write_counter+=1
return object.__setattr__(self, attrib,value)
a = A()
a.b = 23 # second write access (first is in the init method)
if a.b == 34: # first read access
print("OK")
if a.b == 34:
print("OK")
if a.b == 34: # third read access
print("OK")
print(a.b_read_counter)
print(a.b_write_counter)
</code></pre>
<p>result:</p>
<pre><code>3
2
</code></pre>
| 1 |
2016-09-23T09:39:33Z
|
[
"python",
"class"
] |
Quicksort in place Python
| 39,657,307 |
<p>I am extremely new to Python and i am trying my hand in Algorithms. I was just trying my hands in the in place sorting of an array using quicksort algo.</p>
<p>Below is my code . When i run this there is an infinite loop as output. Can anyone kindly go through the code and let me know where i am going wrong logically :</p>
<pre><code>def quicksort(arr,start,end):
if start < end:
pivot = arr[int(start + (end - start)/2)]
while end > start:
while arr[start] < pivot:
start = start + 1
while arr[end] > pivot:
end = end - 1
if start <= end:
arr[start],arr[end] = arr[end],arr[start]
start = start + 1
end = end - 1
quicksort(arr,0,end)
quicksort(arr,start,len(arr) - 1)
else:
return
arr = list(map(int,input().split(" ")))
quicksort(arr,0,len(arr) - 1)
print ("The final sorted array:",arr)
</code></pre>
<p>Thanks for any help in advance.</p>
| 0 |
2016-09-23T09:29:36Z
| 39,668,817 |
<p>Your recursion is wrong. After doing Hoare Partition, you should do :</p>
<ul>
<li>call quicksort from start (of data that being sorted) to index that run from the end, and</li>
<li>call quicksort from end (of data that being sorted) to index that run from the start</li>
</ul>
<p>So you have to create new variables beside the argument to maintain start,end and indices that move toward each other in the partition.</p>
<p>In order to not change a lot of your code, i suggest you to change the argument</p>
<pre><code>def quicksort(arr,left,right):
start = left
end = right
</code></pre>
<p>and do this in the recursion</p>
<pre><code>quicksort(arr,left,end)
quicksort(arr,start,right)
</code></pre>
| 0 |
2016-09-23T20:11:08Z
|
[
"python"
] |
How to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column
| 39,657,330 |
<p><br>A very simple example just for understanding.</p>
<p><strong>The goal is to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column.</strong></p>
<p>I have the following DataFrame:</p>
<pre><code>import numpy as np
import pandas as pd
s = pd.Series([1,2,3,2,1,2,3,2,1])
df = pd.DataFrame({'DATA':s, 'POINTS':0})
df
</code></pre>
<p><a href="http://i.stack.imgur.com/8dZmD.png" rel="nofollow"><img src="http://i.stack.imgur.com/8dZmD.png" alt="DataFrame start"></a></p>
<p><em>Note: I don't even know how to format the Jupyter Notebook results in the Stackoverflow edit window, so I copy and paste the image, I beg your pardon.</em></p>
<p>The <strong>DATA</strong> column shows the observed data; the <strong>POINTS</strong> column, initialized to 0, is used to collect the output of a "rolling" function applied to DATA column, as explained in the following.</p>
<p>Set a window = 4</p>
<pre><code>nwin = 4
</code></pre>
<p>Just for the example, <strong>the "rolling" function calculate the max</strong>.</p>
<p>Now let me use a drawing to explain what I need.</p>
<p><a href="http://i.stack.imgur.com/GflSG.png" rel="nofollow"><img src="http://i.stack.imgur.com/GflSG.png" alt="Algo flow"></a></p>
<p>For every iteration, the rolling function calculate the maximum of the data in the window; then the POINT at the same index of the max DATA is incremented by 1.</p>
<p>The final result is:</p>
<p><a href="http://i.stack.imgur.com/7P1Z5.png" rel="nofollow"><img src="http://i.stack.imgur.com/7P1Z5.png" alt="DataFrame end"></a></p>
<p>Can you help me with the python code?</p>
<p>I really appreciate your help.<br>
Thank you in advance for your time,<br>
Gilberto</p>
<p><em>P.S. Can you also suggest how to copy and paste Jupyter Notebook formatted cell to Stackoverflow edit window? Thank you.</em></p>
| 3 |
2016-09-23T09:30:40Z
| 39,657,514 |
<p>IIUC the explanation by @IanS (thanks again!), you can do</p>
<pre><code>In [75]: np.array([df.DATA.rolling(4).max().shift(-i) == df.DATA for i in range(4)]).T.sum(axis=1)
Out[75]: array([0, 0, 3, 0, 0, 0, 3, 0, 0])
</code></pre>
<p>To update the column:</p>
<pre><code>In [78]: df = pd.DataFrame({'DATA':s, 'POINTS':0})
In [79]: df.POINTS += np.array([df.DATA.rolling(4).max().shift(-i) == df.DATA for i in range(4)]).T.sum(axis=1)
In [80]: df
Out[80]:
DATA POINTS
0 1 0
1 2 0
2 3 3
3 2 0
4 1 0
5 2 0
6 3 3
7 2 0
8 1 0
</code></pre>
| 2 |
2016-09-23T09:38:53Z
|
[
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
How to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column
| 39,657,330 |
<p><br>A very simple example just for understanding.</p>
<p><strong>The goal is to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column.</strong></p>
<p>I have the following DataFrame:</p>
<pre><code>import numpy as np
import pandas as pd
s = pd.Series([1,2,3,2,1,2,3,2,1])
df = pd.DataFrame({'DATA':s, 'POINTS':0})
df
</code></pre>
<p><a href="http://i.stack.imgur.com/8dZmD.png" rel="nofollow"><img src="http://i.stack.imgur.com/8dZmD.png" alt="DataFrame start"></a></p>
<p><em>Note: I don't even know how to format the Jupyter Notebook results in the Stackoverflow edit window, so I copy and paste the image, I beg your pardon.</em></p>
<p>The <strong>DATA</strong> column shows the observed data; the <strong>POINTS</strong> column, initialized to 0, is used to collect the output of a "rolling" function applied to DATA column, as explained in the following.</p>
<p>Set a window = 4</p>
<pre><code>nwin = 4
</code></pre>
<p>Just for the example, <strong>the "rolling" function calculate the max</strong>.</p>
<p>Now let me use a drawing to explain what I need.</p>
<p><a href="http://i.stack.imgur.com/GflSG.png" rel="nofollow"><img src="http://i.stack.imgur.com/GflSG.png" alt="Algo flow"></a></p>
<p>For every iteration, the rolling function calculate the maximum of the data in the window; then the POINT at the same index of the max DATA is incremented by 1.</p>
<p>The final result is:</p>
<p><a href="http://i.stack.imgur.com/7P1Z5.png" rel="nofollow"><img src="http://i.stack.imgur.com/7P1Z5.png" alt="DataFrame end"></a></p>
<p>Can you help me with the python code?</p>
<p>I really appreciate your help.<br>
Thank you in advance for your time,<br>
Gilberto</p>
<p><em>P.S. Can you also suggest how to copy and paste Jupyter Notebook formatted cell to Stackoverflow edit window? Thank you.</em></p>
| 3 |
2016-09-23T09:30:40Z
| 39,659,948 |
<pre><code>import pandas as pd
s = pd.Series([1,2,3,2,1,2,3,2,1])
df = pd.DataFrame({'DATA':s, 'POINTS':0})
df.POINTS=df.DATA.rolling(4).max().shift(-1)
df.POINTS=(df.POINTS*(df.POINTS==df.DATA)).fillna(0)
</code></pre>
| 1 |
2016-09-23T11:43:08Z
|
[
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
openpyxl: Worksheet does not exist (related to character sets)
| 39,657,361 |
<p>I load a worksheet with openpyxl and encounter the issue <code>Worksheet does not exist</code> raised by <code>get_sheet_by_name</code>.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from openpyxl import load_workbook
file_workbook = 'JCR2015å½±åå åï¼æææåä»é«å°ä½æåºï¼+ä¸ç§é¢ååº.xlsx'
sheet_name = '2015å¹´JCR'
wb = load_workbook(file_workbook, read_only=True)
print(wb.get_sheet_names()) # [u'2015\u5e74JCR']
ws = wb.get_sheet_by_name(sheet_name) # raise the error: KeyError: 'Worksheet 2015\xe5\xb9\xb4JCR does not exist.'
</code></pre>
<p>What are the differences among <code>'2015å¹´JCR'</code>, <code>u'2015\u5e74JCR'</code> and <code>'2015\xe5\xb9\xb4JCR'</code>? How do I fix it?</p>
| 0 |
2016-09-23T09:32:04Z
| 39,658,481 |
<p>It seems like you need to tell python you're using unicode:
Add this declaration at the top of your file:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>And every string which holds Characters should be prefixed with u:</p>
<pre><code>file_workbook = u'JCR2015å½±åå åï¼æææåä»é«å°ä½æåºï¼+ä¸ç§é¢ååº.xlsx'
sheet_name = u'2015å¹´JCR'
</code></pre>
| 1 |
2016-09-23T10:26:20Z
|
[
"python",
"excel",
"character-encoding",
"openpyxl"
] |
How to draw properly networkx graphs
| 39,657,395 |
<p>I got this code which allows me to draw a graph like the posted below</p>
<pre><code>import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout
G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)
nx.draw(G, pos=graphviz_layout(G), node_size=1600, cmap=plt.cm.Blues,
node_color=range(len(G)),
prog='dot')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/D0XDx.png" rel="nofollow"><img src="http://i.stack.imgur.com/D0XDx.png" alt="enter image description here"></a></p>
<p>Question is, how could i draw the graph with nodes which:</p>
<ul>
<li>Use white background color </li>
<li>Have labels inside</li>
<li>Have directed arrows</li>
<li>Optionally the arrows show a certain weight</li>
<li>Are arranged nicely either automatically or manually</li>
</ul>
<p>Something similar to the below image</p>
<p><a href="http://i.stack.imgur.com/Vhuai.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vhuai.png" alt="enter image description here"></a></p>
<p>As you can see in that image, nodes are aligned really nicely</p>
| 0 |
2016-09-23T09:33:19Z
| 39,662,097 |
<p>Since you have Graphviz you can use that to make nice drawings and control the elements of the drawing. The 'dot' layout engine does a great job of positioning digraphs like the one in your example.
For example </p>
<pre><code>import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout, to_agraph
import pygraphviz as pgv
G = nx.DiGraph()
G.add_node("A",rank=0)
G.add_nodes_from(['B','C','D'],style='filled',fillcolor='red')
G.add_nodes_from(['D','F','G'])
G.add_nodes_from(['H'],label='target')
G.add_edge('A','B',arrowsize=2.0)
G.add_edge('A','C',penwidth=2.0)
G.add_edge('A','D')
G.add_edges_from([('B','E'),('B','F')],color='blue')
G.add_edges_from([('C','E'),('C','G')])
G.add_edges_from([('D','F'),('D','G')])
G.add_edges_from([('E','H'),('F','H'),('G','H')])
# set defaults
G.graph['graph']={'rankdir':'TD'}
G.graph['node']={'shape':'circle'}
G.graph['edges']={'arrowsize':'4.0'}
A = to_agraph(G)
print(A)
A.layout('dot')
A.draw('abcd.png')
</code></pre>
<p>Produces the output</p>
<pre><code>strict digraph {
graph [rankdir=TD];
node [label="\N",
shape=circle
];
A [rank=0];
C [fillcolor=red,
style=filled];
A -> C [penwidth=2.0];
B [fillcolor=red,
style=filled];
A -> B [arrowsize=2.0];
D [fillcolor=red,
style=filled];
A -> D;
C -> E;
C -> G;
B -> E [color=blue];
B -> F [color=blue];
D -> G;
D -> F;
H [label=target];
E -> H;
G -> H;
F -> H;
}
</code></pre>
<p>which is rendered by dot as</p>
<p><a href="http://i.stack.imgur.com/W2ZAs.png" rel="nofollow"><img src="http://i.stack.imgur.com/W2ZAs.png" alt="enter image description here"></a></p>
<p>You can read about the adjustable drawing parameters at <a href="http://www.graphviz.org/doc/info/attrs.html" rel="nofollow">http://www.graphviz.org/doc/info/attrs.html</a></p>
| 1 |
2016-09-23T13:31:12Z
|
[
"python",
"graph",
"networkx"
] |
Cythonize dynamic pyx function
| 39,657,830 |
<p>I've created a <code>pyx</code> file dynamically, but struggle to cythonize and use the function encoded in it.</p>
<p>I tried </p>
<pre><code>import pyximport
pyximport.install()
import imp
module = imp.load_source('module.name', pyxfilename)
</code></pre>
<p>but this doesn't seem to work. Any idea how can I do this?</p>
| 0 |
2016-09-23T09:52:57Z
| 39,659,093 |
<p>You could use the function <code>pyximport.load_module</code> instead of <code>imp.load_source</code> (<a href="https://github.com/cython/cython/blob/151d653d3c7ab07e9d961c9601b2ff45202e6ce2/pyximport/pyximport.py#L207" rel="nofollow">https://github.com/cython/cython/blob/151d653d3c7ab07e9d961c9601b2ff45202e6ce2/pyximport/pyximport.py#L207</a>). </p>
<p>That appears to build if required then call <code>imp.load_dynamic</code>. You call it in the same way as <code>load_source</code> e.g.</p>
<pre><code>module = pyximport.load_module('module.name', pyxfilename)
</code></pre>
| 2 |
2016-09-23T10:57:58Z
|
[
"python",
"cython"
] |
Django project to domain, vps
| 39,657,888 |
<p>I have VPS-server (CentOS 6.8)</p>
<p>I installed Python 3.5.2 and Django 1.10.1 on virtual enviroment</p>
<p>I connected my domain to VPS-server</p>
<p>Now:</p>
<pre><code>django-project:
(venv) /home/django_user/djtest/venv/django_project/django_project
domain:
/var/www/www-root/data/www/mydomain.com
</code></pre>
<p>I tried set <code>BASE_DIR</code> in settings.py to <code>'/var/www/www-root/data/www/mydomain.com'</code> but not working</p>
<p>How I can to connect django-project to domain?</p>
<p>Project is still empty, just created</p>
| -1 |
2016-09-23T09:55:52Z
| 39,658,093 |
<p>Django project can't be served like this, you need some web-server application like gunicorn or apache too. </p>
<p>Just like you use <code>./manage.py runserver</code> you need some application to execute your django project corresponsing to command theses application are <a href="https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwi5l_menqXPAhVD1oMKHT66BHAQFggdMAA&url=http%3A%2F%2Fgunicorn.org%2F&usg=AFQjCNH4886vZhhVrpKRkAak1Ja0k68d3g&sig2=CX1x8Pp8NmDM8DFIXNlMNA" rel="nofollow">Gunicorn</a>, <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">ApacheWSGI server</a> and <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/" rel="nofollow">others</a>.</p>
<p>There will be a file <code>wsgi.py</code> that would have created when you created the project it's <strong>web server gateway interface</strong> it will interact with the above mentioned web-servers and server your django based website.</p>
| 1 |
2016-09-23T10:06:29Z
|
[
"python",
"django",
"dns",
"vps"
] |
How to show dialogs at a certain position inside a QScintilla widget?
| 39,657,924 |
<p>I got this simple piece of mcve code:</p>
<pre><code>import sys
import re
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.Qsci import QsciScintilla
from PyQt5 import Qsci
class SimpleEditor(QsciScintilla):
def __init__(self, language=None, parent=None):
super().__init__(parent)
font = QtGui.QFont()
font.setFamily('Courier')
font.setFixedPitch(True)
font.setPointSize(10)
self.setFont(font)
self.setMarginsFont(font)
fontmetrics = QtGui.QFontMetrics(font)
self.setMarginsFont(font)
self.setMarginWidth(0, fontmetrics.width("00000") + 6)
self.setMarginLineNumbers(0, True)
self.setMarginsBackgroundColor(QtGui.QColor("#cccccc"))
self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
self.setCaretLineVisible(True)
self.setCaretLineBackgroundColor(QtGui.QColor("#E8E8FF"))
if language:
self.lexer = getattr(Qsci, 'QsciLexer' + language)()
self.setLexer(self.lexer)
self.SendScintilla(QsciScintilla.SCI_FOLDALL, True)
self.setAutoCompletionThreshold(1)
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
# Signals/Slots
self.cursorPositionChanged.connect(self.on_cursor_position_changed)
self.copyAvailable.connect(self.on_copy_available)
self.indicatorClicked.connect(self.on_indicator_clicked)
self.indicatorReleased.connect(self.on_indicator_released)
self.linesChanged.connect(self.on_lines_changed)
self.marginClicked.connect(self.on_margin_clicked)
self.modificationAttempted.connect(self.on_modification_attempted)
self.modificationChanged.connect(self.on_modification_changed)
self.selectionChanged.connect(self.on_selection_changed)
self.textChanged.connect(self.on_text_changed)
self.userListActivated.connect(self.on_user_list_activated)
def on_cursor_position_changed(self, line, index):
print("on_cursor_position_changed")
def on_copy_available(self, yes):
print('-' * 80)
print("on_copy_available")
def on_indicator_clicked(self, line, index, state):
print("on_indicator_clicked")
def on_indicator_released(self, line, index, state):
print("on_indicator_released")
def on_lines_changed(self):
print("on_lines_changed")
def on_margin_clicked(self, margin, line, state):
print("on_margin_clicked")
def on_modification_attempted(self):
print("on_modification_attempted")
def on_modification_changed(self):
print("on_modification_changed")
def on_selection_changed(self):
print("on_selection_changed")
def on_text_changed(self):
print("on_text_changed")
def on_user_list_activated(self, id, text):
print("on_user_list_activated")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = QtWidgets.QWidget()
hlayout = QtWidgets.QHBoxLayout()
ed = SimpleEditor("JavaScript")
hlayout.addWidget(ed)
ed.setText("""#ifdef GL_ES
precision mediump float;
#endif
#extension GL_OES_standard_derivatives : enable
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
void main( void ) {
vec2 st = ( gl_FragCoord.xy / resolution.xy );
vec2 lefbot = step(vec2(0.1), st);
float pct = lefbot.x*lefbot.y;
vec2 rigtop = step(vec2(0.1), 1.-st);
pct *= rigtop.x*rigtop.y;
vec3 color = vec3(pct);
gl_FragColor = vec4( color, 1.0 );""")
ex.setLayout(hlayout)
ex.show()
ex.resize(800, 600)
sys.exit(app.exec_())
</code></pre>
<p>I'm trying to code a similar solution to the one provided on this <a href="https://www.khanacademy.org/computer-programming/tree-generator/822944839" rel="nofollow">site</a>. As you can see, on that site the user can tweak numeric values only by clicking over, when they do so a little dialog will appear and the user will be able to change values in realtime. </p>
<p>Now, the first thing I need to figure out is which are the signals I need to consider when the user click on the QScintilla widget (I'm using these <a href="http://pyqt.sourceforge.net/Docs/QScintilla2/classQsciScintilla.html" rel="nofollow">docs</a>). Which is/are the one/s I should really care about it.</p>
<p>In any case, assuming I use the right signal to popup my dialog containing some sliders, how could i figure out the right position where my dialog should appear?</p>
| 2 |
2016-09-23T09:57:43Z
| 39,665,988 |
<p>The <code>cursorPositionChanged</code> signal can be used to detect whenever the mouse or keyboard moves the caret to a position within a number. A regexp can then be used to find where the number starts and ends on the current line. Once you have that, you can use some low-level functions to calculate the global position of the number.</p>
<p>The method below uses that approach to show a tooltip below the relevant text:</p>
<pre><code>def on_cursor_position_changed(self, line, index):
text = self.text(line)
for match in re.finditer('(?:^|(?<=\W))\d+(?:\.\d+)?(?=$|\W)', text):
start, end = match.span()
if start <= index <= end:
pos = self.positionFromLineIndex(line, start)
x = self.SendScintilla(
QsciScintilla.SCI_POINTXFROMPOSITION, 0, pos)
y = self.SendScintilla(
QsciScintilla.SCI_POINTYFROMPOSITION, 0, pos)
point = self.mapToGlobal(QtCore.QPoint(x, y))
num = float(match.group())
message = 'number: %s' % num
break
else:
point = QtCore.QPoint(0, 0)
message = ''
QtWidgets.QToolTip.showText(point, message)
</code></pre>
| 2 |
2016-09-23T16:59:03Z
|
[
"python",
"pyqt",
"qscintilla"
] |
Fetching model instance from a multiple direct relationship
| 39,658,142 |
<p>Can anyone help me fetch data from this model structure? because i have a hard time doin this for hours now.</p>
<p><strong>First I would like to get all distinct <code>SubSpecialization</code> from all <code>Doctor</code> which has a given <code>Specialization.title</code></strong></p>
<p><strong>Secondly I would like to get all <code>Doctor</code> which has a specific <code>Specialization.title</code> and has no <code>SubSpecialization</code>.</strong></p>
<p>Here is the <code>Doctor</code> model</p>
<pre><code>class Doctor(models.Model):
name = models.CharField(max_length=50)
room_no = models.IntegerField()
floor_no = models.IntegerField()
contact_no = models.CharField(max_length=50, blank=True, null=True)
notes = models.CharField(max_length=70, blank=True, null=True)
</code></pre>
<p>This is the model <code>Doctor</code> relationship is connected to <code>Specialization</code>and <code>SubSpecialization</code>.</p>
<pre><code>class DoctorSpecialization(models.Model):
doc = models.ForeignKey(Doctor, models.DO_NOTHING)
spec = models.ForeignKey('Specialization', models.DO_NOTHING)
class DoctorSubSpecialization(models.Model):
doc = models.ForeignKey(Doctor, models.DO_NOTHING)
sub_spec = models.ForeignKey('SubSpecialization', models.DO_NOTHING)
</code></pre>
<p>This is where i would make a criteria.</p>
<pre><code>class Specialization(models.Model):
title = models.CharField(unique=True, max_length=45)
point = models.IntegerField()
class SubSpecialization(models.Model):
title = models.CharField(max_length=100)
</code></pre>
<p>There is no direct relationship between the <code>Specialization</code> and <code>SubSpecialization</code> please help.</p>
| 0 |
2016-09-23T10:08:59Z
| 39,658,406 |
<p>Firstly, your specialization and subspecialization are both many-to-many relationships with Doctor. You should declare that explicitly, and drop those intervening models unless you need to store other information on them.</p>
<pre><code>class Doctor(models.Model):
...
specializations = models.ManyToManyField('Specialization')
subspecializations = models.ManyToManyField('SubSpecialization')
</code></pre>
<p>Now you can query for all the subspecializations for doctors who have a specific specialization:</p>
<pre><code>SubSpecialization.objects.filter(doctor__specialization__title='My Specialization')
</code></pre>
<p>Your second query doesn't make sense given the fact there is no relationship between specialization and subspecialization, you'll need to clarify what you mean by "no subspecialization in a specific specialization".</p>
<p><strong>Edit</strong></p>
<p>To find doctors who have a specific Specialization and then no subspecializations at all:</p>
<pre><code>Doctor.objects.filter(specialization__name="My Specialization",
subspecialization=None)
</code></pre>
| 1 |
2016-09-23T10:22:26Z
|
[
"python",
"django",
"django-models"
] |
'NoneType' object has no attribute 'append'
| 39,658,150 |
<p>I have two lists that I'm merging into a dictionary</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>
<p>The expected output will be something like</p>
<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'groupchat_2']
}
</code></pre>
<p>My code to create the dictionary is below.</p>
<pre><code>out = {}
out = dict.fromkeys(keys)
for tests in tests_available:
if tests.split('_')[0] in keys:
key = tests.split('_')[0]
out[key].append(tests)
</code></pre>
<p>However, it is throwing the error 'NoneType' object has no attribute 'append' when it is trying to append the values to the key. Can anyone help me identify what is wrong in my code?</p>
| -1 |
2016-09-23T10:09:25Z
| 39,658,215 |
<p>Your values are set to <em>None</em> in <em>fromkeys</em> unless you explicitly set a value:</p>
<p><strong>fromkeys(seq[, value])</strong></p>
<p><em>Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.</em></p>
<p>In your case you need to create lists as values for each key:</p>
<pre><code>d = {k:[] for k in keys}
</code></pre>
<p>You can also do your if check using the dict:</p>
<pre><code>d = {k:[] for k in keys}
for test in tests_available:
k = tests.split('_', 1)[0]
if k in d:
d[k].append(test)
</code></pre>
<p>You can pass a value to use to <em>fromkeys</em> but it has to be <em>immutable</em> or you will be sharing the same object among all keys.</p>
| 3 |
2016-09-23T10:12:20Z
|
[
"python"
] |
'NoneType' object has no attribute 'append'
| 39,658,150 |
<p>I have two lists that I'm merging into a dictionary</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>
<p>The expected output will be something like</p>
<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'groupchat_2']
}
</code></pre>
<p>My code to create the dictionary is below.</p>
<pre><code>out = {}
out = dict.fromkeys(keys)
for tests in tests_available:
if tests.split('_')[0] in keys:
key = tests.split('_')[0]
out[key].append(tests)
</code></pre>
<p>However, it is throwing the error 'NoneType' object has no attribute 'append' when it is trying to append the values to the key. Can anyone help me identify what is wrong in my code?</p>
| -1 |
2016-09-23T10:09:25Z
| 39,658,269 |
<p>For a small number of keys/tests a dictionary comprehension would work as well:</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
out = {k: [v for v in tests_available if v.startswith(k)] for k in keys}
</code></pre>
<p>Demo:</p>
<pre><code>>>> out
{'groupchat': ['groupchat_1', 'groupchat_2'], 'p2p': ['p2p_1', 'p2p_2', 'p2p_3']}
</code></pre>
| 1 |
2016-09-23T10:14:41Z
|
[
"python"
] |
'NoneType' object has no attribute 'append'
| 39,658,150 |
<p>I have two lists that I'm merging into a dictionary</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>
<p>The expected output will be something like</p>
<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'groupchat_2']
}
</code></pre>
<p>My code to create the dictionary is below.</p>
<pre><code>out = {}
out = dict.fromkeys(keys)
for tests in tests_available:
if tests.split('_')[0] in keys:
key = tests.split('_')[0]
out[key].append(tests)
</code></pre>
<p>However, it is throwing the error 'NoneType' object has no attribute 'append' when it is trying to append the values to the key. Can anyone help me identify what is wrong in my code?</p>
| -1 |
2016-09-23T10:09:25Z
| 39,658,370 |
<p>If you use a defaultdict then the append call will work as the value type defaults to a list:</p>
<pre><code>In [269]:
from collections import defaultdict
keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
d = defaultdict(list)
for test in tests_available:
k = test.split('_')[0]
if k in keys:
d[k].append(test)
d.items()
Out[269]:
dict_items([('p2p', ['p2p_1', 'p2p_2', 'p2p_3']), ('groupchat', ['groupchat_1', 'groupchat_2'])])
</code></pre>
<p>See the docs: <a href="https://docs.python.org/2/library/collections.html#defaultdict-examples" rel="nofollow">https://docs.python.org/2/library/collections.html#defaultdict-examples</a></p>
| 2 |
2016-09-23T10:20:25Z
|
[
"python"
] |
Email confirm error rest-auth
| 39,658,373 |
<p>I use a standard form for the confirmation email:
from allauth.account.views import confirm_email as allauthemailconfirmation</p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^accounts/', include('allauth.urls')),
url(r'^rest-auth/registration/account-confirm-email/(?P<key>\w+)/$', allauthemailconfirmation, name="account_confirm_email"),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
]
</code></pre>
<p>Settings:</p>
<pre><code>LOGIN_REDIRECT_URL='/'
ACCOUNT_EMAIL_VERIFICATION='mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET=False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
</code></pre>
<p>I correctly get an e-mail, but when you try to link:</p>
<pre><code>ImproperlyConfigured at /rest-auth/registration/account-confirm-email/MTU:1bn1OD:dQ_mCYi6Zpr8h2aKS9J9BvNdDjA/
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
</code></pre>
| 0 |
2016-09-23T10:20:36Z
| 39,663,046 |
<p>I think I found your problem.</p>
<p>This url:</p>
<pre><code>/rest-auth/registration/account-confirm-email/MTU:1bn1OD:dQ_mCYi6Zpr8h2aKS9J9BvNdDjA/
</code></pre>
<p>is not matched by this pattern:</p>
<pre><code>url(r'^rest-auth/registration/account-confirm-email/(?P<key>\w+)/$', allauthemailconfirmation, name="account_confirm_email"),
</code></pre>
<p>but by the following:</p>
<pre><code>url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
</code></pre>
<p>and if you look at the source code of <code>rest_auth.registration.urls</code>, you will see this code:</p>
<pre><code># This url is used by django-allauth and empty TemplateView is
# defined just to allow reverse() call inside app, for example when email
# with verification link is being sent, then it's required to render email
# content.
# account_confirm_email - You should override this view to handle it in
# your API client somehow and then, send post to /verify-email/ endpoint
# with proper key.
# If you don't want to use API on that step, then just use ConfirmEmailView
# view from:
# django-allauth https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py#L190
url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'),
</code></pre>
<p>So, you should overwrite this view, or you will get the error you've got, as explained here: <a href="https://github.com/Tivix/django-rest-auth/issues/20" rel="nofollow">https://github.com/Tivix/django-rest-auth/issues/20</a></p>
<p>You have indeed tried to overwrite the view, but your matching pattern is wrong, the : char causes it to fail, so let's try something like </p>
<pre><code>url(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', allauthemailconfirmation, name="account_confirm_email"),
</code></pre>
<p>The relevant part being: <strong>(?P[-:\w]+)/$</strong></p>
| 0 |
2016-09-23T14:17:09Z
|
[
"python",
"django",
"django-rest-framework",
"django-allauth",
"django-rest-auth"
] |
Python - cannot import name viewkeys
| 39,658,404 |
<p>I'm importing a module which inturn imports <code>six</code>, but I'm getting this weird error. </p>
<pre><code>Traceback (most recent call last):
File "/Users/praful/Desktop/got/modules/categories/tests.py", line 13, in <module>
import microdata
File "build/bdist.macosx-10.10-intel/egg/microdata.py", line 4, in <module>
File "/Library/Python/2.7/site-packages/html5lib/__init__.py", line 16, in <module>
from .html5parser import HTMLParser, parse, parseFragment
File "/Library/Python/2.7/site-packages/html5lib/html5parser.py", line 2, in <module>
from six import with_metaclass, viewkeys, PY3
ImportError: cannot import name viewkeys
</code></pre>
<p>I'd a look at <a href="https://github.com/JioCloud/python-six/blob/master/six.py" rel="nofollow">six.py</a>, it has <code>viewkeys</code> in it. </p>
<p>Latest <code>six==1.10.0</code> is installed.</p>
| 1 |
2016-09-23T10:22:11Z
| 39,675,202 |
<p>I had the same problem:</p>
<pre><code>> python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import six
>>> import xhtml2pdf.pisa
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/xhtml2pdf/pisa.py", line 3, in <module>
from xhtml2pdf.document import pisaDocument
File "/Library/Python/2.7/site-packages/xhtml2pdf/document.py", line 2, in <module>
from xhtml2pdf.context import pisaContext
File "/Library/Python/2.7/site-packages/xhtml2pdf/context.py", line 23, in <module>
import xhtml2pdf.parser
File "/Library/Python/2.7/site-packages/xhtml2pdf/parser.py", line 17, in <module>
from html5lib import treebuilders, inputstream
File "/Library/Python/2.7/site-packages/html5lib/__init__.py", line 16, in <module>
from .html5parser import HTMLParser, parse, parseFragment
File "/Library/Python/2.7/site-packages/html5lib/html5parser.py", line 2, in <module>
from six import with_metaclass, viewkeys, PY3
ImportError: cannot import name viewkeys
>>> exit()
</code></pre>
<p>I ran the following steps: <br></p>
<ul>
<li><code>sudo -H pip uninstall six</code></li>
<li><code>sudo -H pip install six==1.9.0</code></li>
<li>Test: Error persists</li>
<li><code>sudo -H pip uninstall six==1.9.0</code></li>
<li><code>sudo -H pip install six==1.10.0</code></li>
</ul>
<p>Test:</p>
<pre><code>> python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from six import viewkeys
>>> import xhtml.pisa
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named xhtml.pisa
>>> import xhtml2pdf.pisa
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "xhtml2pdf/pisa.py", line 3, in <module>
from xhtml2pdf.document import pisaDocument
File "xhtml2pdf/document.py", line 2, in <module>
from xhtml2pdf.context import pisaContext
File "xhtml2pdf/context.py", line 23, in <module>
import xhtml2pdf.parser
File "xhtml2pdf/parser.py", line 17, in <module>
from html5lib import treebuilders, inputstream
ImportError: cannot import name inputstream
>>> exit()
</code></pre>
<p>So the viewkeys-error didn't come back.</p>
<p>The problem importing inputstream seems to be a bug in xhtml2pdf:<br>
<a href="https://github.com/xhtml2pdf/xhtml2pdf/issues/318" rel="nofollow">https://github.com/xhtml2pdf/xhtml2pdf/issues/318</a></p>
<p>For me this fixed the problem:<br>
<code>sudo -H pip install html5lib==1.0b8</code></p>
<p>So afterall, I don't really know if the last command would have fixed the problem overall, but this way it works for me now:</p>
<pre><code>> python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import xhtml2pdf.pisa
>>>
</code></pre>
| 1 |
2016-09-24T10:14:41Z
|
[
"python",
"python-six"
] |
postgresql sqlalchemy core define constraint to a combination of the columns at a time
| 39,658,434 |
<p>I have a model defined as:</p>
<pre><code>groups_categories = Table("groups_categories", metadata,
Column("id", Integer, primary_key=True),
Column("group", Integer, ForeignKey("groups.id")),
Column("dept", Integer, ForeignKey("departments.id")),
Column("category", Integer,ForeignKey("categories.id")),
Column("allow_view", Boolean, default=True),
Column("allow_edit", Boolean, default=True),
Column("allow_download", Boolean, default=True),
UniqueConstraint('dept','category',
name='dept_category'),
UniqueConstraint('group','category',
name='group_category'))
</code></pre>
<p>I would like to define a constraint such that for a given category, I can have either dept or group value but not both.
How can this check be implemented at this model level definition itself? I am using <strong>sqlalchemy core</strong> only</p>
| 0 |
2016-09-23T10:23:40Z
| 39,658,985 |
<p>If I understood you correctly, you're looking for a <a href="http://docs.sqlalchemy.org/en/latest/core/constraints.html#check-constraint" rel="nofollow"><code>CheckConstraint</code></a> such that both <em>group</em> and <em>dept</em> cannot be non-null values at the same time:</p>
<pre><code>CHECK (NOT ("group" IS NOT NULL AND dept IS NOT NULL))
</code></pre>
<p>By applying <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow">De Morgan's law</a> this can be simplified a bit:</p>
<pre><code>-- either group or dept must be null
CHECK ("group" IS NULL OR dept IS NULL)
</code></pre>
<p>And your <code>Table</code> definition becomes:</p>
<pre><code>from sqlalchemy import CheckConstraint
groups_categories = Table(
"groups_categories", metadata,
Column("id", Integer, primary_key=True),
Column("group", Integer, ForeignKey("groups.id")),
Column("dept", Integer, ForeignKey("departments.id")),
Column("category", Integer, ForeignKey("categories.id")),
Column("allow_view", Boolean, default=True),
Column("allow_edit", Boolean, default=True),
Column("allow_download", Boolean, default=True),
UniqueConstraint('dept', 'category',
name='dept_category'),
UniqueConstraint('group', 'category',
name='group_category'),
# The CHECK constraint
CheckConstraint('"group" IS NULL OR dept IS NULL',
name='check_group_dept')
)
</code></pre>
| 1 |
2016-09-23T10:52:04Z
|
[
"python",
"postgresql",
"sqlalchemy"
] |
Splice dictonary to create list of tuples in Python
| 39,658,463 |
<p>So I have these two dictonaries, where the key is a year (an integer), and the value a float. I want to combine these two, and as a result create a list of tuples, with the year, value1, value2. So like this:</p>
<p>Dictonary 1</p>
<pre><code> {2011: 1.0,
2012: 2.0,
2013: 3.0}
</code></pre>
<p>Dictonary 2</p>
<pre><code> {2011: 4.0,
2012: 5.0,
2013: 6.0}
</code></pre>
<p>Prefered result:</p>
<pre><code> [(2011, 1.0, 4.0),
(2012, 2.0, 5.0),
(2013, 3.0, 6.0)]
</code></pre>
<p>Is there an easy way of doing this? Thank for your help!</p>
| 1 |
2016-09-23T10:24:57Z
| 39,658,556 |
<p>If both dictionaries have the same keys:</p>
<pre><code>[(k, dict1[k], dict2[k]) for k in dict1.keys()]
</code></pre>
<p>Example:</p>
<pre><code>In[33]: dict1 = {2011: 1.0,
2012: 2.0,
2013: 3.0}
In[34]: dict2 = {2011: 4.0,
2012: 5.0,
2013: 6.0}
In[35]: [(k, dict1[k], dict2[k]) for k in dict1.keys()]
Out[35]: [(2011, 1.0, 4.0), (2012, 2.0, 5.0), (2013, 3.0, 6.0)]
</code></pre>
| 2 |
2016-09-23T10:29:22Z
|
[
"python",
"python-2.7"
] |
Splice dictonary to create list of tuples in Python
| 39,658,463 |
<p>So I have these two dictonaries, where the key is a year (an integer), and the value a float. I want to combine these two, and as a result create a list of tuples, with the year, value1, value2. So like this:</p>
<p>Dictonary 1</p>
<pre><code> {2011: 1.0,
2012: 2.0,
2013: 3.0}
</code></pre>
<p>Dictonary 2</p>
<pre><code> {2011: 4.0,
2012: 5.0,
2013: 6.0}
</code></pre>
<p>Prefered result:</p>
<pre><code> [(2011, 1.0, 4.0),
(2012, 2.0, 5.0),
(2013, 3.0, 6.0)]
</code></pre>
<p>Is there an easy way of doing this? Thank for your help!</p>
| 1 |
2016-09-23T10:24:57Z
| 39,658,582 |
<p>Here's few possible solutions:</p>
<pre><code>import timeit
import random
random.seed(1)
def f1(d1, d2):
return [(k, d1[k], d2[k]) for k in list(set(d1.keys() + d1.keys()))]
def f2(d1, d2):
return [(k, d1[k], d2[k]) for k in d1.viewkeys() & d2]
def f3(d1, d2):
return [(k, d1[k], d2[k]) for k in set().union(d1, d2)]
if __name__ == "__main__":
d1_small = {2011: 1.0,
2012: 2.0,
2013: 3.0}
d2_small = {2011: 4.0,
2012: 5.0,
2013: 6.0}
K, I, N = 1000, 100000, 100
d1_large = {i: random.randint(0, K) for i in range(I)}
d2_large = {i: random.randint(0, K) for i in range(I)}
# Small dataset
print timeit.timeit('f1(d1_small,d2_small)', setup='from __main__ import f1, d1_small,d2_small', number=N)
print timeit.timeit('f2(d1_small,d2_small)', setup='from __main__ import f2, d1_small,d2_small', number=N)
print timeit.timeit('f3(d1_small,d2_small)', setup='from __main__ import f3, d1_small,d2_small', number=N)
# Big dataset
print timeit.timeit('f1(d1_large,d2_large)', setup='from __main__ import f1, d1_large,d2_large', number=N)
print timeit.timeit('f2(d1_large,d2_large)', setup='from __main__ import f2, d1_large,d2_large', number=N)
print timeit.timeit('f3(d1_large,d2_large)', setup='from __main__ import f3, d1_large,d2_large', number=N)
</code></pre>
<p>Results are:</p>
<pre><code>0.000144082492556
0.000120792445814
9.31601869678e-05
2.70233741278
2.74489385463
2.5809042933
</code></pre>
<p>Conclusion:</p>
<p>f3 is the winner here in terms of performance and f2 the one in terms of verbosity</p>
| 4 |
2016-09-23T10:30:37Z
|
[
"python",
"python-2.7"
] |
How to export and import data and auth information in Django?
| 39,658,476 |
<p>I'm working on a project which is already public so there are some <strong>Order</strong> objects and <strong>User</strong> objects in the database (couple of people has registrated and created some orders).</p>
<p>Now I'm changing some things in this project including <strong>Order</strong> model (added some fields like <code>created_time</code> etc.)</p>
<p>So my new database (sqlite3) has very similar schemas compared to old but it's not the same. </p>
<p>How can I add old users and <strong>Order</strong> objects into the new db? Is there some plugin or best practise? </p>
<p>There should be no problem with <strong>Users</strong> because their schema hasn't changed but I suppose that <code>app_users</code> table is not enough to copy.</p>
<pre><code>class Order(models.Model):
customer = models.ForeignKey(User, related_name='orders', blank=True, null=True)
first_name = models.CharField(max_length=40,verbose_name=u'Vorname')
last_name = models.CharField(max_length=40,verbose_name=u'Nachnahme')
dry_wood = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Trockenes Holz')
wet_wood = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Halb trockenes Holz')
briquette = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Brikettes')
stelinka = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Klein Holz')
street = models.CharField(max_length=200, verbose_name=u'StraÃe', null=True, blank=True)
number = models.CharField(max_length=40, null=True, blank=True, verbose_name=u'Hausnummer')
city = models.CharField(max_length=100, verbose_name=u'Stadt', null=True, blank=True)
psc = models.CharField(max_length=40, null=True, blank=True, verbose_name=u'PLZ')
telephone = models.CharField(max_length=50, null=True, blank=True, verbose_name=u"Telefon Nummer")
telephone2 = models.CharField(max_length=50, null=True, blank=True, verbose_name=u'Telefon 2')
email = models.EmailField(null=True, blank=True,verbose_name=u'Mail')
time = models.TextField(null=True, blank=True, verbose_name=u'Kommentar')
price = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True)
text_order = models.TextField(blank=True, null=True, verbose_name=u'Kommentar')
confirmed = models.BooleanField(default=False, verbose_name=u'Potvrdená zákaznÃkom')
done = models.BooleanField(default=False, verbose_name=u'Vybavená')
TYPE_CHOICES = (('wholesale', u'Veľkoodber'),
('retail', u'Maloodber'))
type = models.CharField(max_length=40, choices=TYPE_CHOICES, default='retail')
created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
LENGTH_OF_DRY_WOOD_CHOICES = (('1.0','1.0'),
('0.5', '0.5'),
('0.33', '0.33'),
('0.25', '0.25'))
LENGTH_OF_WET_WOOD_CHOICES = (('1.0','1.0'),
('0.5', '0.5'),
('0.33', '0.33'),
('0.25', '0.25'))
length_of_dry_wood = models.CharField(max_length=40, choices=LENGTH_OF_DRY_WOOD_CHOICES, default='0.5', null=True, blank=True,verbose_name=u'Länge des Holzes (Trockenes Holz)')
length_of_wet_wood = models.CharField(max_length=40, choices=LENGTH_OF_WET_WOOD_CHOICES, default='0.5', null=True, blank=True,verbose_name=u'Länge des Holzes')
backuped = models.BooleanField(default=False)
class Meta:
verbose_name = u'Objednávka'
verbose_name_plural = u'Objednávky'
def save(self, *args, **kwargs):
if self.type == 'retail':
self.price = Price.calculate_price(self.dry_wood, self.wet_wood, self.briquette, self.stelinka)['total']
else:
self.price = 0
super(Order, self).save(*args, **kwargs)
def __str__(self):
return u'Objednávka {} | {} {} | {} ⬠{} {}'.format(self.id, self.first_name, self.last_name, self.price, u'| >>>>>>> NEPOTVRDENà <<<<<<<' if not self.confirmed else '',
u'| >> VYBAVENÃ <<' if self.done else '')
def __unicode__(self):
return self.__str__()
</code></pre>
| 1 |
2016-09-23T10:25:54Z
| 39,658,889 |
<p>Fixtures can be used for this <a href="https://docs.djangoproject.com/en/dev/howto/initial-data/" rel="nofollow">https://docs.djangoproject.com/en/dev/howto/initial-data/</a> </p>
<p>To dump the data on local machine </p>
<pre><code>./manage.py dumpdata mytable > databasedump.json
</code></pre>
<p>and import it on the remote :</p>
<pre><code>./manage.py loaddata databasedump.json
</code></pre>
| 1 |
2016-09-23T10:47:22Z
|
[
"python",
"django",
"sqlite"
] |
Python/OpenCV: Using cv2.resize() I get an error
| 39,658,497 |
<p>I'm using python 2.7 and opencv. </p>
<p>I'm trying to use:</p>
<pre><code>cv2.resize(src, dst, Size(), 0.5, 0.5, interpolation=cv2.INTER_LINEAR);
</code></pre>
<p>taken from <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html#resize" rel="nofollow">here</a>. But when I run this code I get <code>NameError: global name 'Size' is not defined.</code></p>
<p>Can you help me please?</p>
| 0 |
2016-09-23T10:26:48Z
| 39,658,618 |
<p>You are probably looking at the C++ api of <code>resize</code> method.</p>
<p>The python API looks something like this:</p>
<pre><code>dst = cv2.resize(src, dsize)
</code></pre>
<p>where </p>
<pre><code>src - Original image
dsize - a tuple defining the final size of the image.
</code></pre>
<p>If you want to pass additional parameters then you may use the named parameters of the API as:</p>
<pre><code>dst = cv2.resize(src, dsize, fx = 0.5, fy=0.5, interpolation = cv2.INTER_LINEAR)
</code></pre>
<p>Since dsize is required param but if you still want the <code>resize</code> method to calculate the <code>dsize</code> for you then you may pass the param as <code>None</code>.</p>
<pre><code>dst = cv2.resize(src, None, fx = 0.5, fy=0.5)
</code></pre>
| 3 |
2016-09-23T10:32:33Z
|
[
"python",
"python-2.7",
"opencv"
] |
Python class variable getting altered by changing instance variable that should just take its value
| 39,658,532 |
<p>I'm stumbling over a weird effect when initializing a Python class. Not sure if I'm overlooking something obvious or not.</p>
<p>First things first, I'm aware that apparently lists passed to classes are passed by reference while integers are passed by value as shown in this example:</p>
<pre><code>class Test:
def __init__(self,x,y):
self.X = x
self.Y = y
self.X += 1
self.Y.append(1)
x = 0
y = []
Test(x,y)
Test(x,y)
Test(x,y)
print x, y
</code></pre>
<p>Yielding the result:</p>
<pre><code>0 [1, 1, 1]
</code></pre>
<p>So far so good. Now look at this example:</p>
<pre><code>class DataSheet:
MISSINGKEYS = {u'Item': ["Missing"]}
def __init__(self,stuff,dataSheet):
self.dataSheet = dataSheet
if self.dataSheet.has_key(u'Item'):
self.dataSheet[u'Item'].append(stuff[u'Item'])
else:
self.dataSheet[u'Item'] = self.MISSINGKEYS[u'Item']
</code></pre>
<p>Calling it like this</p>
<pre><code>stuff = {u'Item':['Test']}
ds = {}
DataSheet(stuff,ds)
print ds
DataSheet(stuff,ds)
print ds
DataSheet(stuff,ds)
print ds
</code></pre>
<p>yields:</p>
<pre><code>{u'Item': ['Missing']}
{u'Item': ['Missing', ['Test']]}
{u'Item': ['Missing', ['Test'], ['Test']]}
</code></pre>
<p>Now lets print <code>MISSINGKEYS</code> instead:</p>
<pre><code>stuff = {u'Item':['Test']}
ds = {}
DataSheet(stuff,ds)
print DataSheet.MISSINGKEYS
DataSheet(stuff,ds)
print DataSheet.MISSINGKEYS
DataSheet(stuff,ds)
print DataSheet.MISSINGKEYS
</code></pre>
<p>This yields:</p>
<pre><code>{u'Item': ['Missing']}
{u'Item': ['Missing', ['Test']]}
{u'Item': ['Missing', ['Test'], ['Test']]}
</code></pre>
<p>The exact same output. Why?</p>
<p><code>MISSINGKEYS</code> is a class variable but at no point is it deliberately altered.</p>
<p>In the first call the class goes into this line:</p>
<pre><code>self.dataSheet[u'Item'] = self.MISSINGKEYS[u'Item']
</code></pre>
<p>Which apparently starts it all. Obviously I only want <code>self.dataSheet[u'Item']</code> to take the value of <code>self.MISSINGKEYS[u'Item']</code>, not to become a reference to it or something like that.</p>
<p>In the following two calls the line</p>
<pre><code>self.dataSheet[u'Item'].append(stuff[u'Item'])
</code></pre>
<p>is called instead and the <code>append</code> works on <code>self.dataSheet[u'Item']</code> AND on <code>self.MISSINGKEYS[u'Item']</code> which it should not.</p>
<p>This leads to the assumption that after the first call both variables now reference the same object.</p>
<p>However although being equal they do not:</p>
<pre><code>ds == DataSheet.MISSINGKEYS
Out[170]: True
ds is DataSheet.MISSINGKEYS
Out[171]: False
</code></pre>
<p>Can someone explain to me what is going on here and how I can avoid it?</p>
<p>EDIT:
I tried this:</p>
<pre><code>ds[u'Item'] is DataSheet.MISSINGKEYS[u'Item']
Out[172]: True
</code></pre>
<p>So okay, this one entry in both dictionaries references the same object. How can I just assign the value instead?</p>
| 0 |
2016-09-23T10:28:29Z
| 39,658,650 |
<p>Here:</p>
<pre><code> else:
self.dataSheet[u'Item'] = self.MISSINGKEYS[u'Item']
</code></pre>
<p>You are setting <code>dataShee['Item']</code> with the list that is the value of <code>MISSINGKEYS['Item']</code>. <em>The same list.</em> Try</p>
<pre><code> else:
self.dataSheet[u'Item'] = list(self.MISSINGKEYS[u'Item'])
</code></pre>
<p>To make a copy.</p>
| 1 |
2016-09-23T10:34:27Z
|
[
"python",
"python-2.7",
"class",
"pass-by-reference"
] |
Python class variable getting altered by changing instance variable that should just take its value
| 39,658,532 |
<p>I'm stumbling over a weird effect when initializing a Python class. Not sure if I'm overlooking something obvious or not.</p>
<p>First things first, I'm aware that apparently lists passed to classes are passed by reference while integers are passed by value as shown in this example:</p>
<pre><code>class Test:
def __init__(self,x,y):
self.X = x
self.Y = y
self.X += 1
self.Y.append(1)
x = 0
y = []
Test(x,y)
Test(x,y)
Test(x,y)
print x, y
</code></pre>
<p>Yielding the result:</p>
<pre><code>0 [1, 1, 1]
</code></pre>
<p>So far so good. Now look at this example:</p>
<pre><code>class DataSheet:
MISSINGKEYS = {u'Item': ["Missing"]}
def __init__(self,stuff,dataSheet):
self.dataSheet = dataSheet
if self.dataSheet.has_key(u'Item'):
self.dataSheet[u'Item'].append(stuff[u'Item'])
else:
self.dataSheet[u'Item'] = self.MISSINGKEYS[u'Item']
</code></pre>
<p>Calling it like this</p>
<pre><code>stuff = {u'Item':['Test']}
ds = {}
DataSheet(stuff,ds)
print ds
DataSheet(stuff,ds)
print ds
DataSheet(stuff,ds)
print ds
</code></pre>
<p>yields:</p>
<pre><code>{u'Item': ['Missing']}
{u'Item': ['Missing', ['Test']]}
{u'Item': ['Missing', ['Test'], ['Test']]}
</code></pre>
<p>Now lets print <code>MISSINGKEYS</code> instead:</p>
<pre><code>stuff = {u'Item':['Test']}
ds = {}
DataSheet(stuff,ds)
print DataSheet.MISSINGKEYS
DataSheet(stuff,ds)
print DataSheet.MISSINGKEYS
DataSheet(stuff,ds)
print DataSheet.MISSINGKEYS
</code></pre>
<p>This yields:</p>
<pre><code>{u'Item': ['Missing']}
{u'Item': ['Missing', ['Test']]}
{u'Item': ['Missing', ['Test'], ['Test']]}
</code></pre>
<p>The exact same output. Why?</p>
<p><code>MISSINGKEYS</code> is a class variable but at no point is it deliberately altered.</p>
<p>In the first call the class goes into this line:</p>
<pre><code>self.dataSheet[u'Item'] = self.MISSINGKEYS[u'Item']
</code></pre>
<p>Which apparently starts it all. Obviously I only want <code>self.dataSheet[u'Item']</code> to take the value of <code>self.MISSINGKEYS[u'Item']</code>, not to become a reference to it or something like that.</p>
<p>In the following two calls the line</p>
<pre><code>self.dataSheet[u'Item'].append(stuff[u'Item'])
</code></pre>
<p>is called instead and the <code>append</code> works on <code>self.dataSheet[u'Item']</code> AND on <code>self.MISSINGKEYS[u'Item']</code> which it should not.</p>
<p>This leads to the assumption that after the first call both variables now reference the same object.</p>
<p>However although being equal they do not:</p>
<pre><code>ds == DataSheet.MISSINGKEYS
Out[170]: True
ds is DataSheet.MISSINGKEYS
Out[171]: False
</code></pre>
<p>Can someone explain to me what is going on here and how I can avoid it?</p>
<p>EDIT:
I tried this:</p>
<pre><code>ds[u'Item'] is DataSheet.MISSINGKEYS[u'Item']
Out[172]: True
</code></pre>
<p>So okay, this one entry in both dictionaries references the same object. How can I just assign the value instead?</p>
| 0 |
2016-09-23T10:28:29Z
| 39,659,335 |
<p>Thinking about what happens in Python function calls in terms of "pass by reference" vs "pass by value" is not generally useful; some people like to use the term "pass by object". Remember, everything in Python is an object, so even when you pass an integer to a function (in C terminology) you're actually passing a pointer to that integer object. </p>
<p>In your first code block you do</p>
<pre><code>self.X += 1
</code></pre>
<p>This <em>doesn't</em> modify the current integer object bound to <code>self.X</code>. It creates a new integer object with the appropriate value and binds that object to the <code>self.X</code> name.</p>
<p>Whereas, with </p>
<pre><code>self.Y.append(1)
</code></pre>
<p>you <em>are</em> mutating the current list object that's bound to <code>self.Y</code>, which happens to be the list object that was passed to <code>Test.__init__</code> as its <code>y</code> parameter. This is the same <code>y</code> list object in the calling code, so when you modify <code>self.Y</code> you are changing that <code>y</code> list object in the calling code. OTOH, if you did an assignment like </p>
<pre><code>self.Y = ['new stuff']
</code></pre>
<p>then the name <code>self.Y</code> would be bound to the new list, and the old list (which is still bound to <code>y</code> in the calling code) would be unaffected.</p>
<p>You may find this article helpful: <a href="http://nedbatchelder.com/text/names.html" rel="nofollow">Facts and myths about Python names and values</a>, which was written by SO veteran Ned Batchelder.</p>
| 1 |
2016-09-23T11:11:02Z
|
[
"python",
"python-2.7",
"class",
"pass-by-reference"
] |
Modify CherryPy's shutdown procedure
| 39,658,549 |
<p>So I have a cherry py server which wraps a state machine. Behind the scenes this state machine does all the heavy lifting of mananging processes and threads and caching, and it is thread safe. So on start up of my cherry py I attach it to the app and the requests call into app.state_machine.methods.</p>
<p>In pseudo code I do:</p>
<pre><code>from flask_app import app
import cherrypy
#configure app
app.state_machine = State_Machine.start()
try:
cherrypy.tree.graft(app, "/")
cherrypy.server.unsubscribe()
server = cherrypy._cpserver.Server()
server.socket_host="0.0.0.0"
server.socket_port = 5001
server.thread_pool = 10
server.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()
except KeyboardInterrupt:
logging.getLogger(__name__).warn("Recieved keyboard interrupt")
except Exception:
logging.getLogger(__name__).exception("Unknown exception from app")
finally:
logging.getLogger(__name__).info("Entering Finally Block")
state_machine.shutdown()
</code></pre>
<p>The intent here is that a key board interrupt should propagate out the app and calls state_machine.shutdown, which works with, e.g. the flask development server.</p>
<p>However, cherrypy swallows the KeyBoard interrupt and waits for its child threads to shutdown, since they contain references to app.state_machine, they will deadlock indefinitely until app.state_machine.shutdown() is called.</p>
<p>So how can I modify the shutdown procedure of cherrypy such that it will call shut down correctly?</p>
| 0 |
2016-09-23T10:29:08Z
| 39,664,617 |
<p>As suggested by web ninja, the answer was to use the plugin.</p>
<pre><code>from cherrypy.process import wspbus, plugins
class StateMachinePlugin(plugins.SimplePlugin) :
def __init__(self, bus, state_machine):
plugins.SimplePlugin.__init__(self, bus)
self.state_manager = state_machine
def start(self):
self.bus.log("Starting state_machine")
self.state_machine.run()
def stop(self):
self.bus.log("Shutting down state_machine")
self.state_machine.shutdown()
self.bus.log("Successfully shut down state_machine")
</code></pre>
<p>Then just do :</p>
<pre><code>from flask_app import app
import cherrypy
#configure app
app.state_machine = State_Machine.start()
try:
cherrypy.tree.graft(app, "/")
cherrypy.server.unsubscribe()
server = cherrypy._cpserver.Server()
server.socket_host="0.0.0.0"
server.socket_port = 5001
server.thread_pool = 10
server.subscribe()
###########################Added This line####################
StateMachinePlugin(cherrypy.engine, app.state_machine).subscribe()
#####################End Additions##########################
cherrypy.engine.start()
cherrypy.engine.block()
except KeyboardInterrupt:
logging.getLogger(__name__).warn("Recieved keyboard interrupt")
except Exception:
logging.getLogger(__name__).exception("Unknown exception from app")
finally:
logging.getLogger(__name__).info("Entering Finally Block")
state_machine.shutdown()
</code></pre>
| 0 |
2016-09-23T15:35:12Z
|
[
"python",
"multithreading",
"webserver",
"cherrypy"
] |
How to drop columns which have same values in all rows via pandas or spark dataframe?
| 39,658,574 |
<p>Suppose I've data similar to following:</p>
<pre><code> index id name value value2 value3 data1 val5
0 345 name1 1 99 23 3 66
1 12 name2 1 99 23 2 66
5 2 name6 1 99 23 7 66
</code></pre>
<p>How can we drop all those columns like (<code>value</code>, <code>value2</code>, <code>value3</code>) where all rows have same values, in one command or couple of commands using <strong>python</strong> ? </p>
<p>Consider we have many columns similar to <code>value</code>,<code>value2</code>,<code>value3</code>...<code>value200</code>.</p>
<p>Output:</p>
<pre><code> index id name data1
0 345 name1 3
1 12 name2 2
5 2 name6 7
</code></pre>
| 2 |
2016-09-23T10:30:25Z
| 39,658,662 |
<p>What we can do is <code>apply</code> <code>nunique</code> to calc the number of unique values in the df and drop the columns which only have a single unique value:</p>
<pre><code>In [285]:
cols = list(df)
nunique = df.apply(pd.Series.nunique)
cols_to_drop = nunique[nunique == 1].index
df.drop(cols_to_drop, axis=1)
Out[285]:
index id name data1
0 0 345 name1 3
1 1 12 name2 2
2 5 2 name6 7
</code></pre>
<p>Another way is to just <code>diff</code> the numeric columns and <code>sums</code> them:</p>
<pre><code>In [298]:
cols = df.select_dtypes([np.number]).columns
diff = df[cols].diff().sum()
df.drop(diff[diff== 0].index, axis=1)
â
Out[298]:
index id name data1
0 0 345 name1 3
1 1 12 name2 2
2 5 2 name6 7
</code></pre>
<p>Another approach is to use the property that the standard deviation will be zero for a column with the same value:</p>
<pre><code>In [300]:
cols = df.select_dtypes([np.number]).columns
std = df[cols].std()
cols_to_drop = std[std==0].index
df.drop(cols_to_drop, axis=1)
Out[300]:
index id name data1
0 0 345 name1 3
1 1 12 name2 2
2 5 2 name6 7
</code></pre>
<p>Actually the above can be done in a one-liner:</p>
<pre><code>In [306]:
df.drop(df.std()[(df.std() == 0)].index, axis=1)
Out[306]:
index id name data1
0 0 345 name1 3
1 1 12 name2 2
2 5 2 name6 7
</code></pre>
| 3 |
2016-09-23T10:35:00Z
|
[
"python",
"pandas",
"duplicates",
"multiple-columns",
"spark-dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.