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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Shorten a list of tuples by cutting out loops? | 38,862,164 | <p>I have a function that generates a list of tuples like:</p>
<pre><code>[(0, 0), (1, 1), (1, 2), (1,3), (2, 4), (3, 5), (4, 5)]
</code></pre>
<p>which are used to represent a path of tiles (row, column) in a game I'm making.</p>
<p>The function that I use to generate these paths isn't perfect, since it often produces "loops", as shown below:</p>
<pre><code>[(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3),
(3, 2), (4, 1)]
</code></pre>
<p><img src="http://i.stack.imgur.com/Qc5zp.png" alt="Image"></p>
<p>The path above should instead look like:</p>
<pre><code>[(2, 0), (2, 1), (3, 2), (4, 1)]
</code></pre>
<p><img src="http://i.stack.imgur.com/dOwTC.png" alt="Image"></p>
<p>These paths can contain any number of loops, which can be of any size and shape.</p>
<p>So my question is, how do I write a function in python that cuts the loopy list and returns a new, shorter list that does not have these loops.</p>
<p>My attempt below:</p>
<pre><code>def Cut_Out_Loops(Path):
NewList = list(Path)
Cutting = True
a = 0
for Cords in Path:
a += 1
try:
for i in range(a + 2, len(Path)):
if (Path[i][0] == Cords[0] and abs(Path[i][1] - Cords[1]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
elif Path[i][1] == Cords[1] and abs(Path[i][0] - Cords[0]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
elif abs(Path[i][0] - Cords[0]) == 1 and abs(Path[i][1] - Cords[1]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
elif abs(Path[i][1] - Cords[1]) == 1 and abs(Path[i][0] - Cords[0]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
Cutting = False
except IndexError:
Cutting = True
</code></pre>
| 4 | 2016-08-09T23:49:09Z | 38,862,312 | <p>Although your definition of a "loop" isn't too clear, try this</p>
<pre><code>def clean(path):
path1 = []
for (x1,y1) in path:
for (i,(x2,y2)) in enumerate(path1[:-1]):
if abs(x1-x2) <= 1 and abs(y1-y2) <= 1:
path1 = path1[:i+1]
break
path1.append((x1,y1))
return path1
</code></pre>
<p>It definitely works for your example:</p>
<pre><code> >>> path = [(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3), (3, 2), (4, 1)]
>>> clean(path)
[(2, 0), (2, 1), (3, 2), (4, 1)]
</code></pre>
<p>That said, it is just the most straightforward of brute force solutions. The complexity is quadratic.</p>
| 2 | 2016-08-10T00:08:49Z | [
"python",
"list",
"tuples"
] |
Shorten a list of tuples by cutting out loops? | 38,862,164 | <p>I have a function that generates a list of tuples like:</p>
<pre><code>[(0, 0), (1, 1), (1, 2), (1,3), (2, 4), (3, 5), (4, 5)]
</code></pre>
<p>which are used to represent a path of tiles (row, column) in a game I'm making.</p>
<p>The function that I use to generate these paths isn't perfect, since it often produces "loops", as shown below:</p>
<pre><code>[(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3),
(3, 2), (4, 1)]
</code></pre>
<p><img src="http://i.stack.imgur.com/Qc5zp.png" alt="Image"></p>
<p>The path above should instead look like:</p>
<pre><code>[(2, 0), (2, 1), (3, 2), (4, 1)]
</code></pre>
<p><img src="http://i.stack.imgur.com/dOwTC.png" alt="Image"></p>
<p>These paths can contain any number of loops, which can be of any size and shape.</p>
<p>So my question is, how do I write a function in python that cuts the loopy list and returns a new, shorter list that does not have these loops.</p>
<p>My attempt below:</p>
<pre><code>def Cut_Out_Loops(Path):
NewList = list(Path)
Cutting = True
a = 0
for Cords in Path:
a += 1
try:
for i in range(a + 2, len(Path)):
if (Path[i][0] == Cords[0] and abs(Path[i][1] - Cords[1]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
elif Path[i][1] == Cords[1] and abs(Path[i][0] - Cords[0]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
elif abs(Path[i][0] - Cords[0]) == 1 and abs(Path[i][1] - Cords[1]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
elif abs(Path[i][1] - Cords[1]) == 1 and abs(Path[i][0] - Cords[0]) == 1:
NewList = NewList[0:a] + NewList[i:]
Path = list(NewList)
Cutting = False
except IndexError:
Cutting = True
</code></pre>
| 4 | 2016-08-09T23:49:09Z | 38,862,351 | <p>How long are your paths? If they're all under 1000 elements, even a naive brute-force algorithm would work:</p>
<pre><code>path = [
(2, 0),
(2, 1),
(1, 2),
(0, 3),
(0, 4),
(1, 5),
(2, 5),
(3, 4),
(3, 3),
(3, 2),
(4, 1)
]
def adjacent(elem, next_elem):
return (abs(elem[0] - next_elem[0]) <= 1 and
abs(elem[1] - next_elem[1]) <= 1)
new_path = []
i = 0
while True:
elem = path[i]
new_path.append(elem)
if i + 1 == len(path):
break
j = len(path) - 1
while True:
future_elem = path[j]
if adjacent(elem, future_elem):
break
j -= 1
i = j
print new_path
</code></pre>
| 1 | 2016-08-10T00:16:12Z | [
"python",
"list",
"tuples"
] |
When does a class warrant a sub-class? | 38,862,165 | <p>For example, I am trying to build an enemy class for a simple game. Each <em>enemy</em> that spawns has a <em>type</em> which affects it stats which are fields in the <em>enemy</em> class.</p>
<pre><code>class Enemy:
#Base Stats for all enemies
name = "foo"
current_health = 4
max_health = 4
attack = 0
defense = 0
armor = 0
initiative = 0
initMod = 0
alive = True
</code></pre>
<p>Should each <em>type</em> be a <strong>subclass</strong> of <em>enemy</em> like so..</p>
<pre><code>class goblin(Enemy):
name = goblin;
current_health = 8
max_health = 8
attack = 3
defense = 2
armor = 0
def attack(){
//goblin-specific attack
}
</code></pre>
<p>But this method means that I would have to build a class for each individual <em>type</em> (which would be 80+ classes), or is there a better way to do it? This <em>enemy</em> is going to be randomized, so I was thinking the <em>types</em> could also be put into a <strong>dictionary</strong> which uses the names of the <em>types</em> as keywords. Although I'm not entirely sure how I could implement that.</p>
| 0 | 2016-08-09T23:49:14Z | 38,862,272 | <p>If you want to go the dictionary route you could do something like this with a tuple being returned by the key:</p>
<pre><code>enemy_types = {"goblin": ("goblin", 8, 8, 3, 2, 0, goblin_attack)}
def goblin_attack(enemy):
do_stuff()
</code></pre>
<p>Though you may want to use a named_tuple </p>
<p><a href="http://stackoverflow.com/a/13700868/2489837">http://stackoverflow.com/a/13700868/2489837</a></p>
<p>to make sure you don't mix up the fields in the tuple</p>
| 0 | 2016-08-10T00:03:24Z | [
"python",
"dictionary",
"inheritance",
"pygame",
"python-object"
] |
When does a class warrant a sub-class? | 38,862,165 | <p>For example, I am trying to build an enemy class for a simple game. Each <em>enemy</em> that spawns has a <em>type</em> which affects it stats which are fields in the <em>enemy</em> class.</p>
<pre><code>class Enemy:
#Base Stats for all enemies
name = "foo"
current_health = 4
max_health = 4
attack = 0
defense = 0
armor = 0
initiative = 0
initMod = 0
alive = True
</code></pre>
<p>Should each <em>type</em> be a <strong>subclass</strong> of <em>enemy</em> like so..</p>
<pre><code>class goblin(Enemy):
name = goblin;
current_health = 8
max_health = 8
attack = 3
defense = 2
armor = 0
def attack(){
//goblin-specific attack
}
</code></pre>
<p>But this method means that I would have to build a class for each individual <em>type</em> (which would be 80+ classes), or is there a better way to do it? This <em>enemy</em> is going to be randomized, so I was thinking the <em>types</em> could also be put into a <strong>dictionary</strong> which uses the names of the <em>types</em> as keywords. Although I'm not entirely sure how I could implement that.</p>
| 0 | 2016-08-09T23:49:14Z | 38,862,275 | <p>If the set of attributes and possible actions for each enemy type is mostly common across types, I don't see a reason to do anything more complicated than defining an 80 item enumeration for the type, and using a single class called <code>Enemy</code>.</p>
<p>If you do need a variety of actions and such, perhaps you could group your 80 types into various collections that would then have common attributes (e.g. <code>FlyingEnemy</code>, <code>UndeadEnemy</code>, etc). Those would then become your sub-classes.</p>
| 0 | 2016-08-10T00:03:28Z | [
"python",
"dictionary",
"inheritance",
"pygame",
"python-object"
] |
When does a class warrant a sub-class? | 38,862,165 | <p>For example, I am trying to build an enemy class for a simple game. Each <em>enemy</em> that spawns has a <em>type</em> which affects it stats which are fields in the <em>enemy</em> class.</p>
<pre><code>class Enemy:
#Base Stats for all enemies
name = "foo"
current_health = 4
max_health = 4
attack = 0
defense = 0
armor = 0
initiative = 0
initMod = 0
alive = True
</code></pre>
<p>Should each <em>type</em> be a <strong>subclass</strong> of <em>enemy</em> like so..</p>
<pre><code>class goblin(Enemy):
name = goblin;
current_health = 8
max_health = 8
attack = 3
defense = 2
armor = 0
def attack(){
//goblin-specific attack
}
</code></pre>
<p>But this method means that I would have to build a class for each individual <em>type</em> (which would be 80+ classes), or is there a better way to do it? This <em>enemy</em> is going to be randomized, so I was thinking the <em>types</em> could also be put into a <strong>dictionary</strong> which uses the names of the <em>types</em> as keywords. Although I'm not entirely sure how I could implement that.</p>
| 0 | 2016-08-09T23:49:14Z | 38,862,278 | <p>The goblin should probably be an instance of Enemy. However, in your example you added a method called <code>attack</code>. I would say the best way to do this is like this:</p>
<pre><code>class Enemy:
#Base Stats for all enemies
def __init__ (self, **kwargs):
self.name = "foo"
self.current_health = 4
self.max_health = 4
self.attack = 0
self.defense = 0
self.armor = 0
self.initiative = 0
self.initMod = 0
self.alive = True
# Use this to specify any other parameters you may need
for key in kwargs:
exec ("self.%s = %s" % (key, kwargs[key])
</code></pre>
<p>Now you can create an instance of <code>Enemy</code> called goblin. </p>
<p>To answer your initial question of when to use a subclass, I would say that it is great to use sub-classes but may over complicate things in your case. Since you only have one method in your subclass you can easily just make a module and then have an argument in the <code>__init__</code> that specifies the <code>attack</code> function. This will simplify your code more.</p>
<blockquote>
<p>Note: If you are going to use subclasses make sure that in the <code>__init__</code> of your subclass you call the <code>__init__</code> of your baseclass with <code>super()</code>.</p>
</blockquote>
| 0 | 2016-08-10T00:03:33Z | [
"python",
"dictionary",
"inheritance",
"pygame",
"python-object"
] |
Automatically download files using selenium and tor | 38,862,166 | <p>I am using Tor as my webdriver with selenium</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary('/Applications/TorBrowser.app/Contents/MacOS/firefox')
driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=profile)
</code></pre>
<p>It works exactly how its supposed to,but when I try to download a file I get standard pop up asking me where I want to save it and so on. I can't figure out how to deal with them. </p>
<p>I have read several threads on that topic and it seems like </p>
<pre><code>from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
profile = FirefoxProfile()
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'application/pdf')
binary = FirefoxBinary('/Applications/TorBrowser.app/Contents/MacOS/firefox')
driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=profile)
</code></pre>
<p>should work, but it doesn't.</p>
<p>Anyone knows how I can solve that issue</p>
| 0 | 2016-08-09T23:49:23Z | 38,882,609 | <pre><code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
profile = profile = FirefoxProfile('/Applications/TorBrowser.app/TorBrowser/Data/Browser/profile.default')
profile.set_preference("browser.download.manager.showWhenStarting",False)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'application/pdf')
binary = FirefoxBinary('/Applications/TorBrowser.app/Contents/MacOS/firefox')
driver = webdriver.Firefox(firefox_binary=binary,firefox_profile=profile)
</code></pre>
<p>That works</p>
| 0 | 2016-08-10T20:08:02Z | [
"python",
"selenium",
"tor"
] |
Find an item in a list using the known index | 38,862,203 | <p>I'm having trouble with Python here and need your help.</p>
<p>I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using <code>myList.index(item)</code>.</p>
<p>Snippet:</p>
<pre><code>new_lst = x
new_lst.sort()
leng = len(new_lst).....
elif leng > 1 and leng % 2 == 0:
a = (leng / 2) #or float 2.0
b = a - 1
c = new_lst.index(a) #The problem area
d = new_lst.index(b) #The problem area
med = (c + d) / 2.0
return med ......
</code></pre>
<p>The above will only return if <code>a</code> is in <code>new_lst</code>. Else it errors out. I want to get the middle two numbers (if list is even), add them together and then average them.</p>
<p>Example: <code>new_lst = [4,3,8,8]</code>. Get em, sort em, then should take the middle two numbers (<code>a</code> & <code>b</code> above, indices 1 & 2), add them and average: <code>(4 + 8) / 2</code> equaling 6. My code would assign 2 to <code>a</code>, look for it in the list and return an error: 2 not in <code>new_lst</code>. Not what I want.</p>
| -1 | 2016-08-09T23:53:20Z | 38,862,230 | <p>You reference an item in a list by using square brackets, like so</p>
<pre><code>c = new_lst[a]
d = new_lst[b]
</code></pre>
| 2 | 2016-08-09T23:57:09Z | [
"python",
"list",
"indexing"
] |
Find an item in a list using the known index | 38,862,203 | <p>I'm having trouble with Python here and need your help.</p>
<p>I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using <code>myList.index(item)</code>.</p>
<p>Snippet:</p>
<pre><code>new_lst = x
new_lst.sort()
leng = len(new_lst).....
elif leng > 1 and leng % 2 == 0:
a = (leng / 2) #or float 2.0
b = a - 1
c = new_lst.index(a) #The problem area
d = new_lst.index(b) #The problem area
med = (c + d) / 2.0
return med ......
</code></pre>
<p>The above will only return if <code>a</code> is in <code>new_lst</code>. Else it errors out. I want to get the middle two numbers (if list is even), add them together and then average them.</p>
<p>Example: <code>new_lst = [4,3,8,8]</code>. Get em, sort em, then should take the middle two numbers (<code>a</code> & <code>b</code> above, indices 1 & 2), add them and average: <code>(4 + 8) / 2</code> equaling 6. My code would assign 2 to <code>a</code>, look for it in the list and return an error: 2 not in <code>new_lst</code>. Not what I want.</p>
| -1 | 2016-08-09T23:53:20Z | 38,862,234 | <p>You don't want the <code>list.index</code> function - this is for finding the position of an item in a list. To find the item at a position, you should use slicing (which, in other languages, is sometimes called "indexing", which is probably what confused you). Slicing a single element out of an iterable looks like this: <code>lst[index]</code>.</p>
<pre><code>>>> new_lst = [4, 3, 8, 8]
>>> new_lst.sort()
>>> new_lst
[3, 4, 8, 8]
>>> if len(new_lst) % 2 == 0:
a = new_lst[len(new_lst)//2-1]
b = new_lst[len(new_lst)//2]
print((a+b)/2)
6.0
</code></pre>
| 0 | 2016-08-09T23:57:48Z | [
"python",
"list",
"indexing"
] |
Find an item in a list using the known index | 38,862,203 | <p>I'm having trouble with Python here and need your help.</p>
<p>I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using <code>myList.index(item)</code>.</p>
<p>Snippet:</p>
<pre><code>new_lst = x
new_lst.sort()
leng = len(new_lst).....
elif leng > 1 and leng % 2 == 0:
a = (leng / 2) #or float 2.0
b = a - 1
c = new_lst.index(a) #The problem area
d = new_lst.index(b) #The problem area
med = (c + d) / 2.0
return med ......
</code></pre>
<p>The above will only return if <code>a</code> is in <code>new_lst</code>. Else it errors out. I want to get the middle two numbers (if list is even), add them together and then average them.</p>
<p>Example: <code>new_lst = [4,3,8,8]</code>. Get em, sort em, then should take the middle two numbers (<code>a</code> & <code>b</code> above, indices 1 & 2), add them and average: <code>(4 + 8) / 2</code> equaling 6. My code would assign 2 to <code>a</code>, look for it in the list and return an error: 2 not in <code>new_lst</code>. Not what I want.</p>
| -1 | 2016-08-09T23:53:20Z | 38,862,239 | <blockquote>
<p>I want to return an item found at a particular index.</p>
</blockquote>
<p>Do you want to use the <code>[]</code> operator?</p>
<p><code>new_lst[a]</code> gets the item in <code>new_lst</code> at index <code>a</code>.</p>
<p>See <a href="https://docs.python.org/3.5/library/stdtypes.html#sequence-types-list-tuple-range" rel="nofollow">this documentation page</a> for more on the subject.</p>
| 0 | 2016-08-09T23:58:12Z | [
"python",
"list",
"indexing"
] |
Is there a python ReportLab equivalent of TCPDF's 'annotate' function? | 38,862,237 | <p>I'm trying to use the reportlab library to write an 'annotation' on a pdf. I've successfully written new data to a pdf using reportlab, but I can't find any information on how I would create an annotation.</p>
<p>When I say annotation I am referring to TCPDF's annotate function. This creates a clickable and movable text object in the pdf.<br><br>
<a href="https://tcpdf.org/examples/example_036/" rel="nofollow">https://tcpdf.org/examples/example_036/</a></p>
<p>There has to be a way to do this in python, but so far I haven't been able to find any information.</p>
<p>I've looked at this post and the related links posted in the accepted answer. <br><br>
<a href="http://stackoverflow.com/questions/6819336/add-text-to-existing-pdf-document-in-python">Add text to existing PDF document in Python</a>
<br><br>
I've seen this tool for using php in python, but I can't get it to work correctly and It doesn't seem to have any support. <br><br>
<a href="https://github.com/dnet/ppcg/blob/master/tcpdf_example.py" rel="nofollow">https://github.com/dnet/ppcg/blob/master/tcpdf_example.py</a>
<br><br>
When I run the example I get a unreadable pdf with the text shown below:</p>
<pre><code><?
include('tcpdf/config/lang/eng.php');
include('tcpdf/tcpdf.php');
$v0 = new TCPDF('PDF_PAGE_ORIENTATION', 'PDF_UNIT', 'PDF_PAGE_FORMAT', 'true', 'UTF-8', 'false');
$v0->setFontSubsetting(False);
$v0->setAuthor('VSzA');
$v0->setCreator('PPCG');
$v0->setTitle('TCPDF in Python!?');
$v0->setPrintHeader(False);
$v0->setMargins(10, 10);
$v0->AddPage();
$v0->SetFont('dejavusans', 'B', 12);
$v0->Cell(0, 0, 'Hello Python');
$v0->Ln();
$v2 = $v0->GetX();
$v1 = $v0->GetY();
$v0->setXY(30, 30);
$v0->Cell(0, 0, 'GOTOs are bad');
$v3 = $v1 + 2.5;
$v0->setXY($v2, $v3);
$v0->Cell(0, 0, 'I can has PHP variables');
$v0->Output();
?>
</code></pre>
<p>This looks like the correct php code to create a pdf using TCPDF, but the code is being saved to the pdf file instead of being ran. </p>
<p>The conclusion I've came to as of now is to just send all my data from a python script over to a http server using php and creating my pdf on the server using TCPDF, and then sending the new pdf back to my python script to serve it to the end user. This just sounds unefficient so I'd prefer not to do it this way.</p>
<p>Any help would be appreciated!
-Jake</p>
| 1 | 2016-08-09T23:58:03Z | 38,914,750 | <p>There is good news and bad news about annotation in <a href="/questions/tagged/reportlab" class="post-tag" title="show questions tagged 'reportlab'" rel="tag">reportlab</a>, the good news is it is possible to annotate in <a href="/questions/tagged/reportlab" class="post-tag" title="show questions tagged 'reportlab'" rel="tag">reportlab</a>. Bad news it is a pain in the ass as it isn't documented properly and it limits your options pretty hard.</p>
<p>The function you will need <code>canavas.textAnnotation</code> which is used in the following way:</p>
<pre><code>canvas.textAnnotation("Your content", Rect=[x_begin, y_begin, x_end, y_end], relative=1)
</code></pre>
<p>This will place the annotation at <code>(x_begin, y_begin)</code> relative to the current canvas, or if you turn off <code>relative</code> relative to the bottom left corner. </p>
<p>You might notice that the Reportlab annotations look different from those adobe generates, this has to do with the <code>SubType</code> of the annotation which in Reportlab is fixed to <code>Text</code> while Adobe uses something else (See 8.4.5 of the <a href="http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf" rel="nofollow">PDF reference</a>). </p>
<p>This can be changed by overloading the <a href="https://bitbucket.org/rptlab/reportlab/src/d3a68f4690c23e1726b997acd62011358ef1a636/src/reportlab/pdfgen/canvas.py?at=default&fileviewer=file-view-default#canvas.py-1110" rel="nofollow"><code>Canvas</code> object</a> and the <a href="https://bitbucket.org/rptlab/reportlab/src/d3a68f4690c23e1726b997acd62011358ef1a636/src/reportlab/pdfbase/pdfdoc.py?at=default&fileviewer=file-view-default#pdfdoc.py-1565" rel="nofollow"><code>Annotation</code> object</a> but doing so is a lot of work for just changing an icon. So I wouldn't recommend it.</p>
| 0 | 2016-08-12T09:39:13Z | [
"php",
"python",
"pdf",
"tcpdf",
"reportlab"
] |
How to Add Incremental Numbers to a New Column Using Pandas | 38,862,293 | <p>I have this simplified dataframe:</p>
<pre><code>ID Fruit
F1 Apple
F2 Orange
F3 Banana
</code></pre>
<p>I want to add in the begining of the dataframe a new column <code>df['New_ID']</code> which has the number <code>880</code> that increments by one in each row.</p>
<p>The output should be simply like:</p>
<pre><code>New_ID ID Fruit
880 F1 Apple
881 F2 Orange
882 F3 Banana
</code></pre>
<p>I tried the following:</p>
<pre><code>df['New_ID'] = ["880"] # but I want to do this without assigning it the list of numbers literally
</code></pre>
<p>Any idea how to solve this?</p>
<p>Thanks!</p>
| 2 | 2016-08-10T00:05:36Z | 38,862,360 | <p>Here:</p>
<pre><code>df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880
</code></pre>
| 1 | 2016-08-10T00:17:21Z | [
"python",
"pandas",
"dataframe"
] |
How to Add Incremental Numbers to a New Column Using Pandas | 38,862,293 | <p>I have this simplified dataframe:</p>
<pre><code>ID Fruit
F1 Apple
F2 Orange
F3 Banana
</code></pre>
<p>I want to add in the begining of the dataframe a new column <code>df['New_ID']</code> which has the number <code>880</code> that increments by one in each row.</p>
<p>The output should be simply like:</p>
<pre><code>New_ID ID Fruit
880 F1 Apple
881 F2 Orange
882 F3 Banana
</code></pre>
<p>I tried the following:</p>
<pre><code>df['New_ID'] = ["880"] # but I want to do this without assigning it the list of numbers literally
</code></pre>
<p>Any idea how to solve this?</p>
<p>Thanks!</p>
| 2 | 2016-08-10T00:05:36Z | 38,862,389 | <pre><code>df.insert(0, 'New_ID', range(880, 880 + len(df)))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/10mjk.png"><img src="http://i.stack.imgur.com/10mjk.png" alt="enter image description here"></a></p>
| 5 | 2016-08-10T00:21:28Z | [
"python",
"pandas",
"dataframe"
] |
How to Add Incremental Numbers to a New Column Using Pandas | 38,862,293 | <p>I have this simplified dataframe:</p>
<pre><code>ID Fruit
F1 Apple
F2 Orange
F3 Banana
</code></pre>
<p>I want to add in the begining of the dataframe a new column <code>df['New_ID']</code> which has the number <code>880</code> that increments by one in each row.</p>
<p>The output should be simply like:</p>
<pre><code>New_ID ID Fruit
880 F1 Apple
881 F2 Orange
882 F3 Banana
</code></pre>
<p>I tried the following:</p>
<pre><code>df['New_ID'] = ["880"] # but I want to do this without assigning it the list of numbers literally
</code></pre>
<p>Any idea how to solve this?</p>
<p>Thanks!</p>
| 2 | 2016-08-10T00:05:36Z | 38,862,663 | <pre><code>df = df.assign(New_ID=[880 + i for i in xrange(len(df))])
>>> df
ID Fruit New_ID
0 F1 Apple 880
1 F2 Orange 881
2 F3 Banana 882
</code></pre>
| 3 | 2016-08-10T00:59:49Z | [
"python",
"pandas",
"dataframe"
] |
trouble installing rPython | 38,862,299 | <p>I tried to install rPython package in Linux system but I got following errors. I tried to search online but couldn't find a solution. I appreciate any suggestions.</p>
<pre><code>> Sys.setenv(PATH = "/opt/anaconda/2.3.0/bin")
> system("python --version")
Python 2.7.10 :: Anaconda 2.3.0 (64-bit)
> install.packages('rPython')
Installing package into â/usr/local/lib/R/site-libraryâ
(as âlibâ is unspecified)
trying URL 'http://cran.fhcrc.org/src/contrib/rPython_0.0-6.tar.gz'
Content type 'application/x-gzip' length 37138 bytes (36 KB)
==================================================
downloaded 36 KB
/usr/lib/R/bin/R: line 8: uname: command not found
/usr/lib/R/bin/R: line 143: exec: sh: not found
The downloaded source packages are in
â/tmp/Rtmp8seq13/downloaded_packagesâ
Warning message:
In install.packages("rPython") :
installation of package ârPythonâ had non-zero exit status
</code></pre>
| 0 | 2016-08-10T00:06:34Z | 38,862,603 | <p>You're doing wrong with setting up env var <code>PATH</code>. It should be something equivalent with this shell command:</p>
<p><code>
$ export PATH=$PATH:/path/to/your/dir
</code></p>
| 0 | 2016-08-10T00:51:04Z | [
"python"
] |
get Json data from request with Django | 38,862,330 | <p>I'm trying to develop a very simple script in Django, I'd collect a Json data from the request and then store all data in the database.</p>
<p>I developed one python script that I'm using to send the Json data to the Django view, but I'm doing something wrong and I can't understand what, because every time that I run it,I've got "Malformed data!".</p>
<p>Can someone helps me? what am I doing wrong?</p>
<p>Sender.py</p>
<pre><code>import json
import urllib2
data = {
'ids': ["milan", "rome","florence"]
}
req = urllib2.Request('http://127.0.0.1:8000/value/')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
</code></pre>
<p>Django view.py</p>
<pre><code>from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import json
from models import *
from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def value(request):
try:
data = json.loads(request.body)
label = data['label']
url = data ['url']
print label, url
except:
return HttpResponse("Malformed data!")
return HttpResponse("Got json data")
</code></pre>
| 0 | 2016-08-10T00:11:07Z | 38,862,615 | <p>Your dictionary "data" in sender.py contains only one value with key "ids" but in view.py you are trying to access keys "label" and "url" in this parsed dictionary. </p>
| 0 | 2016-08-10T00:53:42Z | [
"python",
"json",
"django"
] |
string cleaning in python | 38,862,344 | <p>Input:</p>
<pre><code> " The Elephant's 4 cats. "
</code></pre>
<p>Expected Output:</p>
<pre><code> the elephants 4 cats
</code></pre>
<p>Code:</p>
<pre><code> import re
temp1 = re.sub('\W+',' ', str).strip()
output = temp2.lower()
</code></pre>
<p>My output:</p>
<pre><code> the elephant s 4 cats
</code></pre>
<p>I still have the extra space between elephant and 's'. One more problem is I am not able to remove '_' (underscore). Where am I going wrong, any suggestions would be helpful. </p>
| 0 | 2016-08-10T00:14:03Z | 38,862,377 | <p>try:</p>
<pre><code>temp1 = re.sub(r'[^\w\s_]+', '', str).strip()
</code></pre>
<p>Basically, your original \W+ means "non-word characters", which matches spaces, quotes, and periods. So it replaces them all with a "space"...which means the apostrophe gains a space.</p>
<p>By specifically matching non-word-non-space-non-underscore characters, you'll probably get a better replacement.</p>
| 3 | 2016-08-10T00:19:22Z | [
"python",
"pyspark"
] |
Regex: How to match words without consecutive vowels? | 38,862,349 | <p>I'm really new to regex and I've been able to find regex which can match this quite easily, but I am unsure how to only match words without it.</p>
<p>I have a .txt file with words like</p>
<pre><code>sheep
fleece
eggs
meat
potato
</code></pre>
<p>I want to make a regular expression that matches words in which vowels are not repeated consecutively, so it would return <code>eggs meat potato</code>.</p>
<p>I'm not very experienced with regex and I've been unable to find anything about how to do this online, so it'd be awesome if someone with more experience could help me out. Thanks!</p>
<p>I'm using python and have been testing my regex with <a href="http://regex101.com" rel="nofollow">https://regex101.com</a>.</p>
<p>Thanks!</p>
<p>EDIT: provided incorrect examples of results for the regular expression. Fixed.</p>
| 4 | 2016-08-10T00:15:54Z | 38,862,495 | <p>Note that, since the desired output includes <code>meat</code> but not <code>fleece</code>, desired words are allowed to have repeated vowels, just not the same vowel repeated.</p>
<p>To select lines with no repeated vowel:</p>
<pre><code>>>> [w for w in open('file.txt') if not re.search(r'([aeiou])\1', w)]
['eggs\n', 'meat\n', 'potato\n']
</code></pre>
<p>The regex <code>[aeiou]</code> matches any vowel (you can include <code>y</code> if you like). The regex <code>([aeiou])\1</code> matches any vowel followed by the same vowel. Thus, <code>not re.search(r'([aeiou])\1', w)</code> is true only for strings <code>w</code> that contain no repeated vowels.</p>
<h3>Addendum</h3>
<p>If we wanted to exclude <code>meat</code> because it has two vowels in a row, even though they are not the <em>same</em> vowel, then:</p>
<pre><code>>>> [w for w in open('file.txt') if not re.search(r'[aeiou]{2}', w)]
['eggs\n', 'potato\n']
</code></pre>
| 7 | 2016-08-10T00:35:16Z | [
"python",
"regex"
] |
Regex: How to match words without consecutive vowels? | 38,862,349 | <p>I'm really new to regex and I've been able to find regex which can match this quite easily, but I am unsure how to only match words without it.</p>
<p>I have a .txt file with words like</p>
<pre><code>sheep
fleece
eggs
meat
potato
</code></pre>
<p>I want to make a regular expression that matches words in which vowels are not repeated consecutively, so it would return <code>eggs meat potato</code>.</p>
<p>I'm not very experienced with regex and I've been unable to find anything about how to do this online, so it'd be awesome if someone with more experience could help me out. Thanks!</p>
<p>I'm using python and have been testing my regex with <a href="http://regex101.com" rel="nofollow">https://regex101.com</a>.</p>
<p>Thanks!</p>
<p>EDIT: provided incorrect examples of results for the regular expression. Fixed.</p>
| 4 | 2016-08-10T00:15:54Z | 38,862,546 | <p>@John1024 's answer should work
I also would try</p>
<blockquote>
<p>"\w*(a{2,}|e{2,}|i{2,}|o{2,}|u{2,})\w*"ig</p>
</blockquote>
| 1 | 2016-08-10T00:45:02Z | [
"python",
"regex"
] |
list not entering first input | 38,862,399 | <p>I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance
Here is my code:</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
num = int(user_input)
user_input_array.append(num)
count = count + 1
except:
print("Invalid input")
while user_input == quits:
#user_input_array.remove('done')
print ("done")
print ('Count: ', count)
print (user_input_array)
break
ask()
</code></pre>
| 1 | 2016-08-10T00:22:44Z | 38,862,417 | <p>That is because you never put it in there.</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = [user_input] # Create the list with the original input
...
</code></pre>
<p>With the above, the first thing entered by the user is placed in the list when the list is created. You might want to do your checks before this</p>
| 1 | 2016-08-10T00:25:22Z | [
"python",
"list",
"python-2.7",
"raw-input"
] |
list not entering first input | 38,862,399 | <p>I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance
Here is my code:</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
num = int(user_input)
user_input_array.append(num)
count = count + 1
except:
print("Invalid input")
while user_input == quits:
#user_input_array.remove('done')
print ("done")
print ('Count: ', count)
print (user_input_array)
break
ask()
</code></pre>
| 1 | 2016-08-10T00:22:44Z | 38,862,473 | <pre><code> def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
num = int(user_input)
user_input_array.append(num)
count = count + 1
except:
if user_input == quits:
#user_input_array.remove('done')
print ("done")
print ('Count: ', count)
print (user_input_array)
else:
print("Invalid input")
ask()
</code></pre>
| 0 | 2016-08-10T00:32:17Z | [
"python",
"list",
"python-2.7",
"raw-input"
] |
list not entering first input | 38,862,399 | <p>I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance
Here is my code:</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
num = int(user_input)
user_input_array.append(num)
count = count + 1
except:
print("Invalid input")
while user_input == quits:
#user_input_array.remove('done')
print ("done")
print ('Count: ', count)
print (user_input_array)
break
ask()
</code></pre>
| 1 | 2016-08-10T00:22:44Z | 38,862,487 | <p>You do not add your initial input to the array. Instead you enter the loop and ask for another input and check then add that to the array. You should ask for all inputs within the loop, as this means you only need one <code>raw_input</code> and one check for the done value. </p>
<p>A common way to do this is to go into an infinite loop and only exit when you read the value <code>done</code>. Like so</p>
<pre><code>def ask():
user_input_array = []
while True:
user_input = raw_input("Enter a number: ")
if user_input == 'done':
break
try:
user_input_array.append(int(user_input))
except ValueError:
print("Invalid input")
print ("done")
print ('Count: ', len(user_input_array))
print (user_input_array)
ask()
</code></pre>
<p>Note that this achieves the desired effect with no repetition. You also don't need to keep a count of how many elements you added, as the list has a <code>len</code> function which will tell you that.</p>
| 0 | 2016-08-10T00:34:19Z | [
"python",
"list",
"python-2.7",
"raw-input"
] |
How to plot an ROC curve for binary-valued scores using scikit-learn? | 38,862,419 | <p>I plotted an <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic" rel="nofollow">ROC curve</a> using the code shown below:</p>
<pre><code>fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
plt.plot(fpr["micro"], tpr["micro"],
label='ROC curve Fold1 (area = %0.2f)' % roc_auc1["micro"])
</code></pre>
<p>I want a plot that looks like a <em>curve</em>, but what I'm achieving now, as seen in the figure below, consists of two straight lines:</p>
<p><a href="http://i.stack.imgur.com/fFpLB.png" rel="nofollow"><img src="http://i.stack.imgur.com/fFpLB.png" alt="enter image description here"></a></p>
| 0 | 2016-08-10T00:25:59Z | 38,862,820 | <p>ROC curves are a way to compare a set of <em>continuous-valued</em> scores to a set of binary-valued labels by applying a varying discrimination threshold to the scores.</p>
<p>If your scores are already binary then there's no need to apply any threshold - just compute the true-positive rate and false-positive rate by directly comparing your scores to your labels, e.g.:</p>
<pre><code>tpr = np.mean((y_score == 1) & (y_label == 1))
fpr = np.mean((y_score == 1) & (y_label == 0))
</code></pre>
<p>If you try to plot the ROC curve for a set of binary scores, you end up with a line containing only three points because there are only three possible pairs of TPR/FPR values:</p>
<ul>
<li>If <code>threshold > 1</code> then you classify every sample as negative, and therefore both your FPR and TPR are both 0.</li>
<li>If <code>threshold <= 0</code> then you classify every sample as positive, and therefore your TPR is equal to the fraction of 1s in your set of labels, and your FPR is equal to the fraction of 0s in your labels.</li>
<li>If <code>0 < threshold <= 1</code> then your TPR and FPR values are equivalent to the standard TPR and FPR values calculated above.</li>
</ul>
<p>That's it.</p>
| 1 | 2016-08-10T01:21:27Z | [
"python",
"scikit-learn",
"roc"
] |
Find value greater than level - Python Pandas | 38,862,657 | <p>In a time series (ordered tuples), what's the most efficient way to find the first time a criterion is met? </p>
<p>In particular, what's the most efficient way to determine when a value goes over 100 for the value of a column in a pandas data frame?</p>
<p>I was hoping for a clever vectorized solution, and not having to use <code>df.iterrows()</code>.</p>
<p>For example, for price or count data, when a value exceeds 100. I.e. df['col'] > 100.</p>
<pre><code> price
date
2005-01-01 98
2005-01-02 99
2005-01-03 100
2005-01-04 99
2005-01-05 98
2005-01-06 100
2005-01-07 100
2005-01-08 98
</code></pre>
<p>but for potentially very large series. Is it better to iterate (slow) or is there a vectorized solution?</p>
<p>A <code>df.iterrows()</code> solution could be: </p>
<pre><code>for row, ind in df.iterrows():
if row['col'] > value_to_check:
breakpoint = row['value_to_record'].loc[ind]
return breakpoint
return None
</code></pre>
<p>But my question is more about efficiency (potentially, a vectorized solution that will scale well).</p>
| 1 | 2016-08-10T00:59:18Z | 38,863,264 | <p>Try this: "> 99" </p>
<pre><code>df[df['price'].gt(99)].index[0]
</code></pre>
<p>returns <code>"2"</code>, the second index row. </p>
<p>all row indexes greater than 99 </p>
<pre><code>df[df['price'].gt(99)].index
Int64Index([2, 5, 6], dtype='int64')
</code></pre>
| 2 | 2016-08-10T02:21:46Z | [
"python",
"pandas"
] |
Python - Looking for a solution to prevent duplicates in lists generated via text file | 38,862,685 | <p>As the title mentions, I'm looking for a way for my code to not only detect duplicates in a list, but to separate the items, moving them to other lists.</p>
<p>I am relatively new at programming, having just finished an introductory course to python at my local JC. During the course of the semester, I had an idea to create a program that would read lines in a .txt file, place them in a list, shuffle the list, and split the single list into two new lists before printing them. This would be used for quickly distributing uniquely named objects to two players in a game, for example. Here is what the code looks like so far:</p>
<p>Given that list.txt = apple, apple, banana, pear, orange, kiwi</p>
<pre><code>import random
#create list from text file
list = [line.strip() for line in open("list.txt", 'r')]
#Copy list to preserve the original
list2 = list[::]
random.shuffle(list2) #shuffle the order
#If # of items = odd, remove one
if len(list2) % 2 == 1:
del list2[-1]
#Divide items into two lists
A = list2[:len(list2)//2]
B = list2[len(list2)//2:]
print("The items in group A are: ", A)
print("The items in group B are: ", B)
</code></pre>
<p>I've gotten everything to work so far, but something I want to implement is having the program detect if, say, both "apple"'s are in list A and, if they are, move one to list B. I've come up with three solutions, but not one of them works. Solution 1 would be to take the two "apple"'s as they are and detect/sort from there. </p>
<pre><code>def moveDuplicates(in_list):
unique = set(in_list)
for each in unique:
count = in_list.count(each)
if count > 1:
return True
else:
return False
</code></pre>
<p>The problem is that I can detect duplicates just fine like this, but I don't know how to specify moving one of them since I won't know the position of either in the new lists, since it's shuffled every time. </p>
<p>Solution 2 is to rename the "apple"s to apple1 and apple2, or something similar. With this solution, I can choose to delete and append either item easily, but I don't know how to get the program to detect that two items with sequential numbers are in the same list.</p>
<p>Solution 3 is the worst one imo, since it involves writing conditions for every potential duplicate to make sure before the shuffle that one of each would be placed in each list, which violates DRY principles.</p>
<p>I feel that the most ideal solution would be to use solution 2 or 3 while somehow using something similar to how google uses asterisks in searches to denote that anything can be in place of the asterisk.</p>
| 0 | 2016-08-10T01:02:24Z | 38,862,893 | <p>How about just to use simple for-cycle? I will try to make it simple for you. If I understood your idea correctly then it can be implemented like this:</p>
<pre><code># Some input into this example
fruits = ["apple", "apple", "banana", "pear", "orange", "kiwi"]
# The code you're probably looking for
first_basket = []
second_basket = []
for fruit in fruits:
if fruit not in first_basket:
first_basket.append(fruit)
elif fruit not in second_basket:
second_basket.append(fruit)
print first_basket
print second_basket
</code></pre>
<p>So, if your first basket not contains fruit from fruits, it will be added to first_basket. Else if your second basket not contains fruit, it will be added to second_basket. So if both baskets already have fruit from your list it won't be added to any basket.</p>
<p>This example will print ["apple", "banana", "pear", "orange", "kiwi"] (this is your first_basket) and then ["apple"] (this is your second_basket).</p>
| 0 | 2016-08-10T01:31:04Z | [
"python",
"python-3.x"
] |
Python - Looking for a solution to prevent duplicates in lists generated via text file | 38,862,685 | <p>As the title mentions, I'm looking for a way for my code to not only detect duplicates in a list, but to separate the items, moving them to other lists.</p>
<p>I am relatively new at programming, having just finished an introductory course to python at my local JC. During the course of the semester, I had an idea to create a program that would read lines in a .txt file, place them in a list, shuffle the list, and split the single list into two new lists before printing them. This would be used for quickly distributing uniquely named objects to two players in a game, for example. Here is what the code looks like so far:</p>
<p>Given that list.txt = apple, apple, banana, pear, orange, kiwi</p>
<pre><code>import random
#create list from text file
list = [line.strip() for line in open("list.txt", 'r')]
#Copy list to preserve the original
list2 = list[::]
random.shuffle(list2) #shuffle the order
#If # of items = odd, remove one
if len(list2) % 2 == 1:
del list2[-1]
#Divide items into two lists
A = list2[:len(list2)//2]
B = list2[len(list2)//2:]
print("The items in group A are: ", A)
print("The items in group B are: ", B)
</code></pre>
<p>I've gotten everything to work so far, but something I want to implement is having the program detect if, say, both "apple"'s are in list A and, if they are, move one to list B. I've come up with three solutions, but not one of them works. Solution 1 would be to take the two "apple"'s as they are and detect/sort from there. </p>
<pre><code>def moveDuplicates(in_list):
unique = set(in_list)
for each in unique:
count = in_list.count(each)
if count > 1:
return True
else:
return False
</code></pre>
<p>The problem is that I can detect duplicates just fine like this, but I don't know how to specify moving one of them since I won't know the position of either in the new lists, since it's shuffled every time. </p>
<p>Solution 2 is to rename the "apple"s to apple1 and apple2, or something similar. With this solution, I can choose to delete and append either item easily, but I don't know how to get the program to detect that two items with sequential numbers are in the same list.</p>
<p>Solution 3 is the worst one imo, since it involves writing conditions for every potential duplicate to make sure before the shuffle that one of each would be placed in each list, which violates DRY principles.</p>
<p>I feel that the most ideal solution would be to use solution 2 or 3 while somehow using something similar to how google uses asterisks in searches to denote that anything can be in place of the asterisk.</p>
| 0 | 2016-08-10T01:02:24Z | 38,863,017 | <p>I'm assuming if you have more than 2 copies of any word, you can ignore everything after the first two. My suggested solution splits the list into repeated values, which will be shared by both groups and single values, which will be shuffled and split among the two groups.</p>
<pre><code>import collections
list = ['a', 'a', 'a', 'b', 'b', 'c', 'd']
# Split the list into words that occur once and ones that are repeats
single = []
repeats = []
for word, count in collections.Counter(list).items():
if count > 1:
repeats.append(word)
else:
single.append(word)
# Each group gets a copy of the repeats
group_a = repeats[:]
group_b = repeats[:]
# Now shuffle/divide the single values
random.shuffle(single)
half = len(single) // 2
group_a.extend(single[:half])
group_b.extend(single[half:2*half])
</code></pre>
<p>You could add additional shuffles for the individual groups, if you like.</p>
| 2 | 2016-08-10T01:49:22Z | [
"python",
"python-3.x"
] |
Range of logarithmic axis of scatter plot is not being set appropriately by matplotlib.pyplot | 38,862,697 | <p>I'm trying to plot 5 points (x, y) on a 2D scatter plot with a logarithmic y axis. The plot is produced but the range of the y-axis is not chosen well so only one point is displayed. The problem goes away when I remove the first point (0.38, 0.005).</p>
<p>Is this a bug in matplotlib?</p>
<p>Could someone try reproducing this?</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
emissions_abs_pts = np.array([
[0.38, 0.005], # without this point it scales appropriately
[0.42, 0.05],
[0.67, 0.5],
[0.96, 5.0],
[1.0, 50.0]
])
fig, ax = plt.subplots(1, 1)
ax.scatter(emissions_abs_pts[:,0], emissions_abs_pts[:,1])
ax.set_yscale('log')
</code></pre>
<p>Here is what the plot looks like with all five points included:
<a href="http://i.stack.imgur.com/cV2yG.png" rel="nofollow"><img src="http://i.stack.imgur.com/cV2yG.png" alt="enter image description here"></a></p>
<p>Note the y-axis range is <em>10^1</em> to <em>10^2</em></p>
<p>Here is the plot with the first point commented-out:
<a href="http://i.stack.imgur.com/LBkpk.png" rel="nofollow"><img src="http://i.stack.imgur.com/LBkpk.png" alt="enter image description here"></a></p>
<p>I'm using <code>%matplotlib inline</code> with a jupyter notebook running Python 2.7.</p>
| 1 | 2016-08-10T01:04:52Z | 38,864,897 | <p>edit: I got the same scaling error.</p>
<p>Add this to the end of your code</p>
<pre><code>ax.set_ylim([0.001, 100])
</code></pre>
<p>It will force the axis to behave. </p>
<p>It might be a jupyter thing?<br>
When I ran your code as a script from the command line (altering it not to be "inline"), the axes scaled correctly without the need to force them.</p>
| 1 | 2016-08-10T05:27:24Z | [
"python",
"matplotlib",
"logarithm"
] |
Trouble building PySide on Mac OS X (El Capitan) | 38,862,699 | <p>I am trying build PySide on a Mac running El Capitan (10.11.5).</p>
<p>This is the command I am using:</p>
<pre><code>python setup.py bdist_wheel --cmake=/Applications/CMake.app/Contents/bin/cmake
</code></pre>
<p>However, every time I run this, I get the following error messages:</p>
<pre><code>In file included from /Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:38:
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.h:56:76: error: virtual function
'metaObject' has a different return type ('Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType>') than the function it overrides (which has return type 'const QMetaObject *')
virtual Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType > metaObject() const;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
/usr/local/Trolltech/Qt-4.8.6/include/phonon/objectdescriptionmodel.h:202:68: note: overridden virtual function is here
PHONON_TEMPLATE_CLASS_MEMBER_EXPORT const QMetaObject *metaObject() const;
~~~~~~~~~~~~~^
/usr/local/Trolltech/Qt-4.8.6/include/phonon/objectdescriptionmodel.h:194:40: error: base class 'QAbstractListModel' has private copy constructor
class PHONON_TEMPLATE_CLASS_EXPORT ObjectDescriptionModel : public QAbstractListModel
^
/usr/local/Trolltech/Qt-4.8.6/lib/QtCore.framework/Headers/qabstractitemmodel.h:380:20: note: declared private here
Q_DISABLE_COPY(QAbstractListModel)
^
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:636:16: note: implicit copy
constructor for 'Phonon::ObjectDescriptionModel<Phonon::ObjectDescriptionType::AudioOutputDeviceType>' first required here
return ::Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType >(((::QObject*)0));
^
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:641:16: error: no viable
conversion from returned value of type 'const QMetaObject *' to function return type 'Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType>'
return this->::Phonon::AudioOutputDeviceModel::metaObject();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:651:16: error: no matching
constructor for initialization of 'Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType>'
return ::Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType >(((::QObject*)0));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:656:150: error: no matching
function for call to 'SbkType'
...2, "Invalid return value in function %s, expected %s, got %s.", "AudioOutputDeviceModel.metaObject", Shiboken::SbkType< Phonon::ObjectDescriptionModel >()->tp_name, pyResult->ob_type->tp_n...
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_install/py2.7-qt4.8.6-64bit-release/include/shiboken/conversions.h:52:15: note: candidate template ignored: invalid explicitly-specified
argument for template parameter 'T'
PyTypeObject* SbkType()
^
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:657:16: error: no matching
constructor for initialization of 'Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType>'
return ::Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType >(((::QObject*)0));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:662:12: error: no viable
conversion from returned value of type '::Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType> *' to function return type
'Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType>'
return cppResult;
^~~~~~~~~
/Users/spearsc/Documents/pyside_tmp/PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp:1460:157: error:
incompatible operand types ('Phonon::ObjectDescriptionModel<Phonon::AudioOutputDeviceType>' and 'const QMetaObject *')
...? reinterpret_cast<AudioOutputDeviceModelWrapper*>(cppSelf)->::AudioOutputDeviceModelWrapper::metaObject() : cppSelf->metaObject());
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
3 warnings and 8 errors generated.
make[2]: *** [PySide/phonon/CMakeFiles/phonon.dir/PySide/phonon/phonon_audiooutputdevicemodel_wrapper.cpp.o] Error 1
make[1]: *** [PySide/phonon/CMakeFiles/phonon.dir/all] Error 2
make: *** [all] Error 2
error: Error compiling pyside
</code></pre>
<p>What is especially maddening is that I have edited the phonon_audiooutputdevicemodelwrapper files, but the edits do not seem to stick. Running the setup.py script seems to undo my changes.</p>
<p>I do not need the Phonon module. However, I do not see a way to skip this module with the PySide build. I can skip this with Qt, but I would prefer to not have to rebuild that again.</p>
<h3>ADDITION 8/10/16</h3>
<p>Strange, I rebuilt Qt without Phonon:</p>
<pre><code>$ ./configure âno-phonon âno-phonon-backend
</code></pre>
<p>I still have that same issue.</p>
<p>Then I removed the phonon directory (PySide-1.2.4/pyside_build/py2.7-qt4.8.6-64bit-release/pyside/PySide/phonon) and got a different error message.</p>
| 0 | 2016-08-10T01:05:09Z | 38,984,653 | <p>Here is how I built PySide without Phonon:</p>
<p>Download the PySide source to a temp direct and uncompress the archive:</p>
<pre><code>$ pwd
/Users/spearsc/Documents/pyside_tmp
$ tar âxvzf dist\PySide-1.2.4.tar
</code></pre>
<p>Now you need to edit PySide-1.2.4/sources/pyside/CMakeLists.txt. Find this line (line 33 I believe):</p>
<pre><code>HAS_QT_MODULE(QT_PHONON_FOUND phonon)
</code></pre>
<p>Just comment out that line:</p>
<pre><code># HAS_QT_MODULE(QT_PHONON_FOUND phonon)
</code></pre>
<p>Then run the setup.py script:</p>
<pre><code>python setup.py bdist_wheel --cmake=/Applications/CMake.app/Contents/bin/cmake
</code></pre>
| 0 | 2016-08-16T21:18:57Z | [
"python",
"osx",
"qt",
"pyside"
] |
Check and extract composition args in sympy python | 38,862,764 | <p>i want to check if an expression is a composition of two functions and extract the args for example</p>
<pre><code>Log(x-1) :
</code></pre>
<p>i want get :</p>
<pre><code>[log(x),x-1]
</code></pre>
<p>and </p>
<pre><code>sin(x)/(1-sin(x))
</code></pre>
<p>i want get :</p>
<pre><code>[x/(1-x),sin(x)]
</code></pre>
<p>are there any sympy function or should i do it by myself</p>
| 3 | 2016-08-10T01:13:32Z | 38,880,365 | <p>There isn't a simple function that does it. You could use <code>cse</code> to pull out common subexpressions and <code>expr.args</code> to pull out non-common subexpressions from those. </p>
| 0 | 2016-08-10T17:53:14Z | [
"python",
"sympy"
] |
transaction based in django | 38,862,775 | <p>I would like to get some idea on how to improve (if any) my code in implementing transaction based query in Django.</p>
<p>This is how I understand the ATOMIC_REQUEST I read on django documentation. I have this function view:</p>
<pre><code>from django.db import transaction
import sys
@transaction.atomic
def save_progress(request):
try:
with atomic.transaction():
qs = AllProgressModel()
qs.name = 'level up'
qs.level = 25
qs.description = 'Increased 2 level'
qs.save()
except:
print(sys.exc_info())
</code></pre>
<p>-Am I doing it right? <br/>
-Is the progress will be saved or not if the connection lost occur during saving?<br/>
Thank you in advance!</p>
| 0 | 2016-08-10T01:15:38Z | 38,863,136 | <p>You don't need both decorator <code>@transaction.atomic</code> and <code>with atomic.transaction()</code>, just use one. Also while using <code>with atomic.transaction()</code>, catch database exceptions (<code>IntegrityError</code>) instead of broadly handling all exceptions at once. </p>
<pre><code>def save_progress(request):
try:
with atomic.transaction():
...
qs.name = 'level up'
qs.level = 25
qs.description = 'Increased 2 level'
qs.save()
except IntegrityError:
# You are here if something goes within the transaction, after rollback
# HANDLE excaption
</code></pre>
| 1 | 2016-08-10T02:07:08Z | [
"python",
"django"
] |
Why can't Django see my static files? | 38,862,786 | <p>I am trying to implement sass_processor in my django_cms site and am getting a weird error.</p>
<pre><code>Unable to locate file mysite/static/scss/main.scss while rendering tag 'sass_src' in template /Users/USER/Work/DIR/APP/SITE/mysite/templates/base.html
</code></pre>
<p>I have followed the latest Django CMS install instructions and have everything set up and working perfectly. I have tried importing static css files and it works fine.</p>
<p>for example in my base.html</p>
<pre><code><link href="{% static 'myapp/static/css/main.css' %}" rel="stylesheet" type="text/css" />
</code></pre>
<p>Imports perfectly</p>
<p>I have made sure to include sass_tags in my template</p>
<p>I have followed the instructions on the github page here:
<a href="https://github.com/jrief/django-sass-processor" rel="nofollow">https://github.com/jrief/django-sass-processor</a></p>
<p>My sass import is as follows:</p>
<pre><code><link href="{% sass_src 'myapp/static/scss/main.scss' %}" rel="stylesheet" type="text/x-scss" />
</code></pre>
<p>My static file structures are as follows:</p>
<pre><code>STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
STATIC_ROOT = os.path.join(DATA_DIR, 'static')
SASS_ROOT = os.path.join(BASE_DIR, 'mysite', 'static', 'scss')
SASS_PROCESSOR_ROOT = SASS_ROOT
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'mysite', 'static'),
)
SASS_PROCESSOR_INCLUDE_DIRS = (
os.path.join(BASE_DIR, 'mysite', 'static'),
SASS_ROOT
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'sass_processor.finders.CssFinder',
)
SASS_PROCESSOR_ENABLED = True
</code></pre>
<p>My file structure is as follows:</p>
<pre><code>|+env/
`~tate/
|+media/
|~mysite/
| |~static/
| | |+css/
| | `~scss/
| | `-main.scss
| |+templates/
| |-__init__.py
| |-__init__.pyc
| |-settings.py
| |-settings.pyc
| |-urls.py
| |-urls.pyc
| |-wsgi.py
| `-wsgi.pyc
|+static/
|-manage.py*
`-requirements.txt
</code></pre>
<p>I feel like I have missed some kind of path configuration but I'm not sure where it could be as I followed the Django CMS tutorial and the instructions outlined on the sass_processor page.</p>
<p>Any help is appreciated.</p>
| 0 | 2016-08-10T01:17:25Z | 39,052,121 | <p>You should change the type of your SASS import to "<em>text/css</em>". The "<em>text/x-scss</em>" type is used by <strong>django-compressor</strong>, but not by <strong>django-sass-processor</strong>.</p>
<p>Your new SASS import then becomes:</p>
<pre><code><link href="{% sass_src 'myapp/static/scss/main.scss' %}" rel="stylesheet" type="text/css" />
</code></pre>
| 0 | 2016-08-20T08:29:42Z | [
"python",
"django",
"sass",
"django-cms"
] |
Pandas Melt several groups of columns into multiple target columns by name | 38,862,832 | <p>I would like to melt several groups of columns of a dataframe into multiple target columns. Similar to questions <a href="http://stackoverflow.com/questions/35187963/python-pandas-melt-groups-of-initial-columns-into-multiple-target-columns">Python Pandas Melt Groups of Initial Columns Into Multiple Target Columns</a> and <a href="http://stackoverflow.com/questions/32105368/pandas-dataframe-reshaping-stacking-of-multiple-value-variables-into-seperate-co">pandas dataframe reshaping/stacking of multiple value variables into seperate columns</a>. However I need to do this explicitly by column name, rather than by index location.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([('a','b','c',1,2,3,'aa','bb','cc'), ('d', 'e', 'f', 4, 5, 6, 'dd', 'ee', 'ff')],
columns=['a_1', 'a_2', 'a_3','b_1', 'b_2', 'b_3','c_1', 'c_2', 'c_3'])
df
</code></pre>
<p>Original Dataframe:</p>
<pre><code> id a_1 a_2 a_3 b_1 b_2 b_3 c_1 c_2 c_3
0 101 a b c 1 2 3 aa bb cc
1 102 d e f 4 5 6 dd ee ff
</code></pre>
<p>Target Dataframe</p>
<pre><code> id a b c
0 101 a 1 aa
1 101 b 2 bb
2 101 c 3 cc
3 102 d 4 dd
4 102 e 5 ee
5 102 f 6 ff
</code></pre>
<p>Advice is much appreciated on an approach to this.</p>
| 4 | 2016-08-10T01:23:09Z | 38,863,051 | <p>You can convert the column names to multi index based on the columns pattern and then stack at a particular level depending on the result you need:</p>
<pre><code>import pandas as pd
df.set_index('id', inplace=True)
df.columns = pd.MultiIndex.from_tuples(tuple(df.columns.str.split("_")))
df.stack(level = 1).reset_index(level = 1, drop = True).reset_index()
# id a b c
#101 a 1 aa
#101 b 2 bb
#101 c 3 cc
#102 d 4 dd
#102 e 5 ee
#102 f 6 ff
</code></pre>
| 5 | 2016-08-10T01:54:48Z | [
"python",
"pandas",
"melt"
] |
Pandas Melt several groups of columns into multiple target columns by name | 38,862,832 | <p>I would like to melt several groups of columns of a dataframe into multiple target columns. Similar to questions <a href="http://stackoverflow.com/questions/35187963/python-pandas-melt-groups-of-initial-columns-into-multiple-target-columns">Python Pandas Melt Groups of Initial Columns Into Multiple Target Columns</a> and <a href="http://stackoverflow.com/questions/32105368/pandas-dataframe-reshaping-stacking-of-multiple-value-variables-into-seperate-co">pandas dataframe reshaping/stacking of multiple value variables into seperate columns</a>. However I need to do this explicitly by column name, rather than by index location.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([('a','b','c',1,2,3,'aa','bb','cc'), ('d', 'e', 'f', 4, 5, 6, 'dd', 'ee', 'ff')],
columns=['a_1', 'a_2', 'a_3','b_1', 'b_2', 'b_3','c_1', 'c_2', 'c_3'])
df
</code></pre>
<p>Original Dataframe:</p>
<pre><code> id a_1 a_2 a_3 b_1 b_2 b_3 c_1 c_2 c_3
0 101 a b c 1 2 3 aa bb cc
1 102 d e f 4 5 6 dd ee ff
</code></pre>
<p>Target Dataframe</p>
<pre><code> id a b c
0 101 a 1 aa
1 101 b 2 bb
2 101 c 3 cc
3 102 d 4 dd
4 102 e 5 ee
5 102 f 6 ff
</code></pre>
<p>Advice is much appreciated on an approach to this.</p>
| 4 | 2016-08-10T01:23:09Z | 38,865,238 | <pre><code>cols = df.columns.difference(['id'])
pd.lreshape(df, cols.groupby(cols.str.split('_').str[0])).sort_values('id')
Out:
id a c b
0 101 a aa 1
2 101 b bb 2
4 101 c cc 3
1 102 d dd 4
3 102 e ee 5
5 102 f ff 6
</code></pre>
| 3 | 2016-08-10T05:53:21Z | [
"python",
"pandas",
"melt"
] |
else statement not executing | 38,862,881 | <p>The part of my code where I ask the user if they want some cake has me confused.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or 'ya' or 'Ya':
print("Cool!")
else:
print('Aww..')
</code></pre>
<p>Sample Input:</p>
<pre class="lang-none prettyprint-override"><code>ya
yes
no
something other
</code></pre>
<p>Expected Output:</p>
<pre class="lang-none prettyprint-override"><code>Cool!
Cool!
Aww..
Aww..
</code></pre>
<p>Actual Output</p>
<pre class="lang-none prettyprint-override"><code>Cool!
Cool!
Cool!
Cool!
</code></pre>
<p>Why is the line <code>print('Aww..')</code> not executing?</p>
| 0 | 2016-08-10T01:29:25Z | 38,862,892 | <p>I haven't written a single line of python before, but my intuition says you need to replace</p>
<pre><code>if cake == 'yes' or 'ya' or 'Ya':
</code></pre>
<p>with</p>
<pre><code>if cake == 'yes' or cake == 'ya' or cake == 'Ya':
</code></pre>
<hr>
<p>You could try <a href="http://stackoverflow.com/questions/9659494/python-check-if-word-is-in-certain-elements-of-a-list">Word in array of words</a> (again, untested, just a guess)</p>
<pre><code>if cake in ['yes','ya','Ya']:
</code></pre>
| 1 | 2016-08-10T01:30:57Z | [
"python",
"if-statement",
"boolean-logic"
] |
else statement not executing | 38,862,881 | <p>The part of my code where I ask the user if they want some cake has me confused.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or 'ya' or 'Ya':
print("Cool!")
else:
print('Aww..')
</code></pre>
<p>Sample Input:</p>
<pre class="lang-none prettyprint-override"><code>ya
yes
no
something other
</code></pre>
<p>Expected Output:</p>
<pre class="lang-none prettyprint-override"><code>Cool!
Cool!
Aww..
Aww..
</code></pre>
<p>Actual Output</p>
<pre class="lang-none prettyprint-override"><code>Cool!
Cool!
Cool!
Cool!
</code></pre>
<p>Why is the line <code>print('Aww..')</code> not executing?</p>
| 0 | 2016-08-10T01:29:25Z | 38,862,921 | <p>Non-empty strings are always evaluated as <code>True</code> in Python. Your code </p>
<pre><code>if cake == 'yes' or 'ya' or 'Ya':
</code></pre>
<p>, using boolean logic, will always execute the tasks under it no matter you enter there. So it always prints "Cool!".</p>
<p>To prevent this from happening you should modify your conditional <code>if</code> statement in such a way that you will only catch the words <code>'yes'</code>, <code>'ya'</code> and <code>'Ya'</code>. Thus, <code>if cake == 'yes' or 'ya' or 'Ya':</code> should be replaced with</p>
<pre><code>if cake == 'yes' or cake == 'ya' or cake == 'Ya':
</code></pre>
<p>or if you are already familiar with Python lists </p>
<pre><code>if cake in ['yes', 'ya', 'Ya']: # Evaluates to True if cake is
# equivalent to one of the strings in the list
</code></pre>
<p>Read this <a href="http://stackoverflow.com/questions/18491777/python-truth-value-of-python-string"><strong>thread</strong></a> for more details on the truth value of a Python string.</p>
| 0 | 2016-08-10T01:35:36Z | [
"python",
"if-statement",
"boolean-logic"
] |
else statement not executing | 38,862,881 | <p>The part of my code where I ask the user if they want some cake has me confused.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or 'ya' or 'Ya':
print("Cool!")
else:
print('Aww..')
</code></pre>
<p>Sample Input:</p>
<pre class="lang-none prettyprint-override"><code>ya
yes
no
something other
</code></pre>
<p>Expected Output:</p>
<pre class="lang-none prettyprint-override"><code>Cool!
Cool!
Aww..
Aww..
</code></pre>
<p>Actual Output</p>
<pre class="lang-none prettyprint-override"><code>Cool!
Cool!
Cool!
Cool!
</code></pre>
<p>Why is the line <code>print('Aww..')</code> not executing?</p>
| 0 | 2016-08-10T01:29:25Z | 38,862,951 | <p>An if statement is built on conditions. If you plan to use a statement with multiple different 'triggers' you must state the new conditions for each. </p>
<p>As such, your statement requires <code>cake ==</code> for every potential true or false outcome.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or cake == 'ya' or cake == 'Ya':
print("Cool!")
else:
print('Aww..')
</code></pre>
<p>To help with your confusion, I believe the <code>or 'ya' or 'Ya'</code> resulted in true due to both the user input and 'ya'/'Ya' being of the string type.</p>
<p><em>Do not quote me on that last part. My assumption may be incorrect.</em></p>
<p>Edit: Your comment "<br>
Isaac It probably works but the or should hook them up. It was working earlier. It will work with one word but if not it will all ways say Cool!" suggests that my assumption regarding the type match resulting in true is in fact correct. That could be why earlier testing could have made the <code>or</code> seem like it was hooking the different possibilities.</p>
<p>The following code <code>if cake in ('yes', 'Ya','ya'):</code> would be the correct method of 'hooking' the different possibilities into a single condition.</p>
<p>Fixed Answer for OP:</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake in ('yes', 'Ya','ya', 'fine', 'sure'):
print("Cool!")
else:
print('Aww..')
</code></pre>
| 2 | 2016-08-10T01:40:01Z | [
"python",
"if-statement",
"boolean-logic"
] |
Python regular expression for matching '0' with no decimal point | 38,862,890 | <p>Consider the multiline string</p>
<pre><code>text = """SPLINE
8 # <------ everything from here
0
70
12
71
2
72
8
73
5
42
0.1000000000000000E-08
43
0.1000000000000000E+01
40
0.1000000000000000E+01
40
0.1157776718684309E+01
41
0.9237223003012139E+00
20
-0.3529600706727810E+02 # <--------- to here
0
LINE
8
0
10
0.1069999999749793E+02
20
-0.3165748401599828E+02
30
0.0000000000000000E+00
0
ARC"""
</code></pre>
<p>What regular expression can I use to obtain everything between <code>SPLINE</code> and the <code>0</code> just above <code>LINE</code>? </p>
<p>I've tried</p>
<pre><code>re.findall(r'SPLINE(.*?)\s\s[0]', text, re.DOTALL)
</code></pre>
<p>and many variations thereof which get me close, but are ultimately not what I need. The issue I suppose is just with the end part of the regex (the <code>\s\s[0]</code> part) given that <code>SPLINE</code> is matched no problem.</p>
<p>Another way of posing my question would be to ask what regex I could use to match two spaces followed by the integer 0 without a decimal point.</p>
| 0 | 2016-08-10T01:30:43Z | 38,863,547 | <p>Fairly trivial, just needed to add a newline character to skip over all the decimals. Successful regex was <code>SPLINE(.*?)\s\s0\n</code>, such that</p>
<pre><code>re.findall('SPLINE(.*?)\s\s0\n', text, re.DOTALL)
</code></pre>
<p>did the trick.</p>
| 0 | 2016-08-10T02:57:58Z | [
"python",
"regex"
] |
how to use flask driver in python splinter | 38,862,891 | <p>all my code is just:</p>
<pre><code>from splinter import Browser
from flask import Flask, request
from splinter.driver.flaskclient import FlaskClient
app = Flask(__name__)
browser = Browser('flask', app=app)
browser.visit('https://www.google.com')
print(browser.html)
</code></pre>
<p>which print the 404 html:
404 Not Found
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p></p>
<p>there is anything I should do?</p>
| 0 | 2016-08-10T01:30:43Z | 38,867,405 | <p>You are getting a 404 error because <strong>your Flask app has no routes</strong>.</p>
<p>I believe the purpose of the Splinter Flask client is to test your Flask app, not to test/request other domains. Visiting another domain with the Splinter Flask client will simply request the URL from your domain. You have not specified any routes for your Flask app, so Flask is responding with a 404 error.</p>
<p>Here's an example that shows how the Splinter Flask client is working:</p>
<pre><code># define simple flask app
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/<name>')
def hello_world(name):
return 'Hello, {name}!'.format(name=name)
# initiate splinter flask client
from splinter import Browser
browser = Browser('flask', app=app)
# simple flask app assertions
browser.visit('http://127.0.0.1:5000')
assert browser.html == 'Hello, World!'
browser.visit('http://127.0.0.1:5000/haofly')
assert browser.html == 'Hello, haofly!'
# Notice that requesting other domains act as if it's your domain
# Here it is requesting the previously defined flask routes
browser.visit('http://www.google.com')
assert browser.html == 'Hello, World!'
browser.visit('http://www.google.com/haofly')
assert browser.html == 'Hello, haofly!'
</code></pre>
<p>Here's another test that demonstrates what's really going on:</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(e):
return 'Flask 404 error!', 404
from splinter import Browser
browser = Browser('flask', app=app)
browser.visit('http://www.google.com/haofly')
assert browser.html == 'Flask 404 error!'
</code></pre>
| 1 | 2016-08-10T07:56:21Z | [
"python",
"python-3.x",
"splinter"
] |
Python selenium script to continue running if element is not found | 38,862,929 | <p>I am dealing with a pop up issue that seems to be random before I click on a button. I want to know if there is any way I can check if the element is displayed and click it, if it is not displayed, i want it to continue running the script. my current script keeps getting an error. when the pop up is displayed, my script runs PERFECT. my error takes place on my script at the </p>
<pre><code>onetouch = self.driver.find_element _by_xpath("").
</code></pre>
<p>Here is a picture of my error:</p>
<p><a href="http://i.stack.imgur.com/fMrtp.png" rel="nofollow"><img src="http://i.stack.imgur.com/fMrtp.png" alt="enter image description here"></a></p>
<pre><code> self.driver.get(redirecturl)
self.driver.implicitly_wait(180)
login_frame = self.driver.find_element_by_name('injectedUl')
# switch to frame to access inputs
self.driver.switch_to.frame(login_frame)
# we now have access to the inputs
email = self.driver.find_element_by_id('email')
password = self.driver.find_element_by_id('password')
button = self.driver.find_element_by_id('btnLogin')
# input your email and password below
email.send_keys('')
password.send_keys('')
button.click()
#############
onetouch = self.driver.find_element_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a")
if onetouch.is_displayed():
time.sleep(2)
onetouch.click()
else:
print "onetouch not present....continuing script"
button2 = self.driver.find_element_by_id('confirmButtonTop')
button2.click()
button3 = self.driver.find_element_by_name('dwfrm_payment_paypal')
# if you want to test the program without placing an order, delete the button3.click() below this.........
button3.click
</code></pre>
| -1 | 2016-08-10T01:36:35Z | 38,863,075 | <p>Actually <code>find_element_by_xpath</code> always returns either element or throws exception, So if there is no element by provided locator you can't execute <code>is_displayed()</code>. You should try using <code>find_elements_by_xpath</code> instead and check the length as below :-</p>
<pre><code>onetouch = self.driver.find_elements_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a")
if len(onetouch) > 0:
time.sleep(2)
onetouch[0].click()
else:
print "onetouch not present....continuing script"
-------
</code></pre>
| 0 | 2016-08-10T01:58:33Z | [
"python",
"selenium"
] |
Python selenium script to continue running if element is not found | 38,862,929 | <p>I am dealing with a pop up issue that seems to be random before I click on a button. I want to know if there is any way I can check if the element is displayed and click it, if it is not displayed, i want it to continue running the script. my current script keeps getting an error. when the pop up is displayed, my script runs PERFECT. my error takes place on my script at the </p>
<pre><code>onetouch = self.driver.find_element _by_xpath("").
</code></pre>
<p>Here is a picture of my error:</p>
<p><a href="http://i.stack.imgur.com/fMrtp.png" rel="nofollow"><img src="http://i.stack.imgur.com/fMrtp.png" alt="enter image description here"></a></p>
<pre><code> self.driver.get(redirecturl)
self.driver.implicitly_wait(180)
login_frame = self.driver.find_element_by_name('injectedUl')
# switch to frame to access inputs
self.driver.switch_to.frame(login_frame)
# we now have access to the inputs
email = self.driver.find_element_by_id('email')
password = self.driver.find_element_by_id('password')
button = self.driver.find_element_by_id('btnLogin')
# input your email and password below
email.send_keys('')
password.send_keys('')
button.click()
#############
onetouch = self.driver.find_element_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a")
if onetouch.is_displayed():
time.sleep(2)
onetouch.click()
else:
print "onetouch not present....continuing script"
button2 = self.driver.find_element_by_id('confirmButtonTop')
button2.click()
button3 = self.driver.find_element_by_name('dwfrm_payment_paypal')
# if you want to test the program without placing an order, delete the button3.click() below this.........
button3.click
</code></pre>
| -1 | 2016-08-10T01:36:35Z | 38,864,279 | <p>Try following:</p>
<pre><code>from selenium.common.exceptions import NoSuchElementException
try:
time.sleep(2)
self.driver.find_element_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a").click()
except NoSuchElementException:
print "onetouch not present....continuing script"
</code></pre>
| 0 | 2016-08-10T04:30:33Z | [
"python",
"selenium"
] |
Sum dictionary items based on rank | 38,862,949 | <p>I can sum items in a list of dicts per key like so:</p>
<pre><code>import functools
dict(
functools.reduce(
lambda x, y:x.update(y) or x,
dict1,
collections.Counter())
)
</code></pre>
<p>But given that</p>
<pre><code>dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
{'ledecky': 1, 'vollmer': 2, 'king': 3},
{'schmitt': 1, 'ledecky': 2, 'vollmer': 3}]
</code></pre>
<p>how could I sum their values according to medal value, given that:</p>
<pre><code>medal_value = {1: 10.0, 2: 5.0, 3: 3.0}
</code></pre>
<p>Such that the final dict would yield:</p>
<pre><code>{'ledecky': 25.0, 'king': 8.0, 'vollmer': 11.0, 'schmitt': 10.0}
</code></pre>
| 2 | 2016-08-10T01:39:52Z | 38,863,116 | <p>The <code>get()</code> dictionary function works really well in this example, we either give the newly created dictionary a default value of <code>0</code> or add it's current value with the weighted value using our <code>value</code> (<em>the value of</em> <code>dict1</code>) as the search key.</p>
<pre><code>def calculate_points(results, medal_value):
d = {}
for item in results:
for key, value in item.iteritems():
d[key] = d.get(key, 0) + medal_value[value]
return d
</code></pre>
<p><strong>Sample output:</strong></p>
<pre><code>dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
{'ledecky': 1, 'vollmer': 2, 'king': 3},
{'schmitt': 1, 'ledecky': 2, 'vollmer': 3}]
medal_value = {1 : 10.0, 2 : 5.0, 3 : 3.0}
print calculate_points(dict1, medal_value)
>>> {'ledecky': 25.0, 'king': 8.0, 'schmitt': 10.0, 'vollmer': 11.0}
</code></pre>
| 3 | 2016-08-10T02:03:59Z | [
"python",
"dictionary",
"collections",
"counter"
] |
Sum dictionary items based on rank | 38,862,949 | <p>I can sum items in a list of dicts per key like so:</p>
<pre><code>import functools
dict(
functools.reduce(
lambda x, y:x.update(y) or x,
dict1,
collections.Counter())
)
</code></pre>
<p>But given that</p>
<pre><code>dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
{'ledecky': 1, 'vollmer': 2, 'king': 3},
{'schmitt': 1, 'ledecky': 2, 'vollmer': 3}]
</code></pre>
<p>how could I sum their values according to medal value, given that:</p>
<pre><code>medal_value = {1: 10.0, 2: 5.0, 3: 3.0}
</code></pre>
<p>Such that the final dict would yield:</p>
<pre><code>{'ledecky': 25.0, 'king': 8.0, 'vollmer': 11.0, 'schmitt': 10.0}
</code></pre>
| 2 | 2016-08-10T01:39:52Z | 38,863,473 | <p>Just define a lookup function to transform the original dict to a medal values dict:</p>
<pre><code>def lookup(d):
return dict((k, medal_value[v]) for k, v in d.items())
</code></pre>
<p>And apply this function to your update part of the expression:</p>
<pre><code>dict(
functools.reduce(
lambda x, y: x.update(lookup(y)) or x,
dict1,
collections.Counter())
)
</code></pre>
| 1 | 2016-08-10T02:47:44Z | [
"python",
"dictionary",
"collections",
"counter"
] |
Class not creating new instances upon repeated calls | 38,863,073 | <p>May be I am missing something really basic here, but when I define a class in the following manner:</p>
<pre><code>class Arbitrary(object):
"""Arbitary class to test init"""
def __init__(self):
self.x = dict()
</code></pre>
<p>and repeatedly instantiate the class in the following way</p>
<pre><code>for i in range(5):
a = Arbitrary()
print '{} {} {} {}'.format(i, a, id(a), a.x)
</code></pre>
<p>I am not getting totally new instances of <code>Arbitrary()</code> class as I expect it to. In fact, I am getting repetition of two instances:</p>
<pre class="lang-none prettyprint-override"><code>0 <__main__.Arbitrary object at 0x1006cb110> 4302090512 {}
1 <__main__.Arbitrary object at 0x1006cb190> 4302090640 {}
2 <__main__.Arbitrary object at 0x1006cb110> 4302090512 {}
3 <__main__.Arbitrary object at 0x1006cb190> 4302090640 {}
4 <__main__.Arbitrary object at 0x1006cb110> 4302090512 {}
</code></pre>
<p>Why is that?</p>
<p>How can I define the <code>__init__</code> in my class such that every new call to <code>Arbitrary()</code> would return a totally new instance?</p>
| 0 | 2016-08-10T01:57:52Z | 38,863,204 | <p>I'm not a Python expert but I can see you are overwring your instances. I tried changing it to below and it runs ok :</p>
<pre><code>#!/bin/env python
class Arbitrary(object):
"""Arbitary class to test init"""
def __init__(self):
self.x = dict()
a = []
for i in range(5):
a.append(Arbitrary())
print '{} {} {} {}'.format(i, a[i], id(a[i]), a[i].x)
</code></pre>
<p>result :</p>
<pre class="lang-none prettyprint-override"><code>ckim@stph45:~/python/test2] test2.py
0 <__main__.Arbitrary object at 0x7fc6952b6090> 140490882900112 {}
1 <__main__.Arbitrary object at 0x7fc6952b6250> 140490882900560 {}
2 <__main__.Arbitrary object at 0x7fc6952b6290> 140490882900624 {}
3 <__main__.Arbitrary object at 0x7fc6952b62d0> 140490882900688 {}
4 <__main__.Arbitrary object at 0x7fc6952b6310> 140490882900752 {}
</code></pre>
| 4 | 2016-08-10T02:15:04Z | [
"python",
"class",
"oop",
"heap-memory"
] |
Python: Pandas Series - Difference between consecutive datetime rows in seconds | 38,863,137 | <p>I have a pandas Series called 'df' as follows</p>
<pre><code> value
date_time_index
2015-10-28 01:54:00 1.0
2015-10-28 01:55:00 1.0
2015-10-28 01:56:00 1.0
2015-10-28 01:57:00 1.0
2015-10-28 01:58:00 1.0
</code></pre>
<p>and I just want a new column with the difference <em>in seconds</em> between consecutive rows, how can I do this?</p>
<p>Note: The type is</p>
<pre><code> type(df.index[1])
</code></pre>
<p>given as</p>
<pre><code> pandas.tslib.Timestamp
</code></pre>
| 1 | 2016-08-10T02:07:12Z | 38,863,249 | <p>I think Ive worked it out using </p>
<pre><code>df['temp_index'] = df.index
df['Delta'] = df['temp_index'].diff().astype('timedelta64[m]')
</code></pre>
<p>in minutes rather than seconds (change m to s for seconds)</p>
| 1 | 2016-08-10T02:19:57Z | [
"python",
"datetime",
"pandas",
"difference",
"seconds"
] |
Python: Pandas Series - Difference between consecutive datetime rows in seconds | 38,863,137 | <p>I have a pandas Series called 'df' as follows</p>
<pre><code> value
date_time_index
2015-10-28 01:54:00 1.0
2015-10-28 01:55:00 1.0
2015-10-28 01:56:00 1.0
2015-10-28 01:57:00 1.0
2015-10-28 01:58:00 1.0
</code></pre>
<p>and I just want a new column with the difference <em>in seconds</em> between consecutive rows, how can I do this?</p>
<p>Note: The type is</p>
<pre><code> type(df.index[1])
</code></pre>
<p>given as</p>
<pre><code> pandas.tslib.Timestamp
</code></pre>
| 1 | 2016-08-10T02:07:12Z | 38,865,697 | <p>I'd do it like this:</p>
<pre><code>df.index.to_series().diff().dt.total_seconds().fillna(0)
date_time_index
2015-10-28 01:54:00 0.0
2015-10-28 01:55:00 60.0
2015-10-28 01:56:00 60.0
2015-10-28 01:57:00 60.0
2015-10-28 01:58:00 60.0
Name: date_time_index, dtype: float64
</code></pre>
| 2 | 2016-08-10T06:22:33Z | [
"python",
"datetime",
"pandas",
"difference",
"seconds"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pre>
<p>I'm not sure what <code>de_DE</code> is, but when I do <code>%p</code> using Django Rest Framework it shows AM and PM in capital letters. How do I change it so that am and pm are displayed in lowercase?</p>
<p>This is my DRF <code>settings.py</code> code where I edit the datetime format (might not be useful):</p>
<pre><code>#added REST_FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DATETIME_FORMAT': "%b %d at %I:%M %p"
}
</code></pre>
| 0 | 2016-08-10T02:15:25Z | 38,863,256 | <p>I'm pretty sure that you cannot. The <code>%p</code> format code is the locale-specific "national representation of either "ante meridiem" (a.m.) or "post meridiem" (p.m.) as appropriate". <code>de_DE</code> is the generic German locale which is what defines the national representation which happens to be lowercase. The <code>en_US</code> locale has it defined in uppercase. Part of using functions like <code>strftime</code> is that they take care of the localization details for you.</p>
<p>The documentation does explicitly mention that the exact values are entirely locale specific:</p>
<blockquote>
<p>Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, âmonth/day/yearâ versus âday/month/yearâ), and the output may contain Unicode characters encoded using the localeâs default encoding (for example, if the current locale is ja_JP, the default encoding could be any one of eucJP, SJIS, or utf-8; use locale.getlocale() to determine the current localeâs encoding).</p>
</blockquote>
| 2 | 2016-08-10T02:20:55Z | [
"python",
"datetime"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pre>
<p>I'm not sure what <code>de_DE</code> is, but when I do <code>%p</code> using Django Rest Framework it shows AM and PM in capital letters. How do I change it so that am and pm are displayed in lowercase?</p>
<p>This is my DRF <code>settings.py</code> code where I edit the datetime format (might not be useful):</p>
<pre><code>#added REST_FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DATETIME_FORMAT': "%b %d at %I:%M %p"
}
</code></pre>
| 0 | 2016-08-10T02:15:25Z | 38,863,271 | <p><code>en_US</code> and <code>de_DE</code> are <a href="https://docs.python.org/2/library/locale.html" rel="nofollow">locales</a>.</p>
<p><code>en_US</code> = English US<br>
<code>de_DE</code> = German Germany</p>
<p>In the <code>en_US</code> locale, AM/PM are uppercase whereas for the <code>de_DE</code> locale, it's shown in lower case.</p>
<p>You can use <code>locale.setlocale(locale.LC_ALL, 'de_DE')</code> to <a href="http://stackoverflow.com/a/956084/1431750">change your locale</a> when you use time formatting and then revert it back after.</p>
<p>And to avoid issues with other date fields showing in the wrong order, like 'day,month,year' instead of the US-preferred 'month,day,year', when you use the time formatting options, make sure you specify all the fields and not one of the standard short/long time formats, since those will always be as per the locale. Example, <code>%x</code>:</p>
<pre><code>%x Localeâs appropriate date representation. 08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
</code></pre>
<p>However, doing this is not a good idea, since the month (for example) will appear in that language's name. So 'May' will appear as 'Mei' (affects both long and short forms).</p>
<p>A <em><strong>dirty workaround</strong></em> is to do a search and replace after the generating the timestring:</p>
<pre><code>>>> datetime.strftime(datetime.today(), '%c %p').replace('AM', 'am').replace('PM', 'pm')
'08/10/16 10:37:49 am'
>>> datetime.strftime(datetime.today(), '%c %p').replace(' AM', ' am').replace(' PM', ' pm')
'08/10/16 10:39:19 am'
</code></pre>
<p>Again, not recommended since that will interfere with the timezone part where 'AM' and 'PM' occur - 'AMT', 'PMDT', 'GAMT'. If you're not displaying that or any other alphabets like for month, then it should be okay.</p>
| 1 | 2016-08-10T02:22:31Z | [
"python",
"datetime"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pre>
<p>I'm not sure what <code>de_DE</code> is, but when I do <code>%p</code> using Django Rest Framework it shows AM and PM in capital letters. How do I change it so that am and pm are displayed in lowercase?</p>
<p>This is my DRF <code>settings.py</code> code where I edit the datetime format (might not be useful):</p>
<pre><code>#added REST_FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DATETIME_FORMAT': "%b %d at %I:%M %p"
}
</code></pre>
| 0 | 2016-08-10T02:15:25Z | 38,863,349 | <p>From the documentation you've linked:</p>
<blockquote>
<p>Because the format depends on the current locale, care should be taken
when making assumptions about the output value. Field orderings will
vary (for example, âmonth/day/yearâ versus âday/month/yearâ), and the
output may contain Unicode characters encoded using the localeâs
default encoding (for example, if the current locale is js_JP, the
default encoding could be any one of eucJP, SJIS, or utf-8; use
locale.getlocale() to determine the current localeâs encoding).</p>
</blockquote>
<p>So, I don't think you can do it with a simple formatting option without overriding locale settings which may irritate users if you end up overwriting their locale settings.</p>
<p><strong>Two suggestions:</strong></p>
<ul>
<li>Use another formatting lib like <a href="https://github.com/django/django/blob/master/django/utils/dateformat.py" rel="nofollow">Django's DateFormat</a> ('a' will give you lowercase am/pm)</li>
<li>If you're using Linux that uses glibc then you can use "%P" as Python's strftime() is backended by C-lib's strftime()</li>
</ul>
| 1 | 2016-08-10T02:31:33Z | [
"python",
"datetime"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pre>
<p>I'm not sure what <code>de_DE</code> is, but when I do <code>%p</code> using Django Rest Framework it shows AM and PM in capital letters. How do I change it so that am and pm are displayed in lowercase?</p>
<p>This is my DRF <code>settings.py</code> code where I edit the datetime format (might not be useful):</p>
<pre><code>#added REST_FRAMEWORK
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DATETIME_FORMAT': "%b %d at %I:%M %p"
}
</code></pre>
| 0 | 2016-08-10T02:15:25Z | 38,863,352 | <p>Try changing '%p' to '%P'. Whether '%P' is supported depends on the 'strftime' function provided by the platform C library.</p>
| 2 | 2016-08-10T02:32:00Z | [
"python",
"datetime"
] |
How can I filter queries in view.py and render them into the template? | 38,863,224 | <p>I understand the querying from a basic perspective. That is if I write:</p>
<pre><code>{% for item in items %}
{{ item.jurisdiction}}
{% endfor %}
</code></pre>
<p>It will for every row item in my database table which has an entry in the "jurisdiction" column capture that row and return just the "jurisdiction".</p>
<p>What I really want to do is to return things filtered. From what I've heard the backend is where the querying/filtering should be done. To me, this means creating the query and filter in views.py</p>
<p>Now, what I really want to do is filter by multiple parameters. "Jurisdiction" + "Retention_Rule", for example.</p>
<p>I'm looking for an explanation of how to create a filtered query in views.py and then rendering it in the index.html (or other template). Also, want to know who to do multiple different kinds of queries that can be used in a template page.</p>
<p><strong>views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.template.response import TemplateResponse
from django.http import Http404
from inventory.models import Item
# Create your views here.
def index(request):
items = Item.objects.filter(jurisdiction="Germany")
return render(request, 'inventory/index.html', {
'items': items,
})
test = Item.objects.filter(jurisdiction="China").filter(record_type="Exit Interview")
return render(request, 'inventory/index.html', {
'test': test,
})
</code></pre>
<p>The "test" doesn't render and isn't called. However, I just put that there to help me think about how to create different kinds of filtered queries that can be accessed in the template.</p>
<p><strong>models.py</strong></p>
<pre><code>from django.db import models
class Item(models.Model):
id = models.AutoField(primary_key=True)
jurisdiction = models.CharField(max_length=200)
business_function = models.CharField(max_length=200)
record_category = models.CharField(max_length=200)
record_type = models.CharField(max_length=200)
retention_rule = models.DecimalField(decimal_places=1,max_digits=3)
retention_trigger = models.CharField(max_length=200)
personal_data = models.BooleanField(default=True)
privacy_driven = models.BooleanField(default=True)
</code></pre>
<p><strong>index.html</strong></p>
<pre><code>{% for item in items %}
<div class="row">
<div class="col-md-12">
<h1>{{ item.jurisdiction }}</h1>
<h1>{{ item.record_category }}</h1>
<h1>{{ item.record_type }}</h1>
<h1>{{ item.retention_rule }}</h1>
<h1>{{ item.retention_trigger }}</h1>
<h1>{{ item.personal_data }}</h1>
<h1>{{ item.privacy_driven }}</h1>
</div>
</div>
{% endfor %}
</code></pre>
<p>Any advice is appreciated.</p>
| 0 | 2016-08-10T02:16:41Z | 38,863,338 | <p>Think of view function is just another normal function. The test is not rendered because the function is already returned. Once the function returns anything no further lines would be executed.</p>
<p>You can pass multiple filtered queries to template by passing all the querysets in the context. </p>
<pre><code>return render(request, 'inventory/index.html', {'items': items, 'test': test})
</code></pre>
| 1 | 2016-08-10T02:29:54Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Change subplot size in python matplotlib | 38,863,262 | <p>I would like to change the size of the <em>subplot</em> when I use Python's matplotlib. I already know how to change the size of the <em>figure</em>, however, how does one go about changing the size of the corresponding subplots themselves? This has remained somewhat elusive in my googling. Thanks. </p>
<p>(For example, given a figure where we have 2x4 subplots. I want to make the subplots within the figure occupy more area). </p>
| 0 | 2016-08-10T02:21:43Z | 38,863,444 | <p>You can use <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.subplots_adjust" rel="nofollow"><code>.subplots_adjust()</code></a>, e.g.</p>
<pre><code>import seaborn as sns, matplotlib.pyplot as plt
titanic = sns.load_dataset('titanic')
g = sns.factorplot(x='sex',y='age',hue='class',data=titanic,
kind='bar',ci=None,legend=False)
g.fig.suptitle('Oversized Plot',size=16)
plt.legend(loc='best')
g.fig.subplots_adjust(top=1.05,bottom=-0.05,left=-0.05,right=1.05)
</code></pre>
<p>Results in this monstrosity:</p>
<p><a href="http://i.stack.imgur.com/cssEQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/cssEQ.png" alt="enter image description here"></a></p>
| 0 | 2016-08-10T02:43:38Z | [
"python",
"numpy",
"matplotlib",
"plot",
"figure"
] |
Change subplot size in python matplotlib | 38,863,262 | <p>I would like to change the size of the <em>subplot</em> when I use Python's matplotlib. I already know how to change the size of the <em>figure</em>, however, how does one go about changing the size of the corresponding subplots themselves? This has remained somewhat elusive in my googling. Thanks. </p>
<p>(For example, given a figure where we have 2x4 subplots. I want to make the subplots within the figure occupy more area). </p>
| 0 | 2016-08-10T02:21:43Z | 38,863,470 | <p>You can also play with the axis size.
<a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">http://matplotlib.org/api/axes_api.html</a></p>
<p>set_position() can be used to change width and height of your axis.</p>
<pre><code>import matplotlib.pyplot as plt
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 1.1 , box.height * 1.1])
</code></pre>
| 1 | 2016-08-10T02:47:30Z | [
"python",
"numpy",
"matplotlib",
"plot",
"figure"
] |
Given a set of bounding boxes in an 2D space, group them into rows | 38,863,534 | <p>Given a set of <strong>N</strong> bounding boxes with vertex coordinates:</p>
<pre><code>"vertices": [
{
"y": 486,
"x": 336
},
{
"y": 486,
"x": 2235
},
{
"y": 3393,
"x": 2235
},
{
"y": 3393,
"x": 336
}
]
</code></pre>
<p>I would like to group the bounding boxes into rows. In other words, given the pictorial representation of bounding boxes in this image:</p>
<p><a href="http://i.stack.imgur.com/r3B67.png" rel="nofollow"><img src="http://i.stack.imgur.com/r3B67.png" alt="Bounding Boxes"></a></p>
<p>I would like an algorithm that returns:</p>
<pre><code>[1,2,3]
[4,5,6]
[7,8]
</code></pre>
<p>[Edit: Clarification] The grouping decisions (e.g. [4,5,6] and [7,8]) should be based on some kind of error minimisation such as least squares. </p>
<p>Is there an algorithm or library (preferably in python) that does this?</p>
| 0 | 2016-08-10T02:55:39Z | 38,864,257 | <p>I think this is a clustering problem. In fact, because you can ignore the x co-ordinates, I think this is a 1-dimensional clustering problem. Some standard clustering algorithms such as k-means are good for minimising sums of squares from cluster centres, which amounts to what you are looking for. Unfortunately, they don't guarantee to find the globally best solution. One-dimensional clustering is a special case for which there are exact algorithms - see <a href="http://stackoverflow.com/questions/7869609/cluster-one-dimensional-data-optimally">Cluster one-dimensional data optimally?</a>.</p>
| 0 | 2016-08-10T04:28:34Z | [
"python",
"algorithm",
"geometry",
"computational-geometry"
] |
Search nested dicts for key trees | 38,863,540 | <p>I would like to check if a tuple of keys exists in a nested dictionary, similarly to <code>dict.get</code>. The functionality can be achieved as follows.</p>
<pre><code>nested_dict = {
'x': 1,
'a': {
'b': {
'c': 2,
'y': 3
},
'z': 4
}
}
def check(nested, *path):
for key in path:
if isinstance(nested, dict) and key in nested:
nested = nested[key]
else:
return False
return True
check(nested_dict, 'a', 'b', 'c') # True
check(nested_dict, 'x') # True
check(nested_dict, 'a', 'b', 'y') # True
check(nested_dict, 'a', 'z') # True
check(nested_dict, 'y') # False
check(nested_dict, 'a', 'y') # False
check(nested_dict, 'a', 'b', 'c', 'y') # False
</code></pre>
<p>Is there a cleaner (or better yet, built-in) method of doing this?</p>
| 1 | 2016-08-10T02:56:59Z | 38,863,581 | <p>For python 3.x do <code>from functools import reduce</code>.</p>
<p>You can wrap a <code>try .. except KeyError</code> (and <code>TypeError</code>) and return the appropriate boolean value:</p>
<pre><code>>>> reduce(lambda x,y: x[y], ["a", "b", "c"], nested_dict)
2
>>> reduce(lambda x,y: x[y], ["a", "b", "d"], nested_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
KeyError: 'd'
</code></pre>
<hr>
<p>PS: These one lines are sometimes fun to write. But I'd honestly use your version for any production code.</p>
| 1 | 2016-08-10T03:04:29Z | [
"python",
"python-3.x",
"dictionary",
"nested",
"python-3.5"
] |
Python: best practice for a dynamic Facebook picture url with access token | 38,863,706 | <p>I've got a Django app where users can sign up with facebook. I'm using <a href="https://pypi.python.org/pypi/facebook-sdk" rel="nofollow">facebook-sdk</a> to query the Facebook Graph API. I'm running into a problem when constructing a profile picture url for a given user.</p>
<p>According to various sources, I can render the user's picture at various widths using the following:</p>
<pre><code><img src="https://graph.facebook.com/{{facebookUserId}}/picture?type=square&width=500">
</code></pre>
<p>That way, I don't have to store the user's picture when they sign up. However, if the user's picture is private, I need to append an access token like so:</p>
<pre><code><img src="https://graph.facebook.com/{{facebookUserId}}/picture?type=square&width=500&access_token={{accessToken}}">
</code></pre>
<p>The problem is that the access token will eventually expire. I can convert a short access token (from the facebook javascript SDK) to a long-lived access token via the Graph API, but eventually even that token will expire, and at that point I won't be able to render the image anymore.</p>
<p>I can store the expiry date of the token on the user model to check when it's expired:</p>
<pre><code>class User(models.Model):
accessToken = models.CharField(...)
accessTokenExpires = models.DateTimeField(...)
</code></pre>
<p>But then I have to check whether the access token is expired every time I need to render the picture, which probably means I should use a URL from my own backend, like <code>/picture/<userId>?size=500</code> which would redirect to <code>graph.facebook.com/<userIdGoesHere>/picture?type=square&width=500&access_token=<accessTokenGoesHere></code> with the stored accessToken, but at that point I lose the speed of using Facebook's CDN to render the image.</p>
<p>I suppose I could try to update the tokens of all my users with a cron'd worker task, but that doesn't seem ideal as the number of users grows and I'm wondering if there's a better way.</p>
<p>What's the best practice for keeping these tokens up to date while still dynamically rendering an image URL?</p>
| 0 | 2016-08-10T03:23:19Z | 38,864,823 | <ul>
<li>if an access token is rejected do regenerate it . An access token might be revoked when user changes his password</li>
<li>Request your long lived token and store it with metadata when to refresh it : <a href="https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension" rel="nofollow">https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension</a></li>
<li>you might consider to cache things like profile photos</li>
</ul>
| 0 | 2016-08-10T05:20:44Z | [
"python",
"django",
"facebook",
"facebook-graph-api"
] |
scikit learn py-earth method parameter 'check_every' and 'min_search_point' doesn't work | 38,863,733 | <p>I am using the method named py-earth from <a href="https://github.com/scikit-learn-contrib/py-earth" rel="nofollow">https://github.com/scikit-learn-contrib/py-earth</a>.</p>
<p>I am trying to use the parameter <code>check_every</code> to control my fitting time, but I found it didn't make any differences when I change the init parameter <code>check_every</code>.</p>
<p>So I wonder whether the parameter <code>check_every</code> is useful now?</p>
| 0 | 2016-08-10T03:27:31Z | 38,987,813 | <p>Quoted from <a href="https://github.com/scikit-learn-contrib/py-earth/issues/130#issuecomment-239050763" rel="nofollow">github</a>:</p>
<blockquote>
<p>I think if you set check_every sufficiently high, you should eventually see a worse fit (and maybe a very slight speed up). I think it speaks to the usefulness of check_every that I actually had to look in the code to make sure it's even still implemented. All it does is reduce the number of candidate knot locations during knot search. One reason to do this would be to make sure you don't end up with knots too close together. However, the minspan argument takes care of that in a much nicer way. </p>
</blockquote>
| 0 | 2016-08-17T03:48:45Z | [
"python",
"scikit-learn"
] |
How to get count of all element in numpy? | 38,863,775 | <p>suppose I have an array in numpy</p>
<pre><code>array([1,1,2,3,4,5,5,5,6,7,7,7,7])
</code></pre>
<p>What I want is to get two arrays to give count of each element:</p>
<pre><code>array([1,2,3,4,5,6,7])
array([1,1,1,1,3,1,4])
</code></pre>
<p>How can I do this without any for loops?</p>
| 0 | 2016-08-10T03:32:26Z | 38,863,921 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> :</p>
<pre><code>>>> import numpy as np
>>> a = np.array([1,1,2,3,4,5,5,5,6,7,7,7,7])
>>> b = np.bincount(a)
>>> b[np.unique(a)]
array([2, 1, 1, 1, 3, 1, 4])
</code></pre>
<p>And to get the other array :</p>
<pre><code>>>> np.unique(a)
array([1, 2, 3, 4, 5, 6, 7])
</code></pre>
| 0 | 2016-08-10T03:52:18Z | [
"python",
"numpy",
"vectorization"
] |
How to get count of all element in numpy? | 38,863,775 | <p>suppose I have an array in numpy</p>
<pre><code>array([1,1,2,3,4,5,5,5,6,7,7,7,7])
</code></pre>
<p>What I want is to get two arrays to give count of each element:</p>
<pre><code>array([1,2,3,4,5,6,7])
array([1,1,1,1,3,1,4])
</code></pre>
<p>How can I do this without any for loops?</p>
| 0 | 2016-08-10T03:32:26Z | 38,863,932 | <pre><code>In [1043]: np.unique(np.array([1,1,2,3,4,5,5,5,6,7,7,7,7]),return_counts=True)
Out[1043]: (array([1, 2, 3, 4, 5, 6, 7]), array([2, 1, 1, 1, 3, 1, 4]))
</code></pre>
| 6 | 2016-08-10T03:53:11Z | [
"python",
"numpy",
"vectorization"
] |
quick sort recursion error | 38,863,810 | <p>My thoughts:
i'm trying to implement quick sort with python.
i set the first element as pivot.
if the element of left mark is larger than pivot then i start moving the right mark to find an element smaller than pivot and then swap.
if right mark is smaller than left mark, swap pivot with the element of right mark.
then separate the list with pivot. and repeat the step</p>
<p>Question:
my code can separate the list into two lists as i imagined. but when it returns it somehow copy the elements several times and made it wrong. i'm not familiar with recursion and can't find the problem.</p>
<pre><code>def quick_sort(lst):
front = []
rear = []
temp = 0
pivot = lst[0]
i = 1 #leftmark
j = len(lst)-1 #rightmark
if len(lst) == 1:
return lst
while i<=j:
if lst[i]<pivot:
i+=1
else:
if lst[j]>pivot:
j-=1
elif lst[j] == pivot:
break
else:
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
'''if j<i (rightmark < leftmark) swap pivot with position j'''
temp = pivot
pivot = lst[j]
lst[j] = temp
lst[0] = pivot
front = lst[0:j+1]
rear = lst[i:len(lst)+1]
return quick_sort(front) + [pivot] + quick_sort(rear)
</code></pre>
| 1 | 2016-08-10T03:37:08Z | 38,863,954 | <p>You are slicing the list wrong. You should replace <code>lst[0:j+1]</code> to <code>lst[ : j ]</code> and <code>lst[i:len(lst)+1]</code> to <code>lst[ j + 1 : ]</code>, since the pivot is at position <code>j</code>and you should ignore it (here, the emptiness before <code>:</code> represent <code>from the start</code> and after <code>:</code> represent <code>till the end</code>).
Last but not least, consider using tuples to swap instead of <code>temp</code> var, example:</p>
<pre class="lang-py prettyprint-override"><code>temp = a
a = b
b = temp
</code></pre>
<p>can be replaced by the one liner</p>
<pre class="lang-py prettyprint-override"><code>a, b = b, a
</code></pre>
<p>here is my final working code:</p>
<pre class="lang-py prettyprint-override"><code>def quick_sort(lst):
if lst:
pivot = lst[0]
i = 1 #leftmark
j = len(lst)-1 #rightmark
if len(lst) == 1:
return lst
while i <= j:
if lst[i] < pivot:
i += 1
elif lst[j]>pivot:
j-=1
elif lst[j] == pivot:
break
else:
lst[i], lst[j] = lst[j], lst[i]
'''if j<i (rightmark < leftmark) swap pivot with position j'''
lst[0], lst[j] = lst[j], lst[0]
front = lst[ : j ]
rear = lst[ j+1 : ]
return quick_sort(front) + [ pivot ] + quick_sort(rear)
return []
</code></pre>
<pre class="lang-py prettyprint-override"><code>>>> quick_sort([1,3,4,2,6,9,0])
[0, 1, 2, 3, 4, 6, 9]
</code></pre>
| 0 | 2016-08-10T03:55:41Z | [
"python",
"recursion"
] |
quick sort recursion error | 38,863,810 | <p>My thoughts:
i'm trying to implement quick sort with python.
i set the first element as pivot.
if the element of left mark is larger than pivot then i start moving the right mark to find an element smaller than pivot and then swap.
if right mark is smaller than left mark, swap pivot with the element of right mark.
then separate the list with pivot. and repeat the step</p>
<p>Question:
my code can separate the list into two lists as i imagined. but when it returns it somehow copy the elements several times and made it wrong. i'm not familiar with recursion and can't find the problem.</p>
<pre><code>def quick_sort(lst):
front = []
rear = []
temp = 0
pivot = lst[0]
i = 1 #leftmark
j = len(lst)-1 #rightmark
if len(lst) == 1:
return lst
while i<=j:
if lst[i]<pivot:
i+=1
else:
if lst[j]>pivot:
j-=1
elif lst[j] == pivot:
break
else:
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
'''if j<i (rightmark < leftmark) swap pivot with position j'''
temp = pivot
pivot = lst[j]
lst[j] = temp
lst[0] = pivot
front = lst[0:j+1]
rear = lst[i:len(lst)+1]
return quick_sort(front) + [pivot] + quick_sort(rear)
</code></pre>
| 1 | 2016-08-10T03:37:08Z | 38,863,974 | <p>You may also use this for quick sort.</p>
<pre><code>import random
def qsort(a,start,end):
if(start >= end):
return a
pivot = a[random.randint(start,end)]
i,j = start,end
while(i <= j):
while(a[i] < pivot):
i+=1
while(a[j] > pivot):
j-=1
if(i <= j):
a[i],a[j] = a[j],a[i]
i+=1
j-=1
qsort(a,start,j)
qsort(a,i,end)
print a
a = [27,43,24,33,60,12]
qsort(a,0,len(a)-1)
</code></pre>
<p>Also there are different ways provided in the below link.</p>
<p><a href="http://stackoverflow.com/questions/18262306/quick-sort-with-python">Quick sort with Python</a></p>
| -2 | 2016-08-10T03:58:50Z | [
"python",
"recursion"
] |
Changing value in pandas dataframe is same row is present in another dataframe | 38,863,830 | <p>I have the foll. 2 pandas dataframes:</p>
<pre><code>df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14], 'col3' : [0,2,0,-1,0]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12], 'col6' : [20, 31, 12]})
</code></pre>
<p>How do I change the value in <code>col3</code> in df1 to 0 if both <code>col1</code> and <code>col2</code> have same value in df1 and df2. The result for df1 should look like this:</p>
<pre><code> col1 col2 col3
0 1 10 0
1 2 11 0
2 3 12 0
3 4 13 -1
4 5 14 0
</code></pre>
| 2 | 2016-08-10T03:40:23Z | 38,864,490 | <p>If you merge two DataFrames on <code>col1</code> and <code>col2</code>, the resulting DataFrame will have rows where both DataFrames have the same value in those columns. However, pandas <a href="http://stackoverflow.com/questions/11976503/how-to-keep-index-when-using-pandas-merge">loses the index</a> when merging. You can use <code>reset_index</code> prior to merging to keep the index and use that index in <code>.loc</code>:</p>
<pre><code>df1.loc[df1.reset_index().merge(df2, on=['col1', 'col2'])['index'], 'col3'] = 0
df1
Out:
col1 col2 col3
0 1 10 0
1 2 11 0
2 3 12 0
3 4 13 -1
4 5 14 0
</code></pre>
| 2 | 2016-08-10T04:50:26Z | [
"python",
"pandas"
] |
Changing value in pandas dataframe is same row is present in another dataframe | 38,863,830 | <p>I have the foll. 2 pandas dataframes:</p>
<pre><code>df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14], 'col3' : [0,2,0,-1,0]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12], 'col6' : [20, 31, 12]})
</code></pre>
<p>How do I change the value in <code>col3</code> in df1 to 0 if both <code>col1</code> and <code>col2</code> have same value in df1 and df2. The result for df1 should look like this:</p>
<pre><code> col1 col2 col3
0 1 10 0
1 2 11 0
2 3 12 0
3 4 13 -1
4 5 14 0
</code></pre>
| 2 | 2016-08-10T03:40:23Z | 38,866,884 | <p>A quick numpy solution. <code>i</code> gets indices for every combination of one row from <code>df1</code> and another row from <code>df2</code>. I use the <code>==</code> to determine which cells are equal. <code>all(2)</code> determines if all cells from one row equal all cells from the other row. If true, then the corresponding set of indices represent a match. So, <code>i[0][matches]</code> tells me all the rows from <code>df1</code> that match the rows in <code>df2</code> represented by <code>i[1][matches]</code>. But I only need to change values in <code>df1</code> so I only use <code>i[0][matches]</code> to slice <code>df1</code> on the 3rd column then assign <code>0</code>.</p>
<pre><code>def pir(df1, df2):
i = np.indices((len(df1), len(df2)))
matches = (df2.values[i[1], :2] == df1.values[i[0], :2]).all(2)
df = df1.copy()
df.iloc[i[0][matches], 2] = 0
return df
pir(df1, df2)
</code></pre>
<p><a href="http://i.stack.imgur.com/Y3PQA.png" rel="nofollow"><img src="http://i.stack.imgur.com/Y3PQA.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<pre><code>def ayhan(df1, df2):
df1 = df1.copy()
df1.loc[df1.reset_index().merge(df2, on=['col1', 'col2'])['index'], 'col3'] = 0
return df1
</code></pre>
<p><a href="http://i.stack.imgur.com/6T467.png" rel="nofollow"><img src="http://i.stack.imgur.com/6T467.png" alt="enter image description here"></a></p>
| 2 | 2016-08-10T07:30:05Z | [
"python",
"pandas"
] |
Method to generate an array of datetimes in python | 38,863,887 | <p>I am trying to come up with a method to generate a set of timestamps 15 minutes every hours, 8 hours per day for the last month. My approach is top-down, first generate the days and then use these candidates to generate 8 children-timestamps for every day and then finally generate 4 grandchildren-timestamps for every hour.</p>
<pre><code>collection = []
numdays = 10
numHours = 4
numMinutes = 5
base = datetime.datetime.today()
datelist = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
hourList = [date - datetime.timedelta(hours=x) for date in datelist]
minuteList = [hour - datetime.timedelta(minutes=numMinutes) for hour in hourList]
</code></pre>
<p>Is there a more elegant substructure to thinking about this?</p>
| 0 | 2016-08-10T03:48:54Z | 38,884,619 | <p>How about something like this:</p>
<pre><code>first = datetime(2016, 8, 1, 8, 0, 0)
dates = [first]
for days in range(1, 31): # How many days.
for _ in range(8 * 4): # 8 hours, 4x 15 min intervals per hour
dates.append(dates[-1] + timedelta(minutes = 15))
dates.append(dates[0] + timedelta(days = days))
</code></pre>
| 1 | 2016-08-10T22:33:39Z | [
"python",
"datetime",
"date-range"
] |
How to file open with different filename using python ftplib | 38,863,906 | <p>My current python code:</p>
<pre><code>import ftplib
import hashlib
import urllib
def ftp():
hashing="123"
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
file = open('Desktop/test.png','rb')
m.update(hashing)
dd = m.hexdigest()
ftp.storbinary('STOR '+dd+ '.png', file)
file.close()
ftp.quit()
</code></pre>
<p>I got different filename that consist of test.png, test1.png and test2.png. And i wanted to open the file and store it whenever any of the file is being open.
I tried using * asterisk and i got an error:</p>
<pre><code>file = open('Desktop/*.png, 'rb')
</code></pre>
| -1 | 2016-08-10T03:50:44Z | 38,864,146 | <p>How about this? Use glob to find the files, then loop over the list from glob running ftp() on each file?</p>
<pre><code>import ftplib
import hashlib
import urllib
from glob import glob
def ftp(filename):
hashing="123"
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
file = open(filename,'rb')
m.update(hashing)
dd = m.hexdigest()
ftp.storbinary('STOR '+dd+ '.png', file)
file.close()
ftp.quit()
if __name__ == '__main__':
# get the files
templist = glob('test*.png')
# loop over the files we found
for filename in templist:
ftp(filename)
</code></pre>
| 0 | 2016-08-10T04:18:46Z | [
"python",
"python-2.7",
"ftp"
] |
How to file open with different filename using python ftplib | 38,863,906 | <p>My current python code:</p>
<pre><code>import ftplib
import hashlib
import urllib
def ftp():
hashing="123"
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
file = open('Desktop/test.png','rb')
m.update(hashing)
dd = m.hexdigest()
ftp.storbinary('STOR '+dd+ '.png', file)
file.close()
ftp.quit()
</code></pre>
<p>I got different filename that consist of test.png, test1.png and test2.png. And i wanted to open the file and store it whenever any of the file is being open.
I tried using * asterisk and i got an error:</p>
<pre><code>file = open('Desktop/*.png, 'rb')
</code></pre>
| -1 | 2016-08-10T03:50:44Z | 38,864,375 | <p>Try this version instead:</p>
<pre><code>import os
import ftplib
import hashlib
import glob
image_directory = '/home/Desktop/images/'
hashing = "123"
m = hashlib.md5()
m.update(hashing)
dd = m.hexdigest()
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
for image in glob.iglob(os.path.join(image_directory, 'test*.png')):
with open(image, 'rb') as file:
ftp.storbinary('STOR '+dd+ '.png', file)
ftp.close()
ftp.quit()
</code></pre>
<p>I hope you realize this will just write the same file over and over again on your FTP server, since <code>dd</code> is never updated.</p>
<p>You also really shouldn't be using MD5 anymore. If you just want to store the files with the checksums, try this version instead:</p>
<pre><code>import os
import ftplib
import hashlib
import glob
def get_sha512(file):
f = open(file, 'rb')
value = hashlib.sha256(f.read()).digest()
f.close()
return value
image_directory = '/home/Desktop/images/'
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
for image in glob.iglob(os.path.join(image_directory, 'test*.png')):
hash = get_sha512(image)[:16]
with open(image, 'rb') as file:
ftp.storbinary('STOR {}.png'.format(hash), file)
ftp.close()
ftp.quit()
</code></pre>
| 1 | 2016-08-10T04:38:38Z | [
"python",
"python-2.7",
"ftp"
] |
Choosing python data structures to speed up algorithm implementation | 38,863,940 | <p>So I'm given a large collection (roughly 200k) of lists. Each contains a subset of the numbers 0 through 27. I want to return two of the lists where the product of their lengths is greater than the product of the lengths of any other pair of lists. There's another condition, namely that the lists have no numbers in common.</p>
<p>There's an algorithm I found for this (can't remember the source, apologies for non-specificity of props) which exploits the fact that there are fewer total subsets of the numbers 0 through 27 than there are words in the dictionary.</p>
<p>The first thing I've done is looped through all the lists, found the unique subset of integers that comprise it and indexed it as a number between 0 and 1<<28. As follows:</p>
<pre><code>def index_lists(lists):
index_hash = {}
for raw_list in lists:
length = len(raw_list)
if length > index_hash.get(index,{}).get("length"):
index = find_index(raw_list)
index_hash[index] = {"list": raw_list, "length": length}
return index_hash
</code></pre>
<p>This gives me the longest list and the length of the that list for each subset that's actually contained in the collection of lists given. Naturally, not all subsets from 0 to (1<<28)-1 are necessarily included, since there's not guarantee the supplied collection has a list containing each unique subset.</p>
<p>What I then want, for each subset 0 through 1<<28 (all of them this time) is the longest list that contains at most that subset. This is the part that is killing me. At a high level, it should, for each subset, first check to see if that subset is contained in the index_hash. It should then compare the length of that entry in the hash (if it exists there) to the lengths stored previously in the current hash for the current subset minus one number (this is an inner loop 27 strong). The greatest of these is stored in this new hash for the current subset of the outer loop. The code right now looks like this:</p>
<pre><code>def at_most_hash(index_hash):
most_hash = {}
for i in xrange(1<<28): # pretty sure this is a bad idea
max_entry = index_hash.get(i)
if max_entry:
max_length = max_entry["length"]
max_word = max_entry["list"]
else:
max_length = 0
max_word = []
for j in xrange(28): # again, probably not great
subset_index = i & ~(1<<j) # gets us a pre-computed subset
at_most_entry = most_hash.get(subset_index, {})
at_most_length = at_most_entry.get("length",0)
if at_most_length > max_length:
max_length = at_most_length
max_list = at_most_entry["list"]
most_hash[i] = {"length": max_length, "list": max_list}
return most_hash
</code></pre>
<p>This loop obviously takes several forevers to complete. I feel that I'm new enough to python that my choice of how to iterate and what data structures to use may have been completely disastrous. Not to mention the prospective memory problems from attempting to fill the dictionary. Is there perhaps a better structure or package to use as data structures? Or a better way to set up the iteration? Or maybe I can do this more sparsely?</p>
<p>The next part of the algorithm just cycles through all the lists we were given and takes the product of the subset's max_length and complementary subset's max length by looking them up in at_most_hash, taking the max of those.</p>
<p>Any suggestions here? I appreciate the patience for wading through my long-winded question and less than decent attempt at coding this up.</p>
<p>In theory, this is still a better approach than working with the collection of lists alone since that approach is roughly o(200k^2) and this one is roughly o(28*2^28 + 200k), yet my implementation is holding me back.</p>
| 2 | 2016-08-10T03:53:59Z | 38,864,174 | <p>This is a bit too long for a comment so I will post it as an answer. One more direct way to index your subsets as integers is to use "bitsets" with each bit in the binary representation corresponding to one of the numbers.</p>
<p>For example, the set {0,2,3} would be represented by 2<sup>0</sup> + 2<sup>2</sup> + 2<sup>3</sup> = 13 and {4,5} would be represented by 2<sup>4</sup> + 2<sup>5</sup> = 48</p>
<p>This would allow you to use simple lists instead of dictionaries and Python's generic hashing function.</p>
| 1 | 2016-08-10T04:21:32Z | [
"python",
"algorithm",
"performance",
"optimization",
"data-structures"
] |
Choosing python data structures to speed up algorithm implementation | 38,863,940 | <p>So I'm given a large collection (roughly 200k) of lists. Each contains a subset of the numbers 0 through 27. I want to return two of the lists where the product of their lengths is greater than the product of the lengths of any other pair of lists. There's another condition, namely that the lists have no numbers in common.</p>
<p>There's an algorithm I found for this (can't remember the source, apologies for non-specificity of props) which exploits the fact that there are fewer total subsets of the numbers 0 through 27 than there are words in the dictionary.</p>
<p>The first thing I've done is looped through all the lists, found the unique subset of integers that comprise it and indexed it as a number between 0 and 1<<28. As follows:</p>
<pre><code>def index_lists(lists):
index_hash = {}
for raw_list in lists:
length = len(raw_list)
if length > index_hash.get(index,{}).get("length"):
index = find_index(raw_list)
index_hash[index] = {"list": raw_list, "length": length}
return index_hash
</code></pre>
<p>This gives me the longest list and the length of the that list for each subset that's actually contained in the collection of lists given. Naturally, not all subsets from 0 to (1<<28)-1 are necessarily included, since there's not guarantee the supplied collection has a list containing each unique subset.</p>
<p>What I then want, for each subset 0 through 1<<28 (all of them this time) is the longest list that contains at most that subset. This is the part that is killing me. At a high level, it should, for each subset, first check to see if that subset is contained in the index_hash. It should then compare the length of that entry in the hash (if it exists there) to the lengths stored previously in the current hash for the current subset minus one number (this is an inner loop 27 strong). The greatest of these is stored in this new hash for the current subset of the outer loop. The code right now looks like this:</p>
<pre><code>def at_most_hash(index_hash):
most_hash = {}
for i in xrange(1<<28): # pretty sure this is a bad idea
max_entry = index_hash.get(i)
if max_entry:
max_length = max_entry["length"]
max_word = max_entry["list"]
else:
max_length = 0
max_word = []
for j in xrange(28): # again, probably not great
subset_index = i & ~(1<<j) # gets us a pre-computed subset
at_most_entry = most_hash.get(subset_index, {})
at_most_length = at_most_entry.get("length",0)
if at_most_length > max_length:
max_length = at_most_length
max_list = at_most_entry["list"]
most_hash[i] = {"length": max_length, "list": max_list}
return most_hash
</code></pre>
<p>This loop obviously takes several forevers to complete. I feel that I'm new enough to python that my choice of how to iterate and what data structures to use may have been completely disastrous. Not to mention the prospective memory problems from attempting to fill the dictionary. Is there perhaps a better structure or package to use as data structures? Or a better way to set up the iteration? Or maybe I can do this more sparsely?</p>
<p>The next part of the algorithm just cycles through all the lists we were given and takes the product of the subset's max_length and complementary subset's max length by looking them up in at_most_hash, taking the max of those.</p>
<p>Any suggestions here? I appreciate the patience for wading through my long-winded question and less than decent attempt at coding this up.</p>
<p>In theory, this is still a better approach than working with the collection of lists alone since that approach is roughly o(200k^2) and this one is roughly o(28*2^28 + 200k), yet my implementation is holding me back.</p>
| 2 | 2016-08-10T03:53:59Z | 38,864,815 | <p>Given that your indexes are just ints, you could save some time and space by using lists instead of dicts. I'd go further and bring in <a href="http://www.numpy.org/" rel="nofollow">NumPy</a> arrays. They offer compact storage representation and efficient operations that let you implicitly perform repetitive work in C, bypassing a ton of interpreter overhead.</p>
<p>Instead of <code>index_hash</code>, we start by building a NumPy array where <code>index_array[i]</code> is the length of the longest list whose set of elements is represented by <code>i</code>, or <code>0</code> if there is no such list:</p>
<pre><code>import numpy
index_array = numpy.zeros(1<<28, dtype=int) # We could probably get away with dtype=int8.
for raw_list in lists:
i = find_index(raw_list)
index_array[i] = max(index_array[i], len(raw_list))
</code></pre>
<p>We then use NumPy operations to bubble up the lengths in C instead of interpreted Python. Things might get confusing from here:</p>
<pre><code>for bit_index in xrange(28):
index_array = index_array.reshape([1<<(28-bit_index), 1<<bit_index])
numpy.maximum(index_array[::2], index_array[1::2], out=index_array[1::2])
index_array = index_array.reshape([1<<28])
</code></pre>
<p>Each <code>reshape</code> call takes a new view of the array where data in even-numbered rows corresponds to sets with the bit at <code>bit_index</code> clear, and data in odd-numbered rows corresponds to sets with the bit at <code>bit_index</code> set. The <code>numpy.maximum</code> call then performs the bubble-up operation for that bit. At the end, each cell <code>index_array[i]</code> of <code>index_array</code> represents the length of the longest list whose elements are a subset of set <code>i</code>.</p>
<p>We then compute the products of lengths at complementary indices:</p>
<pre><code>products = index_array * index_array[::-1] # We'd probably have to adjust this part
# if we picked dtype=int8 earlier.
</code></pre>
<p>find where the best product is:</p>
<pre><code>best_product_index = products.argmax()
</code></pre>
<p>and the longest lists whose elements are subsets of the set represented by <code>best_product_index</code> and its complement are the lists we want.</p>
| 2 | 2016-08-10T05:19:41Z | [
"python",
"algorithm",
"performance",
"optimization",
"data-structures"
] |
Error in code in python | 38,863,959 | <pre><code>data=open('D:\\e.txt','r',encoding='utf-8')
x= data.readlines()
tw= x.split(',"text":" ')[1].split('","source')[0]
</code></pre>
<p>i have problem </p>
<pre><code>AttributeError: 'list' object has no attribute 'split'
</code></pre>
| 0 | 2016-08-10T03:56:11Z | 38,865,544 | <p><code>readlines()</code> returns a list of all the lines in a file. Whereas split() is a string method. As @inspectorG4dget suggested if you want to use <code>split()</code>, use <code>read()</code> which returns the contents of a file as string.</p>
<pre><code>data=open('D:\\file_path','r')
x= data.read()
tw= x.split("separator")
</code></pre>
| 0 | 2016-08-10T06:14:02Z | [
"python"
] |
How to understand logging formatter? | 38,863,988 | <p>To Python Experts:</p>
<p>I'm new to programming and learning logging python package. </p>
<p>According to logging document, I set the format of my logging message as follows:</p>
<pre><code>logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
</code></pre>
<p>Here is the output of logging message:</p>
<pre><code>2016-08-09 19:57:08,363 - DEBUG - A B
2016-01-31 0 12
2016-02-29 -1 12
</code></pre>
<p>How to make A B (the column names of the datafram) to the next line?:</p>
<p>Also, would you please help me understand %(asctime)s - %(levelname)s - %(message)s? why put % before bracket and s after bracket?</p>
<pre><code>2016-08-09 19:57:08,363 - DEBUG -
A B
2016-01-31 0 12
2016-02-29 -1 12
</code></pre>
| 0 | 2016-08-10T04:00:39Z | 38,864,057 | <p>For your first question:</p>
<p>Just add an extra newline to your call of <code>logging.debug</code>:</p>
<p>For example, if your logger is called <code>logger</code>, and you are logging the message through <code>logging.debug(msg)</code>, you can call <code>logging.debug('\n' + msg</code>) to move the message onto the newline.</p>
<p>As for the format: the <code>%</code> indicates that the upcoming text should be parsed as a format specifier. The parentheses, <code>()</code>, surround the name of the specifier, and the trailing <code>s</code> converts the input data into a string. See: <a class='doc-link' href="http://stackoverflow.com/documentation/python/1019/string-formatting#t=201608100406234849918">string formatting</a>, <a href="http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format">difference between <code>str.format</code> and <code>%</code></a>.</p>
<p>So, <code>%(name)s</code> allows you to specify <code>name</code> which will be converted to a string. The different names, <code>asctime</code>, <code>levelname</code>, <code>message</code> are specified by the logging framework.</p>
| 1 | 2016-08-10T04:08:56Z | [
"python",
"logging"
] |
Creating an instance of a class existing in a different file(python) | 38,864,032 | <p>I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)</p>
<p>main.py</p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero
</code></pre>
<p>player.py</p>
<pre><code>import pygame
import main
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()
</code></pre>
<p>Running this gives me the following error:</p>
<pre><code>AttributeError: 'module' object has no attribute 'hero'
</code></pre>
<p>I'm not quite understanding why it's trying to get an attribute instead of creating an instance. I've tried looking at other examples and how they are solving the problem but when I attempt to apply it to the code above it does not solve my issue.</p>
| 0 | 2016-08-10T04:06:10Z | 38,864,266 | <p>Drop the <code>import main</code> in player.py and change the last line in main.py to:</p>
<pre><code>p1 = player.hero("woody.png",[2,2])
</code></pre>
<p><strong>Edit:</strong>
Python does not know what class/function <code>hero</code> is. It needs you to tell it hero is a class in the player module. And that's what <code>player.hero</code> means. </p>
<p>Also never import one module from another and vice versa. You can get an import loop which is very hard to debug.</p>
<p>Lastly, in python it is common to name a class with a capital letter as <code>Hero</code> instead of <code>hero</code>. </p>
| 0 | 2016-08-10T04:29:25Z | [
"python",
"python-2.7",
"oop"
] |
Creating an instance of a class existing in a different file(python) | 38,864,032 | <p>I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)</p>
<p>main.py</p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero
</code></pre>
<p>player.py</p>
<pre><code>import pygame
import main
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()
</code></pre>
<p>Running this gives me the following error:</p>
<pre><code>AttributeError: 'module' object has no attribute 'hero'
</code></pre>
<p>I'm not quite understanding why it's trying to get an attribute instead of creating an instance. I've tried looking at other examples and how they are solving the problem but when I attempt to apply it to the code above it does not solve my issue.</p>
| 0 | 2016-08-10T04:06:10Z | 38,864,284 | <p>Like Athena said above, don't import <code>main</code> into <code>player</code> and <code>player</code> into <code>main</code>. This causes a import loop. Just simply import <code>player</code> into <code>main</code></p>
<p>Secondly, you must say <code>player.hero()</code> if you want to use the class <code>hero</code> from the <code>player</code> module. Or if you want to just say <code>hero()</code>, you can say <code>from player import*</code>. This tells python to import all the files from <code>player</code> into the namespace <code>main</code>. </p>
<p><strong>Be careful using this though</strong>, as a function or class from your player file may conflict with an already exiting function or class, with the same name.</p>
<p>And as a side note, classes in python general have their first letter capitalized.</p>
<p>here is how your files should look:</p>
<p><strong>main.py</strong></p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero
</code></pre>
<p><strong>player.py</strong></p>
<pre><code>import pygame
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()#.......etc
</code></pre>
| 0 | 2016-08-10T04:30:52Z | [
"python",
"python-2.7",
"oop"
] |
Creating an instance of a class existing in a different file(python) | 38,864,032 | <p>I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)</p>
<p>main.py</p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero
</code></pre>
<p>player.py</p>
<pre><code>import pygame
import main
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()
</code></pre>
<p>Running this gives me the following error:</p>
<pre><code>AttributeError: 'module' object has no attribute 'hero'
</code></pre>
<p>I'm not quite understanding why it's trying to get an attribute instead of creating an instance. I've tried looking at other examples and how they are solving the problem but when I attempt to apply it to the code above it does not solve my issue.</p>
| 0 | 2016-08-10T04:06:10Z | 38,864,322 | <ol>
<li><p>To import <code>hero</code> from another module, you should write <code>player.hero</code>, or simply <code>from player import hero</code>.</p></li>
<li><p>Importing <code>player</code> in <code>main</code> and <code>main</code> in <code>player</code> would cause "circular references".</p></li>
</ol>
<hr>
<p>Here is the modified code:</p>
<p>main.py</p>
<pre><code>import pygame
from player import hero # Imports the player.py script
p1 = hero("woody.png",[2,2]) # Creates an instance of hero
</code></pre>
<p>player.py</p>
<pre><code>import pygame
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()#.....etc
</code></pre>
| 1 | 2016-08-10T04:33:47Z | [
"python",
"python-2.7",
"oop"
] |
How to call a function that is later in a Python script? | 38,864,080 | <p>I am currently learning Python for some penetration testing and was practicing making password cracking scripts. While I was making a script for a telnet pass cracker I ran into a problem with some of the functionality of it. While trying to allow the user to output the findings, as well as some extra information, I found my issue. </p>
<p>I am using getopt to take arguments for the script such as the ip, username, and an output file (I am trying to make an option to put in a word list for the passwords and usernames but I am still learning about using files). Because a function has to be written above where it is called I am running into the issue of needing the function in two places.</p>
<p>I need it above the getopt for loop, but I also need it in the for loop that guesses the password. I have looked at a few possible solutions but I am really confused by them as I am still somewhat new to Python. I do not really know how to explain it well but the basis of what I need to do is to be able to call the function before the function is written if anyone understands that. Thank you for all the help in advance.</p>
<p>Also I know that there are most likely a lot more efficient ways to do what I am trying, but I just wanted to mess around and see if I had the ability to do this, no matter how unorganized the code is.</p>
<p>Here is my code:</p>
<pre><code>import telnetlib
import re
import sys
import time
import getopt
from time import gmtime, strftime
total_time_start = time.clock()
#Get the arguments from the user
try:
opts, args = getopt.getopt(sys.argv[1:], "i:u:f:")
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
passwords = ["hello","test", "msfadmin", "password"]
username = " "
ip = "0.0.0.0"
output_file = " "
for o, a in opts:
if o == "-i":
ip = a
elif o in ("-u"):
username =a
elif o in ("-f"):
output_file = a
file_out()
else:
assert False, "unhandled option"
#Connect using the password and username from the for loop later in the script.
def connect(username, password, ip):
global tn
tn = telnetlib.Telnet(ip)
print "[*] Trying " + username + " and " + password
tn.read_until("metasploitable login: ")
tn.write(username + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
#Guess the password
for password in passwords:
attempt = connect(username, password, ip)
time_start = time.clock()
if attempt == tn.read_until("msfadmin@metasploitable", timeout = 1):
pass
time_end = time.clock()
time_finish = time_end - time_start
#Determine if the password is correct or not
if time_finish > 0.001000:
print "\033[1;32;40m [*] Password '" + password + "' found for user '" + username+"'\033[0;37;40m\n"
total_time_end = time.clock()
total_time = (total_time_end - total_time_start)
#Print the findings to a file that is selected from an argument
def file_out():
date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
fout = open(output_file, 'w')
fout.write("Server IP: " + ip)
fout.write("\nUsername is " + username)
fout.write("Password is " + password)
fout.write("\nCrack was conducted on " + date)
fout.write("The crack took a total time of " + total_time)
sys.exit(0)
</code></pre>
<p>Here is the error I am getting:</p>
<p>python telnet_cracker.py -i [ip of metasploitable] -u msfadmin -f test.txt</p>
<pre><code>Traceback (most recent call last):
File "telnet_cracker.py", line 49, in <module>
file_out()
NameError: name 'file_out' is not defined
</code></pre>
| 0 | 2016-08-10T04:10:57Z | 38,864,117 | <p>Move the function to the top level of the script. Don't nest it inside of an if statement inside of a loop. </p>
<p>There's no need to redefine a function in a loop (and defining it in a conditional doesn't seem good either)</p>
<blockquote>
<p>a function has to be written above where it is called</p>
</blockquote>
<p>Not quite. Functions simply need to be <em>defined</em> before the code that runs them. The functions don't need to explicitly be "above the code" where they are called. Same logic applies to variables. </p>
<p>If you need to reference certain variables for the function, then use parameters. </p>
| 2 | 2016-08-10T04:15:50Z | [
"python",
"scripting",
"telnet",
"penetration-testing"
] |
How to call a function that is later in a Python script? | 38,864,080 | <p>I am currently learning Python for some penetration testing and was practicing making password cracking scripts. While I was making a script for a telnet pass cracker I ran into a problem with some of the functionality of it. While trying to allow the user to output the findings, as well as some extra information, I found my issue. </p>
<p>I am using getopt to take arguments for the script such as the ip, username, and an output file (I am trying to make an option to put in a word list for the passwords and usernames but I am still learning about using files). Because a function has to be written above where it is called I am running into the issue of needing the function in two places.</p>
<p>I need it above the getopt for loop, but I also need it in the for loop that guesses the password. I have looked at a few possible solutions but I am really confused by them as I am still somewhat new to Python. I do not really know how to explain it well but the basis of what I need to do is to be able to call the function before the function is written if anyone understands that. Thank you for all the help in advance.</p>
<p>Also I know that there are most likely a lot more efficient ways to do what I am trying, but I just wanted to mess around and see if I had the ability to do this, no matter how unorganized the code is.</p>
<p>Here is my code:</p>
<pre><code>import telnetlib
import re
import sys
import time
import getopt
from time import gmtime, strftime
total_time_start = time.clock()
#Get the arguments from the user
try:
opts, args = getopt.getopt(sys.argv[1:], "i:u:f:")
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
passwords = ["hello","test", "msfadmin", "password"]
username = " "
ip = "0.0.0.0"
output_file = " "
for o, a in opts:
if o == "-i":
ip = a
elif o in ("-u"):
username =a
elif o in ("-f"):
output_file = a
file_out()
else:
assert False, "unhandled option"
#Connect using the password and username from the for loop later in the script.
def connect(username, password, ip):
global tn
tn = telnetlib.Telnet(ip)
print "[*] Trying " + username + " and " + password
tn.read_until("metasploitable login: ")
tn.write(username + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
#Guess the password
for password in passwords:
attempt = connect(username, password, ip)
time_start = time.clock()
if attempt == tn.read_until("msfadmin@metasploitable", timeout = 1):
pass
time_end = time.clock()
time_finish = time_end - time_start
#Determine if the password is correct or not
if time_finish > 0.001000:
print "\033[1;32;40m [*] Password '" + password + "' found for user '" + username+"'\033[0;37;40m\n"
total_time_end = time.clock()
total_time = (total_time_end - total_time_start)
#Print the findings to a file that is selected from an argument
def file_out():
date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
fout = open(output_file, 'w')
fout.write("Server IP: " + ip)
fout.write("\nUsername is " + username)
fout.write("Password is " + password)
fout.write("\nCrack was conducted on " + date)
fout.write("The crack took a total time of " + total_time)
sys.exit(0)
</code></pre>
<p>Here is the error I am getting:</p>
<p>python telnet_cracker.py -i [ip of metasploitable] -u msfadmin -f test.txt</p>
<pre><code>Traceback (most recent call last):
File "telnet_cracker.py", line 49, in <module>
file_out()
NameError: name 'file_out' is not defined
</code></pre>
| 0 | 2016-08-10T04:10:57Z | 38,864,191 | <p>Python is a dynamic language, but requires functions at the top-level to be resolved by interpretation time.</p>
<p>Just move the function to the top and call it later, or nest it within a function. </p>
<p>For example, this <strong>will not</strong> work:</p>
<pre><code>x()
def x():
pass
</code></pre>
<p>This however will work:</p>
<pre><code>def x():
pass
x()
</code></pre>
<p>And so will this:</p>
<pre><code>def y():
x()
def x():
pass
y()
</code></pre>
<p>Python gives you all the tools to avoid forward declarations and circular dependencies with ease.</p>
| 0 | 2016-08-10T04:22:59Z | [
"python",
"scripting",
"telnet",
"penetration-testing"
] |
create a third list by combining values in two lists | 38,864,103 | <p>I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get the sum of the corresponding floats from "donlist". I have absolutely no idea how to do this and have been trying to figure it out for the past 2-3 hours now. Does anyone know how to do it? Thank you.</p>
<pre><code>import random
from array import *
counter = 0
donlist = []
charlist = []
while counter != 100:
d = random.uniform(1.00,100.00)
c = random.randint(1,15)
counter +=1
donlist.append(d)
donlist = [round(elem,2) for elem in donlist]
charlist.append(c)
if counter == 100:
break
</code></pre>
<p>Sample output:</p>
<pre><code>Charity Total Donations
1 802.65
2 1212.25
3 108.25
4 9324.12
5 534.98
6 6235.12
7 223.18
8 11.12
9 3345.68
10 856.68
11 7123.05
12 6125.86
13 1200.25
14 468.32
15 685.26
</code></pre>
| 1 | 2016-08-10T04:13:54Z | 38,864,206 | <p>Use a <code>dict</code>, with the charity number as the key. You simply add the donation to the corresponding <code>dict</code> value. If the <code>dict</code> element doesn't exist yet, set it to zero as its initial value.
I'm using <code>defaultdict</code>: the <code>lambda: 0</code> argument will guarantee a zero value if the key doesn't exist yet, otherwise you can just add to it.</p>
<p>Updating your script (with a few minor other alterations):</p>
<pre><code>import random
from collections import defaultdict
donlist = []
charlist = []
totals = defaultdict(float)
counter = 0
while counter != 100:
counter += 1
d = random.uniform(1.00,100.00)
c = random.randint(1,15)
donlist.append(d)
donlist = [round(elem,2) for elem in donlist]
charlist.append(c)
totals[c] += d
</code></pre>
<p>nb: I removed the <code>array</code> import, since you're only using <code>list</code>s in the code.</p>
| 2 | 2016-08-10T04:24:02Z | [
"python",
"list"
] |
create a third list by combining values in two lists | 38,864,103 | <p>I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get the sum of the corresponding floats from "donlist". I have absolutely no idea how to do this and have been trying to figure it out for the past 2-3 hours now. Does anyone know how to do it? Thank you.</p>
<pre><code>import random
from array import *
counter = 0
donlist = []
charlist = []
while counter != 100:
d = random.uniform(1.00,100.00)
c = random.randint(1,15)
counter +=1
donlist.append(d)
donlist = [round(elem,2) for elem in donlist]
charlist.append(c)
if counter == 100:
break
</code></pre>
<p>Sample output:</p>
<pre><code>Charity Total Donations
1 802.65
2 1212.25
3 108.25
4 9324.12
5 534.98
6 6235.12
7 223.18
8 11.12
9 3345.68
10 856.68
11 7123.05
12 6125.86
13 1200.25
14 468.32
15 685.26
</code></pre>
| 1 | 2016-08-10T04:13:54Z | 38,864,231 | <p>This seems a good example to use the <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">zip</a> function. It gets two lists as argument (in your case the <code>donlist</code> and <code>charlist</code>) and creates an iterator of these, so you can iterate one time adding the values from <code>donlist</code> in the right charity position. <code>zip</code> example:</p>
<pre class="lang-py prettyprint-override"><code>for a, b in zip(range(1, 5), range(5, 10)):
print(a, b)
</code></pre>
<p>will output</p>
<pre><code>1 5
2 6
3 7
4 8
</code></pre>
<p>I strongly recommend generating the data lists before creating the third, so you can do</p>
<pre class="lang-py prettyprint-override"><code>donlist = [ random.uniform(1.0, 100.0) for _ in range(0, 100) ]
charlist = [ random.randint(1, 15) for _ in range(0, 100) ]
</code></pre>
<p>This is a simple syntax to create a list from an iterator. You can read more about it <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">here</a>.</p>
<p>This way, you can guarantee that it works for cases when these lists are not generated during the calculation, for an example, where the user input the values.</p>
<p>After the lists generation / input you can just:</p>
<pre class="lang-py prettyprint-override"><code># this is the same as a list comprehension but for a dict
# https://docs.python.org/3/tutorial/datastructures.html#dictionaries
result = { char : 0 for char in range(1, 16) }
for don, char in zip(donlist, charlist):
result[char] += don
</code></pre>
<p>In the end each charity <code>N</code> has it's donation value in <code>result[N]</code>.</p>
| 1 | 2016-08-10T04:26:09Z | [
"python",
"list"
] |
create a third list by combining values in two lists | 38,864,103 | <p>I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get the sum of the corresponding floats from "donlist". I have absolutely no idea how to do this and have been trying to figure it out for the past 2-3 hours now. Does anyone know how to do it? Thank you.</p>
<pre><code>import random
from array import *
counter = 0
donlist = []
charlist = []
while counter != 100:
d = random.uniform(1.00,100.00)
c = random.randint(1,15)
counter +=1
donlist.append(d)
donlist = [round(elem,2) for elem in donlist]
charlist.append(c)
if counter == 100:
break
</code></pre>
<p>Sample output:</p>
<pre><code>Charity Total Donations
1 802.65
2 1212.25
3 108.25
4 9324.12
5 534.98
6 6235.12
7 223.18
8 11.12
9 3345.68
10 856.68
11 7123.05
12 6125.86
13 1200.25
14 468.32
15 685.26
</code></pre>
| 1 | 2016-08-10T04:13:54Z | 38,864,690 | <pre><code>>>> l1 = [1,1,3,4] # charity list
>>> l2 = [5,6,7,8] # donation list
>>> zip(l1,l2)
[(1, 5), (1, 6), (3, 7), (4, 8)]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for k,v in zip(l1,l2):
... d[k] += v
...
>>> d
defaultdict(<type 'int'>, {1: 11, 3: 7, 4: 8})
</code></pre>
<p>You can now index <code>d</code> by charity number and get the value of donation.</p>
| 0 | 2016-08-10T05:09:57Z | [
"python",
"list"
] |
pymysql inserting random numbers into a column using python | 38,864,144 | <p>I want to insert random numbers to a MySQL column <code>rnd_value</code> with 100 random numbers including and between 1 to 100 using python.</p>
<p>I will generate random numbers from python using </p>
<pre><code>random.randrange(1,100)
</code></pre>
<p>I have added MYSQL query to the database </p>
<pre><code> CREATE SCHEMA `random_values` ;
CREATE TABLE `exercise`.`random_values` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`rnd_value` INT NULL COMMENT '',
PRIMARY KEY (`id`) COMMENT '');
</code></pre>
<p>I use pymysql connector to insert data into MySQL database. Can anyone suggest me to how to insert these random numbers into a MySQL column using python?</p>
| 0 | 2016-08-10T04:18:13Z | 38,864,471 | <p>How about this simple approach? Connect to the db (assuming localhost and database name is exercise). Then shove the 100 values in 1 by 1? </p>
<pre><code>import pymysql
import random
with pymysql.connect(host='localhost', db='exercise') as db:
for i in random.randrange(1,100):
qry = "INSERT INTO random_values (rnd_value) VALUES ({})".format(i)
with db.cursor() as cur:
cur.execute(qry)
db.commit()
</code></pre>
| 1 | 2016-08-10T04:48:09Z | [
"python",
"mysql",
"random",
"pymysql"
] |
pymysql inserting random numbers into a column using python | 38,864,144 | <p>I want to insert random numbers to a MySQL column <code>rnd_value</code> with 100 random numbers including and between 1 to 100 using python.</p>
<p>I will generate random numbers from python using </p>
<pre><code>random.randrange(1,100)
</code></pre>
<p>I have added MYSQL query to the database </p>
<pre><code> CREATE SCHEMA `random_values` ;
CREATE TABLE `exercise`.`random_values` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`rnd_value` INT NULL COMMENT '',
PRIMARY KEY (`id`) COMMENT '');
</code></pre>
<p>I use pymysql connector to insert data into MySQL database. Can anyone suggest me to how to insert these random numbers into a MySQL column using python?</p>
| 0 | 2016-08-10T04:18:13Z | 38,864,508 | <p>referred some portions from:
<a href="http://stackoverflow.com/questions/20485332/pymysql-insert-into-not-working">Pymysql Insert Into not working</a></p>
<h3>install pymysql</h3>
<pre><code>pip install pymysql
</code></pre>
<h3>in mysql</h3>
<pre><code>CREATE TABLE `t1` (`c1` INT NULL,`c2` INT NULL )
</code></pre>
<h2>python program</h2>
<pre><code>import pymysql
from random import randint
conn = pymysql.connect(host='localhost', port=3306, user="root")
cursor = conn.cursor()
for i in range (1, 101): # since you want to add 100 entries
v1 = randint(1,100)
v2 = randint(1,100)
sql_statement = "INSERT INTO test.t1(c1, c2) VALUES (" + str(v1) + "," + str(v2) + ")"
cursor.execute(sql_statement)
conn.commit() # commit to insert records into database
cursor.close()
conn.close()
</code></pre>
for multiple inserts, use some sort of looping mechanism, or use multi insert method
<p>Then switch over to mysql console and fire select statements to see if insert succeeded</p>
| 0 | 2016-08-10T04:51:46Z | [
"python",
"mysql",
"random",
"pymysql"
] |
pymysql inserting random numbers into a column using python | 38,864,144 | <p>I want to insert random numbers to a MySQL column <code>rnd_value</code> with 100 random numbers including and between 1 to 100 using python.</p>
<p>I will generate random numbers from python using </p>
<pre><code>random.randrange(1,100)
</code></pre>
<p>I have added MYSQL query to the database </p>
<pre><code> CREATE SCHEMA `random_values` ;
CREATE TABLE `exercise`.`random_values` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`rnd_value` INT NULL COMMENT '',
PRIMARY KEY (`id`) COMMENT '');
</code></pre>
<p>I use pymysql connector to insert data into MySQL database. Can anyone suggest me to how to insert these random numbers into a MySQL column using python?</p>
| 0 | 2016-08-10T04:18:13Z | 38,865,142 | <p>Thanks for all the responses, this code seems to work for me,</p>
<pre><code>import pymysql
import random
connection=pymysql.connect(host='localhost',user='root',password='server',
db='exercise',charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
for i in range (1, 101):
j=random.randrange(1,100)
sql = "INSERT INTO exercise.random_values(rnd_value) VALUES (%s)"
cursor.execute(sql,(j))
connection.commit()
finally:
connection.close()
</code></pre>
| 0 | 2016-08-10T05:46:21Z | [
"python",
"mysql",
"random",
"pymysql"
] |
Splitting a network into subnets of multiple prefixes | 38,864,268 | <p>I'm using the <code>netaddr</code> module and trying to figure out how/if I can split a network into subnets of varying prefixes. For example take a /16 and split it into X /23s and Y /24s. </p>
<p>From what I can tell we can use the <code>subnet</code> function to split a network in X number of a given prefix but it only takes 1 prefix.</p>
<p>The above would slice out 4 /23s out of the /16 which is great, but how do I take the remaining space and slice that into a differing prefix?</p>
<pre><code>ip = IPNetwork('172.24.0.0/16')
subnets = list(ip.subnet(23, count=4))
</code></pre>
<p>Is there a way that I can achieve what I'm trying to do with netaddr?</p>
| 4 | 2016-08-10T04:29:36Z | 38,865,810 | <p>Try the below </p>
<pre><code>from netaddr import IPNetwork, cidr_merge, cidr_exclude
class IPSplitter(object):
def __init__(self, base_range):
self.avail_ranges = set((IPNetwork(base_range),))
def get_subnet(self, prefix, count=None):
for ip_network in self.get_available_ranges():
subnets = list(ip_network.subnet(prefix, count=count))
if not subnets:
continue
self.remove_avail_range(ip_network)
self.avail_ranges = self.avail_ranges.union(set(cidr_exclude(ip_network, cidr_merge(subnets)[0])))
return subnets
def get_available_ranges(self):
return sorted(self.avail_ranges, key=lambda x: x.prefixlen, reverse=True)
def remove_avail_range(self, ip_network):
self.avail_ranges.remove(ip_network)
</code></pre>
<p>You can use it like below. With some more math you can make it more efficient,like chopping of subnets from two different blocks when count is not satisfied from a single block.</p>
<pre><code>In [1]: from ip_splitter import IPSplitter
In [2]: s = IPSplitter('172.24.0.0/16')
In [3]: s.get_available_ranges()
Out[3]: [IPNetwork('172.24.0.0/16')]
In [4]: s.get_subnet(23, count=4)
Out[4]:
[IPNetwork('172.24.0.0/23'),
IPNetwork('172.24.2.0/23'),
IPNetwork('172.24.4.0/23'),
IPNetwork('172.24.6.0/23')]
In [5]: s.get_available_ranges()
Out[5]:
[IPNetwork('172.24.8.0/21'),
IPNetwork('172.24.16.0/20'),
IPNetwork('172.24.32.0/19'),
IPNetwork('172.24.64.0/18'),
IPNetwork('172.24.128.0/17')]
In [6]: s.get_subnet(28, count=10)
Out[6]:
[IPNetwork('172.24.8.0/28'),
IPNetwork('172.24.8.16/28'),
IPNetwork('172.24.8.32/28'),
IPNetwork('172.24.8.48/28'),
IPNetwork('172.24.8.64/28'),
IPNetwork('172.24.8.80/28'),
IPNetwork('172.24.8.96/28'),
IPNetwork('172.24.8.112/28'),
IPNetwork('172.24.8.128/28'),
IPNetwork('172.24.8.144/28')]
In [7]: s.get_available_ranges()
Out[7]:
[IPNetwork('172.24.8.128/25'),
IPNetwork('172.24.9.0/24'),
IPNetwork('172.24.10.0/23'),
IPNetwork('172.24.12.0/22'),
IPNetwork('172.24.16.0/20'),
IPNetwork('172.24.32.0/19'),
IPNetwork('172.24.64.0/18'),
IPNetwork('172.24.128.0/17')]
</code></pre>
| 3 | 2016-08-10T06:29:41Z | [
"python",
"python-2.7",
"networking"
] |
Splitting a network into subnets of multiple prefixes | 38,864,268 | <p>I'm using the <code>netaddr</code> module and trying to figure out how/if I can split a network into subnets of varying prefixes. For example take a /16 and split it into X /23s and Y /24s. </p>
<p>From what I can tell we can use the <code>subnet</code> function to split a network in X number of a given prefix but it only takes 1 prefix.</p>
<p>The above would slice out 4 /23s out of the /16 which is great, but how do I take the remaining space and slice that into a differing prefix?</p>
<pre><code>ip = IPNetwork('172.24.0.0/16')
subnets = list(ip.subnet(23, count=4))
</code></pre>
<p>Is there a way that I can achieve what I'm trying to do with netaddr?</p>
| 4 | 2016-08-10T04:29:36Z | 38,876,316 | <p>In my case the prefixes aren't completely arbitrary and they'll always result in an even split. For example for a /24 I'll always ask for 6 /27s and 4 /28s and in a /23 I'll always ask for 2 /25s, 2 /26s, 2 /27s and 4 /28s and I'll always be starting with either a /24 or /23 so the scheme is fairly predictable. </p>
<p>This is what I'm going with for the /24 and similarly for the /23:</p>
<pre><code>ip = IPNetwork('10.40.72.0/24')
network28s = list(ip.subnet(28, count=16))
presentation1 = list(network28s[0:1])
presentation2 = list(network28s[1:2])
database1 = list(network28s[2:3])
database2 = list(network28s[3:4])
internetlb1 = cidr_merge(list(network28s[4:6]))
internetlb2 = cidr_merge(list(network28s[6:8]))
internet1 = cidr_merge(list(network28s[8:10]))
internet2 = cidr_merge(list(network28s[10:12]))
application1 = cidr_merge(list(network28s[12:14]))
application2 = cidr_merge(list(network28s[14:16]))
</code></pre>
<p>I could only do this because of the fact that the scheme is so predictable and by predictable I mean, those 10 subnets will always be requested and they'll always be the same size the only variance is the CIDR itself. </p>
| 1 | 2016-08-10T14:31:15Z | [
"python",
"python-2.7",
"networking"
] |
Splitting a network into subnets of multiple prefixes | 38,864,268 | <p>I'm using the <code>netaddr</code> module and trying to figure out how/if I can split a network into subnets of varying prefixes. For example take a /16 and split it into X /23s and Y /24s. </p>
<p>From what I can tell we can use the <code>subnet</code> function to split a network in X number of a given prefix but it only takes 1 prefix.</p>
<p>The above would slice out 4 /23s out of the /16 which is great, but how do I take the remaining space and slice that into a differing prefix?</p>
<pre><code>ip = IPNetwork('172.24.0.0/16')
subnets = list(ip.subnet(23, count=4))
</code></pre>
<p>Is there a way that I can achieve what I'm trying to do with netaddr?</p>
| 4 | 2016-08-10T04:29:36Z | 38,933,612 | <p>You could first split it into a number of <code>/23</code> and then split a certain number of those into the number of <code>/24</code> you want. Quick example code off the top of my head.</p>
<pre><code>>>> from netaddr import *
>>> ip = IPNetwork('172.24.0.0/16')
>>> subnet_23 = list(ip.subnet(23))
>>> subnet_23[:6]
[IPNetwork('172.24.0.0/23'), IPNetwork('172.24.2.0/23'), IPNetwork('172.24.4.0/23'), IPNetwork('172.24.6.0/23'), IPNetwork('172.24.8.0/23'), IPNetwork('172.24.10.0/23')]
>>> len(subnet_23)
128
>>> final_subnets = []
>>> number_of_24s_wanted = 10
>>> for s in subnet_23:
... if len(final_subnets) < number_of_24s_wanted:
... final_subnets.extend(list(s.subnet(24)))
... else:
... final_subnets.append(s)
...
>>> final_subnets[:20]
[IPNetwork('172.24.0.0/24'), IPNetwork('172.24.1.0/24'), IPNetwork('172.24.2.0/24'), IPNetwork('172.24.3.0/24'), IPNetwork('172.24.4.0/24'), IPNetwork('172.24.5.0/24'), IPNetwork('172.24.6.0/24'), IPNetwork('172.24.7.0/24'), IPNetwork('172.24.8.0/24'), IPNetwork('172.24.9.0/24'), IPNetwork('172.24.10.0/23'), IPNetwork('172.24.12.0/23'), IPNetwork('172.24.14.0/23'), IPNetwork('172.24.16.0/23'), IPNetwork('172.24.18.0/23'), IPNetwork('172.24.20.0/23'), IPNetwork('172.24.22.0/23'), IPNetwork('172.24.24.0/23'), IPNetwork('172.24.26.0/23'), IPNetwork('172.24.28.0/23')]
>>> len(final_subnets)
133
</code></pre>
| 1 | 2016-08-13T14:17:22Z | [
"python",
"python-2.7",
"networking"
] |
Connect to local bluetooth | 38,864,366 | <p>I am using pybluez to develop a bluetooth application on linux in python. I want to know if it is possible to connect to a "localhost" for bluetooth so I can run the client and server on the same machine (as most people do for web development).</p>
<p>If this is not possible, how to most people develop bluetooth applications? Do they just run the client and server on different devices or is there a more clever way to handle this?</p>
<p>Eventually the server will run on a raspberry pi and the client will be any bluetooth enabled device (cell phone, laptop, etc.) but during development it would be great if I could run both on the same machine.</p>
<p>Here is my server:</p>
<pre><code>import bluetooth as bt
socket = bt.BluetoothSocket(bt.RFCOMM)
host = ""
socket.bind((host, bt.PORT_ANY))
port = socket.getsockname()[1]
print("port: " + str(port))
socket.listen(1)
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
# bt.advertise_service(socket, "BTServer", uuid)
print("Listening on " + host + ":" + str(port))
client_sock, addr = socket.accept()
print("Connection accepted from " + addr)
data = client_sock.recv(1024)
print(data)
client_sock.close()
socket.close()
</code></pre>
<p>And when I call <code>services = bt.find_service(name=None, uuid=None, address="localhost")</code> on the client it cannot find any services.</p>
| 0 | 2016-08-10T04:38:07Z | 38,886,021 | <p>Through further research I have found that it is not possible to run a bluetooth client and server on the same device with the same bluetooth adapter. For local testing you can either use two bluetooth enabled computers or get a bluetooth dongle.</p>
| 0 | 2016-08-11T01:42:27Z | [
"python",
"bluetooth",
"pybluez"
] |
Conditional cumsum based on column | 38,864,592 | <p>Given the following dataframe, how do I generate a conditional cumulative sum column.</p>
<pre><code>import pandas as pd
import numpy as np
data = {'D':[2015,2015,2015,2015,2016,2016,2016,2017,2017,2017], 'Q':np.arange(10)}
df = pd.DataFrame(data)
D Q
0 2015 0
1 2015 1
2 2015 2
3 2015 3
4 2016 4
5 2016 5
6 2016 6
7 2017 7
8 2017 8
9 2017 9
</code></pre>
<p>The cumulative sum adds the whole column. I'm trying to figure out how to use the <code>np.cumsum</code> with a conditional function.</p>
<pre><code>df['Q_cum'] = np.cumsum(df.Q)
D Q Q_cum
0 2015 0 0
1 2015 1 1
2 2015 2 3
3 2015 3 6
4 2016 4 10
5 2016 5 15
6 2016 6 21
7 2017 7 28
8 2017 8 36
9 2017 9 45
</code></pre>
<p>But I intend to create cumulative sums depending on a specific column. In this example I want it by the <code>D</code> column. Something like the following dataframe:</p>
<pre><code> D Q Q_cum
0 2015 0 0
1 2015 1 1
2 2015 2 3
3 2015 3 6
4 2016 4 4
5 2016 5 9
6 2016 6 15
7 2017 7 7
8 2017 8 15
9 2017 9 24
</code></pre>
| 1 | 2016-08-10T05:01:09Z | 38,864,639 | <pre><code>>>> df['Q_cum'] = df.groupby('D').cumsum()
>>> df
D Q Q_cum
0 2015 0 0
1 2015 1 1
2 2015 2 3
3 2015 3 6
4 2016 4 4
5 2016 5 9
6 2016 6 15
7 2017 7 7
8 2017 8 15
9 2017 9 24
</code></pre>
<p>As @Ayhan said, If you want to <code>cumsum</code> on a specific column (like Q here) <code>df.groupby('D')['Q'].cumsum()</code></p>
| 2 | 2016-08-10T05:05:40Z | [
"python",
"pandas",
"numpy"
] |
Pycharm not showing inherited fields of base class in django 1.10 | 38,864,604 | <p>I am using pycharm for my project, and I have created a core folder such that, it host all the abstract models, such that</p>
<pre><code>class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
</code></pre>
<p>When I try to import this class in other apps, Pycharm gave me an error, such that the base class attributes, such as models are not recoginzed </p>
<p><a href="http://i.stack.imgur.com/0SPka.png" rel="nofollow"><img src="http://i.stack.imgur.com/0SPka.png" alt="enter image description here"></a></p>
<p>But this is perfect valid python code. How to fix this.</p>
<p>My project structue is <a href="http://i.stack.imgur.com/KsO4F.png" rel="nofollow"><img src="http://i.stack.imgur.com/KsO4F.png" alt="enter image description here"></a></p>
| 1 | 2016-08-10T05:02:16Z | 38,875,234 | <p>Man you imported <code>TimeStampedModel</code>. But I didn't find your <code>models</code>. Where did you import? if your <code>models</code> inside <code>TimeStampedModel</code> then, import like that,</p>
<p><code>from ..core.TimeStampedModel import models</code> or</p>
<p><code>from ..core import TimeStampedModel.models as models</code></p>
<p>Feel free to write pythonic code :) </p>
| 0 | 2016-08-10T13:45:08Z | [
"python",
"django",
"pycharm"
] |
The current URL did not match any of these, include() giving problems | 38,864,608 | <p>I decided to make a <code>urls.py</code> for each app. However I am running into problems when I <code>include</code> the urls. I do not know what is the problem as I have done everything right. My site has the same structure as the Django 1.9 tutorial. I have <code>template</code> folder at the root, and also a <code>template</code> directory inside <code>myapp</code> like so <code>template\myapp\</code>. <code>home.html</code> and <code>profile.html</code> are in <code>myapp\template\myapp\</code></p>
<p>Only the urls in <code>myapp</code> are giving problems that consequently renders neither <code>home.html</code> nor <code>profile.html</code> which gives the </p>
<blockquote>
<p>Using the URLconf defined in mysite.urls, Django tried these URL
patterns, in this order:</p>
<pre><code>^$ [name='index']
^myapp/
^admin/
</code></pre>
<p>The current URL, profile, didn't match any of these.</p>
</blockquote>
<p>Error. I could get them working by writing all <code>urls</code> directly in the main site <code>mysite</code>, by importing their <code>views</code> but I rather have things more organized and let each app have their own <code>urls.py</code>. I have also registered <code>myapp</code> and placed <code>myapp</code> under <code>INSTALLED_APPS</code></p>
<p>myapp: view</p>
<pre><code>from django.shortcuts import render
def home(request):
return render(request, 'myapp/home.html')
def profile(request):
return render(request, 'myapp/profile.html')
</code></pre>
<p>myapp urls:</p>
<pre><code>from django.conf.urls import url
from .import views
app_name = 'myapp'
urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^profile/$', views.profile, name='profile'),
]
</code></pre>
<p>mysite urls:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
from .import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^myapp/', include('myapp.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
| 0 | 2016-08-10T05:02:47Z | 38,866,500 | <p>You seem to be going to just /profile, but you don't have that defined as a URL, you have /myapp/profile.</p>
| 0 | 2016-08-10T07:10:39Z | [
"python",
"django",
"django-views",
"django-urls"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The text is then displayed onto the image. I need to display the stream in realtime, and it is ok if there is a lag between the text and the video being shown (i.e. if the text was applicable to a previous frame, that's ok).</em> </p>
<p><em>Perhaps an easier way to think of this is that I'm doing image recognition on what the webcam sees. I send one frame at a time to a separate process to do recognition analysis on the frame, and send the text back to be put as a caption on the live feed. Obviously the processing takes more time than simply grabbing frames from the webcam and showing them, so if there is a delay in what the caption is and what the webcam feed shows, that's acceptable and expected.</em></p>
<p><em>What's happening now is that the live video I'm displaying is lagging due to the other processes (when I don't send frames to the process for computing, there is no lag). I've also ensured only one frame is enqueued at a time so avoid overloading the queue and causing lag. I've updated the code below to reflect this detail.</em></p>
<p>I'm using the multiprocessing module in python to help speed up my main program. However I believe I might be doing something incorrectly, as I don't think the computations are happening quite in parallel. </p>
<p>I want my program to read in images from a video stream in the main process, and pass on the frames to two child processes that do computations on them and send text back (containing the results of the computations) to the main process. </p>
<p>However, the main process seems to lag when I use multiprocessing, running about half as fast as without it, leading me to believe that the processes aren't running completely in parallel.</p>
<p>After doing some research, I surmised that the lag may have been due to communicating between the processes using a queue (passing an image from the main to the child, and passing back text from child to main).</p>
<p>However I commented out the computational step and just had the main process pass an image and the child return blank text, and in this case, the main process did not slow down at all. It ran at full speed.</p>
<p>Thus I believe that either </p>
<p>1) I am not optimally using multiprocessing </p>
<p>OR</p>
<p>2) These processes cannot truly be run in parallel (I would understand a little lag, but it's slowing the main process down in half). </p>
<p>Here's a outline of my code. There is only one consumer instead of 2, but both consumers are nearly identical. If anyone could offer guidance, I would appreciate it. </p>
<pre><code>class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
while True:
image = self.task_queue.get()
#Do computations on image
self.result_queue.put("text")
return
import cv2
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
if tasks.empty():
tasks.put(image)
else:
text = tasks.get()
#Add text to frame
cv2.putText(frame,text)
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
</code></pre>
| 12 | 2016-08-10T05:11:53Z | 38,913,757 | <p>You could try setting the affinity mask to make sure each process runs on a different core. I use this on windows 7. </p>
<pre><code>def setaffinity(mask = 128): # 128 is core 7
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetProcessAffinityMask(handle, mask)
return
</code></pre>
| -2 | 2016-08-12T08:48:26Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The text is then displayed onto the image. I need to display the stream in realtime, and it is ok if there is a lag between the text and the video being shown (i.e. if the text was applicable to a previous frame, that's ok).</em> </p>
<p><em>Perhaps an easier way to think of this is that I'm doing image recognition on what the webcam sees. I send one frame at a time to a separate process to do recognition analysis on the frame, and send the text back to be put as a caption on the live feed. Obviously the processing takes more time than simply grabbing frames from the webcam and showing them, so if there is a delay in what the caption is and what the webcam feed shows, that's acceptable and expected.</em></p>
<p><em>What's happening now is that the live video I'm displaying is lagging due to the other processes (when I don't send frames to the process for computing, there is no lag). I've also ensured only one frame is enqueued at a time so avoid overloading the queue and causing lag. I've updated the code below to reflect this detail.</em></p>
<p>I'm using the multiprocessing module in python to help speed up my main program. However I believe I might be doing something incorrectly, as I don't think the computations are happening quite in parallel. </p>
<p>I want my program to read in images from a video stream in the main process, and pass on the frames to two child processes that do computations on them and send text back (containing the results of the computations) to the main process. </p>
<p>However, the main process seems to lag when I use multiprocessing, running about half as fast as without it, leading me to believe that the processes aren't running completely in parallel.</p>
<p>After doing some research, I surmised that the lag may have been due to communicating between the processes using a queue (passing an image from the main to the child, and passing back text from child to main).</p>
<p>However I commented out the computational step and just had the main process pass an image and the child return blank text, and in this case, the main process did not slow down at all. It ran at full speed.</p>
<p>Thus I believe that either </p>
<p>1) I am not optimally using multiprocessing </p>
<p>OR</p>
<p>2) These processes cannot truly be run in parallel (I would understand a little lag, but it's slowing the main process down in half). </p>
<p>Here's a outline of my code. There is only one consumer instead of 2, but both consumers are nearly identical. If anyone could offer guidance, I would appreciate it. </p>
<pre><code>class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
while True:
image = self.task_queue.get()
#Do computations on image
self.result_queue.put("text")
return
import cv2
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
if tasks.empty():
tasks.put(image)
else:
text = tasks.get()
#Add text to frame
cv2.putText(frame,text)
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
</code></pre>
| 12 | 2016-08-10T05:11:53Z | 38,915,996 | <blockquote>
<p>I want my program to read in images from a video stream in the main process</p>
</blockquote>
<p>In producer/consumer implementations, which is what you have above, the producer, what puts tasks into the queue to be executed by the consumers, needs to be separate from the main/controlling process so that it can add tasks in parallel with the main process reading output from results queue. </p>
<p>Try the following. Have added a sleep in the consumer processes to simulate processing and added a second consumer to show they are being run in parallel.</p>
<p>It would also be a good idea to limit the size of the task queue to avoid having it run away with memory usage if processing cannot keep up with input stream. Can specify a size when calling <code>Queue(<size>)</code>. If the queue is at that size, calls to <code>.put</code> will block until the queue is not full.</p>
<pre><code>import time
import multiprocessing
import cv2
class ImageProcessor(multiprocessing.Process):
def __init__(self, tasks_q, results_q):
multiprocessing.Process.__init__(self)
self.tasks_q = tasks_q
self.results_q = results_q
def run(self):
while True:
image = self.tasks_q.get()
# Do computations on image
time.sleep(1)
# Display the result on stream
self.results_q.put("text")
# Tasks queue with size 1 - only want one image queued
# for processing.
# Queue size should therefore match number of processes
tasks_q, results_q = multiprocessing.Queue(1), multiprocessing.Queue()
processor = ImageProcessor(tasks_q, results_q)
processor.start()
def capture_display_video(vc):
rval, frame = vc.read()
while rval:
image = frame.get_image()
if not tasks_q.full():
tasks_q.put(image)
if not results_q.empty():
text = results_q.get()
cv2.putText(frame, text)
cv2.imshow("preview", frame)
rval, frame = vc.read()
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if not vc.isOpened():
raise Exception("Cannot capture video")
capture_display_video(vc)
processor.terminate()
</code></pre>
| 7 | 2016-08-12T10:40:54Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The text is then displayed onto the image. I need to display the stream in realtime, and it is ok if there is a lag between the text and the video being shown (i.e. if the text was applicable to a previous frame, that's ok).</em> </p>
<p><em>Perhaps an easier way to think of this is that I'm doing image recognition on what the webcam sees. I send one frame at a time to a separate process to do recognition analysis on the frame, and send the text back to be put as a caption on the live feed. Obviously the processing takes more time than simply grabbing frames from the webcam and showing them, so if there is a delay in what the caption is and what the webcam feed shows, that's acceptable and expected.</em></p>
<p><em>What's happening now is that the live video I'm displaying is lagging due to the other processes (when I don't send frames to the process for computing, there is no lag). I've also ensured only one frame is enqueued at a time so avoid overloading the queue and causing lag. I've updated the code below to reflect this detail.</em></p>
<p>I'm using the multiprocessing module in python to help speed up my main program. However I believe I might be doing something incorrectly, as I don't think the computations are happening quite in parallel. </p>
<p>I want my program to read in images from a video stream in the main process, and pass on the frames to two child processes that do computations on them and send text back (containing the results of the computations) to the main process. </p>
<p>However, the main process seems to lag when I use multiprocessing, running about half as fast as without it, leading me to believe that the processes aren't running completely in parallel.</p>
<p>After doing some research, I surmised that the lag may have been due to communicating between the processes using a queue (passing an image from the main to the child, and passing back text from child to main).</p>
<p>However I commented out the computational step and just had the main process pass an image and the child return blank text, and in this case, the main process did not slow down at all. It ran at full speed.</p>
<p>Thus I believe that either </p>
<p>1) I am not optimally using multiprocessing </p>
<p>OR</p>
<p>2) These processes cannot truly be run in parallel (I would understand a little lag, but it's slowing the main process down in half). </p>
<p>Here's a outline of my code. There is only one consumer instead of 2, but both consumers are nearly identical. If anyone could offer guidance, I would appreciate it. </p>
<pre><code>class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
while True:
image = self.task_queue.get()
#Do computations on image
self.result_queue.put("text")
return
import cv2
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
if tasks.empty():
tasks.put(image)
else:
text = tasks.get()
#Add text to frame
cv2.putText(frame,text)
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
</code></pre>
| 12 | 2016-08-10T05:11:53Z | 38,953,909 | <p>(Updated solution based on you last code sample)</p>
<p>It will get images from the stream, put one in the task queue as soon as it is available, and display the last image with the last text.</p>
<p>I put some active loop in there to simulate a processing longer than the time between two images.
I means that the text displayed is not necessarily the one belonging to the image, but the last one computed.
If the processing is fast enough, the shift between image and text should be limited.</p>
<p>Note that I force calls to get/put with some try/catch. Per the doc, empty and full are not 100% accurate.</p>
<pre><code>import cv2
import multiprocessing
import random
from time import sleep
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
# Other initialization stuff
def run(self):
while True:
frameNum, frameData = self.task_queue.get()
# Do computations on image
# Simulate a processing longer than image fetching
m = random.randint(0, 1000000)
while m >= 0:
m -= 1
# Put result in queue
self.result_queue.put("result from image " + str(frameNum))
return
# No more than one pending task
tasks = multiprocessing.Queue(1)
results = multiprocessing.Queue()
# Init and start consumer
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
else:
rval = False
# Dummy int to represent frame number for display
frameNum = 0
# String for result
text = None
font = cv2.FONT_HERSHEY_SIMPLEX
# Process loop
while rval:
# Grab image from stream
frameNum += 1
# Put image in task queue if empty
try:
tasks.put_nowait((frameNum, frame))
except:
pass
# Get result if ready
try:
# Use this if processing is fast enough
# text = results.get(timeout=0.4)
# Use this to prefer smooth display over frame/text shift
text = results.get_nowait()
except:
pass
# Add last available text to last image and display
print("display:", frameNum, "|", text)
# Showing the frame with all the applied modifications
cv2.putText(frame,text,(10,25), font, 1,(255,0,0),2)
cv2.imshow("preview", frame)
# Getting next frame from camera
rval, frame = vc.read()
# Optional image resize
# frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
</code></pre>
<p>Here is some output, you can see the delay between image and result, and the result catching back.</p>
<pre><code>> ('display:', 493, '|', 'result from image 483')
> ('display:', 494, '|', 'result from image 483')
> ('display:', 495, '|', 'result from image 489')
> ('display:', 496, '|', 'result from image 490')
> ('display:', 497, '|', 'result from image 495')
> ('display:', 498, '|', 'result from image 496')
</code></pre>
| 2 | 2016-08-15T11:06:20Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The text is then displayed onto the image. I need to display the stream in realtime, and it is ok if there is a lag between the text and the video being shown (i.e. if the text was applicable to a previous frame, that's ok).</em> </p>
<p><em>Perhaps an easier way to think of this is that I'm doing image recognition on what the webcam sees. I send one frame at a time to a separate process to do recognition analysis on the frame, and send the text back to be put as a caption on the live feed. Obviously the processing takes more time than simply grabbing frames from the webcam and showing them, so if there is a delay in what the caption is and what the webcam feed shows, that's acceptable and expected.</em></p>
<p><em>What's happening now is that the live video I'm displaying is lagging due to the other processes (when I don't send frames to the process for computing, there is no lag). I've also ensured only one frame is enqueued at a time so avoid overloading the queue and causing lag. I've updated the code below to reflect this detail.</em></p>
<p>I'm using the multiprocessing module in python to help speed up my main program. However I believe I might be doing something incorrectly, as I don't think the computations are happening quite in parallel. </p>
<p>I want my program to read in images from a video stream in the main process, and pass on the frames to two child processes that do computations on them and send text back (containing the results of the computations) to the main process. </p>
<p>However, the main process seems to lag when I use multiprocessing, running about half as fast as without it, leading me to believe that the processes aren't running completely in parallel.</p>
<p>After doing some research, I surmised that the lag may have been due to communicating between the processes using a queue (passing an image from the main to the child, and passing back text from child to main).</p>
<p>However I commented out the computational step and just had the main process pass an image and the child return blank text, and in this case, the main process did not slow down at all. It ran at full speed.</p>
<p>Thus I believe that either </p>
<p>1) I am not optimally using multiprocessing </p>
<p>OR</p>
<p>2) These processes cannot truly be run in parallel (I would understand a little lag, but it's slowing the main process down in half). </p>
<p>Here's a outline of my code. There is only one consumer instead of 2, but both consumers are nearly identical. If anyone could offer guidance, I would appreciate it. </p>
<pre><code>class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
while True:
image = self.task_queue.get()
#Do computations on image
self.result_queue.put("text")
return
import cv2
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
if tasks.empty():
tasks.put(image)
else:
text = tasks.get()
#Add text to frame
cv2.putText(frame,text)
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
</code></pre>
| 12 | 2016-08-10T05:11:53Z | 38,963,942 | <p>Let me suggest you a slightly different approach, with a lot less "red tape". I think the main problem is that you are overlooking the main way to communicate with a process: it is through its arguments and return values. If you can send the frame data as an argument, there is no need of queues or pipes or other methods.</p>
<pre><code>import time
from multiprocessing import Pool
def process_frame(frame_id, frame_data):
# this function simulates the processing of the frame.
# I used a longer sleep thinking that it takes longer
# and therefore the reason of parallel processing.
print("..... got frame {}".format(frame_id))
time.sleep(.5)
char = frame_data[frame_id]
count = frame_data.count(char)
return frame_id, char, count
def process_result(res):
# this function simulates the function that would receive
# the result from analyzing the frame, and do what is
# appropriate, like printing, making a dict, saving to file, etc.
# this function is called back when the result is ready.
frame_id, char, count = res
print("in frame {}".format(frame_id), \
", character '{}' appears {} times.".format(
chr(char), count))
if __name__ == '__main__':
pool = Pool(4)
# in my laptop I got these times:
# workers, time
# 1 10.14
# 2 5.22
# 4 2.91
# 8 2.61 # no further improvement after 4 workers.
# your case may be different though.
from datetime import datetime as dt
t0 = dt.now()
for i in range(20): # I limited this loop to simulate 20 frames
# but it could be a continuous stream,
# that when finishes should execute the
# close() and join() methods to finish
# gathering all the results.
# The following lines simulate the video streaming and
# your selecting the frames that you need to analyze and
# send to the function process_frame.
time.sleep(0.1)
frame_id = i
frame_data = b'a bunch of binary data representing your frame'
pool.apply_async( process_frame, #func
(frame_id, frame_data), #args
callback=process_result #return value
)
pool.close()
pool.join()
print(dt.now() - t0)
</code></pre>
<p>I think that this simpler approach would be enough for your program. No need of using classes or queues.</p>
| 1 | 2016-08-15T22:23:59Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The text is then displayed onto the image. I need to display the stream in realtime, and it is ok if there is a lag between the text and the video being shown (i.e. if the text was applicable to a previous frame, that's ok).</em> </p>
<p><em>Perhaps an easier way to think of this is that I'm doing image recognition on what the webcam sees. I send one frame at a time to a separate process to do recognition analysis on the frame, and send the text back to be put as a caption on the live feed. Obviously the processing takes more time than simply grabbing frames from the webcam and showing them, so if there is a delay in what the caption is and what the webcam feed shows, that's acceptable and expected.</em></p>
<p><em>What's happening now is that the live video I'm displaying is lagging due to the other processes (when I don't send frames to the process for computing, there is no lag). I've also ensured only one frame is enqueued at a time so avoid overloading the queue and causing lag. I've updated the code below to reflect this detail.</em></p>
<p>I'm using the multiprocessing module in python to help speed up my main program. However I believe I might be doing something incorrectly, as I don't think the computations are happening quite in parallel. </p>
<p>I want my program to read in images from a video stream in the main process, and pass on the frames to two child processes that do computations on them and send text back (containing the results of the computations) to the main process. </p>
<p>However, the main process seems to lag when I use multiprocessing, running about half as fast as without it, leading me to believe that the processes aren't running completely in parallel.</p>
<p>After doing some research, I surmised that the lag may have been due to communicating between the processes using a queue (passing an image from the main to the child, and passing back text from child to main).</p>
<p>However I commented out the computational step and just had the main process pass an image and the child return blank text, and in this case, the main process did not slow down at all. It ran at full speed.</p>
<p>Thus I believe that either </p>
<p>1) I am not optimally using multiprocessing </p>
<p>OR</p>
<p>2) These processes cannot truly be run in parallel (I would understand a little lag, but it's slowing the main process down in half). </p>
<p>Here's a outline of my code. There is only one consumer instead of 2, but both consumers are nearly identical. If anyone could offer guidance, I would appreciate it. </p>
<pre><code>class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
while True:
image = self.task_queue.get()
#Do computations on image
self.result_queue.put("text")
return
import cv2
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
if tasks.empty():
tasks.put(image)
else:
text = tasks.get()
#Add text to frame
cv2.putText(frame,text)
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
</code></pre>
| 12 | 2016-08-10T05:11:53Z | 38,985,343 | <p>After reading your comment to my previous answer, I understood your problem a 'bit' better. I would like to have more information about your code/problem. Anyway, and because this code is significantly different than my previous answer, I decided to provide another answer. I won't comment the code too much though, because you can follow it from my previous answer. I will use text instead of images, just to simulate the process.</p>
<p>The following code prints a letter out of "lorem ipsum", selecting one out of 6 letters (frames). Because there is a lag, we need a buffer that I implemented with a deque. After the buffer has advanced, the displaying of the frame and caption are in sync.</p>
<p>I don't know how often you tag a frame, or how much it really takes to process it, but you can have an educated guess with this code by playing with some of the variables.</p>
<pre><code>import time
import random
random.seed(1250)
from multiprocessing import Pool, Manager
from collections import deque
def display_stream(stream, pool, queue, buff, buffered=False):
delay = 24
popped_frames = 0
for i, frame in enumerate(stream):
buff.append([chr(frame), ''])
time.sleep(1/24 * random.random()) # suppose a 24 fps video
if i % 6 == 0: # suppose one out of 6 frames
pool.apply_async(process_frame, (i, frame, queue))
ii, caption = (None, '') if queue.empty() else queue.get()
if buffered:
if ii is not None:
buff[ii - popped_frames][1] = caption
if i > delay:
print(buff.popleft())
popped_frames += 1
else:
lag = '' if ii is None else i - ii
print(chr(frame), caption, lag)
else:
pool.close()
pool.join()
if buffered:
try:
while True:
print(buff.popleft())
except IndexError:
pass
def process_frame(i, frame, queue):
time.sleep(0.4 * random.random()) # suppose ~0.2s to process
caption = chr(frame).upper() # mocking the result...
queue.put((i, caption))
if __name__ == '__main__':
p = Pool()
q = Manager().Queue()
d = deque()
stream = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
display_stream(stream, p, q, b)
</code></pre>
| 1 | 2016-08-16T22:16:22Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The text is then displayed onto the image. I need to display the stream in realtime, and it is ok if there is a lag between the text and the video being shown (i.e. if the text was applicable to a previous frame, that's ok).</em> </p>
<p><em>Perhaps an easier way to think of this is that I'm doing image recognition on what the webcam sees. I send one frame at a time to a separate process to do recognition analysis on the frame, and send the text back to be put as a caption on the live feed. Obviously the processing takes more time than simply grabbing frames from the webcam and showing them, so if there is a delay in what the caption is and what the webcam feed shows, that's acceptable and expected.</em></p>
<p><em>What's happening now is that the live video I'm displaying is lagging due to the other processes (when I don't send frames to the process for computing, there is no lag). I've also ensured only one frame is enqueued at a time so avoid overloading the queue and causing lag. I've updated the code below to reflect this detail.</em></p>
<p>I'm using the multiprocessing module in python to help speed up my main program. However I believe I might be doing something incorrectly, as I don't think the computations are happening quite in parallel. </p>
<p>I want my program to read in images from a video stream in the main process, and pass on the frames to two child processes that do computations on them and send text back (containing the results of the computations) to the main process. </p>
<p>However, the main process seems to lag when I use multiprocessing, running about half as fast as without it, leading me to believe that the processes aren't running completely in parallel.</p>
<p>After doing some research, I surmised that the lag may have been due to communicating between the processes using a queue (passing an image from the main to the child, and passing back text from child to main).</p>
<p>However I commented out the computational step and just had the main process pass an image and the child return blank text, and in this case, the main process did not slow down at all. It ran at full speed.</p>
<p>Thus I believe that either </p>
<p>1) I am not optimally using multiprocessing </p>
<p>OR</p>
<p>2) These processes cannot truly be run in parallel (I would understand a little lag, but it's slowing the main process down in half). </p>
<p>Here's a outline of my code. There is only one consumer instead of 2, but both consumers are nearly identical. If anyone could offer guidance, I would appreciate it. </p>
<pre><code>class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
#other initialization stuff
def run(self):
while True:
image = self.task_queue.get()
#Do computations on image
self.result_queue.put("text")
return
import cv2
tasks = multiprocessing.Queue()
results = multiprocessing.Queue()
consumer = Consumer(tasks,results)
consumer.start()
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
if tasks.empty():
tasks.put(image)
else:
text = tasks.get()
#Add text to frame
cv2.putText(frame,text)
#Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
#Getting next frame from camera
rval, frame = vc.read()
</code></pre>
| 12 | 2016-08-10T05:11:53Z | 39,001,345 | <p>Here's a more elegant (IMHO) solution that utilizes multiple processes for processing your frames:</p>
<pre><code>def process_image(args):
image, frame = args
#Do computations on image
return "text", frame
import cv2
pool = multiprocessing.Pool()
def image_source():
#Creating window and starting video capturer from camera
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
#Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
yield image, frame
# Getting next frame from camera
rval, frame = vc.read()
for (text, frame) in pool.imap(process_image, image_source()):
# Add text to frame
cv2.putText(frame, text)
# Showing the frame with all the applied modifications
cv2.imshow("preview", frame)
</code></pre>
<p><code>Pool.imap</code> should allow you to iterate through the pool's results while it's still processing other images from your cam.</p>
| 2 | 2016-08-17T15:59:37Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
Python Tkinter StringVar only displaying Py_Var(number) | 38,864,986 | <p>I am using Tkinter in python 3.4 to make a text based game, and I cannot figure out how to get a string from an Entry widget, it just returns <code>Py_Var#</code>, # being a number. I have looked at answers to similar questions, but none of them quite line up with what I need and have. Here's the relevant pieces of code:</p>
<pre><code>from tkinter import *
win = Tk()
win.geometry("787x600")
playername = StringVar()
def SubmitName():
playername.get
#messagebox.showinfo("Success", playername)
print(playername)
frame3 = Frame(win)
frame3.pack()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")
label2 = Label(frame3, text="First, how about you give yourself a name:")
label1.config(font=("Courier", 11))
label2.config(font=("Courier", 11))
entry1 = Entry(frame3, textvariable=playername)
entry1.config(font=("Courier", 11))
label1.grid(row=0, column=0, columnspan=3)
label2.grid(row=1, column=0)
entry1.grid(row=1, column=1)
bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName())
bnamesub.grid()
win.mainloop()
</code></pre>
<p>Thanks! </p>
<p>Also, first time using stackoverflow and its reading weird but w/e.</p>
| 0 | 2016-08-10T05:34:42Z | 38,865,088 | <p>You have two mistakes in <code>SubmitName()</code>.</p>
<p>First, you need to get the text like this:</p>
<pre><code>txt = playername.get()
</code></pre>
<p>Then you need to print that <code>txt</code>:</p>
<pre><code>print(txt)
</code></pre>
<p>By mistake you printed the <code>StringVar</code> variable itself.</p>
| 2 | 2016-08-10T05:42:52Z | [
"python",
"tkinter",
"entry"
] |
Python Tkinter StringVar only displaying Py_Var(number) | 38,864,986 | <p>I am using Tkinter in python 3.4 to make a text based game, and I cannot figure out how to get a string from an Entry widget, it just returns <code>Py_Var#</code>, # being a number. I have looked at answers to similar questions, but none of them quite line up with what I need and have. Here's the relevant pieces of code:</p>
<pre><code>from tkinter import *
win = Tk()
win.geometry("787x600")
playername = StringVar()
def SubmitName():
playername.get
#messagebox.showinfo("Success", playername)
print(playername)
frame3 = Frame(win)
frame3.pack()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")
label2 = Label(frame3, text="First, how about you give yourself a name:")
label1.config(font=("Courier", 11))
label2.config(font=("Courier", 11))
entry1 = Entry(frame3, textvariable=playername)
entry1.config(font=("Courier", 11))
label1.grid(row=0, column=0, columnspan=3)
label2.grid(row=1, column=0)
entry1.grid(row=1, column=1)
bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName())
bnamesub.grid()
win.mainloop()
</code></pre>
<p>Thanks! </p>
<p>Also, first time using stackoverflow and its reading weird but w/e.</p>
| 0 | 2016-08-10T05:34:42Z | 38,865,346 | <pre><code>from tkinter import *
import pickle
win = Tk()
win.geometry("787x600")
def SubmitName():
playername = entry1.get()
messagebox.showinfo("Success", playername)
print(playername)
frame3 = Frame(win)
frame3.grid()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")
label2 = Label(frame3, text="First, how about you give yourself a name:")
label1.config(font=("Courier", 11))
label2.config(font=("Courier", 11))
#name entered is a StringVar, returns as Py_Var7, but I need it to return the name typed into entry1.
entry1 = Entry(frame3)
entry1.config(font=("Courier", 11))
label1.grid(row=0, column=0, columnspan=3)
label2.grid(row=1, column=0)
entry1.grid(row=1, column=1)
bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName())
bnamesub.grid()
</code></pre>
<p><b>What I changed:</b><br>
-deleted <code>playername = StringVar()</code>. We don't really need it;<br>
-changed inside the function: changed <code>playername.get</code> to <code>playername = entry1.get()</code>;<br>
-added <code>frame3.grid()</code> (without geometry managment, widgets cannot be shown on the screen.);<br>
-also, a little edit: in Python, comments are created with <code>#</code> sign. So I changed <code>*</code> to <code>#</code>.</p>
| 0 | 2016-08-10T06:00:54Z | [
"python",
"tkinter",
"entry"
] |
Is `await` in Python3 Cooperative Multitasking? | 38,865,050 | <p>I am trying to understand the new <a href="https://docs.python.org/3/library/asyncio-task.html#example-chain-coroutines" rel="nofollow">await</a> coroutines (introduced in Python 3.5). </p>
<p>In 1997 I attended a course at university which roughly covered the content of the book <a href="https://en.wikipedia.org/wiki/Modern_Operating_Systems" rel="nofollow">Modern Operating Systems</a> by Andrew Tanenbaum.</p>
<p>Somehow the <code>await</code> in Python3 reminds me at <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking" rel="nofollow">Cooperative Multitasking</a>.</p>
<p>From Wikipedia:</p>
<blockquote>
<p>Cooperative multitasking, also known as non-preemptive multitasking, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, processes voluntarily yield control periodically or when idle in order to enable multiple applications to be run simultaneously. This type of multitasking is called "cooperative" because all programs must cooperate for the entire scheduling scheme to work. </p>
</blockquote>
<p>If you look at the Python interpreter like an operating system, does the term "Cooperative Multitasking" apply to <code>await</code>?</p>
<p>But may be I am missing something. </p>
| 2 | 2016-08-10T05:39:52Z | 38,865,200 | <blockquote>
<p>Inside a coroutine function, the await expression can be used to
suspend coroutine execution until the result is available. Any object
can be awaited, as long as it implements the awaitable protocol by
defining the <strong>await</strong>() method.</p>
</blockquote>
<p>A coroutine can pause execution using the await keyword with another coroutine. While it is paused, the coroutineâs state is maintained, allowing it to resume where it left off the next time it is awakened. <em>That sounds quite like Cooperative multitasking to me</em>. See this <a href="https://pymotw.com/3/asyncio/coroutines.html" rel="nofollow">example</a></p>
| 2 | 2016-08-10T05:50:06Z | [
"python",
"asynchronous",
"async-await",
"python-asyncio"
] |
Is `await` in Python3 Cooperative Multitasking? | 38,865,050 | <p>I am trying to understand the new <a href="https://docs.python.org/3/library/asyncio-task.html#example-chain-coroutines" rel="nofollow">await</a> coroutines (introduced in Python 3.5). </p>
<p>In 1997 I attended a course at university which roughly covered the content of the book <a href="https://en.wikipedia.org/wiki/Modern_Operating_Systems" rel="nofollow">Modern Operating Systems</a> by Andrew Tanenbaum.</p>
<p>Somehow the <code>await</code> in Python3 reminds me at <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking" rel="nofollow">Cooperative Multitasking</a>.</p>
<p>From Wikipedia:</p>
<blockquote>
<p>Cooperative multitasking, also known as non-preemptive multitasking, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, processes voluntarily yield control periodically or when idle in order to enable multiple applications to be run simultaneously. This type of multitasking is called "cooperative" because all programs must cooperate for the entire scheduling scheme to work. </p>
</blockquote>
<p>If you look at the Python interpreter like an operating system, does the term "Cooperative Multitasking" apply to <code>await</code>?</p>
<p>But may be I am missing something. </p>
| 2 | 2016-08-10T05:39:52Z | 38,953,375 | <p>Yes. According to <a href="https://en.wikipedia.org/wiki/Coroutine" rel="nofollow">Wikipedia</a>: </p>
<blockquote>
<p>Coroutines are computer program components that generalize subroutines for <strong>nonpreemptive multitasking</strong>, by allowing multiple entry points for suspending and resuming execution at certain locations.</p>
</blockquote>
| 0 | 2016-08-15T10:26:55Z | [
"python",
"asynchronous",
"async-await",
"python-asyncio"
] |
Is `await` in Python3 Cooperative Multitasking? | 38,865,050 | <p>I am trying to understand the new <a href="https://docs.python.org/3/library/asyncio-task.html#example-chain-coroutines" rel="nofollow">await</a> coroutines (introduced in Python 3.5). </p>
<p>In 1997 I attended a course at university which roughly covered the content of the book <a href="https://en.wikipedia.org/wiki/Modern_Operating_Systems" rel="nofollow">Modern Operating Systems</a> by Andrew Tanenbaum.</p>
<p>Somehow the <code>await</code> in Python3 reminds me at <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking" rel="nofollow">Cooperative Multitasking</a>.</p>
<p>From Wikipedia:</p>
<blockquote>
<p>Cooperative multitasking, also known as non-preemptive multitasking, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, processes voluntarily yield control periodically or when idle in order to enable multiple applications to be run simultaneously. This type of multitasking is called "cooperative" because all programs must cooperate for the entire scheduling scheme to work. </p>
</blockquote>
<p>If you look at the Python interpreter like an operating system, does the term "Cooperative Multitasking" apply to <code>await</code>?</p>
<p>But may be I am missing something. </p>
| 2 | 2016-08-10T05:39:52Z | 39,024,906 | <p>It is cooperative multitasking indeed.</p>
<p>What about a small program to prove it. Let's first sleep with cooperative <code>asyncio.sleep</code> for a second and then let's sleep with blocking <code>time.sleep</code> for a second. Let's print a thread id, time spent in the coroutine and id of a task.</p>
<pre><code>import threading
import asyncio
import time
async def async_function(i):
started = time.time()
print("Id:", i, "ThreadId:", threading.get_ident())
await asyncio.sleep(1)
time.sleep(1)
print("Id:", i, "ThreadId:", threading.get_ident(), "Time:", time.time() - started)
async def async_main():
await asyncio.gather(
async_function(1),
async_function(2),
async_function(3)
)
loop = asyncio.get_event_loop()
loop.run_until_complete(async_main())
</code></pre>
<p>Now let's try and see:</p>
<pre><code>Id: 3 ThreadId: 140027884312320
Id: 2 ThreadId: 140027884312320
Id: 1 ThreadId: 140027884312320
Id: 3 ThreadId: 140027884312320 Time: 2.002575397491455
Id: 2 ThreadId: 140027884312320 Time: 3.0038201808929443
Id: 1 ThreadId: 140027884312320 Time: 4.00504469871521
</code></pre>
<p>As expected. Execution was only in one thread. <code>asyncio.sleep(1)</code> is nonblocking, so it took 1 second to process all of them concurrently. <code>time.sleep(1)</code> is blocking (it does not cooperate), so it blocks the rest. Id <code>1</code> waits for id <code>2</code> to finish while id <code>2</code> waits for id <code>3</code> to finish.</p>
<h1>C# has async/await too, does it have cooperative multitasking as well?</h1>
<p>Let's try the same thing in C#:</p>
<pre><code>using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class MainClass {
private static async Task AsyncMethod(int id) {
var started = DateTime.Now;
Console.WriteLine("Id: {0} ThreadId: {1}", id, Thread.CurrentThread.ManagedThreadId);
await Task.Delay(1000);
Thread.Sleep(1000);
Console.WriteLine("Id: {0} ThreadId: {1} Time: {2}", id, Thread.CurrentThread.ManagedThreadId, DateTime.Now - started);
}
private static async Task MainAsync()
{
await Task.WhenAll(AsyncMethod(1), AsyncMethod(2), AsyncMethod(3));
}
public static void Main (string[] args) {
MainAsync().Wait();
}
}
}
</code></pre>
<p>Run it and...</p>
<pre><code>Id: 1 ThreadId: 1
Id: 2 ThreadId: 1
Id: 3 ThreadId: 1
Id: 2 ThreadId: 7 Time: 00:00:02.0147000
Id: 3 ThreadId: 8 Time: 00:00:02.0144560
Id: 1 ThreadId: 6 Time: 00:00:02.0878160
</code></pre>
<p>Damn. The threads are different after await. And it tooks just 2 seconds for each of the coroutine! What's wrong?</p>
<p>Nothing is wrong. <strong>Unlike Python, async/await in C# has a combination of cooperative multitasking and multithreading.</strong> <code>Task.Delay(1000)</code> is indeed nonblocking but when a coroutine resumes, it can resume in a totally different thread as it did in the example. Since the coroutines continued in three different threads, <code>Thread.Sleep(1000)</code> blocked them in parallel.</p>
<p>Note there are more things in C# which can influence this behavior (like SynchronizationContext), but this is a different topic.</p>
| 1 | 2016-08-18T18:13:46Z | [
"python",
"asynchronous",
"async-await",
"python-asyncio"
] |
Exiting interactive python3 session from script | 38,865,080 | <p>I'd like my program to automatically exit if it detects an error when loading a file and parsing it (even when called from an interactive mode with -i). I've tried variations of <code>exit()</code> and <code>sys.exit()</code>, but nothing seems to be working. Instead of exiting the interactive session I get a stack trace. For example, if I have the file <code>test.py</code> that is the following:</p>
<pre><code>import sys
sys.exit(0)
</code></pre>
<p>when I run <code>python3 -i test.py</code> I get the following result:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 2, in <module>
sys.exit()
SystemExit
>>>
</code></pre>
<p>and the session continues on, until I exit myself (using those exact lines subsequently work, just not when they're called from the script). What am I missing?</p>
| 1 | 2016-08-10T05:42:08Z | 38,866,028 | <p>Try calling <a href="https://docs.python.org/2/library/os.html#os._exit" rel="nofollow">os._exit()</a> to exit directly, without throwing an exception</p>
<pre><code>import os
os._exit(1)
</code></pre>
<p>Note that this will bypass all of the python shutdown logic.
Hope it helps.</p>
| 2 | 2016-08-10T06:41:54Z | [
"python"
] |
Python - getting the average of two dict lists? | 38,865,129 | <p>Here I have two lists: "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I used two "dict"'s: "totals" to calculate the total donation per charity, and "numdon" to calculate the number of donations per charity. I now have to find the average donation per charity. I tried dividing "totals" by "numdon", but the output is just a list of "1.0"'s. I think it's because the dict has the charity number as well as the total/number of donations in them. Please help me calculate the average donation per charity. Thank you!</p>
<pre><code>from __future__ import division
import random
from collections import defaultdict
from pprint import pprint
counter = 0
donlist = []
charlist = []
totals = defaultdict(lambda:0)
numdon = defaultdict(lambda:0)
while counter != 100:
d = round(random.uniform(1.00,100.00),2)
c = random.randint(1,15)
counter +=1
donlist.append(d)
donlist = [round(elem,2) for elem in donlist]
charlist.append(c)
totals[c] += d
numdon[c] += 1
if counter == 100:
break
print('Charity \t\tDonations')
for (c,d) in zip(charlist,donlist):
print(c,d,sep='\t\t\t')
print("\nTotal Donations per Charity:")
pprint(totals)
print("\nNumber of Donations per Charity:")
pprint(numdon)
# The average array doesn't work; I think it's because the "totals" and "numdon" have the charity numbers in them, so it's not just two lists of floats to divide.
avg = [x/y for x,y in zip(totals,numdon)]
pprint(avg)
</code></pre>
| 0 | 2016-08-10T05:45:39Z | 38,865,380 | <p>Solve your problem:</p>
<pre><code>avg = [totals[i] / numdon[i] for i in numdon]
</code></pre>
<p><strong>Reason</strong>:</p>
<p>In python list comprehension of a dict, the default iteration will be on the key of a dict. Try this:</p>
<pre><code>l = {1: 'a', 2: 'b'}
for i in l:
print(i)
# output:
# 1
# 2
</code></pre>
| 3 | 2016-08-10T06:02:53Z | [
"python",
"arrays",
"dictionary",
"random"
] |
How to automate "pull-request creation" on GitHub? | 38,865,157 | <p>I have forked a rep from my organization's repo. </p>
<p>I am updating some files on regular basis and pushing changes to my forked repo.</p>
<p>Lets say: My organization repo URL is : X and my forked repo URL: Y</p>
<p>I know we can use "git pull-request" but I am not getting what exactly the command should be.</p>
<p>If anyone knows this then that would be of great help to me.</p>
| 0 | 2016-08-10T05:47:26Z | 38,867,178 | <p><code>git request-pull [-p] <start> <url> [<end>]</code></p>
<p><a href="https://git-scm.com/docs/git-request-pull" rel="nofollow">https://git-scm.com/docs/git-request-pull</a></p>
| 0 | 2016-08-10T07:45:35Z | [
"java",
"python",
"git",
"github",
"version-control"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.