title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Pandas plot mean values from corresponding unique id values
40,065,762
<p>This is my csv file. I want to find the mean cost for each unique ids. </p> <p>so for example: id 1, mean cost should be 20.</p> <pre><code>id,cost 1,10 1,20 1,30 2,40 2,50 </code></pre> <p>I got the output right with:</p> <pre><code>df.groupby(['id'])['cost'].mean() id 1 20 2 45 Name: cost, dtype: int64 ...
2
2016-10-16T00:53:29Z
40,066,139
<p>Piggybacking off of Psidom's comment...</p> <pre><code>df.groupby('id').mean().plot(kind='bar') </code></pre> <p><a href="https://i.stack.imgur.com/Kga1c.png" rel="nofollow"><img src="https://i.stack.imgur.com/Kga1c.png" alt="enter image description here"></a></p> <hr> <pre><code>In [108]: df Out[108]: id c...
1
2016-10-16T02:13:25Z
[ "python", "pandas", "matplotlib", "plot" ]
Using tweepy to follow people tweeting a specific hashtag
40,065,791
<p>This is one of my first python projects and I'm using Tweepy to trying to search for a specific hashtag and follow those people tweeting that hashtag. I don't understand why this doesn't work and I've tried to append followers to list but nothing either. I've read the tweepy docs and this is what I've come up wit...
0
2016-10-16T01:00:14Z
40,134,236
<p>Want you are getting in your loop, the variable <code>follower</code>, is a <code>user</code> object with a huge lot of information about the user, and not just a name as you seem to believe. To get the screen name of a <code>user</code> object, use <code>follower.screen_name</code>:</p> <pre><code>api.create_frien...
0
2016-10-19T14:26:24Z
[ "python", "for-loop", "tweepy" ]
Check if common letters are at the same position in two strings in Python?
40,065,821
<p>I am trying to write a program that checks two strings and prints the number of common characters that are at the same position in both of the strings so if it checked, say:</p> <ol> <li><p>the words <code>'hello'</code> and <code>'heron'</code> it would output <code>2</code> because there are two common letters at...
-1
2016-10-16T01:07:18Z
40,065,841
<p>You can use <code>zip()</code> to iterate through both of them simultaneously:</p> <pre><code>sum(1 if c1 == c2 else 0 for c1, c2 in zip(string1, string2)) </code></pre> <p>or even (using implicit integer values for <code>True</code> and <code>False</code>):</p> <pre><code>sum(c1 == c2 for c1, c2 in zip(string1, ...
5
2016-10-16T01:10:20Z
[ "python" ]
Is there an easy way to install opencv 3 on mac through anaconda?
40,065,851
<p>Is there an easy way to install opencv 3 on mac through anaconda?</p> <p>Thanks in advance!</p>
0
2016-10-16T01:13:34Z
40,065,885
<p>No there is no easy way to install it but here is a website that could help you a little bit. <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/</a></p>
0
2016-10-16T01:20:34Z
[ "python", "osx", "opencv", "anaconda" ]
Is there an easy way to install opencv 3 on mac through anaconda?
40,065,851
<p>Is there an easy way to install opencv 3 on mac through anaconda?</p> <p>Thanks in advance!</p>
0
2016-10-16T01:13:34Z
40,066,141
<p>If you used Python 2.7, you just copy the .pyd file from OpenCV installation folder. If you used Python 3, check these out:</p> <p><a href="http://www.pyimagesearch.com/2015/06/29/install-opencv-3-0-and-python-3-4-on-osx/" rel="nofollow">Install OpenCV 3.0 and Python 3.4+ on OSX</a></p> <p>or</p> <p><a href="http...
0
2016-10-16T02:14:10Z
[ "python", "osx", "opencv", "anaconda" ]
Disable tree view from filling the window after update
40,065,896
<p>I have very simple grid layout with two columns, where first column should display some text, and the second to show tree view:</p> <pre><code>#! python3 from random import randint import tkinter as tk from tkinter import ttk from tkinter.constants import * class Application(ttk.Frame): def __init__(self, r...
0
2016-10-16T01:22:13Z
40,090,484
<p>The treeview will grow to fit all of its columns, unless constrained by the window. The window will grow to fit all of it children unless you give it a fixed size. What is happening is that you're giving the treeview many columns, causing it to grow. Because it grows, the window grows because you haven't constraint ...
1
2016-10-17T15:38:25Z
[ "python", "tkinter", "ttk" ]
Python flask webpage single item page for multiple item
40,065,959
<p>I am doing a flask website project and im trying to get create an individual item page for each of my items. Im using sqlite for the database.</p> <p>Below is the html code for my homepage:</p> <pre><code>{% extends "base-template.html" %} {% block content %} &lt;h1&gt;Valves&lt;/h1&gt; &lt;form action="/product-...
-1
2016-10-16T01:36:46Z
40,067,789
<p>Create a new <code>@app.route</code> in your Python file to display an individual product's information, and then add a link for each valve. It could look like this:</p> <pre><code>&lt;!-- other HTML up here --&gt; {% for valve in valve_list %} &lt;li&gt; &lt;b&gt;Item ID:&lt;/b&gt; {{ valve['item_id']...
1
2016-10-16T07:04:40Z
[ "python", "html", "sqlite", "flask" ]
Making subplots based on specific column in Pandas
40,065,971
<p>I have a pandas data frame that contains polynomial approximations of various functions at given points, with variable degrees to the polynomial approximation. It is arranged so that the first column is the function name, the second is the x value, then columns 2-5 are the approximations with a polynomial of the co...
2
2016-10-16T01:39:21Z
40,066,747
<pre><code>import pandas from matplotlib import pyplot as plt df = pandas.DataFrame({'fnctn':['a','a','a','b','b','b'],'x':[1,2,3,1,2,3],'y1':[2,3,4,3,2,2],'y2':[3,2,3,4,3,2]}) In [19]: df Out[19]: fnctn x y1 y2 0 a 1 2 3 1 a 2 3 2 2 a 3 4 3 3 b 1 3 4 4 b 2 2 3 5 ...
1
2016-10-16T04:12:54Z
[ "python", "pandas" ]
Flask framework error
40,065,998
<p>Hi guys i am getting an error and i am not sure what it means after looking at it for a lil while...</p> <p>here is the error:</p> <pre><code>vagrant@vagrant-ubuntu-trusty-32:/vagrant/PayUp$ python setup_database.py Traceback (most recent call last): File "setup_database.py", line 58, in &lt;module&gt; Base....
-1
2016-10-16T01:44:23Z
40,066,093
<p>Because you're using SQLite, the error message <code>sqlalchemy.exc.DatabaseError: (DatabaseError) database disk image is malformed 'PRAGMA table_info("users")' ()</code> leads to the assumption that there is something wrong with your database file called <code>payup.db</code>.</p> <p>Moving or deleting the possibl...
1
2016-10-16T02:01:40Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Missing Widgets
40,066,018
<p>I have recently installed Orange Data Mining tool, but cannot seem to find a few widgets such as "Scatter Plot" and "Distributions". I'm currently using version 3.3.8.</p> <p>How do I fix this issue?</p>
0
2016-10-16T01:48:43Z
40,080,020
<p>How did you install Orange? Seems like there's an issue with your PyQt installation. I'd suggest going Conda (<a href="https://www.continuum.io/downloads" rel="nofollow">Anaconda</a> distribution), as it works out of the box (at least on Windows).</p> <pre><code>conda config --add channels conda-forge conda install...
0
2016-10-17T06:45:04Z
[ "python", "data-mining", "orange" ]
apply images to pyplot python bar graphs
40,066,089
<p>So below is a snippet of my code, and it all works fine. Just curious instead of display bars with specific colors, can an image be applied to the bar, such as a countries flag etc. (please ignore my inconsistent order of param passing)</p> <p>thanks</p> <pre><code>l_images=["australia.png","turkey.png"] # this is...
0
2016-10-16T02:01:21Z
40,067,407
<p>AFAIK there's no built-in way to do this, although <code>matplotlib</code> does allow hatches in bar plots. See for example, <a href="http://matplotlib.org/examples/pylab_examples/hatch_demo.html" rel="nofollow">hatch_demo</a>.</p> <p>But it's not terribly difficult to put together several calls to <code>plt.imshow...
1
2016-10-16T06:11:46Z
[ "python", "image", "matplotlib", "graph" ]
How do i get these Postal code characters together?
40,066,115
<p>So I am trying to generate postal codes in order but the output makes each character separate, is there a way to get them together?</p> <pre><code>for first in range(10): for second in range(65,91): for third in range(10): for fourth in range(10): for fifth in range(65,91): ...
-2
2016-10-16T02:06:52Z
40,066,445
<p>use <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">.format</a></p> <p>ex:</p> <pre><code>a = 10 b = 11 '{}{}'.format(a,b) </code></pre> <p>outputs:</p> <pre><code>1011 </code></pre> <p>so:</p> <pre><code>for first in range(10): for second in range(65,91): for t...
0
2016-10-16T03:12:22Z
[ "python", "loops", "scripting" ]
Remove IMG tag from HTML using Regex - Python 2.7
40,066,116
<p>I have HTML and I want to remove IMG tag from it.</p> <p>I am not good at regex, I have this function but it does not remove IMG tag</p> <pre><code>def remove_img_tags(data): p = re.compile(r'&lt;img.*?/&gt;') return p.sub('', data) </code></pre> <p>What is the proper regex? I don't want to use any librar...
0
2016-10-16T02:06:58Z
40,066,249
<p>Try this:</p> <pre><code>image_tag = re.compile(r'&lt;img.*?/&gt;').search(data).group() data.replace(image_tag, '') </code></pre>
1
2016-10-16T02:34:12Z
[ "python", "regex", "python-2.7" ]
Remove IMG tag from HTML using Regex - Python 2.7
40,066,116
<p>I have HTML and I want to remove IMG tag from it.</p> <p>I am not good at regex, I have this function but it does not remove IMG tag</p> <pre><code>def remove_img_tags(data): p = re.compile(r'&lt;img.*?/&gt;') return p.sub('', data) </code></pre> <p>What is the proper regex? I don't want to use any librar...
0
2016-10-16T02:06:58Z
40,066,373
<p>All you need is to capture <code>img</code> tag and replace it with empty string.</p> <pre><code>clean_data = re.sub("(&lt;img.*?&gt;)", "", data, 0, re.IGNORECASE | re.DOTALL | re.MULTILINE) </code></pre> <p>You'll be passing HTML content in <code>data</code>. Regex will remove all <code>img</code> tags, their co...
1
2016-10-16T02:58:55Z
[ "python", "regex", "python-2.7" ]
How do I remove the circular dependency in my Organization-Owner-Member models?
40,066,130
<p>Heyo, I'm fairly new to this stuff so please pardon me if this is a stupid question. I'm trying to create an app where users can create organizations and join already existing ones. My requirements are:</p> <ul> <li>an organization may have only one user designated the owner (the user who creates it)</li> <li>user...
1
2016-10-16T02:11:06Z
40,066,352
<p>I still can't see why you have so much looping information. Your <code>OrgMember</code> class has an organization field, even though <code>Org</code> already has a <code>ManyToMany</code> with <code>OrgMember</code>. Same thing with <code>OrgOwner</code> - except that points to <code>OrgMember</code> which already p...
0
2016-10-16T02:55:46Z
[ "python", "django", "django-models" ]
ping through linux and get output in python
40,066,155
<p>I'm trying to create small script that provide whois and external ip and ping a site to find its statue. my code is running fine except for the ping part. It's pinging but not for the limit of 3 I asked for. I'm trying to run it in ubuntu server any suggestions?</p> <pre><code>import os os.system("clear") # clear ...
1
2016-10-16T02:16:23Z
40,066,184
<p>Try adding the count <code>-c</code> option to your command:</p> <pre><code>target = "stackoverflow.com" response = os.system("ping %s -c 3" % target) if response is not 0: print("failed") else: print("success") </code></pre> <p>You can do away with the loop also...</p>
0
2016-10-16T02:21:58Z
[ "python", "linux", "if-statement", "for-loop", "os.system" ]
cannot remove newline from a string
40,066,177
<p>Can you help me with this line of python code? I am trying to add strings to an array, and exclude the newlines. While the code appears to work the first time it splits the string, it seems to think there's another newline in there since it returns an error message: <code>substring not found</code>. However, when i ...
1
2016-10-16T02:20:42Z
40,066,252
<p>Why don't you use "replace" command?</p> <pre><code>x.replace("\n","") </code></pre>
3
2016-10-16T02:34:32Z
[ "python" ]
cannot remove newline from a string
40,066,177
<p>Can you help me with this line of python code? I am trying to add strings to an array, and exclude the newlines. While the code appears to work the first time it splits the string, it seems to think there's another newline in there since it returns an error message: <code>substring not found</code>. However, when i ...
1
2016-10-16T02:20:42Z
40,066,275
<p>Your problem stems from the fact that the <code>x</code> you iterate over does not see the changes you make.</p> <p>It's somewhat like this:</p> <pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf' y = x for i in x: if i=='\n': cut = y.index(i) y = y[cut+2:] </code></pre> <p>This is because ...
1
2016-10-16T02:39:27Z
[ "python" ]
Django FileNotFoundError in a view when returning HTML using codecs
40,066,199
<p>I am creating a view in Django that returns a static HTML page, and my code for that view is as follows:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response import codecs # Basic HTTP response that returns my html index # To call t...
0
2016-10-16T02:24:20Z
40,071,691
<p>If you want to open a file from the same directory as your view.py file, use the following:</p> <pre><code>html = open(os.path.dirname(os.path.realpath(__file__)) + 'index.html', "r") </code></pre>
0
2016-10-16T14:57:45Z
[ "python", "html", "django", "http", "web-deployment" ]
RecursionError while iterating over list
40,066,205
<p>I have a list of geodesic points by the format: <code>[lat, long, elevation, index, land/sea binary classifier]</code> in a grid formation with regular spacing throughout the dataset. I'm trying to find all neighbouring points that are land (elv > 0) to the current point in the list.</p> <p>I keep getting this err...
0
2016-10-16T02:24:59Z
40,067,691
<p>To stringify a point (really a <code>list</code>), <code>print</code> must first get the string representation of every element. The last element of each point is a <code>list</code> of neighboring points, each of which is a <code>list</code> that contains yet another <code>list</code> of neighboring points... one ...
1
2016-10-16T06:50:53Z
[ "python" ]
add own text inside nested braces
40,066,293
<p>I have this source of text which contains HTML tags and PHP code at the same time: <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&l...
1
2016-10-16T02:43:53Z
40,066,668
<p>Pyparsing has a helper method called <code>nestedExpr</code> that makes it easy to match strings of nested open/close delimiters. Since you have nested PHP tags within your <code>&lt;h1&gt;</code> tag, then I would use a <code>nestedExpr</code> like:</p> <pre><code>nested_angle_braces = nestedExpr('&lt;', '&gt;') <...
1
2016-10-16T03:59:05Z
[ "python", "pyparsing", "python-textprocessing" ]
Print items from a list in an external .py file
40,066,381
<p>I have a list in a external file and I'm able to access the file but I have a list in that file with the name of <code>facts</code>with some items on it but how can I read the items from that list? It goes something like</p> <pre><code>x = open("Trivia"+"/fact.py", "r") f = x.read() fact = f.? </code></pre> <p>Wh...
0
2016-10-16T03:00:08Z
40,066,470
<p><code>open</code> is for files containing data; files containing Python code are typically accessed with <a href="https://docs.python.org/3/reference/import.html" rel="nofollow"><code>import</code></a>. See <a href="https://docs.python.org/3/tutorial/" rel="nofollow"><em>The Python Tutorial</em></a>'s section <a hr...
1
2016-10-16T03:17:58Z
[ "python", "list" ]
Safe to use property names inside class methods?
40,066,387
<p>Given a class with a read-only property, one can modify it quite easily:</p> <pre><code>cls.prop_name = property(cls.prop_name.fget, my_setter) </code></pre> <p>However, one might <code>del cls.prop_name</code> or change it as I did. This is considered acceptable by PEP 8, which states <code>prop_name</code> is a ...
3
2016-10-16T03:02:23Z
40,066,968
<p>Okay, I'm not sure there is a good solution here, so I'm going with a different option: if a user tries to do something that messes everything up, it's their own fault. After all, Python is "a language for consenting adults".</p> <p>Just because an attribute is conventionally "public" by PEP 8 standards, that does ...
0
2016-10-16T04:52:07Z
[ "python", "properties" ]
How to calculate frequency of elements for pairwise comparisons of lists in Python?
40,066,439
<p>I have the the sample stored in the following list</p> <pre><code> sample = [AAAA,CGCG,TTTT,AT-T,CATC] </code></pre> <p>.. To illustrate the problem, I have denoted them as "Sets" below</p> <pre><code>Set1 AAAA Set2 CGCG Set3 TTTT Set4 AT-T Set5 CATC </code></pre> <ol> <li>Eliminate all Sets where each every ele...
2
2016-10-16T03:11:34Z
40,073,665
<p>I think this is what you want:</p> <pre><code>from collections import Counter # Remove elements where all nucleobases are the same. for index in range(len(sample) - 1, -1, -1): if sample[index][:1] * len(sample[index]) == sample[index]: del sample[index] for indexA, setA in enumerate(sample): for ...
2
2016-10-16T18:08:40Z
[ "python", "list", "for-loop", "dictionary", "frequency" ]
SQL: Finding the rarest and most common value in a set of relations
40,066,498
<p>I have a schema that looks like this:</p> <p>Person</p> <pre><code>pid name </code></pre> <p>Appearance</p> <pre><code>pid latitude longitude datetime </code></pre> <p>Class</p> <pre><code>pid major (1/0) type </code></pre> <p>I'm trying to write a function in Python that finds both the r...
-1
2016-10-16T03:24:42Z
40,067,177
<p>Just a stab in the dark... I agree with @2ps comment - you are a bit light on detail.</p> <p>The SQL part might look a bit like </p> <pre><code>SELECT pc.pid, MIN(pc.p_count) rare, MAX(pc.p_count) most_common FROM (SELECT a.pid, COUNT(*) p_count FROM appearance a ...
0
2016-10-16T05:28:47Z
[ "python", "sql", "sqlite", "relational-database", "schema" ]
Dictionary saving last result to every value using BeautifulSoup
40,066,532
<p>I am currently in the process of making a web crawler using <code>requests</code> and <code>BeautifulSoup</code>. I am using a for loop to create a list of dictionaries with the values being the <code>href</code> of the <code>a</code> tags. I am having issues doing this however since all of the results will be the l...
0
2016-10-16T03:31:37Z
40,066,696
<p>Your issue is with <code>tags_dict</code>. You are just storing a reference to that <strong>one</strong> dictionary again and again in your list, and since its a reference, the last value gets reflected in all entries. I changed it to create a new dict object for each iteration, now it works fine</p> <pre><code>imp...
2
2016-10-16T04:03:56Z
[ "python", "dictionary" ]
Django: Slug in Vietnamese working not correctly
40,066,533
<p>I begin to develop website online store using Django framework. I have faced with problem that I want to change the name in Vietnamese "những-viên-kẹo" to "nhung-vien-keo". I have read this article: <a href="http://stackoverflow.com/questions/1605041/django-slug-in-vietnamese">Django: Slug in Vietnamese</a></p...
1
2016-10-16T03:31:41Z
40,066,604
<pre><code>if not self.slug: ... self.slug = slugify(unicode(self.slug).translate(vietnamese_map)) </code></pre> <p>Your logic here is "translate slug only if slug is empty". Firstly, try to remove this condition (because it doesn't make sense). Secondly, try to make this work in forms instead, because at the ...
0
2016-10-16T03:46:10Z
[ "python", "django", "slug" ]
How to detect fast moving soccer ball with OpenCV, Python, and Raspberry Pi?
40,066,680
<p>This is the code. I am trying to detect different types of soccer ball using OpenCV and python. Soccer ball could of different colors. I can detect the ball if it is not moving. But, the code does not work if the ball is moving fast.</p> <pre><code>from picamera.array import PiRGBArray from picamera import PiCamera...
0
2016-10-16T04:01:05Z
40,128,794
<p>May I suggest you read this post?</p> <p><a href="http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/" rel="nofollow">http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/</a> </p> <p>There are also a few comments below indicating how to detect multiple balls rather than one.</p>
0
2016-10-19T10:30:08Z
[ "python", "opencv", "raspberry-pi", "detection", "object-detection" ]
unable to iterate over elements in selenium python
40,066,687
<p>Im a selenium noob and have been struggling to get things done with python. Im trying to iterate over all user reviews("partial_entry" class) from this page <a href="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS" rel="nofollow">https://www.tripadvisor.com/Airlin...
0
2016-10-16T04:02:28Z
40,067,370
<p><strong>1.</strong> The reason you keep getting the first element repeatedly while iterating over <code>i.find_element(By.XPATH, '//p[@class="partial_entry"]')</code> in the 2nd loop is that the beginning <code>//</code> tries to locate elements from the root/top level, <em>not</em> as a descendant element of <code>...
2
2016-10-16T06:06:22Z
[ "python", "selenium", "web-scraping" ]
why is this o(n) three-way set disjointness algorithm slower than then o(n^3) version?
40,066,778
<p>O(n) because converting list to set is O(n) time, getting intersection is O(n) time and len is O(n)</p> <pre><code>def disjoint3c(A, B, C): """Return True if there is no element common to all three lists.""" return len(set(A) &amp; set(B) &amp; set(C)) == 0 </code></pre> <p>or similarly, should be clearly ...
3
2016-10-16T04:19:15Z
40,067,260
<p>The comments made clarifications about the Big-Oh notations. So I will just start with testing the code.</p> <p>Here is the setup I used for testing the speed of the code.</p> <pre><code>import random # Collapsed these because already known def disjoint3c(A, B, C): def set_disjoint_medium (a, b, c): def set_disjo...
4
2016-10-16T05:44:32Z
[ "python", "algorithm", "complexity-theory" ]
why is this o(n) three-way set disjointness algorithm slower than then o(n^3) version?
40,066,778
<p>O(n) because converting list to set is O(n) time, getting intersection is O(n) time and len is O(n)</p> <pre><code>def disjoint3c(A, B, C): """Return True if there is no element common to all three lists.""" return len(set(A) &amp; set(B) &amp; set(C)) == 0 </code></pre> <p>or similarly, should be clearly ...
3
2016-10-16T04:19:15Z
40,067,923
<p>O notation ignores all the constant factors. So it will only answer for <em>infinite</em> data sets. For any finite set, it is only a rule of thumb.</p> <p>With interpreted languages such as Python and R, constant factors can be pretty large. They need to create and collect many objects, which is all O(1) but not f...
0
2016-10-16T07:23:37Z
[ "python", "algorithm", "complexity-theory" ]
Subproject dependencies in pants
40,066,815
<p>I am new to using <a href="http://www.pantsbuild.org/" rel="nofollow">pantsbuild</a> and I can't seem to find any good questions, answers, or documentation around my dillema.</p> <p>I have a Pants project which should be buildable on its own. It has its own <code>pants</code> and <code>pants.ini</code> file as well...
0
2016-10-16T04:25:38Z
40,067,144
<blockquote> <p>This is all well and good. However, since projectA is an independent project, it's src/python/libA/BUILD file contains something of the sort:</p> <blockquote> <p>dependencies = [ "src/python:libB" ]</p> </blockquote> </blockquote> <p>iiuc <code>src/python:libB</code> needs to be <code>proj...
0
2016-10-16T05:21:58Z
[ "python", "pants" ]
pandas get average of a groupby
40,066,837
<p>I am trying to find the average monthly cost per user_id but i am only able to get average cost per user or monthly cost per user. </p> <p>Because i group by user and month, there is no way to get the average of the second groupby (month) unless i transform the groupby output to something else.</p> <p>This is my d...
1
2016-10-16T04:29:39Z
40,067,099
<p>Resetting the index should work. Try this:</p> <pre><code>In [19]: df.groupby(['id', 'mth']).sum().reset_index().groupby('id').mean() Out[19]: mth cost id 1 4.0 33.333333 2 4.0 86.666667 </code></pre> <p>You can just drop <code>mth</code> if you want. The logic is that after the ...
2
2016-10-16T05:15:18Z
[ "python", "pandas", "dataframe", "group-by" ]
Subprocess not capturing the output of stdout storing it inside a variable in Python
40,066,876
<p>I tried the below code to capture the output from screen using the sub-process, but its not doing what I intended to do.</p> <pre><code>#!/tools/bin/python import subprocess result = subprocess.check_output("echo $USERNAME", shell=True) print result </code></pre> <p>expected output is:</p> <pre><code>vimo vimo...
0
2016-10-16T04:36:14Z
40,066,953
<p>Here you goes some greatly stripped (and altered for privacy reasons) raw <em>dummy</em> piece of code, grabbing both stdin and stdout from external script output.</p> <pre><code>from subprocess import Popen, PIPE cmd = ['echo', 'foo'] proc = Popen(cmd, stdout=PIPE, stderr=PIPE) comm = proc.communicate() if pro...
0
2016-10-16T04:48:59Z
[ "python", "python-2.7" ]
django stream json data that is created by request
40,066,877
<p>how can we stream data in django i saw many tutorials but still can figure it out, i requested a data inside view.py and send it through the context to template.html, but i want to update the data once it got changed so i need to keep sending request but how can i create that type of connection? basically some thi...
0
2016-10-16T04:36:17Z
40,079,785
<p>The most common use case of what you want to do is endless pagination, when you have lots of data and you do not want to retrieve them in one request. Instead, you request data multiple times and update your front end. Try to use django-el-pagination django package, it can help you with your problem. <a href="https...
0
2016-10-17T06:28:27Z
[ "python", "json", "django", "sockets", "request" ]
How to transfer edit method of an ID to a button/links in Django?
40,066,882
<p>This is the code in my ulrs.py</p> <pre><code>url(r'^viewguides/detail/(?P&lt;id&gt;\d+)/edit/$', views.post_update, name='update'), </code></pre> <p>Now I want to make it look like this:</p> <pre><code>&lt;a href="/detail/(?P&lt;id&gt;\d+)/edit" class="btn btn-default btn-lg" style="background-color: transparent...
0
2016-10-16T04:36:36Z
40,067,014
<p>You must use the url tag in your template, something like this:</p> <pre><code>&lt;a href="{% url update guide.id %}"&gt;EDIT&lt;/a&gt; </code></pre> <p>Where "update" is the <code>name</code> found in urls.py and "guide" the instance you want to update.</p>
0
2016-10-16T04:58:24Z
[ "python", "django", "python-2.7", "django-templates", "django-views" ]
How to transfer edit method of an ID to a button/links in Django?
40,066,882
<p>This is the code in my ulrs.py</p> <pre><code>url(r'^viewguides/detail/(?P&lt;id&gt;\d+)/edit/$', views.post_update, name='update'), </code></pre> <p>Now I want to make it look like this:</p> <pre><code>&lt;a href="/detail/(?P&lt;id&gt;\d+)/edit" class="btn btn-default btn-lg" style="background-color: transparent...
0
2016-10-16T04:36:36Z
40,071,222
<p>I just asked my colleagues who have some experience in Django. The answer is very simple.</p> <p>you just need to create this function in "models.py" :</p> <pre><code>def get_absolute_url(self): return "/viewguides/detail/%s/" %(self.id) </code></pre> <p>and then you can call it in the html by:</p> <pre><cod...
0
2016-10-16T14:09:10Z
[ "python", "django", "python-2.7", "django-templates", "django-views" ]
python challenge qn for loop
40,067,065
<p>EDIT: I SOLVED THE QUESTION BUT I WOULD APPRECIATE IF SOMEONE COULD JUST HELP ME MAKE MY CODE AS SHORT AS POSSIBLE (THE CHALLENGE WAS TO CODE IT WITH THE LEAST POSSIBLE CHARACTERS).</p> <p>I was going through some python challenges online and I came across this question.</p> <p><a href="https://i.stack.imgur.com/w...
0
2016-10-16T05:07:21Z
40,067,511
<p>Try using lists to keep track of the cells that need to change under certain conditions. I have also used a multidimensional list to keep track of the field of flowers.</p> <p>Code with annotations:</p> <pre><code>#sets up the grid and the number of generations grid=[['H','H','H','H','H'],['H','H','I','H','H'],['H...
0
2016-10-16T06:24:56Z
[ "python", "for-loop" ]
python challenge qn for loop
40,067,065
<p>EDIT: I SOLVED THE QUESTION BUT I WOULD APPRECIATE IF SOMEONE COULD JUST HELP ME MAKE MY CODE AS SHORT AS POSSIBLE (THE CHALLENGE WAS TO CODE IT WITH THE LEAST POSSIBLE CHARACTERS).</p> <p>I was going through some python challenges online and I came across this question.</p> <p><a href="https://i.stack.imgur.com/w...
0
2016-10-16T05:07:21Z
40,068,155
<p>Here is another solution:</p> <pre><code>import sys # use a string to hold the flowerbed bed = 'HHHHH' 'HHIHH' 'HHFHH' 'HHHHH' 'HHHHH' # a function to write out a flowerbed pr = lambda b: sys.stdout.write('\n'.join(b[x:x+5] for x in range(0, 25, 5))+'\n\n') # make a list of the cells to check for infection, for e...
0
2016-10-16T07:55:35Z
[ "python", "for-loop" ]
python challenge qn for loop
40,067,065
<p>EDIT: I SOLVED THE QUESTION BUT I WOULD APPRECIATE IF SOMEONE COULD JUST HELP ME MAKE MY CODE AS SHORT AS POSSIBLE (THE CHALLENGE WAS TO CODE IT WITH THE LEAST POSSIBLE CHARACTERS).</p> <p>I was going through some python challenges online and I came across this question.</p> <p><a href="https://i.stack.imgur.com/w...
0
2016-10-16T05:07:21Z
40,069,183
<p>This answer should work</p> <pre><code>class Flowers(object): def __init__(self, flowers_state): self.flowers_state = flowers_state def run_rule(self): """ Rule1 -&gt; Infected area become faded the following year Rule2 -&gt; Faded aread becomes Healthy Rule3 -&gt; I...
0
2016-10-16T10:18:23Z
[ "python", "for-loop" ]
python challenge qn for loop
40,067,065
<p>EDIT: I SOLVED THE QUESTION BUT I WOULD APPRECIATE IF SOMEONE COULD JUST HELP ME MAKE MY CODE AS SHORT AS POSSIBLE (THE CHALLENGE WAS TO CODE IT WITH THE LEAST POSSIBLE CHARACTERS).</p> <p>I was going through some python challenges online and I came across this question.</p> <p><a href="https://i.stack.imgur.com/w...
0
2016-10-16T05:07:21Z
40,073,783
<p>A Numpy based solution (in the 2D numpy arrays <code>curr</code> and <code>next</code> in function <code>update</code>, 0, 1 and 2 correspond to "healthy", "infected" and "faded" respectively):</p> <pre><code>import numpy as np def update(curr, next): next[curr==1] = 2 # infected flowers become faded next[c...
0
2016-10-16T18:19:07Z
[ "python", "for-loop" ]
Create a new instance of a generator in python
40,067,070
<p>I am trying to scrape a page which has many links to pages which contain ads. What I am currently doing to navigate it is going to the first page with the list of ads and getting the link for the individual ads. After that, I check to make sure that I haven't scraped any of the links by pulling data from my databa...
0
2016-10-16T05:08:10Z
40,067,423
<p>It looks to me like your code would be a lot simpler if you put the logic that scrapes successive pages into a generator function. This would let you use <code>for</code> loops rather than messing around and calling <code>next</code> on the generator objects directly:</p> <pre><code>def urls_gen(driver): while ...
0
2016-10-16T06:14:23Z
[ "python", "generator", "yield-keyword" ]
Creating lists from rows with different lengths in python
40,067,078
<p>I am trying to create a list for each column in python of my data that looks like this:</p> <pre><code>399.75833 561.572000000 399.75833 561.572000000 a_Fe I 399.73920 nm 399.78316 523.227000000 399.78316 523.227000000 399.80799 455.923000000 399.80799 455.923000000 ...
1
2016-10-16T05:10:31Z
40,067,266
<p>You need to use <code>izip_longest</code> to make your column lists, since standard <code>zip</code> will only run till the shortest length in the given list of arrays.</p> <pre><code>from itertools import izip_longest with open('workfile', 'r') as f: fh = f.readlines() # Process all the rows line by line rows...
1
2016-10-16T05:45:20Z
[ "python" ]
Creating lists from rows with different lengths in python
40,067,078
<p>I am trying to create a list for each column in python of my data that looks like this:</p> <pre><code>399.75833 561.572000000 399.75833 561.572000000 a_Fe I 399.73920 nm 399.78316 523.227000000 399.78316 523.227000000 399.80799 455.923000000 399.80799 455.923000000 ...
1
2016-10-16T05:10:31Z
40,067,300
<p>So, your lines are either whitespace delimited or comma delimited, and if comma delimited, the line contains no whitespace? (note that if <code>len(splits)==1</code> is true, then <code>splits[0]==line.strip()</code> is also true). That's not the data you're showing, and not what you're describing.</p> <p>To get ...
0
2016-10-16T05:51:17Z
[ "python" ]
How do I replace items in a file with items in a list
40,067,081
<p>I have f1.txt, a file in which I want to replace all occurrences of 999 with the consecutive elements of the list lst. I have the following code, but it doesn't quite work. </p> <pre><code>lst = ['1', '2', '3'] f1 = open('f1.txt', 'r') f2 = open('f2.txt', 'w') for no in lst: for line in f1: if 'some_text' in...
0
2016-10-16T05:10:51Z
40,067,125
<pre><code>lst = ['1', '2', '3'] f1 = open('f1.txt', 'r') f2 = open('f2.txt', 'w') idx = 0 for line in f1: if ('some_text' in line) and ('999' in line): f2.write(line.replace('999', lst[idx])) idx += 1 else: f2.write(line) f1.close() f2.close() </code></pre>
0
2016-10-16T05:19:01Z
[ "python", "list", "file" ]
Incorporate duplicates in a list of tuples into a dictionary summing the values
40,067,128
<p>Hi I wish to convert this list of tuples into dictionary. As I am new to python, I am figuring out ways to convert into dictionary. I could only convert into dictionary if there is only one value. In my case, there are two values in it.I will demonstrate with more details below:</p> <pre><code> `List of tuples: ...
0
2016-10-16T05:19:28Z
40,067,151
<p>You can do this with a dictionary comprehension</p> <p>What you really want are <em>tuples</em> for keys, which will be the company and the device.</p> <pre><code>tuples = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10), ('Sony','Handphone',100)] d...
0
2016-10-16T05:23:36Z
[ "python", "list", "dictionary", "tuples", "counter" ]
Incorporate duplicates in a list of tuples into a dictionary summing the values
40,067,128
<p>Hi I wish to convert this list of tuples into dictionary. As I am new to python, I am figuring out ways to convert into dictionary. I could only convert into dictionary if there is only one value. In my case, there are two values in it.I will demonstrate with more details below:</p> <pre><code> `List of tuples: ...
0
2016-10-16T05:19:28Z
40,067,196
<p>Good opportunity for <code>defaultdict</code></p> <pre><code>from collections import defaultdict the_list = [ ('Samsung', 'Handphone', 10), ('Samsung', 'Handphone', -1), ('Samsung', 'Tablet', 10), ('Sony', 'Handphone', 100) ] d = defaultdict(lambda: defaultdict(int)) for brand, thing, quantity ...
3
2016-10-16T05:33:06Z
[ "python", "list", "dictionary", "tuples", "counter" ]
Incorporate duplicates in a list of tuples into a dictionary summing the values
40,067,128
<p>Hi I wish to convert this list of tuples into dictionary. As I am new to python, I am figuring out ways to convert into dictionary. I could only convert into dictionary if there is only one value. In my case, there are two values in it.I will demonstrate with more details below:</p> <pre><code> `List of tuples: ...
0
2016-10-16T05:19:28Z
40,067,257
<p>Your output has a problem, that can be seen with proper identation:</p> <pre><code>{ 'Sony': ['Handphone',100], 'Samsung': ['Tablet',10], ['Handphone', 9] } </code></pre> <p>Handphone isn't a part of 'Samsung', you can do a list of lists to get:</p> <pre><code>{ 'Sony': [ ['Handphone',100...
0
2016-10-16T05:44:26Z
[ "python", "list", "dictionary", "tuples", "counter" ]
ImportError: No module named app.views django 1.10 python
40,067,182
<p>I just have started learning django in its 1.10 version. In a project (called <code>refugio</code>) I have created an app called <code>mascota</code>.</p> <p>This is my views.py file for my app:</p> <pre><code>from __future__ import unicode_literals, absolute_import from django.shortcuts import render from django....
0
2016-10-16T05:29:42Z
40,067,319
<p>Change your file structure into </p> <pre><code>REFUGIO mascota views.py urls.py refugio settings.py urls.py manage.py </code></pre> <p>and then change the line in urls.py </p> <pre><code>from apps.mascota.views import index </code></pre> <p>into </p> <pre><code>form ...
0
2016-10-16T05:57:03Z
[ "python", "django", "django-views", "django-urls" ]
ImportError: No module named app.views django 1.10 python
40,067,182
<p>I just have started learning django in its 1.10 version. In a project (called <code>refugio</code>) I have created an app called <code>mascota</code>.</p> <p>This is my views.py file for my app:</p> <pre><code>from __future__ import unicode_literals, absolute_import from django.shortcuts import render from django....
0
2016-10-16T05:29:42Z
40,067,835
<p>Every Python package need <code>__init__.py</code> file (read <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow">this</a> and <a class='doc-link' href="http://stackoverflow.com/documentation/python/3142/difference-between-module-and-package#t=201610160717100771537">this</a>).</p> <pre><code>RE...
1
2016-10-16T07:12:03Z
[ "python", "django", "django-views", "django-urls" ]
matplotlib adding blue shade to an image
40,067,243
<p>I am trying to use matplotlib for basic operations but I see that whenever I try to display an image using matplotlib, a blue shade is added to the image. </p> <p>For example, </p> <p>Code:</p> <pre><code># import the necessary packages import numpy as np import cv2 import matplotlib.pyplot as plt image = cv2.im...
1
2016-10-16T05:40:57Z
40,068,263
<p>see: <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html#using-matplotlib" rel="nofollow">http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html#using-matplotlib</a></p> <blockquote> <p>Warning: Color image loaded by OpenC...
2
2016-10-16T08:10:41Z
[ "python", "opencv", "image-processing", "matplotlib" ]
Optimization of iterating over long list of string
40,067,276
<p>The below snippet of code executes in about 18s. <code>EdgeList</code> is estimated to be 330K in length. Is there a way to optimize it, considering that I am calling it multiple times.</p> <p>I have tried optimizing the insertion into my <code>MeanspeedDict</code>. But I guess it's the best it can go already? ...
0
2016-10-16T05:47:05Z
40,067,376
<pre><code>from collections import deque, defaultdict MeanspeedDict = defaultdict(lambda: deque(maxlen=300)) EdgeList = traci.edge.getIDList() for edge in EdgeList: MeanspeedDict[edge].append(traci.edge.getLastStepMeanSpeed(edge)) </code></pre>
1
2016-10-16T06:07:54Z
[ "python", "python-2.7" ]
Optimization of iterating over long list of string
40,067,276
<p>The below snippet of code executes in about 18s. <code>EdgeList</code> is estimated to be 330K in length. Is there a way to optimize it, considering that I am calling it multiple times.</p> <p>I have tried optimizing the insertion into my <code>MeanspeedDict</code>. But I guess it's the best it can go already? ...
0
2016-10-16T05:47:05Z
40,067,517
<p>It seems <code>getLastStepMeanSpeed</code> is too slow:</p> <pre><code>3607912 2.785 0.000 221.939 0.000 _edge.py:151(getLastStepMeanSpeed) </code></pre> <p>The script spend executing it 75% of the time (221/295)</p>
1
2016-10-16T06:26:04Z
[ "python", "python-2.7" ]
Pandas annotate dataframe hist
40,067,293
<pre><code>df = { 'id' : pd.Series([1,1,1,1,2,2,2,2,3,3,4,4,4])} num_id = df['id'].value_counts().hist(bins=2) </code></pre> <p>I an get a nice histogram with the count of number of ids that fall into each bin. </p> <p>Question is, how do i add annotations to each bar to show the count? It could be in the middle wit...
1
2016-10-16T05:50:04Z
40,067,598
<p>Here you are (with the <code>import</code> statements, just in case):</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ 'id' : [1,1,1,1,2,2,2,2,3,3,4,4,4]}) fig, ax = plt.subplots() freq, bins, _ = ax.hist(df['id'].value_counts(), 2, facecolor='skyblue') ax.grid(True) for i, n...
1
2016-10-16T06:36:37Z
[ "python", "pandas", "matplotlib" ]
Trouble with ".select()" Method in Peewee
40,067,342
<p>I am making a peewee database. In my python code I try to retrieve rows from the model that may be empty:</p> <p><code>player_in_db = Player.select().where(Player.name == player.name_display_first_last)</code></p> <p><code>Player</code> is the name of the model</p> <p><code>name</code> is a field instance in <cod...
1
2016-10-16T06:02:09Z
40,067,442
<p>The error says you're missing the <code>name</code> column in the table (named <code>t1</code>) that your Player model uses. Most likely you've told PeeWee to create the table for player before it had the name field or you simply haven't created the table at all. You should always try to fully write your model befor...
0
2016-10-16T06:16:43Z
[ "python", "database", "sqlite3", "peewee", "datatable.select" ]
How to obtain the nth row of the pascal triangle
40,067,386
<p>Here is my code to find the nth row of pascals triangle</p> <pre><code>def pascaline(n): line = [1] for k in range(max(n,0)): line.append(line[k]*(n-k)/(k+1)) return line </code></pre> <p>There are two things I would like to ask. First, the outputs integers ...
0
2016-10-16T06:09:15Z
40,067,484
<p>subtract 1 from n and typecast. basically change your method to this:</p> <pre><code>def pascaline(n): n = n - 1 line = [1] for k in range(max(n ,0)): line.append(int(line[k]*(n-k)/(k+1))) return line print(pascaline(5)); </code></pre>
0
2016-10-16T06:22:17Z
[ "python" ]
How to obtain the nth row of the pascal triangle
40,067,386
<p>Here is my code to find the nth row of pascals triangle</p> <pre><code>def pascaline(n): line = [1] for k in range(max(n,0)): line.append(line[k]*(n-k)/(k+1)) return line </code></pre> <p>There are two things I would like to ask. First, the outputs integers ...
0
2016-10-16T06:09:15Z
40,067,541
<p>the .0 can be removed by taking the floor division using <code>//</code> instead of float division with <code>/</code> so your code would be <code>line.append(line[k]*(n-k)//(k+1))</code>. To get it to start one back just make n one less with <code>n -= 1</code>.</p> <pre><code>def pascaline(n): n -= 1 li...
5
2016-10-16T06:30:27Z
[ "python" ]
How to obtain the nth row of the pascal triangle
40,067,386
<p>Here is my code to find the nth row of pascals triangle</p> <pre><code>def pascaline(n): line = [1] for k in range(max(n,0)): line.append(line[k]*(n-k)/(k+1)) return line </code></pre> <p>There are two things I would like to ask. First, the outputs integers ...
0
2016-10-16T06:09:15Z
40,067,792
<p>I know you've got your answer. The problem is you are dealing with floating point numbers, <em>not</em> integers. This is programming, not math. Numbers are represented concretely. I just wanted to compare these two implementations, where the first one let's you save some calculation time by using symmetry. Both are...
1
2016-10-16T07:05:31Z
[ "python" ]
string input from Python list
40,067,538
<p>i Want to make a very simple script that will do the following:</p> <p>1- I have a List Named tries = ["First", "Second", "Last"]</p> <p>2- I want the user will make an input string for each try</p> <p>so I made script as below:</p> <pre><code>print("You got 3 Guessing tries to guess What is My Name") tries = [...
-3
2016-10-16T06:30:11Z
40,067,612
<p>The <code>input</code> function takes only <strong>one</strong> arguments. Here, you give two to it.</p> <p>I'm guessing that what you want to do is</p> <pre><code>print("You got 3 Guessing tries to guess What is My Name") tries = ["First", "Second", "Last"] for x in tries: Names = str(input("{} Guess ?".for...
0
2016-10-16T06:38:13Z
[ "python", "python-2.7", "python-3.x" ]
string input from Python list
40,067,538
<p>i Want to make a very simple script that will do the following:</p> <p>1- I have a List Named tries = ["First", "Second", "Last"]</p> <p>2- I want the user will make an input string for each try</p> <p>so I made script as below:</p> <pre><code>print("You got 3 Guessing tries to guess What is My Name") tries = [...
-3
2016-10-16T06:30:11Z
40,067,624
<p><strong>first</strong> off the str() is not needed because input always outputs a string</p> <p><strong>secondly</strong> this is python 3.x not 2.7 (in the tagging)</p> <p><strong>third</strong> the issue you are having is you are trying to give input 2 parameters, this works with print and that throws new python...
0
2016-10-16T06:41:13Z
[ "python", "python-2.7", "python-3.x" ]
How to implement 'range' with a python BST
40,067,554
<p>My code at the moment allows me to search for a specific node, I would like to edit it so that I can search within a range of numbers. For example, I have a price list of apples, and I would like to add all apples to a list/dictionary that cost between $2-$4 or something like that. </p> <p>Here is my current code</...
1
2016-10-16T06:31:43Z
40,068,402
<p><strong>Using recursive in-order traversal:</strong></p> <pre><code>def range(self, a, b): return self._traverse_range(self._root, a, b) def _traverse_range(self, subtree, a, b, cumresult=None): if subtree is None: return # Cumulative variable. if cumresult is None: cumresult = [] ...
1
2016-10-16T08:30:52Z
[ "python", "binary-search-tree" ]
python csv new line
40,067,590
<p>iam using this code to convert db table to csv file, it is converting in to csv but instead of new line / line breck its using double quotes , can someone help me </p> <pre>...
0
2016-10-16T06:35:59Z
40,068,007
<p>SQL queries will return results to you in a list of tuples from <code>fetchall()</code>. In your current approach, you iterate through this list but call <code>str()</code> on each tuple, thereby converting the whole tuple to its string representation.</p> <p>Instead, you could use a list comprehension on each tupl...
0
2016-10-16T07:35:06Z
[ "python", "mysql-python" ]
How to assign variables to numpy matrix
40,067,593
<p>I want to make a function to generate rotational matrix R. Here is my code:</p> <pre><code>import numpy as np def R(theta): a = np.cos(theta) b = -1*np.sin(theta) c = np.sin(theta) d = np.cos(theta) return np.matrix('a b; c d') </code></pre> <p>But it has error like this</p> <pre><code>raise T...
0
2016-10-16T06:36:03Z
40,067,678
<p>use <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">.format</a> to put the variables into string form </p> <pre><code>return np.matrix('{} {};{} {}'.format(a,b,c,d)) </code></pre>
0
2016-10-16T06:49:25Z
[ "python", "numpy", "matrix" ]
How to assign variables to numpy matrix
40,067,593
<p>I want to make a function to generate rotational matrix R. Here is my code:</p> <pre><code>import numpy as np def R(theta): a = np.cos(theta) b = -1*np.sin(theta) c = np.sin(theta) d = np.cos(theta) return np.matrix('a b; c d') </code></pre> <p>But it has error like this</p> <pre><code>raise T...
0
2016-10-16T06:36:03Z
40,067,741
<p>That matrix notation:</p> <pre><code>a = np.matrix('1 2; 3 4') </code></pre> <p>only works for literals, not variables; with scalar variables you'd use the bracket notation</p> <pre><code>np.matrix([[1, 2], [3, 4]]) np.matrix([[a, b], [c, d]]) </code></pre> <p>This part, <code>[[a, b], [c, d]]</code> is an ordin...
0
2016-10-16T06:58:45Z
[ "python", "numpy", "matrix" ]
Why it raises error when print the return values of function for non-linear equations
40,067,610
<p>I use fsolve to solve equations, but when I put the solution into the KMV() function again, it raises an exception. I can not figure it out... </p> <pre><code>def KMV(x, *args): valueToEquity = float(x[0]) volOfValue = float(x[1]) equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity = args d1 = (...
-1
2016-10-16T06:38:03Z
40,067,711
<p>If you remove the leading <code>*</code> from <code>args</code> in the declaration of <code>KVM</code> you can call it like that, but other code would fail if you did that. <code>*args</code> is for <em>variadic</em> functions, that is functions with a variable number of parameters. </p> <p>If you want to pass ke...
0
2016-10-16T06:53:49Z
[ "python", "scipy" ]
Why it raises error when print the return values of function for non-linear equations
40,067,610
<p>I use fsolve to solve equations, but when I put the solution into the KMV() function again, it raises an exception. I can not figure it out... </p> <pre><code>def KMV(x, *args): valueToEquity = float(x[0]) volOfValue = float(x[1]) equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity = args d1 = (...
-1
2016-10-16T06:38:03Z
40,067,749
<p>Just take a look at this quick reminder...</p> <pre><code>def func(arg1): print(arg1) func('hello') # output 'hello' def func(*args): # you can call this function with as much arguments as you want ! # type(args) == tuple print(args) func('some', 'args', 5) # output ('some', 'args', 5) def func(...
0
2016-10-16T06:59:32Z
[ "python", "scipy" ]
Replacing string in a list of strings
40,067,659
<p>I have problem with my code. In this example it should print out <code>The Wind in the Willows</code>, but it does print <strong>The Wind In The Willows</strong>. I think the problem is that replace function does not execute. I have no idea what's wrong with this code. Please help.</p> <p>PS. Basic idea of this fun...
0
2016-10-16T06:47:50Z
40,067,863
<pre><code>def title_case(title, minor_words): # lowercase minor_words and make a set for quicker lookups minor_set = set(i for i in minor_words.lower().split()) # tokenize the title by lowercasing tokens = title.lower().split() # create a new title by capitalizing words that dont belong to minor_se...
2
2016-10-16T07:16:26Z
[ "python", "string" ]
Replacing string in a list of strings
40,067,659
<p>I have problem with my code. In this example it should print out <code>The Wind in the Willows</code>, but it does print <strong>The Wind In The Willows</strong>. I think the problem is that replace function does not execute. I have no idea what's wrong with this code. Please help.</p> <p>PS. Basic idea of this fun...
0
2016-10-16T06:47:50Z
40,067,886
<pre><code>for x in minor_words.split(): title = title.replace(x,x.lower()) </code></pre> <p>I'm a little confused as to what exactly you are trying to do(its late for me so I can't think) but that will replace all words in <code>title</code> that are <code>minor_words</code> with a lower case copy. Making the...
0
2016-10-16T07:19:14Z
[ "python", "string" ]
Replacing string in a list of strings
40,067,659
<p>I have problem with my code. In this example it should print out <code>The Wind in the Willows</code>, but it does print <strong>The Wind In The Willows</strong>. I think the problem is that replace function does not execute. I have no idea what's wrong with this code. Please help.</p> <p>PS. Basic idea of this fun...
0
2016-10-16T06:47:50Z
40,067,904
<p>Since you assign to <code>title</code> in the loop, you get the value of title is the same as the value assigned to it by the last time through the loop.</p> <p>I've done this differently. I loop through all the words in the title (not just the exclusions) and title case those that are not excluded.</p> <pre><code...
1
2016-10-16T07:21:51Z
[ "python", "string" ]
Can't call CMake from a Python script
40,067,690
<p>I'm trying to call the <a href="http://en.wikipedia.org/wiki/CMake" rel="nofollow">CMake</a> command from a Python script. This is my code:</p> <pre><code>cmakeCmd = ["C:\Program Files\CMake\bin\cmake.exe",'-G Visual Studio 11 Win64', 'C:\Users\MyUser\Desktop\new\myProject'] retCode = subprocess.check_call(cmakeCmd...
1
2016-10-16T06:50:51Z
40,067,811
<p>A backslash (<code>\</code>) in a Python string is an escape character. That's why the string <code>"C:\Program Files\CMake\bin\cmake.exe"</code> is translated to <code>C:\\Program Files\\CMake\x08in\\cmake.exe</code> (notice that <code>\b</code> equals <code>\x08</code>). To fix this, tell Python you want the strin...
1
2016-10-16T07:08:28Z
[ "python", "cmake" ]
About random.shuffle, arrays
40,067,692
<p>Hi there so I have this code. It works well (has also taught me alot about Python as I am new and a bit of a beginner but catching up very well.) Anyway I want to shuffle the questions in the following code. I understand the idea of random.shuffle and arrays. Just not sure howto put it together and what fits best</p...
1
2016-10-16T06:50:58Z
40,067,767
<p>You use random.shuffle by simply passing in the list.</p> <pre><code>import random list1 = ["10","7","13","4","1","6","9","12","17","2"] random.shuffle(list1) # list1 is now shuffled print list1 # observe shuffled list </code></pre>
0
2016-10-16T07:01:39Z
[ "python", "random" ]
About random.shuffle, arrays
40,067,692
<p>Hi there so I have this code. It works well (has also taught me alot about Python as I am new and a bit of a beginner but catching up very well.) Anyway I want to shuffle the questions in the following code. I understand the idea of random.shuffle and arrays. Just not sure howto put it together and what fits best</p...
1
2016-10-16T06:50:58Z
40,070,579
<pre><code>def game(): #defines the games script start_time = time.time() #starts game timer. correct = 0 ...
0
2016-10-16T13:06:24Z
[ "python", "random" ]
How to call the random list function without chaning it in Python?
40,067,693
<p>I really need help. I defined a function that gives a x number of rolls for n-sided dice. Now I am asked to calculate the frequency of the each side and <code>freq1 += 1</code> doesn't seem to work considering there can be many more sides (not just 6) and what I did was; </p> <p>the first function I defined was <co...
0
2016-10-16T06:51:06Z
40,068,686
<p>You called the dice() function twice, once when you printed it, and once when you iterated through it in a for loop. The different results come from there.</p> <pre><code>import random n = raw_input('Number of the sides of the dice: ') n = int(n) x = raw_input('Number of the rolls: ') x = int(x) def dice(): r...
0
2016-10-16T09:10:40Z
[ "python", "dice" ]
Trying to Solve Numerical Diff Eq Using Euler's Method, Invalid Value Error
40,067,790
<p>I am trying to learn it from this website: <a href="http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb" rel="nofollow">http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb...
1
2016-10-16T07:04:52Z
40,069,114
<p>The solution is very simple. You forgot the return statement in euler_step. Change</p> <pre><code>def euler_step(u, f, dt): u + dt * f(u) </code></pre> <p>to</p> <pre><code>def euler_step(u, f, dt): return u + dt * f(u) </code></pre> <p>and it will work</p>
0
2016-10-16T10:10:04Z
[ "python", "numpy", "matplotlib", "numerical-methods" ]
Switching database backend in Mezzanine
40,067,806
<p>I am trying to script a series of examples where the reader incrementally builds a web application. The first stage takes place with Mezzanine's default configuration, using built-in SQLlite:</p> <pre><code>sudo pip install mezzanine sudo -u mezzanine python manage.py createdb </code></pre> <p>After the initial e...
0
2016-10-16T07:07:57Z
40,069,801
<p>The Mezzanine project is based on Django, the Python framework.<br> Unless you encounter a Mezzanine specific problem, most issues can be solved by figuring out how its done the Django way.</p> <p><em>Migrations</em> is just Django's way of refering to alterations &amp; amendments <em>within</em> the DB, ie, the sc...
3
2016-10-16T11:38:12Z
[ "python", "mysql", "django", "mezzanine" ]
How to save a dictionary as a value of another dictionary in pymongo for flask?
40,067,814
<p>I have a <code>Json</code> request that looks like this:</p> <pre><code>{"name":"jane", "family": "doe", "address":{"country":"Iran", "State": "Ilam", "city": "ilam"}, "age": "25" } </code></pre> <p>and i can get the values into a variable using:</p> <pre><code>name = request.json['name'] family = requst.json['fa...
0
2016-10-16T07:08:45Z
40,068,472
<p>If you have the following dictionary, 'address' is a dictionary that is nested in another dictionary:</p> <pre><code>{"name":"jane", "family": "doe", "address":{"country":"Iran", "State": "Ilam", "city": "ilam"}, "age": "25" } </code></pre> <p>Extracting the address is done in the following way:</p> <pre><code>ad...
3
2016-10-16T08:39:51Z
[ "python", "dictionary", "pymongo" ]
Remove numbers from list which contains some particular numbers in python
40,067,822
<p>Given List:</p> <pre><code>l = [1,32,523,336,13525] </code></pre> <p>I am having a number 23 as an output of some particular function.</p> <p>Now, </p> <p>I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.</p> <pre><code>Output should be:[1] </code></pre> <p>I want to writ...
1
2016-10-16T07:09:56Z
40,067,970
<p>You could convert the numbers to sets of characters:</p> <pre><code>&gt;&gt;&gt; values = [1, 32, 523, 336, 13525] &gt;&gt;&gt; number = 23 &gt;&gt;&gt; [value for value in values ... if set(str(number)).isdisjoint(set(str(value)))] [1] </code></pre>
3
2016-10-16T07:30:26Z
[ "python", "list", "python-2.7", "python-3.x", "filter" ]
Remove numbers from list which contains some particular numbers in python
40,067,822
<p>Given List:</p> <pre><code>l = [1,32,523,336,13525] </code></pre> <p>I am having a number 23 as an output of some particular function.</p> <p>Now, </p> <p>I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.</p> <pre><code>Output should be:[1] </code></pre> <p>I want to writ...
1
2016-10-16T07:09:56Z
40,067,974
<p>You're looking for the <code>filter</code> function. Say you have a list of ints and you want the odd ones only:</p> <pre><code>def is_odd(val): return val % 2 == 1 filter(is_odd, range(100)) </code></pre> <p>or a list comprehension</p> <pre><code>[x for x in range(100) if x % 2 == 1] </code></pre> <p>The l...
0
2016-10-16T07:31:11Z
[ "python", "list", "python-2.7", "python-3.x", "filter" ]
How do you define a function during dynamic Python type creation
40,067,900
<p>(This is in Python 3 btw)</p> <p>Okay so say we use <code>type()</code> as a class constructor:</p> <p><code>X = type('X', (), {})</code></p> <p>What I'm trying to find is how would <code>type()</code> accept a function as an argument and allow it to be callable? </p> <p>I'm looking for an example of how this co...
1
2016-10-16T07:21:14Z
40,067,963
<p>You need to pass the function. In your code, you call the function, and pass the result.</p> <p>Try:</p> <pre><code>def print_hello(self): print("Hello {0}!".format(self.name)) X = type('X', (), {'name':'World', 'greet': print_hello}) </code></pre>
1
2016-10-16T07:29:35Z
[ "python", "python-3.x", "dynamic-programming", "metaclass", "class-method" ]
Reading from CSV and filtering columns
40,067,988
<p>I have a CSV file.</p> <p>There are a fixed number of columns and an unknown number of rows. </p> <p>The information I need is always in the same 2 columns but not in the same row.</p> <p>When column 6 has a 17 character value I also need to get the data from column 0. </p> <p>This is an example row from the CSV...
0
2016-10-16T07:32:26Z
40,068,079
<p>You could open the file and go through it line by line. Split the line and if element 6 has 17 characters append element 0 to your result array.</p> <pre><code>f = open(file_name, 'r') res = [] for line in f: L = line.split(',') If len(L[6])==17: res.append(L[0]) </code></pre> <p>Now you have a lis...
0
2016-10-16T07:44:33Z
[ "python", "csv" ]
Reading from CSV and filtering columns
40,067,988
<p>I have a CSV file.</p> <p>There are a fixed number of columns and an unknown number of rows. </p> <p>The information I need is always in the same 2 columns but not in the same row.</p> <p>When column 6 has a 17 character value I also need to get the data from column 0. </p> <p>This is an example row from the CSV...
0
2016-10-16T07:32:26Z
40,068,692
<p>You can use <strong>csv</strong> module to read the csv files and you can provide delimiter/dialect as you need (, or | or tab etc..) while reading the file using csv reader. csv reader takes care of providing the row/record with columns as list of values. If you want access the csv record/row as dict then you can...
0
2016-10-16T09:11:47Z
[ "python", "csv" ]
Remove the function and command from the output
40,068,050
<p>I have trying out defaultdict with lamba function. However, I could not get the output I want. I will demonstrate with more details. Below is my code:</p> <pre><code>from collections import defaultdict the_list = [ ('Samsung', 'Handphone', 10), ('Samsung', 'Handphone', -1), ('Samsung', 'Tablet', 10),...
0
2016-10-16T07:39:39Z
40,068,107
<p>Just convert each <code>defaultdict</code> back to a regular <code>dict</code>, you can do it easily using <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/738/dictionary-comprehensions#t=201610160749050862097">dict comprehension</a>:</p> <pre><code>{ k:dict(v) for k,v in d...
1
2016-10-16T07:48:46Z
[ "python", "defaultdict" ]
Remove the function and command from the output
40,068,050
<p>I have trying out defaultdict with lamba function. However, I could not get the output I want. I will demonstrate with more details. Below is my code:</p> <pre><code>from collections import defaultdict the_list = [ ('Samsung', 'Handphone', 10), ('Samsung', 'Handphone', -1), ('Samsung', 'Tablet', 10),...
0
2016-10-16T07:39:39Z
40,068,246
<p>Try dumping your data in JSON format if you want to remove the type information. </p> <p><p> Insert this at the top:</p> <pre><code>import json </code></pre> <p>And this at the bottom:</p> <pre><code>print json.dumps(d, indent=4) </code></pre> <p>And your code should print out like this:</p> <pre><code>{ "...
0
2016-10-16T08:08:02Z
[ "python", "defaultdict" ]
how to use onehotcoding
40,068,104
<p>so im trying to do a project that asks to do one hot coding for a certain part. but i have no idea how to use it. ive been using google to try and understand but i just cant understand. my question is below.</p> <p>Now, we want to use the categorical features as well! Thus, we have to perform OneHotEncoding for the...
0
2016-10-16T07:48:17Z
40,068,444
<p>I guess you may use <a href="http://scikit-learn.org/" rel="nofollow">scikit-learn</a> for data train, here is one-hot encoder example in <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow">it</a>:</p> <pre><code>from sklearn.preprocessing import OneHot...
1
2016-10-16T08:36:39Z
[ "python", "scikit-learn", "jupyter", "jupyter-notebook" ]
Stuck in Python with **kwargs
40,068,137
<p>I need to create a function with <code>**kwargs</code>, which should double the numeric values in my dictionary. Only numeric values!</p> <p>My code looks like this:</p> <pre><code>fmm= {'zbk': 30, 'moartea': 78, 'Cox': 'sweet', 'fanina': 'Alex', 'rex': 24 } def my_func(**k...
0
2016-10-16T07:53:56Z
40,068,186
<p>One way to do this:</p> <pre><code>fmm= {'zbk': 30, 'moartea': 78, 'Cox': 'sweet', 'fanina': 'Alex', 'rex': 24 } def my_func(**kwargs): for k,v in kwargs.items(): if isinstance(v,int) or isinstance(v,float): kwargs[k] *= 2 return kwargs fmm = my...
3
2016-10-16T07:59:00Z
[ "python" ]
Stuck in Python with **kwargs
40,068,137
<p>I need to create a function with <code>**kwargs</code>, which should double the numeric values in my dictionary. Only numeric values!</p> <p>My code looks like this:</p> <pre><code>fmm= {'zbk': 30, 'moartea': 78, 'Cox': 'sweet', 'fanina': 'Alex', 'rex': 24 } def my_func(**k...
0
2016-10-16T07:53:56Z
40,068,211
<p>Why the double pointer? You can do perfectly without it too.</p> <pre><code>fmm= {'zbk': 30, 'moartea': 78, 'Cox': 'sweet', 'fanina': 'Alex', 'rex': 24 } def my_func(): for k,v in fmm.items(): print(v*2) my_func() </code></pre>
1
2016-10-16T08:02:52Z
[ "python" ]
Pyinstaller tells me he created the .exe file but I can't find it
40,068,197
<p>Well basically i did this:</p> <pre><code>pyinstaller --onefile --name=OrdnerErstellen --windowed "filepath" </code></pre> <p>And it worked out but then I copied the Path where my .exe file should be and my PC couldn't find the file. Does somebody know why? It also didn't even create the dist folder where all thes...
0
2016-10-16T08:00:51Z
40,068,418
<p>Simple navigate to the folder where you kept <strong>your_script.py</strong> file , From there run on console <strong>pyinstaller --onefile your_script.py</strong></p>
0
2016-10-16T08:33:18Z
[ "python", "python-3.5", "pyinstaller" ]
Django inlineformset - 'CapForm' object has no attribute 'cleaned_data'
40,068,295
<p>I am facing attribute error,</p> <pre><code>'CapForm' object has no attribute 'cleaned_data' </code></pre> <p>This is my post method</p> <pre><code>def post(self,request,*args,**kwargs): user = request.user.id form = SesForm(request.POST,request.FILES,user=request.user) if form.is_valid():...
0
2016-10-16T08:15:10Z
40,068,493
<p>You've called <code>is_valid</code> on SesForm, but not on CapFormSet.</p>
0
2016-10-16T08:42:17Z
[ "python", "django" ]
(Python) How to find the number of occurrences in a list?
40,068,486
<p>Instead of using the .count function, I'm trying to determine the number of times a number input by a user occurs in a list. Appended to the originally empty list are 20 random integers between 1 and 10.</p> <pre><code>import random print() num_list = [] for num in range(20): num_list.append(random.randint(1,...
-4
2016-10-16T08:41:13Z
40,068,517
<p>Yes. </p> <pre><code>counter = 0 for n in list_of_stuff: if n == what_to_count_occurences_of: counter += 1 </code></pre> <p>For non homework uses, use count. </p>
1
2016-10-16T08:46:58Z
[ "python" ]
(Python) How to find the number of occurrences in a list?
40,068,486
<p>Instead of using the .count function, I'm trying to determine the number of times a number input by a user occurs in a list. Appended to the originally empty list are 20 random integers between 1 and 10.</p> <pre><code>import random print() num_list = [] for num in range(20): num_list.append(random.randint(1,...
-4
2016-10-16T08:41:13Z
40,068,522
<p>It is very easy:</p> <pre><code>occurences = 0 for item in num_list: if item == chosen_num: occurences += 1 </code></pre> <p>So the full program looks like this:</p> <pre><code>import random print() num_list = [] for num in range(20): num_list.append(random.randint(1, 10)) chosen_num = eval(inp...
1
2016-10-16T08:48:11Z
[ "python" ]
How to get a specific HTML tags
40,068,542
<p>I'm trying to get a HTML tags if the item has no text.<br> For instance: I am looping through all the "a" attributes(URL).<br> However, some of the URL has text in it and some don't.<br> In this case I'm trying to get the URL for the ones that don't have text on it.<br> Therefore, I did something like this.</p> <pr...
1
2016-10-16T08:50:25Z
40,068,662
<blockquote> <p>I'm trying to get the URL for the ones that don't have text on it</p> </blockquote> <p>You could use list-comprehension</p> <pre><code>hrefs = [a['href'] for a in main_wrapper if a.string is None] </code></pre> <blockquote> <p>get that item specific url only and not all the URL!</p> </blockquote>...
0
2016-10-16T09:07:57Z
[ "python", "parsing", "beautifulsoup" ]
How to get a specific HTML tags
40,068,542
<p>I'm trying to get a HTML tags if the item has no text.<br> For instance: I am looping through all the "a" attributes(URL).<br> However, some of the URL has text in it and some don't.<br> In this case I'm trying to get the URL for the ones that don't have text on it.<br> Therefore, I did something like this.</p> <pr...
1
2016-10-16T08:50:25Z
40,070,732
<p>I presume you are trying to get the unique anchors from the <em>unordered list</em> inside your <em>div</em>. You can see each anchor has a unique class, <code>rel-ink</code> vs <code>rel-name</code>:</p> <pre><code> &lt;a href="//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358" target="_blank" class=...
0
2016-10-16T13:22:00Z
[ "python", "parsing", "beautifulsoup" ]
Python: String slice in pandas DataFrame is a series? I need it to be convertible to int
40,068,572
<p>I have a problem that has kept me up for hours. I need to slice a string variable in a pandas DataFrame and extract an he numerical value (so I can perform a merge). (as a way to provide context, the variables is the result of .groupby ... and now am trying to merge in additional information. </p> <p>Getting the nu...
2
2016-10-16T08:54:56Z
40,068,634
<p>You can't use <code>int(Series)</code> construction (it's similar to <code>int(['1','2','3'])</code>, which also won't work), you should use <code>Series.astype(int)</code> or better <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow">pd.to_numeric(Series)</a> instea...
2
2016-10-16T09:04:15Z
[ "python", "pandas", "dataframe", "type-conversion", "series" ]
Scatter and Hist in one subplot in Python
40,068,605
<p>Here is code</p> <pre><code> df = pd.DataFrame(3 * np.random.rand(4, 2), columns=['a', 'b']) plt.subplot(121) df["a"].plot.box() plt.subplot(122) df.plot.scatter(x="a", y="b") plt.show() </code></pre> <p>Output comes in two different windows as follows:-</p> <p>Figure 1 <a href="https://i.s...
3
2016-10-16T08:59:45Z
40,068,737
<p>You need to specify which axis to draw on when you call <code>scatter</code>. This can be done by passing an <code>ax =</code> argument to the plotting function:</p> <pre><code>df = pd.DataFrame(3 * np.random.rand(4, 2), columns=['a', 'b']) plt.subplot(121) df["a"].plot.box() ax = plt.subplot(122) df.plot.scatter(x...
3
2016-10-16T09:18:29Z
[ "python", "pandas", "matplotlib", "subplot" ]
How to create factory boy with several child
40,068,655
<p>I have two <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/" rel="nofollow">Django models</a> like: </p> <pre><code>class Country(models.Model): country_name = models.CharField(max_length=10) class Resident(models.Model): country = models.ForeignKey('Country') name = models.CharField(...
-1
2016-10-16T09:06:35Z
40,068,700
<p>First write down <code>CountryFactory</code> and <code>ResidentFactory</code> (as described in FactoryBoy documentation). Then write your function:</p> <pre><code>def create_country_with_residents(): country = CountryFactory.create() ResidentFactory.create(country=country, name=Paul, age=33) ResidentFac...
0
2016-10-16T09:13:24Z
[ "python", "django" ]
Nested for Loop optimization in python
40,068,689
<p>i want to optimize 2 for loops into single for loop, is there any way as length of array is very large.</p> <pre><code>A = [1,4,2 6,9,10,80] #length of list is very large B = [] for x in A: for y in A: if x != y: B.append(abs(x-y)) print(B) </code></pre>
-2
2016-10-16T09:11:41Z
40,068,831
<p>not any better but more pythonic:</p> <pre><code>B = [abs(x-y) for x in A for y in A if x!=y] </code></pre> <p>unless you absolutely need duplicates (<code>abs(a-b) == abs(b-a)</code>), you can half your list (and thus computation):</p> <pre><code>B = [abs(A[i]-A[j]) for i in range(len(A)) for j in range(i+1, len...
1
2016-10-16T09:31:57Z
[ "python", "loops", "optimization" ]
How to edit string from STDOUT
40,068,695
<p>I have this code:</p> <pre><code>netshcmd = subprocess.Popen('netsh wlan stop hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) output, errors = netshcmd.communicate() if errors: print("Warrning: ", errors) else: print("Success", output) </code></pre> <p>and output is this: </p> ...
2
2016-10-16T09:11:55Z
40,068,730
<p>Reading from a sub-process gives you a <em>bytestring</em>. You could either decode this bytestring (you'll have to find a suitable encoding), or use the <code>universal_newlines</code> option and have Python automatically decode it for you:</p> <pre><code>netshcmd = subprocess.Popen( 'netsh wlan stop hostednet...
2
2016-10-16T09:17:33Z
[ "python", "subprocess", "netsh" ]
How to edit string from STDOUT
40,068,695
<p>I have this code:</p> <pre><code>netshcmd = subprocess.Popen('netsh wlan stop hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) output, errors = netshcmd.communicate() if errors: print("Warrning: ", errors) else: print("Success", output) </code></pre> <p>and output is this: </p> ...
2
2016-10-16T09:11:55Z
40,068,736
<p>That is a bytestring. Change your code to make that a str:</p> <pre><code>netshcmd = subprocess.Popen('netsh wlan stop hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) output, errors = netshcmd.communicate() if errors: print("Warrning: ", errors.decode()) else: print("Success", ou...
0
2016-10-16T09:18:11Z
[ "python", "subprocess", "netsh" ]
What is proper workflow for insuring "transactional procedures" in case of exceptions
40,068,842
<p>In programming web applications, Django in particular, sometimes we have a set of actions that must all succeed or all fail (in order to insure a predictable state of some sort). Now obviously, when we are working with the database, we can use transactions.</p> <p>But in some circumstances, these (all or nothing) c...
0
2016-10-16T09:33:23Z
40,071,369
<p>We use microservices in our company and at least once a month, we have one of our microservices down for a while. We have <code>Transaction</code> model for the payment process and statuses for every step that go before we send a product to the user. If something goes wrong or one of the connected microservices is d...
1
2016-10-16T14:23:50Z
[ "python", "django", "exception", "transactions" ]
Unique Data Uplload in Python Excel
40,068,892
<p>In New API(Python-Odo o) I Successfully upload Excel File.</p> <p>But if second time i upload same file Data are Duplicated. So How I upload only Unique Data.</p> <p>If No Change in Excel file no changes in recored</p> <p>But if Change in Data this only recored updated reaming recored same as upload.</p> <p>Tha...
0
2016-10-16T09:40:25Z
40,134,328
<p>For that you need atleast one field to identify the record to check the duplicacy.</p>
0
2016-10-19T14:29:50Z
[ "python", "openerp", "odoo-8" ]