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 |
---|---|---|---|---|---|---|---|---|---|
Using widgets intregrated. PyQT with Tkinter
| 39,679,473 |
<p>I have an image editor created in tkinter. However, I would add a floating widgets that exist in PyQt. Is there any way to run integrated tkinter with PyQt?</p>
| 1 |
2016-09-24T18:09:16Z
| 39,681,979 |
<p>No, there is no way to combine widgets from PyQt and Tkinter in a single app. </p>
| 0 |
2016-09-24T23:39:21Z
|
[
"python",
"tkinter",
"pyqt",
"pyqt4"
] |
Using widgets intregrated. PyQT with Tkinter
| 39,679,473 |
<p>I have an image editor created in tkinter. However, I would add a floating widgets that exist in PyQt. Is there any way to run integrated tkinter with PyQt?</p>
| 1 |
2016-09-24T18:09:16Z
| 39,689,904 |
<p>I make a workaround that solved the problem. I used python subprocess for call the PyQT instance and the option QtCore.Qt.WindowStaysOnTopHint for app running on top of tkinter. It´s work.</p>
<p>but the best solution is to create a thread in python and call PyQt in this thread. In this case it is possible to pass an instance of tk for PyQt and make communication between the two. It´s work too. It´s fine.</p>
| 0 |
2016-09-25T17:48:07Z
|
[
"python",
"tkinter",
"pyqt",
"pyqt4"
] |
openpyxl iterate through cells of column => TypeError: 'generator' object is not subscriptable
| 39,679,497 |
<p>i I want to loop over all values op a column, to safe them as the key in a dict. As far as i know, everything is ok, but python disagrees.</p>
<p>So my question is: "what am i doing wrong?"</p>
<pre><code>>>> wb = xl.load_workbook('/home/x/repos/network/input/y.xlsx')
>>> sheet = wb.active
>>> for cell in sheet.columns[0]:
... print(cell.value)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
</code></pre>
<p>I must be missing something, but after a few hours of trying, I must throw in the towle and call in the cavalecry ;)</p>
<p>thanks in advance for all the help!</p>
<p>===================================================================</p>
<p>@Charlie Clark: thanks for taking the time to answer. The thing is, I need the first column as keys in a dict, afterwards, I need to do</p>
<pre><code>for cell in sheet.columns[1:]:
</code></pre>
<p>so, while it would resolve my issue, it would come back to me a few lines later, in my code. I will use your suggestion in my code to extract the keys.</p>
<p>The question I mostly have is: </p>
<p>why doesn't it work, I am sure I used this code snippet before and this is also how, when googling, people are suggesting to do it.</p>
<p>==========================================================================</p>
<pre><code>>>> for column in ws.iter_cols(min_col = 2):
... for cell in column:
... print(cell.value)
</code></pre>
<p>goes over all columns of the sheet, except the first. Now, I still need to exclude the first 3 rows </p>
| -1 |
2016-09-24T18:11:46Z
| 39,680,171 |
<p><code>ws.columns</code> returns a generator of columns because this is much more efficient on large workbooks, as in your case: you only want one column. <a href="https://openpyxl.readthedocs.io/en/default/tutorial.html#accessing-many-cells" rel="nofollow">Version 2.4</a> now provides the option to get columns directly: <code>ws['A']</code> </p>
| 0 |
2016-09-24T19:29:52Z
|
[
"python",
"excel",
"loops",
"openpyxl"
] |
openpyxl iterate through cells of column => TypeError: 'generator' object is not subscriptable
| 39,679,497 |
<p>i I want to loop over all values op a column, to safe them as the key in a dict. As far as i know, everything is ok, but python disagrees.</p>
<p>So my question is: "what am i doing wrong?"</p>
<pre><code>>>> wb = xl.load_workbook('/home/x/repos/network/input/y.xlsx')
>>> sheet = wb.active
>>> for cell in sheet.columns[0]:
... print(cell.value)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
</code></pre>
<p>I must be missing something, but after a few hours of trying, I must throw in the towle and call in the cavalecry ;)</p>
<p>thanks in advance for all the help!</p>
<p>===================================================================</p>
<p>@Charlie Clark: thanks for taking the time to answer. The thing is, I need the first column as keys in a dict, afterwards, I need to do</p>
<pre><code>for cell in sheet.columns[1:]:
</code></pre>
<p>so, while it would resolve my issue, it would come back to me a few lines later, in my code. I will use your suggestion in my code to extract the keys.</p>
<p>The question I mostly have is: </p>
<p>why doesn't it work, I am sure I used this code snippet before and this is also how, when googling, people are suggesting to do it.</p>
<p>==========================================================================</p>
<pre><code>>>> for column in ws.iter_cols(min_col = 2):
... for cell in column:
... print(cell.value)
</code></pre>
<p>goes over all columns of the sheet, except the first. Now, I still need to exclude the first 3 rows </p>
| -1 |
2016-09-24T18:11:46Z
| 39,698,206 |
<p>apparently, the openpyxl module got upgraded to 2.4, without my knowledge.</p>
<pre><code>>>> for col in ws.iter_cols(min_col = 2, min_row=4):
... for cell in col:
... print(cell.value)
</code></pre>
<p>should do the trick.
I posted this in case other people are looking for the same answer.</p>
<pre><code>iter_cols(min_col=None, max_col=None, min_row=None, max_row=None)[source]
Returns all cells in the worksheet from the first row as columns.
If no boundaries are passed in the cells will start at A1.
If no cells are in the worksheet an empty tuple will be returned.
Parameters:
min_col (int) â smallest column index (1-based index)
min_row (int) â smallest row index (1-based index)
max_col (int) â largest column index (1-based index)
max_row (int) â smallest row index (1-based index)
Return type:
generator
</code></pre>
| 0 |
2016-09-26T08:39:53Z
|
[
"python",
"excel",
"loops",
"openpyxl"
] |
What is happening in this urlpatterns list of Python Django urls.py file?
| 39,679,542 |
<p>I have three versions of <code>urls.py</code> file.</p>
<p>Here are imports (shared between versions):</p>
<pre><code>from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import patterns, url
from main import views
</code></pre>
<p><strong>Version 1.</strong> Everything works fine here. No problems running <code>python2 manage.py runserver</code>.</p>
<pre><code>urlpatterns = patterns(
url(r'^bio$', 'views.bio_view'),
)
</code></pre>
<p><strong>Version 2.</strong> Hmm I need some more urls though. Let's add them. No problems here either.</p>
<pre><code>urlpatterns = patterns(
'',
url(r'^$', views.index, name='index'),
url(r'^bio$', 'views.bio_view'),
)
</code></pre>
<p><strong>Version 3.</strong> Wait a sec... What is <code>''</code> doing here? I don't actually need it. Let's remove it, shall we?</p>
<pre><code>urlpatterns = patterns(
url(r'^$', views.index, name='index'),
url(r'^bio$', 'views.bio_view'),
)
</code></pre>
<p>And here is the issue after running the <code>manage.py</code> server:</p>
<p>(Some of top <code>django</code> library calls ommitted)</p>
<pre><code> File "/home/konrad/workspace/mydir/myproject/urls.py", line 20, in <module>
url(r'^', include('main.urls')),
File "/usr/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/konrad/workspace/mydir/myproject/urls.py", line 15, in <module>
url(r'^bio$', 'views.bio_view'),
File "/usr/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 91, in patterns
t.add_prefix(prefix)
File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py", line 232, in add_prefix
self._callback_str = prefix + '.' + self._callback_str
TypeError: unsupported operand type(s) for +: 'RegexURLPattern' and 'unicode'
</code></pre>
<p>So... Actually the question is about the <strong>Version 2.</strong> - why is it fixing the <strong>Version 3.</strong> error? And what is the error?</p>
<p>What is actually happening here?</p>
| 0 |
2016-09-24T18:16:33Z
| 39,679,586 |
<p>I'm not sure why you're surprised; you removed a parameter, and things went wrong. (Your first version might well have "worked" when you ran the server, but I doubt you could actually get to the URL.)</p>
<p>You are using an old version of Django. In this version, <code>urlpatterns</code> must be defined with the result of the <code>patterns</code> function. The first parameter to that function is a prefix to apply to all view strings. Your prefix is empty, but that doesn't mean you can just remove it; your first URL is now being taken as the prefix parameter.</p>
<p>In recent versions it was recognised that this prefix is confusing and rarely used. As a result, the <code>patterns</code> function is removed and there is no prefix; the value of <code>urlpatterns</code> must now be a simple list. Additionally, views in urls must be callables, not strings.</p>
| 2 |
2016-09-24T18:21:42Z
|
[
"python",
"django",
"python-2.7",
"typeerror",
"django-urls"
] |
Insert char from string into list in one line
| 39,679,559 |
<p>I'm after a way to reduce the following code down to one line, I assume through list comprehension. </p>
<pre><code>string = raw_input("String: ")
stringlist = []
for char in string:
stringlist.insert(0, char)
</code></pre>
| 0 |
2016-09-24T18:18:17Z
| 39,679,573 |
<p>So, you basically want to reverse the string and create a list from its reversed version:</p>
<pre><code>stringlist = list(reversed(raw_input("String: ")))
</code></pre>
<p>The following is even shorter, but probably a bit harder to read:</p>
<pre><code>stringlist = list(raw_input("String: ")[::-1])
</code></pre>
<p>This code uses <a href="https://docs.python.org/release/2.3.5/whatsnew/section-slices.html" rel="nofollow">extended slices</a>.</p>
| 3 |
2016-09-24T18:20:22Z
|
[
"python",
"python-2.7",
"list-comprehension"
] |
How to convert a list to a dictionary where both key and value are the same?
| 39,679,649 |
<p>This is based on this question: <a href="http://stackoverflow.com/questions/6900955/python-convert-list-to-dictionary">python convert list to dictionary</a></p>
<p>The asker provides the following:</p>
<blockquote>
<pre><code>l = ["a", "b", "c", "d", "e"]
</code></pre>
<p>I want to convert this list to a
dictionary like:</p>
<pre><code>d = {"a": "b", "c": "d", "e": ""}
</code></pre>
</blockquote>
<p>While the grouper recipe is quite interesting and I have been "playing" around with it, however, what I would like to do is, unlike the output dictionary wanted by that asker, I would like to convert a list with strings like the one above into a dictionary where all values and keys are the same. Example:</p>
<pre><code>d = {"a": "a", "c": "c", "d": "d", "e": "e"}
</code></pre>
<p>How would I do this? </p>
<hr>
<p><strong>Edit</strong>:</p>
<p>Implementation code: </p>
<pre><code>def ylimChoice():
#returns all permutations of letter capitalisation in a certain word.
def permLet(s):
return(''.join(t) for t in product(*zip(s.lower(), s.upper())))
inputList = []
yesNo = input('Would you like to set custom ylim() arguments? ')
inputList.append(yesNo)
yes = list(permLet("yes"))
no = list(permLet("no"))
if any(yesNo in str({y: y for y in yes}.values()) for yesNo in inputList[0]):
yLimits()
elif any(yesNo in str({n: n for n in no}.values()) for yesNo in inputList[0]):
labelLocation = number.arange(len(count))
plot.bar(labelLocation, list(count.values()), align='center', width=0.5)
plot.xticks(labelLocation, list(count.keys()))
plot.xlabel('Characters')
plot.ylabel('Frequency')
plot.autoscale(enable=True, axis='both', tight=False)
plot.show()
</code></pre>
| -3 |
2016-09-24T18:29:50Z
| 39,679,662 |
<p>You can use a <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">dict-comprehension</a> like this:</p>
<pre><code>l = ["a", "b", "c", "d", "e"]
d = {s: s for s in l}
</code></pre>
| 2 |
2016-09-24T18:30:58Z
|
[
"python",
"python-3.x",
"dictionary"
] |
How to convert a list to a dictionary where both key and value are the same?
| 39,679,649 |
<p>This is based on this question: <a href="http://stackoverflow.com/questions/6900955/python-convert-list-to-dictionary">python convert list to dictionary</a></p>
<p>The asker provides the following:</p>
<blockquote>
<pre><code>l = ["a", "b", "c", "d", "e"]
</code></pre>
<p>I want to convert this list to a
dictionary like:</p>
<pre><code>d = {"a": "b", "c": "d", "e": ""}
</code></pre>
</blockquote>
<p>While the grouper recipe is quite interesting and I have been "playing" around with it, however, what I would like to do is, unlike the output dictionary wanted by that asker, I would like to convert a list with strings like the one above into a dictionary where all values and keys are the same. Example:</p>
<pre><code>d = {"a": "a", "c": "c", "d": "d", "e": "e"}
</code></pre>
<p>How would I do this? </p>
<hr>
<p><strong>Edit</strong>:</p>
<p>Implementation code: </p>
<pre><code>def ylimChoice():
#returns all permutations of letter capitalisation in a certain word.
def permLet(s):
return(''.join(t) for t in product(*zip(s.lower(), s.upper())))
inputList = []
yesNo = input('Would you like to set custom ylim() arguments? ')
inputList.append(yesNo)
yes = list(permLet("yes"))
no = list(permLet("no"))
if any(yesNo in str({y: y for y in yes}.values()) for yesNo in inputList[0]):
yLimits()
elif any(yesNo in str({n: n for n in no}.values()) for yesNo in inputList[0]):
labelLocation = number.arange(len(count))
plot.bar(labelLocation, list(count.values()), align='center', width=0.5)
plot.xticks(labelLocation, list(count.keys()))
plot.xlabel('Characters')
plot.ylabel('Frequency')
plot.autoscale(enable=True, axis='both', tight=False)
plot.show()
</code></pre>
| -3 |
2016-09-24T18:29:50Z
| 39,679,666 |
<p>You can just zip the same list together:</p>
<pre><code>dict(zip(l, l))
</code></pre>
<p>or use a dict comprehension:</p>
<pre><code>{i: i for i in l}
</code></pre>
<p>The latter is faster:</p>
<pre><code>>>> from timeit import timeit
>>> timeit('dict(zip(l, l))', 'l = ["a", "b", "c", "d", "e"]')
0.850489666001522
>>> timeit('{i: i for i in l}', 'l = ["a", "b", "c", "d", "e"]')
0.38318819299456663
</code></pre>
<p>This holds even for large sequences:</p>
<pre><code>>>> timeit('dict(zip(l, l))', 'l = range(1000000)', number=10)
1.28369528199255
>>> timeit('{i: i for i in l}', 'l = range(1000000)', number=10)
0.9533485669962829
</code></pre>
| 4 |
2016-09-24T18:31:20Z
|
[
"python",
"python-3.x",
"dictionary"
] |
python xpath loop through paragraphs and grab <strong>
| 39,679,668 |
<p>I have a series of paragraphs I'm trying to parse using xpath. The html is formatted like this:</p>
<pre><code><div id="content_third">
<h3>Title1</h3>
<p>
<strong>District</strong>
John Q Public <br>
Susie B Private
<p>
<p>
<strong>District</strong>
Anna C Public <br>
Bob J Private
<p>
<h3>Title1</h3>
<p>
<strong>District</strong>
John Q Public <br>
Susie B Private
<p>
<p>
<strong>District</strong>
Anna C Public <br>
Bob J Private
<p>
</div>
</code></pre>
<p>I'm setting up an initial loop like this:</p>
<pre><code>titles = tree.xpath('//*[@id="content_third"]/h3')
for num in range(len(titles):
</code></pre>
<p>Then an inner loop:</p>
<pre><code>district_races = tree.xpath('//*[@id="content_third"]/p[count(preceding-sibling::h3)={0}]'.format(num))
for index in range(len(district_races)):
</code></pre>
<p>Each loop, I want to select just the "District" within that <code>strong</code>. I've tried this, which spits out empty arrays except for one that's filled with all the Districts:</p>
<pre><code>zone = tree.xpath('//*[@id="content_third"]/p[count(preceding-sibling::h3)={0}/strong[{1}]/text()'.format(num, index))
</code></pre>
<p>Gotta love those unformatted state election webpages.</p>
| 0 |
2016-09-24T18:31:34Z
| 39,680,517 |
<p>I presume each <em>District</em> is a placeholder for some actual name so to get each District is a lot simpler than what you are trying to do, just extract the <em>text</em> from each <em>strong</em> inside each <em>p</em>:</p>
<pre><code>h = """<div id="content_third">
<h3>Title1</h3>
<p>
<strong>District</strong>
John Q Public <br>
Susie B Private
<p>
<p>
<strong>District</strong>
Anna C Public <br>
Bob J Private
<p>
<h3>Title1</h3>
<p>
<strong>District</strong>
John Q Public <br>
Susie B Private
<p>
<p>
<strong>District</strong>
Anna C Public <br>
Bob J Private
<p>
</div>"""
from lxml import html
tree = html.fromstring(h)
print(tree.xpath('//*[@id="content_third"]/p/strong/text()'))
</code></pre>
| 1 |
2016-09-24T20:10:56Z
|
[
"python",
"loops",
"xpath"
] |
Python - IF function inside of the button
| 39,679,966 |
<p>I have a problem with below code. By default it's a simple code, that switches frames. What I try to do is to modify LoginPage class to do what it says - login ;) as you can see, I have a test.db SQL database in place. It contains table users with columns: (Id INT, Name TEXT, Password TEXT)
What I need to do is input login and password, and compare it with users in database. Afterwards direct them to either LoginSuccessful or LoginFailed frames. The problem is every time I get near this class, I brake the code.</p>
<p>I'm totally clueless on how to insert the IF statement inside the button.</p>
<p>Just to clarify: It's not encrypted yet (it's just a school project), so you don't have to mention it's not safe, as I'm very aware of that :)
Anyone has any ideas?</p>
<pre><code>import tkinter as tk
import sqlite3 as lite
import sys
from Crypto.Cipher import AES
con = None
con = lite.connect('test.db')
cur = con.cursor()
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (LoginPage, LoginSuccessful, LoginFailed):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("LoginPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the login page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
inst_lbl = tk.Label(self, text = "Please enter your login credentials")
inst_lbl.pack()
pwa = tk.Label(self, text = "Login")
pwa.pack()
login = tk.Entry(self)
login.pack()
pwb = tk.Label(self, text = "pPassword")
pwb.pack()
password = tk.Entry(self)
password.pack()
button1 = tk.Button(self, text="Log in",
command=lambda: controller.show_frame("LoginSuccessful"))
button1.pack()
class LoginSuccessful(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Login was successful!", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the Login page",
command=lambda: controller.show_frame("LoginPage"))
button.pack()
class LoginFailed(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Login failed!", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the Login page",
command=lambda: controller.show_frame("LoginPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
</code></pre>
| 1 |
2016-09-24T19:06:46Z
| 39,682,025 |
<p>Consider adding a method <code>checkLogin</code> and not an anonymous <code>lambda</code> function which currently always opens the success screen. This method will run the parameterized SQL query to check credentials and depending on results calls the login success or failed frames:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT 1 FROM users WHERE [Name] = ? AND [Password] = ?
</code></pre>
<p>Then, have the login button call this method. One important item is to qualify all your class variables with <code>self.</code>, so <code>checkLogin</code> can use the returned <em>LoginPage</em> frame user input values. Below is an adjustment of the <em>LoginPage</em> class, the only change required:</p>
<pre><code>class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.label = tk.Label(self, text="This is the login page", font=TITLE_FONT)
self.label.pack(side="top", fill="x", pady=10)
self.inst_lbl = tk.Label(self, text = "Please enter your login credentials")
self.inst_lbl.pack()
self.pwa = tk.Label(self, text = "Login")
self.pwa.pack()
self.login = tk.Entry(self)
self.login.pack()
self.pwb = tk.Label(self, text = "pPassword")
self.pwb.pack()
self.password = tk.Entry(self)
self.password.pack()
button1 = tk.Button(self, text="Log in", command=self.checkLogin)
button1.pack()
def checkLogin(self):
cur.execute("SELECT 1 FROM users WHERE [Name] = ? AND [Password] = ?",
[self.login.get(), self.password.get()])
result = cur.fetchone()
if result is None:
self.controller.show_frame("LoginFailed")
else:
self.controller.show_frame("LoginSuccessful")
</code></pre>
| 1 |
2016-09-24T23:46:30Z
|
[
"python",
"sql",
"tkinter"
] |
Tornado Coroutine : Return value and one time execution
| 39,680,068 |
<p>I'm new to Tornado so I wanted to know if the code below is a correct way to approach the problem or there is a better one. It works but I'm not sure regarding its efficiency. </p>
<p>The code is based on the documentation <a href="http://www.tornadoweb.org/en/stable/guide/coroutines.html" rel="nofollow">here</a></p>
<p>In the middle of my script, I need to run HTTP Requests (10-50). Apparently, it is possible to do this in parallel this way :</p>
<pre><code>@gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
# responses is a list of HTTPResponses in the same order
</code></pre>
<p>How do I access responses after the coroutine is done ? Can I just add <code>return responses</code> ?
Also, as I only need to use an async process once in my code, I start the IOLoop this way :</p>
<pre><code># run_sync() doesn't take arguments, so we must wrap the
# call in a lambda.
IOLoop.current().run_sync(lambda: parallel_fetch_many(googleLinks))
</code></pre>
<p>Is it correct to do it this way ? Or should I just start the IOLoop at the beginning of the script and stop it a the end, even though I only use an async process once.</p>
<p>Basically, my question is : Is the code below correct ?</p>
<pre><code>@gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
return responses
googleLinks = [url1,url2,...,urln]
responses = IOLoop.current().run_sync(lambda:parallel_fetch_many(googleLinks))
do_something(responses)
</code></pre>
| 0 |
2016-09-24T19:19:08Z
| 39,680,224 |
<p>Yes, your code looks correct to me.</p>
| 1 |
2016-09-24T19:36:28Z
|
[
"python",
"tornado"
] |
Can I set variable column widths in pandas?
| 39,680,147 |
<p>I've got several columns with long strings of text in a pandas data frame, but am only interested in examining one of them. Is there a way to use something along the lines of <code>pd.set_option('max_colwidth', 60)</code> but for a <strong>single column</strong> only, rather than expanding the width of all the columns in my df?</p>
| 1 |
2016-09-24T19:27:39Z
| 39,680,725 |
<p>If you want to change the display in a Jupyter Notebook, you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Style</a> feature.
To use this formatting for only some columns simply indicate the column(s) to enlarge thanks to the <code>subset</code> parameter. This is basically HTML and CSS.</p>
<pre><code>### Test data
df = DataFrame({'text': ['foo foo foo foo foo foo foo foo', 'bar bar bar bar bar'],
'number': [1, 2]})
df.style.set_properties(subset=['text'], **{'width': '300px'})
</code></pre>
<p><a href="http://i.stack.imgur.com/75CvJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/75CvJ.png" alt="enter image description here"></a></p>
| 4 |
2016-09-24T20:33:40Z
|
[
"python",
"pandas"
] |
Can I set variable column widths in pandas?
| 39,680,147 |
<p>I've got several columns with long strings of text in a pandas data frame, but am only interested in examining one of them. Is there a way to use something along the lines of <code>pd.set_option('max_colwidth', 60)</code> but for a <strong>single column</strong> only, rather than expanding the width of all the columns in my df?</p>
| 1 |
2016-09-24T19:27:39Z
| 39,680,775 |
<p>check this link pls: Truncating column width in pandas</p>
<p><a href="http://check%20this%20link%20pls%20http://stackoverflow.com/questions/22792740/truncating-colum%E2%80%8C%E2%80%8Bn-width-in-pandas" rel="nofollow">http://stackoverflow.com/questions/22792740/truncating-column-width-in-pandas</a></p>
| 0 |
2016-09-24T20:41:52Z
|
[
"python",
"pandas"
] |
Why are there blank spaces in the Unicode character table and how do I check if a unicode value is one of those?
| 39,680,148 |
<p>If you check out the <a href="http://unicode-table.com/en/#control-character" rel="nofollow">Unicode Table</a>, there are several spaces further in the table that are simply blank. There's a unicode value, but no character, ex. U+0BA5. Why are there these empty places?</p>
<p>Second of all, how would I check if a unicode value is one of these empty spaces? My code determines a unicode value using unichr(int), which returns a valid unicode value, but I don't know how to check if this unicode value will simply appear as an empty box. </p>
| 0 |
2016-09-24T19:27:43Z
| 39,680,197 |
<p>Not all Unicode codepoints have received an assignment; this can be for any number of reasons, historical, practical, policital, etc.</p>
<p>You can test if a given codepoint has a Unicode <em>name</em>, by using the <a href="https://docs.python.org/3/library/unicodedata.html#unicodedata.name" rel="nofollow"><code>unicodedata.name()</code> function</a>; it'll raise a <code>ValueError</code> when a codepoint has no name assigned to it:</p>
<pre><code>>>> import unicodedata
>>> unicodedata.name(u'\u0BA5')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: no such name
</code></pre>
| 1 |
2016-09-24T19:33:06Z
|
[
"python",
"unicode"
] |
PYTHONPATH in OS X
| 39,680,157 |
<p>I set PYTHONPATH variable on my Apple laptop a while ago.
I have checked /private/etc/profile config file. It is not there. Where else I could find it?</p>
<p>What other config file could be used to set the PYTHONPATH variable on OS X?</p>
| 0 |
2016-09-24T19:28:43Z
| 39,681,022 |
<p>There are several config files that can be used to set <strong>PYTHONPATH</strong> in OS X:</p>
<p>The first is <strong>profile</strong> file which is located in hidden <em>/private/etc/</em> folder:</p>
<pre><code>/private/etc/profile
</code></pre>
<p>You can use the following syntax to set the variable there:</p>
<pre><code>export MY_CUSTOM_ENV_VARIABLE="/Applications/MyApp/bin"
</code></pre>
<p>Other config files are <code>.cshrc</code>, <code>.bashrc</code> and <code>. bash_profile</code> which (thanks <a href="http://stackoverflow.com/users/3991125/albert">albert</a> for your info) are located in user's home directory and based on your OS X might or might not be there:</p>
<pre><code>/Users/username/.cshrc
/Users/username/.bashrc
/Users/username/.bash_profile
</code></pre>
<p>To set the environment variable in <code>.cshrc</code> file use the syntax below:</p>
<pre><code>setenv MY_CUSTOM_ENV_VARIABLE /Applications/MyApp/bin
</code></pre>
<p>To set the environment variable using <code>.bash_profile</code> file use this syntax:</p>
<pre><code>export MY_CUSTOM_ENV_VARIABLE=/Applications/MyApp/bin:$MY_CUSTOM_ENV_VARIABLE
</code></pre>
<p>In my case <strong>PYTHONPATH</strong> variable was set in <code>.bash_profile</code> file. And it was set with the following syntax:</p>
<pre><code>export PYTHONPATH=/Users/myModules:$PYTHONPATH
</code></pre>
| 1 |
2016-09-24T21:13:55Z
|
[
"python"
] |
Pandas, split dataframe by monotonic increase of column value
| 39,680,162 |
<p>I have a gigantic dataframe with a datetime type column called time, and another float type column called dist, the data frame is sorted based on time, and dist already.
I want to split the dataframe into several dataframes base on monotonic increase of dist.</p>
<p>Split</p>
<pre><code> dt dist
0 20160811 11:10 1.0
1 20160811 11:15 1.4
2 20160811 12:15 1.8
3 20160811 12:32 0.6
4 20160811 12:34 0.8
5 20160811 14:38 0.2
</code></pre>
<p>into</p>
<pre><code> dt dist
0 20160811 11:10 1.0
1 20160811 11:15 1.4
2 20160811 12:15 1.8
dt dist
0 20160811 12:32 0.6
1 20160811 12:34 0.8
dt dist
0 20160811 14:38 0.2
</code></pre>
| 1 |
2016-09-24T19:29:25Z
| 39,680,327 |
<p>You can calculate a difference vector of <code>dist</code> column and then do a <code>cumsum()</code> on the condition <code>diff < 0</code> (this creates a new id whenever the <code>dist</code> decreases from previous value)</p>
<pre><code>df['id'] = (df.dist.diff() < 0).cumsum()
print(df)
# dt dist id
#0 20160811 11:10 1.0 0
#1 20160811 11:15 1.4 0
#2 20160811 12:15 1.8 0
#3 20160811 12:32 0.6 1
#4 20160811 12:34 0.8 1
#5 20160811 14:38 0.2 2
for _, g in df.groupby((df.dist.diff() < 0).cumsum()):
print(g)
# dt dist
#0 20160811 11:10 1.0
#1 20160811 11:15 1.4
#2 20160811 12:15 1.8
# dt dist
#3 20160811 12:32 0.6
#4 20160811 12:34 0.8
# dt dist
#5 20160811 14:38 0.2
</code></pre>
| 4 |
2016-09-24T19:48:56Z
|
[
"python",
"pandas",
"numpy",
"dataframe"
] |
Pandas, split dataframe by monotonic increase of column value
| 39,680,162 |
<p>I have a gigantic dataframe with a datetime type column called time, and another float type column called dist, the data frame is sorted based on time, and dist already.
I want to split the dataframe into several dataframes base on monotonic increase of dist.</p>
<p>Split</p>
<pre><code> dt dist
0 20160811 11:10 1.0
1 20160811 11:15 1.4
2 20160811 12:15 1.8
3 20160811 12:32 0.6
4 20160811 12:34 0.8
5 20160811 14:38 0.2
</code></pre>
<p>into</p>
<pre><code> dt dist
0 20160811 11:10 1.0
1 20160811 11:15 1.4
2 20160811 12:15 1.8
dt dist
0 20160811 12:32 0.6
1 20160811 12:34 0.8
dt dist
0 20160811 14:38 0.2
</code></pre>
| 1 |
2016-09-24T19:29:25Z
| 39,680,343 |
<p>you can do it using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow">np.split()</a> method:</p>
<pre><code>In [92]: df
Out[92]:
dt dist
0 2016-08-11 11:10:00 1.0
1 2016-08-11 11:15:00 1.4
2 2016-08-11 12:15:00 1.8
3 2016-08-11 12:32:00 0.6
4 2016-08-11 12:34:00 0.8
5 2016-08-11 14:38:00 0.2
In [93]: dfs = np.split(df, df[df.dist.diff().fillna(0) < 0].index)
In [94]: [print(x) for x in dfs]
dt dist
0 2016-08-11 11:10:00 1.0
1 2016-08-11 11:15:00 1.4
2 2016-08-11 12:15:00 1.8
dt dist
3 2016-08-11 12:32:00 0.6
4 2016-08-11 12:34:00 0.8
dt dist
5 2016-08-11 14:38:00 0.2
Out[94]: [None, None, None]
</code></pre>
<p>Explanation:</p>
<pre><code>In [97]: df.dist.diff().fillna(0) < 0
Out[97]:
0 False
1 False
2 False
3 True
4 False
5 True
Name: dist, dtype: bool
In [98]: df[df.dist.diff().fillna(0) < 0]
Out[98]:
dt dist
3 2016-08-11 12:32:00 0.6
5 2016-08-11 14:38:00 0.2
In [99]: df[df.dist.diff().fillna(0) < 0].index
Out[99]: Int64Index([3, 5], dtype='int64')
</code></pre>
| 1 |
2016-09-24T19:51:18Z
|
[
"python",
"pandas",
"numpy",
"dataframe"
] |
How to call UI class in Qt5 in Python
| 39,680,265 |
<p>This is the class that have to call the UI class:</p>
<pre><code>class mainpanelManager(QtGui.QGuiApplication, Ui_MainWindow):
def __init__(self):
QtGui.QGuiApplication.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
if __name__ == "__main__":
app = QtGui.QGuiApplication(sys.argv)
window = mainpanelManager()
window.show()
sys.exit(app.exec_())
</code></pre>
<p>and this is the UI class(generated from QtCreator and Qt5.7):</p>
<pre><code> from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(QtGui.QWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1155, 704)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.listView = QtWidgets.QListView(self.centralwidget)
self.listView.setMaximumSize(QtCore.QSize(300, 16777215))
self.listView.setObjectName("listView")
self.gridLayout.addWidget(self.listView, 1, 0, 1, 1)
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.gridLayout_2 = QtWidgets.QGridLayout(self.tab)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.listWidget_2 = QtWidgets.QListWidget(self.tab)
self.listWidget_2.setFrameShape(QtWidgets.QFrame.NoFrame)
self.listWidget_2.setFrameShadow(QtWidgets.QFrame.Plain)
self.listWidget_2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.listWidget_2.setIconSize(QtCore.QSize(100, 100))
self.listWidget_2.setViewMode(QtWidgets.QListView.IconMode)
self.listWidget_2.setModelColumn(0)
self.listWidget_2.setObjectName("listWidget_2")
self.gridLayout_2.addWidget(self.listWidget_2, 0, 0, 1, 1)
self.tabWidget.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.gridLayout_3 = QtWidgets.QGridLayout(self.tab_2)
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setObjectName("gridLayout_3")
self.listWidget = QtWidgets.QListWidget(self.tab_2)
self.listWidget.setViewMode(QtWidgets.QListView.IconMode)
self.listWidget.setObjectName("listWidget")
self.gridLayout_3.addWidget(self.listWidget, 0, 0, 1, 1)
self.tabWidget.addTab(self.tab_2, "")
self.gridLayout.addWidget(self.tabWidget, 1, 1, 1, 1)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
self.label_2.setSizePolicy(sizePolicy)
self.label_2.setMinimumSize(QtCore.QSize(300, 130))
self.label_2.setMaximumSize(QtCore.QSize(300, 100))
self.label_2.setText("")
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.horizontalSlider_2 = QtWidgets.QSlider(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.horizontalSlider_2.sizePolicy().hasHeightForWidth())
self.horizontalSlider_2.setSizePolicy(sizePolicy)
self.horizontalSlider_2.setMinimumSize(QtCore.QSize(300, 40))
self.horizontalSlider_2.setMaximumSize(QtCore.QSize(300, 16777215))
self.horizontalSlider_2.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_2.setObjectName("horizontalSlider_2")
self.verticalLayout.addWidget(self.horizontalSlider_2)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(50, 30))
self.pushButton.setMaximumSize(QtCore.QSize(50, 30))
self.pushButton.setBaseSize(QtCore.QSize(50, 30))
self.pushButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton.setText("")
self.pushButton.setIconSize(QtCore.QSize(30, 30))
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
self.pushButton_2.setSizePolicy(sizePolicy)
self.pushButton_2.setMinimumSize(QtCore.QSize(50, 30))
self.pushButton_2.setMaximumSize(QtCore.QSize(50, 30))
self.pushButton_2.setBaseSize(QtCore.QSize(50, 30))
self.pushButton_2.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_2.setText("")
self.pushButton_2.setIconSize(QtCore.QSize(30, 30))
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
self.pushButton_3.setSizePolicy(sizePolicy)
self.pushButton_3.setMinimumSize(QtCore.QSize(50, 30))
self.pushButton_3.setMaximumSize(QtCore.QSize(50, 30))
self.pushButton_3.setBaseSize(QtCore.QSize(50, 30))
self.pushButton_3.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_3.setText("")
self.pushButton_3.setIconSize(QtCore.QSize(30, 30))
self.pushButton_3.setObjectName("pushButton_3")
self.horizontalLayout.addWidget(self.pushButton_3)
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
self.pushButton_4.setSizePolicy(sizePolicy)
self.pushButton_4.setMinimumSize(QtCore.QSize(50, 30))
self.pushButton_4.setMaximumSize(QtCore.QSize(50, 30))
self.pushButton_4.setBaseSize(QtCore.QSize(50, 30))
self.pushButton_4.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_4.setText("")
self.pushButton_4.setIconSize(QtCore.QSize(30, 30))
self.pushButton_4.setObjectName("pushButton_4")
self.horizontalLayout.addWidget(self.pushButton_4)
self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_5.sizePolicy().hasHeightForWidth())
self.pushButton_5.setSizePolicy(sizePolicy)
self.pushButton_5.setMinimumSize(QtCore.QSize(50, 30))
self.pushButton_5.setMaximumSize(QtCore.QSize(50, 30))
self.pushButton_5.setBaseSize(QtCore.QSize(50, 30))
self.pushButton_5.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_5.setText("")
self.pushButton_5.setIconSize(QtCore.QSize(30, 30))
self.pushButton_5.setObjectName("pushButton_5")
self.horizontalLayout.addWidget(self.pushButton_5)
self.verticalLayout.addLayout(self.horizontalLayout)
self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setText("")
self.label.setObjectName("label")
self.horizontalLayout_3.addWidget(self.label)
self.label_3 = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
self.label_3.setSizePolicy(sizePolicy)
self.label_3.setMinimumSize(QtCore.QSize(180, 180))
self.label_3.setMaximumSize(QtCore.QSize(180, 180))
self.label_3.setText("")
self.label_3.setObjectName("label_3")
self.horizontalLayout_3.addWidget(self.label_3)
self.verticalLayout_2.addLayout(self.horizontalLayout_3)
self.horizontalSlider = QtWidgets.QSlider(self.centralwidget)
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setObjectName("horizontalSlider")
self.verticalLayout_2.addWidget(self.horizontalSlider)
self.gridLayout.addLayout(self.verticalLayout_2, 0, 1, 1, 1)
self.horizontalSlider_3 = QtWidgets.QSlider(self.centralwidget)
self.horizontalSlider_3.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_3.setObjectName("horizontalSlider_3")
self.gridLayout.addWidget(self.horizontalSlider_3, 2, 1, 1, 1)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_6.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_6.setText("")
self.pushButton_6.setObjectName("pushButton_6")
self.horizontalLayout_2.addWidget(self.pushButton_6)
self.pushButton_7 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_7.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_7.setText("")
self.pushButton_7.setObjectName("pushButton_7")
self.horizontalLayout_2.addWidget(self.pushButton_7)
self.pushButton_8 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_8.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_8.setText("")
self.pushButton_8.setObjectName("pushButton_8")
self.horizontalLayout_2.addWidget(self.pushButton_8)
self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1155, 19))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuSettings = QtWidgets.QMenu(self.menubar)
self.menuSettings.setObjectName("menuSettings")
self.menuLibrary = QtWidgets.QMenu(self.menuSettings)
self.menuLibrary.setObjectName("menuLibrary")
self.menuAbout = QtWidgets.QMenu(self.menubar)
self.menuAbout.setObjectName("menuAbout")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen = QtWidgets.QAction(MainWindow)
self.actionOpen.setObjectName("actionOpen")
self.actionOpen_Dir = QtWidgets.QAction(MainWindow)
self.actionOpen_Dir.setObjectName("actionOpen_Dir")
self.actionMinimize = QtWidgets.QAction(MainWindow)
self.actionMinimize.setObjectName("actionMinimize")
self.actionClose = QtWidgets.QAction(MainWindow)
self.actionClose.setObjectName("actionClose")
self.actionGeneral = QtWidgets.QAction(MainWindow)
self.actionGeneral.setObjectName("actionGeneral")
self.actionRefresh = QtWidgets.QAction(MainWindow)
self.actionRefresh.setObjectName("actionRefresh")
self.actionRebuild = QtWidgets.QAction(MainWindow)
self.actionRebuild.setObjectName("actionRebuild")
self.actionClear = QtWidgets.QAction(MainWindow)
self.actionClear.setObjectName("actionClear")
self.actionSettings = QtWidgets.QAction(MainWindow)
self.actionSettings.setObjectName("actionSettings")
self.actionAbout_Siren = QtWidgets.QAction(MainWindow)
self.actionAbout_Siren.setObjectName("actionAbout_Siren")
self.actionCheck_for_updates = QtWidgets.QAction(MainWindow)
self.actionCheck_for_updates.setObjectName("actionCheck_for_updates")
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionOpen_Dir)
self.menuFile.addAction(self.actionMinimize)
self.menuFile.addAction(self.actionClose)
self.menuLibrary.addAction(self.actionRefresh)
self.menuLibrary.addAction(self.actionRebuild)
self.menuLibrary.addAction(self.actionClear)
self.menuLibrary.addAction(self.actionSettings)
self.menuSettings.addAction(self.menuLibrary.menuAction())
self.menuSettings.addAction(self.actionGeneral)
self.menuAbout.addAction(self.actionAbout_Siren)
self.menuAbout.addAction(self.actionCheck_for_updates)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuSettings.menuAction())
self.menubar.addAction(self.menuAbout.menuAction())
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
self.horizontalSlider_2.valueChanged['int'].connect(self.label_2.setNum)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.listWidget_2.setSortingEnabled(True)
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Artist"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Album"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuSettings.setTitle(_translate("MainWindow", "Settings"))
self.menuLibrary.setTitle(_translate("MainWindow", "Library"))
self.menuAbout.setTitle(_translate("MainWindow", "About"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
self.actionOpen_Dir.setText(_translate("MainWindow", "Open Dir..."))
self.actionMinimize.setText(_translate("MainWindow", "Minimize"))
self.actionClose.setText(_translate("MainWindow", "Close"))
self.actionGeneral.setText(_translate("MainWindow", "General"))
self.actionRefresh.setText(_translate("MainWindow", "Refresh"))
self.actionRebuild.setText(_translate("MainWindow", "Rebuild"))
self.actionClear.setText(_translate("MainWindow", "Clear"))
self.actionSettings.setText(_translate("MainWindow", "Settings"))
self.actionAbout_Siren.setText(_translate("MainWindow", "About Siren"))
self.actionCheck_for_updates.setText(_translate("MainWindow", "Check for updates"))
</code></pre>
<p>When i run the <code>class mainpanelManager</code> i get this error:</p>
<pre><code>QtGui.QGuiApplication.__init__(self)
TypeError: QGuiApplication(List[str]): not enough arguments
</code></pre>
<p>Please give me some advice how to run the UI class from the other class.
What am i doing wrong?? The samples i found were using <code>import PyQt4 import QtCore, QtGui, QtWidgets</code> but in my case (using Qt5) there is no <code>QApplication</code> option like in <code>Qt4</code>. Seems <code>Qt5</code> uses <code>QtGui.QGuiApplication</code>. I can't understand this. Any help will be welcome. Please explain in details. I am still quite new in Python.</p>
| 1 |
2016-09-24T19:41:34Z
| 39,680,430 |
<p>You need a subclass which matches the top-level object from Qt Designer - which in this case appears to be a <code>QMainWindow</code>:</p>
<pre><code>class mainpanelManager(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
</code></pre>
<p>And you should use a <code>QApplication</code>:</p>
<pre><code>if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = mainpanelManager()
window.show()
sys.exit(app.exec_())
</code></pre>
<p>PS:</p>
<p>PyQt4 is not compatible with PyQt5. See: <a href="http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html" rel="nofollow">Differences Between PyQt4 and PyQt5</a>.</p>
<p>PPS:</p>
<p>It also looks like you've attempted to edit the module generated by pyuic. Do not ever do that. I suggest you re-run pyuic so you get a clean module.</p>
| 1 |
2016-09-24T20:00:29Z
|
[
"python",
"python-3.x",
"qt5",
"qt-creator",
"pyqt5"
] |
Append nested dictionaries
| 39,680,317 |
<p>If you have a nested dictionary, where each 'outer' key can map to a dictionary with multiple keys, how do you add a new key to the 'inner' dictionary? For example, I have a list where each element is composed of 3 components: an outer key, an inner key, and a value (A B 10).</p>
<p>Here's the loop I have so far</p>
<pre><code>for e in keyList:
nested_dict[e[0]] = {e[2] : e[3:]}
</code></pre>
<p>Right now, instead of adding the new key:value to the inner dictionary, any new key:value outright replaces the inner dictionary.</p>
<p>For instance, lets say the keyList is just [(A B 10), (A D 15)]. The result with that loop is </p>
<pre><code>{'A' : {'D' : 15}}
</code></pre>
<p>How can I make it so that instead it's</p>
<pre><code>{'A' : {'B' : 10, 'D' : 15}}
</code></pre>
| 0 |
2016-09-24T19:47:57Z
| 39,680,349 |
<p>You told your code to assign newly created dict to key <code>e[0]</code>. It's always replaced blindly and it does not look at previously stored value.</p>
<p>Instead you need something like:</p>
<pre><code>for e in keyList:
if e[0] not in nested_dict:
nested_dict[e[0]] = {}
nested_dict[e[0]].update({e[2] : e[3:]})
</code></pre>
<p><code>If</code> conditional is required to handle 'first key' case. Alternatively <code>defaultdict</code> can be used.</p>
<pre><code>from collections import defaultdict
nested_dict = defaultdict(dict)
for e in keyList:
nested_dict[e[0]].update({e[2] : e[3:]})
</code></pre>
| 3 |
2016-09-24T19:51:37Z
|
[
"python",
"dictionary"
] |
Paser symbol(pdb) file and get function name and offset
| 39,680,387 |
<p>I want to know what is the easiest way to parse a PDB (debugging symbol) file and get function name and offset in binary, preferably in Python.</p>
<p>Thanks,</p>
| 0 |
2016-09-24T19:55:08Z
| 39,680,409 |
<p>Dunno about Python but you should be able to do it using <a href="https://msdn.microsoft.com/en-us/library/t6tay6cz.aspx" rel="nofollow">DIA API</a>. See <a href="https://msdn.microsoft.com/en-us/library/eee38t3h.aspx" rel="nofollow">Querying the .Pdb File</a> for example.</p>
| -1 |
2016-09-24T19:58:32Z
|
[
"python",
"debugging",
"symbols",
"pdb",
"debug-symbols"
] |
Python Turtle Program not working
| 39,680,569 |
<p>Can't figure out why am I getting this error: AttributeError: 'str' object has no attribute 'forward'</p>
<p>Write a function named drawSquare. The function drawSquare takes two
parameters: a turtle, t and an integer, length, that is the length of a side of the square.</p>
<p>The function drawSquare should use the parameter t to draw the square.
Do not make any assumptions about the initial up/down state of the turtle,
its position on the screen or its orientation. The function drawSquare
should begin drawing with the turtle at its initial position and
orientation. When drawSquare returns, the turtle should again be in its
initial position and orientation.
You must use a loop for repeated operations.</p>
<pre><code>import turtle
s = turtle.Screen()
t = turtle.Turtle()
def drawSquare(t, length):
for i in range(4):
t.forward(length)
t.right(90)
drawSquare('turtle', 100)
</code></pre>
| 0 |
2016-09-24T20:16:06Z
| 39,680,606 |
<p>In the last line, when you made the call to your drawSquare function you passed the string 'turtle' - pass in your Turtle object t instead.</p>
| 1 |
2016-09-24T20:20:41Z
|
[
"python",
"turtle-graphics"
] |
scikit-learn - train_test_split and ShuffleSplit yielding very different results
| 39,680,596 |
<p>I'm trying to do run a simple RandomForestClassifier() with a large-ish dataset. I typically first do the cross-validation using <code>train_test_split</code>, and then start using <code>cross_val_score</code>.</p>
<p>In this case though, I get very different results from these two approaches, and I can't figure out why. My understanding these is that these two snippets should do <em>exactly the same thing</em>:</p>
<pre><code>cfc = RandomForestClassifier(n_estimators=50)
scores = cross_val_score(cfc, X, y,
cv = ShuffleSplit(len(X), 1, 0.25),
scoring = 'roc_auc')
print(scores)
>>> [ 0.88482262]
</code></pre>
<p>and this:</p>
<pre><code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
cfc = RandomForestClassifier(n_estimators=50)
cfc.fit(X_train, y_train)
roc_auc_score(y_test, cfc.predict(X_test))
>>> 0.57733474562203269
</code></pre>
<p>And yet the scores are widely different. (The scores are very representative, I observed the same behavior across many many runs).</p>
<p>Any ideas why this can be? I am tempted to trust the <code>cross_val_score</code> result, but I want to be sure that I am not messing up somewhere..</p>
<p>** Update **</p>
<p>I noticed that when I reverse the order of the arguments to <code>roc_auc_score</code>, I get a similar result:</p>
<pre><code>roc_auc_score(cfc.predict(X_test), y_test)
</code></pre>
<p>But the documentation explicitly states that the first element should be the real values, and the second one the target.</p>
| 0 |
2016-09-24T20:19:40Z
| 39,772,418 |
<p>I'm not sure what's the issue but here are two things you could try:</p>
<ol>
<li><p>ROC AUC needs prediction probabilities for proper evaluation, not hard scores (i.e. 0 or 1). Therefore change the <code>cross_val_score</code> to work with probabilities. You can check the first answer on <a href="http://stackoverflow.com/questions/28787500/predict-proba-for-a-cross-validated-model">this link</a> for more details.</p>
<p>Compare this with <code>roc_auc_score(y_test, cfc.predict_proba(X_test)[:,1])</code></p></li>
<li><p>As xysmas said, try setting a random_state to both <code>cross_val_score</code> and <code>roc_auc_score</code></p></li>
</ol>
| 0 |
2016-09-29T13:59:17Z
|
[
"python",
"pandas",
"scikit-learn"
] |
Matching company names in the news data using Python
| 39,680,624 |
<p>I have news dataset which contains almost 10,000 news over the last 3 years.
I also have a list of companies (names of companies) which are registered in NYSE. Now I want to check whether list of company names in the list have appeared in the news dataset or not.
Example:</p>
<pre><code>company Name: 'E.I. du Pont de Nemours and Company'
News: 'Monsanto and DuPont settle major disputes with broad patent-licensing deal, with DuPont agreeing to pay at least $1.75 billion over 10 years for rights to technology for herbicide-resistant soybeans.'
</code></pre>
<p>Now, I can find the news contains company name if the exact company name is in the news but you can see from the above example it is not the case.
I also tried another way i.e. I took the integral name in the company's full name i.e. in the above example 'Pont' is a word which should be definitely a part of the text when this company name is called. So it worked for majority of the times but then problem occurs in the following example:</p>
<pre><code>Company Name: Ennis, Inc.
News: L D`ennis` Kozlowski, former chief executive convicted of looting nearly $100 million from Tyco International, has emerged into far more modest life after serving six-and-a-half year sentence and probation; Kozlowski, who became ultimate symbol of corporate greed in era that included scandals at Enron and WorldCom, describes his personal transformation and more humble pleasures that have replaced his once high-flying lifestyle.
</code></pre>
<p>Now you can see <code>Ennis</code> is matching with <code>Dennis</code> in the text so it giving irrelevant news results. </p>
<p>Can someone help in telling the right way of doing this ? Thanks.</p>
| 1 |
2016-09-24T20:22:07Z
| 39,680,656 |
<p>You can try</p>
<pre><code> difflib.get_close_matches
</code></pre>
<p>with the full company name.</p>
| -1 |
2016-09-24T20:26:11Z
|
[
"python",
"python-3.x",
"machine-learning"
] |
Matching company names in the news data using Python
| 39,680,624 |
<p>I have news dataset which contains almost 10,000 news over the last 3 years.
I also have a list of companies (names of companies) which are registered in NYSE. Now I want to check whether list of company names in the list have appeared in the news dataset or not.
Example:</p>
<pre><code>company Name: 'E.I. du Pont de Nemours and Company'
News: 'Monsanto and DuPont settle major disputes with broad patent-licensing deal, with DuPont agreeing to pay at least $1.75 billion over 10 years for rights to technology for herbicide-resistant soybeans.'
</code></pre>
<p>Now, I can find the news contains company name if the exact company name is in the news but you can see from the above example it is not the case.
I also tried another way i.e. I took the integral name in the company's full name i.e. in the above example 'Pont' is a word which should be definitely a part of the text when this company name is called. So it worked for majority of the times but then problem occurs in the following example:</p>
<pre><code>Company Name: Ennis, Inc.
News: L D`ennis` Kozlowski, former chief executive convicted of looting nearly $100 million from Tyco International, has emerged into far more modest life after serving six-and-a-half year sentence and probation; Kozlowski, who became ultimate symbol of corporate greed in era that included scandals at Enron and WorldCom, describes his personal transformation and more humble pleasures that have replaced his once high-flying lifestyle.
</code></pre>
<p>Now you can see <code>Ennis</code> is matching with <code>Dennis</code> in the text so it giving irrelevant news results. </p>
<p>Can someone help in telling the right way of doing this ? Thanks.</p>
| 1 |
2016-09-24T20:22:07Z
| 39,680,694 |
<p>Use a regex with <a href="http://www.rexegg.com/regex-boundaries.html" rel="nofollow">boundaries</a> for exact matches whether you choose the full name or some partial part you think is unique is up to you but using word boundaries <code>D'ennis'</code> won't match <code>Ennis</code> :</p>
<pre><code>companies = ["name1", "name2",...]
companies_re = re.compile(r"|".join([r"\b{}\b".format(name) for name in companies]))
</code></pre>
<p>Depending on how many matches per news item, you may want to use <code>companies_re.search(artice)</code> or <code>companies_re.find_all(article)</code>.
Also for case insensitive matches pass <code>re.I</code> to compile.</p>
<p>If the only line you want to check is also always the one starting with company <code>company Name:</code> you can narrow down the search:</p>
<pre><code>for line in all_lines:
if line.startswith("company Name:"):
name = companies_re.search(line)
if name:
...
break
</code></pre>
| 1 |
2016-09-24T20:29:53Z
|
[
"python",
"python-3.x",
"machine-learning"
] |
Empty .mp4 file created after making video from matplotlib using matplotlib.animation
| 39,680,733 |
<p>I found this little code, and I am able to save a video (random colors changing in a grid) using it:</p>
<pre><code>import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import rand
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='xy'), bitrate=3600)
fig = plt.figure()
frames = []
for add in np.arange(15):
base = rand(10, 10)
frames.append((plt.pcolormesh(base, ),))
im_ani = animation.ArtistAnimation(fig, frames, interval=500, repeat_delay=3000,
blit=True)
im_ani.save('Vid.mp4', writer=writer)
</code></pre>
<p>I tried to insert it into my simulation, I get no errors, but the video is empty, the whole picture is white. Can you help me with that? This is the simplest case where I got it:</p>
<pre><code>class Dummy():
def __init__(self):
self.video=[]
def addFrame(self):
Frame=rand(10,10)
print (Frame)
self.video.append((plt.pcolormesh(Frame),))
def saveVideo(self):
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='XY'), bitrate=3600)
fig = plt.figure()
im_ani = animation.ArtistAnimation(fig, self.video, interval=500, repeat_delay=3000,
blit=True)
im_ani.save('myVid.mp4', writer=writer, dpi=dpi)
</code></pre>
<p>You can try it out:</p>
<pre><code>from scipy import rand
foo=Dummy()
for i in range(20):
foo.addFrame()
foo.saveVideo()
</code></pre>
| 2 |
2016-09-24T20:35:04Z
| 39,683,095 |
<p>Your <code>self.video.append((plt.pcolormesh(Frame),))</code> line is fine. You just changed the order of statements.</p>
<pre><code>import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
class Dummy():
def __init__(self, fname):
self.fname = fname
self.video = []
self.fig, self.ax = plt.subplots() # Create new figure here
def addFrame(self):
Frame = np.random.rand(10, 10)
self.video.append((self.ax.pcolormesh(Frame), ))
def saveVideo(self):
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='XY'), bitrate=3600)
im_ani = animation.ArtistAnimation(self.fig, self.video, interval=500,
repeat_delay=3000, blit=True)
im_ani.save(self.fname, writer=writer)
foo1 = Dummy('foo1.mp4')
for i in range(20):
foo1.addFrame()
foo1.saveVideo()
foo2 = Dummy('foo2.mp4')
for i in range(40):
foo2.addFrame()
foo2.saveVideo()
</code></pre>
| 1 |
2016-09-25T03:30:00Z
|
[
"python",
"numpy",
"video",
"matplotlib",
"simulation"
] |
Redirect error when trying to request a url with requests/urllib only in python
| 39,680,860 |
<p>im trying to post data to a url in my server ... but im stuck in sending any request to that url (any url on that server ) here is one for example </p>
<pre><code>http://apimy.in/page/test
</code></pre>
<p>the website is written in python3.4/django1.9</p>
<p>i can send request with <code>curl</code> in <code>php</code> without any problem </p>
<p>but any request with python will result on some kind of redirect error </p>
<p>at first i've tried <code>requests</code> lib </p>
<p>i got this error </p>
<pre><code>TooManyRedirects at /api/sender
Exceeded 30 redirects.
Request Method: GET
Request URL: http://localhost:8000/api/sender
Django Version: 1.9.6
Exception Type: TooManyRedirects
Exception Value:
Exceeded 30 redirects.
</code></pre>
<p>i thought maybe something wrong with <code>requests</code> so i tried <code>urllib</code> </p>
<pre><code>request_data = urllib.parse.urlencode({"DATA": 'aaa'}).encode()
response = urllib.request.urlopen("http://apimy.in/page/test" , data=request_data)
HTTPError at /api/sender
HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Found
Request Method: GET
Request URL: http://localhost:8000/api/sender
Django Version: 1.9.6
Exception Type: HTTPError
Exception Value:
HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Found
Exception Location: c:\Python344\lib\urllib\request.py in http_error_302, line 675
</code></pre>
<p>im using mod_wsgi and apache to serve the website </p>
| 1 |
2016-09-24T20:52:56Z
| 39,681,064 |
<p>Since you are using the <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> module did you try to tell the requests module to ignore redirects?</p>
<pre><code>import requests
response = requests.get('your_url_here', allow_redirects=False)
</code></pre>
<p>Maybe this work.
If this doesn't work, you can also try to change your <code>user-agent</code> in case your server is configured to drop <code>script-requests</code> for security reasons.</p>
<pre><code>import requests
headers = {'user-agent': 'some_user_agent'}
response = requests.get(url, headers=headers)
</code></pre>
| 0 |
2016-09-24T21:19:38Z
|
[
"python",
"django",
"redirect",
"curl",
"urllib"
] |
pelican: do not build specific article
| 39,680,887 |
<p>what's the best way to not build a page for a specific Pelican article?</p>
<p>I'm asking because I'm using some article pages mainly as metadata collections but I don't want them to have a specific page you can access.
For example I have a bunch of articles for portfolio clients which include metadata like the link to their logo, name of the client, the category of the job we did, etc... but there's not actual article I want to link to.</p>
<p>I tried to give them the Draft metadata or Hidden metadata but that way they do not show up when I iterate them in the relevant page.
I would like to be able to iterate them and access and use their metadata without building a webpage for them.</p>
<p>Thanks for your help.</p>
| 0 |
2016-09-24T20:55:25Z
| 39,700,238 |
<p>It's unclear to me what you're after, it sounds like what you really want is to be able to include data from a file into other articles? </p>
<p>If so, you could use the reStructuredText <a href="http://docutils.sourceforge.net/docs/ref/rst/directives.html#including-an-external-document-fragment" rel="nofollow">include</a> directive. Save the metadata files with an extension that won't be picked up by Pelican and then include them in all the pages where you want to use them.</p>
| 0 |
2016-09-26T10:19:07Z
|
[
"python",
"blogs",
"pelican"
] |
Accessing marshmallow decorators when using flask-marshmallow
| 39,680,910 |
<p>I'm using flask-restful, flask-sqlalchemy and flask-marshmallow to build an API service. I define the following -</p>
<pre><code>ma = Marshmallow(app)
</code></pre>
<p>However, trying to access the @validates decorator using ma throws an error.</p>
<pre><code>@ma.validates('field1')
</code></pre>
<p>What am I doing wrong? Is it better to directly use the marshmallow library and skip using flask-marshmallow altogether?</p>
| 0 |
2016-09-24T20:58:06Z
| 39,681,060 |
<p>The problem is that you are trying to reach <code>flask-marshmallow</code> decorators in its API, however there is none.</p>
<p>So you to understand if you need <code>flask-marshmallow</code> package, or only <code>marshmallow</code> is required.</p>
<p>Also to make things work, you need to use <a href="http://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.decorators.validates" rel="nofollow"><code>validates()</code></a> decorator as it presented in docs</p>
<pre><code>@validates('field1')
</code></pre>
| 0 |
2016-09-24T21:18:45Z
|
[
"python",
"flask-restful",
"marshmallow"
] |
?how to make a two dimensional matrix
| 39,681,055 |
<p>I have 1 dictionary and 1 tuple </p>
<pre><code> students = { 0: "Nynke", 1: "Lolle", 2: "Jikke", 3: "Popke", 4: "Teake", 5:
"Lieuwe", 6: "Tsjabbe", 7: "Klaske", 8: "Ypke", 9: "Lobke"}
friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5,
6), (5, 7), (6, 8), (7, 8), (8, 9)]
</code></pre>
<p>First thing I have to make is a 2-dimensional matrix wherein for each student a list with their friends like: [[1, 2], [0, 2, 3], ..., [8]]</p>
<p>the second thing is i have to sort the list based on the number of friends i have to print it like: [(9, 1), (0, 2), ..., (8, 3)].
number 9 has only 1 friend, number 0 has two friends etc...</p>
<p>my code:</p>
<pre><code>for i in students:
for x in friendships:
if students[i] == friendships(x):
new_list.append(x)
print(i)
</code></pre>
| -3 |
2016-09-24T21:17:26Z
| 39,681,116 |
<p>Not a 100% sure I understand exactly what you're trying to do, so correct me if I have the wrong idea. But here's what I think,</p>
<p>For the first one you can try creating a dictionary to store every friendships</p>
<pre><code>all_friends = {}
for f in friendships:
if f[0] in all_friends:
all_friends[f[0]] = all_friends[f[0]] + [f[1]]
else:
all_friends[f[0]] = [f[1]]
</code></pre>
<p>Then you'll want to get a list of this dictionaries values, and that'll be your 2d matrix:</p>
<pre><code>all_friends.values()
</code></pre>
<p>For the second one you will first need to keep track of how many friendships each person has, try a dictionary for this</p>
<pre><code>friendships_dict = {}
for f in friendships:
if f[0] in friendships_dict{}:
friendships_dict[f[0]] = friendships_dict[f[0]] + 1
else:
friendships_dict[f[0]] = 1
</code></pre>
<p>Then you'll want to make that a list of tuples that you can sort:</p>
<pre><code>friends_list = [(f1, f2) for f1, f2 in friendships_dict.iteritems()]
sorted_friends_list = sorted(friends_list, key=lambda x: x[1])
</code></pre>
<p><strong>EDIT</strong></p>
<p>Now that I better understand the first part of your question, let me go ahead and try to offer a solution.</p>
<p>You'll still want the first piece of code I included: </p>
<pre><code>all_friends = {}
for f in friendships:
if f[0] in all_friends:
all_friends[f[0]] = all_friends[f[0]] + [f[1]]
else:
all_friends[f[0]] = [f[1]]
</code></pre>
<p>Then add the following: </p>
<pre><code>matrix = []
for key in sorted(all_friends.iterkeys()):
matrix.append(all_friends[key])
</code></pre>
<p>And <code>matrix</code> will be what you wanted </p>
| 0 |
2016-09-24T21:26:15Z
|
[
"python"
] |
Import Error : ImapLibrary robotframework-RIDE
| 39,681,061 |
<p>I'm new to robotframwork. I'm able to work with Selenium2Library and other libraries. I tried to import the Imaplibrary after installation via pip it throws an error:</p>
<pre><code>[ ERROR ] Error in file 'C:\Users\prathod\Documents\automation\Registration.txt': Importing test library 'ImapLibrary' failed: ImportError: No module named builtins
Traceback (most recent call last):
File "ImapLibrary\__init__.py", line 30, in <module>
from builtins import str as ustr
PYTHONPATH:
C:\jython2.7.0\Lib
__classpath__
__pyclasspath__/
C:\jython2.7.0\Lib\site-packages
CLASSPATH:
C:\jython2.7.0\jython.jar
jars/Automaton-1.3.2-all-deps.jar
\Users\prathod\AppData\Local\Abcd\app\Abcd-jfx.jar
\Users\prathod\AppData\Local\Abcd\app\AbcdCore-jfx.jar
</code></pre>
<p>My environments are:<br>
Classpath : C:\ProgramFiles\Java\jdk1.8.0_101\jre\lib\ext*.jar<br>
C:\Program Files\Java\jdk1.8.0_101\jre\lib*.jar<br>
PATH : %JAVA_HOME%\bin, C:\Python27\, C:\Python27\Scripts C:\jython2.7.0\bin</p>
<p>I am not sure what's wrong. </p>
| 1 |
2016-09-24T21:19:07Z
| 39,734,466 |
<p>Try this</p>
<pre><code>pip install future --upgrade
</code></pre>
<p>then retry.</p>
| 0 |
2016-09-27T21:18:23Z
|
[
"python",
"jython",
"robotframework"
] |
Text arbitrarily not reading into buffer
| 39,681,101 |
<p>I'm trying to analyze philosophical and classic texts with the Watson Alchemy API, I'm having trouble with reading texts from a .txt file on my computer to a python variable.</p>
<p>Here is the code:</p>
<pre><code>from __future__ import print_function
from alchemyapi import AlchemyAPI
import argparse
import json
def conceptual(fileName):
path = "/Users/myname/Desktop/texts/"
name = path + fileName
with open(name, 'r') as myfile:
data=myfile.read().replace('\n', ' ')
if data != None:
print(data)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--concepts', dest = 'conceptFile', required = False)
args = parser.parse_args()
if args.conceptFile:
conceptual(args.conceptFile)
else:
print('Use CL args.')
main()
</code></pre>
<p>The issue is that for some texts it works fine: The entire .txt file prints out onto the terminal window. For others it prints something like this(for all the files that aren't working the output is very similar to this):</p>
<pre><code>. THE ENDy mountains. glowing and strong, like a
</code></pre>
<p>The end of that particular file (Zarauthstra_Nietzsche.txt) is </p>
<pre><code> Thus spake Zarathustra and left his cave, glowing and strong, like a
morning sun coming out of gloomy mountains.
THE END
</code></pre>
<p>But the rest of the file doesn't print.</p>
<p>I've been tinkering around with various differences, tweaking it here and there, but the only common thread to those that don't work seem to be that I downloaded them from a different website (<a href="http://philosophy.eserver.org/texts.htm" rel="nofollow">http://philosophy.eserver.org/texts.htm</a> not Project Gutenberg). I've tried changing the file's path, the contents, the permissions, the filenames. Any ideas?</p>
| 0 |
2016-09-24T21:24:41Z
| 39,681,263 |
<p>Turns out the \r characters in the file were somehow messing it up.</p>
<p>changed this line:<code>data=myfile.read().replace('\n', ' ')</code> to
<code>data=myfile.read().replace('\n', ' ').replace('\r', ' ')</code></p>
| 1 |
2016-09-24T21:46:13Z
|
[
"python"
] |
Cannot understand how this property on a model is being invoked
| 39,681,108 |
<p>I am going over a tutorial on extending a user model and it seems to work however I had 2 questions on how a property is being invoked and about a constructor. First this is the code in question</p>
<p>The main model is this</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
likes_cheese = models.BooleanField(default=True)
puppy_name = models.CharField(max_length=20)
User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])--->Statement A
</code></pre>
<p>Now the form which gets presented to the user is this</p>
<pre><code>class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('likes_cheese','puppy_name')
</code></pre>
<p>and the view that presents this form is as follows this is where my questions are (Over here i am simply interested in presenting the form so I removed the other code out):</p>
<pre><code>def user_profile(request):
display_page = "profile.html"
csrf_token = csrf(request)
args={}
user = request.user
profile = user.profile ---------------------->statement B - Question 1 below
form = UserProfileForm(instance=profile) ------->statement C - Question 2 below
args.update(csrf_token)
args["form"] = form
return render_to_response(display_page,args)
</code></pre>
<p>Now here are my two questions </p>
<p>Q1- Why isnt a parameter being passed to the property <code>profile</code> of <code>User</code> object ?</p>
<p>from what I understand from statement A which is </p>
<pre><code> User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])
</code></pre>
<p>is that profile is being defined as a property of User and that it has a setter function which is a lambda that takes a parameter. Where is that parameter being passed ? All i see is this (A parameter to the property is not being passed anywhere that I can see)</p>
<pre><code> profile = user.profile
form = UserProfileForm(instance=profile)
</code></pre>
<p>Q2-In the code <code>form = UserProfileForm(instance=profile)</code> we are passing in an instance as a parameter but my UserProfileForm does not have a constructor ? What is happening here.</p>
<p>Thanks in advance</p>
| 0 |
2016-09-24T21:25:19Z
| 39,681,156 |
<p><strong>Q1</strong>: Because you are using django predefined <code>User</code> class you have two options to add new property(to inherit <code>User</code> model and say django to use it for just adding new property), or just do it like you did.</p>
<p>When you call <code>user.profile</code> you already passing <code>user</code> as a parameter, so that <code>lambda</code> does <code>UserProfile.objects.get_or_create(user=user)[0]</code></p>
<p><strong>Q2</strong>: Your <code>UserProfileForm</code> inherit from <code>forms.ModelForm</code> which already has a constructor. And you can pass <code>instance</code> argument, so that form would be populated with model data(<code>UserProfile</code>).</p>
<p><code>django.forms.ModelForm</code> at the same moment inherit from <code>django.forms.models.BaseModelForm</code> and in <code>__init__</code> it checks if <code>instance</code> keyword argument is provided and populates form as follows, from <a href="https://docs.djangoproject.com/en/1.10/_modules/django/forms/models/#ModelForm" rel="nofollow">source</a></p>
<pre><code>if instance is None:
# if we didn't get an instance, instantiate a new one
self.instance = opts.model()
object_data = {}
</code></pre>
| 2 |
2016-09-24T21:31:04Z
|
[
"python",
"django",
"django-models",
"lambda",
"django-forms"
] |
Why is QColorDialog.getColor crashing unexpectedly?
| 39,681,109 |
<p>I got this little 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):
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)
color = QtWidgets.QColorDialog.getColor()
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")
def show_requirements():
print(sys.version)
print(QtCore.QT_VERSION_STR)
print(QtCore.PYQT_VERSION_STR)
if __name__ == "__main__":
show_requirements()
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>For some unknown reason, when I press OK after picking up a color the script will crash unexpectedly, here's a <a href="http://screencast.com/t/ZDoxPAWjmkdH" rel="nofollow">video</a> showing what I mean.</p>
<p>Any idea why this would happen?</p>
| 0 |
2016-09-24T21:25:23Z
| 39,681,886 |
<p>Opening a dialog with a blocking <code>exec()</code> inside the cursor-change handler seems like a bad idea, so I'm not surprised it crashes. It will be much safer to open the dialog asynchronously and use a signal/slot to handle the result. Using a closure with <code>show()</code> would seem best, as it will give access to the current local variables:</p>
<pre><code>class SimpleEditor(QsciScintilla):
def __init__(self, language=None, parent=None):
super().__init__(parent)
...
self.colors = QtWidgets.QColorDialog(self)
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
def handler():
print(message)
print(self.colors.selectedColor().name())
self.colors.finished.disconnect()
self.colors.finished.connect(handler)
self.colors.show()
break
</code></pre>
| 1 |
2016-09-24T23:23:19Z
|
[
"python",
"python-3.x",
"pyqt"
] |
Python code output isn't displaying properly
| 39,681,132 |
<p>My code seems fine but when i run it and input the sales it wont show the commission.</p>
<p><img src="http://i.stack.imgur.com/J7NyF.png" alt="picture"></p>
<p>this is python btw.</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>keep_going = "y"
while keep_going == "y":
sales = float(input("Enter the amount of sales: "))
comm_rate = 10
commission = sales * comm_rate
print ("The commission is: "),commission
keep_going = input("Do you want to calculate another commission? (Enter y for yes): ")
main()</code></pre>
</div>
</div>
</p>
| -1 |
2016-09-24T21:27:50Z
| 39,681,148 |
<p>Change:</p>
<pre><code>print ("The commission is: "),commission
</code></pre>
<p>To:</p>
<pre><code>print ("The commission is: ", commission)
</code></pre>
| 1 |
2016-09-24T21:30:17Z
|
[
"python",
"output",
"modular"
] |
Scrapy: populate items with item loaders over multiple pages
| 39,681,269 |
<p>I'm trying to crawl and scrape multiple pages, given multiple urls. I am testing with Wikipedia, and to make it easier I just used the same Xpath selector for each page, but I eventually want to use many different Xpath selectors unique to each page, so each page has its own separate parsePage method. </p>
<p>This code works perfectly when I don't use item loaders, and just populate items directly. When I use item loaders, the items are populated strangely, and it seems to be completely ignoring the callback assigned in the parse method and only using the start_urls for the parsePage methods.</p>
<pre><code>import scrapy
from scrapy.http import Request
from scrapy import Spider, Request, Selector
from testanother.items import TestItems, TheLoader
class tester(scrapy.Spider):
name = 'vs'
handle_httpstatus_list = [404, 200, 300]
#Usually, I only get data from the first start url
start_urls = ['https://en.wikipedia.org/wiki/SANZAAR','https://en.wikipedia.org/wiki/2016_Rugby_Championship','https://en.wikipedia.org/wiki/2016_Super_Rugby_season']
def parse(self, response):
#item = TestItems()
l = TheLoader(item=TestItems(), response=response)
#when I use an item loader, the url in the request is completely ignored. without the item loader, it works properly.
request = Request("https://en.wikipedia.org/wiki/2016_Rugby_Championship", callback=self.parsePage1, meta={'loadernext':l}, dont_filter=True)
yield request
request = Request("https://en.wikipedia.org/wiki/SANZAAR", callback=self.parsePage2, meta={'loadernext1': l}, dont_filter=True)
yield request
yield Request("https://en.wikipedia.org/wiki/2016_Super_Rugby_season", callback=self.parsePage3, meta={'loadernext2': l}, dont_filter=True)
def parsePage1(self,response):
loadernext = response.meta['loadernext']
loadernext.add_xpath('title1', '//*[@id="firstHeading"]/text()')
return loadernext.load_item()
#I'm not sure if this return and load_item is the problem, because I've tried yielding/returning to another method that does the item loading instead and the first start url is still the only url scraped.
def parsePage2(self,response):
loadernext1 = response.meta['loadernext1']
loadernext1.add_xpath('title2', '//*[@id="firstHeading"]/text()')
return loadernext1.load_item()
def parsePage3(self,response):
loadernext2 = response.meta['loadernext2']
loadernext2.add_xpath('title3', '//*[@id="firstHeading"]/text()')
return loadernext2.load_item()
</code></pre>
<p>Here's the result when I don't use item loaders:</p>
<pre><code>{'title1': [u'2016 Rugby Championship'],
'title': [u'SANZAAR'],
'title3': [u'2016 Super Rugby season']}
</code></pre>
<p>Here's the a bit of the log with item loaders:</p>
<pre><code>{'title2': u'SANZAAR'}
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/2016_Rugby_Championship> (referer: https://en.wikipedia.org/wiki/SANZAAR)
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/2016_Rugby_Championship> (referer: https://en.wikipedia.org/wiki/2016_Rugby_Championship)
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/2016_Super_Rugby_season>
{'title2': u'SANZAAR', 'title3': u'SANZAAR'}
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/SANZAAR> (referer: https://en.wikipedia.org/wiki/2016_Rugby_Championship)
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/2016_Rugby_Championship> (referer: https://en.wikipedia.org/wiki/2016_Super_Rugby_season)
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/2016_Super_Rugby_season> (referer: https://en.wikipedia.org/wiki/2016_Rugby_Championship)
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/2016_Super_Rugby_season> (referer: https://en.wikipedia.org/wiki/2016_Super_Rugby_season)
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/2016_Rugby_Championship>
{'title1': u'SANZAAR', 'title2': u'SANZAAR', 'title3': u'SANZAAR'}
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/2016_Rugby_Championship>
{'title1': u'2016 Rugby Championship'}
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/SANZAAR>
{'title1': u'2016 Rugby Championship', 'title2': u'2016 Rugby Championship'}
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/2016_Rugby_Championship>
{'title1': u'2016 Super Rugby season'}
2016-09-24 14:30:43 [scrapy] DEBUG: Crawled (200) <GET https://en.wikipedia.org/wiki/SANZAAR> (referer: https://en.wikipedia.org/wiki/2016_Super_Rugby_season)
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/2016_Super_Rugby_season>
{'title1': u'2016 Rugby Championship',
'title2': u'2016 Rugby Championship',
'title3': u'2016 Rugby Championship'}
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/2016_Super_Rugby_season>
{'title1': u'2016 Super Rugby season', 'title3': u'2016 Super Rugby season'}
2016-09-24 14:30:43 [scrapy] DEBUG: Scraped from <200 https://en.wikipedia.org/wiki/SANZAAR>
{'title1': u'2016 Super Rugby season',
'title2': u'2016 Super Rugby season',
'title3': u'2016 Super Rugby season'}
2016-09-24 14:30:43 [scrapy] INFO: Clos
</code></pre>
<p>What exactly is going wrong? Thanks!</p>
| 0 |
2016-09-24T21:47:26Z
| 39,681,398 |
<p>One issue is that you're passing multiple references of <em>a same item loader instance</em> into multiple callbacks, e.g. there are two <code>yield request</code> instructions in <code>parse</code>.</p>
<p>Also, in the following-up callbacks, the loader is still using the old <code>response</code> object, e.g. in <code>parsePage1</code> the item loader is still operating on the <code>response</code> from <code>parse</code>.</p>
<p>In most of the cases it is not suggested to pass item loaders to another callback. Alternatively, you might find it better to pass item objects directly.</p>
<p>Here's a short (and incomplete) example, by editing your code:</p>
<pre><code>def parse(self, response):
l = TheLoader(item=TestItems(), response=response)
request = Request(
"https://en.wikipedia.org/wiki/2016_Rugby_Championship",
callback=self.parsePage1,
meta={'item': l.load_item()},
dont_filter=True
)
yield request
def parsePage1(self,response):
loadernext = TheLoader(item=response.meta['item'], response=response)
loadernext.add_xpath('title1', '//*[@id="firstHeading"]/text()')
return loadernext.load_item()
</code></pre>
| 1 |
2016-09-24T22:07:21Z
|
[
"python",
"scrapy"
] |
Kivy custom widget instanciated twice
| 39,681,281 |
<p>I'm trying to build a simple Kivy custom widget containing two sliders.
When the screen is rendered I get two pairs of sliders instead of one.</p>
<p>What am I doing wrong ?</p>
<p><strong>Main.kv:</strong></p>
<pre><code>ScreenManagement:
MainScreen:
<Button>:
size_hint: .2, .1
font_size: 20
<Mixer>:
orientation:'vertical'
Slider:
min:0
max:127
value:64
Slider:
min:0
max:127
value:100
<MainScreen>:
name: "mainscreen"
Mixer:
FloatLayout:
Button:
text: "Exit"
pos: root.width - self.width, 0
on_release: app.stop()
</code></pre>
<p><strong>Main.py:</strong></p>
<pre><code>import kivy
kivy.require("1.9.1")
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
class ScreenManagement(ScreenManager):
pass
class Mixer(BoxLayout):
pass
class MainScreen(Screen):
pass
class MainApp(App):
def build(self):
return Builder.load_file("Main.kv")
if __name__ == "__main__":
MainApp().run()
</code></pre>
<p>Thanks for your help !</p>
| 0 |
2016-09-24T21:50:34Z
| 39,708,529 |
<p>You should rename the kv file to <code>main.kv</code>, and delete the explicit load of it in <code>build</code> method. It is going to load itself automatically. The bug is weird, maybe worth a ticket.</p>
| 0 |
2016-09-26T17:07:10Z
|
[
"python",
"user-interface",
"kivy"
] |
Import Django model class in Scrapy project
| 39,681,337 |
<p>I have a django project and a scrapy project</p>
<p>and I want to import django model from to scrapy project.</p>
<p>This is my spider:</p>
<pre><code>import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
import sys
sys.path.append('/home/ubuntu/venv/dict')
from dmmactress.models import EnActress
class JpnNameSpider(scrapy.Spider):
name = jp_name
allowed_domains = ['enjoyjapan.co.kr']
rx = EnActress.objects.values_list('name', flat=True)
rxs = rx.reverse()
start_urls = ['http://enjoyjapan.co.kr/how_to_read_japanese_name.php?keyword=%s' % jp for jp in rxs]
def parse(self, response):
for sel in response('//*[@id="contents"]/div/div[1]/div/div[1]'):
item = JapanessItem()
item['koname'] = sel.xpath('div[4]/div[1]()/text()').extract()
item['jpname'] = sel.xpath('div[2]/div[1]()/text()').extract()
yield item
next_page = response.css('#contents > div > div:nth-child(4) > div > a::attr(href)').extract_first()
if naxt_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, self.parse)
</code></pre>
<p>and I got error when I ran spider</p>
<pre><code>django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configure.
</code></pre>
<p>-- Can someone help me to see what I am doing wrong?</p>
<p>Thanks in advance!</p>
| 0 |
2016-09-24T21:58:43Z
| 39,681,577 |
<p>You need to <a href="https://docs.djangoproject.com/en/1.10/ref/applications/#initialization-process" rel="nofollow">initialize Django </a> before using models outside the context of Django apps:</p>
<pre><code>import django
django.setup()
</code></pre>
| 1 |
2016-09-24T22:36:20Z
|
[
"python",
"django",
"scrapy"
] |
"len(sys.argv) < 2" not satisfied even when command called with only one argument
| 39,681,347 |
<pre><code>#! /usr/bin/python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'aklsjdlksajdkljl',
'blog': 'dklasjkl9379343',
'luggage': '12345'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python ' + sys.argv[0] + ' [' + sys.argv[1] + '] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + " " + sys.argv[0] + " " + sys.argv[1] + ' copied to clipboard.')
else:
print('There is no account named ' + account)
</code></pre>
<p>When I type <code>./pw.py email</code> in terminal, it will go straight to the line: <code>if account in PASSWORDS:</code> and will skip line: <code>if len(sys.argv) < 2:</code></p>
<p>Why did it skip that line?</p>
| -1 |
2016-09-24T21:59:23Z
| 39,681,370 |
<p>If <code>sys.argv[1]</code> is defined, the length of <code>sys.argv</code> is 2 or greater. The test <code>sys.argv < 2</code> is only going to be true when <code>sys.argv</code> contains just 0 or 1 items. So the <code>if len(sys.argv) < 2:</code> is not skipped, the test is just <em>false</em> and the associated block is not executed.</p>
<p><code>sys.argv[0]</code> is always set to the script name (here <code>pw.py</code>), so the length would be at least 1.</p>
<p>Note that you just used <code>python pw.py</code> (so no account or other arguments), you'd get an index error, as the following line tries to index to <code>sys.argv[1]</code>, a value that is <em>not set</em>:</p>
<pre><code>print('Usage: python ' + sys.argv[0] + ' [' + sys.argv[1] + '] - copy account password')
# This raises an index error when len(sys.argv) < 2 ^^^
</code></pre>
| 1 |
2016-09-24T22:02:48Z
|
[
"python"
] |
Parse only text within a div class python
| 39,681,359 |
<p>so what I wanna do is from reading the source code, search for the div class named "gsc_prf_il", then within this div class, extract only the text, ignoring the href link. e.g. </p>
<pre><code><div class="gsc_prf_il"><a href="/citations?view_op=view_org&hl=en&org=13784427342582529234">McGill University</a></div>
</code></pre>
<p>But when I use this code, it doesn't work, only gives me error: AttributeError: 'NoneType' object has no attribute 'contents'</p>
<pre><code>soup=BeautifulSoup(p.readlines()[0], 'html.parser')
s=soup.find(id='gsc_prf_il')
scholar_info['department']= s.contents
</code></pre>
<p>So then I tried this: </p>
<pre><code>scholar_info['department']=[s.find('a')['href'], s.find('a').contents[0]]
</code></pre>
<p>It doesn't work either. What am I doing wrong? </p>
| 1 |
2016-09-24T22:01:44Z
| 39,690,485 |
<p>Just find the <em>div</em> and pull the text, you are looking for <code>soup.find(id='gsc_prf_il')</code> which is looking for an element with an <code>id</code> of <code>gsc_prf_il</code> not a div with that class:</p>
<pre><code>from bs4 import BeautifulSoup
url = "http://python-data.dr-chuck.net/comments_283660.html"
soup = BeautifulSoup("""<div class="gsc_prf_il"><a href="/citations?view_op=view_org&hl=en&org=13784427342582529234">McGill University</a></div>""")
</code></pre>
<p>So use <code>class_="gsc_prf_il"</code>:</p>
<pre><code>print(soup.find("div", class_="gsc_prf_il").text) -> McGill University
</code></pre>
<p>Or use a css selector:</p>
<pre><code>print(soup.select_one("div.gsc_prf_il").text) -> McGill University
</code></pre>
| 1 |
2016-09-25T18:42:14Z
|
[
"python",
"python-2.7",
"beautifulsoup",
"html-parsing"
] |
Smarter way to gather data or a way to sort the data
| 39,681,360 |
<p>I'm pulling data from an sqlite table using <code>snip1</code>, this of course grabs each row containing the relevant <code>id</code> value. The <code>services</code> list now looks like <code>output1</code>.</p>
<p>I'd like to be able to sort the list of lists of tuples into a more managable data set. Merging all relevant id sets.
For example <code>[(10, u'80'), (10, u'443')]</code> becomes <code>{10: 80, 443}</code> and of course all other entries added to the same <code>dict</code>.</p>
<p>I'm having a hard time sorting the data. How would I compare items in the same list? The <code>example1</code> below shows the data cleaned up, but I'm uncertain on how to achieve a clean dictionary from it.</p>
<p><strong>snip1</strong></p>
<pre><code>c.execute('SELECT * FROM services WHERE id=?', (id_value,))
services = c.fetchall()
</code></pre>
<p><strong>output1</strong></p>
<pre><code>[[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
</code></pre>
<p><strong>example1</strong></p>
<pre><code>data = [(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
for item in data:
for i in item:
print i #output2
</code></pre>
<p><strong>output2</strong></p>
<pre><code>(2, u'22')
(3, u'25')
(4, u'443')
(5, u'443')
(6, u'443')
(7, u'22')
(8, u'80')
(9, u'443')
(10, u'80')
(10, u'443')
(11, u'80')
(11, u'443')
(12, u'80')
(12, u'443')
(13, u'443')
(14, u'80')
(14, u'443')
(15, u'25')
</code></pre>
| 1 |
2016-09-24T22:01:45Z
| 39,681,453 |
<pre><code>d = {}
for item in data:
d[item[0][0]] = []
for i in item:
d[i[0]] = d[i[0]] + [int(i[1])]
</code></pre>
| 1 |
2016-09-24T22:17:52Z
|
[
"python",
"dictionary"
] |
Smarter way to gather data or a way to sort the data
| 39,681,360 |
<p>I'm pulling data from an sqlite table using <code>snip1</code>, this of course grabs each row containing the relevant <code>id</code> value. The <code>services</code> list now looks like <code>output1</code>.</p>
<p>I'd like to be able to sort the list of lists of tuples into a more managable data set. Merging all relevant id sets.
For example <code>[(10, u'80'), (10, u'443')]</code> becomes <code>{10: 80, 443}</code> and of course all other entries added to the same <code>dict</code>.</p>
<p>I'm having a hard time sorting the data. How would I compare items in the same list? The <code>example1</code> below shows the data cleaned up, but I'm uncertain on how to achieve a clean dictionary from it.</p>
<p><strong>snip1</strong></p>
<pre><code>c.execute('SELECT * FROM services WHERE id=?', (id_value,))
services = c.fetchall()
</code></pre>
<p><strong>output1</strong></p>
<pre><code>[[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
</code></pre>
<p><strong>example1</strong></p>
<pre><code>data = [(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
for item in data:
for i in item:
print i #output2
</code></pre>
<p><strong>output2</strong></p>
<pre><code>(2, u'22')
(3, u'25')
(4, u'443')
(5, u'443')
(6, u'443')
(7, u'22')
(8, u'80')
(9, u'443')
(10, u'80')
(10, u'443')
(11, u'80')
(11, u'443')
(12, u'80')
(12, u'443')
(13, u'443')
(14, u'80')
(14, u'443')
(15, u'25')
</code></pre>
| 1 |
2016-09-24T22:01:45Z
| 39,681,538 |
<p>You can do this with one line with using <code>dict</code> and <code>list</code> comprehensions</p>
<pre><code>>>> data = [[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
>>> output = {record[0][0]: [int(item[1]) for item in record] for record in data}
>>> output
{2: [22],
3: [25],
4: [443],
5: [443],
6: [443],
7: [22],
8: [80],
9: [443],
10: [80, 443],
11: [80, 443],
12: [80, 443],
13: [443],
14: [80, 443],
15: [25]}
</code></pre>
| 1 |
2016-09-24T22:30:53Z
|
[
"python",
"dictionary"
] |
Smarter way to gather data or a way to sort the data
| 39,681,360 |
<p>I'm pulling data from an sqlite table using <code>snip1</code>, this of course grabs each row containing the relevant <code>id</code> value. The <code>services</code> list now looks like <code>output1</code>.</p>
<p>I'd like to be able to sort the list of lists of tuples into a more managable data set. Merging all relevant id sets.
For example <code>[(10, u'80'), (10, u'443')]</code> becomes <code>{10: 80, 443}</code> and of course all other entries added to the same <code>dict</code>.</p>
<p>I'm having a hard time sorting the data. How would I compare items in the same list? The <code>example1</code> below shows the data cleaned up, but I'm uncertain on how to achieve a clean dictionary from it.</p>
<p><strong>snip1</strong></p>
<pre><code>c.execute('SELECT * FROM services WHERE id=?', (id_value,))
services = c.fetchall()
</code></pre>
<p><strong>output1</strong></p>
<pre><code>[[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
</code></pre>
<p><strong>example1</strong></p>
<pre><code>data = [(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
for item in data:
for i in item:
print i #output2
</code></pre>
<p><strong>output2</strong></p>
<pre><code>(2, u'22')
(3, u'25')
(4, u'443')
(5, u'443')
(6, u'443')
(7, u'22')
(8, u'80')
(9, u'443')
(10, u'80')
(10, u'443')
(11, u'80')
(11, u'443')
(12, u'80')
(12, u'443')
(13, u'443')
(14, u'80')
(14, u'443')
(15, u'25')
</code></pre>
| 1 |
2016-09-24T22:01:45Z
| 39,681,562 |
<p>To convert a list of tuples into a dictionary:</p>
<pre><code> list = [(10, u'80'), (10, u'443')]
dict = {}
for (i, j) in list:
dict.setdefault(i, []).append(j)
</code></pre>
<p>This will give you:</p>
<pre><code> >>> dict
{10: [u'80', u'443']}
</code></pre>
<p>You can then use pprint to print in a way that it is easy to compare dictionary items. </p>
<pre><code> import pprint
pprint.pprint(dict)
</code></pre>
<p>The example only has one key but pprint will make a new row for each key similiar to what you have up there.</p>
| 1 |
2016-09-24T22:34:28Z
|
[
"python",
"dictionary"
] |
Which is faster in Python: if or try
| 39,681,373 |
<p>Please consider the following code:</p>
<pre><code>def readPath(path):
content = None
if os.path.isfile(path):
f = open(path,"rb")
content = f.read()
f.close()
return content
</code></pre>
<p>versus this one:</p>
<pre><code>def readPath(path):
content = None
try:
f = open(path,"rb")
content = f.read()
f.close()
except:
pass
return content
</code></pre>
<p>Given that the def is called many (hundreds to thousands times) in succession, mostly with valid paths (that represent actual files on the file system) but sometimes with non existent paths, which version is more efficient? Is checking a condition prior to opening the file is slower than setting a try block?</p>
| 0 |
2016-09-24T22:03:20Z
| 39,681,409 |
<p>Usually, the answer to "whichever to use, <code>if</code> or <code>try</code>", the answer is <strong>EAFP</strong> - it is easier to ask for forgiveness than permission, thus always prefer <code>try</code> over <code>if</code>. However, in this case, neither EAFP nor performance considerations shouldn't be reason to choose one over another. Instead you should choose the one that is correct.</p>
<p>Using <code>isfile</code> because it makes your code prone to race conditions. Suppose someone removes the file just after you called <code>isfile</code> and before you actually opened it - and you would get a spurious exception. However, there have been countless of security bugs because of code that first checks for existence, permissions, ownership or so on, of a file, and then open it - an attacker may change the file that the link is pointing to in between.</p>
<p>Furthermore, there are other reasons why <code>open</code> would fail than just the file not existing:</p>
<pre><code>>>> os.path.isfile('/etc/shadow')
True
>>> open('/etc/shadow')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: '/etc/shadow'
</code></pre>
<p><code>isfile</code> also amounts to an <em>extra</em> system call and that in itself is more expensive than catching an exception; just doing the system call alone makes the overhead of catching an exception minuscule in comparison. As you have stated that you expect most of the file names to actually exist, the time spent in <code>isfile</code> is just extra overhead.</p>
<p>I did some timings with Python 3 on Ubuntu 16.04, and <code>os.path.isfile</code> for a non-existent file took <code>/etc/foo</code> ~2 µs (it is actually faster for an existing file <code>/etc/passwd</code>, 1.8 µs); trying to open a non-existent file and failing and catching the <code>IOError</code> took ~3 µs - so checking for the existence of a file using <code>os.path.isfile</code> is faster than checking for its existence using <code>open</code>; but that's not what your code needs to do: it needs to read the contents of a file that can be read, and return its contents, and for that, if 66 % of the files are expected to exist, then <code>open</code> without checking is absolutely faster than using <code>isfile</code> to check first, so this should be a no-brainer.</p>
<hr>
<p>P.S: your code possibly leaks an open file on other Pythons than CPython, and is unnecessarily complicated. Using the <code>with</code> block, this becomes much cleaner:</p>
<pre><code>def read_path(path):
try:
with open(path, "rb") as f:
return f.read()
except IOError:
return None
</code></pre>
| 6 |
2016-09-24T22:09:48Z
|
[
"python"
] |
Sorting an XML file based on node value
| 39,681,434 |
<p>I was trying to compare two XML files which have same content but on different lines at times. To overcome this, I was trying to sort the XMLs on one of the child nodes (which usually differs in position in both files).</p>
<p>Here is my sample XML file</p>
<pre><code><Report>
<rptName>Sample</rptName>
<reportNameGrp>
<grpName>AggrDataSet</grpName>
<RC>
<rptSubHdr>
<membLglNam>Registered Customer 103</membLglNam>
<membId>RC103</membId>
<relCM>CM022</relCM>
</rptSubHdr>
</RC>
<RC>
<rptSubHdr>
<membLglNam>Registered Customer 055</membLglNam>
<membId>RC055</membId>
<relCM>CM022</relCM>
</rptSubHdr>
</RC>
<RC>
<rptSubHdr>
<membLglNam>Registered Customer 047</membLglNam>
<membId>RC047</membId>
<relCM>CM022</relCM>
</rptSubHdr>
</RC>
<RC>
<rptSubHdr>
<membLglNam>Registered Customer 015</membLglNam>
<membId>RC015</membId>
<relCM>CM022</relCM>
</rptSubHdr>
</RC>
<RC>
<rptSubHdr>
<membLglNam>Registered Customer 024</membLglNam>
<membId>RC024</membId>
<relCM>CM022</relCM>
</rptSubHdr>
</RC>
</reportNameGrp>
</Report>
</code></pre>
<p>I am trying to sort based on <code><membId></code> node for <code><RC></code> parent node. Whatever method I try, my document fails to sort. I tried using XSLT, but sorting doesn't work. I even tried writing a python script but it fails to sort.</p>
<p>Here is my python script - </p>
<pre><code>import sys
from lxml import etree
filename, tag = sys.argv[1:]
doc = etree.parse(filename, etree.XMLParser(remove_blank_text=True))
root = doc.getroot()
root[:] = sorted(root, key=lambda el: el.findtext(tag))
print etree.tostring(doc, pretty_print=True)
</code></pre>
<p>I execute <code>python test.py 2.xml membId</code> to run the script (please note that 2.xml is file name for input xml and membId is the tag I was looking for).</p>
<p>I will really appreciate any help in where I am going wrong. I am just starting with Python, so I might have made some pretty obvious mistake. A python script or XSLT solution (either) will work for me!</p>
| -1 |
2016-09-24T22:14:35Z
| 39,681,680 |
<p>Consider the following XSLT script with Python's <code>lxml</code> integration. Also, you attempt to run a dynamic command line process. Unfortunately, the XSLT will structurally change depending on what specific node you intend to sort. Below will specifically sort <code><membId></code> in ascending order:</p>
<p><strong>XSLT</strong></p>
<pre><code><xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>
<!-- Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Sort MembId under RC/rptSubHdr -->
<xsl:template match="reportNameGrp">
<xsl:copy>
<xsl:copy-of select="grpName"/>
<xsl:apply-templates select="RC">
<xsl:sort select="rptSubHdr/membId" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:transform>
</code></pre>
<p><strong>Python</strong></p>
<pre><code>import lxml.etree as et
// LOAD XML AND XSL SOURCES
dom = et.parse('Input.xml')
xslt = et.parse('XSLTScript.xsl')
// TRANSFORM
transform = et.XSLT(xslt)
newdom = transform(dom)
// SAVE TO FILE
with open('Output.xml', 'wb') as f:
f.write(newdom)
</code></pre>
| 2 |
2016-09-24T22:52:14Z
|
[
"python",
"xml",
"python-2.7",
"xslt",
"xslt-2.0"
] |
random.randrange does not seem quite random
| 39,681,473 |
<p>I am pretty new to python so i dont know many things.
So lets say i got this piece of code </p>
<pre><code>for i in range(10000):
n = random.randrange(1, 1000**20)
ar.append(n)
print(n)
</code></pre>
<p>The smallest number i get out of the 10000 is always 3-4 digits smaller than 1000^20
in this particular example the smallest numbers are</p>
<pre><code>2428677832187681074801010996569419611537028033553060588
8134740394131686305349870676240657821649938786653774568
44697837467174999512466010709212980674765975179401904173
50027463313770628365294401742988068945162971582587075902
61592865033437278850861444506927272718324998780980391309
71066003554034577228599139472327583180914625767704664425
90125804190638177118373078542499530049455096499902511032
100371114393629537113796511778272151802547292271926376588
</code></pre>
<p>i have tried multiple ranges on multiple occasions and every time i get the same results.Maybe i am doing something wrong?</p>
| -2 |
2016-09-24T22:21:14Z
| 39,681,610 |
<p>Okay, so let's use small numbers to illustrate that clearly.</p>
<p>Suppose you pick a random number from 1 to 100, inclusively.</p>
<p>How many 1 digit numbers are there? 9, from 1 to 9. For 2 digits it's from 10 to 99, 90 numbers. For 3 digits it's just 1, 100. Since it's a random pick, the probability of picking one of those 100 (9 + 90 + 9) numbers is equal, and it should be intuitively clear it's 1/100. But since there are 90 2-digit numbers, the probability of picking a 2-digit number is 90/100, or 9/10. For 1-digit numbers it's 9/100, and for the only 3-digit one it's 1/100.</p>
<p>I hope that answers the question.</p>
| 1 |
2016-09-24T22:41:39Z
|
[
"python",
"random"
] |
Time localized wrongly in Python
| 39,681,474 |
<p>Using python Im trying to localize a datetime value to timezone "America/Chicago" which is -06:00 currently.
I get the timezone the following way:</p>
<pre><code>>>> import pytz
>>> tz = pytz.timezone("America/Chicago")
<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>
</code></pre>
<p>when I localize a date:</p>
<pre><code>>>> my_date = tz.localize(datetime.now())
datetime.datetime(2016, 9, 24, 17, 4, 43, 439824, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>)
</code></pre>
<p>Notice it is the wrong timezone after localize:</p>
<pre><code><DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>
</code></pre>
<p>And later when i ask for the offset, you can see it is confirmed it has the wrong offset: </p>
<pre><code>>>> my_date.strftime("%z")
'-0500'
</code></pre>
<p>Exactly the same happend if I use astimezone instead:</p>
<pre><code>>>>my_date
datetime.datetime(2016, 9, 24, 22, 15, 1, 620364, tzinfo=<UTC>)
>>>my_date.astimezone(tz)
datetime.datetime(2016, 9, 24, 17, 15, 1, 620364, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>)
</code></pre>
| 0 |
2016-09-24T22:21:17Z
| 39,682,969 |
<p>Btw Chicago is observing DST now. So -05.00 is the right offset. Pytz timezone by default has the standard time, but when localized can account for day light saving based on the date(as in your case).</p>
| 1 |
2016-09-25T03:01:30Z
|
[
"python",
"python-2.7",
"datetime",
"localization"
] |
Python - Only printing 'PRINT'
| 39,681,504 |
<p>I am trying to make my own basic programming language. I have the following code in my <code>smrlang.py</code> file</p>
<pre><code>from sys import *
tokens = []
def open_file(filename):
data = open(filename, "r").read()
return data
def smr(filecontents):
tok = ""
state = 0
string = ""
filecontents = list(filecontents)
for char in filecontents:
tok += char
if tok == " ":
if state == 0:
tok = ""
else:
tok = " "
elif tok == "PRINT":
tokens.append("PRINT")
tok = ""
elif tok == "\"":
if state == 0:
state = 1
elif state == 1:
print("STRING")
string = ""
state = 0
elif state == 1:
string += tok
print(tokens)
def run():
data = open_file(argv[1])
smr(data)
run()
</code></pre>
<p>And I have this in my <code>one.smr</code> file:</p>
<pre><code>PRINT "HELLO WORLD"
</code></pre>
<p>The output should be something like <code>PRINT STRING</code>, but when I use the command <code>python3 smrlang.py one.smr</code>, the output is just <code>PRINT</code>. I am using Python 3</p>
| -1 |
2016-09-24T22:26:28Z
| 39,681,621 |
<p>Debugging it in the head, I found the problem:</p>
<pre><code>elif state == 1:
string += tok
</code></pre>
<p>You don't reset the token here. It will be <code>aababcabcd</code> instead of <code>abcd</code> and recognizing <code>\</code> won't work (as it will be <code>aababcabcd\</code>).</p>
<p>This also causes the token to just be everything and it will never print.</p>
<p>Try changing it to:</p>
<pre><code>elif state == 1:
string += tok
tok = ""
</code></pre>
<p>Output after fix:</p>
<pre><code>> py -3 temp.py temp.txt
STRING
['PRINT']
</code></pre>
| 0 |
2016-09-24T22:43:10Z
|
[
"python"
] |
Django app has a no ImportError: No module named 'django.core.context_processors'
| 39,681,560 |
<p>Tried git pushing my app after tweaking it and got the following error.</p>
<pre><code>ImportError: No module named 'django.core.context_processors'
</code></pre>
<p>this was not showing up in my heroku logs and my app works locally so I was confused. I had to set debug to true on the production side to finally figure this out. What can I do to clear this up?</p>
<p>this is some of the traceback</p>
<pre><code>Request Method: GET
Request URL: http://hispanicheights.com/
Django Version: 1.10.1
Exception Type: ImportError
Exception Value:
No module named 'django.core.context_processors'
Exception Location: /app/.heroku/python/lib/python3.5/importlib/__init__.py in import_module, line 126
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.5.1
Python Path:['/app',
'/app/.heroku/python/bin',
'/app/.heroku/python/lib/python3.5/site-packages/setuptools-23.1.0-py3.5.egg',
'/app/.heroku/python/lib/python3.5/site-packages/pip-8.1.2-py3.5.egg',
'/app',
'/app/.heroku/python/lib/python35.zip',
'/app/.heroku/python/lib/python3.5',
'/app/.heroku/python/lib/python3.5/plat-linux',
'/app/.heroku/python/lib/python3.5/lib-dynload',
'/app/.heroku/python/lib/python3.5/site-packages',
'/app',
'/app']
</code></pre>
<p>I looked at line 126 and this is what's there</p>
<pre><code> return _bootstrap._gcd_import(name[level:], package, level)
</code></pre>
<p>this</p>
<pre><code>django.core.context_processors
</code></pre>
<p>is no where to be found in the init file. I looked in my settings file for production and saw this</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"django.core.context_processors.request",
],
},
},
]
</code></pre>
<p>am I supposed to modify this some how?</p>
| 0 |
2016-09-24T22:34:23Z
| 39,681,821 |
<p>Try removing <code>"django.core.context_processors.request"</code> from your settings.</p>
<p>In Django 1.10 <code>django.core.context_processors</code> has been moved to <code>django.template.context_processors</code>. See <a href="https://docs.djangoproject.com/en/1.10/releases/1.8/#django-core-context-processors" rel="nofollow">the release notes</a></p>
<p>You already have the request context processors, no need to add it again with the wrong location.</p>
| 1 |
2016-09-24T23:13:48Z
|
[
"python",
"django",
"git",
"heroku",
"deployment"
] |
Django app has a no ImportError: No module named 'django.core.context_processors'
| 39,681,560 |
<p>Tried git pushing my app after tweaking it and got the following error.</p>
<pre><code>ImportError: No module named 'django.core.context_processors'
</code></pre>
<p>this was not showing up in my heroku logs and my app works locally so I was confused. I had to set debug to true on the production side to finally figure this out. What can I do to clear this up?</p>
<p>this is some of the traceback</p>
<pre><code>Request Method: GET
Request URL: http://hispanicheights.com/
Django Version: 1.10.1
Exception Type: ImportError
Exception Value:
No module named 'django.core.context_processors'
Exception Location: /app/.heroku/python/lib/python3.5/importlib/__init__.py in import_module, line 126
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.5.1
Python Path:['/app',
'/app/.heroku/python/bin',
'/app/.heroku/python/lib/python3.5/site-packages/setuptools-23.1.0-py3.5.egg',
'/app/.heroku/python/lib/python3.5/site-packages/pip-8.1.2-py3.5.egg',
'/app',
'/app/.heroku/python/lib/python35.zip',
'/app/.heroku/python/lib/python3.5',
'/app/.heroku/python/lib/python3.5/plat-linux',
'/app/.heroku/python/lib/python3.5/lib-dynload',
'/app/.heroku/python/lib/python3.5/site-packages',
'/app',
'/app']
</code></pre>
<p>I looked at line 126 and this is what's there</p>
<pre><code> return _bootstrap._gcd_import(name[level:], package, level)
</code></pre>
<p>this</p>
<pre><code>django.core.context_processors
</code></pre>
<p>is no where to be found in the init file. I looked in my settings file for production and saw this</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"django.core.context_processors.request",
],
},
},
]
</code></pre>
<p>am I supposed to modify this some how?</p>
| 0 |
2016-09-24T22:34:23Z
| 39,681,840 |
<p>I fixed it, in settings.py In my TEMPLATES, I changed this line from this</p>
<pre><code>django.core.context_processors.request
</code></pre>
<p>to this</p>
<pre><code>django.template.context_processors.request
</code></pre>
<p>and now I can see my site. I hope this helps someone.</p>
| 0 |
2016-09-24T23:15:37Z
|
[
"python",
"django",
"git",
"heroku",
"deployment"
] |
Python Webdriver raises http.client.BadStatusLine error
| 39,681,605 |
<p>I'm writing a parser and I'm using Selenium Webdriver. So, I have this <a href="https://repl.it/Dgtp" rel="nofollow">https://repl.it/Dgtp</a> code and it's working fine until one random element and throws following exception:
http.client.BadStatusLine: ''<br>
Don't know how to fix it at all. Help.</p>
<p><strong>[UPD]</strong></p>
<p>I tried to scroll the page via webdriver (it had to cause thumbnails to load) and got this <a href="https://repl.it/DkiX" rel="nofollow">https://repl.it/DkiX</a> error series. It would be caused by HTTP error from one of images which were loading, but I've not found any loading errors on the page. Still searching the answer.</p>
| 0 |
2016-09-24T22:40:47Z
| 39,681,760 |
<p>This is a <code>urllib</code> problem. This happens most commonly in python3. What it means is that the status code that the server returned isn't recognized by the http library. Sometimes the server doesn't receive the request at all and the status code returns an empty string triggering that error. </p>
<p><strong>How to fix</strong></p>
<p>Check if the URL string has a trailing newline character. Make sure that your URLs are stripped of any leading or trailing special characters. More info <a href="http://stackoverflow.com/questions/1767934/why-am-i-getting-this-error-in-python-httplib">here</a></p>
<p>If everything looks fine with the URL just treat the exception</p>
<pre><code>import http
try:
browser.get(MONTHLY_URL)
except http.client.HTTPException as e:
print e
</code></pre>
| 0 |
2016-09-24T23:03:59Z
|
[
"python",
"django",
"selenium",
"webdriver",
"phantomjs"
] |
Gantt Chart python machine scheduling
| 39,681,620 |
<p>I'm having some bad time trying to plot a gantt chart from a data set with python. I have a set of machines that work on different tasks during a time period. I want to make a gantt chart that shows by the y axis the machines and x axis the time spent on each task.
Each machine should appear just once on the y axis and to make easier to see the tasks I want the same color for each task. </p>
<p>The idea is to check strange things like having the same task being processed by two or more machines together. </p>
<p>Let me show what data set I have with a small example:</p>
<pre><code>machine equipment start finish
m1 e2 date1 date2
m2 e2 date3 date4
m1 e1 date5 date6
m3 e3 date7 date8
m3 e4 date9 date10
</code></pre>
<p>I tried to use the <a href="http://matplotlib.org/examples/pylab_examples/broken_barh.html" rel="nofollow">broken_barh</a> from matplotlib, but I can't figure out a way to add the data for the plot efficiently. Since I have some thing like 100 machines and 400 tasks.</p>
<p><a href="http://i.stack.imgur.com/ea3eL.gif" rel="nofollow">Here is a picture</a> to show how the output should look like.</p>
<p>Current code bellow:</p>
<pre><code>import datetime as dt
machines = set(list(mydata["machine"]))
tasks = set(list(mydata["task"]))
fig, ax = plt.subplots(figsize=(20, 10))
yrange = 5 # y width of gantt bar
ymin = 0
orign = min(list(mydata["start"])) # time origin
for i in machines:
stdur = [] # list of tuples (start, duration)
ymin = index*6 # start y of gantt bar
for index, row in mydata.iterrows():
if row["machine"] == i:
start = (row["start"] - orign).total_seconds()/3600
duration = (row["finish"] - row["start"]).total_seconds()/3600
stdur.append((start,duration))
ax.broken_barh(stdur,(ymin,yrange))
ax.set_xlabel('Time')
ax.set_yticklabels(machines)
plt.show()
</code></pre>
| 0 |
2016-09-24T22:43:04Z
| 39,703,040 |
<p>Seimetz,</p>
<p>If you are fine passing the entire data to the client and let a JS Gantt do it's thing, then the RadiantQ jQuery Gantt Package will be a better option for you. Here is an online demo of something similar:
<a href="http://demos.radiantq.com/jQueryGanttDemo/Samples/ServerStatusWithHugeData.htm" rel="nofollow">http://demos.radiantq.com/jQueryGanttDemo/Samples/ServerStatusWithHugeData.htm</a></p>
<p>This is how it looks:
<a href="http://i.stack.imgur.com/VyzsO.png" rel="nofollow">Server Status Sample</a></p>
<p>More on the product here:
<a href="http://radiantq.com/products/jquery-gantt-package/jquery-gantt-package-features/" rel="nofollow">http://radiantq.com/products/jquery-gantt-package/jquery-gantt-package-features/</a></p>
| 0 |
2016-09-26T12:37:20Z
|
[
"python",
"matplotlib",
"job-scheduling",
"gantt-chart"
] |
Python - Property Getter as a lambda with a parameter
| 39,681,623 |
<p>Being new to python I just came across the <code>property</code> keyword which basically lets you assign getters and setters. I came up with this simple example</p>
<pre><code>class foo:
def __init__(self,var=2):
self.var= var
def setValue(self,var):
print("Setting value called")
self._var = var
def getValue(self):
print("getting value")
var = property(getValue,setValue)
</code></pre>
<p>Now in my django project I came across with something like this (using a lambda in a property)</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
likes_cheese = models.BooleanField(default=True)
puppy_name = models.CharField(max_length=20)
User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])
</code></pre>
<p>I had no clue that you could use a lambda inside a property. Now from what I understand is that it is setting the getter of the <code>profile</code> as a lambda and the getter requires a parameter. This kind of confused me. So I decided to try my own example</p>
<pre><code>class double:
def setValue(self,var):
print("Setting value called")
self._var = var
def getValue(self):
print("getting value")
#var = property(getValue,setValue)
var = property(lambda x: print("The value of parameter is" + str(x)))
d =double()
d.var #Call the getter but how do i pass a value parameter to it ?
</code></pre>
<p>Now in my case how can i pass a parameter to the lambda ?</p>
| 1 |
2016-09-24T22:43:23Z
| 39,681,740 |
<p>The normal/idomatic way to write a property is:</p>
<pre><code>class MyClass(object):
def __init__(self):
self._foo = 42
@property
def foo(self):
return self._foo
@foo.setter
def foo(self, val):
self._foo = val
</code></pre>
<p>as you can see, like all other method definitions in Python, the first parameter to the method is <code>self</code>.</p>
<p>You can name the parameter whatever you want (don't!), but the first parameter will always be the object itself.</p>
<p>The nice syntax above can be deconstructed to </p>
<pre><code>class MyClass(object):
def __init__(self):
self._foo = 42
def foo_get(self):
return self._foo
def foo_set(self, val):
self._foo = val
foo = property(foo_get, foo_set)
</code></pre>
<p>and instead of passing function <em>names</em> to <code>property</code> we can instead use lambdas:</p>
<pre><code>class MyClass(object):
def __init__(self):
self._foo = 42
def foo_set(self, val):
self._foo = val
foo = property(lambda self: self._foo, foo_set)
</code></pre>
<p>we can't pass the setter as a lambda since lambdas cannot contain assignments. Here I've continued using <code>self</code> as the parameter name, but I could use any variable name, e.g.:</p>
<pre><code>foo = property(lambda u: u._foo, foo_set)
</code></pre>
| 5 |
2016-09-24T22:59:50Z
|
[
"python",
"lambda"
] |
Python - Property Getter as a lambda with a parameter
| 39,681,623 |
<p>Being new to python I just came across the <code>property</code> keyword which basically lets you assign getters and setters. I came up with this simple example</p>
<pre><code>class foo:
def __init__(self,var=2):
self.var= var
def setValue(self,var):
print("Setting value called")
self._var = var
def getValue(self):
print("getting value")
var = property(getValue,setValue)
</code></pre>
<p>Now in my django project I came across with something like this (using a lambda in a property)</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
likes_cheese = models.BooleanField(default=True)
puppy_name = models.CharField(max_length=20)
User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])
</code></pre>
<p>I had no clue that you could use a lambda inside a property. Now from what I understand is that it is setting the getter of the <code>profile</code> as a lambda and the getter requires a parameter. This kind of confused me. So I decided to try my own example</p>
<pre><code>class double:
def setValue(self,var):
print("Setting value called")
self._var = var
def getValue(self):
print("getting value")
#var = property(getValue,setValue)
var = property(lambda x: print("The value of parameter is" + str(x)))
d =double()
d.var #Call the getter but how do i pass a value parameter to it ?
</code></pre>
<p>Now in my case how can i pass a parameter to the lambda ?</p>
| 1 |
2016-09-24T22:43:23Z
| 39,681,764 |
<p>You probably want to do something like this.</p>
<pre><code>class double:
def __init__(self):
self._var = None
var = property(lambda self: self._var,
lambda self, value: setattr(self, "_var", value))
d = double()
d.var = 3
print(d.var)
</code></pre>
<p>When you work with bound methods, the first parameter passed to them is always an instance of a class. It's named <code>self</code> in vast majority of the cases. But it's only a convention, you can name it whatever you want, so when you do just</p>
<pre><code>var = property(lambda x: print("The value of parameter is" + str(x)))
</code></pre>
<p><code>x</code> points to the instance, and <code>str(x)</code> is something like <code><__main__.double object at 0x105f47a90></code>, which is clearly not what you want.</p>
<p>Second, a getter doesn't accept any other arguments, because... well, you really don't need anything else but instance.</p>
<p>Third, we can also use a lambda as a setter; we need 2 parameters here, instance and value, but lambda cannot contain an assignment, so we gotta workaround it with <code>setattr()</code> function.</p>
<p>But if this approach used not just to train and explore, I'd recommend to fallback to <code>@property</code> syntax as shown by @thebjorn.</p>
| 1 |
2016-09-24T23:04:23Z
|
[
"python",
"lambda"
] |
Subprocess Isolation in Python
| 39,681,631 |
<p>I am currently working on a personal project where I have to run two processes simultaneously. The problem is that I have to isolate each of them (they cannot communicate between them or with my system) and I must be able to control their stdin, stdout and stderr. Is there anyway I can achieve this?</p>
<p>Thank you!</p>
| 0 |
2016-09-24T22:45:01Z
| 39,681,690 |
<p>I don't know if you have an objection to using a 3'rd party communication library for your task but this sounds like what ZeroMQ would be used for.</p>
| 0 |
2016-09-24T22:53:08Z
|
[
"python",
"subprocess",
"chroot",
"isolation"
] |
Subprocess Isolation in Python
| 39,681,631 |
<p>I am currently working on a personal project where I have to run two processes simultaneously. The problem is that I have to isolate each of them (they cannot communicate between them or with my system) and I must be able to control their stdin, stdout and stderr. Is there anyway I can achieve this?</p>
<p>Thank you!</p>
| 0 |
2016-09-24T22:45:01Z
| 39,691,935 |
<p>A combination of <code>os.setuid()</code>, <code>os.setgid()</code> and <code>os.setgroups()</code> (also maybe <code>os.chroot()</code>) is a good solution.</p>
| 0 |
2016-09-25T21:17:35Z
|
[
"python",
"subprocess",
"chroot",
"isolation"
] |
What does "overhead" memory refer to in the case of Linked Lists?
| 39,681,639 |
<p>I understand that a node is usually 8 bytes, 4 for a value, 4 for a pointer in a singly linked list.</p>
<p>Does this mean that a doubly linked list node is 12 bytes in memory with two pointers?</p>
<p>Also this book I'm reading talks about how theres 8 bytes of "overhead" for every 12 byte node, what does this refer to?</p>
| 0 |
2016-09-24T22:46:35Z
| 39,681,668 |
<p>First, you're evidently talking about a 32-bit machine since your pointers and values are 4 bytes. Obviously, that's different for a 64-bit machine.</p>
<p>Second, the value needn't be 4 bytes. Frequently the value is a pointer or an int, in which case it is 4 bytes (on your 32-bit machine). But if it was a double, for example, it would be 8 bytes. In fact, the payload could be any type at all, and have that type's size.</p>
<p>Third, your book probably is referring to the two pointers - the links - as the "overhead'.</p>
<p>Fourth, your book is omitting the impact of the memory manager ("heap manager"). Frequently, because of alignment issues and heap management issues, heap elements are larger than actually requested. Most heap implementations on a 32-bit machine won't allocate 12 bytes when you ask for 12. They'll allocate 16 bytes. (The last 4 bytes are not used by your program.) Because for many machines, 8-byte alignment of certain values (e.g., doubles) is either required by the machine architecture or desirable for performance reasons. You have to investigate yourself, for your particular heap implementation (that is, the compiler's run-time's heap implementation) what kind of overhead it imposes. Additionally, some heap implementations (many?) actually use memory inside the allocated object for its own bookkeeping purposes. In this case, that header amount is sometimes as small as 4 bytes, but typically, for most machines which require 8 byte alignment for doubles, is 8 bytes. So in this usual case, if you ask for 12 bytes you'll <em>actually</em> use up <em>24</em> bytes: 8 bytes of heap overhead and 12 bytes for your data, and that's only 20, so an additional 4 bytes just for alignment!</p>
| 2 |
2016-09-24T22:50:23Z
|
[
"python",
"memory-management",
"linked-list"
] |
What does "overhead" memory refer to in the case of Linked Lists?
| 39,681,639 |
<p>I understand that a node is usually 8 bytes, 4 for a value, 4 for a pointer in a singly linked list.</p>
<p>Does this mean that a doubly linked list node is 12 bytes in memory with two pointers?</p>
<p>Also this book I'm reading talks about how theres 8 bytes of "overhead" for every 12 byte node, what does this refer to?</p>
| 0 |
2016-09-24T22:46:35Z
| 39,681,696 |
<blockquote>
<p>Does this mean that a doubly linked list node is 12 bytes in memory with two pointers?</p>
</blockquote>
<p>Yes, if the data is 4 bytes, and the code is compiled for 32bit and not 64bit, so 4 bytes per pointer.</p>
<blockquote>
<p>Also this book I'm reading talks about how theres 8 bytes of "overhead" for every 12 byte node, what does this refer to?</p>
</blockquote>
<p>That <em>might</em> be referring to the 8 bytes used for the 2 pointers. But it <em>might</em> also refer to the memory manager's own overhead when allocating the 12 bytes. Memory managers usually have to allocate more bytes than requested so they can store tracking info used later when freeing the memory (class type for destructor calls, array element counts, etc).</p>
| 0 |
2016-09-24T22:54:29Z
|
[
"python",
"memory-management",
"linked-list"
] |
How to change text-align of float field in odoo 9
| 39,681,686 |
<p>I got a float field in my model that left align when I put it in form view. My question is how to change it to right align.</p>
<p>I've tried so many ways to change its align to right but failed. I've tried to add <code>class="oe_right"</code>, create css custom module but not working. please help me</p>
<p><a href="http://i.stack.imgur.com/TG4p2.png" rel="nofollow"><img src="http://i.stack.imgur.com/TG4p2.png" alt="enter image description here"></a></p>
| 0 |
2016-09-24T22:52:43Z
| 39,683,355 |
<p>You can set text align right by give in-line style in particular field. Try following code.</p>
<p><strong>1. Right align of Float field</strong></p>
<pre><code><field name="field_name" style="text-align:right;"/>
</code></pre>
<p><strong>2. Right align of Float field value while edit mode</strong></p>
<p>You need to create custom css</p>
<p>File <strong>base.css</strong></p>
<pre><code>.openerp .oe_form_editable .oe_form .oe_form_field_float input{
text-align: right !important;}
</code></pre>
<p><strong>Add css to assets_common</strong></p>
<pre><code> <template id="assets_common_float_inherited" inherit_id="web.assets_common">
<xpath expr="." position="inside">
<link rel="stylesheet" href='/your_module_name/static/src/css/base.css'/>
</xpath>
</template>
</code></pre>
<p>Add xml file into <strong>__openerp__.py</strong></p>
<p>Thanks.</p>
| 0 |
2016-09-25T04:24:49Z
|
[
"python",
"css",
"xml",
"openerp"
] |
Most efficient way to get average of all elements in list where each element occurs at least half as many times as the mode of the list
| 39,681,725 |
<p>I have a specific task to perform in python. Efficiency and speed are the most important here which is why I'm posting the question. </p>
<p>I need to get the average of items in a list, but only of the items that occur as least half as many times as the mode of the list occurs. </p>
<p>For instance if the list is <code>[1,2,2,3,4,4,4,4]</code> I need to get the average of <code>2,2,4,4,4,4</code>. Since <code>4</code> is the mode of the list and occurs four times, the only element that occurs at least half of four times (twice) is <code>2</code>. Thus I discount all occurrences <code>1</code> and <code>3</code> and average the list. </p>
<p>I'm not sure what the most efficient way to do this is. I know how to brute force calculate the solution, but that's obviously not the quickest implementation. </p>
<p>I thought it may be best to use a <code>numpy</code> array, but since I'll be appending to the list quite frequently, I didn't think this would be the best choice. </p>
<p>My other thoughts have been to possibly use a <code>Counter</code> based approach from the <code>collections</code> module. But once again, I don't know if it's the fastest or most sensible for performing a rather weird calculation like this. </p>
| 0 |
2016-09-24T22:57:40Z
| 39,681,860 |
<p>To get the mode of the list, you must iterate through the whole list at least once (Technically, you could stop as soon as the count of one of the elements is more than the remaining items in the list, but the efficiency is negligible).</p>
<p>Python has an efficient and easy way to do this with <code>Counter</code>.</p>
<pre><code>from __future__ import division
from collections import Counter
from itertools import islice
data = [1,2,2,3,4,4,4,4]
c = Counter(data)
# Get the mode
mode, mode_n = c.most_common(1)[0]
# Store the cumulative sum and count so we can compute the mean
# Process the most common element (the mode) first since we
# already have that data.
cumulative_sum = mode * mode_n
cumulative_n = mode_n
# Process the remaining elements. most_common returns the remaining
# elements and their counts in descending order by the number of times
# the appear in the original list. We can skip the first element since
# we've already processed it. As soon as an element is less numerous
# than half the mode, we can stop processing further elements.
for val, val_n in islice(c.most_common(), 1, None):
if val_n < mode_n / 2:
break
cumulative_sum += val * val_n
cumulative_n += val_n
# Compute the Mean
avg = cumulative_sum / cumulative_n
</code></pre>
<p>The only thing I'm not completely sure of is how you treat modes that appear an odd number of times. If the mode appeared <code>5</code> times, do you round up to <code>3</code> or down to <code>2</code> when checking the other elements?</p>
<p>Currently, it's rounding up, but if you wanted to round down, you could just change it to this:</p>
<pre><code>if val_n < mode_n // 2:
</code></pre>
| 1 |
2016-09-24T23:19:03Z
|
[
"python",
"list",
"numpy",
"average"
] |
Most efficient way to get average of all elements in list where each element occurs at least half as many times as the mode of the list
| 39,681,725 |
<p>I have a specific task to perform in python. Efficiency and speed are the most important here which is why I'm posting the question. </p>
<p>I need to get the average of items in a list, but only of the items that occur as least half as many times as the mode of the list occurs. </p>
<p>For instance if the list is <code>[1,2,2,3,4,4,4,4]</code> I need to get the average of <code>2,2,4,4,4,4</code>. Since <code>4</code> is the mode of the list and occurs four times, the only element that occurs at least half of four times (twice) is <code>2</code>. Thus I discount all occurrences <code>1</code> and <code>3</code> and average the list. </p>
<p>I'm not sure what the most efficient way to do this is. I know how to brute force calculate the solution, but that's obviously not the quickest implementation. </p>
<p>I thought it may be best to use a <code>numpy</code> array, but since I'll be appending to the list quite frequently, I didn't think this would be the best choice. </p>
<p>My other thoughts have been to possibly use a <code>Counter</code> based approach from the <code>collections</code> module. But once again, I don't know if it's the fastest or most sensible for performing a rather weird calculation like this. </p>
| 0 |
2016-09-24T22:57:40Z
| 39,682,931 |
<p>If you decide to use numpy, here's a concise method using <code>numpy.unique</code> and <code>numpy.average</code>:</p>
<pre><code>In [54]: x = np.array([1, 2, 2, 3, 4, 4, 4, 4])
In [55]: uniqx, counts = np.unique(x, return_counts=True)
In [56]: keep = counts >= 0.5*counts.max()
In [57]: np.average(uniqx[keep], weights=counts[keep])
Out[57]: 3.3333333333333335
</code></pre>
<p>Note that <code>np.unique</code> sorts its argument, so its time complexity is O(n*log(n)), while the problem can be solved with an algorithm that is O(n). Do some timing comparisons using arrays with lengths that will be typical before you rule out this method based on its asymptotic time complexity.</p>
| 1 |
2016-09-25T02:53:33Z
|
[
"python",
"list",
"numpy",
"average"
] |
Finding Top-K using Python & Hadoop Streaming
| 39,681,761 |
<p>So I have an output file from a previous job in this format (.txt file) </p>
<pre><code>" 145
"Defects," 1
"Information 1
"Plain 2
"Project 5
"Right 1
#51302] 1
$5,000) 1
& 3
'AS-IS', 1
( 1
("the 1
</code></pre>
<p>The left hand side of each line is the word that I read from the document and the number on the right hand side of each line is the number of times I have counted it. I want to create another map reduce job, using Python & Hadoop Streaming, to find the top-k values. Let's say 5 in this case. I am having trouble visualizing what the mapper is supposed to do. </p>
<p>Should I be parsing each line and appending each word and count to a list. Then from those lists, will I be taking the top-k values and sending it to the reducer? Then the reducer reads through all these lists and returns only the top-k values? If someone could offer some advice through pseudo code or correct me if I am on the wrong path it would be appreciated. Thanks!</p>
| 1 |
2016-09-24T23:04:06Z
| 39,688,276 |
<p>You are almost on the right track. Consider your word as the Key and the count as the Value for your mapper task. If in your input file, you can get multiple entries for the same word and different count, then you can't take out top K from it. Then you shall have to aggregate the data and then find out top K . This shall be done in reducer then. As reducer shall receive all the data for the same key, it can aggregate the complete data and take out top K. But then there has to be another chained map reduce to find out top K amongst all records, where you shall have 1 reducer for finding the top elements.</p>
<p>But if your input file has an entry for the key once, you can just emit top K from all mappers and then send it to 1 Reducer to find out the top K from all the map entries. </p>
| 0 |
2016-09-25T14:57:12Z
|
[
"python",
"python-2.7",
"hadoop",
"mapreduce",
"hadoop-streaming"
] |
How to set the default value of date field to Null ones a table entry is created and update it when a book is returned?
| 39,681,798 |
<p>How can I set the <code>date_in</code> field to <code>null</code> at the time of entry and update the value to the date book is returned. </p>
<pre><code>class Book_Loans(models.Model):
Loan_id = models.AutoField(primary_key=True)
Isbn = models.ForeignKey('Books')
Card_id = models.ForeignKey('Borrower')
Date_out = models.DateField(auto_now_add = True, auto_now = False)
Due_date = models.DateField(default = get_deadline())
Date_in = models.DateField(null = True,auto_now_add = False, auto_now = True)
def __unicode__(self):
return str(self.Loan_id)
</code></pre>
| 1 |
2016-09-24T23:09:45Z
| 39,682,002 |
<p>Set <code>auto_now = False</code> and the field will remain empty when creating or updating an instance that doesn't specify a value for Date_in. You may also want to set <code>blank = True</code> if you need Date_in as an optional field on a form. </p>
| 1 |
2016-09-24T23:43:00Z
|
[
"python",
"django"
] |
Python turtle won't create multiple squares
| 39,681,828 |
<p>I tried to play around with this code many times but I can't create multiple squares. This is the problem:</p>
<p>Write a function named drawSquares that calls drawSquare to draw a
specified number of squares.
The function drawSquares takes four parameters: a turtle t, an integer size, an integer num, the number of squares to draw, and an integer angle, the clockwise rotation between successive squares</p>
<p>For example, the following would be
correct output.</p>
<p>import turtle</p>
<p>s = turtle.Screen()</p>
<p>snapper = turtle.Turtle()</p>
<p>drawSquares(snapper, 100, 4, 20)</p>
<pre><code>import turtle
s = turtle.Screen()
t = turtle.Turtle()
def drawSquares(t, size, num, angle):
for i in range(num):
for x in range(num):
t.forward(size)
t.right(angle)
t.forward(size)
drawSquares(t, 100, 4, 20)
</code></pre>
| 0 |
2016-09-24T23:14:29Z
| 39,681,868 |
<p>If I understand you correctly, this code should do exactly what you want:</p>
<pre><code>import turtle
s = turtle.Screen()
t = turtle.Turtle()
def drawSquares(t, size, num, angle):
for i in range(num):
for x in range(4):
turtle.forward(size)
turtle.left(90)
turtle.right(angle)
drawSquares(t, 100, 4, 20)
</code></pre>
| 0 |
2016-09-24T23:20:21Z
|
[
"python",
"turtle-graphics"
] |
How can I find the angle of a T shape in OpenCV
| 39,681,837 |
<p>I'm using OpenCV 2.4 to do some tracking, and I can get a contour of the shape I want, which is a T.</p>
<p>Input image:
<a href="http://i.stack.imgur.com/iQ6ZW.png" rel="nofollow"><img src="http://i.stack.imgur.com/iQ6ZW.png" alt="enter image description here"></a></p>
<p>I can use <code>cv2.minAreaRect(my_t_contour)</code> and get the angle of that rect, but that only gives me 0-180 degrees. But this is a T shape though, so I want to be able to tell 0-360. I was thinking of:</p>
<ol>
<li>Split the contour into two rects</li>
<li>Get a line through the rects (either using skeletonize > HoughLinesP)</li>
<li>Determine which line is which, determine their gradient (using the coordinates I get from HoughLinesP) and then determine the direction of the T.</li>
</ol>
<p>But I'm stuck at number 1, how can I split a contour into two shapes?</p>
<hr>
<p><strong>Method 1</strong>: draw center of contour and center of minAreaRect of contour</p>
<pre><code>dst = cv2.cvtColor(r_target, cv2.COLOR_BGR2GRAY)
dst = cv2.GaussianBlur(dst, (11, 11), 0)
ret,dst = cv2.threshold(dst,110,255,cv2.THRESH_BINARY_INV)
cnts = cv2.findContours(dst, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
# get minAreaRect around contour and draw its center in red
rect = cv2.minAreaRect(c)
cv2.circle(r_target, (int(rect[0][0]), int(rect[0][1])), 7, (0, 0, 255), -1)
# get moments of contour to get center and draw it in white
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.circle(r_target, (cX, cY), 7, (255, 255, 255), -1)
</code></pre>
<p><a href="http://i.stack.imgur.com/Py5kb.png" rel="nofollow"><img src="http://i.stack.imgur.com/Py5kb.png" alt="enter image description here"></a></p>
<p>Next step would probably calculate a simple gradient between the centers to determine the angle.</p>
<hr>
<p><strong>Method 2</strong>: skeletonize the image and get lines using HoughLinesP.</p>
<pre><code>dst = cv2.cvtColor(r_target, cv2.COLOR_BGR2GRAY)
dst = cv2.GaussianBlur(dst, (11, 11), 0)
ret,dst = cv2.threshold(dst,110,255,cv2.THRESH_BINARY)
dst = 1 - dst / 255
dst = skimage.morphology.skeletonize(dst).astype(np.uint8)
rho = 1
theta = np.pi / 180
threshold = 1
minLineLength = 30
maxLineGap = 15
lines = cv2.HoughLinesP(dst, rho, theta, threshold, minLineLength=minLineLength, maxLineGap=maxLineGap)
for line in lines[0]:
cv2.line(r_target, (line[0], line[1]), (line[2], line[3]), (0, 255, 0), 1, 8)
</code></pre>
<p>But the lines don't come out nicely. This is how the skeleton looks like:</p>
<p><a href="http://i.stack.imgur.com/2f9KL.png" rel="nofollow"><img src="http://i.stack.imgur.com/2f9KL.png" alt="enter image description here"></a></p>
<p>I'm still experimenting with the variables but is there a specific thought process around using HoughLinesP?</p>
| 1 |
2016-09-24T23:15:18Z
| 39,687,023 |
<p>As a variant you can use PCA, find first component direction, and use it as an searced angle. You can check here for an example: <a href="http://docs.opencv.org/trunk/d1/dee/tutorial_introduction_to_pca.html" rel="nofollow">http://docs.opencv.org/trunk/d1/dee/tutorial_introduction_to_pca.html</a></p>
| 1 |
2016-09-25T12:49:51Z
|
[
"python",
"opencv"
] |
How to ensure update() adds to end of dictionary
| 39,681,839 |
<p>I've read that <a href="http://stackoverflow.com/questions/20110627/print-original-input-order-of-dictionary-in-python">OrderedDict</a> can be used to keep information in a dictionary in order, but it seems to require that you input the information while instantiating the dictionary itself.</p>
<p>However, I need to be able to use update() multiple times in a for loop and ensure the each entry gets added to the <em>end</em> of the dictionary. Is there a way to do that?</p>
<p>Here's a visual of what I'm talking about</p>
<pre><code>for e in entryList:
myDict.update({e[2]: e[3]})
</code></pre>
<p>This enters all the new info, but doesn't keep it in order.</p>
| 1 |
2016-09-24T23:15:25Z
| 39,681,872 |
<p>@Bob, please refer to the docs here. <a href="https://docs.python.org/3.5/library/collections.html?highlight=ordereddict#collections.OrderedDict" rel="nofollow">https://docs.python.org/3.5/library/collections.html?highlight=ordereddict#collections.OrderedDict</a></p>
<p>It says:</p>
<blockquote>
<p>The OrderedDict constructor and update() method both accept keyword
arguments, but their order is lost because Pythonâs function call
semantics pass in keyword arguments using a regular unordered
dictionary.</p>
</blockquote>
<p>However, there's a workaround added in 3.2: (from the same page)</p>
<blockquote>
<p>move_to_end(key, last=True) Move an existing key to either end of an
ordered dictionary. The item is moved to the right end if last is true
(the default) or to the beginning if last is false. Raises KeyError if
the key does not exist.</p>
</blockquote>
<p>I hope that answers the question.</p>
| 0 |
2016-09-24T23:21:15Z
|
[
"python",
"dictionary"
] |
How to ensure update() adds to end of dictionary
| 39,681,839 |
<p>I've read that <a href="http://stackoverflow.com/questions/20110627/print-original-input-order-of-dictionary-in-python">OrderedDict</a> can be used to keep information in a dictionary in order, but it seems to require that you input the information while instantiating the dictionary itself.</p>
<p>However, I need to be able to use update() multiple times in a for loop and ensure the each entry gets added to the <em>end</em> of the dictionary. Is there a way to do that?</p>
<p>Here's a visual of what I'm talking about</p>
<pre><code>for e in entryList:
myDict.update({e[2]: e[3]})
</code></pre>
<p>This enters all the new info, but doesn't keep it in order.</p>
| 1 |
2016-09-24T23:15:25Z
| 39,681,874 |
<p>Per the docs (<a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">https://docs.python.org/2/library/collections.html#collections.OrderedDict</a>) you'll have to delete the entry before adding it.</p>
<p>You can wrap this in a subclass for convenience..:</p>
<pre><code>class MyOrderedDict(OrderedDict):
def update(self, other):
for k, v in other.items():
if k in self:
del self[k]
self[k] = v
</code></pre>
<p>it seems strange to use update the way you do though:</p>
<pre><code>myDict.update({e[2]: e[3]})
</code></pre>
<p>since it would be more clear to write:</p>
<pre><code>myDict[e[2]] = e[3]
</code></pre>
<p>to make that work you'll also need to override <code>__setitem__</code></p>
<pre><code>class MyOrderedDict(OrderedDict):
def __setitem__(self, key, val):
if key in self:
del self[key]
super(self, MyOrderedDict).__setitem__(key, val)
def update(self, other):
for k, v in other.items():
self[k] = v
</code></pre>
| 3 |
2016-09-24T23:21:22Z
|
[
"python",
"dictionary"
] |
Python for Data Analysis error: Expecting value: line 1 column 1 (char 0)
| 39,681,847 |
<p>I am following along the examples of Python for Data Analysis and the first examples shows:</p>
<pre><code>In [15]: path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
In [16]: open(path).readline()
Out[16]: '{ "a": "Mozilla\\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\\/535.11
(KHTML, like Gecko) Chrome\\/17.0.963.78 Safari\\/535.11", "c": "US", "nk": 1,
"tz": "America\\/New_York", "gr": "MA", "g": "A6qOVH", "h": "wfLQtf", "l":
"orofrog", "al": "en-US,en;q=0.8", "hh": "1.usa.gov", "r":
"http:\\/\\/www.facebook.com\\/l\\/7AQEFzjSi\\/1.usa.gov\\/wfLQtf", "u":
"http:\\/\\/www.ncbi.nlm.nih.gov\\/pubmed\\/22415991", "t": 1331923247, "hc":
1331822918, "cy": "Danvers", "ll": [ 42.576698, -70.954903 ] }\n'
</code></pre>
<p>After following these instructions I get:</p>
<pre><code>In [21]: open(path).readline()
Out[21]: '{ "a": "Mozilla\\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\\/535.11
(KHTML, like Gecko) Chrome\\/17.0.963.78 Safari\\/535.11", "c": "US", "nk": 1, "
tz": "America\\/New_York", "gr": "MA", "g": "A6qOVH", "h": "wfLQtf", "l": "orofr
og", "al": "en-US,en;q=0.8", "hh": "1.usa.gov", "r": "http:\\/\\/www.facebook.co
m\\/l\\/7AQEFzjSi\\/1.usa.gov\\/wfLQtf", "u": "http:\\/\\/www.ncbi.nlm.nih.gov\\
/pubmed\\/22415991", "t": 1331923247, "hc": 1331822918, "cy": "Danvers", "ll": [
42.576698, -70.954903 ] }\n'
</code></pre>
<p>The only difference from the book is the "" part. </p>
<p>Later, when I try:</p>
<pre><code>import json
path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
records = [json.loads(line) for line in open(path)]
</code></pre>
<p>... what I get is:</p>
<pre><code>`In [22]: import json
In [23]: path = 'usagov_bitly_data2012-03-16-1331923249.txt'
In [24]: records = [json.loads(line) for line in open(path)]
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
<ipython-input-24-b1e0b494454a> in <module>()
----> 1 records = [json.loads(line) for line in open(path)]
<ipython-input-24-b1e0b494454a> in <listcomp>(.0)
----> 1 records = [json.loads(line) for line in open(path)]
C:\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_
float, parse_int, parse_constant, object_pairs_hook, **kw)
317 parse_int is None and parse_float is None and
318 parse_constant is None and object_pairs_hook is None and not
kw):
--> 319 return _default_decoder.decode(s)
320 if cls is None:
321 cls = JSONDecoder
C:\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):
C:\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from
None
358 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)`
</code></pre>
<p>Does any one know why I get this JSONDecodeError error?</p>
| -1 |
2016-09-24T23:16:59Z
| 39,735,291 |
<p>Sir, , It is not JSON format, I think that you should remove anomaly text '' or try some online format JSON to be more clear.</p>
| 0 |
2016-09-27T22:27:27Z
|
[
"python",
"data-analysis"
] |
Uncaught ReferenceError: rotateAnimation is not defined(anonymous function)
| 39,681,924 |
<p>please have patience for me, I am new at programming :)
I am testing Brython in browsers. I have this code for simple rotate image, in this case it's a cog.
I wan to use python and DOM to animate this image of cog.
This is the code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- load Brython -->
<script src="http://brython.info/src/brython_dist.js"></script>
<!-- the main script; after loading, Brython will run all 'text/python3' scripts -->
<script type='text/python3'>
from browser import window, timer, document, html
def user_agent():
""" Helper function for determining the user agent """
if window.navigator.userAgent.find('Chrome'):
return 'chrome'
elif window.navigator.userAgent.find('Firefox'):
return 'firefox'
elif window.navigator.userAgent.find('MSIE'):
return 'msie'
elif window.navigator.userAgent.find('Opera'):
return 'opera'
# Dict Mapping UserAgents to Transform Property names
rotate_property = {
'chrome':'WebkitTransform',
'firefox':'MozTransform',
'msie':'msTransform',
'opera':'OTransform'
}
degrees = 0
def animation_step(elem_id):
""" Called every 30msec to increase the rotatation of the element. """
global degrees, tm
# Get the right property name according to the useragent
agent = user_agent()
prop = rotate_property.get(agent,'transform')
# Get the element by id
el = document[elem_id]
# Set the rotation of the element
setattr(el.style, prop, "rotate("+str(degrees)+"deg)")
document['status'].innerHTML = "rotate("+str(degrees)+"deg)"
# Increase the rotation
degrees += 1
if degrees > 359:
# Stops the animation after 360 steps
timer.clear_interval(tm)
degrees = 0
# Start the animation
tm = timer.set_interval(lambda id='img1':animation_step(id),30)
</script>
</head>
<!-- After the page has finished loading, run bootstrap Brython by running
the Brython function. The argument '1' tells Brython to print error
messages to the console. -->
<body onload='brython(1)'>
<img id="img1" src="cog1.png" alt="cog1">
<script>rotateAnimation("img1",30);</script>
<h2 style="width:200px;" id="status"></h2>
</body>
</html>
</code></pre>
<p>This is source code in JavaScript:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script>
var looper;
var degrees = 0;
function rotateAnimation(el,speed){
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
} else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout('rotateAnimation(\''+el+'\','+speed+')',speed);
degrees++;
if(degrees > 359){
degrees = 1;
}
document.getElementById("status").innerHTML = "rotate("+degrees+"deg)";
}
</script>
</head>
<body>
<img id="img1" src="cog1.png" alt="cog1">
<script>rotateAnimation("img1",30);</script>
<h2 style="width:200px;" id="status"></h2>
</body>
</html>
</code></pre>
<p>I have error:</p>
<pre><code>(index):67 Uncaught ReferenceError: rotateAnimation is not defined(anonymous
function) @ (index):67
brython_dist.js:4985 File "__main__", line 6
if window.navigator.userAgent.find('Chrome'):
IndentationError: unexpected indent
</code></pre>
<p>What's wrong?</p>
<p>If I change</p>
<pre><code><script>rotateAnimation("img1",30);</script>
</code></pre>
<p>to</p>
<pre><code><script>animation_step("img1",30);</script>
</code></pre>
<p>I have error:</p>
<pre><code>(index):67 Uncaught ReferenceError: animation_step is not defined(anonymous function) @ (index):67
brython_dist.js:4985 File "__main__", line 6
if window.navigator.userAgent.find('Chrome'):
IndentationError: unexpected indent
</code></pre>
| 0 |
2016-09-24T23:30:59Z
| 39,687,808 |
<p>in line 14</p>
<pre><code> """ Helper function for determining the user agent """
</code></pre>
<p>to much space's</p>
<p>Should be</p>
<pre><code> """ Helper function for determining the user agent """
</code></pre>
| 0 |
2016-09-25T14:14:54Z
|
[
"javascript",
"python",
"html",
"dom",
"brython"
] |
Optimizing queries in Django, prefact_related for objects that are reversely linked
| 39,682,035 |
<p>In my django project I have 3 models, simplified for this example: Contact, WorkRelation and Group objects.</p>
<p><strong>Contact</strong></p>
<pre><code>class Contact(BaseModel):
title = models.CharField(max_length=30, blank=True)
initials = models.CharField(max_length=10, blank=True)
first_name = models.CharField(max_length=30, blank=True)
prefix = models.CharField(max_length=20, blank=True)
surname = models.CharField(max_length=30)
def get_workrelations(self):
workrelations = apps.get_model('groups', 'WorkRelation')
return workrelations.objects.filter(contact=self)
def get_organisations(self):
output = ""
strings = []
wr = self.get_workrelations()
for relation in wr:
group = relation.group
name = group.name
strings.append(s)
if len(strings) > 0:
output = ", ".join(strings)
return output
</code></pre>
<p><strong>WorkRelation</strong></p>
<pre><code>class WorkRelation(BaseModel):
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
function = models.CharField(max_length=40, blank=True)
email_address = models.EmailField()
phone_number = models.CharField(max_length=13, blank=True)
description = models.TextField(max_length=400, blank=True)
</code></pre>
<p><strong>Group</strong></p>
<pre><code>class Group(BaseModel):
group_type = models.ForeignKey(GroupType, on_delete=models.CASCADE)
name = models.CharField(max_length=60, unique=True)
street_name = models.CharField(max_length=40, blank=True)
house_number = models.CharField(max_length=10, blank=True)
</code></pre>
<p>The problem with this setup is that it becomes extremely slow when I want to call get_organisations() on a large contact set. For example: when trying to list all my contacts (600 for my demo set), and call get_organisations(), about 1250 queries are needed.</p>
<p>I found that you can prevent this by using prefetch_data(), but somehow I can't get this working in my setup. I tried to replace my query for </p>
<pre><code>queryset = Contact.objects.prefetch_related('workrelation_set')
</code></pre>
<p>But this didn't speed it up (against my presumption). Do you guys know if it is even possible to speed this up?</p>
| 0 |
2016-09-24T23:47:55Z
| 39,684,414 |
<p>Change your get_organisations code to this:</p>
<pre><code>def get_organisations(self):
return ', '.join(
workrelation.group.name for workrelation
in self.workrelation_set.all()
)
</code></pre>
<p>And use this query for fetching Contact objects:</p>
<pre><code>Contact.objects.prefetch_related('workrelation_set__group')
</code></pre>
<p>This will return the result with a single query.</p>
| 1 |
2016-09-25T07:23:39Z
|
[
"python",
"django",
"django-queryset"
] |
Python extension module segfault
| 39,682,074 |
<p>I wrote a nifty fitter in C, and I want to provide an interface in python. So I wrote an extension module for it (below). However, when I run</p>
<pre><code>from nelder_mead import minimize
minimize(lambda x: x[0]**2, [42])
</code></pre>
<p>I get a segfault. I have no idea where to begin debugging, is the problem at all obvious? When I call the fitter from C, it works great.</p>
<p>Here's my wrapper, the function primitive for the fitter is at the top:</p>
<pre><code>#include "Python.h"
void _minimize(double (*func)(double* x, void* args), double* x0, int N, void* args);
typedef struct arg_struct {
PyObject* func;
int N;
} arg_struct;
double func(double* x, void* args){
//Build a PyList off of x
int N = ((arg_struct*)args)->N;
PyObject* x_list = PyList_New(N);
for (int i=0; i<N; i++){ PyList_SetItem(x_list, i, PyFloat_FromDouble(x[i])); }
//Pass x_list into the python objective function
PyObject* arglist = Py_BuildValue("(O)", x_list);
PyObject* result = PyObject_CallObject(((arg_struct*)args)->func, arglist);
//Convert result to a double and return
return PyFloat_AsDouble(result);
}
static PyObject* minimize(PyObject* self, PyObject* py_args){
//Get object pointers to f and x0
PyObject* py_func, *x0_list;
if (!PyArg_ParseTuple(py_args, "OO", py_func, x0_list)) return NULL;
//Copy doubles out of x0_list to a regular double* array
int N = PyList_Size(x0_list);
double* x0 = (double*)malloc(N*sizeof(double));
for (int i=0; i<N; i++) x0[i] = PyFloat_AsDouble(PyList_GetItem(x0_list, i));
//Set up an arg_struct and minimize py_func(x0)
arg_struct c_args = { py_func, N };
_minimize(&func, x0, N, (void*)&c_args);
//Now build a list off of x0 and return it
PyObject* result_list = PyList_New(N);
for (int i=0; i<N; i++){ PyList_SetItem(result_list, i, PyFloat_FromDouble(x0[i])); }
return result_list;
}
//Initialize the module with the module table and stuff
static PyMethodDef module_methods[] = {
{ "minimize", minimize, METH_VARARGS, "Minimize a function." },
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC
initnelder_mead(void){
(void) Py_InitModule("nelder_mead", module_methods);
}
</code></pre>
<p>And here's my <code>setup.py</code>:</p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
setup(name='nelder_mead',
ext_modules = [Extension('nelder_mead', sources = ['wrapper.c', 'nm.c'])])
</code></pre>
| 0 |
2016-09-24T23:55:59Z
| 39,682,696 |
<p>Turned out to be two small things. As @robyschek pointed out, I should have put <code>x[0]</code> instead of <code>x</code>, which caused a type error. Additionally, it turns out the argument parsing needs pointers to pointers:
changing it to <code>PyArg_ParseTuple(py_args, "OO", &py_func, &x0_list)</code> works fine.</p>
| 1 |
2016-09-25T01:56:26Z
|
[
"python",
"c",
"python-c-api"
] |
Using Pandas and Sklearn.Neighbors
| 39,682,124 |
<p>I'm trying to fit a KNN model on a dataframe, using Python 3.5/Pandas/Sklearn.neighbors. I've imported the data, split it into training and testing data and labels, but when I try to predict using it, I get the following error. I'm quite new to Pandas so any help would be appreciated, thanks!</p>
<p><a href="http://i.stack.imgur.com/AQnIF.png" rel="nofollow"><img src="http://i.stack.imgur.com/AQnIF.png" alt="enter image description here"></a></p>
<pre><code>import pandas as pd
from sklearn import cross_validation
import numpy as np
from sklearn.neighbors import KNeighborsRegressor
seeds = pd.read_csv('seeds.tsv',sep='\t',names=['Area','Perimeter','Compactness','Kern_len','Kern_width','Assymetry','Kern_groovlen','Species'])
data = seeds.iloc[:,[0,1,2,3,4,5,6]]
labels = seeds.iloc[:,[7]]
x_train, x_test, y_train, y_test = cross_validation.train_test_split(data,labels, test_size=0.4, random_state=1 )
knn = KNeighborsRegressor(n_neighbors=30)
knn.fit(x_train,y_train)
knn.predict(x_test)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-121-2292e64e5ab8> in <module>()
----> 1 knn.predict(x_test)
C:\Anaconda3\lib\site-packages\sklearn\neighbors\regression.py in predict(self, X)
151
152 if weights is None:
--> 153 y_pred = np.mean(_y[neigh_ind], axis=1)
154 else:
155 y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float)
C:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in mean(a, axis, dtype, out, keepdims)
2876
2877 return _methods._mean(a, axis=axis, dtype=dtype,
-> 2878 out=out, keepdims=keepdims)
2879
2880
C:\Anaconda3\lib\site-packages\numpy\core\_methods.py in _mean(a, axis, dtype, out, keepdims)
66 if isinstance(ret, mu.ndarray):
67 ret = um.true_divide(
---> 68 ret, rcount, out=ret, casting='unsafe', subok=False)
69 elif hasattr(ret, 'dtype'):
70 ret = ret.dtype.type(ret / rcount)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
</code></pre>
| 1 |
2016-09-25T00:04:10Z
| 39,683,184 |
<p>You should be using the <code>KNeighborsClassifier</code> for this KNN. You are trying to predict the label <code>Species</code> for classification. The regressor in your code above is trying to train and predict continuously valued numerical variables, which is where your problem is being introduced.</p>
<pre><code>from sklearn.neighbors import KNeighborsClassifier
seeds = pd.read_csv('seeds.tsv',sep='\t',names=['Area','Perimeter','Compactness','Kern_len','Kern_width','Assymetry','Kern_groovlen','Species'])
data = seeds.iloc[:,[0,1,2,3,4,5,6]]
labels = seeds.iloc[:,[7]]
x_train, x_test, y_train, y_test = cross_validation.train_test_split(data,labels, test_size=0.4, random_state=1 )
knn = KNeighborsClassifier(n_neighbors=30)
</code></pre>
<p><a href="http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html</a></p>
<p>Here is what the regressor would plot compared to the classifier (which you want to use).</p>
<p><a href="http://i.stack.imgur.com/a0uHV.png" rel="nofollow"><img src="http://i.stack.imgur.com/a0uHV.png" alt="Regressor"></a></p>
<p><a href="http://i.stack.imgur.com/eGDWR.png" rel="nofollow"><img src="http://i.stack.imgur.com/eGDWR.png" alt="Classifier"></a></p>
| 2 |
2016-09-25T03:46:05Z
|
[
"python",
"pandas",
"scikit-learn",
"python-3.5",
"sklearn-pandas"
] |
how to hash numpy arrays to check for duplicates
| 39,682,192 |
<p>I have searched around a bit for tutorials etc. to help with this problem but cant seem to find anything. </p>
<p>I have two lists of n-dimensional numpy arrays (3D array form of some images) and am wanting to check for overlapping images within each list. Lets says list a is a training set and list b is a validation set.
One solution is just to use a nested loop and check if each pair of arrays is equal using <code>np.array(a[i], b[j])</code> but that is slow (each list has about 200,000 numpy arrays in it) and frankly quite disgusting. </p>
<p>I was thinking a more elegant way of achieving this would be to hash each of the numpy arrays within each list and then compare each entry using these hash tables. </p>
<p>Firstly, is this solution correct, and secondly, how would I go about achieving this?<br>
An example of some of the data is below.</p>
<pre><code>train_dataset[:3]
array([[[-0.5 , -0.49607843, -0.5 , ..., -0.5 ,
-0.49215686, -0.5 ],
[-0.49607843, -0.47647059, -0.5 , ..., -0.5 ,
-0.47254902, -0.49607843],
[-0.49607843, -0.49607843, -0.5 , ..., -0.5 ,
-0.49607843, -0.49607843],
...,
[-0.49607843, -0.49215686, -0.5 , ..., -0.5 ,
-0.49215686, -0.49607843],
[-0.49607843, -0.47647059, -0.5 , ..., -0.5 ,
-0.47254902, -0.49607843],
[-0.5 , -0.49607843, -0.5 , ..., -0.5 ,
-0.49607843, -0.5 ]],
[[-0.5 , -0.5 , -0.5 , ..., 0.48823529,
0.5 , 0.1509804 ],
[-0.5 , -0.5 , -0.5 , ..., 0.48431373,
0.14705883, -0.32745099],
[-0.5 , -0.5 , -0.5 , ..., -0.32745099,
-0.5 , -0.49607843],
...,
[-0.5 , -0.44901961, 0.1509804 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.49607843, -0.49607843, -0.49215686, ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.49607843, -0.48823529, ..., -0.5 ,
-0.5 , -0.5 ]],
[[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.49607843, ..., -0.5 ,
-0.5 , -0.5 ],
...,
[-0.5 , -0.5 , -0.5 , ..., -0.48823529,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ]]], dtype=float32)
</code></pre>
<p>I appreciate the help in advance.</p>
| 1 |
2016-09-25T00:18:30Z
| 39,682,801 |
<p>You can find duplicates between arrays using numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.html#numpy.intersect1d" rel="nofollow"><code>intersect1d</code></a> (one dimensional set intersect) function. </p>
<pre><code>duplicate_images = np.intersect1d(train_dataset, test_dataset)
</code></pre>
<p>I timed this using the train and test sets (55000 and 10000 arrays respectively) from one of the <a href="https://www.tensorflow.org/versions/r0.10/tutorials/mnist/beginners/index.html" rel="nofollow">tensorflow tutorials</a> which I'm guessing is similar to your data. Using <code>intersect1d</code>, it took about 2.4 seconds to complete on my machine (it took only 1.3 seconds with the parameter <code>assume_unique=True</code>). A pairwise comparison like you describe took several minutes. </p>
<p><strong>EDIT</strong></p>
<p>This answer (above) does not compare each "image" array, as @mbhall88 points out in the comments, this compares elements within the arrays, not the arrays themselves. In order to make sure it compares the arrays you can still use <code>intersect1d</code> but you have to mess around with the dtypes first as explained <a href="http://stackoverflow.com/a/8317403/5992438">here</a>. But, the example in that answer deals with 2d arrays and since you're working with 3d arrays you should first flatten the second two dimensions. You should be able to do something like:</p>
<pre><code>def intersect3d(A,B, assume_unique=False):
# get the original shape of your arrays
a1d, a2d, a3d = A.shape
# flatten the 2nd and 3rd dimensions in your arrays
A = A.reshape((a1d,a2d*a3d))
B = B.reshape((len(B),a2d*a3d))
# define a structured dtype so you can treat your arrays as single "element"
dtype=(', '.join([str(A.dtype)]*ncols))
# find the duplicate elements
C = np.intersect1d(A.view(dtype), B.view(dtype), assume_unique=assume_unique)
# reshape the result and return
return C.view(A.dtype).reshape(-1, ncols).reshape((len(C),a2d,a3d))
</code></pre>
| 0 |
2016-09-25T02:21:57Z
|
[
"python",
"arrays",
"numpy",
"hash"
] |
how to hash numpy arrays to check for duplicates
| 39,682,192 |
<p>I have searched around a bit for tutorials etc. to help with this problem but cant seem to find anything. </p>
<p>I have two lists of n-dimensional numpy arrays (3D array form of some images) and am wanting to check for overlapping images within each list. Lets says list a is a training set and list b is a validation set.
One solution is just to use a nested loop and check if each pair of arrays is equal using <code>np.array(a[i], b[j])</code> but that is slow (each list has about 200,000 numpy arrays in it) and frankly quite disgusting. </p>
<p>I was thinking a more elegant way of achieving this would be to hash each of the numpy arrays within each list and then compare each entry using these hash tables. </p>
<p>Firstly, is this solution correct, and secondly, how would I go about achieving this?<br>
An example of some of the data is below.</p>
<pre><code>train_dataset[:3]
array([[[-0.5 , -0.49607843, -0.5 , ..., -0.5 ,
-0.49215686, -0.5 ],
[-0.49607843, -0.47647059, -0.5 , ..., -0.5 ,
-0.47254902, -0.49607843],
[-0.49607843, -0.49607843, -0.5 , ..., -0.5 ,
-0.49607843, -0.49607843],
...,
[-0.49607843, -0.49215686, -0.5 , ..., -0.5 ,
-0.49215686, -0.49607843],
[-0.49607843, -0.47647059, -0.5 , ..., -0.5 ,
-0.47254902, -0.49607843],
[-0.5 , -0.49607843, -0.5 , ..., -0.5 ,
-0.49607843, -0.5 ]],
[[-0.5 , -0.5 , -0.5 , ..., 0.48823529,
0.5 , 0.1509804 ],
[-0.5 , -0.5 , -0.5 , ..., 0.48431373,
0.14705883, -0.32745099],
[-0.5 , -0.5 , -0.5 , ..., -0.32745099,
-0.5 , -0.49607843],
...,
[-0.5 , -0.44901961, 0.1509804 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.49607843, -0.49607843, -0.49215686, ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.49607843, -0.48823529, ..., -0.5 ,
-0.5 , -0.5 ]],
[[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.49607843, ..., -0.5 ,
-0.5 , -0.5 ],
...,
[-0.5 , -0.5 , -0.5 , ..., -0.48823529,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ]]], dtype=float32)
</code></pre>
<p>I appreciate the help in advance.</p>
| 1 |
2016-09-25T00:18:30Z
| 39,690,707 |
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (diclaimer: I am its author) has an efficient one-liner for this:</p>
<pre><code>import numpy_indexed as npi
duplicate_images = npi.intersection(train_dataset, test_dataset)
</code></pre>
<p>Plus a lot of related functions which you might find useful in this context.</p>
| 0 |
2016-09-25T19:05:31Z
|
[
"python",
"arrays",
"numpy",
"hash"
] |
how to hash numpy arrays to check for duplicates
| 39,682,192 |
<p>I have searched around a bit for tutorials etc. to help with this problem but cant seem to find anything. </p>
<p>I have two lists of n-dimensional numpy arrays (3D array form of some images) and am wanting to check for overlapping images within each list. Lets says list a is a training set and list b is a validation set.
One solution is just to use a nested loop and check if each pair of arrays is equal using <code>np.array(a[i], b[j])</code> but that is slow (each list has about 200,000 numpy arrays in it) and frankly quite disgusting. </p>
<p>I was thinking a more elegant way of achieving this would be to hash each of the numpy arrays within each list and then compare each entry using these hash tables. </p>
<p>Firstly, is this solution correct, and secondly, how would I go about achieving this?<br>
An example of some of the data is below.</p>
<pre><code>train_dataset[:3]
array([[[-0.5 , -0.49607843, -0.5 , ..., -0.5 ,
-0.49215686, -0.5 ],
[-0.49607843, -0.47647059, -0.5 , ..., -0.5 ,
-0.47254902, -0.49607843],
[-0.49607843, -0.49607843, -0.5 , ..., -0.5 ,
-0.49607843, -0.49607843],
...,
[-0.49607843, -0.49215686, -0.5 , ..., -0.5 ,
-0.49215686, -0.49607843],
[-0.49607843, -0.47647059, -0.5 , ..., -0.5 ,
-0.47254902, -0.49607843],
[-0.5 , -0.49607843, -0.5 , ..., -0.5 ,
-0.49607843, -0.5 ]],
[[-0.5 , -0.5 , -0.5 , ..., 0.48823529,
0.5 , 0.1509804 ],
[-0.5 , -0.5 , -0.5 , ..., 0.48431373,
0.14705883, -0.32745099],
[-0.5 , -0.5 , -0.5 , ..., -0.32745099,
-0.5 , -0.49607843],
...,
[-0.5 , -0.44901961, 0.1509804 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.49607843, -0.49607843, -0.49215686, ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.49607843, -0.48823529, ..., -0.5 ,
-0.5 , -0.5 ]],
[[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.49607843, ..., -0.5 ,
-0.5 , -0.5 ],
...,
[-0.5 , -0.5 , -0.5 , ..., -0.48823529,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ],
[-0.5 , -0.5 , -0.5 , ..., -0.5 ,
-0.5 , -0.5 ]]], dtype=float32)
</code></pre>
<p>I appreciate the help in advance.</p>
| 1 |
2016-09-25T00:18:30Z
| 39,692,548 |
<p>It's not so difficult to come up with <em>something</em>:</p>
<pre><code>from collections import defaultdict
import numpy as np
def arrayhash(arr):
u = arr.view('u' + str(arr.itemsize))
return np.bitwise_xor.reduce(u.ravel())
def do_the_thing(a, b, hashfunc=arrayhash):
table = defaultdict(list)
for i, a_i in enumerate(a):
table[hashfunc(a_i)].append(i)
indices = []
for j, b_j in enumerate(b):
candidates = table[hashfunc(b_j)]
for i in candidates:
if np.array_equiv(a[i], b_j):
indices.append((i,j))
return indices
</code></pre>
<p>But note:</p>
<ul>
<li><p>Checking for floating point equality is oftentimes a bad idea, because limited precision and rounding error. Famous example:</p>
<pre><code>>>> 0.1 + 0.2 == 0.3
False
</code></pre></li>
<li><p>NaN's don't compare equal to themselves:</p>
<pre><code>>>> np.nan == np.nan
False
</code></pre></li>
<li><p>The simple hash function above regards the bit-representation of floats, but this is problematic in the presence of negative-zero and signaling NaN's.</p></li>
</ul>
<p>See also the discussion in this question: <a href="http://stackoverflow.com/questions/650175/good-way-to-hash-a-float-vector">Good way to hash a float vector?</a></p>
| 0 |
2016-09-25T22:48:20Z
|
[
"python",
"arrays",
"numpy",
"hash"
] |
Automated Inclusion of Objects in Python List
| 39,682,201 |
<p>I'm declaring a class, and in the <code>__init__</code> method, I'm declaring two variables which will be associated with an instance of that class. Each declared variable is initialised as a NumPy array of zeros that is later filled with other data.</p>
<p>At some point, outside of this <code>__init__</code> method, I need to loop through an object containing each of these variables (NumPy arrays) and reset the array values in each to zero. Thus, in the <code>__init__</code> method, I would like to add all of these variables to a list to later iterate through. If I do that once manually, it's trivial.</p>
<p>However, I need to frequently add and remove some number of these variables being declared in <code>__init__</code>. Every time I do that, I don't want to have to manually adjust the variables that are contained in the list.</p>
<p>How can I create a <code>list</code>, <code>dict</code>, or other container of these variables that automatically adjusts itself so it contains all of these variables being initialised, regardless of the number of those variables? As an additional complication, <code>self.container_of_arrays</code> must not contain "other" variables from <code>__init__</code>, such as <code>self.array_length</code>.</p>
<p>What I have, where <code>self.container_of_arrays</code> must currently be manually adjusted if a <code>self.my_variable_three</code> is created:</p>
<pre><code>class generic_class():
def __init__(self, array_width_one, array_width_two):
self.array_length = some_integer
self.my_variable_one = numpy.zeros((self.array_length, array_width_one), dtype=float)
self.my_variable_two = numpy.zeros((self.array_length, array_width_two), dtype=float)
self.container_of_arrays = [self.my_variable_one, self.my_variable_two]
</code></pre>
<p>I tried to declare my variables within a <code>dict</code>, so that from the very start they are contained within that <code>dict</code>, but this leads to there being references to undefined variables. E.g.</p>
<pre><code> self.container_of_arrays = OrderedDict([(self.my_variable_one, numpy.zeros((self.array_length, array_width_one), dtype=float)),
(self.my_variable_two, numpy.zeros((self.array_length, array_width_two), dtype=float))
])
</code></pre>
<p><strong>Update:</strong></p>
<p>xli's answer provides the correct solution. As suggested, it's possible to access the arrays by name using a dict or OrderedDict. For anyone who wants to do so, here's the code I've actually implemented:</p>
<pre><code>my_data = [('variable_one_name', len(variable_one_data)),
('variable_two_name', len(variable_two_data)),
] # Intentionally outside the class in a location where variables are added by the user
class generic_class():
def __init__(self, array_length, my_data):
self.container_of_arrays = OrderedDict((variable_name, numerix.zeros((array_length, array_width), dtype=float))
for variable_name, array_width in my_data)
</code></pre>
| 0 |
2016-09-25T00:20:21Z
| 39,682,301 |
<p>Instead of creating a variable for each numpy array, why don't you just create a list of arrays containing each array you need, and reference them by index?</p>
<pre><code>class generic_class():
def __init__(self, array_length, array_widths=[]):
self.array_length = array_length
self.arrays = [
numpy.zeros((self.array_length, array_width), dtype=float)
for array_width in array_widths
]
</code></pre>
<p>Then you can access each array by index as <code>self.arrays[i]</code>.</p>
<p>Or, if you need to access the array by name, you can use a dict with just a string (the name of the array) as the key for each array. </p>
| 1 |
2016-09-25T00:35:40Z
|
[
"python",
"list",
"numpy",
"dictionary",
"containers"
] |
why is pymongo requiring sudo to pip install?
| 39,682,274 |
<p>why is pymongo requiring sudo for install? Its docs don't mention anything about sudo...</p>
<pre><code>(myapp) cchilders:~/projects/app (master)
$ sudo pip3 uninstall pymongo
Successfully uninstalled pymongo-3.3.0
The directory '/home/cchilders/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
(myapp) cchilders:~/projects/app (master)
$ pip3 install pymongo
Collecting pymongo
Using cached pymongo-3.3.0-cp35-cp35m-manylinux1_x86_64.whl
Installing collected packages: pymongo
Exception:
Traceback (most recent call last):
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 742, in install
**kwargs
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/wheel.py", line 287, in clobber
ensure_dir(dest) # common for the 'include' path
File "/home/cchilders/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir
os.makedirs(path)
File "/usr/lib/python3.5/os.py", line 241, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages'
(myapp) cchilders:~/projects/app (master)
$ sudo pip3 install pymongo
The directory '/home/cchilders/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/cchilders/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pymongo
Downloading pymongo-3.3.0-cp35-cp35m-manylinux1_x86_64.whl (337kB)
100% |ââââââââââââââââââââââââââââââââ| 337kB 1.5MB/s
Installing collected packages: pymongo
Successfully installed pymongo-3.3.0
</code></pre>
<p>perms are the same here and any other:</p>
<pre><code>drwxrwxr-x 6 cchilders cchilders 4096 Sep 24 19:42 myapp
-rw-r--r-- 1 cchilders cchilders 96 Feb 23 2016 initialize
drwxrwxr-x 6 cchilders cchilders 4096 Apr 21 16:19 knockoutjs_official_tutorial
drwxrwxr-x 6 cchilders cchilders 4096 Apr 3 10:38 my_scripting_library
drwxrwxr-x 8 cchilders cchilders 4096 Sep 15 03:41 neo4j_sandbox
</code></pre>
<p>Thank you</p>
| 0 |
2016-09-25T00:32:17Z
| 39,682,406 |
<p>Check your virtual environment ownership. If your don't have write permission to that path, you will need <code>sudo</code></p>
| 1 |
2016-09-25T00:53:46Z
|
[
"python",
"mongodb",
"ubuntu",
"pip",
"pymongo"
] |
How to debug ctypes without error message
| 39,682,318 |
<p>I have a simple python script that uses a c/c++ library with <code>ctypes</code>. My c++ library also contains a main method, so I can compile it without the <code>-shared</code> flag and it can be excecuted and it runs without issues.</p>
<p>However, when I run the same code from a python script using <code>ctypes</code>, a part of the c++ program is excecuted (I can tell that from the <code>cout</code> calls). Then the entire application, including the python script, termiantes (I can tell that from the missing <code>cout</code> and <code>print</code> calls). There is no error message, no segfault, no python stacktrace.</p>
<p>My question is: How can I debug this? What are possible reasons for this to happen?</p>
<p>Here is part of the code, however, since there is no error message, I don't know which code is relevant.</p>
<pre><code>import ctypes
interface = ctypes.CDLL("apprunner.so")
interface.start()
print "complete"
</code></pre>
<p>.</p>
<pre><code>#include "../../app/ShaderApp.cpp"
#include <iostream>
#include "TestApp.cpp"
TestApp* app = 0;
extern "C" void start() {
app = new TestApp();
cout << "Running from library" << endl;
app->run();
}
int main( int argc, const char* argv[]) {
cout << "Running from excecutable" << endl;
start();
}
</code></pre>
| 0 |
2016-09-25T00:38:04Z
| 39,682,494 |
<p>Typically you begin from a small mock-up library that just lets you test the function calls from python. When this is ready (all the debug prints are ok) you proceed further. In your example, comment out #include "testapp.cpp" and get the prints to cout working.</p>
| 0 |
2016-09-25T01:09:18Z
|
[
"python",
"c++",
"ctypes"
] |
Replacing string element in for loop Python
| 39,682,342 |
<p>I am reading data in from a text file so each row is a list of strings, and all those lists are in a data list. So my lists look like:</p>
<pre><code>data = [row1, row2, etc.]
row1 = [str1, str2, etc.]
</code></pre>
<p>I am trying to remove any $ or % signs that appear in the strings in a row list. I have checked that if I try and do this for one individual element, say the second row and the fourth element has a "%", so:</p>
<pre><code>data[1][3] = data[1][3].replace("%","")
</code></pre>
<p>This will properly remove it, but when I try and use a nested for loop to do it all:</p>
<pre><code>for row in data:
for x in row:
x = x.replace("%","")
x = x.replace("$","")
</code></pre>
<p>This doesn't remove any of the % or $ signs, I have tried just doing it without the second replace to see if it would at least remove the % signs, but even that didn't work.</p>
<p>Any ideas why this wouldn't work, or how I could do this?<br>
Thanks in advance for any help!</p>
| 0 |
2016-09-25T00:43:44Z
| 39,682,363 |
<p>The problem is that your <em>str</em> variable is shadowing the builtin Python <a href="https://docs.python.org/2.7/library/functions.html#str" rel="nofollow"><em>str</em></a> variable. That fix is easy. Just use another variable name.</p>
<p>The second problem is that the replaced string isn't being replaced in the row list itself. The fix is to save the replaced string back into the <em>row</em> list. For that, you can use <a href="https://docs.python.org/2.7/library/functions.html#enumerate" rel="nofollow"><em>enumerate()</em></a> to give you both the value and its position in the row:</p>
<pre><code>for row in data:
for i, x in enumerate(row):
x = x.replace("%","")
x = x.replace("$","")
row[i] = x
</code></pre>
| 1 |
2016-09-25T00:47:16Z
|
[
"python",
"python-2.7"
] |
Replacing string element in for loop Python
| 39,682,342 |
<p>I am reading data in from a text file so each row is a list of strings, and all those lists are in a data list. So my lists look like:</p>
<pre><code>data = [row1, row2, etc.]
row1 = [str1, str2, etc.]
</code></pre>
<p>I am trying to remove any $ or % signs that appear in the strings in a row list. I have checked that if I try and do this for one individual element, say the second row and the fourth element has a "%", so:</p>
<pre><code>data[1][3] = data[1][3].replace("%","")
</code></pre>
<p>This will properly remove it, but when I try and use a nested for loop to do it all:</p>
<pre><code>for row in data:
for x in row:
x = x.replace("%","")
x = x.replace("$","")
</code></pre>
<p>This doesn't remove any of the % or $ signs, I have tried just doing it without the second replace to see if it would at least remove the % signs, but even that didn't work.</p>
<p>Any ideas why this wouldn't work, or how I could do this?<br>
Thanks in advance for any help!</p>
| 0 |
2016-09-25T00:43:44Z
| 39,682,381 |
<p>You are assigning a new value to the name <code>x</code> but that does not change the contents of <code>row</code> or <code>data</code>. After changing <code>x</code>, you need to assign <code>row[j] = x</code> or <code>data[i][j] = x</code> for the appropriate column index <code>j</code> (and row index <code>i</code>). See also <a href="http://stackoverflow.com/questions/34820183/python-3-lists-dont-change-their-values">python 3: lists dont change their values</a></p>
| 0 |
2016-09-25T00:49:40Z
|
[
"python",
"python-2.7"
] |
Replacing string element in for loop Python
| 39,682,342 |
<p>I am reading data in from a text file so each row is a list of strings, and all those lists are in a data list. So my lists look like:</p>
<pre><code>data = [row1, row2, etc.]
row1 = [str1, str2, etc.]
</code></pre>
<p>I am trying to remove any $ or % signs that appear in the strings in a row list. I have checked that if I try and do this for one individual element, say the second row and the fourth element has a "%", so:</p>
<pre><code>data[1][3] = data[1][3].replace("%","")
</code></pre>
<p>This will properly remove it, but when I try and use a nested for loop to do it all:</p>
<pre><code>for row in data:
for x in row:
x = x.replace("%","")
x = x.replace("$","")
</code></pre>
<p>This doesn't remove any of the % or $ signs, I have tried just doing it without the second replace to see if it would at least remove the % signs, but even that didn't work.</p>
<p>Any ideas why this wouldn't work, or how I could do this?<br>
Thanks in advance for any help!</p>
| 0 |
2016-09-25T00:43:44Z
| 39,682,637 |
<p>Also in your in this case you can use list comprehension</p>
<pre><code>data = [[item.replace("%", "").replace("$", "0") for item in row] for row in data]
</code></pre>
| 0 |
2016-09-25T01:42:50Z
|
[
"python",
"python-2.7"
] |
Trying to convert Matlab .m symbolic function file(s) to SymPy symbolic expression
| 39,682,366 |
<p>I have computer generated .m files for electrical circuit transfer functions output by Sapwin 4.0
<a href="http://cirlab.dinfo.unifi.it/Sapwin4/" rel="nofollow">http://cirlab.dinfo.unifi.it/Sapwin4/</a></p>
<p>The .m files have fairly simple structure for my present interests:</p>
<pre class="lang-Matlab prettyprint-override"><code>function [out]=my003_v1(s,C1,C2,E1,R1,R2);
num = + ( E1 )+ ( E1*C1*R2 +E1*C2*R2 )*s;
den = + ( E1 +1 )+ ( E1*C1*R2 +C1*R2 +C1*R1 +E1*C2*R2 +C2*R2 )*s+ ( E1*C2*C1*R1*R2 +C2*C1*R1*R2 )*s^2;
out = num/den;
</code></pre>
<p>I want to convert many of these .m files into SymPy symbolic expressions for further symbolic manipulation</p>
<p>with open, infile.read(), indexing lines, slicing to get desired strings for args and num, den all work</p>
<p>So I just show cut down symbolic conversion steps with even the string variables replaced with the actual strings:
</p>
<pre><code>from sympy import symbols, var, sympify
var('s,C1,C2,E1,R1,R2')
'''
#awkward alternative to var:
exp_str='s,C1,C2,E1,R1,R2' + " = symbols('" + 's,C1,C2,E1,R1,R2' + "')"
exec(exp_str)
print(exp_str)
'''
a=sympify(' ( E1 )+ ( E1*C1*R2 +E1*C2*R2 )*s')
'''
# another alternative to sympify:
from sympy.parsing.sympy_parser import (parse_expr,
standard_transformations)
parse_expr(' ( E1 )+ ( E1*C1*R2 +E1*C2*R2 )*s', transformations=(standard_transformations))
'''
</code></pre>
<p>The triple quote blocks show alternatives I've already tried with similar results, same bottom line:</p>
<blockquote>
<p>TypeError: unsupported operand type(s) for *: 'function' and 'Symbol'</p>
</blockquote>
<p>The error report with code ran on SympyLive:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 12, in <module>
File "/base/data/home/apps/s~sympy-live-hrd/46.393464279709602171/sympy/sympy/core/sympify.py", line 322, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
File "/base/data/home/apps/s~sympy-live-hrd/46.393464279709602171/sympy/sympy/parsing/sympy_parser.py", line 894, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "/base/data/home/apps/s~sympy-live-hrd/46.393464279709602171/sympy/sympy/parsing/sympy_parser.py", line 807, in eval_expr
code, global_dict, local_dict) # take local objects in preference
File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'function' and 'Symbol'
</code></pre>
<p>I see similar error on my Anaconda3 recent install, Spyder, on IPython and regular console</p>
<p>sympify seems to work with similar expression structure in SymPy Live:</p>
<pre><code>>>> sympify(x*y+(z**k+x*y*z)*t)
t(xyz+zk)+xy
... sympify('-(x**k+ y*z*t+ m)*z')
z(âmâtyzâxk)
</code></pre>
<p>What about the .m file den string is breaking it?
or am I doing it wrong some other way?</p>
<p>for more fun, if I slice the .m den string earlier after the "=" to be safe, it includes the leading "+", and I get:</p>
<blockquote>
<p>TypeError: bad operand type for unary +: 'function'</p>
</blockquote>
<p>Which is a problem that can be worked around with the filtering but not allowing this unary use of "+" seems be a poor assumption
The numerator term in a transfer function may easily be positive or negative</p>
| 1 |
2016-09-25T00:47:39Z
| 39,682,578 |
<p>Well, let's try to find the minimum failing case:</p>
<pre><code>>>> a=sympify('E1*C2')
Traceback (most recent call last):
[...]
TypeError: unsupported operand type(s) for *: 'function' and 'Symbol'
</code></pre>
<p>which makes it clear it's the E1 which is the problem here, because it's an <a href="http://docs.sympy.org/latest/modules/functions/special.html?highlight=e1#sympy.functions.special.error_functions.E1" rel="nofollow">existing function</a>:</p>
<pre><code>>>> a=sympify('E1')
>>> a
<function E1 at 0x7fcb04c11510>
</code></pre>
<p>And thus the error message. One way to get around this would be to specify that you don't want E1 to be the function by overriding it in the locals argument:</p>
<pre><code>>>> a = sympify(' ( E1 )+ ( E1*C1*R2 +E1*C2*R2 )*s', locals={'E1': E1})
>>> a
E1 + s*(C1*E1*R2 + C2*E1*R2)
</code></pre>
<p>(after you've already done your <code>var</code> to create <code>E1</code> in the namespace), or more generally if you wanted to protect everything in your <code>vv</code>:</p>
<pre><code>vv = sympy.var('s,C1,C2,E1,R1,R2')
a=sympify(' ( E1 )+ ( E1*C1*R2 +E1*C2*R2 )*s', locals={str(v):v for v in vv})
</code></pre>
| 1 |
2016-09-25T01:30:50Z
|
[
"python",
"sympy"
] |
Exception when migrating custom User in Django
| 39,682,431 |
<p>I need to create a custom User for my app and followed exactly the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#a-full-example" rel="nofollow">example</a> from the documentation with the <code>AUTH_USER_MODEL = 'core.MyUser'</code> in my <code>settings.py</code>. However, when I make a new database, delete all the migrations folders and run the <code>python manage.py migrate</code> again, it gives me the exception like this </p>
<pre><code> File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 173, in handle
migration_name=self.migration_name,
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 47, in changes
changes = self._detect_changes(convert_apps, graph)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 132, in _detect_changes
self.old_apps = self.from_state.concrete_apps
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 180, in concrete_apps
self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 242, in __init__
self.render_multiple(list(models.values()) + self.real_models)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 277, in render_multiple
model.render(self)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 559, in render
body,
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/models/base.py", line 153, in __new__
raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))
TypeError: Customer cannot proxy the swapped model 'core.MyUser'.
</code></pre>
<p>I am not sure why there is a migrations script for the <code>customer</code> there, since in my app, I used to have the <code>Customer</code> model as well, though I deleted it already. </p>
<p>Then, I created a new django project to test and try to run the migration. Surprisingly, I also see those customer migration steps, but it run successfully. </p>
<pre><code> Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_customer... OK
Applying auth.0010_delete_customer... OK
Applying sessions.0001_initial... OK
</code></pre>
<p>In short, how can I create the custom User in Django 1.10 ? Example code can be viewed in here <a href="https://github.com/bubuzzz/django-customer-swap-exception" rel="nofollow">https://github.com/bubuzzz/django-customer-swap-exception</a></p>
| 0 |
2016-09-25T00:57:48Z
| 39,684,159 |
<p>You should not delete your migration folder. If you do that, django won't make migrations for you. Create migrations folder in your core app, create an empty <code>__init__.py</code> file inside it, remove your db.sqlite3 file, run ./manage.py makemigrations, and then migrate should work perfectly.</p>
| 1 |
2016-09-25T06:41:10Z
|
[
"python",
"django"
] |
Exception when migrating custom User in Django
| 39,682,431 |
<p>I need to create a custom User for my app and followed exactly the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#a-full-example" rel="nofollow">example</a> from the documentation with the <code>AUTH_USER_MODEL = 'core.MyUser'</code> in my <code>settings.py</code>. However, when I make a new database, delete all the migrations folders and run the <code>python manage.py migrate</code> again, it gives me the exception like this </p>
<pre><code> File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 173, in handle
migration_name=self.migration_name,
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 47, in changes
changes = self._detect_changes(convert_apps, graph)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 132, in _detect_changes
self.old_apps = self.from_state.concrete_apps
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 180, in concrete_apps
self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 242, in __init__
self.render_multiple(list(models.values()) + self.real_models)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 277, in render_multiple
model.render(self)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 559, in render
body,
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/models/base.py", line 153, in __new__
raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))
TypeError: Customer cannot proxy the swapped model 'core.MyUser'.
</code></pre>
<p>I am not sure why there is a migrations script for the <code>customer</code> there, since in my app, I used to have the <code>Customer</code> model as well, though I deleted it already. </p>
<p>Then, I created a new django project to test and try to run the migration. Surprisingly, I also see those customer migration steps, but it run successfully. </p>
<pre><code> Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_customer... OK
Applying auth.0010_delete_customer... OK
Applying sessions.0001_initial... OK
</code></pre>
<p>In short, how can I create the custom User in Django 1.10 ? Example code can be viewed in here <a href="https://github.com/bubuzzz/django-customer-swap-exception" rel="nofollow">https://github.com/bubuzzz/django-customer-swap-exception</a></p>
| 0 |
2016-09-25T00:57:48Z
| 39,684,429 |
<p>Mehdi Pourfar's answer is correct.If you want to know more details </p>
<blockquote>
<p>By running makemigrations, youâre telling Django that youâve made some changes to your models (in this case, youâve made new ones) and that youâd like the changes to be stored as a migration.</p>
<p>Migrations are how Django stores changes to your models (and thus your database schema) - theyâre just files on disk. You can read the migration for your new model if you like; itâs the file polls/migrations/0001_initial.py. Donât worry, youâre not expected to read them every time Django makes one, but theyâre designed to be human-editable in case you want to manually tweak how Django changes things.</p>
</blockquote>
<p>Tell django which app you want to make migrations all fix your problem.It will auto create a folder call migrations keep your model's record.</p>
<pre><code>python manage.py makemigrations core
</code></pre>
| 0 |
2016-09-25T07:28:03Z
|
[
"python",
"django"
] |
I have afunction that works locally on my django app but deployed it raises an list index out of range error
| 39,682,466 |
<p>I have a function that raises an error in my logs when I try to use it remotely. I have it run in my background task. the other task I have runs both locally and remotely. heres my code</p>
<p>my my_scraps.py</p>
<pre><code>def liveleak_task():
url = 'http://www.example1.com/rss?featured=1'
name = 'live leak'
live_leaks = [i for i in feedparser.parse(url).entries]
the_count = len(live_leaks)
live_entries = [{'href': live_leak.links[0]['href'],
'src': live_leak.media_thumbnail[0]['url'],
'text': live_leak.title,
'comments': live_leak.description,
'name': name,
'url': live_leak.links[0]['href'], # this is the link to the source
'embed': live_leak.links[1]['href'],
'author': None,
'video': False
} for live_leak in live_leaks][10]
return live_entries
def worldstar_task():
# scraping from worldstar
url_to = 'http://www.example2.com'
html = requests.get(url_to, headers=headers)
soup = BeautifulSoup(html.text, 'html5lib')
titles = soup.find_all('section', 'box')
def make_soup(url):
the_comments_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(the_comments_page.text, 'html5lib')
comment = soupdata.find('div')
para = comment.find_all('p')
kids = [child.text for child in para]
blu = str(kids).strip('[]')
return blu
name = 'World Star'
cleaned_titles = [title for title in titles if title.a.get('href') != 'vsubmit.php']
world_entries = [{'href': url_to + box.a.get('href'),
'src': box.img.get('src'),
'text': box.strong.a.text,
'comments': make_soup(url_to + box.a.get('href')),
'name': name,
'url': url_to + box.a.get('href'),
'embed': None,
'author': None,
'video': True
} for box in cleaned_titles][:10]
return world_entries
def scrambled(a, b):
site_one = a
site_two = b
merged = site_one+site_two
random.shuffle(merged)
for entry in merged:
post = Post() #
post.title = entry['text'] #
title = post.title #
if not Post.objects.filter(title=title):
post.title = entry['text']
post.name = entry['name']
post.url = entry['url']
post.body = entry['comments']
post.image_url = entry['src']
post.video_path = entry['embed']
post.author = None
post.video = True
post.status = 'draft'
post.save()
post.tags.add("video")
return merged
</code></pre>
<p>my tasks.py</p>
<pre><code>@app.task
def behind():
a = worldstar_task()
b = liveleak_task()
the_seen = scrambled(a, b)
return the_seen
</code></pre>
<p>my views.py</p>
<pre><code>def noindex(request):
behind.delay()
return redirect('/')
</code></pre>
<p>the traceback</p>
<pre><code>Task blog.tasks.behind[833ef3d3-91e7-4851-99ee-3f7cac4294d6] raised unexpected: IndexError('list index out of range',)
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.5/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/app/.heroku/python/lib/python3.5/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/app/blog/tasks.py", line 91, in behind
b = liveleak_task()
File "/app/blog/my_scraps.py", line 397, in liveleak_task
} for live_leak in live_leaks][10]
File "/app/blog/my_scraps.py", line 397, in <listcomp>
} for live_leak in live_leaks][10]
IndexError: list index out of range
</code></pre>
<p>I tried this</p>
<pre><code>the_count = len(live_leaks)
</code></pre>
<p>and then </p>
<pre><code>for live_leak in live_leaks][the_count -1]
</code></pre>
<p>then</p>
<p>-2 it worked locally but not remotely</p>
<p>then I tried </p>
<pre><code>:10 didn't work remotely or locally
</code></pre>
<p>didn't work. not sure why that isIf any one knows how I can fix this I'm all ears</p>
| 0 |
2016-09-25T01:04:31Z
| 39,682,849 |
<p>I have remedied the problem. I moved the [10] from where it was</p>
<pre><code> live_leaks = [i for i in feedparser.parse(url).entries]
the_count = len(live_leaks)
live_entries = [{'href': live_leak.links[0]['href'],
'src': live_leak.media_thumbnail[0]['url'],
'text': live_leak.title,
'comments': live_leak.description,
'name': name,
'url': live_leak.links[0]['href'], # this is the link to the source
'embed': live_leak.links[1]['href'],
'author': None,
'video': False
} for live_leak in live_leaks][10]<----here
return live_entries
</code></pre>
<p>to </p>
<pre><code> live_leaks = [i for i in feedparser.parse(url).entries][:10]<-------to here
the_count = len(live_leaks)
live_entries = [{'href': live_leak.links[0]['href'],
'src': live_leak.media_thumbnail[0]['url'],
'text': live_leak.title,
'comments': live_leak.description,
'name': name,
'url': live_leak.links[0]['href'], # this is the link to the source
'embed': live_leak.links[1]['href'],
'author': None,
'video': False
} for live_leak in live_leaks]
return live_entries
</code></pre>
<p>and I also added a colon in the front of the 10 like this</p>
<pre><code> [:10] this selects 10
[10] this selects the 10th
</code></pre>
<p>I hope this helps somebody</p>
| 0 |
2016-09-25T02:33:42Z
|
[
"python",
"django",
"indexing",
"deployment",
"syntax"
] |
How to use Python to decrypt files encrypted using Vim's cryptmethod=blowfish2?
| 39,682,512 |
<p>I would like to use Python to decrypt files encrypted using Vim encrypted with the <a href="http://vim.wikia.com/wiki/Encryption" rel="nofollow"><code>cryptmethod=blowfish2</code></a> method. I have not seen the encryption method documented anywhere and would appreciate help in figuring out how to do this.</p>
<p>Is this a standard ability with Python, or has a library been implemented, or other?</p>
| 2 |
2016-09-25T01:14:20Z
| 39,684,687 |
<p>Check out this module: <a href="https://github.com/nlitsme/vimdecrypt" rel="nofollow">https://github.com/nlitsme/vimdecrypt</a>. You can use it to decrypt your files, or study the code to learn how to implement it yourself. Example usage:</p>
<pre><code>from collections import namedtuple
from vimdecrypt import decryptfile
args = namedtuple('Args', ('verbose', 'test'))(False, False)
password = 'password'
with open('somefile', 'rb') as somefile:
decrypted = decryptfile(somefile.read(), password, args)
</code></pre>
| 3 |
2016-09-25T08:04:47Z
|
[
"python",
"encryption",
"vim",
"blowfish"
] |
Can't extract data from beautiful_soup object
| 39,682,561 |
<p>I'm crawling a website(<a href="https://www.zhihu.com/people/xie-ke-41/followers" rel="nofollow">https://www.zhihu.com/people/xie-ke-41/followers</a>), and i want to get all the followers' information. As you can see, some followers' information is bring with AJAX, I use the developers' tool in chrome and locate the url <a href="http://%22https://www.zhihu.com/node/ProfileFollowersListV2%22" rel="nofollow">the url which has followers' information</a></p>
<p>my code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
zhihu_rl = 'https://www.zhihu.com/node/ProfileFollowersListV2'
data = {
'method': 'next',
'params': '{"offset":20,"order_by":"created","hash_id":"86858a7a4aa77d290364625efcaacb70"}'}
headers = {
'Host': 'www.zhihu.com',
'Origin': 'https://www.zhihu.com',
'Referer': 'https://www.zhihu.com/people/xie-ke-41/followers',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
'X-Xsrftoken': 'foo',
'Cookie':'xxxxxxxxxxxx'}
rep = requests.post(url=zhihu_rl, data=data, headers=headers)
bsobj = BeautifulSoup(rep.text, 'html.parser')
print(bsobj.find_all('div', {'class': "zm-profile-card zm-profile-section-item zg-clear no-hovercard"}))
</code></pre>
<p>and an empty list returned.
i can see the information is developer's tool:
<a href="http://i.stack.imgur.com/PetCj.png" rel="nofollow"><img src="http://i.stack.imgur.com/PetCj.png" alt="thr information i see in developers' tool"></a>
,why can't bs4 extract them?
PS:i can get all the div,but when i limit the attributes.it failed</p>
| -1 |
2016-09-25T01:25:20Z
| 39,682,824 |
<p>You have used good header combination otherwise the server may not recognize your header and it thinks that you don't have javascript enabled. In limiting the attribute use . for class and # for id. Other CSS selectors will also work fine. You need also to use <a href="http://www.seleniumhq.org/" rel="nofollow">Selenium</a> for the javascript execution(ajax calls) since beautifulsoup lack this feature
Finally, make sure the website doesn't have anti-scraping protection. In that case, you need to use javascript runtimes like <a href="https://github.com/PiotrDabkowski/Js2Py" rel="nofollow">Js2Py</a></p>
| -2 |
2016-09-25T02:27:02Z
|
[
"python",
"beautifulsoup",
"web-crawler"
] |
Can't extract data from beautiful_soup object
| 39,682,561 |
<p>I'm crawling a website(<a href="https://www.zhihu.com/people/xie-ke-41/followers" rel="nofollow">https://www.zhihu.com/people/xie-ke-41/followers</a>), and i want to get all the followers' information. As you can see, some followers' information is bring with AJAX, I use the developers' tool in chrome and locate the url <a href="http://%22https://www.zhihu.com/node/ProfileFollowersListV2%22" rel="nofollow">the url which has followers' information</a></p>
<p>my code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
zhihu_rl = 'https://www.zhihu.com/node/ProfileFollowersListV2'
data = {
'method': 'next',
'params': '{"offset":20,"order_by":"created","hash_id":"86858a7a4aa77d290364625efcaacb70"}'}
headers = {
'Host': 'www.zhihu.com',
'Origin': 'https://www.zhihu.com',
'Referer': 'https://www.zhihu.com/people/xie-ke-41/followers',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
'X-Xsrftoken': 'foo',
'Cookie':'xxxxxxxxxxxx'}
rep = requests.post(url=zhihu_rl, data=data, headers=headers)
bsobj = BeautifulSoup(rep.text, 'html.parser')
print(bsobj.find_all('div', {'class': "zm-profile-card zm-profile-section-item zg-clear no-hovercard"}))
</code></pre>
<p>and an empty list returned.
i can see the information is developer's tool:
<a href="http://i.stack.imgur.com/PetCj.png" rel="nofollow"><img src="http://i.stack.imgur.com/PetCj.png" alt="thr information i see in developers' tool"></a>
,why can't bs4 extract them?
PS:i can get all the div,but when i limit the attributes.it failed</p>
| -1 |
2016-09-25T01:25:20Z
| 39,685,633 |
<p>The problem is you have escaped json, if you print the bsobj you can see output like:</p>
<pre><code>{"r":0,
"msg": ["<div class=\"zm-profile-card zm-profile-section-item zg-clear no-hovercard\">\n<div class=\"zg-right\">\n<button data-follow=\"m:button\" data-id=\"6327483c9e474097e7dbb2493a7f277c\" class=\"zg-btn zg-btn-follow zm-rich-follow-btn small nth-0\">\u5173\u6ce8\u4ed6<\/button>\n<\/div>\n<a title=\"\u738b\u5728\u9014\"\ndata-hovercard=\"p$t$wang-zai-tu-81\"\nclass=\"zm-item-link-avatar\"\nhref=\"\/people\/wang-zai-tu-81\">\n<img src=\"https:\/\/pic1.zhimg.com\/da8e974dc_m.jpg\" class=\"zm-item-img-avatar\">\n<\/a>\n<div class=\"zm-list-content-medium\">\n<h2 class=\"zm-list-content-title\"><span class=\"author-link-line\">\n<a data-hovercard=\"p$t$wang-zai-tu-81\" href=\"https:\/\/www.zhihu.com\/people\/wang-zai-tu-81\" class=\"zg-link author-link\" title=\"\u738b\u5728\u9014\"\n>\u738b\u5728\u9014<\/a><\/span><\/h2>\n\n<div class=\"summary-wrapper summary-wrapper--medium\">\n\n<span class=\"bio\"><\/span>\n<\/div>\n<div class=\"details zg-gray\">\n<a target=\"_blank\" href=\"\/people\/wang-zai-tu-81\/followers\" class=\"zg-link-gray-normal\">1 \u5173\u6ce8\u8005<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/wang-zai-tu-81\/asks\" class=\"zg-link-gray-normal\">0 \u63d0\u95ee<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/wang-zai-tu-81\/answers\" class=\"zg-link-gray-normal\">1 \u56de\u7b54<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/wang-zai-tu-81\" class=\"zg-link-gray-normal\">0 \u8d5e\u540c<\/a>\n<\/div>\n\n<\/div>\n<\/div>","<div class=\"zm-profile-card zm-profile-section-item zg-clear no-hovercard\">\n<div class=\"zg-right\">\n<button data-follow=\"m:button\" data-id=\"a3596eaecae6f05f0ddf95dfcc6b5517\" class=\"zg-btn zg-btn-follow zm-rich-follow-btn small nth-0\">\u5173\u6ce8<\/button>\n<\/div>\n<a title=\"\u7075\u9b42\"\ndata-hovercard=\"p$t$ling-hun-30-21\"\nclass=\"zm-item-link-avatar\"\nhref=\"\/people\/ling-hun-30-21\">\n<img src=\"https:\/\/pic1.zhimg.com\/da8e974dc_m.jpg\" class=\"zm-item-img-avatar\">\n<\/a>\n<div class=\"zm-list-content-medium\">\n<h2 class=\"zm-list-content-title\"><span class=\"author-link-line\">\n<a data-hovercard=\"p$t$ling-hun-30-21\" href=\"https:\/\/www.zhihu.com\/people\/ling-hun-30-21\" class=\"zg-link author-link\" title=\"\u7075\u9b42\"\n>\u7075\u9b42<\/a><\/span><\/h2>\n\n<div class=\"summary-wrapper summary-wrapper--medium\">\n\n<span class=\"bio\"><\/span>\n<\/div>\n<div class=\"details zg-gray\">\n<a target=\"_blank\" href=\"\/people\/ling-hun-30-21\/followers\" class=\"zg-link-gray-normal\">0 \u5173\u6ce8\u8005<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/ling-hun-30-21\/asks\" class=\"zg-link-gray-normal\">0 \u63d0\u95ee<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/ling-hun-30-21\/answers\" class=\"zg-link-gray-normal\">0 \u56de\u7b54<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/ling-hun-30-21\" class=\"zg-link-gray-normal\">0 \u8d5e\u540c<\/a>\n<\/div>\n\n<\/div>\n<\/div>","<div class=\"zm-profile-card zm-profile-section-item zg-clear no-hovercard\">\n<div class=\"zg-right\">\n<button data-follow=\"m:button\" data-id=\"74fad3af2b93f7da69c37eda64c31037\" class=\"zg-btn zg-btn-follow zm-rich-follow-btn small nth-0\">\u5173\u6ce8<\/button>\n<\/div>\n<a title=\"\u5f90\u6668\"\ndata-hovercard=\"p$t$xu-chen-77-49\"\nclass=\"zm-item-link-avatar\"\nhref=\"\/people\/xu-chen-77-49\">\n<img src=\"https:\/\/pic1.zhimg.com\/da8e974dc_m.jpg\" class=\"zm-item-img-avatar\">\n<\/a>\n<div class=\"zm-list-content-medium\">\n<h2 class=\"zm-list-content-title\"><span class=\"author-link-line\">\n<a data-hovercard=\"p$t$xu-chen-77-49\" href=\"https:\/\/www.zhihu.com\/people\/xu-chen-77-49\" class=\"zg-link author-link\" title=\"\u5f90\u6668\"\n>\u5f90\u6668<\/a><\/span><\/h2>\n\n<div class=\"summary-wrapper summary-wrapper--medium\">\n\n<span class=\"bio\">\u4f1a\u8ba1\u5e08<\/span>\n<\/div>\n<div class=\"details zg-gray\">\n<a target=\"_blank\" href=\"\/people\/xu-chen-77-49\/followers\" class=\"zg-link-gray-normal\">0 \u5173\u6ce8\u8005<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/xu-chen-77-49\/asks\" class=\"zg-link-gray-normal\">0 \u63d0\u95ee<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/xu-chen-77-49\/answers\" class=\"zg-link-gray-normal\">0 \u56de\u7b54<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/xu-chen-77-49\" class=\"zg-link-gray-normal\">0 \u8d5e\u540c<\/a>\n<\/div>\n\n<\/div>\n<\/div>","<div class=\"zm-profile-card zm-profile-section-item zg-clear no-hovercard\">\n<div class=\"zg-right\">\n<button data-follow=\"m:button\" data-id=\"032b36abfbe05a30913c794a4b099629\" class=\"zg-btn zg-btn-follow zm-rich-follow-btn small nth-0\">\u5173\u6ce8\u5979<\/button>\n<\/div>\n<a title=\"Shuai Zhang\"\ndata-hovercard=\"p$t$shuai-zhang-49\"\nclass=\"zm-item-link-avatar\"\nhref=\"\/people\/shuai-zhang-49\">\n<img src=\"https:\/\/pic2.zhimg.com\/v2-8aa42ff00873460e29444d62ff51acfd_m.jpg\" class=\"zm-item-img-avatar\">\n<\/a>\n<div class=\"zm-list-content-medium\">\n<h2 class=\"zm-list-content-title\"><span class=\"author-link-line\">\n<a data-hovercard=\"p$t$shuai-zhang-49\" href=\"https:\/\/www.zhihu.com\/people\/shuai-zhang-49\" class=\"zg-link author-link\" title=\"Shuai Zhang\"\n>Shuai Zhang<\/a><\/span><\/h2>\n\n<div class=\"summary-wrapper summary-wrapper--medium\">\n\n<span class=\"bio\"><\/span>\n<\/div>\n<div class=\"details zg-gray\">\n<a target=\"_blank\" href=\"\/people\/shuai-zhang-49\/followers\" class=\"zg-link-gray-normal\">79 \u5173\u6ce8\u8005<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/shuai-zhang-49\/asks\" class=\"zg-link-gray-normal\">1 \u63d0\u95ee<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/shuai-zhang-49\/answers\" class=\"zg-link-gray-normal\">119 \u56de\u7b54<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/shuai-zhang-49\" class=\"zg-link-gray-normal\">174 \u8d5e\u540c<\/a>\n<\/div>\n\n<\/div>\n<\/div>","<div class=\"zm-profile-card zm-profile-section-item zg-clear no-hovercard\">\n<div class=\"zg-right\">\n<button data-follow=\"m:button\" data-id=\"6388162f5357ca1bd872dc0b6efe4802\" class=\"zg-btn zg-btn-follow zm-rich-follow-btn small nth-0\">\u5173\u6ce8\u4ed6<\/button>\n<\/div>\n<a title=\"\u5468\u5468\"\ndata-hovercard=\"p$t$zhou-zhou-69-22\"\nclass=\"zm-item-link-avatar\"\nhref=\"\/people\/zhou-zhou-69-22\">\n<img src=\"https:\/\/pic1.zhimg.com\/da8e974dc_m.jpg\" class=\"zm-item-img-avatar\">\n<\/a>\n<div class=\"zm-list-content-medium\">\n<h2 class=\"zm-list-content-title\"><span class=\"author-link-line\">\n<a data-hovercard=\"p$t$zhou-zhou-69-22\" href=\"https:\/\/www.zhihu.com\/people\/zhou-zhou-69-22\" class=\"zg-link author-link\" title=\"\u5468\u5468\"\n>\u5468\u5468<\/a><\/span><\/h2>\n\n<div class=\"summary-wrapper summary-wrapper--medium\">\n\n<span class=\"bio\"><\/span>\n<\/div>\n<div class=\"details zg-gray\">\n<a target=\"_blank\" href=\"\/people\/zhou-zhou-69-22\/followers\" class=\"zg-link-gray-normal\">4 \u5173\u6ce8\u8005<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/zhou-zhou-69-22\/asks\" class=\"zg-link-gray-normal\">0 \u63d0\u95ee<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/zhou-zhou-69-22\/answers\" class=\"zg-link-gray-normal\">7 \u56de\u7b54<\/a>\n\/\n<a target=\"_blank\" href=\"\/people\/zhou-zhou-69-22\" class=\"zg-link-gray-normal\">1 \u8d5e\u540c<\/a>\n<\/div>\n\n<\/div>\n<\/div>","<div class=\"zm-profile-card zm-profile-section-item zg-clear no-hovercard\">\n<div class=\"zg-right\">\n<button data-follow=\"m:button\" data-id=\"3a1a9da0e0bb4abe2554fa2a6032f27f\" class=\"zg-btn zg-btn-follow zm-rich-follow-btn small nth-0\">\u5173\u6ce8\u5979<\/button>\n<\/div>\n<a title=\"\u7f8e\u7f8e\u836f\u5242\u5e08\"\ndata-hovercard=\"p$t$sui-nuo-81\"\nclass=\"zm-item-link-avatar\"\nhref=\"\/people\/sui-nuo-81\">\n<img src=\"https:\/\/pic2.zhimg.com\/ae23b8e89725a24de650dee53e9a60a5_m.jpg\" class=\"zm-item-img-avatar\">\n<\/a>\n<div class=\"zm-list-content-medium\">\n<h2 class=\"zm-list-content-title\"><span class=\"author-link-line\">\n<a data-hovercard=\"p$t$sui-nuo-81\" href=\"https:\/\/www.zhihu.com\/people\/sui-nuo-81\" class=\"zg-link
</code></pre>
<p>Unfortunately it is also invalid <em>json</em> so we cannot call <code>req.json()</code> and get nice un-escaped html so you will have to do it manually using <em>string_escape</em>:</p>
<pre><code>In [14]: rep = requests.post(url=zhihu_rl, data=data, headers=headers)
In [15]: bsobj = BeautifulSoup(rep.text.decode("string_escape"), 'lxml')
In [16]: ancs = (bsobj.find_all('div', {'class': 'zm-profile-card zm-profile-section-item zg-clear no-hovercard'}))
In [17]: len(ancs)
Out[17]: 20
</code></pre>
<p>It is also <em><code>zm-profile-section-item</code></em> not <em><code>zm-profile-section- item</code></em></p>
<p>Also in future never post login cookies, I could have full access to your account in a couple of minutes.</p>
| 1 |
2016-09-25T10:05:17Z
|
[
"python",
"beautifulsoup",
"web-crawler"
] |
Open a Datafile(csv,xls,xlsx,ods, etc) using "FILEPICKER" python?
| 39,682,574 |
<p>I got to know how to open a data file when we know the name and type of the file but how do we code to pick a file with file picker?</p>
<pre><code>import pyexcel as pe
records = pe.get_records(file_name="your_file.xls")
for record in records:
print("%s is aged at %d" % (record['Name'], record['Age']))
</code></pre>
| 1 |
2016-09-25T01:29:14Z
| 39,682,724 |
<p>You can def a function to return the name of the function which you can use as input for pe.get_records().
<code>
from tkinter import *
root = Tk()
def get_file_name():
global root
root.filename = filedialog.askopenfilename(initialdir = "D:/",title = "choose your excel file",filetypes = (("excel files","*.xls"),("all files","*.*")))
print (root.filename)
root.withdraw()
return root.filename</code></p>
| 0 |
2016-09-25T02:05:11Z
|
[
"python",
"excel",
"csv",
"xls",
"filepicker"
] |
Open a Datafile(csv,xls,xlsx,ods, etc) using "FILEPICKER" python?
| 39,682,574 |
<p>I got to know how to open a data file when we know the name and type of the file but how do we code to pick a file with file picker?</p>
<pre><code>import pyexcel as pe
records = pe.get_records(file_name="your_file.xls")
for record in records:
print("%s is aged at %d" % (record['Name'], record['Age']))
</code></pre>
| 1 |
2016-09-25T01:29:14Z
| 40,046,532 |
<p>I got the problem, Now this code runs!</p>
<pre><code>def loadCsv(self):
self.progressBar.setValue(0)
tab_table_view = QtGui.QWidget()
self.Tab.insertTab(0, tab_table_view, self.File_Name)
self.tableView = QtGui.QTableView(tab_table_view)
self.tableView.setGeometry(QtCore.QRect(0, 0, 721, 571))
self.model = QtGui.QStandardItemModel(self)
self.tableView.setModel(self.model)
self.tableView.horizontalHeader().setStretchLastSection(True)
self.model.clear()
file_name_temp=self.File_Name
if (".csv" or ".txt") in self.File_Name:
with open(file_name_temp, "rt") as fileInput:
i = 1
for row in csv.reader(fileInput):
items = [
QtGui.QStandardItem(field)
for field in row
]
self.model.appendRow(items)
# items.setFlags(QtCore.Qt.ItemIsUserCheckable |
# QtCore.Qt.ItemIsEnabled)
# items.setCheckState(QtCore.Qt.Unchecked)
Progress_completed = (i + 1) / (len(self.Datas)) * 100
self.progressBar.setValue(Progress_completed)
i += 1
elif(".xls" or ".xml" or ".xlsx" or ".xlsm")in self.File_Name:
import pandas as pd
import numpy as np
from itertools import chain
ii = 1
book=xlrd.open_workbook(self.File_Name)
sheet = book.sheet_by_index(0)
num_col = len(self.Datas.columns)
num_row = len(self.Datas)
colll = self.Datas.dtypes.index
npData=np.array(self.Datas)
# print(npData)
col_names = np.array(colll)
col_names = np.insert(col_names, 0, self.Datas.index.name)
for i in range (num_row):
# print (i)
if i is 0:
items = [QtGui.QStandardItem(col_names[j]) for j in range (num_col+1)]
else:
items = [QtGui.QStandardItem(str(self.Datas.index.values[i-1]))]+[ QtGui.QStandardItem(str(self.Datas.iat[i-1,j])) for j in range (num_col)]
self.model.appendRow(items)
Progress_completed = (ii + 1) / (len(self.Datas)) * 100
self.progressBar.setValue(Progress_completed)
ii += 1
self.Tab.setCurrentIndex(0)
</code></pre>
| 0 |
2016-10-14T15:12:49Z
|
[
"python",
"excel",
"csv",
"xls",
"filepicker"
] |
How to access variables from super?
| 39,682,611 |
<p>I need to get at some variables in a method called with <code>super</code> I would really like to do this instead of subclassing and then redefining the method...</p>
<pre><code>class Foo(object):
def bar(self):
x = 1
class SubFoo(Foo):
def bar(self):
print x
super(SubFoo, self).bar(*args, **kwargs)
</code></pre>
<p>but I am getting <code>object has no attribute 'request'</code></p>
<p>I tried using self as well but it would not work</p>
| -1 |
2016-09-25T01:38:14Z
| 39,682,642 |
<p>There are two ways you can do this, either make x an instance attribute, or return x in your <code>Foo.bar</code> method. Below example makes use of assigning x as an instance attribute: </p>
<pre><code>class Foo(object):
def bar(self):
self.x = 1
class SubFoo(Foo):
def bar(self):
super(SubFoo, self).bar()
print(self.x)
s = SubFoo()
s.bar()
</code></pre>
<p>The above execution will output <code>1</code>. </p>
<p>Alternatively, you can do a <code>return x</code> from your <code>Foo.bar</code> method, but remember, then that means you need to handle this return somehow. So, you need to make sure you get the return from your <code>super</code> call: </p>
<pre><code> def bar(self):
res = super(SubFoo, self).bar()
print(res)
</code></pre>
| 4 |
2016-09-25T01:43:51Z
|
[
"python"
] |
How to instantly destory a frame after a certain program is run
| 39,682,618 |
<p>This code is used to display 2 buttons, which are both linked to definitions which launch other sections of code, and then close the windows. I need to be able to close the widget after the button has been clicked</p>
<pre><code>from tkinter import *
import tkinter
import sys
root = tkinter.Tk()
def cs_age():
print("to be completed")
def cs_male():
print('type code here to add strength and athleticism to attributes')
#I need code here to destroy the window that popped up
cs_age()
def cs_female():
print('type code here')
# I need code here to destroy the window that popped up
cs_age()
def close_window()
#put code here to universally close all popped up widgets
</code></pre>
<h1>this is all to display buttons</h1>
<pre><code>frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack (side = BOTTOM)
cs_gendermale_button = tkinter.Button(frame, text=("Male"), fg='blue', command = cs_male)
cs_gendermale_button.pack( side = LEFT )
cs_genderfemale_button = tkinter.Button(frame, text=("Female"), fg='red', command = cs_female)
cs_genderfemale_button.pack( side = LEFT )
root.mainloop()
</code></pre>
| 0 |
2016-09-25T01:39:07Z
| 39,682,671 |
<p>This really should be a comment not an answer but I don't have enough reputation for that yet.
Is this what you're looking for?
<a href="http://stackoverflow.com/questions/8009176/function-to-close-the-window-in-tkinter">Function to close the window in Tkinter</a></p>
| -1 |
2016-09-25T01:51:09Z
|
[
"python",
"tkinter"
] |
Capture more than one value from URL with Flask/Python
| 39,682,641 |
<p>I want to pass values to my Python script based on what button was clicked in the HTML. I can do it like this if there is only one value:</p>
<pre><code>@app.route('/', defaults={'category': ''})
@app.route('/<category>')
def index(category):
</code></pre>
<p>But altogether there are 3 values what I want to capture, and I can't figure out how to do that. All of these values are optional. One (a sorting method) has a default value set, the other two are not set by default.</p>
<p>How can I make this work within a single function and 3 variables? Thanks.</p>
| 0 |
2016-09-25T01:43:31Z
| 39,682,672 |
<p>You can use <code>request.args</code> for query string parameters, which will be optional:</p>
<pre><code>@app.route('/')
def index():
category = request.args.get('category', '')
attr1 = request.args.get('attr1')
attr2 = request.args.get('attr2')
</code></pre>
<p><code>request.args</code> is a dict (more exactly a MultiDict).</p>
<p>A request would look like this</p>
<p><code>/?category=my_category&attr1=some_value&attr2=some_value</code>
or</p>
<p><code>/?attr1=some_value</code></p>
<p><code>/</code></p>
| 1 |
2016-09-25T01:51:19Z
|
[
"python",
"flask"
] |
Capture more than one value from URL with Flask/Python
| 39,682,641 |
<p>I want to pass values to my Python script based on what button was clicked in the HTML. I can do it like this if there is only one value:</p>
<pre><code>@app.route('/', defaults={'category': ''})
@app.route('/<category>')
def index(category):
</code></pre>
<p>But altogether there are 3 values what I want to capture, and I can't figure out how to do that. All of these values are optional. One (a sorting method) has a default value set, the other two are not set by default.</p>
<p>How can I make this work within a single function and 3 variables? Thanks.</p>
| 0 |
2016-09-25T01:43:31Z
| 39,682,674 |
<p>You can set more than 1 variable in your routing/function:</p>
<pre><code>@app.route('/', defaults={'category': '', 'var2': '', 'var3': ''})
@app.route('/<category>/<var2>/<var3>')
def index(category, var2, var3):
</code></pre>
| 0 |
2016-09-25T01:51:25Z
|
[
"python",
"flask"
] |
How to set PYTHONPATH to multiple folders
| 39,682,688 |
<p>In <code>~/.bash_profile</code> file (OS X) I've set PYTHONPATH to point to two folders:</p>
<pre><code>export PYTHONPATH=/Applications/python/common:$PYTHONPATH
export PYTHONPATH=/Applications/sitecustomize:$PYTHONPATH
</code></pre>
<p>Even while <code>sitecustomize</code> folder is set on a second line (after <code>/common</code>)
the first path is ignored and I am not able to import any module from the path defined in a first line. What needs to be revised in above syntax to make both folders PYTHONPATHish to Python?</p>
| 2 |
2016-09-25T01:53:46Z
| 39,682,723 |
<p>Append your paths so there is only one PYTHONPATH. </p>
<pre><code>PYTHONPATH="/Applications/python/common:/Applications/sitecustomize:$PYTHONPATH"
export PYTHONPATH
</code></pre>
<p>Then <code>source ~/.bash_profile</code></p>
<p>OR import them into your Python script (this would only work for the script added to):</p>
<pre><code>import sys
sys.path.append("/Applications/python/common")
sys.path.append("/Applications/sitecustomize")
</code></pre>
| 0 |
2016-09-25T02:05:10Z
|
[
"python",
"bash"
] |
Code Not Converging Vanilla Gradient Descent
| 39,682,732 |
<p>I have a specific analytical gradient I am using to calculate my cost f(x,y), and gradients dx and dy. It runs, but I can't tell if my gradient descent is broken. Should I plot my partial derivatives x and y?</p>
<pre><code>import math
gamma = 0.00001 # learning rate
iterations = 10000 #steps
theta = np.array([0,5]) #starting value
thetas = []
costs = []
# calculate cost of any point
def cost(theta):
x = theta[0]
y = theta[1]
return 100*x*math.exp(-0.5*x*x+0.5*x-0.5*y*y-y+math.pi)
def gradient(theta):
x = theta[0]
y = theta[1]
dx = 100*math.exp(-0.5*x*x+0.5*x-0.0035*y*y-y+math.pi)*(1+x*(-x + 0.5))
dy = 100*x*math.exp(-0.5*x*x+0.5*x-0.05*y*y-y+math.pi)*(-y-1)
gradients = np.array([dx,dy])
return gradients
#for 2 features
for step in range(iterations):
theta = theta - gamma*gradient(theta)
value = cost(theta)
thetas.append(theta)
costs.append(value)
thetas = np.array(thetas)
X = thetas[:,0]
Y = thetas[:,1]
Z = np.array(costs)
iterations = [num for num in range(iterations)]
plt.plot(Z)
plt.xlabel("num. iteration")
plt.ylabel("cost")
</code></pre>
| 0 |
2016-09-25T02:07:34Z
| 39,689,425 |
<p>I strongly recommend you check whether or not your analytic gradient is working correcly by first evaluating it against a numerical gradient.
I.e make sure that your f'(x) = (f(x+h) - f(x)) / h for some small h.</p>
<p>After that, make sure your updates are actually in the right direction by picking a point where you know x or y should decrease and then checking the sign of your gradient function output. </p>
<p>Of course make sure your goal is actually minimization vs maximization.</p>
| 2 |
2016-09-25T16:54:26Z
|
[
"python",
"machine-learning",
"gradient-descent"
] |
Django ORM: Models with 2 table referencing each other
| 39,682,811 |
<p>I have 2 tables. User and Group. 1:Many relationship. Each user can only belong to a single group. </p>
<p>here's the model.py. </p>
<pre><code>class Group(models.Model):
group_name = models.CharField(max_length=150, blank=True, null=True)
group_description = models.TextField(blank=True, null=True)
group_creator = models.ForeignKey(User, models.DO_NOTHING)
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
...
group = models.ForeignKey(Group, models.DO_NOTHING)
</code></pre>
<p>The issue I have is that they are both referencing each other which is acceptable in MySQL and Oracle, but, I get an error when migrating:</p>
<blockquote>
<p>group_creator = models.ForeignKey(User, models.DO_NOTHING)
NameError: name 'User' is not defined</p>
</blockquote>
<p>Now when I reverse the order (so, User first than Group), I get</p>
<blockquote>
<p>group = models.ForeignKey(Group, models.DO_NOTHING, blank=True, null=True)
NameError: name 'Group' is not defined</p>
</blockquote>
<p>This is getting quite frustrating. I have a few work around (make it a many:many and keep creator on Group class), but before I start destroying my datamodel and move data move all the data around, I wonder if anyone has this issue before. How did you solve this? Do you really have to change your datamodel?</p>
| 0 |
2016-09-25T02:23:44Z
| 39,682,894 |
<p>Add <code>related_name</code> to your <strong>ForeignKey</strong> fields:</p>
<pre><code>class Group(models.Model):
group_name = models.CharField(max_length=150, blank=True, null=True)
group_description = models.TextField(blank=True, null=True)
group_creator = models.ForeignKey('User',related_name='myUser')
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
group = models.ForeignKey('Group', related_name='MyGroup')
</code></pre>
| 0 |
2016-09-25T02:44:52Z
|
[
"python",
"mysql",
"django"
] |
Django ORM: Models with 2 table referencing each other
| 39,682,811 |
<p>I have 2 tables. User and Group. 1:Many relationship. Each user can only belong to a single group. </p>
<p>here's the model.py. </p>
<pre><code>class Group(models.Model):
group_name = models.CharField(max_length=150, blank=True, null=True)
group_description = models.TextField(blank=True, null=True)
group_creator = models.ForeignKey(User, models.DO_NOTHING)
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
...
group = models.ForeignKey(Group, models.DO_NOTHING)
</code></pre>
<p>The issue I have is that they are both referencing each other which is acceptable in MySQL and Oracle, but, I get an error when migrating:</p>
<blockquote>
<p>group_creator = models.ForeignKey(User, models.DO_NOTHING)
NameError: name 'User' is not defined</p>
</blockquote>
<p>Now when I reverse the order (so, User first than Group), I get</p>
<blockquote>
<p>group = models.ForeignKey(Group, models.DO_NOTHING, blank=True, null=True)
NameError: name 'Group' is not defined</p>
</blockquote>
<p>This is getting quite frustrating. I have a few work around (make it a many:many and keep creator on Group class), but before I start destroying my datamodel and move data move all the data around, I wonder if anyone has this issue before. How did you solve this? Do you really have to change your datamodel?</p>
| 0 |
2016-09-25T02:23:44Z
| 39,683,975 |
<p>as Pourfar mentioned in a comment, you may avoid the <code>NameError</code> via the quoting the model object as string. also it is safe to set <code>related_name</code> for accessing this relation.</p>
<pre><code>class Group(models.Model):
...
group_creator = models.ForeignKey('User', related_name='creator_set')
</code></pre>
<p>and then, with your constraint,</p>
<blockquote>
<p>Each user can only belong to a single group.</p>
</blockquote>
<p>in that case, <code>OneToOneField</code> is more appropriate.</p>
<pre><code>class User(models.Model):
...
group = models.OneToOneField(Group)
</code></pre>
<p>then you can access the relations as follows:</p>
<pre><code># USER is a User object
GROUP_BELONGED = USER.group # access to 1-1 relation
GROUP_CREATED = USER.creator_set.all() # reverse access to foreignkey relation
# now GROUP_BELONGED is a Group object
CREATOR = GROUP_BELONGED.group_creator # access to foreignkey relation
</code></pre>
| 1 |
2016-09-25T06:11:08Z
|
[
"python",
"mysql",
"django"
] |
TM1 REST API Python Requests ConnectionResetError MaxRetryError ProxyError but JavaScript/jQuery Works
| 39,682,812 |
<p>I am trying to run a get request using the TM1 REST API and Python Requests but receive a ConnectionResetError / MaxRetryError / ProxyError. Here is my code:</p>
<pre><code>headers = {'Accept' : 'application/json; charset=utf-8',
'Content-Type': 'text/plain; charset=utf-8'
}
login = b64encode(str.encode("{}:{}:{}".format(user, password, namespace))).decode("ascii")
headers['Authorization'] = 'CAMNamespace {}'.format(login)
s = requests.Session()
r = s.get(url+query, headers=headers, proxies=urllib.request.getproxies())
</code></pre>
<p>I've tried the get request with proxy auth / no auth / no proxies but i get the same 3 errors. </p>
<p>For reference, the same url is https and works in JavaScript/jQuery:</p>
<pre><code>function updateTable(){
$.ajax({
async:false,
headers: {
'Accept' : 'application/json; charset=utf-8',
'Content-Type': 'text/plain; charset=utf-8',
'Authorization' : 'CAMNamespace ' + btoa('username' + ':' + 'password' + ':' + 'namespace')
},
url: 'url_is_here',
success: function(data){data_is_here}
}
</code></pre>
<p>Here is the TraceBack:</p>
<pre><code>---------------------------------------------------------------------------
ConnectionResetError Traceback (most recent call last)
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, **response_kw)
571 if is_new_proxy_conn:
--> 572 self._prepare_proxy(conn)
573
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _prepare_proxy(self, conn)
779
--> 780 conn.connect()
781
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py in connect(self)
288 server_hostname=hostname,
--> 289 ssl_version=resolved_ssl_version)
290
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir)
307 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
--> 308 return context.wrap_socket(sock, server_hostname=server_hostname)
309
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
376 server_hostname=server_hostname,
--> 377 _context=self)
378
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\ssl.py in __init__(self, sock, keyfile, certfile, server_side, cert_reqs, ssl_version, ca_certs, do_handshake_on_connect, family, type, proto, fileno, suppress_ragged_eofs, npn_protocols, ciphers, server_hostname, _context)
751 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 752 self.do_handshake()
753
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\ssl.py in do_handshake(self, block)
987 self.settimeout(None)
--> 988 self._sslobj.do_handshake()
989 finally:
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\ssl.py in do_handshake(self)
632 """Start the SSL/TLS handshake."""
--> 633 self._sslobj.do_handshake()
634 if self.context.check_hostname:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
MaxRetryError Traceback (most recent call last)
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
402 retries=self.max_retries,
--> 403 timeout=timeout
404 )
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, **response_kw)
622 retries = retries.increment(method, url, error=e, _pool=self,
--> 623 _stacktrace=sys.exc_info()[2])
624 retries.sleep()
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
280 if new_retry.is_exhausted():
--> 281 raise MaxRetryError(_pool, url, error or ResponseError(cause))
282
MaxRetryError: HTTPSConnectionPool(host='ip', port=49003): Max retries exceeded with url: /api/v1/Threads (Caused by ProxyError('Cannot connect to proxy.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)))
During handling of the above exception, another exception occurred:
ProxyError Traceback (most recent call last)
<ipython-input-36-0d70f21b1422> in <module>()
1 s = requests.Session()
----> 2 r = s.get(url+query, headers=headers)
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\sessions.py in get(self, url, **kwargs)
485
486 kwargs.setdefault('allow_redirects', True)
--> 487 return self.request('GET', url, **kwargs)
488
489 def options(self, url, **kwargs):
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
473 }
474 send_kwargs.update(settings)
--> 475 resp = self.send(prep, **send_kwargs)
476
477 return resp
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
583
584 # Send the request
--> 585 r = adapter.send(request, **kwargs)
586
587 # Total elapsed time of the request (approximately)
C:\Users\vmora\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
463
464 if isinstance(e.reason, _ProxyError):
--> 465 raise ProxyError(e, request=request)
466
467 raise ConnectionError(e, request=request)
ProxyError: HTTPSConnectionPool(host='ip', port=49003): Max retries exceeded with url: /api/v1/Threads (Caused by ProxyError('Cannot connect to proxy.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)))
</code></pre>
| 1 |
2016-09-25T02:23:58Z
| 39,733,432 |
<p>A couple of people at work helped me solve my problem. The http and https proxies that I had set in my environment variables were causing the issue. I removed them / restarted / and was then able to query the api.</p>
| 0 |
2016-09-27T20:08:21Z
|
[
"jquery",
"python",
"rest",
"python-requests",
"cognos-tm1"
] |
Is it possible to access a local variable in another function?
| 39,682,842 |
<p>Goal: Need to use local variable in another function. Is that possible in Python?</p>
<p>I would like to use the local variable in some other function. Because in my case I need to use a counter to see the number of connections happening and number of connections releasing/ For that I am maintaining a counter. To implement that I have written sample code for count and returning local variable in another function.</p>
<p>How can I print <code>t</code> & <code>my_reply</code> in the <code>test()</code> function?</p>
<p>Code: counter_glob.py</p>
<pre><code>my_test = 0
t = 0
def test():
print("I: ",t)
print("IIIIIIII: ",my_reply)
def my():
global t
reply = foo()
t = reply
print("reply:",reply)
print("ttttt:",t)
def foo():
global my_test
my_test1 = 0
my_test += 1
print my_test1
my_test1 = my_test
my_test += 1
print("my_test:",my_test1)
return my_test1
my()
</code></pre>
<p>Result:</p>
<pre class="lang-none prettyprint-override"><code>> $ python counter_glob.py
0
('my_test:', 1)
('reply:', 1)
('ttttt:', 1)
</code></pre>
| 0 |
2016-09-25T02:32:22Z
| 39,682,956 |
<p>As I know, you can't get access to local variable outside function. But even you can in my opinion it will be a bad practice.</p>
<p>Why not use function or class.</p>
<pre><code>connections = 0
def set_connection_number(value):
global connections; connections = value;
def get_connection_number():
global connections;
return connections;
# test
set_connection_number(10)
print("Current connections {}".format(get_connection_number()))
</code></pre>
| 0 |
2016-09-25T02:59:26Z
|
[
"python",
"python-2.7",
"python-3.x"
] |
Is it possible to access a local variable in another function?
| 39,682,842 |
<p>Goal: Need to use local variable in another function. Is that possible in Python?</p>
<p>I would like to use the local variable in some other function. Because in my case I need to use a counter to see the number of connections happening and number of connections releasing/ For that I am maintaining a counter. To implement that I have written sample code for count and returning local variable in another function.</p>
<p>How can I print <code>t</code> & <code>my_reply</code> in the <code>test()</code> function?</p>
<p>Code: counter_glob.py</p>
<pre><code>my_test = 0
t = 0
def test():
print("I: ",t)
print("IIIIIIII: ",my_reply)
def my():
global t
reply = foo()
t = reply
print("reply:",reply)
print("ttttt:",t)
def foo():
global my_test
my_test1 = 0
my_test += 1
print my_test1
my_test1 = my_test
my_test += 1
print("my_test:",my_test1)
return my_test1
my()
</code></pre>
<p>Result:</p>
<pre class="lang-none prettyprint-override"><code>> $ python counter_glob.py
0
('my_test:', 1)
('reply:', 1)
('ttttt:', 1)
</code></pre>
| 0 |
2016-09-25T02:32:22Z
| 39,683,843 |
<p>There are different ways to access the local scope of a function. You can return the whole local scope if you want by calling <code>locals()</code> this will give you the entire local scope of a function, it's atypical to save the local scope. For your functions you can save the variables that you need in the function itself, <em><code>func.var = value</code></em>: </p>
<pre><code>def test():
print("I: ", my.t)
print("IIIIIIII: ", my.reply)
def my():
my.reply = foo()
my.t = m.reply
print("reply:", my.reply)
print("ttttt:", my.t)
</code></pre>
<p>You can now access <code>t</code> and <code>reply</code> normally. Each time you call your function <code>my</code> and <code>reply</code> will be updated, whatever <code>foo</code> returns will be assigned to <code>my.reply</code>. </p>
| 1 |
2016-09-25T05:52:18Z
|
[
"python",
"python-2.7",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.