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
sequence
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 </code></pre> <p>But i dont know how to plot such that x-axis is the id (1,2) and y axis as the mean values (20,45). </p> <p>The below code made the mean to be the x-axis (should be on y-axis) while the y-axis is only until 1 (should be 2 and should be the x-axis). </p> <pre><code>df.groupby(['id'])['cost'].mean().hist() </code></pre> <p><a href="https://i.stack.imgur.com/tpP7j.png" rel="nofollow"><img src="https://i.stack.imgur.com/tpP7j.png" alt="enter image description here"></a></p>
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 cost 0 1 10 1 1 20 2 1 30 3 2 40 4 2 50 </code></pre>
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 with:</p> <pre><code>import tweepy import time auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) for follower in tweepy.Cursor(api.search, q="#kenbone").items(): api.create_friendship(screen_name = follower) print(follower) </code></pre>
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_friendship(screen_name = follower.screen_name) </code></pre>
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 the same positions,</p></li> <li><p>but if it checked <code>'hello'</code> and <code>'fires'</code> it would output <code>0</code> because although it has a common letter, it is not at the same position in each string. </p></li> </ol> <p>How would I achieve this?</p>
-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, string2)) </code></pre> <hr> <h3>Let's break this down:</h3> <pre><code>zip(string1, string) </code></pre> <p>This creates a series of tuples with paired items from each of the inputs, for instance with <code>hello</code> and <code>heron</code> it looks like this: <code>[('h', 'h'), ('e', 'e'), ('l', 'r'), ('l', 'o'), ('o', 'n')]</code>.</p> <pre><code>for c1, c2 in </code></pre> <p>We're using a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> to iterate over these tuples, assigning each of the two elements to a variable.</p> <pre><code>1 if c1 == c2 else 0 </code></pre> <p>We're going to emit a sequence of 1s and 0s, where the number of 1s is equal to the number of cases where the equivalent position characters were equal.</p> <pre><code>sum() </code></pre> <p>Finally, we sum the emitted sequence of 1s and 0s - effectively counting the total number of equal characters.</p> <p>You can even shorten this a bit, because in Python you can treat boolean values <code>True</code> and <code>False</code> as <code>1</code> and <code>0</code> respectively, which leads to the second form above.</p> <p>You might wonder: what happens if <code>string1</code> and <code>string2</code> are different lengths? This expression will actually still work, because <code>zip()</code> will stop as soon as it reaches the end of either. Since by definition the extra characters in the longer string will not be equal to the lack of characters in the shorter, this doesn't affect the count.</p>
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://tsaith.github.io/install-opencv-3-for-python-3-on-osx.html" rel="nofollow">Install OpenCV 3 for Python 3 on OSX</a></p>
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, root): self.root = root self.root.resizable(0, 0) self.root.grid_columnconfigure(0, weight=1) self.root.grid_columnconfigure(1, weight=3) self.init_widgets() self.arrange_grid() def init_widgets(self): self.text_frame = ttk.Labelframe(self.root, text='Info') self.button = ttk.Button(self.root, text='Process', command=self.on_button) self.tree = ttk.Treeview(self.root) self.scroll = ttk.Scrollbar(self.root, orient=HORIZONTAL, command=self.tree.xview) self.tree.configure(xscrollcommand=self.scroll.set) def arrange_grid(self): self.text_frame.grid(row=0, sticky=NSEW) self.button.grid(row=0, sticky=N, pady=32) self.tree.grid(row=0, column=1, sticky=NSEW) self.scroll.grid(row=0, column=1, sticky=(S, W, E)) def on_button(self): headers = list(range(20)) rows = [[randint(0, 100)] * len(headers) for i in headers] self.tree["columns"] = headers for i, row in enumerate(rows): self.tree.insert("", i, values=row) if __name__ == '__main__': root = tk.Tk() app = Application(root) root.mainloop() </code></pre> <p>When I click on a "Process" button, tree view is populated with data, but at the same time it resizes the root window and fills whole space.</p> <p>How can I instruct ttk tree view, to remain it's size after populating with data?</p>
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 its growth.</p> <p>There are several solutions. Perhaps the simplest solution is to put the tree in a frame so that you can give it an explicit width and height. The key to this is to make the frame control the size of its children rather than the other way around. This is done by turning <em>geometry propagation</em> off. </p> <p>First, start by creating a frame, and then putting the tree in the frame. We can also put the scrollbar in the frame so that we can treat the tree and scrollbar as a single unit.</p> <pre><code>self.tree_frame = tk.Frame(self.root, width=400, height=200) self.tree = ttk.Treeview(self.treeframe) self.scroll = ttk.Scrollbar(self.tree_frame, orient=HORIZONTAL, command=self.tree.xview) self.tree.configure(xscrollcommand=self.scroll.set) </code></pre> <p>Next, add the treeview and scrollbar to the frame. You can use any of <code>pack</code>, <code>place</code> or <code>grid</code>; I find <code>pack</code> superior for a top-to-bottom layout. We also use <code>pack_propagate</code> to turn off geometry propagation (meaning: the frame width and height are honored):</p> <pre><code>self.tree_frame.pack_propagate(0) self.scroll.pack(side="bottom", fill="x") self.tree.pack(side="top", fill="both", expand=True) </code></pre> <p>With that, you need to modify your <code>arrange_grid</code> to put the frame in the root window, and then ignore the scrollbar since it's already packed in the frame:</p> <pre><code>def arrange_grid(self): self.text_frame.grid(row=0, sticky=NSEW) self.button.grid(row=0, sticky=N, pady=32) self.tree_frame.grid(row=0, column=1, sticky=NSEW) </code></pre> <hr> <p>Note: you've turned off the ability for the user to resize the window. I recommend avoiding this -- the user usually knows better what size they want the window. Instead, you should configure your GUI to properly resize when the user resizes the window.</p> <p>Since you're using <code>grid</code>, all you have to do is tell tkinter which rows and columns get any extra space caused by the user resizing the window. Since everything is in a single row, you merely need to give that row a weight:</p> <pre><code>root.grid_rowconfigure(0, weight=1) </code></pre>
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-info" methods=["link", "post"] class="valve-box"&gt; {% for valve in valve_list %} &lt;li&gt; &lt;b&gt;Name/Model:&lt;/b&gt; {{ valve['item_name'] }}&lt;br&gt; &lt;b&gt;Price:&lt;/b&gt; {{ valve['item_price'] }}$ &lt;input type="submit" value="Go to info page"/&gt; &lt;/li&gt; {% endfor %} &lt;/form&gt; {% endblock %} </code></pre> <p>This on html is basically a verticle list of items. When i'm interested in an item, I press the button next to the item, and the routes file in my folder will takes me to the product-info page.</p> <p>Below is html code for my product info page:</p> <pre><code>{% extends "base-template.html" %} {% block content %} &lt;h1&gt;Information&lt;/h1&gt; &lt;form class="valve-box"&gt; {% for valve in valve_list %} &lt;li&gt; &lt;b&gt;Item ID:&lt;/b&gt; {{ valve['item_id'] }}&lt;br&gt; &lt;b&gt;Name/Model:&lt;/b&gt; {{ valve['item_name'] }}&lt;br&gt; &lt;b&gt;Description:&lt;/b&gt; {{ valve['description'] }}&lt;br&gt; &lt;b&gt;Price:&lt;/b&gt; {{ valve['item_price'] }}$ &lt;/li&gt; {% endfor %} &lt;/form&gt; {% endblock %} </code></pre> <p>The problem is i need a interactive product info page that only shows information of the product that the user was interested and pressed on. How can i do that?</p>
-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'] }}&lt;br&gt; &lt;b&gt;Name/Model:&lt;/b&gt; {{ valve['item_name'] }}&lt;br&gt; &lt;b&gt;Description:&lt;/b&gt; {{ valve['description'] }}&lt;br&gt; &lt;b&gt;Price:&lt;/b&gt; {{ valve['item_price'] }}$ &lt;a href='{{ url_for("show_valve", valve_id=valve["item_id"]) }}'&gt;Show detail&lt;/a&gt; &lt;/li&gt; {% endfor %} &lt;!-- the rest of your HTML --&gt; </code></pre> <p>Your new function in the Python file will accept the ID sent by your template, and you can then build a page just for that item. Here's an example of what I'm thinking for your new function in the Python code:</p> <pre><code>@app.route('whatever/address/you/want') def show_valve(valve_id): # get your list of valves from wherever it comes from for valve in valves: if valve["item_id"] == valve_id: target_valve = valve break return render_template('showValveDetail.html', valve=target_valve) </code></pre>
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 corresponding degree. I would like to make 1 plot for each function showing the convergence of the approximations to that function. I know one way to do it is to break the data frame into separate data frames based on the first column name, but wanted to know if there was a more elegant way to do it.</p> <p>Edit for clarification: So in the data frame, there are two unrelated functions, say a and b. The second column contains the x values, then third and fourth are functions of x. So it might look like </p> <pre><code> fnctn x y1 y2 0 a 1 2 3 1 a 2 3 2 2 a 3 4 3 3 a 4 3 4 4 a 5 2 3 5 b 1 1 2 6 b 2 4 6 7 b 3 9 12 8 b 4 16 20 9 b 5 25 30 </code></pre> <p>I would want a plot of y1 and y2 where the first column is <em>a</em> on one plot, and on another plot y1 and y2 where the first column is <em>b</em></p>
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 b 3 2 2 for f in set(df['fnctn']): df[df['fnctn']==f].plot(x='x') </code></pre> <p><a href="https://i.stack.imgur.com/Rpkgo.png" rel="nofollow"><img src="https://i.stack.imgur.com/Rpkgo.png" alt="a"></a> <a href="https://i.stack.imgur.com/dAqiC.png" rel="nofollow"><img src="https://i.stack.imgur.com/dAqiC.png" alt="b"></a></p>
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.metadata.create_all(engine) File "/usr/lib/python2.7/dist-packages/sqlalchemy/schema.py", line 2848, in create_all tables=tables) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1479, in _run_visitor conn._run_visitor(visitorcallable, element, **kwargs) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1122, in _run_visitor **kwargs).traverse_single(element) File "/usr/lib/python2.7/dist-packages/sqlalchemy/sql/visitors.py", line 122, in traverse_single return meth(obj, **kw) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/ddl.py", line 57, in visit_metadata if self._can_create_table(t)] File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/ddl.py", line 35, in _can_create_table table.name, schema=table.schema) File "/usr/lib/python2.7/dist-packages/sqlalchemy/dialects/sqlite/base.py", line 722, in has_table cursor = _pragma_cursor(connection.execute(statement)) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 662, in execute params) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 805, in _execute_text statement, parameters File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 874, in _execute_context context) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1024, in _handle_dbapi_exception exc_info File "/usr/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 196, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 867, in _execute_context context) File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 324, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.DatabaseError: (DatabaseError) database disk image is malformed 'PRAGMA table_info("users")' () </code></pre> <p>i was looking at it i didnt really understand what the error was saying</p> <p>Here is the code that i have for creating my database which was not getting error and the server setup file which is where my server would hold.</p> <pre><code>from flask import Flaskfrom sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from setup_database import Base, Users, User_Auth, User_info, User_Location # The following line is what initiates the flask app for this project app = Flask(__name__) engine = create_engine('sqlite:///payup.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() @app.route('/') def HomePage(): output = "&lt;h1&gt;hello&lt;/h1&gt;" @app.route('/users') def UsersList(users.id): output = "&lt;h1&gt;This page will list all of the current users&lt;/h1&gt;" @app.route('/adduser') def CreateNewUser(users): output = "&lt;h1&gt;This page will be able to create new users&lt;/h1&gt;" @app.route('/manageUsers') def ManageUsers(users.id): output = "&lt;h1&gt;This page will be able to manage all of the users&lt;/h1&gt;" @app.route('/userProfile') def UsersProfile(all of the tables): output = "&lt;h1&gt;This page will display all of the users informaiton &lt;/h1&gt;" if __name__ == '__main__': app.debug = True app.run(host = '0.0.0.0', port = 5555) </code></pre>
-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 possibly corrupt SQLite database file should help you to get your script to run without errors. Upon successful execution (and server start), a new SQLite database file should have been created automatically by SQLAlchemy.</p>
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 orange3 </code></pre>
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 desired l_colors=["pink","blue"] if (l_bar_dir=="vertical"): plt.bar(xs2,ys,tick_label=xs,color=l_colors,bottom=bottoms,width=bar_width,align='center') # set plot to be a bar graph else: plt.barh(bottom=xs2,width=ys,tick_label=xs,align='center',color=l_colors) # set plot to be a bar graph </code></pre>
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</code> in the form of a bar plot. Here is a rather crude function that could be used to make basic bar plots using images, using your idea of flags as the images.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.misc import imread def image_plot(heights, images, spacing=0): # Iterate through images and data, autoscaling the width to # the aspect ratio of the image for i, (height, img) in enumerate(zip(heights, images)): AR = img.shape[1] / img.shape[0] width = height * AR left = width*i + spacing*i right = left + width plt.imshow(img, extent=[left, right, 0, height]) # Set x,y limits on plot window plt.xlim(0, right) plt.ylim(0, max(heights)*1.1) # Read in flag images usa_flag = imread('american_flag.png') aussie_flag = imread('australian_flag.png').swapaxes(0, 1) turkish_flag = imread('turkish_flag.png').swapaxes(0, 1) # Make up some data about each country usa_data = 33 aussie_data = 36 turkish_data = 27 data = [usa_data, aussie_data, turkish_data] flags = [usa_flag, aussie_flag, turkish_flag] image_plot(data, flags, spacing=2) </code></pre> <p>Without doing anything fancy to the <code>x</code> and <code>y</code> axes, returns this plot.</p> <p><a href="https://i.stack.imgur.com/mAOL4.png" rel="nofollow"><img src="https://i.stack.imgur.com/mAOL4.png" alt="enter image description here"></a></p>
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): for sixth in range(10): print(first,chr(second),third,fourth,chr(fifth),sixth) </code></pre>
-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 third in range(10): for fourth in range(10): for fifth in range(65,91): for sixth in range(10): print('{}{}{}{}{}{}'.format(first,chr(second),third,fourth,chr(fifth),sixth)) </code></pre>
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 library.</p>
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 library.</p>
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 content and return clean data in <code>clean_data</code> variable.</p>
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>users must be able to join several organizations</li> <li>users must be able to create organizations and therefore be owners of multiple organizations</li> </ul> <p>So far I've got the following models.py:</p> <pre><code>from django.db import models from django.utils.translation import ugettext_lazy as _ from myapp.users.models import User class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Org(TimeStampedModel): name = models.CharField( _('Organization name'), max_length=255, ) owner = models.OneToOneField('OrgOwner') members = models.ManyToManyField( 'OrgMember', related_name='organization_members' ) users = models.ManyToManyField( User, related_name='organization_users' ) def __str__(self): return self.name class OrgMember(TimeStampedModel): user = models.ForeignKey( User, related_name='user_profile' ) organization = models.ForeignKey( Org, related_name='member_organization' ) def __str__(self): return self.user.username class OrgOwner(TimeStampedModel): member = models.OneToOneField(OrgMember) organization = models.OneToOneField(Org) def __str__(self): return self.member.__str__() </code></pre> <p>My issue is that the way I've designed the models so far, I have a circular dependency. In order for a user to create an Org from scratch he needs to be an OrgMember of said, not yet created, Org. In other words, I cannot instantiate an OrgMember without assigning it an Org, but I cannot instantiate a new Org without an OrgOwner, for which I also need an OrgMember. </p> <p>I'm sure there is just an error in my reasoning here. But perhaps there are some best practices for situations like this one you could share. There is probably a fairly simple solution to this, but I haven't been able to find one in an hour of searching and reading the django docs. Any help is much appreciated!</p>
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 points to an <code>Org</code> as well. Both of those classes only have two fields - the <code>User</code> associated with it, and then the <code>Org</code>. Unless there are more fields, they serve no purpose - the same thing can be accomplished in one model:</p> <pre><code>class Org(TimeStampedModel): name = models.CharField(_('Organization name'), max_length=255) # Only one owner, but each User can own more than one org owner = models.ForeignKey('auth.User', related_name='owned_orgs') members = models.ManyToManyField('auth.User', related_name='organization_members') users = models.ManyToManyField(User, related_name='organization_users') def __str__(self): return self.name </code></pre> <p>I'd recommend that you do some more reading <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#module-django.db.models.fields.related" rel="nofollow">about Django's relationship fields</a></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 the screen inp = input("Enter your choice from the menu: \n1) To find your external IP address\n2) To check domain name whois information\n3) To check if the website or ip address is up\n") if (inp == "1"): print("Your external ip address is: ") # me trying to be smart XD ip = os.system("dig +short myip.opendns.com @resolver1.opendns.com") #print("Your external ip address is: %d" % ip) elif (inp == "2"): domain = input("Enter the domain you want to whois it: \n") info = os.system("whois %s" % domain) print(info) elif (inp == "3"): target = input("Enter the url or ip address you want to check:\n") for x in range(3): response = os.system("ping %s" % target) if (response == 1): # how can I decide based on response result ? print("%s is up" % target) else: print("%s is down" % target) </code></pre>
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 printed the value of cut it returned <code>kdfjsalsdjf</code>, showing the newlines code had been removed</p> <pre><code>x='lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf' for i in x: if i=='\n': cut=x.index(i) x=x[cut+2:] Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 3, in &lt;module&gt; cut=x.index(i) ValueError: substring not found </code></pre>
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 printed the value of cut it returned <code>kdfjsalsdjf</code>, showing the newlines code had been removed</p> <pre><code>x='lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf' for i in x: if i=='\n': cut=x.index(i) x=x[cut+2:] Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 3, in &lt;module&gt; cut=x.index(i) ValueError: substring not found </code></pre>
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 of how <code>str.__iter__</code> works, and that therefore, changes you make to <code>x</code> within the for-loop are not reflected in future iterations of the for-loop.</p> <p>You can fix this with a while-loop instead:</p> <pre><code>i = 0 while &lt; len(x): if x[i] == '\n': x = x[i+2 :] i = -1 i += 1 </code></pre> <p>This is a bit convoluted, as it seems that you want to find the last occurrence of <code>'\n'</code>, and take whatever's 2 characters after it. So you could do this:</p> <pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf' inds = [] for i,char in enumerate(x): if char=='\n': inds.append(i) if not inds: # '\n' was nowhere in the string x = x # we don't have to make any changes else: max_ind = max(inds) x = x[max_ind+2 :] </code></pre> <p>Now, let's shorten this:</p> <pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf' inds = [i for i,char in enumerate(x) if char=='\n'] max_ind = max(inds)+2 if inds else -2 x = x[max_ind :] </code></pre> <p>Or:</p> <pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf' try: max_ind = x.rindex('\n') x = x[max_ind+2 :] except ValueError: pass </code></pre>
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 this view, map it to a URLconf def index(request): # When a request is called, return my index.html html = codecs.open("index.html", "r") return HttpResponse(html.read()) </code></pre> <p>When I fire up the Django dev. server and navigate to my app, instead of the rendering of <code>index.html</code> that I expect, I am confronted with a <code>FileNotFoundError at /myapp/</code> as well as <code>[Errno 2] No such file or directory: 'index.html'</code>. I know for a fact that <code>index.html</code> is a real file in the same directory as my<code>views.py</code>, and I have also tried debugging by opening a <code>debug.txt</code> in the same directory and returning that, but with the same result. When I open the python shell in the same directory and try to open the same file, it works without a hitch. Any insight would be appreciated, as I am thouroughly stumped.</p>
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 error: <code>RecursionError: maximum recursion depth exceeded while getting the repr of a list</code> and although I understand the sort of thing that could be causing this, I have no idea how this applies to this situation as I'm not explicitly using recursion. How am I able to remedy this error? How can I understand the problem better as well?</p> <p>(topLat, bottomLat, westLong, eastLong are the lats and longs for the first and last point in the grid/map to identify points at the edge of the map)</p> <pre><code>def buildNeighbours(point, dataset): neighbours = [] ix = int(point[3]) if point[0] != topLat and point[0] != bottomLat and point[1] != westLong and point[1] != eastLong: nw = dataset[ix - (rowLength + 1)] n = dataset[ix - rowLength] ne = dataset[ix - (rowLength - 1)] e = dataset[ix + 1] se = dataset[ix + (rowLength + 1)] s = dataset[ix + rowLength] sw = dataset[ix + (rowLength - 1)] w = dataset[ix - 1] neighbours = [nw, n, ne, e, se, s, sw, w] point.append(neighbours) else: point = [] return point for point in dataList: point = buildNeighbours(point, dataList) print(dataList[2000]) </code></pre>
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 of which is the original point. And so it continues...</p> <p><code>list</code>'s <code>__repr__</code> attempts to limit recursive cases, eventually giving up and returning <code>'...'</code>. Assuming it uses the same defaults as <a href="https://docs.python.org/3/library/reprlib.html#repr-objects" rel="nofollow"><code>reprlib.Repr</code> objects</a>, the <code>maxlevel</code> (max recursion depth) is 6. With 8 neighbors each, that could mean thousands of visits to a relatively small number of unique points.</p> <p>I was able to print a 3&times;3 grid, where the fan-out is limited because most of the points only have 3 or 5 neighbors (corners and sides). My simplified <code>point</code> lists, which didn't contain altitude or land/sea elements, required about 700kiB to represent the whole grid... about 40KiB for the upper-left corner alone. On a 4&times;4 grid, a single point ballooned up to about 16MiB.</p> <p>That said, I'm guessing what your inputs look like, and I probably haven't reproduced what you're really doing. More importantly, I did <em>not</em> get a <code>RecursionError</code> like you did, perhaps because I gave up waiting for it.</p> <p>With those caveats in mind, I suggest:</p> <ul> <li><p>In each point's <code>neighbors</code> list, store the <em>indices</em> of the neighbors. Look them up later whenever you need them. (This is the simplest solution I could come up with.) Write a couple helper functions that calculate the northwest or south or whatever neighbor of a given index, since you'll be doing that a lot.</p></li> <li><p>Alternatively, consider creating a <code>neighbors</code> dictionary, mapping each point's index to a list of indices. You'd have to keep that dictionary alongside <code>dataList</code> at all times, but it would let you remove the list of neighbors from all of your points.</p></li> <li><p>If you really have to store the neighbors themselves, create a <code>Point</code> class with custom <code>__str__</code> and <code>__repr__</code> methods that don't try to print the neighbors. As a bonus, a class would let you refer to fields with names like <code>lat</code>, <code>lng</code>, and <code>index</code> instead of mysterious subscripts like <code>[1]</code> and <code>[3]</code>.</p></li> </ul>
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;&lt;?php echo "title here"; ?&gt;&lt;/title&gt; &lt;head&gt; &lt;body&gt; &lt;h1 &lt;?php echo "class='big'" ?&gt;&gt;foo&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>and I need place my own text (for example: MY_TEXT) after opened tag and get this result:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;?php echo "title here"; ?&gt;&lt;/title&gt; &lt;head&gt; &lt;body&gt; &lt;h1 &lt;?php echo "class='big'" ?&gt;&gt;MY_TEXTfoo&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>thus I need consider nested braces</p> <p>if I will use regex it will creates problems (I need consider any level of nested braces). I need another strategy.</p> <p>now my idea try to use pyparsing, but I can't get it now, too complicated for my current level</p> <p>could anybody make solution please?</p>
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;') </code></pre> <p>However, this will match <em>every</em> tag in your input HTML source:</p> <pre><code>for match in nested_angle_braces.searchString(html): print match </code></pre> <p>gives:</p> <pre><code>[['html']] [['head']] [['title']] [['?php', 'echo', '"title here"', ';', '?']] [['/title']] [['head']] [['body']] [['h1', ['?php', 'echo', '"class=\'big\'"', '?']]] [['/h1']] [['/body']] [['/html']] </code></pre> <p>You want to match <em>only</em> those tags whose opening text is 'h1'. We can add a condition to an expression in pyparsing using <code>addCondition</code>:</p> <pre><code>nested_angle_braces_with_h1 = nested_angle_braces().addCondition( lambda tokens: tokens[0][0].lower() == 'h1') </code></pre> <p>Now we will match only the desired tag. Just a few more steps...</p> <p>First of all, <code>nestedExpr</code> gives back nested lists of matched items. We want the original text that was matched. Pyparsing includes another helper for that, unimaginatively named <code>originalTextFor</code> - we combine this with the previous definition to get:</p> <pre><code>nested_angle_braces_with_h1 = originalTextFor( nested_angle_braces().addCondition(lambda tokens: tokens[0][0].lower() == 'h1') ) </code></pre> <p>Lastly, we have to add one more parse-time callback action, to append "MY_TEXT" to the tag:</p> <pre><code>nested_angle_braces_with_h1.addParseAction(lambda tokens: tokens[0] + 'MY_TEXT') </code></pre> <p>Now that we are able to match the desired <code>&lt;h1&gt;</code> tag, we can use <code>transformString</code> method of the expression to do the search-and-replace work for us:</p> <pre><code>print(nested_angle_braces_with_h1.transformString(html)) </code></pre> <p>With your original sample saved as a variable named <code>html</code>, we get:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;?php echo "title here"; ?&gt;&lt;/title&gt; &lt;head&gt; &lt;body&gt; &lt;h1 &lt;?php echo "class='big'" ?&gt;&gt;MY_TEXTfoo&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note: this will add "MY_TEXT" after <em>every</em> <code>&lt;h1&gt;</code> tag. If you want this to be applied <em>only</em> after <code>&lt;h1&gt;</code> tags containing PHP, then write the appropriate condition and add it to <code>nested_angle_braces_with_h1</code>.</p>
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>What do I have to do there? If I run the code like that it just prints the whole list with the variable name and everything.</p>
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 href="https://docs.python.org/3/tutorial/modules.html#modules" rel="nofollow">6. Modules</a> for the typical use cases.</p> <p>Assuming you'll always be running your script from the same directory:</p> <pre><code>import Trivia.fact do_something_with(Trivia.fact.facts) </code></pre> <p>Or, if you're only going to use that one value:</p> <pre><code>from Trivia.fact import facts do_something_with(facts) </code></pre> <p>If you want to install all of this as a package so you can run it from anywhere, you will also have to learn about <a href="https://docs.python.org/3/reference/import.html#packages" rel="nofollow">packages</a>, and maybe the <a href="https://docs.python.org/3/glossary.html#term-import-path" rel="nofollow">import path</a>, but don't worry about that until it's clear you need it.</p> <hr> <p>All this assumes there's some advantage to storing your data in a Python file --- like it's a list of objects that took a bit of work to initialize. If it's just "raw" data like strings, then a plain text file with one string per line might be the way to go... and you'd be back to using <code>open</code> and probably <a href="https://docs.python.org/3/library/io.html#io.IOBase.readlines" rel="nofollow"><code>readlines</code></a> or <code>for line in ...:</code>.</p> <p>"Nearly-raw" data like tables, dictionaries of numbers and strings, or lists of lists can be read and written with either the <a href="https://docs.python.org/3/library/json.html" rel="nofollow"><code>json</code></a> or <a href="https://docs.python.org/3/library/csv.html#examples" rel="nofollow"><code>csv</code></a> modules, depending on how complex your data is and which format you're more comfortable with.</p>
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 public attribute and is therefore usable by any user of the class however they like, similar to just modifying the non-public attribute I'm hiding behind the property directly and bypassing any checks I might have created, such as restricting an RGB component's value to the range 0..255.</p> <p>This would be a bad idea according to PEP 8 if the property name began with an underscore, but it doesn't, making it OK to delete or modify the property in some way. This is the exact sort of thing that properties are meant to prevent, but by deleting or otherwise changing the property, people can override my behavior like shown above.</p> <p>That leads me to my question: should I just use a non-public validating setter method inside the class and simply use it as the property setter, or should I use a public setter method because validation of new values for a non-public attribute isn't an intended use of properties? I'm trying to avoid code duplication, so those are really my only two options for allowing user access while also validating the value in the case of a property setter or setter method.</p> <p>Does anybody have any experience with this sort of issue? How did you resolve it, if you did?</p>
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 not imply that a user of a class can just do whatever they want with its attributes, whether that's replacing their values, altering them in place, or even deleting them. That naturally goes for properties, too, which are class attributes.</p> <p>I'll leave this unanswered for a while, but I'm fairly certain this attitude is the right way to approach this "problem".</p>
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 element in the set is identical to itself.</li> </ol> <p>Output:</p> <pre><code> Set2 CGCG Set4 AT-T Set5 CATC </code></pre> <ol start="2"> <li><p>Perform pairwise comparison between the sets. (Set2 v Set4, Set 2v Set5, Set4 v Set5)</p></li> <li><p>Each pairwise comparison can have only two types of combinations, if not then those pairwise comparisons are eliminated. eg,</p> <pre><code>Set2 Set5 C C G A C T G C </code></pre></li> </ol> <p>Here, there are more than two types of pairs (CC), (GA), (CT) and (GC). So this pairwise comparison cannot occur. </p> <p>Every comparison can have only 2 combinations out of (AA, GG,CC,TT, AT,TA,AC,CA,AG,GA,GC,CG,GT,TG,CT,TC) ... basically all possible combinations of ACGT where order matters. </p> <p>In the given example, more than 2 such combinations are found. </p> <p>Hence, Set2 and Set4; Set4 and Set5 cannot be considered.Thus the only pairs, that remain are:</p> <pre><code>Output Set2 CGCG Set4 AT-T </code></pre> <ol start="4"> <li><p>In this pairwise comparison, remove any the element with "-" and its corresponding element in the other pair</p> <pre><code>Output Set2 CGG Set4 ATT </code></pre></li> <li><p>Calculate frequency of elements in Set2 and Set4. Calculate frequency of occurrence of types of pairs across the Sets (CA and GT pairs)</p> <pre><code>Output Set2 (C = 1/3, G = 2/3) Set4 (A = 1/3, T = 2/3) Pairs (CA = 1/3, GT = 2/3) </code></pre></li> <li><p>Calculate float(a) = (Pairs) - (Set2) * (Set4) for corresponding element (any one pair is sufficient)</p> <pre><code>eg. For CA pairs, float (a) = (freq of CA pairs) - (freq of C) * (freq of A) </code></pre></li> </ol> <p>NOTE: If the pair is AAAC and CCCA, the freq of C would it be 1/4, i.e. it is the frequency of the base over one of the pairs</p> <ol start="7"> <li><p>Calculate </p> <pre><code>float (b) = float(a)/ (freq of C in CGG) * (freq G in CGG) * (freq A in ATT) * (ATT==&gt; freq of T in ATT) </code></pre></li> <li><p>Repeat this for all pairwise comparisons</p></li> </ol> <p>eg. </p> <pre><code>Set2 CGCG Set4 AT-T Set6 GCGC </code></pre> <p>Set2 v Set4, Set2 v Set6, Set4 v Set6</p> <p>My half-baked code till now: ** I would prefer if all codes suggested would be in standard for-loop format and not comprehensions **</p> <pre><code>#Step 1 for i in sample: for j in range(i): if j = j+1 #This needs to be corrected to if all elements in i identical to each other i.e. if all "j's" are the same del i #insert line of code where sample1 = new sample with deletions as above #Step 2 for i,i+1 in enumerate(sample): #Step 3 for j in range(i): for k in range (i+1): #insert line of code to say only two types of pairs can be included, if yes continue else skip #Step 4 if j = "-" or k = "-": #Delete j/k and the corresponding element in the other pair #Step 5 count_dict = {} square_dict = {} for base in list(i): if base in count_dict: count_dict[base] += 1 else: count_dict[base] = 1 for allele in count_dict: freq = (count_dict[allele] / len(i)) #frequencies of individual alleles #Calculate frequency of pairs #Step 6 No code yet </code></pre>
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 indexB, setB in enumerate(sample): # Don't compare samples with themselves nor compare same pair twice. if indexA &lt;= indexB: continue # Calculate number of unique pairs pair_count = Counter() for pair in zip(setA, setB): if '-' not in pair: pair_count[pair] += 1 # Only analyse pairs of sets with 2 unique pairs. if len(pair_count) != 2: continue # Count individual bases. base_counter = Counter() for pair, count in pair_count.items(): base_counter[pair[0]] += count base_counter[pair[1]] += count # Get the length of one of each item in the pair. sequence_length = sum(pair_count.values()) # Convert counts to frequencies. base_freq = {} for base, count in base_counter.items(): base_freq[base] = count / float(sequence_length) # Examine a pair from the two unique pairs to calculate float_a. pair = list(pair_count)[0] float_a = (pair_count[pair] / float(sequence_length)) - base_freq[pair[0]] * base_freq[pair[1]] # Step 7! float_b = float_a / float(base_freq.get('A', 0) * base_freq.get('T', 0) * base_freq.get('C', 0) * base_freq.get('G', 0)) </code></pre> <p>Or, more Pythonically (with the list/dict comprehensions you don't want):</p> <pre><code>from collections import Counter BASES = 'ATCG' # Remove elements where all nucleobases are the same. sample = [item for item in sample if item[:1] * len(item) != item] for indexA, setA in enumerate(sample): for indexB, setB in enumerate(sample): # Don't compare samples with themselves nor compare same pair twice. if indexA &lt;= indexB: continue # Calculate number of unique pairs relevant_pairs = [(elA, elB) for (elA, elB) in zip(setA, setB) if elA != '-' and elB != '-'] pair_count = Counter(relevant_pairs) # Only analyse pairs of sets with 2 unique pairs. if len(pair_count) != 2: continue # setA and setB as tuples with pairs involving '-' removed. setA, setB = zip(*relevant_pairs) # Get the total for each base. seq_length = len(setA) # Convert counts to frequencies. base_freq = {base : count / float(seq_length) for (base, count) in (Counter(setA) + Counter(setB)).items()} # Examine a pair from the two unique pairs to calculate float_a. pair = list(pair_count)[0] float_a = (pair_count[pair] / float(seq_length)) - base_freq[pair[0]] * base_freq[pair[1]] # Step 7! denominator = 1 for base in BASES: denominator *= base_freq.get(base, 0) float_b = float_a / denominator </code></pre>
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 rarest and most common people for each class. My function takes my database name, Collections, as input and I'm trying to get it to return a list with a tuple for each distinct class type and columns with the most and least common person names. This is what I have so far:</p> <pre><code>def rareCommon(){ c.execute('SELECT COUNT(mid) AS Most Common FROM Appearance') } </code></pre> <p>I'm having a lot of trouble with the query due its subquery ish nature. If anyone here could help me out, that would be greatly appreciated.</p>
-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 GROUP BY a.pid) pc GROUP BY pid </code></pre>
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 last <code>href</code> on that page. Here is the output when I print out the final result:</p> <pre><code>[{'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}] </code></pre> <p>I am unsure as to why it's doing the last value only. I assume it's because through the last loop, it assigns all keys with the same name to that value. How can I go around fixing this? Here is the code.</p> <pre><code>import json import requests from bs4 import BeautifulSoup tags_dict = {} tags_list = [] r = requests.get("http://chicosadventures.com/") soup = BeautifulSoup(r.content, "lxml") for link in soup.find_all('a'): tags_dict['link'] = link.get('href') tags_list.append(tags_dict) dump = json.dumps(tags_list) print(dump) </code></pre>
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>import json import requests from bs4 import BeautifulSoup tags_list = [] r = requests.get("http://chicosadventures.com/") soup = BeautifulSoup(r.content, "lxml") for link in soup.find_all('a'): tags_list.append({"link": link.get('href')}) dump = json.dumps(tags_list) print(dump) </code></pre> <p>Output:</p> <blockquote> <p>[{"link": "/"}, {"link": "/about_chico"}, {"link": "/about_the_author"}, {"link": "/about_the_illustrator"}, {"link": "/chico_in_the_news_"}, {"link": "/order_your_copy"}, {"link": "/contact_us"}, {"link": "/about_chico"}, {"link": "/about_the_author"}, {"link": "/about_the_illustrator"}, {"link": "/chico_in_the_news_"}, {"link": "/order_your_copy"}, {"link": "/contact_us"}, {"link": "/privacy"}, {"link": "javascript:print()"}, {"link": "<a href="http://www.ebtech.net/" rel="nofollow">http://www.ebtech.net/</a>"}, {"link": "/terms"}]</p> </blockquote>
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> <p>and I do something on model.py like this:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.template.defaultfilters import slugify class Category(models.Model): name = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True,help_text = 'Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text = 'Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'categories' ordering = ['-created_at'] verbose_name_plural = 'Categories' def __unicode__ (self): return self.name @models.permalink def get_absolute_url(self): return ('catalog_category', (), { 'category_slug': self.slug }) </code></pre> <p>But when I type "những-viên-kẹo" in the Name field of Admin page, the slug field appear "nhng-vien-ko". I don't know something wrong. And when I run a test with:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals vietnamese_map = { ord(u'ư'): 'u', ord(u'ơ'): 'o', ord(u'á'): 'a', ord(u'n'): 'n', ord(u'h'): 'h', ord(u'ữ'): 'u', ord(u'n'): 'n', ord(u'g'): 'g', ord(u'v'): 'v', ord(u'i'): 'i', ord(u'ê'): 'e', ord(u'n'): 'n', ord(u'k'): 'k', ord(u'ẹ'): 'e', ord(u'o'): 'o', } print unicode("những-viên-kẹo").translate(vietnamese_map) </code></pre> <p>It work correctly, and return "nhung-vien-keo"</p> <p>[EDIT]</p> <p>I have try this on my form.py</p> <pre><code>class CategoryAdminForm(forms.ModelForm): class Meta: model = Category exclude = () def clean_slug(self): slug = self.cleaned_data['slug'] vietnamese_map = { ord(u'ư'): 'u', ord(u'ơ'): 'o', ord(u'á'): 'a', ord(u'n'): 'n', ord(u'h'): 'h', ord(u'ữ'): 'u', ord(u'n'): 'n', ord(u'g'): 'g', ord(u'v'): 'v', ord(u'i'): 'i', ord(u'ê'): 'e', ord(u'n'): 'n', ord(u'k'): 'k', ord(u'ẹ'): 'e', ord(u'o'): 'o', } slug = slugify(unicode(slug).translate(vietnamese_map)) return slug </code></pre> <p>And in admin.py</p> <pre><code>class CategoryAdmin(admin.ModelAdmin): form = CategoryAdminForm # sets up values for how admin site lists categories list_display = ('name', 'created_at', 'updated_at',) list_display_links = ('name',) list_per_page = 20 ordering = ['name'] search_fields = ['name', 'description', 'meta_keywords', 'meta_description'] exclude = ('created_at', 'updated_at',) # sets up slug to be generated from category name prepopulated_fields = {'slug': ('name',)} admin.site.register(Category, CategoryAdmin) </code></pre> <p>But it still not work!</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 point of model saving your slug is already processed by <code>slugify</code> function of django. To do this:</p> <ol> <li><p>Create ModelForm for your class: </p> <pre><code>class SomeModelForm(forms.ModelForm): class Meta: model = SomeModel exclude = () def clean_slug(self): slug = self.cleaned_data['slug'] # Consider adding vietnamese_map here slug = slugify(unicode(slug).translate(vietnamese_map)) return slug </code></pre></li> <li><p>In your admin class: </p> <pre><code>class YourModelAdmin(admin.ModelAdmin): form = SomeModelForm </code></pre></li> </ol> <p>You may need to replace <code>SlugField</code> with regular <code>CharField</code> at the point.</p>
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 PiCamerafrom picamera.array import PiRGBArray from picamera import PiCamera import time, cv2, sys, imutils, cv import cv2.cv as cv # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (400, 300) camera.framerate = 30 rawCapture = PiRGBArray(camera, size=(400, 300)) for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): image = frame.array img = cv2.medianBlur(image, 3) imgg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #imgg = cv2.blur(imgg, (3,3)) #imgg = cv2.dilate(imgg, np.ones((5, 5))) #imgg = cv2.GaussianBlur(imgg,(5,5),0) circles = cv2.HoughCircles(imgg, cv.CV_HOUGH_GRADIENT, 1, 20, param1=100, param2=40, minRadius=5, maxRadius=90) cv2.imshow("Frame", imgg) # clear the stream in preparation for the next frame rawCapture.truncate(0) key = cv2.waitKey(1) &amp; 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break if circles is None: continue for i in circles[0,:]: cv2.circle(imgg,(i[0],i[1]),i[2],(0,255,0),1) # draw the outer circle cv2.circle(imgg,(i[0],i[1]),2,(0,0,255),3) # draw the center of the circle cv2.imshow("Framed", imgg) </code></pre>
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/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS</a></p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome("C:\Users\shalini\Downloads\chromedriver_win32\chromedriver.exe") driver.maximize_window() url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS" driver.get(url) for i in driver.find_elements_by_xpath("//div[@class='wrap']"): print i.find_element(By.XPATH, '//p[@class="partial_entry"]') print i.text print "==============================================" # THIS IF BLOCK IS NECESSARY, I CANT DO AWAY WITH THIS ONE if i.find_elements(By.CSS_SELECTOR,"#REVIEWS .googleTranslation&gt;.link"): print "======YES TRANSLATION AVAILABLE========" </code></pre> <p>Even though Im selecting a different element each time in for loop, but its printing the same element over and over again. (I have to keep the last if block &amp; cant do away with it, so whatever the solution be it has to include that if block also)</p> <p>======EDIT===================</p> <p>Even this isnt working (which should actually work, according to <a href="http://selenium-python.readthedocs.io/locating-elements.html" rel="nofollow">http://selenium-python.readthedocs.io/locating-elements.html</a> ) . I dont know whats going on with selenium !!!!!</p> <pre><code>print i.find_element(By.CSS_SELECTOR, 'p.partial_entry') </code></pre> <p>Output:</p> <pre><code>NoSuchElementException: </code></pre>
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>i</code>. So that just keeps returning the first <code>p.partial_entry</code> element for each iteration of the outer loop.</p> <p>To search for descendant elements of <code>i</code> which match <code>p[@class="partial_entry"]</code>, the xpath should start with <code>.//</code>. That's what the dot does.</p> <p><strong>2.</strong> For the line <code>print i.find_element(By.CSS_SELECTOR, 'p.partial_entry')</code>:<br> The single <code>find_element</code> either return the first found element or throw an error if none are found. There are some 'div.wrap's which don't have that descendant element, so you will get <code>NoSuchElementException</code>.</p> <p>The <code>find_elements</code> (note the 's') methods return a list of elements or an empty list if none are found, rather than an error.</p> <p>So putting all that together:</p> <pre><code>&gt;&gt;&gt; for i in driver.find_elements_by_xpath("//div[@class='wrap']"): ... for ent in i.find_elements_by_xpath('.//p[@class="partial_entry"]'): ... print ent.text ... if i.find_elements_by_css_selector('#REVIEWS .googleTranslation&gt;.link'): ... print 'translation available' ... print # output clarity ... </code></pre> <hr> <p>Btw, why are you mixing things like <code>find_elements_by_xpath('...')</code> along with <code>find_element(By.XPATH, '...')</code>? Stick to one pattern.</p>
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 O(N)</p> <pre><code>def set_disjoint_medium (a, b, c): a, b, c = set(a), set(b), set(c) for elem in a: if elem in b and elem in c: return False return True </code></pre> <p>yet this O(n^3) code:</p> <pre><code>def set_disjoint_slowest (a, b, c): for e1 in a: for e2 in b: for e3 in c: if e1 == e2 == e3: return False return True </code></pre> <p>runs faster</p> <p>see time where algorithm one is the n^3, and algorithm three is the O(n) set code... algorithm two is actually n^2 where we optimize algorithm one by checking for disjointness before the third loop starts</p> <pre><code>Size Input (n): 10000 Algorithm One: 0.014993906021118164 Algorithm Two: 0.013481855392456055 Algorithm Three: 0.01955580711364746 Size Input (n): 100000 Algorithm One: 0.15916991233825684 Algorithm Two: 0.1279449462890625 Algorithm Three: 0.18677806854248047 Size Input (n): 1000000 Algorithm One: 1.581618070602417 Algorithm Two: 1.146049976348877 Algorithm Three: 1.8179030418395996 </code></pre>
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_disjoint_slowest (a, b, c): a = [random.randrange(100) for i in xrange(10000)] b = [random.randrange(100) for i in xrange(10000)] c = [random.randrange(100) for i in xrange(10000)] # Ran timeit. # Results with timeit module. 1-) 0.00635750419422 2-) 0.0061145967287 3-) 0.0487953200969 </code></pre> <p>Now to the results, as you see, the <code>O(n^3)</code> solution runs <strong>8</strong> times slower than the other solutions. But this is still fast for such an algorithm(Even faster in your test). <strong>Why this happens ?</strong></p> <p>Because medium and slowest solutions you used, finishes the execution of the code <strong>as soon as a common element is detected</strong>. So the full complexity of the code is not realized. It breaks as soon as it finds an answer. Why the slowest solution ran almost as fast as the other ones in your test ? Probably because it finds the answer closer to the beginning of the lists.</p> <p>To test this, you could create the lists like this. Try this yourself.</p> <pre><code>a = range(1000) b = range(1000, 2000) c = range(2000, 3000) </code></pre> <p>Now the real difference between the times will be obvious because the slowest solution will have to run until it finishes all iterations, because there is no common element.</p> <p>So it is a situation of <strong>Worst case</strong> and <strong>Best case</strong> performance.</p> <p><strong>Not a part of the question edit:</strong> So, what if you want to retain the speed of finding early common occurances, but also don't want to increase complexity. I made a rough solution for that, maybe more experienced users can suggest faster code.</p> <pre><code>def mysol(a, b, c): store = [set(), set(), set()] # zip_longest for Python3, not izip_longest. for i, j, k in itertools.izip_longest(a, b, c): if i: store[0].add(i) if j: store[1].add(j) if k: store[2].add(k) if (i in store[1] and i in store[2]) or (j in store[0] and i in store[2]) or (k in store[0] and i in store[1]): return False return True </code></pre> <p>What is basically being done in this code is, you avoid converting all the lists to sets in the beginning. Rather, iterate through all lists at the same time, add elements to sets, check for common occurances. So now, you keep the speed of finding an early solution, but it is still slow for the worst case that I shown.</p> <p>For the speeds, this runs 3-4 times slower than your first two solutions in the worst case. But runs 4-10 times faster than those solutions in randomized lists.</p>
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 O(N)</p> <pre><code>def set_disjoint_medium (a, b, c): a, b, c = set(a), set(b), set(c) for elem in a: if elem in b and elem in c: return False return True </code></pre> <p>yet this O(n^3) code:</p> <pre><code>def set_disjoint_slowest (a, b, c): for e1 in a: for e2 in b: for e3 in c: if e1 == e2 == e3: return False return True </code></pre> <p>runs faster</p> <p>see time where algorithm one is the n^3, and algorithm three is the O(n) set code... algorithm two is actually n^2 where we optimize algorithm one by checking for disjointness before the third loop starts</p> <pre><code>Size Input (n): 10000 Algorithm One: 0.014993906021118164 Algorithm Two: 0.013481855392456055 Algorithm Three: 0.01955580711364746 Size Input (n): 100000 Algorithm One: 0.15916991233825684 Algorithm Two: 0.1279449462890625 Algorithm Three: 0.18677806854248047 Size Input (n): 1000000 Algorithm One: 1.581618070602417 Algorithm Two: 1.146049976348877 Algorithm Three: 1.8179030418395996 </code></pre>
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 free. So it is fairly common to see 100x performance differences of virtually equivalent code, unfortunately.</p> <p>Secondly, the first algorithm computes <em>all</em> common elements, while the others fail on the <em>first</em>. If you benchmark <code>algX(a,a,a)</code> (yes, all three sets be the same) then it will do much more work than the others!</p> <p>I would not be surprised to see a sort-based O(n log n) algorithm to be very competitive (because sorting is usually incredibly well optimized). For integers, I would use numpy arrays, and by avoiding the python interpreter as much as possible you can get very fast. While numpys <code>in1d</code> and <code>intersect</code> will likely give you aan O(n^2) or O(n^3) algorithm, they may end up being faster as long as your sets are usually disjoint.</p> <p>Also note that in your case, the sets won't necessarily be pairwise disjoint... <code>algX(set(),a,a)==True</code>.</p>
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 as all <code>BUILD</code> files containing paths relative to the project root (where <code>pants.ini</code> is). This project is hosted on GitHub.</p> <p>I'd like to use this project as a dependency in a second project. I've chosen to use git submodules to do this. Now, I have a layout like the following:</p> <pre><code>path ├── pants ├── pants.ini ├── projectA │   └── src │   └── python | └── main │   ├── BUILD │   └── main.py └── projectB ├── pants ├── pants.ini └── src └── python ├── libA | ├── BUILD | └── lib.py └── libB ├── BUILD └── lib.py </code></pre> <p>Naturally, I am looking to use projectB's BUILD targets from within projectA, so in projectA's <code>BUILD</code>, I have something of the sort:</p> <pre><code>dependencies = [ "projectB/src/python:libA" ] </code></pre> <p>This is all well and good. However, since projectB is an independent project, it's <code>src/python/libA/BUILD</code> file contains something of the sort:</p> <pre><code>dependencies = [ "src/python:libB" ] </code></pre> <p>Because of this, projectB can indeed be built independently. However, when trying to build projectA, the build targets from projectB search starting from projectA's project root, for instance:</p> <pre><code>Exception Message: libB was not found in BUILD files from path/src/python </code></pre> <p>Does pantsbuild have any clean way to handle these subproject dependencies? Or would I be forced to alter the BUILD files of the subproject in order to fit them within my project layout (Causing the project to be unbuildable independently)?</p> <p>Any solutions or advice is welcomed!</p>
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>projectB/src/python:libB</code>. All target paths in the repo should be relative to the build root which is <code>path</code> in your example. </p>
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 df:</p> <pre><code> df = { 'id' : pd.Series([1,1,1,1,2,2,2,2]), 'cost' : pd.Series([10,20,30,40,50,60,70,80]), 'mth': pd.Series([3,3,4,5,3,4,4,5])} cost id mth 0 10 1 3 1 20 1 3 2 30 1 4 3 40 1 5 4 50 2 3 5 60 2 4 6 70 2 4 7 80 2 5 </code></pre> <p>I can get monthly sum but i want the average of the months for each user_id. </p> <pre><code>df.groupby(['id','mth'])['cost'].sum() id mth 1 3 30 4 30 5 40 2 3 50 4 130 5 80 </code></pre> <p>i want something like this:</p> <pre><code>id average_monthly 1 (30+30+40)/3 2 (50+130+80)/3 </code></pre>
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 <code>sum</code> part, you have this:</p> <pre><code>In [20]: df.groupby(['id', 'mth']).sum() Out[20]: cost id mth 1 3 30 4 30 5 40 2 3 50 4 130 5 80 </code></pre> <p>Resetting the index at this point will give you unique months.</p> <pre><code>In [21]: df.groupby(['id', 'mth']).sum().reset_index() Out[21]: id mth cost 0 1 3 30 1 1 4 30 2 1 5 40 3 2 3 50 4 2 4 130 5 2 5 80 </code></pre> <p>It's just a matter of grouping it again, this time using <code>mean</code> instead of <code>sum</code>. This should give you the averages.</p> <p>Let us know if this helps.</p>
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 </code></pre> <p>i.e. one for the echo process and one for printing the result output. But what I see is </p> <pre><code>vimo </code></pre> <p>But when I try to print the result output, its always empty.</p> <p>What am I missing in the above puzzle !! Help out !!</p>
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 proc.returncode != 0: # code to handle / parse stderr (comm[1]) raise RuntimeError( '\'%s\': command has failed (%d):\n%s' % ('some value', proc.returncode, comm[1])) for line in comm[0].split('\n'): if line.find('Wrote:') == 0: # some code to parse stdout pass </code></pre>
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 thing like this:</p> <pre><code>webserver ---------&gt; Wsgi -----------&gt; urls.py | | | | | keep sending data | keep requesting data templat.html&lt;--------------------- views.py -------------------------&gt; request </code></pre> <p>i dont now if we need to use sockets or how to approach this problem.</p>
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://github.com/shtalinberg/django-el-pagination" rel="nofollow">django-el-pagination</a> on GitHub.</p>
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;"&gt;&lt;font color="Orange"&gt; EDIT &lt;/font&gt;&lt;/a&gt;&lt;hr&gt; </code></pre> <p>So that I can edit the certain ID that I want to. But it gives me an error. How do you do it? or is there any other way? I'm new to Django.</p>
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;"&gt;&lt;font color="Orange"&gt; EDIT &lt;/font&gt;&lt;/a&gt;&lt;hr&gt; </code></pre> <p>So that I can edit the certain ID that I want to. But it gives me an error. How do you do it? or is there any other way? I'm new to Django.</p>
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><code>&lt;a href="{{obj.get_absolute_url}}edit" class="btn"&gt;EDIT&lt;/a&gt; </code></pre> <p>Every time you click the btn EDIT, it will take you to the following edit page with the given id (id that contains the forms/models of the user).</p>
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/wGw4F.png" rel="nofollow">Click here to view the challenge question</a></p> <p>I have been trying to solve it for quite a while but I am stuck in one place (heres my code):</p> <pre><code>c = ['H','H','H','H','H','H','H','I','H','H','H','H','F','H','H','H','H','H','H','H','H','H','H','H','H',] c_copy = list(c) def prt(): print("\n"+c[0]+"\t"+c[1]+"\t"+c[2]+"\t"+c[3]+"\t"+c[4]+"\n"+ c[5]+"\t"+c[6]+"\t"+c[7]+"\t"+c[8]+"\t"+c[9]+"\n"+ c[10]+"\t"+c[11]+"\t"+c[12]+"\t"+c[13]+"\t"+c[14]+"\n"+ c[15]+"\t"+c[16]+"\t"+c[17]+"\t"+c[18]+"\t"+c[19]+"\n"+ c[20]+"\t"+c[21]+"\t"+c[22]+"\t"+c[23]+"\t"+c[24]) generations = 3 while generations &gt; 0: for x, y in enumerate(c): if(y == 'F'): c_copy[x] = 'H' if(y == 'I'): c_copy[x] = 'F' try: if(c[x+1] == 'H'): c_copy[x+1] = 'I' if(c[x-1] == 'H'): c_copy[x-1] = 'I' if(c[x+5] == 'H'): c_copy[x+5] = 'I' if(c[x-5] == 'H'): c_copy[x-5] = 'I' except IndexError: pass c = list(c_copy) generations = generations - 1 prt() </code></pre> <p>I know where my problem is but I cant seem to get around it. In the for loop, when i[7] == I, I change the value to its east to 'I', but when the for loop goes to i[8], it will change the value to its east again. That keeps happening until the value is not 'I'. how do I get around that? And also if someone can do the challenge in a simpler and better way, please put up your code. Thanks</p>
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','H','F','H','H'],['H','H','H','H','H'],['H','H','H','H','H']] gen=3 #loops for each generation for i in range(gen): #creates lists for cells that need to be infected if possible #and cells that need to be replanted infect=[] plant=[] #loops through the grid cells for x in range(5): for y in range(5): if grid[x][y]=='F': #adds each fading cell to the list for replanting plant.append([x,y]) if grid[x][y]=='I': #makes the cell fade grid[x][y]='F' #checks if each of its neighbours is a valid grid square #and if so adds it to the list to be infected if possible if x&gt;0: infect.append([x-1,y]) if x&lt;4: infect.append([x+1,y]) if y&gt;0: infect.append([x,y-1]) if y&lt;4: infect.append([x,y+1]) #infects healthy cells in the 'to be infected' list for x,y in infect: if grid[x][y]=='H': grid[x][y]='I' #replants cells in the replanting list for x,y in plant: grid[x][y]='H' #nicely prints the grid for a in grid: for b in a: print(b,end='') print() </code></pre> <p>Code without annotations:</p> <pre><code>grid=[['H','H','H','H','H'],['H','H','I','H','H'],['H','H','F','H','H'],['H','H','H','H','H'],['H','H','H','H','H']] gen=3 for i in range(gen): infect=[] plant=[] for x in range(5): for y in range(5): if grid[x][y]=='F': plant.append([x,y]) if grid[x][y]=='I': grid[x][y]='F' if x&gt;0: infect.append([x-1,y]) if x&lt;4: infect.append([x+1,y]) if y&gt;0: infect.append([x,y-1]) if y&lt;4: infect.append([x,y+1]) for x,y in infect: if grid[x][y]=='H': grid[x][y]='I' for x,y in plant: grid[x][y]='H' for a in grid: for b in a: print(b,end='') print() </code></pre>
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/wGw4F.png" rel="nofollow">Click here to view the challenge question</a></p> <p>I have been trying to solve it for quite a while but I am stuck in one place (heres my code):</p> <pre><code>c = ['H','H','H','H','H','H','H','I','H','H','H','H','F','H','H','H','H','H','H','H','H','H','H','H','H',] c_copy = list(c) def prt(): print("\n"+c[0]+"\t"+c[1]+"\t"+c[2]+"\t"+c[3]+"\t"+c[4]+"\n"+ c[5]+"\t"+c[6]+"\t"+c[7]+"\t"+c[8]+"\t"+c[9]+"\n"+ c[10]+"\t"+c[11]+"\t"+c[12]+"\t"+c[13]+"\t"+c[14]+"\n"+ c[15]+"\t"+c[16]+"\t"+c[17]+"\t"+c[18]+"\t"+c[19]+"\n"+ c[20]+"\t"+c[21]+"\t"+c[22]+"\t"+c[23]+"\t"+c[24]) generations = 3 while generations &gt; 0: for x, y in enumerate(c): if(y == 'F'): c_copy[x] = 'H' if(y == 'I'): c_copy[x] = 'F' try: if(c[x+1] == 'H'): c_copy[x+1] = 'I' if(c[x-1] == 'H'): c_copy[x-1] = 'I' if(c[x+5] == 'H'): c_copy[x+5] = 'I' if(c[x-5] == 'H'): c_copy[x-5] = 'I' except IndexError: pass c = list(c_copy) generations = generations - 1 prt() </code></pre> <p>I know where my problem is but I cant seem to get around it. In the for loop, when i[7] == I, I change the value to its east to 'I', but when the for loop goes to i[8], it will change the value to its east again. That keeps happening until the value is not 'I'. how do I get around that? And also if someone can do the challenge in a simpler and better way, please put up your code. Thanks</p>
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 each bed position ckl = [ list(cc for cc in (5*(r-1)+c, 5*r+c-1, 5*r+c, 5*r+c+1, 5*(r+1)+c) if 0 &lt;= cc &lt; 25 and (cc // 5 ==r or cc % 5 == c)) for r in range(5) for c in range(5) ] pr(bed) # print the initial configuration for gen in range(5): bed = ''.join([ tx.get(c, 'I' if bed[i]=='H' and any([bed[n]=='I' for n in ckl[i]]) else 'H') for i,c in enumerate(bed) ]) pr(bed) </code></pre>
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/wGw4F.png" rel="nofollow">Click here to view the challenge question</a></p> <p>I have been trying to solve it for quite a while but I am stuck in one place (heres my code):</p> <pre><code>c = ['H','H','H','H','H','H','H','I','H','H','H','H','F','H','H','H','H','H','H','H','H','H','H','H','H',] c_copy = list(c) def prt(): print("\n"+c[0]+"\t"+c[1]+"\t"+c[2]+"\t"+c[3]+"\t"+c[4]+"\n"+ c[5]+"\t"+c[6]+"\t"+c[7]+"\t"+c[8]+"\t"+c[9]+"\n"+ c[10]+"\t"+c[11]+"\t"+c[12]+"\t"+c[13]+"\t"+c[14]+"\n"+ c[15]+"\t"+c[16]+"\t"+c[17]+"\t"+c[18]+"\t"+c[19]+"\n"+ c[20]+"\t"+c[21]+"\t"+c[22]+"\t"+c[23]+"\t"+c[24]) generations = 3 while generations &gt; 0: for x, y in enumerate(c): if(y == 'F'): c_copy[x] = 'H' if(y == 'I'): c_copy[x] = 'F' try: if(c[x+1] == 'H'): c_copy[x+1] = 'I' if(c[x-1] == 'H'): c_copy[x-1] = 'I' if(c[x+5] == 'H'): c_copy[x+5] = 'I' if(c[x-5] == 'H'): c_copy[x-5] = 'I' except IndexError: pass c = list(c_copy) generations = generations - 1 prt() </code></pre> <p>I know where my problem is but I cant seem to get around it. In the for loop, when i[7] == I, I change the value to its east to 'I', but when the for loop goes to i[8], it will change the value to its east again. That keeps happening until the value is not 'I'. how do I get around that? And also if someone can do the challenge in a simpler and better way, please put up your code. Thanks</p>
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; Infected area passes infections to North, east, west, south. """ visited = [] for row_index, row_flowers_state in enumerate(self.flowers_state): for flower_index, flower_state in enumerate(row_flowers_state): if (row_index, flower_index) not in visited and flower_state == 'I': # Rule -&gt; 3 for x, y in [(0, 1), (0, -1), (1, 0), (-1, 0)]: try: if (row_index+x, flower_index+y) not in visited and \ self.flowers_state[row_index+x][flower_index+y] == 'H': self.flowers_state[row_index+x][flower_index+y] = 'I' visited.append((row_index+x, flower_index+y)) except IndexError: pass # Rule -&gt; 1 self.flowers_state[row_index][flower_index] = 'F' visited.append((row_index, flower_index)) elif (row_index, flower_index) not in visited and flower_state == 'F': # Rule -&gt; 2 self.flowers_state[row_index][flower_index] = 'H' visited.append((row_index, flower_index)) def print_states(self): print "\n".join(["".join(flowers_state_row) for flowers_state_row in self.flowers_state]) def main(): flowers_state = [ ['H', 'H', 'H', 'H', 'H'], ['H', 'H', 'I', 'H', 'H'], ['H', 'H', 'F', 'H', 'H'], ['H', 'H', 'H', 'H', 'H'], ['H', 'H', 'H', 'H', 'H'] ] f = Flowers(flowers_state) for _ in xrange(0, 3): f.run_rule() f.print_states() print "\n" main() </code></pre>
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/wGw4F.png" rel="nofollow">Click here to view the challenge question</a></p> <p>I have been trying to solve it for quite a while but I am stuck in one place (heres my code):</p> <pre><code>c = ['H','H','H','H','H','H','H','I','H','H','H','H','F','H','H','H','H','H','H','H','H','H','H','H','H',] c_copy = list(c) def prt(): print("\n"+c[0]+"\t"+c[1]+"\t"+c[2]+"\t"+c[3]+"\t"+c[4]+"\n"+ c[5]+"\t"+c[6]+"\t"+c[7]+"\t"+c[8]+"\t"+c[9]+"\n"+ c[10]+"\t"+c[11]+"\t"+c[12]+"\t"+c[13]+"\t"+c[14]+"\n"+ c[15]+"\t"+c[16]+"\t"+c[17]+"\t"+c[18]+"\t"+c[19]+"\n"+ c[20]+"\t"+c[21]+"\t"+c[22]+"\t"+c[23]+"\t"+c[24]) generations = 3 while generations &gt; 0: for x, y in enumerate(c): if(y == 'F'): c_copy[x] = 'H' if(y == 'I'): c_copy[x] = 'F' try: if(c[x+1] == 'H'): c_copy[x+1] = 'I' if(c[x-1] == 'H'): c_copy[x-1] = 'I' if(c[x+5] == 'H'): c_copy[x+5] = 'I' if(c[x-5] == 'H'): c_copy[x-5] = 'I' except IndexError: pass c = list(c_copy) generations = generations - 1 prt() </code></pre> <p>I know where my problem is but I cant seem to get around it. In the for loop, when i[7] == I, I change the value to its east to 'I', but when the for loop goes to i[8], it will change the value to its east again. That keeps happening until the value is not 'I'. how do I get around that? And also if someone can do the challenge in a simpler and better way, please put up your code. Thanks</p>
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[curr==2] = 0 # faded flowers become healthy iw0 = np.argwhere(curr==0) # indices of elements of `curr` that are 0 (healthy) next[tuple(iw0.T)] = 0 def fix_bad_indices(ia, shape): """ ia : an array of array-indices, some of which may be bad (exceed array dimensions) shape: an array's shape based on which any bad index in `ia` will be fixed (Note that the data in `ia` may get modified in this function) """ assert ia.ndim == 2 and len(shape) == ia.shape[1] for axis, size in enumerate(shape): for bad, new in [(-1, 0), (size, size-1)]: kk = ia[:, axis] kk[bad == kk] = new return ia senw = [(1, 0), (0, 1), (-1, 0), (0, -1)] # south, east, north, west # an array of neighbour indices of all healthy flowers nb_idxs = np.stack([fix_bad_indices(iw0 + shift, curr.shape) for shift in senw], axis=1) # elements of `curr` at neighbour-indices nb_elems = curr[tuple(nb_idxs.reshape(-1, 2).T)] nb_elems = nb_elems.reshape(*nb_idxs.shape[:-1]) nb_elems[nb_elems==2] = 0 next[tuple(iw0.T)] = np.any(nb_elems, axis=1) def run(grid): curr = grid next = curr.copy() while 1: update(curr, next) yield next next, curr = curr, next def main(grid, ngens): dct = {'H':0, 'I':1, 'F':2} rdct = dict(zip(dct.values(), dct.keys())) def to_string(array): return '\n'.join(''.join(rdct[x] for x in row) for row in array) def to_array(string): return np.array([[dct[x] for x in row] for row in string.splitlines()]) # grid = np.mod(np.arange(20).reshape(5, 4), 3) grid = to_array(grid) print(to_string(grid)) print() for i, grid in zip(range(ngens), run(grid)): print(to_string(grid)) print() return to_string(grid) if __name__ == '__main__': grid="""HHHHH HHIHH HHFHH HHHHH HHHHH""".replace(' ','') main(grid, 3) </code></pre>
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 database. The code below basically gets all the href attributes and joins them as a list. After, I crosscheck it against the the list of links I have stored in my database of pages I have already scraped. So basically it will return a list of the links I haven't scraped yet. </p> <pre><code>@staticmethod def _scrape_home_urls(driver): home_url_list = list(home_tab.find_element_by_tag_name('a').get_attribute('href') for home_tab in driver.find_elements_by_css_selector('div[class^="nhs_HomeResItem clearfix"]')) return (home_url for home_url in home_url_list if home_url not in(url[0] for url in NewHomeSource.outputDB())) </code></pre> <p>Once it scrapes all the links of that page, it goes to the next one. I tried to reuse it by calling _scrape_home_urls() again </p> <pre><code> NewHomeSource.unique_home_list = NewHomeSource._scrape_home_urls(driver) for x in xrange(0,limit): try: home_url = NewHomeSource.unique_home_list.next() except StopIteration: page_num = int(NewHomeSource.current_url[NewHomeSource.current_url.rfind('-')+1:]) + 1 #extract page number from url and gets next page by adding 1. example: /.../.../page-3 page_url = NewHomeSource.current_url[:NewHomeSource.current_url.rfind('-')+1] + str(page_num) print page_url driver.get(page_url) NewHomeSource.current_url = driver.current_url NewHomeSource.unique_home_list = NewHomeSource._scrape_home_urls(driver) home_url = NewHomeSource.unique_home_list.next() #and then I use the home_url to do some processing within the loop </code></pre> <p>Thanks in advance.</p>
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 True: for url in NewHomeSource._scrape_home_urls(driver): yield url page_num = int(NewHomeSource.current_url[NewHomeSource.current_url.rfind('-')+1:]) + 1 #extract page number from url and gets next page by adding 1. example: /.../.../page-3 page_url = NewHomeSource.current_url[:NewHomeSource.current_url.rfind('-')+1] + str(page_num) print page_url driver.get(page_url) NewHomeSource.current_url = driver.current_url </code></pre> <p>This will transparently skip over pages that don't have any unprocessed links. The generator function yields the url values indefinitely. To iterate on it with a limit like your old code did, use <code>enumerate</code> and <code>break</code> when the limit is reached:</p> <pre><code>for i, home_url in urls_gen(driver): if i == limit: break # do stuff with home_url here </code></pre> <p>I've not changed your code other than what was necessary to change the iteration. There are quite a few other things that could be improved however. For instance, using a shorter variable than <code>NewHomeSource.current_url</code> would make the lines of the that figure out the page number and then the next page's URL much more compact and readable. It's also not clear to me where that variable is initially set. If it's not used anywhere outside of this loop, it could easily be changed to a local variable in <code>urls_gen</code>.</p> <p>Your <code>_scrape_home_urls</code> function is probably also very inefficient. It looks like it does a database query for every url it returns (not one lookup before checking all of the urls). Maybe that's what you want it to do, but I suspect it would be much faster done another way.</p>
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 a_Fe I 401.45340 nm 399.83282 389.436000000 399.83282 389.436000000 399.85765 289.804000000 399.85765 289.804000000 </code></pre> <p>The problem is that each row of my data is a different length. Is there anyway to format the remaining spaces of the shorter rows with a space so they are all the same length?</p> <p>I would like my data to be in the form: </p> <pre><code>list one= [399.75833, 399.78316, 399.80799, 399.83282, 399.85765] list two= [561.572000000, 523.227000000, 455.923000000, 389.436000000, 289.804000000] list three= [a_Fe, " ", a_Fe, " ", " "] </code></pre> <p>This is the code I used to import the data into python:</p> <pre><code>fh = open('help.bsp').read() the_list = [] for line in fh.split('\n'): print line.strip() splits = line.split() if len(splits) ==1 and splits[0]== line.strip(): splits = line.strip().split(',') if splits:the_list.append(splits) </code></pre>
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 = [line.strip().split() for line in fh] # Use izip_longest to get all columns, with None's filled in blank spots cols = [col for col in izip_longest(*rows)] # Then run your type conversions for your final data lists list_one = [float(i) for i in cols[2]] list_two = [float(i) for i in cols[3]] # Since you want " " instead of None for blanks list_three = [i if i else " " for i in cols[4]] </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; print list_one [399.75833, 399.78316, 399.80799, 399.83282, 399.85765] &gt;&gt;&gt; print list_two [561.572, 523.227, 455.923, 389.436, 289.804] &gt;&gt;&gt; print list_three ['a_Fe', ' ', 'a_Fe', ' ', ' '] </code></pre>
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 a_Fe I 401.45340 nm 399.83282 389.436000000 399.83282 389.436000000 399.85765 289.804000000 399.85765 289.804000000 </code></pre> <p>The problem is that each row of my data is a different length. Is there anyway to format the remaining spaces of the shorter rows with a space so they are all the same length?</p> <p>I would like my data to be in the form: </p> <pre><code>list one= [399.75833, 399.78316, 399.80799, 399.83282, 399.85765] list two= [561.572000000, 523.227000000, 455.923000000, 389.436000000, 289.804000000] list three= [a_Fe, " ", a_Fe, " ", " "] </code></pre> <p>This is the code I used to import the data into python:</p> <pre><code>fh = open('help.bsp').read() the_list = [] for line in fh.split('\n'): print line.strip() splits = line.split() if len(splits) ==1 and splits[0]== line.strip(): splits = line.strip().split(',') if splits:the_list.append(splits) </code></pre>
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 the lists you want from the data you show:</p> <pre><code>with open('help.bsp') as h: the_list = [ line.strip().split() for line in h.readlines() ] list_one = [ d[0] for d in the_list ] list_two = [ d[1] for d in the_list ] list_three = [ d[4] if len(d) &gt; 4 else ' ' for d in the_list ] </code></pre> <p>If you're reading comma separated (or similarly delimited) files, I always recommend using the <code>csv</code> module - it handles a lot of edge cases that you may not have considered.</p>
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 line: f2.write(line.replace('999', no)) continue else: f2.write(line) f1.close() f2.close() </code></pre> <p>Sample from f1.txt:</p> <pre><code>tags text something some_text blablabla 999 other text whatever some_text blablabla 999 non interesting text some_text blablabla 999 </code></pre> <p>The result should be:</p> <pre><code>tags text something some_text blablabla 1 other text whatever some_text blablabla 2 non interesting text some_text blablabla 3 </code></pre> <p>Can you please help me?</p> <p>Thank you</p>
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: [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]` </code></pre> <p>As you can see above, I wish to identify 'Samsung' as the key and 'Handphone' and '10' as the values with respect to the key.</p> <p>My desired output would be:</p> <pre><code> `Output: {'Sony': ['Handphone',100], 'Samsung': ['Tablet',10,'Handphone', 9]}` </code></pre> <p>As you can see above, the item 'handphone' and 'tablet' are group according to the key values which in my case is Sony and Samsung. The quantity of the item are are added / subtracted if they belong to the same item and same key (Samsung or Sony).</p> <p>I would really appreciate any suggestions and ideas that you guys have in order to achieve the above output. I really ran out of ideas. Thank you. </p>
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 = {} for company, device, n in tuples: key = (company, device) d[key] = d.get(key, 0) + n </code></pre>
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: [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]` </code></pre> <p>As you can see above, I wish to identify 'Samsung' as the key and 'Handphone' and '10' as the values with respect to the key.</p> <p>My desired output would be:</p> <pre><code> `Output: {'Sony': ['Handphone',100], 'Samsung': ['Tablet',10,'Handphone', 9]}` </code></pre> <p>As you can see above, the item 'handphone' and 'tablet' are group according to the key values which in my case is Sony and Samsung. The quantity of the item are are added / subtracted if they belong to the same item and same key (Samsung or Sony).</p> <p>I would really appreciate any suggestions and ideas that you guys have in order to achieve the above output. I really ran out of ideas. Thank you. </p>
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 in the_list: d[brand][thing] += quantity </code></pre> <p>Result will be</p> <pre><code>{ 'Samsung': { 'Handphone': 9, 'Tablet': 10 }, 'Sony': { 'Handphone': 100 } } </code></pre>
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: [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]` </code></pre> <p>As you can see above, I wish to identify 'Samsung' as the key and 'Handphone' and '10' as the values with respect to the key.</p> <p>My desired output would be:</p> <pre><code> `Output: {'Sony': ['Handphone',100], 'Samsung': ['Tablet',10,'Handphone', 9]}` </code></pre> <p>As you can see above, the item 'handphone' and 'tablet' are group according to the key values which in my case is Sony and Samsung. The quantity of the item are are added / subtracted if they belong to the same item and same key (Samsung or Sony).</p> <p>I would really appreciate any suggestions and ideas that you guys have in order to achieve the above output. I really ran out of ideas. Thank you. </p>
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] ], 'Samsung': [ ['Tablet',10], ['Handphone', 9] ] } </code></pre> <p>With:</p> <pre><code>my_list = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)] result = {} for brand, device, value in my_list: # first verify if key is present to add list for the first time if not brand in result: result[brand] = [] # then add new list to already existent list result[brand] += [[device, value]] </code></pre> <p>But I think the best format would be a dict:</p> <pre><code>{ 'Sony': { 'Handphone': 100 }, 'Samsung': { 'Tablet': 10, 'Handphone': 9 } } </code></pre> <p>That would be like:</p> <pre><code>my_list = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)] result = {} for brand, device, value in my_list: # first verify if key is present to add dict for the first time if not brand in result: result[brand] = {} # then add new key/value to already existent dict result[brand][device] = value </code></pre>
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.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Index") </code></pre> <p>Also, I already have written my urls.py file for it:</p> <pre><code>from django.conf.urls import url from apps.mascota.views import index urlpatterns = [ url(r'^$/', index), ] </code></pre> <p>And I have modified the url.py file of my project:</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('apps.mascota.urls')), ] </code></pre> <p>But when I run the server of my project, it sends me the next error message: <a href="https://i.stack.imgur.com/Ww9EC.png" rel="nofollow"><img src="https://i.stack.imgur.com/Ww9EC.png" alt="enter image description here"></a></p> <p>If it helps, My dir tree is the following:</p> <p><code>REFUGIO apps mascota views.py urls.py refugio settings.py urls.py manage.py </code></p> <p>I know this is a dummy question, but I don't know what is wrong, I have already checked my urls sentences, but I see everything ok.</p> <p>I will appreciate your help.</p> <p>Ps.: My app is located inside a folder called apps.</p> <p>Regards.</p>
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 mascota.views import index </code></pre> <p>Hope this helps.</p>
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.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Index") </code></pre> <p>Also, I already have written my urls.py file for it:</p> <pre><code>from django.conf.urls import url from apps.mascota.views import index urlpatterns = [ url(r'^$/', index), ] </code></pre> <p>And I have modified the url.py file of my project:</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('apps.mascota.urls')), ] </code></pre> <p>But when I run the server of my project, it sends me the next error message: <a href="https://i.stack.imgur.com/Ww9EC.png" rel="nofollow"><img src="https://i.stack.imgur.com/Ww9EC.png" alt="enter image description here"></a></p> <p>If it helps, My dir tree is the following:</p> <p><code>REFUGIO apps mascota views.py urls.py refugio settings.py urls.py manage.py </code></p> <p>I know this is a dummy question, but I don't know what is wrong, I have already checked my urls sentences, but I see everything ok.</p> <p>I will appreciate your help.</p> <p>Ps.: My app is located inside a folder called apps.</p> <p>Regards.</p>
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>REFUGIO apps mascota __init__.py views.py urls.py __init__.py refugio __init__.py settings.py urls.py manage.py </code></pre>
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.imread("./data/images/cat_and_dog.jpg") cv2.imshow('image',image) # Display the picture plt.imshow(image) plt.show() cv2.waitKey(0) # wait for closing cv2.destroyAllWindows() # Ok, destroy the window </code></pre> <p>And the images shown by opencv gui and matplotlib are different.</p> <p><a href="https://i.stack.imgur.com/Qqe4K.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/Qqe4K.jpg" alt="enter image description here"></a></p> <p>Even the histogram is distorted and not just the display</p> <p><a href="https://i.stack.imgur.com/KL1X9.png" rel="nofollow"><img src="https://i.stack.imgur.com/KL1X9.png" alt="enter image description here"></a></p> <p>How do I avoid this blue shade on an image</p>
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 OpenCV is in BGR mode. But Matplotlib displays in RGB mode. So color images will not be displayed correctly in Matplotlib if image is read with OpenCV. Please see the exercises for more details.</p> </blockquote> <p>you can replace your <code>plt.imshow(image)</code> line with the following lines:</p> <pre><code>im2 = image.copy() im2[:, :, 0] = image[:, :, 2] im2[:, :, 2] = image[:, :, 0] plt.imshow(im2) </code></pre>
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? </p> <pre><code> EdgeList = traci.edge.getIDList() #Returns a list of Strings for edge in EdgeList: meanspeed = traci.edge.getLastStepMeanSpeed(edge) #returns a float value ''' if edge in MeanspeedDict: MeanspeedDict[edge].append(meanspeed) MeanspeedDict[edge] = MeanspeedDict[edge][-300:] #Only keep the last 300 values else: MeanspeedDict[edge] = [meanspeed] ''' try: MeanspeedDict[edge].append(meanspeed) MeanspeedDict[edge] = MeanspeedDict[edge][-300:] #Only keep the last 300 values except KeyError: MeanspeedDict[edge] = [meanspeed] </code></pre> <p>Profile Data as per request. Running it <strong>11</strong> times</p> <pre><code> 252229348 function calls in 295.056 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 295.056 295.056 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 40.158 40.158 __init__.py:101(getVersion) 1 0.000 0.000 4.908 4.908 __init__.py:105(close) 1 0.000 0.000 0.000 0.000 __init__.py:111(switch) 1 0.000 0.000 0.507 0.507 __init__.py:45(connect) 1 0.000 0.000 0.000 0.000 __init__.py:49(normalize_encoding) 1 0.000 0.000 40.665 40.665 __init__.py:64(init) 1 0.000 0.000 0.008 0.008 __init__.py:71(search_function) 11 0.000 0.000 1.646 0.150 __init__.py:92(simulationStep) 3607912 2.785 0.000 221.939 0.000 _edge.py:151(getLastStepMeanSpeed) 1 0.000 0.000 0.000 0.000 codecs.py:92(__new__) 3607923 5.689 0.000 16.796 0.000 connection.py:119(_beginMessage) 3607923 3.451 0.000 210.529 0.000 connection.py:128(_sendReadOneStringCmd) 3607923 8.231 0.000 190.282 0.000 connection.py:152(_checkResult) 11 0.000 0.000 1.646 0.150 connection.py:254(simulationStep) 1 0.000 0.000 40.158 40.158 connection.py:273(getVersion) 1 0.000 0.000 4.908 4.908 connection.py:285(close) 1 0.000 0.000 0.507 0.507 connection.py:48(__init__) 3607923 4.167 0.000 8.645 0.000 connection.py:64(_packString) 3607936 19.808 0.000 108.622 0.000 connection.py:72(_recvExact) 3607936 19.507 0.000 200.505 0.000 connection.py:91(_sendExact) 15 0.000 0.000 0.000 0.000 copy.py:123(_copy_inst) 15 0.000 0.000 0.000 0.000 copy.py:66(copy) 15 0.000 0.000 0.000 0.000 domain.py:108(_setConnection) 3607923 4.273 0.000 236.643 0.000 domain.py:111(_getUniversal) 11 0.004 0.000 17.493 1.590 domain.py:116(getIDList) 15 0.000 0.000 0.000 0.000 domain.py:37(__init__) 495 0.000 0.000 0.000 0.000 domain.py:47(reset) 15 0.000 0.000 0.000 0.000 domain.py:99(_register) 1 0.000 0.000 0.000 0.000 latin_1.py:13(Codec) 1 0.000 0.000 0.000 0.000 latin_1.py:20(IncrementalEncoder) 1 0.000 0.000 0.000 0.000 latin_1.py:24(IncrementalDecoder) 1 0.000 0.000 0.000 0.000 latin_1.py:28(StreamWriter) 1 0.000 0.000 0.000 0.000 latin_1.py:31(StreamReader) 1 0.000 0.000 0.000 0.000 latin_1.py:34(StreamConverter) 1 0.000 0.000 0.000 0.000 latin_1.py:41(getregentry) 1 0.000 0.000 0.000 0.000 latin_1.py:8(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 six.py:180(find_module) 1 0.000 0.000 0.000 0.000 six.py:184(find_module) 1 0.001 0.001 0.001 0.001 socket.py:189(__init__) 1 0.000 0.000 0.000 0.000 socket.py:196(close) 2 0.000 0.000 0.506 0.253 socket.py:227(meth) 3607936 1.590 0.000 1.590 0.000 storage.py:32(__init__) 39687197 29.658 0.000 39.432 0.000 storage.py:36(read) 12 0.000 0.000 0.000 0.000 storage.py:41(readInt) 3607912 1.564 0.000 5.345 0.000 storage.py:44(readDouble) 3607924 1.712 0.000 5.389 0.000 storage.py:47(readLength) 10823772 17.543 0.000 50.373 0.000 storage.py:53(readString) 11 1.922 0.175 16.496 1.500 storage.py:57(readStringList) 1 0.000 0.000 0.000 0.000 subprocess.py:458(_cleanup) 1 0.000 0.000 0.000 0.000 subprocess.py:578(list2cmdline) 1 0.000 0.000 0.045 0.045 subprocess.py:651(__init__) 1 0.000 0.000 0.000 0.000 subprocess.py:811(_get_handles) 3 0.000 0.000 0.000 0.000 subprocess.py:881(_make_inheritable) 1 0.000 0.000 0.045 0.045 subprocess.py:905(_execute_child) 3 0.000 0.000 0.000 0.000 subprocess.py:946(_close_in_parent) 1 6.670 6.670 295.056 295.056 traciTest_meanspeed.py:45(runTraCI) 1 0.007 0.007 0.007 0.007 {__import__} 39687197 3.728 0.000 3.728 0.000 {_struct.calcsize} 10823795 3.374 0.000 3.374 0.000 {_struct.pack} 43295133 7.225 0.000 7.225 0.000 {_struct.unpack} 1 0.045 0.045 0.045 0.045 {_subprocess.CreateProcess} 3 0.000 0.000 0.000 0.000 {_subprocess.DuplicateHandle} 6 0.000 0.000 0.000 0.000 {_subprocess.GetCurrentProcess} 1 0.000 0.000 0.000 0.000 {_subprocess.GetStdHandle} 4 0.000 0.000 0.000 0.000 {built-in method Close} 1 0.000 0.000 0.000 0.000 {built-in method __new__ of type object at 0x1E22B4F8} 8 0.000 0.000 0.000 0.000 {getattr} 61 0.000 0.000 0.000 0.000 {hasattr} 6 0.000 0.000 0.000 0.000 {isinstance} 32471566 2.246 0.000 2.246 0.000 {len} 3 0.000 0.000 0.000 0.000 {method 'add' of 'set' objects} 10496061 2.479 0.000 2.479 0.000 {method 'append' of 'list' objects} 990 0.000 0.000 0.000 0.000 {method 'clear' of 'dict' objects} 1 0.506 0.506 0.506 0.506 {method 'connect' of '_socket.socket' objects} 10823772 12.557 0.000 12.565 0.000 {method 'decode' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 3607923 3.371 0.000 3.371 0.000 {method 'encode' of 'str' objects} 2 0.000 0.000 0.000 0.000 {method 'fileno' of 'file' objects} 17 0.000 0.000 0.000 0.000 {method 'get' of 'dict' objects} 2 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 7215956 84.503 0.000 84.503 0.000 {method 'recv' of '_socket.socket' objects} 3 0.000 0.000 0.000 0.000 {method 'remove' of 'set' objects} 3607936 46.414 0.000 46.414 0.000 {method 'send' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 {method 'setsockopt' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'startswith' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'translate' of 'str' objects} 15 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects} 11 0.000 0.000 0.000 0.000 {method 'values' of 'dict' objects} 2 0.000 0.000 0.000 0.000 {msvcrt.get_osfhandle} 12 0.023 0.002 0.023 0.002 {range} 27 0.000 0.000 0.000 0.000 {setattr} 1 0.000 0.000 0.000 0.000 {sys.exit} 22 0.000 0.000 0.000 0.000 {time.clock} </code></pre>
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? </p> <pre><code> EdgeList = traci.edge.getIDList() #Returns a list of Strings for edge in EdgeList: meanspeed = traci.edge.getLastStepMeanSpeed(edge) #returns a float value ''' if edge in MeanspeedDict: MeanspeedDict[edge].append(meanspeed) MeanspeedDict[edge] = MeanspeedDict[edge][-300:] #Only keep the last 300 values else: MeanspeedDict[edge] = [meanspeed] ''' try: MeanspeedDict[edge].append(meanspeed) MeanspeedDict[edge] = MeanspeedDict[edge][-300:] #Only keep the last 300 values except KeyError: MeanspeedDict[edge] = [meanspeed] </code></pre> <p>Profile Data as per request. Running it <strong>11</strong> times</p> <pre><code> 252229348 function calls in 295.056 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 295.056 295.056 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 40.158 40.158 __init__.py:101(getVersion) 1 0.000 0.000 4.908 4.908 __init__.py:105(close) 1 0.000 0.000 0.000 0.000 __init__.py:111(switch) 1 0.000 0.000 0.507 0.507 __init__.py:45(connect) 1 0.000 0.000 0.000 0.000 __init__.py:49(normalize_encoding) 1 0.000 0.000 40.665 40.665 __init__.py:64(init) 1 0.000 0.000 0.008 0.008 __init__.py:71(search_function) 11 0.000 0.000 1.646 0.150 __init__.py:92(simulationStep) 3607912 2.785 0.000 221.939 0.000 _edge.py:151(getLastStepMeanSpeed) 1 0.000 0.000 0.000 0.000 codecs.py:92(__new__) 3607923 5.689 0.000 16.796 0.000 connection.py:119(_beginMessage) 3607923 3.451 0.000 210.529 0.000 connection.py:128(_sendReadOneStringCmd) 3607923 8.231 0.000 190.282 0.000 connection.py:152(_checkResult) 11 0.000 0.000 1.646 0.150 connection.py:254(simulationStep) 1 0.000 0.000 40.158 40.158 connection.py:273(getVersion) 1 0.000 0.000 4.908 4.908 connection.py:285(close) 1 0.000 0.000 0.507 0.507 connection.py:48(__init__) 3607923 4.167 0.000 8.645 0.000 connection.py:64(_packString) 3607936 19.808 0.000 108.622 0.000 connection.py:72(_recvExact) 3607936 19.507 0.000 200.505 0.000 connection.py:91(_sendExact) 15 0.000 0.000 0.000 0.000 copy.py:123(_copy_inst) 15 0.000 0.000 0.000 0.000 copy.py:66(copy) 15 0.000 0.000 0.000 0.000 domain.py:108(_setConnection) 3607923 4.273 0.000 236.643 0.000 domain.py:111(_getUniversal) 11 0.004 0.000 17.493 1.590 domain.py:116(getIDList) 15 0.000 0.000 0.000 0.000 domain.py:37(__init__) 495 0.000 0.000 0.000 0.000 domain.py:47(reset) 15 0.000 0.000 0.000 0.000 domain.py:99(_register) 1 0.000 0.000 0.000 0.000 latin_1.py:13(Codec) 1 0.000 0.000 0.000 0.000 latin_1.py:20(IncrementalEncoder) 1 0.000 0.000 0.000 0.000 latin_1.py:24(IncrementalDecoder) 1 0.000 0.000 0.000 0.000 latin_1.py:28(StreamWriter) 1 0.000 0.000 0.000 0.000 latin_1.py:31(StreamReader) 1 0.000 0.000 0.000 0.000 latin_1.py:34(StreamConverter) 1 0.000 0.000 0.000 0.000 latin_1.py:41(getregentry) 1 0.000 0.000 0.000 0.000 latin_1.py:8(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 six.py:180(find_module) 1 0.000 0.000 0.000 0.000 six.py:184(find_module) 1 0.001 0.001 0.001 0.001 socket.py:189(__init__) 1 0.000 0.000 0.000 0.000 socket.py:196(close) 2 0.000 0.000 0.506 0.253 socket.py:227(meth) 3607936 1.590 0.000 1.590 0.000 storage.py:32(__init__) 39687197 29.658 0.000 39.432 0.000 storage.py:36(read) 12 0.000 0.000 0.000 0.000 storage.py:41(readInt) 3607912 1.564 0.000 5.345 0.000 storage.py:44(readDouble) 3607924 1.712 0.000 5.389 0.000 storage.py:47(readLength) 10823772 17.543 0.000 50.373 0.000 storage.py:53(readString) 11 1.922 0.175 16.496 1.500 storage.py:57(readStringList) 1 0.000 0.000 0.000 0.000 subprocess.py:458(_cleanup) 1 0.000 0.000 0.000 0.000 subprocess.py:578(list2cmdline) 1 0.000 0.000 0.045 0.045 subprocess.py:651(__init__) 1 0.000 0.000 0.000 0.000 subprocess.py:811(_get_handles) 3 0.000 0.000 0.000 0.000 subprocess.py:881(_make_inheritable) 1 0.000 0.000 0.045 0.045 subprocess.py:905(_execute_child) 3 0.000 0.000 0.000 0.000 subprocess.py:946(_close_in_parent) 1 6.670 6.670 295.056 295.056 traciTest_meanspeed.py:45(runTraCI) 1 0.007 0.007 0.007 0.007 {__import__} 39687197 3.728 0.000 3.728 0.000 {_struct.calcsize} 10823795 3.374 0.000 3.374 0.000 {_struct.pack} 43295133 7.225 0.000 7.225 0.000 {_struct.unpack} 1 0.045 0.045 0.045 0.045 {_subprocess.CreateProcess} 3 0.000 0.000 0.000 0.000 {_subprocess.DuplicateHandle} 6 0.000 0.000 0.000 0.000 {_subprocess.GetCurrentProcess} 1 0.000 0.000 0.000 0.000 {_subprocess.GetStdHandle} 4 0.000 0.000 0.000 0.000 {built-in method Close} 1 0.000 0.000 0.000 0.000 {built-in method __new__ of type object at 0x1E22B4F8} 8 0.000 0.000 0.000 0.000 {getattr} 61 0.000 0.000 0.000 0.000 {hasattr} 6 0.000 0.000 0.000 0.000 {isinstance} 32471566 2.246 0.000 2.246 0.000 {len} 3 0.000 0.000 0.000 0.000 {method 'add' of 'set' objects} 10496061 2.479 0.000 2.479 0.000 {method 'append' of 'list' objects} 990 0.000 0.000 0.000 0.000 {method 'clear' of 'dict' objects} 1 0.506 0.506 0.506 0.506 {method 'connect' of '_socket.socket' objects} 10823772 12.557 0.000 12.565 0.000 {method 'decode' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 3607923 3.371 0.000 3.371 0.000 {method 'encode' of 'str' objects} 2 0.000 0.000 0.000 0.000 {method 'fileno' of 'file' objects} 17 0.000 0.000 0.000 0.000 {method 'get' of 'dict' objects} 2 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 7215956 84.503 0.000 84.503 0.000 {method 'recv' of '_socket.socket' objects} 3 0.000 0.000 0.000 0.000 {method 'remove' of 'set' objects} 3607936 46.414 0.000 46.414 0.000 {method 'send' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 {method 'setsockopt' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'startswith' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'translate' of 'str' objects} 15 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects} 11 0.000 0.000 0.000 0.000 {method 'values' of 'dict' objects} 2 0.000 0.000 0.000 0.000 {msvcrt.get_osfhandle} 12 0.023 0.002 0.023 0.002 {range} 27 0.000 0.000 0.000 0.000 {setattr} 1 0.000 0.000 0.000 0.000 {sys.exit} 22 0.000 0.000 0.000 0.000 {time.clock} </code></pre>
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 with white text. </p> <p>I know there is an <code>ax</code> parameter that we can specify in <code>hist()</code> but i am not sure how. </p> <p><a href="https://i.stack.imgur.com/lO6JQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/lO6JQ.png" alt="enter image description here"></a></p>
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 in enumerate(freq): ax.text(bins[i]+0.5, 2, n) ax.set_xlabel('Bins') ax.set_ylabel('Freq') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/t85V1.png" rel="nofollow"><img src="https://i.stack.imgur.com/t85V1.png" alt="Histogram, with Text"></a></p>
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 <code>Player</code> defined...</p> <pre><code>class Player(Model): name = CharField() </code></pre> <p><code>player.name_display_first_last</code> is a string</p> <p>I get an error that says <code>peewee.OperationalError: no such column: t1.name</code></p> <p>I've been trying to solve this problem for the bulk of today, but to no avail. Any help would be much appreciated. Let me know if you need any more information to help me. Thanks.</p>
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 before creating it's table.</p> <p>If you're just using test data for now, you can use <a href="http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.drop_table" rel="nofollow"><code>drop_table()</code></a> to delete the entire table and then re-create it with <a href="http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.create_tables" rel="nofollow"><code>create_tables()</code></a>.</p> <pre><code>drop_tables(Player) create_tables([Player]) </code></pre>
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 end with .0 always like in </p> <pre><code>pascaline(2) = [1, 2.0, 1.0] </code></pre> <p>How do I remove those .0 at the end? also, how can I do to start at $n=1$ and not at $0$? For instance, in this case, pascaline(2) should be [1, 1] and not [1, 2, 1]</p>
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 end with .0 always like in </p> <pre><code>pascaline(2) = [1, 2.0, 1.0] </code></pre> <p>How do I remove those .0 at the end? also, how can I do to start at $n=1$ and not at $0$? For instance, in this case, pascaline(2) should be [1, 1] and not [1, 2, 1]</p>
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 line = [1] for k in range(max(n,0)): line.append(line[k]*(n-k)//(k+1)) return line pascaline(2) &gt;&gt;&gt; [1,1] </code></pre>
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 end with .0 always like in </p> <pre><code>pascaline(2) = [1, 2.0, 1.0] </code></pre> <p>How do I remove those .0 at the end? also, how can I do to start at $n=1$ and not at $0$? For instance, in this case, pascaline(2) should be [1, 1] and not [1, 2, 1]</p>
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 still O(n), though:</p> <pre><code>def pascal_line(n): line = [1] mid, even = divmod(n, 2) for k in range(1, mid + 1): num = int(line[k-1]*(n + 1 - k)/(k)) line.append(num) reverse_it = reversed(line) if not even: next(reverse_it) for n in reverse_it: line.append(n) return line def pascal_line2(n): line = [1] for k in range(1, n + 1): num = int(line[k-1]*(n + 1 - k)/(k)) line.append(num) return line </code></pre> <p>Now, in action:</p> <pre><code>&gt;&gt;&gt; for i in range(21): ... print(pascal_line(i)) ... [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1] [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1] [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1] [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1] [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1] [1, 15, 105, 455, 1365, 3003, 5005, 6435, 6435, 5005, 3003, 1365, 455, 105, 15, 1] [1, 16, 120, 560, 1820, 4368, 8008, 11440, 12870, 11440, 8008, 4368, 1820, 560, 120, 16, 1] [1, 17, 136, 680, 2380, 6188, 12376, 19448, 24310, 24310, 19448, 12376, 6188, 2380, 680, 136, 17, 1] [1, 18, 153, 816, 3060, 8568, 18564, 31824, 43758, 48620, 43758, 31824, 18564, 8568, 3060, 816, 153, 18, 1] [1, 19, 171, 969, 3876, 11628, 27132, 50388, 75582, 92378, 92378, 75582, 50388, 27132, 11628, 3876, 969, 171, 19, 1] [1, 20, 190, 1140, 4845, 15504, 38760, 77520, 125970, 167960, 184756, 167960, 125970, 77520, 38760, 15504, 4845, 1140, 190, 20, 1] </code></pre> <p>Now, a quick and dirty time-test:</p> <pre><code>&gt;&gt;&gt; def time_me(f, n): ... start = time.time() ... f(n) ... stop = time.time() ... &gt;&gt;&gt; times = [time_me(pascal_line,n) for n in range(10, 1001,10)] &gt;&gt;&gt; times2 = [time_me(pascal_line2,n) for n in range(10, 1001,10)] &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import matplotlib.pyplot as plt &gt;&gt;&gt; n = range(10, 1001,10) &gt;&gt;&gt; df = pd.DataFrame({'pascal_lines':times, 'pascal_lines2':times2},index=list(n)) &gt;&gt;&gt; df.plot() &lt;matplotlib.axes._subplots.AxesSubplot object at 0x7f6c1c3d1c18&gt; &gt;&gt;&gt; plt.savefig('pascal.png') </code></pre> <p>Result:</p> <p><a href="https://i.stack.imgur.com/x2X4n.png" rel="nofollow"><img src="https://i.stack.imgur.com/x2X4n.png" alt="enter image description here"></a></p> <p>Not sure if it is worth it, since I'm reaching an <code>OverFlow</code> error somewhere soon after n = 1000.</p> <h2>EDIT</h2> <p>As others have pointed out, using integer division instead of converting from float to int is more efficient. It also has the added benefit of not throwing: <code>OverflowError: integer division result too large for a float</code> after around n = 1000.</p> <pre><code>def pascal_line0(n): line = [1] mid, even = divmod(n, 2) for k in range(1, mid + 1): num = line[k-1]*(n + 1 - k)//(k) line.append(num) reverse_it = reversed(line) if not even: next(reverse_it) for n in reverse_it: line.append(n) return line </code></pre> <p><a href="https://i.stack.imgur.com/GGrJP.png" rel="nofollow"><img src="https://i.stack.imgur.com/GGrJP.png" alt="enter image description here"></a></p>
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 = ["First", "Second", "Last"] for x in tries: Names = str(input(x,"Guess ?")) print(Names) </code></pre> <p>but it seems that Python doesn't accept this line: Names = str(input(x,"Guess ?"))</p> <p>so any suggestions how to make the Questions to be appearing to the user as: "First Guess?", then "Second Guess?", then "last guess?" </p>
-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 ?".format(x))) print(Names) </code></pre> <p>If you want more about <code>format</code>: <a href="http://devdocs.io/python~3.5/library/functions#format" rel="nofollow">on devdocs</a></p> <p>Matt</p>
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 = ["First", "Second", "Last"] for x in tries: Names = str(input(x,"Guess ?")) print(Names) </code></pre> <p>but it seems that Python doesn't accept this line: Names = str(input(x,"Guess ?"))</p> <p>so any suggestions how to make the Questions to be appearing to the user as: "First Guess?", then "Second Guess?", then "last guess?" </p>
-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 coders off but other functions won't allow it. you can fix it by simply adding the two strings together like this <code>input(x+"Guess ?")</code></p>
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</p> <pre><code>def valueOf(self, key): node = self._bstSearch(self._root, key) assert node is not None, "Invalid map key." return node.value def _bstSearch(self, subtree, target): if subtree is None: return None elif target &lt; subtree.key: return self._bstSearch( subtree.left, target) elif target &gt; subtree.key: return self._bstSearch(subtree.right, target) else: return subtree </code></pre> <p>I think I should be editing target to change it from a single item search to a ranged item search but I'm not 100% sure how to</p>
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 = [] # Traverse LEFT subtree if it is possible to find values in required range there. if subtree.key &gt; a: self._traverse_range(subtree.left, a, b, cumresult) # Push VALUE if it is in our range. if a &lt;= subtree.key &lt;= b: # Change to strict "&lt; b" to act like python's range cumresult.append(subtree.key) # Traverse RIGHT subtree if it is possible to find values in required range there. if subtree.key &lt; b: self._traverse_range(subtree.right, a, b, cumresult) return cumresult </code></pre>
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><code>import MySQLdb import csv conn = MySQLdb.connect(user='root', db='users', host='localhost') cursor = conn.cursor() cursor.execute('SELECT * FROM users.newusers') ver = cursor.fetchall() ver1 = [] for ve in ver: ve = str(ve).replace("', '","|").replace(", '","|").replace(","," ").replace(" "," ").replace("|",",") ver1.append(ve) print ver1 csv_file = open('filename', 'wb') writer = csv.writer(csv_file) writer.writerow(ver1) csv_file.close() </code></pre> <p>current output </p> <pre><code>"(114L,New,9180971675,Ravi Raju,RAJRAVI,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.0.1,no,yes')","(115L,New,9180971676,Rajendran Mohan,rajemoh,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.10.10,no,yes')" </code></pre> <p>expected out </p> <pre><code> 114L,New,9180971675,Ravi Raju,RAJRAVI,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.0.1,no,yes 115L,New,9180971676,Rajendran Mohan,rajemoh,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.10.10,no,yes </code></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 tuple both to get it into a nested list format and apply your <code>replace()</code> operations.</p> <pre><code>for ve in ver: ver1.append([str(item).replace(&lt;something&gt;) for item in ve]) </code></pre> <p>In the final step you use <code>csv.writerow()</code> which is designed to be used within a <code>for</code> loop. If your list is nested in the form <code>[[row1], [row2]]</code> then you can just change this to writerow<strong>s</strong>. Also, it's best practice to use the context manager <code>with</code> to handle files as this will automatically close the file once the operation is completed.</p> <pre><code>with open('filename.csv', 'wb') as csv_file: writer = csv.writer(csv_file) writer.writerows(ver1) </code></pre>
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 TypeError("Invalid data string supplied: " + astr) TypeError: Invalid data string supplied: a </code></pre> <p>Any suggestions?</p>
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 TypeError("Invalid data string supplied: " + astr) TypeError: Invalid data string supplied: a </code></pre> <p>Any suggestions?</p>
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 ordinary Python list (of lists). <code>np.matrix(...)</code> then takes this list and turns it into a <code>numpy</code> matrix.</p> <p>But really, you should be using</p> <pre><code>np.array(...) </code></pre> <p><code>np.matrix</code> was written to make things familiar to MATLAB visitors. Most <code>numpy</code> work is the <code>array</code>, not <code>matrix</code>.</p> <p>Another point - <code>a = np.cos(theta)</code> works with <code>theta</code> is scalar or an array. But if an array, than <code>a</code> itself will be an array, not a scalar. You should be aware of that when constructing this rotation matrix.</p>
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 = (np.log(equityToDebt * equityToDebt) + (riskFreeRate + 0.5 * volOfEquity**0.5) * TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5) d2 = (np.log(abs(equityToDebt * equityToDebt)) + (riskFreeRate - 0.5 * volOfEquity**0.5) * TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5) f1 = valueToEquity * norm.cdf(d1) - np.exp(-riskFreeRate * TimeToMaturity) * norm.cdf(d2) / equityToDebt - 1 f2 = norm.cdf(d1) * valueToEquity * volOfValue - volOfEquity return f1, f2 def solver(): equityToDebt = 1 volOfEquity = 0.2 riskFreeRate = 0.03 TimeToMaturity = 1 args = equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity x0 = [1, 0.2] sol = fsolve(KMV, x0, args=args) print(sol) </code></pre> <p>The solutions I get is </p> <pre><code>[ 1.29409904 0.17217742] </code></pre> <p>However if I use the following code:</p> <pre><code>print(KMV(sol, args=args)) </code></pre> <p>The exception is shown as below:</p> <pre><code> print(KMV(sol, args = args)) TypeError: KMV() got an unexpected keyword argument 'args' </code></pre> <p>Then I changed into another way to call KMV():</p> <pre><code>print(KMV(sol, args)) </code></pre> <p>The exception is another one:</p> <pre><code>ValueError: need more than 1 value to unpack </code></pre>
-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 keywords as well then pass a dictionary, often called <code>kwargs</code>. Note that the left-right order of these is critical. Here is a simple example:</p> <pre><code>def KMV(x, *args, **kwargs): if 'args' in kwargs: args = kwargs['args'], return args args = 1,2,3,4 sol = 42 print(KMV(sol, args)) print(KMV(sol, args = args)) </code></pre>
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 = (np.log(equityToDebt * equityToDebt) + (riskFreeRate + 0.5 * volOfEquity**0.5) * TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5) d2 = (np.log(abs(equityToDebt * equityToDebt)) + (riskFreeRate - 0.5 * volOfEquity**0.5) * TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5) f1 = valueToEquity * norm.cdf(d1) - np.exp(-riskFreeRate * TimeToMaturity) * norm.cdf(d2) / equityToDebt - 1 f2 = norm.cdf(d1) * valueToEquity * volOfValue - volOfEquity return f1, f2 def solver(): equityToDebt = 1 volOfEquity = 0.2 riskFreeRate = 0.03 TimeToMaturity = 1 args = equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity x0 = [1, 0.2] sol = fsolve(KMV, x0, args=args) print(sol) </code></pre> <p>The solutions I get is </p> <pre><code>[ 1.29409904 0.17217742] </code></pre> <p>However if I use the following code:</p> <pre><code>print(KMV(sol, args=args)) </code></pre> <p>The exception is shown as below:</p> <pre><code> print(KMV(sol, args = args)) TypeError: KMV() got an unexpected keyword argument 'args' </code></pre> <p>Then I changed into another way to call KMV():</p> <pre><code>print(KMV(sol, args)) </code></pre> <p>The exception is another one:</p> <pre><code>ValueError: need more than 1 value to unpack </code></pre>
-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(required_arg, optional_arg=False, other_optional_arg='something'): print(required_arg, optional_arg, other_optional_arg) # so, say you just want to specify the value of other_optional_arg, and let optional_arg have its default value (here False) # with python, you can do this func('the value for the required arg', other_optional_arg='My super great value') # output ('the value for the required arg', False, 'My super great value') def func(**kwargs): # type(kwargs) = dict print(kwargs ) func(arg1='hello', arg2='world', arg3='!') # output {'arg3': '!', 'arg2': 'world', 'arg1': 'hello'} </code></pre>
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 function is to return title lookalike string with exception (<code>minor_words</code>). <code>Minor_words</code> should be lower case in a title (despite the case if <code>minor_words</code> is the first word in the <code>title</code>)</p> <pre><code>def title_case(title, minor_words): exc = [x for x in title.lower().split() if x in minor_words.lower().split()] for string in exc: if title.split().index(string) == 0: title = title.title() else: title = title.title().replace(string, string.lower()) return title print (title_case('THE WIND IN THE WILLOWS', 'The In')) </code></pre>
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_set new_title = ' '.join(i if i in minor_set else i.capitalize() for i in tokens) # Finally return the capitalized title. if len(new_title) &gt; 1: return new_title[0].upper() + new_title[1:] else: # Since its just one char, just uppercase it and return it return new_title.upper() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; print (title_case('THE WIND IN THE WILLOWS', 'The In')) The Wind in the Willows </code></pre>
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 function is to return title lookalike string with exception (<code>minor_words</code>). <code>Minor_words</code> should be lower case in a title (despite the case if <code>minor_words</code> is the first word in the <code>title</code>)</p> <pre><code>def title_case(title, minor_words): exc = [x for x in title.lower().split() if x in minor_words.lower().split()] for string in exc: if title.split().index(string) == 0: title = title.title() else: title = title.title().replace(string, string.lower()) return title print (title_case('THE WIND IN THE WILLOWS', 'The In')) </code></pre>
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 first word capital can be done with <code>title = title.title()[0]+title[1:]</code></p>
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 function is to return title lookalike string with exception (<code>minor_words</code>). <code>Minor_words</code> should be lower case in a title (despite the case if <code>minor_words</code> is the first word in the <code>title</code>)</p> <pre><code>def title_case(title, minor_words): exc = [x for x in title.lower().split() if x in minor_words.lower().split()] for string in exc: if title.split().index(string) == 0: title = title.title() else: title = title.title().replace(string, string.lower()) return title print (title_case('THE WIND IN THE WILLOWS', 'The In')) </code></pre>
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>def title_case(title, minor_words): """Title case, excluding minor words, but including the first word""" exclusions = minor_words.lower().split() words = title.split() # Loop over the words, replace each word with either the title # case (for first word and words not in the exclusions list) # or the lower case (for excluded words) for i, word in enumerate(words): if i == 0 or word.lower() not in exclusions: words[i] = words[i].title() else: words[i] = words[i].lower() title = " ".join(words) return title print (title_case('THE WIND IN THE WILLOWS', 'The In')) </code></pre>
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, shell=True) </code></pre> <p>But I get the following output when running the script:</p> <pre><code>The filename, directory name, or volume label syntax is incorrect. Traceback (most recent call last): File "C:\Users\ochitaya\Desktop\New\myProj\sc.py", line 10, in &lt;module&gt; retCode = subprocess.check_call(cmakeCmd, stderr=subprocess.STDOUT, shell=True) File "C:\Python27\lib\subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['C:\\Program Files\\CMake\x08in\\cmake.exe', '-G Visual Studio 11 Win64', 'C:\\Users\\ochitaya\\Desktop\new\\myProj']' returned non-zero exit status 1 </code></pre>
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 string to be read as-is, or in other words, as a <strong>raw</strong> string, by prefixing the string with <code>r</code>:</p> <pre><code>cmakeCmd = [r"C:\Program Files\CMake\bin\cmake.exe",'-G Visual Studio 11 Win64', r'C:\Users\MyUser\Desktop\new\myProject'] </code></pre> <p>For more on this topic, take a look at the official documentation on <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">string literals</a>.</p>
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> <pre><code>def game(): #defines the games script start_time = time.time() #starts game timer. correct = 0 #recalls amount of correct questions. wrong = 0 time.sleep(2) #sleep function pauses game for 2 seconds. list1 = ["10","7","13","4","1","6","9","12","17","2"] #list of answers, if statements check answer for each question. i.e: 1 number = answer for 1 question. print "\nQuestion 1:\n" #printed text. print "First question: _ - 8 = 2" #prints user question. print "a, 10" #prints question hint. print "b, 9" #prints question hint. print "c, 13" #prints question hint. list1 = raw_input("Your answer: ") #asks user to input answer. if list1 == "10": #checks list above for answer. correct += 1 #adds 1 to correct total. print "\n\t Wonderful, correct",list1,"- 8 = 2\n" #printed text. else: #if not correct, else checks and chooses wrong. wrong +=1 #adds 1 to wrong total. print "\n\tSorry you got that number wrong. The correct number was 10\n" #printed text. </code></pre>
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> <pre><code>def game(): #defines the games script start_time = time.time() #starts game timer. correct = 0 #recalls amount of correct questions. wrong = 0 time.sleep(2) #sleep function pauses game for 2 seconds. list1 = ["10","7","13","4","1","6","9","12","17","2"] #list of answers, if statements check answer for each question. i.e: 1 number = answer for 1 question. print "\nQuestion 1:\n" #printed text. print "First question: _ - 8 = 2" #prints user question. print "a, 10" #prints question hint. print "b, 9" #prints question hint. print "c, 13" #prints question hint. list1 = raw_input("Your answer: ") #asks user to input answer. if list1 == "10": #checks list above for answer. correct += 1 #adds 1 to correct total. print "\n\t Wonderful, correct",list1,"- 8 = 2\n" #printed text. else: #if not correct, else checks and chooses wrong. wrong +=1 #adds 1 to wrong total. print "\n\tSorry you got that number wrong. The correct number was 10\n" #printed text. </code></pre>
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 #recalls amount of correct questions. wrong = 0 time.sleep(2) #sleep function pauses game for 2 seconds. list2 = ["\nQuestion 1", "\nQuestion 2", "\nQuestion 3", "\nQuestion 4", "\nQuestion 5", "\nQuestion 6", "\nQuestion 7", "\nQuestion 8", "\nQuestion 9", "\nQuestion 10",] list3 = ["_ - 8 = 2", "_ - 4 = 3", "20 - _ = 7", "11 - 7 = _", "5 - _ = 4", "19 - 13 = _", "_ - 7 = 2", "17 - 5 = _", "_ - 6 = 11", "15 - 13 = _"] ans = ["10","7","13","4","1","6","9","12","17","2"] #list of answers, if statements check answer for each question. i.e: 1 number = answer for 1 question. ans2 = ["10 - 8 = 2", "7 - 4 = 3", "20 - 13 = 7", "11 - 7 = 4", "5 - 1 = 4", "19 - 13 = 6", "9 - 7 = 2", "17 - 5 = 12", "17 - 6 = 11", "15 - 13 = 2"] op = list(zip(list3, ans, ans2)) #zips operations to be randomly unzipped. random.shuffle(op) #shuffles the questions out of order everytime list3, ans, ans2 = zip(*op) #sets op as zip * is used to unzip print list2[0] #printed text. print list3[0] #prints user question. op = raw_input("Your answer: ") #asks user to input answer. if op == ans[0]: #checks list above for answer. correct += 1 #adds 1 to correct total. print "\n\t Wonderful, correct",ans2[0],"\n" #printed text. else: #if not correct, else checks and chooses wrong. wrong +=1 #adds 1 to wrong total. print "\n\tSorry you got that number wrong.",ans2[0],"\n" #printed text. </code></pre>
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 <code>dice(x)</code>,</p> <pre><code>freq_list = list(range(1,(n+1))) rollfreq = [0]*n for w in dice(x): rollfreq[w-1] += 1 print zip(freq_list,rollfreq) </code></pre> <p>I get a list such as <code>[(1,0),(2,4),(3,1)...]</code> so on, which is expected, yet the problem is the rollfreq valus doesn't match the original randomly generated <code>dice(x)</code> list. I assume it is because since it is RNG, it changes the values of the <code>dice(x)</code> in the second run as well so that I can not refer to my original randomly generated <code>dice(x)</code> function. Is there any solution to this? I mean I tried almost everything, yet it apparently doesn't work!</p> <p>EDIT:</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(): rolls = [] for i in range(x): rolls.append(random.randrange(1, (n+1))) return rolls print dice() freq_list = list(range(1,(n+1))) rollfreq = [0]*n for w in dice(): rollfreq[w-1] += 1 print 'The number of frequency of each side:', zip(freq_list,rollfreq) </code></pre> <p>I have added the code - hope you guys can help me figure it out this, thank you!</p>
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(): rolls = [] for i in range(x): rolls.append(random.randrange(1, (n+1))) return rolls freq_list = list(range(1,(n+1))) rollfreq = [0]*n # Grab the rolls rolls = dice() # Print them here print(rolls) for w in rolls: rollfreq[w-1] += 1 print 'The number of frequency of each side:', zip(freq_list,rollfreq) </code></pre>
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</a></p> <p>I was trying to code it with as little help as possible, but I kept getting this error:</p> <p>C:\Users\"My Real Name"\Anaconda2\lib\site-packages\ipykernel__main__.py:29: RuntimeWarning: invalid value encountered in double_scalars</p> <p>With no data points on my plot. So I literally pasted all the code in directly from the website and I still get there error! I give up, can someone help a python newbie?</p> <pre><code>import numpy as np from matplotlib import pyplot from math import sin, cos, log, ceil %matplotlib inline from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 # model parameters: g = 9.8 # gravity in m s^{-2} v_t = 30.0 # trim velocity in m s^{-1} C_D = 1/40 # drag coefficient --- or D/L if C_L=1 C_L = 1 # for convenience, use C_L = 1 ### set initial conditions ### v0 = v_t # start at the trim velocity (or add a delta) theta0 = 0 # initial angle of trajectory x0 = 0 # horizotal position is arbitrary y0 = 1000 # initial altitude def f(u): v = u[0] theta = u[1] x = u[2] y = u[3] return np.array([-g*sin(theta) - C_D/C_L*g/v_t**2*v**2, -g*cos(theta)/v + g/v_t**2*v, v*cos(theta), v*sin(theta)]) def euler_step(u, f, dt): u + dt * f(u) T = 100 # final time dt = 0.1 # time increment N = int(T/dt) + 1 # number of time-steps t = np.linspace(0, T, N) # time discretization # initialize the array containing the solution for each time-step u = np.empty((N, 4)) u[0] = np.array([v0, theta0, x0, y0])# fill 1st element with initial values # time loop - Euler method for n in range(N-1): u[n+1] = euler_step(u[n], f, dt) x = u[:,2] y = u[:,3] pyplot.figure(figsize=(8,6)) pyplot.grid(True) pyplot.xlabel(r'x', fontsize=18) pyplot.ylabel(r'y', fontsize=18) pyplot.title('Glider trajectory, flight time = %.2f' % T, fontsize=18) pyplot.plot(x,y, 'k-', lw=2); </code></pre>
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 examples are complete, I want to switch the existing setup to a mysql backend. If that is too complex, I at least want to re-create the built-in examples that come with Mezzanine on the new backend, but Mezzanine won't allow re-running <code>createdb</code></p> <pre><code>CommandError: Database already created, you probably want the migrate command </code></pre> <p>This seems like something that should be incredibly simple, yet I can't seem to get it quite right (and <code>migrate</code> alone does not do the trick). Google and official docs not helping either.</p> <p>Steps I am taking: first, I create a MySQL database on Amazon RDS. Then, I set appropriate configuration for it in myapp/local_settings (I am sure these steps are correct). Then:</p> <pre><code>sudo apt install python-mysqldb sudo -u mezzanine python /srv/mezzanine/manage.py migrate </code></pre> <p>but then:</p> <pre><code>Running migrations: No migrations to apply. </code></pre> <p>What am I missing?</p>
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 schema (because apps evolve &amp; databases are metamorphic).</p> <p>In order to actually migrate the data however you could:</p> <ol> <li><p><strong>Export the contents from the current database, eg:</strong></p> <p>./manage.py dumpdata > db-dump-in-json.json<br> ./manage.py --format=xml > db-dump-in-xml.xml</p></li> </ol> <p>This may crash if there is too much data or not enough memory. Then the thing would be to use native DB tools to get the <em>dump</em>.</p> <ol start="2"> <li><p><strong>Create and add the settings for the new DB in <code>settings.py</code>:</strong></p></li> <li><p><strong>Create the tables and set them up (based on your <em>models</em>) on the newly defined DB:</strong></p> <p>./manage.py makemigrations<br> ./manage.py migrate</p></li> </ol> <p><code>createdb</code> = <code>syncdb</code> (create) + <code>migrate</code> (set) combined </p> <ol start="4"> <li><p><strong>And reload the exported data there:</strong></p> <p>./manage.py loaddata db-dump-in-json.json</p></li> </ol>
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['family'] age = requst.json['age'] </code></pre> <p>but, how do i get the address field and save it to a variable?</p>
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>address = request.json['address'] &gt;&gt;&gt; address {'country': 'Iran', 'State': 'Ilam', 'city': 'ilam'} </code></pre> <p>Address that you extracted is now a new dictionary, and you need to extract values from it like this:</p> <pre><code>state = address['State'] city = address['city'] country = address['country'] </code></pre>
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 write some cool one liner code.</p> <p>Please help!</p> <p>My approach was :</p> <p>1.) Convert list of int into list of string.</p> <p>2.) then use for loop to check for either character 2 or character 3 like this: <code>A=[x for x in l if "2" not in x]</code> (not sure for how to include 3 also in this line)</p> <p>3.) Convert A list into integer list using :</p> <p><code>B= [int(numeric_string) for numeric_string in A]</code></p> <p>This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.</p>
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 write some cool one liner code.</p> <p>Please help!</p> <p>My approach was :</p> <p>1.) Convert list of int into list of string.</p> <p>2.) then use for loop to check for either character 2 or character 3 like this: <code>A=[x for x in l if "2" not in x]</code> (not sure for how to include 3 also in this line)</p> <p>3.) Convert A list into integer list using :</p> <p><code>B= [int(numeric_string) for numeric_string in A]</code></p> <p>This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.</p>
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 list comprehension in particular is perfectly Pythonic. All you need now is a function that returns a boolean for your particular needs.</p>
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 could be accomplished. Something along the lines of:</p> <pre><code>&gt;&gt;&gt; X = type('X', (), {'name':'World', 'greet':print("Hello {0}!".format(name))} &gt;&gt;&gt; X.greet() Hello World! </code></pre>
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 file:</p> <pre><code>E4:DD:EF:1C:00:4F, 2012-10-08 11:29:04, 2012-10-08 11:29:56, -75, 9, 18:35:2C:18:16:ED, </code></pre>
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 list with all the elements in column 6 of you cvs.</p>
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 file:</p> <pre><code>E4:DD:EF:1C:00:4F, 2012-10-08 11:29:04, 2012-10-08 11:29:56, -75, 9, 18:35:2C:18:16:ED, </code></pre>
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 use <strong>DictReader</strong> and its methods.</p> <pre><code>import csv res = [] with open('simple.csv', 'rb') as f: reader = csv.reader(f, delimiter=',') for row in reader: # Index start with 0 so the 6th column will be 5th index # Using strip method would trim the empty spaces of column value # Check the length of columns is more than 5 to handle uneven columns if len(row) &gt; 5 and len(row[5].strip()) == 17: res.append(row[0]) # Result with column 0 where column 6 has 17 char length print res </code></pre>
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), ('Sony', 'Handphone', 100) ] d = defaultdict(lambda: defaultdict(int)) for brand, thing, quantity in the_list: d[brand][thing] += quantity </code></pre> <p>My result is:</p> <pre><code>defaultdict(&lt;function &lt;lambda&gt; at 0x02715C70&gt;, {'Sony': defaultdict(&lt;type 'int'&gt;, {'Handphone': 100}), 'Samsung': defaultdict(&lt;type 'int'&gt;, {'Handphone': 9, 'Tablet': 10})}) </code></pre> <p>I want my result to be this:</p> <pre><code>{ 'Samsung': { 'Handphone': 9, 'Tablet': 10 }, 'Sony': { 'Handphone': 100 } } </code></pre> <p>How am I supposed to do remove the <code>defaultdict(&lt;function &lt;lambda&gt; at 0x02715C70&gt;, {'Sony': defaultdict(&lt;type int'&gt;,</code> to achieve my desired output. Thank you!</p>
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.items() } #output {'Sony': {'Handphone': 100}, 'Samsung': {'Tablet': 10, 'Handphone': 9}} </code></pre>
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), ('Sony', 'Handphone', 100) ] d = defaultdict(lambda: defaultdict(int)) for brand, thing, quantity in the_list: d[brand][thing] += quantity </code></pre> <p>My result is:</p> <pre><code>defaultdict(&lt;function &lt;lambda&gt; at 0x02715C70&gt;, {'Sony': defaultdict(&lt;type 'int'&gt;, {'Handphone': 100}), 'Samsung': defaultdict(&lt;type 'int'&gt;, {'Handphone': 9, 'Tablet': 10})}) </code></pre> <p>I want my result to be this:</p> <pre><code>{ 'Samsung': { 'Handphone': 9, 'Tablet': 10 }, 'Sony': { 'Handphone': 100 } } </code></pre> <p>How am I supposed to do remove the <code>defaultdict(&lt;function &lt;lambda&gt; at 0x02715C70&gt;, {'Sony': defaultdict(&lt;type int'&gt;,</code> to achieve my desired output. Thank you!</p>
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>{ "Sony": { "Handphone": 100 }, "Samsung": { "Handphone": 9, "Tablet": 10 } } </code></pre> <p>This will serve as a solution if order does not matter.</p>
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 categorical features. To do this, each categorical feature should be replaced with dummy columns in the feature table (one column for each possible value of a categorical feature), and then encode it in a binary manner such that at most only one of the dummy columns can take “1” at a time (and zero for the rest). For example, “Gender” can take two values “m” and “f”. Thus, we need to replace this feature (in the feature table) by two columns titled “m” and “f”. Wherever, we have a male subject, we can put “1” and ”0” in the columns “m” and “f”. Wherever, we have a female subject, we can put “0” and ”1” in the columns “m” and “f”. (Hint: you will need 4 columns to encode “ChestPain” and 3 columns to encode “Thal”).</p> <p>my code so far is this ,</p> <pre><code># a- Read the dataset from the following URL: # and assign it to a Pandas DataFrame heart_d = pd.read_csv("C:/Users/Michael/Desktop/HW2/Heart_s.csv") feature_cols = ['Age','RestBP','Chol','RestECG','MaxHR','Oldpeak'] X = heart_d[feature_cols] y = heart_d['AHD'] # Randomly splitting the original dataset into training set and testing set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3) </code></pre> <p>this works so far , but now i have to use that one hot encoding for the catagorical stuff , but im totally lost with how that works. the 3 categorical features in the dataset are (Gender, ChestPain, Thal). i tried doin this</p> <pre><code>df_cp = pd.get_dummies(heart_d['ChestPain']) df_g = pd.get_dummies(heart_d['Gender']) df_t = pd.get_dummies(heart_d['Thal']) df_new = pd.concat([df, df_cp,df_g,df_t ], axis=1) </code></pre> <p>but im not sure thats working , when i run my classifications i get the same answer for everything</p>
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 OneHotEncoder &gt;&gt;&gt; enc = OneHotEncoder() &gt;&gt;&gt; enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]]) OneHotEncoder(categorical_features='all', dtype=&lt;... 'numpy.float64'&gt;, handle_unknown='error', n_values='auto', sparse=True) &gt;&gt;&gt; enc.n_values_ array([2, 3, 4]) &gt;&gt;&gt; enc.feature_indices_ array([0, 2, 5, 9]) &gt;&gt;&gt; enc.transform([[0, 1, 1]]).toarray() array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]]) </code></pre> <p>==== UPDATE ====</p> <p>I write one detail example about how to use one-hot encoder for string attributes, with <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html" rel="nofollow">DictVectorizer</a> </p> <pre><code>import pandas as pd from sklearn.feature_extraction import DictVectorizer as DV d = [ {'country':'A', 'Gender':'M'}, {'country':'B', 'Gender':'F'}, {'country':'C', 'Gender':'F'} ] df = pd.DataFrame(d) print df test_d = [ {'country':'A', 'Gender':'F'}, {'country':'B', 'Gender':'F'} ] test_df = pd.DataFrame(test_d) print test_df train_x = df.T.to_dict().values() vx = DV(sparse=False) transform_x = vx.fit_transform(train_x) print 'transform_train_df' print transform_x test_x = test_df.T.to_dict().values() transform_test_x = vx.transform(test_x) print 'transform_test_df' print transform_test_x </code></pre> <p>output:</p> <pre><code> Gender country 0 M A 1 F B 2 F C Gender country 0 F A 1 F B transform_train_df [[ 0. 1. 1. 0. 0.] [ 1. 0. 0. 1. 0.] [ 1. 0. 0. 0. 1.]] transform_test_df [[ 1. 0. 1. 0. 0.] [ 1. 0. 0. 1. 0.]] </code></pre>
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(**kwargs): for k,v in fmm.items(): print(v*2) my_func() </code></pre>
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_func(**fmm) print(fmm) </code></pre> <p>Note that I wasn't able to directly change the arguments; Python makes a copy of the passed dict.</p>
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(**kwargs): for k,v in fmm.items(): print(v*2) my_func() </code></pre>
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 these files are supposed to go...</p> <p>Im really new to programming and I just wanted to try it out :)</p> <p><em>EDIT: PyInstaller did make a compiled .pyc file for the one I wanted, but didn't create the .exe</em></p>
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(): frm = form.save(commit=False) frm.user = request.user frm.status = False obj = frm.save() cap_formset = CapFormSet(request.POST) cap_formset.instance = frm # Tried obj also it throws - 'NoneType' object has no attribute '_state' cap_formset.save() </code></pre> <p><strong>My Form</strong></p> <pre><code>class CapForm(forms.ModelForm): title = forms.CharField(label=_('Cap')) class Meta: model = Cap fields = ('title',) def __init__(self,*args,**kwargs): super(CapForm,self).__init__(*args,**kwargs) for name, field in self.fields.iteritems(): field.widget.attrs.update({'class': 'form-control', 'placeholder': field.label}) </code></pre> <p><strong>Formset declaration</strong></p> <pre><code>CapFormSet = inlineformset_factory(Ses, Cap, form=CapForm, extra=1, can_delete=True) </code></pre> <p>Can any one help me pointing where the issue is</p>
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, 10)) chosen_num = eval(input("Enter a number between 1 and 10, inclusive: ")) occurences = num_list.count(chosen_num) print() print("The number " + str(chosen_num) + " occurs " + str(occurences) + " time(s) in the list ") </code></pre> <p>Is there any way I can use a "for" loop or if-else statement to determine the number of times a number appears in the list, rather than using .count?</p> <p>Thanks.</p>
-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, 10)) chosen_num = eval(input("Enter a number between 1 and 10, inclusive: ")) occurences = num_list.count(chosen_num) print() print("The number " + str(chosen_num) + " occurs " + str(occurences) + " time(s) in the list ") </code></pre> <p>Is there any way I can use a "for" loop or if-else statement to determine the number of times a number appears in the list, rather than using .count?</p> <p>Thanks.</p>
-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(input("Enter a number between 1 and 10, inclusive: ")) occurences = 0 for item in num_list: if item == chosen_num: occurences += 1 print() print("The number " + str(chosen_num) + " occurs " + str(occurences) + " time(s) in the list ") </code></pre>
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> <pre><code>response = requests.get('https://fw.tmall.com/tmall/ser/tmall_detail.htm?spm=a1z1g.2177293.0.0.qF9gPO&amp;service_code=ts-4078').text soup = BeautifulSoup(response) main_wrapper = soup.find('div',attrs={'id':'success-case'}).findAll('a') for items in main_wrapper: dictionary = {} href = items['href'] if items.string is None: print items['href'] else: print items.string </code></pre> <p>How do I do it so that <code>if items.string is None:</code> get that item specific URL only and not all the URL?</p>
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> <p>Not clear what that means. Each <code>a</code> tag only has one, specific URL. You are iterating over a list of <code>a</code> tags, therefore you get a list of URLs</p> <blockquote> <p>I want to get specific HTML attribute, in this case it would be IMG URL that's inside <code>&lt;a&gt;</code> </p> </blockquote> <p>Then you need another <code>find</code> method within the loop to extract out that <code>&lt;img&gt;</code> element to get the <code>src</code> attribute </p>
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> <pre><code>response = requests.get('https://fw.tmall.com/tmall/ser/tmall_detail.htm?spm=a1z1g.2177293.0.0.qF9gPO&amp;service_code=ts-4078').text soup = BeautifulSoup(response) main_wrapper = soup.find('div',attrs={'id':'success-case'}).findAll('a') for items in main_wrapper: dictionary = {} href = items['href'] if items.string is None: print items['href'] else: print items.string </code></pre> <p>How do I do it so that <code>if items.string is None:</code> get that item specific URL only and not all the URL?</p>
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="rel-ink"&gt;&lt;img alt="NIHAOMARKET官方海外旗舰店" src="//img.alicdn.com/top/i1/TB1urimJFXXXXabaXXXwu0bFXXX.png" class="rel-img"&gt;&lt;/a&gt; &lt;a href="//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358" target="_blank" class="rel-name"&gt;NIHAOMARKET官方海外旗舰店&lt;/a&gt; </code></pre> <p>So you can use the anchor class name for the first anchor inside each <em>li</em> i.e <em>rel-ink</em> to get them:</p> <pre><code>urls =[a["href"] for a in soup.find('div', id="success-case").find_all("a",class_="rel-ink")] </code></pre> <p>Or using a <em>css selector</em>:</p> <pre><code>urls = [a["href"] for a in soup.select("#success-case ul li a.rel-ink")] </code></pre> <p>Both will give you:</p> <pre><code>['//store.taobao.com/shop/view_shop.htm?user_number_id=692020965', '//store.taobao.com/shop/view_shop.htm?user_number_id=2087799889', '//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358', '//store.taobao.com/shop/view_shop.htm?user_number_id=377676745', '//store.taobao.com/shop/view_shop.htm?user_number_id=2367059695', '//store.taobao.com/shop/view_shop.htm?user_number_id=449764134', '//store.taobao.com/shop/view_shop.htm?user_number_id=698389964', '//store.taobao.com/shop/view_shop.htm?user_number_id=509711360', '//store.taobao.com/shop/view_shop.htm?user_number_id=692020965', '//store.taobao.com/shop/view_shop.htm?user_number_id=1125022434', '//store.taobao.com/shop/view_shop.htm?user_number_id=1071997040', '//store.taobao.com/shop/view_shop.htm?user_number_id=795947607', '//store.taobao.com/shop/view_shop.htm?user_number_id=509711360', '//store.taobao.com/shop/view_shop.htm?user_number_id=692020965', '//store.taobao.com/shop/view_shop.htm?user_number_id=1071997040', '//store.taobao.com/shop/view_shop.htm?user_number_id=509711360', '//store.taobao.com/shop/view_shop.htm?user_number_id=377676745', '//store.taobao.com/shop/view_shop.htm?user_number_id=2367059695', '//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358'] </code></pre>
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 number out of a string should be easy. </p> <p>Basically, I am doing the following: </p> <pre><code>string = x_1 number = string[2:] number == 2 et voila! </code></pre> <p>To that goal, let's build up code</p> <pre><code>In [32]: import pandas as pd ...: d = {'id' : [1, 2, 3, 4], ...: 'str_id' : ['x_2', 'x_4', 'x_8', 'x_1']} ...: In [33]: df= pd.DataFrame(d) In [34]: df.head() Out[34]: id str_id 0 1 x_2 1 2 x_4 2 3 x_8 3 4 x_1 In [35]: df['num_id']=df.str_id.str[2:] In [36]: df.head() Out[36]: id str_id num_id 0 1 x_2 2 1 2 x_4 4 2 3 x_8 8 3 4 p_1 1 In [37]: df.dtypes Out[37]: id int64 str_id object num_id object dtype: object </code></pre> <p>The result LOOKS good -- we have an object, so we'll just convert to int and be golden, right? Sadly not so much. </p> <pre><code>In [38]: df['num_id3'] = int(df['num_id']) Traceback (most recent call last): File "&lt;ipython-input-38-50312cced30b&gt;", line 1, in &lt;module&gt; df['num_id3'] = int(df['num_id']) File "/Users/igor/anaconda/lib/python2.7/site-packages/pandas/core/series.py", line 92, in wrapper "{0}".format(str(converter))) TypeError: cannot convert the series to &lt;type 'int'&gt; </code></pre> <p>ok let's try something simpler ---stripping leading and trailing blanks </p> <pre><code> In [39]: df['num_id3'] = (df['num_id']).strip() Traceback (most recent call last): File "&lt;ipython-input-39-0af6d5f8bb8c&gt;", line 1, in &lt;module&gt; df['num_id3'] = (df['num_id']).strip() File "/Users/igor/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 2744, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'strip' </code></pre> <p>So .. somehow I have a series object ... with a single item in it ... I have not been able to get the series object to convert to anything usable</p> <p>Please will you help?! Thanks!</p>
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> instead:</p> <pre><code>In [32]: df Out[32]: id str_id 0 1 x_2 1 2 x_4 2 3 x_8 3 4 x_1 4 5 x_AAA In [33]: df['num_id'] = pd.to_numeric(df.str_id.str.extract(r'_(\d+)', expand=False)) In [34]: df Out[34]: id str_id num_id 0 1 x_2 2.0 1 2 x_4 4.0 2 3 x_8 8.0 3 4 x_1 1.0 4 5 x_AAA NaN </code></pre>
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.stack.imgur.com/OFZeu.png" rel="nofollow"><img src="https://i.stack.imgur.com/OFZeu.png" alt="Figure 1"></a></p> <p>Figure 2 <a href="https://i.stack.imgur.com/yjYPP.png" rel="nofollow"><img src="https://i.stack.imgur.com/yjYPP.png" alt="Figure 2"></a></p> <p>Although both should come in one window. Any advice where is mistake</p>
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="a", y="b", ax = ax) plt.show() </code></pre>
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(max_length=10) age = models.PositiveSmallInteger() </code></pre> <p>and I want to <a href="http://factoryboy.readthedocs.io/en/latest/orms.html" rel="nofollow">Factory Boy</a> create a <code>Country</code> with two children which have different attribute(s).</p> <p>For example, <code>somefactory.create()</code> creates <code>FooCountry</code> and <code>FooCountry</code> has two residents: </p> <pre><code>name=Paul, country=foo, age=33 name=Jamse, country=foo, age=34 </code></pre> <p>How to do it?</p>
-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) ResidentFactory.create(country=country, name=James, age=34) return country </code></pre>
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(A))] </code></pre> <p>finaly you can use the power of <code>numpy</code> to get C++ speedup:</p> <pre><code>import numpy as np A = np.array(A) A.shape = -1,1 # make it a column vector diff = np.abs(A - A.T) # diff is the matrix of abs differences # grab upper triangle of order 1 (i.e. less the diagonal) B = diff[np.triu_indices(len(A), k=1)] </code></pre> <p>But this will always be O(n^2) no matter what...</p>
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> <pre><code>Success b'The hosted network stopped. \r\n\r\n' </code></pre> <p>How to get output like this "Success The hosted network stopped."?</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 hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) </code></pre> <p>From the <a href="https://docs.python.org/3/library/subprocess.html#frequently-used-arguments" rel="nofollow"><em>Frequently Used Arguments</em> documentation section</a>:</p> <blockquote> <p>If <em>universal_newlines</em> is <code>True</code>, these file objects will be opened as text streams in universal newlines mode using the encoding returned by <code>locale.getpreferredencoding(False)</code>. For <code>stdin</code>, line ending characters <code>'\n'</code> in the input will be converted to the default line separator <code>os.linesep</code>. For <code>stdout</code> and <code>stderr</code>, all line endings in the output will be converted to <code>'\n'</code>. For more information see the documentation of the <code>io.TextIOWrapper</code> class when the newline argument to its constructor is <code>None</code>.</p> </blockquote> <p>For a process run via the shell, <code>locale.getpreferredencoding(False)</code> should be <em>exactly</em> the right codec to use, as that gets the information on what encoding to use from the exact same location that other processes like <code>netsh</code> are supposed to consult, the <a href="https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html" rel="nofollow">locale environment variables</a>.</p> <p>With <code>universal_newlines=True</code>, <code>output</code> will be set to the string <code>'The hosted network stopped. \n\n'; note the newlines at the end. You may want to use</code>str.strip()` to remove the extra whitespace there:</p> <pre><code>print("Success", output.strip()) </code></pre>
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> <pre><code>Success b'The hosted network stopped. \r\n\r\n' </code></pre> <p>How to get output like this "Success The hosted network stopped."?</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", output.decode()) </code></pre>
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) constraints are needed outside of a database context</p> <p>(e.g. If payment is a success, we must send the product activation code or else risk customer complaints, etc)</p> <p>But lets say on some fateful day, the <code>send_code()</code> function just failed time and again due to some temporary network error (that lasted for 1+ hours)</p> <p>Should I log the error, and manually fix the problem, e.g. send the mail manually </p> <p>Should I set up some kind of work queue, where when things fail, they just go back onto the end of the queue for future retry?</p> <p>What if the logging/queueing systems also fail? (am I worrying too much at this point?)</p>
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 down, we mark it like <code>status=error</code> and save to the database. Then we use cron job to find and finish those processes. You need to try something for the beginning and if does not fit your needs, try something else.</p>
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>Thanks</p>
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" ]