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
Reading a .json file using python - Flask
40,019,961
<p>I'm trying to read a <code>.json</code> file from within my Flask application using:</p> <pre><code>def renderblog(): with open(url_for("static", filename="blogs.json")) as blog_file: data = json.load(blog_file) </code></pre> <p>However I get the error:</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: '/static/blogs.json' </code></pre> <p>Now I know for a fact that the directory exists within my project structure, but I have no idea why I'm getting this error. Any ideas? Is there a specific way to retrieve <code>.json</code> in Flask? </p>
0
2016-10-13T11:40:36Z
40,020,056
<p>You generated a <em>URL path</em>, not a path to the local static folder. Use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.static_folder" rel="nofollow"><code>app.static_folder</code> attribute</a> instead:</p> <pre><code>def renderblog(): filename = os.path.join(app.static_folder, 'blogs.json') with open(filename) as blog_file: data = json.load(blog_file) </code></pre>
4
2016-10-13T11:45:02Z
[ "python", "json", "flask" ]
Replace IP addresses with filename in Python for all files in a directory
40,020,173
<p>If I knew the first thing about Python, I'd have figured this out myself just by referring to other similar questions that were already answered. </p> <p>With that out of the way, I'm hoping you can help me achieve the following: </p> <p>I'm looking to replace all occurrences of IP addresses with the file name itself, in a directory, inline.</p> <p>Let's say all my files are in <code>D:\super\duper\directory\</code></p> <p>Files don't have any extension, i.e., a sample file name will be <em><code>"jb-nnnn-xy"</code></em>. Even if there are multiple mentions of IP address in the file, I'm interested in replacing only the line that looks like this (without quotes):</p> <p><code>" TCPHOST = 72.163.363.25"</code></p> <p>So overall, there are thousands of files in the directory, of which only few have hard-coded IP addresses. </p> <p>And the line of interest should finally look like this:</p> <p><code>" TCPHOST = jb-yyyy-nz"</code></p> <p>where <em><code>"jb-yyyy-nz"</code></em> is the name of the file itself</p> <p>Thank you very much for your time and help!</p> <p>EDIT: Just a mish mash of code from other posts that I'm trying out..</p> <pre><code>from __future__ import print_function import fnmatch import os from fileinput import FileInput import re ip_addr_regex = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') def find_replace(topdir, text): for dirpath, dirs, files in os.walk(topdir, topdown=True): files = [os.path.join(dirpath, filename) for filename in files] for line in FileInput(files, inplace=True): print(line.replace(text, str(filename))) find_replace(r"D:\testmulefew",ip_addr_regex) </code></pre>
0
2016-10-13T11:49:40Z
40,021,305
<p>Please check the below code with comments inline:</p> <pre><code>import os import re import fileinput #Get the file list from the directory file_list = [f for f in os.listdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo")] #Change the directory where file to checked and modify os.chdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo") #FileInput takes file_list as input with fileinput.input(files=file_list,inplace=True) as f: #Read file line by line for line in f: d='' #Find the line with TCPHOST a = re.findall(r'TCPHOST\s*=\s*\d+\.',line.strip()) if len(a) &gt; 0: #If found update the line d = 'TCPHOST = '+str(fileinput.filename()) print (d) else: #Otherwise keep as it is print (line.strip()) </code></pre> <p><strong>P.S:</strong> <em>Assumed the directory contains file and it does not have other directory inside it. Otherwise, file listing need to do recursively.</em> </p>
0
2016-10-13T12:40:56Z
[ "python", "regex", "file", "replace", "substitution" ]
What python linter can I use to spot Python 2-3 compatibility issues?
40,020,178
<p>I want to migrate a Python codebase to work in both Python 2 and Python 3 and I was surprised to see that by default tools like flake8 or pep8 missed a very simple use of print without parentheses (<code>print 1</code> instead of <code>print(1)</code>).</p> <p>How can I ease this migration?</p>
0
2016-10-13T11:49:46Z
40,020,575
<p>You should use 2to3 to spot issues/incompatibilities in the code</p> <p><a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">https://docs.python.org/3/howto/pyporting.html</a></p>
1
2016-10-13T12:07:00Z
[ "python", "python-3.x", "pep8", "flake8" ]
SyntaxError: invalid syntax -- One line if statement in python
40,020,244
<p>My initial <code>if else</code> code is :</p> <pre><code>if response.get('fulfillments') is None: return (False, response) else: return (True, response) </code></pre> <p>But I want to convert it to <code>one-line-if-else-statement</code>. </p> <p>Here is what I am doing : </p> <pre><code>return (False, response) if response.get('fulfillments') is None else return (True, response) </code></pre> <p>But it is raising a syntax error, What am I doing wrong ?</p>
1
2016-10-13T11:52:51Z
40,020,329
<p>Omit the second <code>return</code>. To simplify:</p> <pre><code>&gt;&gt;&gt; def foo(x): ... return True if x == 2 else False </code></pre> <p>read it as "return the results of this ternary expression" not "return this thing in one case but return some other thing in another case"</p>
2
2016-10-13T11:56:25Z
[ "python", "if-statement" ]
SyntaxError: invalid syntax -- One line if statement in python
40,020,244
<p>My initial <code>if else</code> code is :</p> <pre><code>if response.get('fulfillments') is None: return (False, response) else: return (True, response) </code></pre> <p>But I want to convert it to <code>one-line-if-else-statement</code>. </p> <p>Here is what I am doing : </p> <pre><code>return (False, response) if response.get('fulfillments') is None else return (True, response) </code></pre> <p>But it is raising a syntax error, What am I doing wrong ?</p>
1
2016-10-13T11:52:51Z
40,020,365
<p>A one-line <code>if-else</code> is not the same as the block. It is an expression, not a statement or multiple statements. You can't do something like:</p> <pre><code>(x = 4) if x &gt; 5 else (x = 6) </code></pre> <p>Because those are statements. Instead, it is like this:</p> <pre><code>x = (4 if x &gt; 5 else 6) </code></pre> <p>Or in your case:</p> <pre><code>return (False, response) if response.get('fulfillments') is None else (True, response) </code></pre> <p>You don't really need the <code>if-else</code>, though. Just do this:</p> <pre><code>return (response.get('fulfillments') is not None, response) </code></pre>
6
2016-10-13T11:57:30Z
[ "python", "if-statement" ]
SyntaxError: invalid syntax -- One line if statement in python
40,020,244
<p>My initial <code>if else</code> code is :</p> <pre><code>if response.get('fulfillments') is None: return (False, response) else: return (True, response) </code></pre> <p>But I want to convert it to <code>one-line-if-else-statement</code>. </p> <p>Here is what I am doing : </p> <pre><code>return (False, response) if response.get('fulfillments') is None else return (True, response) </code></pre> <p>But it is raising a syntax error, What am I doing wrong ?</p>
1
2016-10-13T11:52:51Z
40,020,377
<pre><code>return (False, response) if response.get('fulfillments') is None else (True, response) </code></pre> <p><code>val_positive if expression else val_negative</code>. val_positive or val_negative can't contain return statement</p>
2
2016-10-13T11:58:09Z
[ "python", "if-statement" ]
Pandas groupby countif with dynamic columns
40,020,270
<p>I have a dataframe with this structure:</p> <pre><code>time,10.0.0.103,10.0.0.24 2016-10-12 13:40:00,157,172 2016-10-12 14:00:00,0,203 2016-10-12 14:20:00,0,0 2016-10-12 14:40:00,0,200 2016-10-12 15:00:00,185,208 </code></pre> <p>It details the number of events per IP address for a given 20 minute period. I need a dataframe of how many 20 minute periods per miner had 0 events, from which I need to derive IP 'uptime' as a percent. The number of IP addresses is dynamic. Desired output:</p> <pre><code>IP,noEvents,uptime 10.0.0.103,3,40 10.0.0.24,1,80 </code></pre> <p>I have tried with groupby, agg and lambda to no avail. What is the best way of doing a 'countif' by dynamic columns?</p>
2
2016-10-13T11:53:55Z
40,020,437
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a> of boolean mask by condition <code>df == 0</code>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> both <code>Series</code>:</p> <pre><code>df.set_index('time', inplace=True) mask = (df == 0) print (mask) 10.0.0.103 10.0.0.24 time 2016-10-12 13:40:00 False False 2016-10-12 14:00:00 True False 2016-10-12 14:20:00 True True 2016-10-12 14:40:00 True False 2016-10-12 15:00:00 False False noEvents = mask.sum() print (noEvents) 10.0.0.103 3 10.0.0.24 1 dtype: int64 uptime = 100 * mask.mean() print (uptime) 10.0.0.103 60.0 10.0.0.24 20.0 dtype: float64 print (pd.concat([noEvents, uptime], axis=1, keys=('noEvents','uptime')) .reset_index() .rename(columns={'index':'IP'})) IP noEvents uptime 0 10.0.0.103 3 60.0 1 10.0.0.24 1 20.0 </code></pre>
3
2016-10-13T12:01:20Z
[ "python", "pandas", "sum", "multiple-columns", "mean" ]
Pandas groupby countif with dynamic columns
40,020,270
<p>I have a dataframe with this structure:</p> <pre><code>time,10.0.0.103,10.0.0.24 2016-10-12 13:40:00,157,172 2016-10-12 14:00:00,0,203 2016-10-12 14:20:00,0,0 2016-10-12 14:40:00,0,200 2016-10-12 15:00:00,185,208 </code></pre> <p>It details the number of events per IP address for a given 20 minute period. I need a dataframe of how many 20 minute periods per miner had 0 events, from which I need to derive IP 'uptime' as a percent. The number of IP addresses is dynamic. Desired output:</p> <pre><code>IP,noEvents,uptime 10.0.0.103,3,40 10.0.0.24,1,80 </code></pre> <p>I have tried with groupby, agg and lambda to no avail. What is the best way of doing a 'countif' by dynamic columns?</p>
2
2016-10-13T11:53:55Z
40,024,011
<p>Transpose the <code>DF</code>:</p> <pre><code>df = df.T </code></pre> <p>Since you tried along the lines of using <code>groupby</code>, you could further proceed using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> to get the count of zeros in every group after stacking it to produce a <code>series</code> object and later unstack it back to the <code>DF</code> as shown:</p> <pre><code>grp = df.stack().to_frame('val').groupby(level=0)['val'] df['noEvents'] = grp.value_counts().unstack()[0] </code></pre> <p>Later, divide the values with the size of that group to get it's percentage distribution:</p> <pre><code>df['upTime'] = (100*df['noEvents']/grp.size()) </code></pre> <p>For Aesthetic purpose:</p> <pre><code>df = df[['noEvents', 'upTime']].astype(int) df.index.name = 'IP' df.columns.name = None df </code></pre> <p><a href="https://i.stack.imgur.com/zf06U.png" rel="nofollow"><img src="https://i.stack.imgur.com/zf06U.png" alt="Image"></a></p>
2
2016-10-13T14:36:20Z
[ "python", "pandas", "sum", "multiple-columns", "mean" ]
Pyplot errorbar keeps connecting my points with lines?
40,020,274
<p>I am having trouble getting these lines between my data points to go away! It seems to be whenever I try to add error bars it does this. If you look at the graphs, the first is without the errorbar line, and the second is with it. Is this a usual side effect of pyplot errorbar? Does anyone know why it does this, or how to make it go away? </p> <pre><code>plt.figure() plt.scatter(x, y, label = 'blah') plt.errorbar(x, y, yerr = None, xerr = x_err) plt.plot(x, f) #this is a line of best fit </code></pre> <p><a href="https://i.stack.imgur.com/HkMVT.png" rel="nofollow"><img src="https://i.stack.imgur.com/HkMVT.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/RY9rf.png" rel="nofollow"><img src="https://i.stack.imgur.com/RY9rf.png" alt="enter image description here"></a></p>
0
2016-10-13T11:54:00Z
40,020,492
<p>You can set the line style (<code>ls</code>) to <code>none</code>:</p> <pre><code>import numpy as np import matplotlib.pylab as plt x = np.arange(10) y = np.arange(10) yerr = np.random.random(10) xerr = np.random.random(10) plt.figure() plt.subplot(121) plt.scatter(x, y, label = 'blah') plt.errorbar(x, y, yerr = None, xerr = xerr) plt.subplot(122) plt.scatter(x, y, label = 'blah') plt.errorbar(x, y, yerr = None, xerr = xerr, ls='none') </code></pre> <p><a href="https://i.stack.imgur.com/dfiQi.png" rel="nofollow"><img src="https://i.stack.imgur.com/dfiQi.png" alt="enter image description here"></a></p>
2
2016-10-13T12:03:48Z
[ "python", "matplotlib", "errorbar" ]
How to remove words containing only numbers in python?
40,020,326
<p>I have some text in Python which is composed of numbers and alphabets. Something like this:</p> <pre><code>s = "12 word word2" </code></pre> <p>From the string s, I want to remove all the words containing <strong>only numbers</strong></p> <p>So I want the result to be </p> <pre><code>s = "word word2" </code></pre> <p>This is a regex I have but it works on alphabets i.e. it replaces each alphabet by a space.</p> <pre><code>re.sub('[\ 0-9\ ]+', ' ', line) </code></pre> <p>Can someone help in telling me what is wrong? Also, is there a more time-efficient way to do this than regex?</p> <p>Thanks!</p>
2
2016-10-13T11:56:14Z
40,020,376
<p>You can use this regex:</p> <pre><code>&gt;&gt;&gt; s = "12 word word2" &gt;&gt;&gt; print re.sub(r'\b[0-9]+\b\s*', '', s) word word2 </code></pre> <p><code>\b</code> is used for word boundary and <code>\s*</code> will remove 0 or more spaces after your number word.</p>
3
2016-10-13T11:58:06Z
[ "python", "regex", "string" ]
How to remove words containing only numbers in python?
40,020,326
<p>I have some text in Python which is composed of numbers and alphabets. Something like this:</p> <pre><code>s = "12 word word2" </code></pre> <p>From the string s, I want to remove all the words containing <strong>only numbers</strong></p> <p>So I want the result to be </p> <pre><code>s = "word word2" </code></pre> <p>This is a regex I have but it works on alphabets i.e. it replaces each alphabet by a space.</p> <pre><code>re.sub('[\ 0-9\ ]+', ' ', line) </code></pre> <p>Can someone help in telling me what is wrong? Also, is there a more time-efficient way to do this than regex?</p> <p>Thanks!</p>
2
2016-10-13T11:56:14Z
40,020,421
<p>Using a regex is probably a bit overkill here depending whether you need to preserve whitespace:</p> <pre><code>s = "12 word word2" s2 = ' '.join(word for word in s.split() if not word.isdigit()) # 'word word2' </code></pre>
6
2016-10-13T12:00:33Z
[ "python", "regex", "string" ]
How to remove words containing only numbers in python?
40,020,326
<p>I have some text in Python which is composed of numbers and alphabets. Something like this:</p> <pre><code>s = "12 word word2" </code></pre> <p>From the string s, I want to remove all the words containing <strong>only numbers</strong></p> <p>So I want the result to be </p> <pre><code>s = "word word2" </code></pre> <p>This is a regex I have but it works on alphabets i.e. it replaces each alphabet by a space.</p> <pre><code>re.sub('[\ 0-9\ ]+', ' ', line) </code></pre> <p>Can someone help in telling me what is wrong? Also, is there a more time-efficient way to do this than regex?</p> <p>Thanks!</p>
2
2016-10-13T11:56:14Z
40,020,470
<p>Without using any external library you could do:</p> <pre><code>stringToFormat = "12 word word2" words = "" for word in stringToFormat.split(" "): try: int(word) except ValueError: words += "{} ".format(word) print(words) </code></pre>
1
2016-10-13T12:02:48Z
[ "python", "regex", "string" ]
Flask-SQLAlchemy db.session.query(Model) vs Model.query
40,020,388
<p>This is a weird bug I've stumbled upon, and I am not sure why is it happening, whether it's a bug in SQLAlchemy, in Flask-SQLAlchemy, or any feature of Python I'm not yet aware of.</p> <p>We are using Flask 0.11.1, with Flask-SQLAlchemy 2.1 using a PostgreSQL as DBMS.</p> <p>Examples use the following code to update data from the database:</p> <pre><code>entry = Entry.query.get(1) entry.name = 'New name' db.session.commit() </code></pre> <p>This works totally fine when executing from the Flask shell, so the database is correctly configured. Now, our controller for updating entries, slightly simplified (without validation and other boilerplate), looks like this:</p> <pre><code>def details(id): entry = Entry.query.get(id) if entry: if request.method == 'POST': form = request.form entry.name = form['name'] db.session.commit() flash('Updated successfully.') return render_template('/entry/details.html', entry=entry) else: flash('Entry not found.') return redirect(url_for('entry_list')) # In the application the URLs are built dynamically, hence why this instead of @app.route app.add_url_rule('/entry/details/&lt;int:id&gt;', 'entry_details', details, methods=['GET', 'POST']) </code></pre> <p>When I submit the form in details.html, I can see perfectly fine the changes, meaning the form has been submitted properly, is valid and that the model object has been updated. However, when I reload the page, the changes are gone, as if it had been rolled back by the DBMS.</p> <p>I have enabled <code>app.config['SQLALCHEMY_ECHO'] = True</code> and I can see a "ROLLBACK" before my own manual commit.</p> <p>If I change the line:</p> <pre><code>entry = Entry.query.get(id) </code></pre> <p>To:</p> <pre><code>entry = db.session.query(Entry).get(id) </code></pre> <p>As explained in <a href="http://stackoverflow.com/a/21806294/4454028">http://stackoverflow.com/a/21806294/4454028</a>, it does work as expected, so my guess what there was some kind of error in Flask-SQLAlchemy's <code>Model.query</code> implementation.</p> <p>However, as I prefer the first construction, I did a quick modification to Flask-SQLAlchemy, and redefined the <code>query</code> <code>@property</code> from the original:</p> <pre><code>class _QueryProperty(object): def __init__(self, sa): self.sa = sa def __get__(self, obj, type): try: mapper = orm.class_mapper(type) if mapper: return type.query_class(mapper, session=self.sa.session()) except UnmappedClassError: return None </code></pre> <p>To:</p> <pre><code>class _QueryProperty(object): def __init__(self, sa): self.sa = sa def __get__(self, obj, type): return self.sa.session.query(type) </code></pre> <p>Where <code>sa</code> is the Flask-SQLAlchemy object (ie <code>db</code> in the controller).</p> <p>Now, this is where things got weird: it still doesn't save the changes. Code is exactly the same, yet the DBMS is still rolling back my changes.</p> <p>I read that Flask-SQLAlchemy can execute a commit on teardown, and tried adding this:</p> <pre><code>app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True </code></pre> <p>Suddenly, everything works. Question is: why?</p> <p>Isn't teardown supposed to happen only when the view has finished rendering? Why is the modified <code>Entry.query</code> behaving different to <code>db.session.query(Entry)</code>, even if the code is the same?</p>
1
2016-10-13T11:58:47Z
40,022,276
<p>So, the correct way to made changes in model instance and also committed them to DB is looks like this:-</p> <pre><code># get the instance of `Entry` entry = Entry.query.get(1) # change the attribute of an instance which you want, here `name` attribute is changed entry.name = 'New name' # now, commit your changes into the DB, this will flush all changes # in current session to DB db.session.commit() </code></pre> <p><strong>Note:</strong> Don't use <code>SQLALCHEMY_COMMIT_ON_TEARDOWN</code> , as it's considered harmful and also removed from docs. <a href="http://flask-sqlalchemy.pocoo.org/2.1/changelog/" rel="nofollow">See here</a> in changelog of version 2.0.</p> <p><strong>Edit:</strong> If you have two objects of <strong>normal session</strong> (created using <code>sessionmaker()</code>) instead of <strong>scoped session</strong> , then on calling <code>db.session.add(entry)</code> above code will raise error <code>sqlalchemy.exc.InvalidRequestError: Object '' is already attached to session '2' (this is '3')</code>. For more understanding about sqlalchemy session, read below section</p> <h2>Major Difference between Scoped Session vs. Normal Session</h2> <p>The session object we mostly constructed from the <code>sessionmaker()</code> call and used to communicate with our database is a <strong>normal session</strong>. If you call <code>sessionmaker()</code> a second time, you will get a new session object whose states are independent of the previous session. For example, suppose we have two session objects constructed in the following way:</p> <pre><code>from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String) from sqlalchemy import create_engine engine = create_engine('sqlite:///') from sqlalchemy.orm import sessionmaker session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) # Construct the first session object s1 = session() # Construct the second session object s2 = session() </code></pre> <p>Then, we won't be able to add the same User object to both <code>s1</code> and <code>s2</code> at the same time. In other words, an object can only be attached at most one unique session object.</p> <pre><code>&gt;&gt;&gt; jessica = User(name='Jessica') &gt;&gt;&gt; s1.add(jessica) &gt;&gt;&gt; s2.add(jessica) Traceback (most recent call last): ...... sqlalchemy.exc.InvalidRequestError: Object '' is already attached to session '2' (this is '3') </code></pre> <p>If the session objects are retrieved from a <code>scoped_session</code> object, however, then we don't have such an issue since the <code>scoped_session</code> object maintains a registry for the same session object.</p> <pre><code>&gt;&gt;&gt; session_factory = sessionmaker(bind=engine) &gt;&gt;&gt; session = scoped_session(session_factory) &gt;&gt;&gt; s1 = session() &gt;&gt;&gt; s2 = session() &gt;&gt;&gt; jessica = User(name='Jessica') &gt;&gt;&gt; s1.add(jessica) &gt;&gt;&gt; s2.add(jessica) &gt;&gt;&gt; s1 is s2 True &gt;&gt;&gt; s1.commit() &gt;&gt;&gt; s2.query(User).filter(User.name == 'Jessica').one() </code></pre> <p>Notice that<code>s1</code> and <code>s2</code> are the same session object since they are both retrieved from a <code>scoped_session</code> object who maintains a reference to the same session object.</p> <h2>Tips</h2> <p>So, try to avoid creating more than one <strong>normal session</strong> object. Create one object of the session and use it everywhere from declaring models to querying.</p>
2
2016-10-13T13:23:10Z
[ "python", "postgresql", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Flask-SQLAlchemy db.session.query(Model) vs Model.query
40,020,388
<p>This is a weird bug I've stumbled upon, and I am not sure why is it happening, whether it's a bug in SQLAlchemy, in Flask-SQLAlchemy, or any feature of Python I'm not yet aware of.</p> <p>We are using Flask 0.11.1, with Flask-SQLAlchemy 2.1 using a PostgreSQL as DBMS.</p> <p>Examples use the following code to update data from the database:</p> <pre><code>entry = Entry.query.get(1) entry.name = 'New name' db.session.commit() </code></pre> <p>This works totally fine when executing from the Flask shell, so the database is correctly configured. Now, our controller for updating entries, slightly simplified (without validation and other boilerplate), looks like this:</p> <pre><code>def details(id): entry = Entry.query.get(id) if entry: if request.method == 'POST': form = request.form entry.name = form['name'] db.session.commit() flash('Updated successfully.') return render_template('/entry/details.html', entry=entry) else: flash('Entry not found.') return redirect(url_for('entry_list')) # In the application the URLs are built dynamically, hence why this instead of @app.route app.add_url_rule('/entry/details/&lt;int:id&gt;', 'entry_details', details, methods=['GET', 'POST']) </code></pre> <p>When I submit the form in details.html, I can see perfectly fine the changes, meaning the form has been submitted properly, is valid and that the model object has been updated. However, when I reload the page, the changes are gone, as if it had been rolled back by the DBMS.</p> <p>I have enabled <code>app.config['SQLALCHEMY_ECHO'] = True</code> and I can see a "ROLLBACK" before my own manual commit.</p> <p>If I change the line:</p> <pre><code>entry = Entry.query.get(id) </code></pre> <p>To:</p> <pre><code>entry = db.session.query(Entry).get(id) </code></pre> <p>As explained in <a href="http://stackoverflow.com/a/21806294/4454028">http://stackoverflow.com/a/21806294/4454028</a>, it does work as expected, so my guess what there was some kind of error in Flask-SQLAlchemy's <code>Model.query</code> implementation.</p> <p>However, as I prefer the first construction, I did a quick modification to Flask-SQLAlchemy, and redefined the <code>query</code> <code>@property</code> from the original:</p> <pre><code>class _QueryProperty(object): def __init__(self, sa): self.sa = sa def __get__(self, obj, type): try: mapper = orm.class_mapper(type) if mapper: return type.query_class(mapper, session=self.sa.session()) except UnmappedClassError: return None </code></pre> <p>To:</p> <pre><code>class _QueryProperty(object): def __init__(self, sa): self.sa = sa def __get__(self, obj, type): return self.sa.session.query(type) </code></pre> <p>Where <code>sa</code> is the Flask-SQLAlchemy object (ie <code>db</code> in the controller).</p> <p>Now, this is where things got weird: it still doesn't save the changes. Code is exactly the same, yet the DBMS is still rolling back my changes.</p> <p>I read that Flask-SQLAlchemy can execute a commit on teardown, and tried adding this:</p> <pre><code>app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True </code></pre> <p>Suddenly, everything works. Question is: why?</p> <p>Isn't teardown supposed to happen only when the view has finished rendering? Why is the modified <code>Entry.query</code> behaving different to <code>db.session.query(Entry)</code>, even if the code is the same?</p>
1
2016-10-13T11:58:47Z
40,047,125
<p>Our project is separated in several files to ease mantenaince. One is <code>routes.py</code> with the controllers, and another one is <code>models.py</code>, which contains the SQLAlchemy instance and models.</p> <p>So, while I was removing boilerplate to get a minimal working Flask project to upload it to a git repository to link it here, I found the cause.</p> <p>Apparently, the reason is that my workmate, while attempting to insert data using queries instead of the model objects (no, I have no idea why on earth he wanted to do that, but he spent a whole day coding it), <strong>had defined another SQLAlchemy instance in the <code>routes.py</code></strong>.</p> <p>So, when I was trying to insert data from the Flask shell using:</p> <pre><code>from .models import * entry = Entry.query.get(1) entry.name = 'modified' db.session.commit() </code></pre> <p>I was using the correct <code>db</code> object, as defined in <code>models.py</code>, and it was working completely fine.</p> <p><em>However</em>, as in <code>routes.py</code> there was another <code>db</code> defined after the model import, <strong>this one was overwriting the reference</strong> to the correct SQLAlchemy instance, so I was <strong>commiting with a different session</strong>.</p>
0
2016-10-14T15:41:42Z
[ "python", "postgresql", "flask", "sqlalchemy", "flask-sqlalchemy" ]
creating a pandas dataframe from a list first I create a dictionary then convert that to a dataframe
40,020,566
<p>I have a list that I have converted to a dictionary and want to convert the dictionary to a pandas dataframe.</p> <p>My attempt is below however I am getting the following error:</p> <blockquote> <p>'numpy.int64' object has no attribute 'DataFrame'</p> </blockquote> <pre><code>**df = pd.DataFrame.from_dict(a, orient='index') </code></pre> <p><strong>Sample of Data:</strong></p> <pre><code>{'AAM': 2, 'ABC': 5, 'ABP': 3, 'ABU': 1, 'ACL': 3, 'ACX': 6, 'ADA': 7, 'ADE': 2, </code></pre> <p>Here are the functions I have used to attempt to create the dataframe. The last line is causing the issue.</p> <blockquote> <p>df = pd.DataFrame.from_dict(a, orient='index')</p> </blockquote> <pre><code>def list_to_dict(a_list): results = {} for i in a_list: i = str(i) if len(results.keys())==0: results[i] = 1 else: if i not in results.keys(): results[i] = 1 else: results[i] = results[i] + 1 return results flatten = df.mentions.tolist() combined = [item for sublist in flatten for item in sublist] a = list_to_dict(combined) df = pd.DataFrame.from_dict(a, orient='index') </code></pre>
0
2016-10-13T12:06:40Z
40,022,569
<p>If you already have the dict as in your sample you could do two list comprehensions:</p> <pre><code>d = { 'AAM': 2, 'ABC': 5, 'ABP': 3, 'ABU': 1, 'ACL': 3, 'ACX': 6, 'ADA': 7, 'ADE': 2 } pd.DataFrame([[item for item in d.keys()],[item for item in d.values()]]) </code></pre> <p>Result is a dataframe with you data</p> <pre><code> 0 1 0 ADA 7 1 ACX 6 2 ABU 1 3 AAM 2 4 ABC 5 5 ACL 3 6 ABP 3 7 ADE 2 </code></pre>
0
2016-10-13T13:36:19Z
[ "python", "pandas", "dataframe" ]
creating a pandas dataframe from a list first I create a dictionary then convert that to a dataframe
40,020,566
<p>I have a list that I have converted to a dictionary and want to convert the dictionary to a pandas dataframe.</p> <p>My attempt is below however I am getting the following error:</p> <blockquote> <p>'numpy.int64' object has no attribute 'DataFrame'</p> </blockquote> <pre><code>**df = pd.DataFrame.from_dict(a, orient='index') </code></pre> <p><strong>Sample of Data:</strong></p> <pre><code>{'AAM': 2, 'ABC': 5, 'ABP': 3, 'ABU': 1, 'ACL': 3, 'ACX': 6, 'ADA': 7, 'ADE': 2, </code></pre> <p>Here are the functions I have used to attempt to create the dataframe. The last line is causing the issue.</p> <blockquote> <p>df = pd.DataFrame.from_dict(a, orient='index')</p> </blockquote> <pre><code>def list_to_dict(a_list): results = {} for i in a_list: i = str(i) if len(results.keys())==0: results[i] = 1 else: if i not in results.keys(): results[i] = 1 else: results[i] = results[i] + 1 return results flatten = df.mentions.tolist() combined = [item for sublist in flatten for item in sublist] a = list_to_dict(combined) df = pd.DataFrame.from_dict(a, orient='index') </code></pre>
0
2016-10-13T12:06:40Z
40,023,781
<p>Do you just want the key and value as two columns or are you trying to do something else? If the former, this is all you need:</p> <pre><code>pd.DataFrame(a.items()) </code></pre>
1
2016-10-13T14:26:14Z
[ "python", "pandas", "dataframe" ]
Scrapy: NameError: global name 'MyItem' is not defined
40,020,654
<p>I'm trying to fill my Items with parsed data and I'm getting error: <strong>NameError: global name 'QuotesItem' is not defined</strong> when trying to run <strong>$ scrapy crawl quotes</strong></p> <p>Here's my spider's code: </p> <p>quotes.py:</p> <pre><code>import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" def start_requests(self): start_urls = [ 'http://www.successories.com/iquote/category/39/inspirational-quotes/4', 'http://www.successories.com/iquote/category/39/inspirational-quotes/6', 'http://www.successories.com/iquote/category/39/inspirational-quotes/7', 'http://www.successories.com/iquote/category/39/inspirational-quotes/8', 'http://www.successories.com/iquote/category/39/inspirational-quotes/9', ] def parse(self,response): items = [] for quote in response.css('div.quotebox'): item = QuotesItem() item['quoteAuthor'] = quote.css('div.quote a::text').extract_first() item['quoteText'] = quote.css('div.quote a::text').extract_first() items.append(item) yield items </code></pre> <p>Here's my items code items.py:</p> <pre><code>import scrapy class QuotesItem(scrapy.Item): quoteAuthor = scrapy.Field() quoteText = scrapy.Field() </code></pre>
0
2016-10-13T12:10:47Z
40,020,699
<p>You've defined <code>QuotesItem</code> in another file called <code>items.py</code>. Now you have to <a href="https://docs.python.org/3.5/tutorial/modules.html" rel="nofollow">import</a> either the entire module <code>items</code> or just the <code>QuotesItem</code>. Add the following to the top of your <code>quotes.py</code>:</p> <pre><code>from items import QuotesItem </code></pre>
1
2016-10-13T12:13:32Z
[ "python", "scrapy" ]
List of lists: replacing and adding up items of sublists
40,020,663
<p>I have a list of lists, let's say something like this:</p> <pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]] </code></pre> <p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p> <p>My aim is to get a list where trips with coincident start and end points get their third and fourth values added up. The start and end values should always be numbers from 1 to lets say 8. If they are letters instead, those should be replaced with the corresponding number (a=1, b=2, and so on).</p> <p>This is my code. It works but I'm sure it can be improved. The main issue for me is performance. I have quite a number of lists like this with many more sublists.</p> <pre><code>dicPoints = {'a':'1','b':'2','c':'3', 'd':'4', 'e':'5', 'f':'6', 'g':'7', 'h':'8'} def getTrips (trips): okTrips = [] for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] break else: if i == len(okTrips)-1: okTrips.append(trip) </code></pre> <p><strong>As <em>eguaio</em> mentioned the code above has a bug. It should be like this:</strong></p> <pre><code>def getTrips (trips): okTrips = [] print datetime.datetime.now() for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: flag = 0 for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] flag = 1 break if flag == 0: okTrips.append(trip) </code></pre> <hr> <p><strong>I got an improved version thanks to eguaio's answer that I want to share. This is my script based on his answer. My data and requirements are more complex now than what I was first told so I made a few changes.</strong></p> <p>CSV files look like this:</p> <pre><code>LineT;Line;Route;Day;Start_point;End_point;Adults;Children;First_visit SM55;5055;3;Weekend;15;87;21;4;0 SM02;5002;8;Weekend;AF3;89;5;0;1 ... </code></pre> <p>Script:</p> <pre><code>import os, csv, psycopg2 folder = "F:/route_project/routes" # Day type dicDay = {'Weekday':1,'Weekend':2,'Holiday':3} # Dictionary with the start and end points of each route # built from a Postgresql table (with coumns: line_route, start, end) conn = psycopg2.connect (database="test", user="test", password="test", host="###.###.#.##") cur = conn.cursor() cur.execute('select id_linroute, start_p, end_p from route_ends') recs = cur.fetchall() dicPoints = {rec[0]: rec[1:] for rec in recs} # When point labels are text, replace them with a number label in dicPoints # Text is not important: they are special text labels for start and end # of routes (for athletes), so we replace them with labels for start or # the end of each route def convert_point(line, route, point, i): if point.isdigit(): return point else: return dicPoints["%s_%s" % (line,route)][i] # Points with text labels mean athletes made the whole or part of this route, # we keep them as adults but also keep this number as an extra value # for further purposes def num_athletes(start_p, end_p, adults): if not start_p.isdigit() or not end_p.isdigit(): return adults else: return 0 # Data is taken for CSV files in subfolders for root, dirs, files in os.walk(folder): for file in files: if file.endswith(".csv"): file_path = (os.path.join(root, file)) with open(file_path, 'rb') as csvfile: rows = csv.reader(csvfile, delimiter=';', quotechar='"') # Skips the CSV header row rows.next() # linT is not used, yet it's found in every CSV file # There's an unused last column in every file, I take advantage out of it # to store the number of athletes in the generator gen =((lin, route, dicDay[tday], convert_point(lin,route,s_point,0), convert_point(lin,route,e_point,1), adults, children, num_athletes(s_point,e_point,adults)) for linT, lin, route, tday, s_point, e_point, adults, children, athletes in rows) dicCSV = {} for lin, route, tday, s_point, e_point, adults, children, athletes in gen: visitors = dicCSV.get(("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday), (0, 0, 0)) dicCSV[("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday)] = (visitors[0] + int(adults), visitors[1] + int(children), visitors[2] + int(athletes)) for k,v in dicCSV.iteritems(): print k, v </code></pre>
1
2016-10-13T12:11:14Z
40,020,977
<p>See if this helps </p> <pre><code>trips = [['1','2',6,2], ['a','h',4,2], ['1','2',6,1], ['1','8',18,3], ['a','h',2,1]] # To get the equivalent value def x(n): if '1' &lt;= n &lt;= '8': return int(n) return ord(n) - ord('a') # To group lists with similar start and end points from collections import defaultdict groups = defaultdict(list) for trip in trips: # Grouping based on start and end point. groups[(x(trip[0]), x(trip[1]))].append(trip) grouped_trips = groups.values() result = [] for group in grouped_trips: start = group[0][0] end = group[0][1] adults = group[0][2] children = group[0][3] for trip in group[1:]: adults += trip [2] children += trip [3] result += [[start, end, adults, children]] print result </code></pre>
0
2016-10-13T12:27:17Z
[ "python", "nested-lists" ]
List of lists: replacing and adding up items of sublists
40,020,663
<p>I have a list of lists, let's say something like this:</p> <pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]] </code></pre> <p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p> <p>My aim is to get a list where trips with coincident start and end points get their third and fourth values added up. The start and end values should always be numbers from 1 to lets say 8. If they are letters instead, those should be replaced with the corresponding number (a=1, b=2, and so on).</p> <p>This is my code. It works but I'm sure it can be improved. The main issue for me is performance. I have quite a number of lists like this with many more sublists.</p> <pre><code>dicPoints = {'a':'1','b':'2','c':'3', 'd':'4', 'e':'5', 'f':'6', 'g':'7', 'h':'8'} def getTrips (trips): okTrips = [] for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] break else: if i == len(okTrips)-1: okTrips.append(trip) </code></pre> <p><strong>As <em>eguaio</em> mentioned the code above has a bug. It should be like this:</strong></p> <pre><code>def getTrips (trips): okTrips = [] print datetime.datetime.now() for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: flag = 0 for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] flag = 1 break if flag == 0: okTrips.append(trip) </code></pre> <hr> <p><strong>I got an improved version thanks to eguaio's answer that I want to share. This is my script based on his answer. My data and requirements are more complex now than what I was first told so I made a few changes.</strong></p> <p>CSV files look like this:</p> <pre><code>LineT;Line;Route;Day;Start_point;End_point;Adults;Children;First_visit SM55;5055;3;Weekend;15;87;21;4;0 SM02;5002;8;Weekend;AF3;89;5;0;1 ... </code></pre> <p>Script:</p> <pre><code>import os, csv, psycopg2 folder = "F:/route_project/routes" # Day type dicDay = {'Weekday':1,'Weekend':2,'Holiday':3} # Dictionary with the start and end points of each route # built from a Postgresql table (with coumns: line_route, start, end) conn = psycopg2.connect (database="test", user="test", password="test", host="###.###.#.##") cur = conn.cursor() cur.execute('select id_linroute, start_p, end_p from route_ends') recs = cur.fetchall() dicPoints = {rec[0]: rec[1:] for rec in recs} # When point labels are text, replace them with a number label in dicPoints # Text is not important: they are special text labels for start and end # of routes (for athletes), so we replace them with labels for start or # the end of each route def convert_point(line, route, point, i): if point.isdigit(): return point else: return dicPoints["%s_%s" % (line,route)][i] # Points with text labels mean athletes made the whole or part of this route, # we keep them as adults but also keep this number as an extra value # for further purposes def num_athletes(start_p, end_p, adults): if not start_p.isdigit() or not end_p.isdigit(): return adults else: return 0 # Data is taken for CSV files in subfolders for root, dirs, files in os.walk(folder): for file in files: if file.endswith(".csv"): file_path = (os.path.join(root, file)) with open(file_path, 'rb') as csvfile: rows = csv.reader(csvfile, delimiter=';', quotechar='"') # Skips the CSV header row rows.next() # linT is not used, yet it's found in every CSV file # There's an unused last column in every file, I take advantage out of it # to store the number of athletes in the generator gen =((lin, route, dicDay[tday], convert_point(lin,route,s_point,0), convert_point(lin,route,e_point,1), adults, children, num_athletes(s_point,e_point,adults)) for linT, lin, route, tday, s_point, e_point, adults, children, athletes in rows) dicCSV = {} for lin, route, tday, s_point, e_point, adults, children, athletes in gen: visitors = dicCSV.get(("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday), (0, 0, 0)) dicCSV[("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday)] = (visitors[0] + int(adults), visitors[1] + int(children), visitors[2] + int(athletes)) for k,v in dicCSV.iteritems(): print k, v </code></pre>
1
2016-10-13T12:11:14Z
40,021,413
<p>Let say start and end points are between 0 and n values. </p> <p>Then, the result 'OkTrip' has maximum n^2 elements. Then, your second loop in function has a complexity O(n^2). It is possible to reduce the complexity to O(n) if you have not problem with space complexity.</p> <p>Firslty, create dict which contains n lists such that k'(th) sublist contains trips starting with 'k'. </p> <p>When you search whether there are different trips with same start and end points, you need search only corresponding sublist instead of searching all elements. </p> <p>The idea comes from sparse matrix storage techniques. I could not check validation of following code. </p> <p>The code is following,</p> <pre><code>dicPoints = {'a':'1','b':'2','c':'3', 'd':'4', 'e':'5', 'f':'6', 'g':'7', 'h':'8'} Temp = {'1':[],'2':[],'3':[],'4':[],'5':[],'6':[],'7':[],'8':[]}; def getTrips (trips): okTrips = [] for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(Temp[trip[0]]) == 0: Temp[trip[0]].append(trip) else: for i, stop in enumerate(Temp[trip[0]]): if stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] break else: if i == len(Temp[trip[0]])-1: Temp[trip[0]].append(trip) print Temp for key in Temp: okTrips = okTrips + Temp[key]; </code></pre>
0
2016-10-13T12:45:06Z
[ "python", "nested-lists" ]
List of lists: replacing and adding up items of sublists
40,020,663
<p>I have a list of lists, let's say something like this:</p> <pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]] </code></pre> <p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p> <p>My aim is to get a list where trips with coincident start and end points get their third and fourth values added up. The start and end values should always be numbers from 1 to lets say 8. If they are letters instead, those should be replaced with the corresponding number (a=1, b=2, and so on).</p> <p>This is my code. It works but I'm sure it can be improved. The main issue for me is performance. I have quite a number of lists like this with many more sublists.</p> <pre><code>dicPoints = {'a':'1','b':'2','c':'3', 'd':'4', 'e':'5', 'f':'6', 'g':'7', 'h':'8'} def getTrips (trips): okTrips = [] for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] break else: if i == len(okTrips)-1: okTrips.append(trip) </code></pre> <p><strong>As <em>eguaio</em> mentioned the code above has a bug. It should be like this:</strong></p> <pre><code>def getTrips (trips): okTrips = [] print datetime.datetime.now() for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: flag = 0 for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] flag = 1 break if flag == 0: okTrips.append(trip) </code></pre> <hr> <p><strong>I got an improved version thanks to eguaio's answer that I want to share. This is my script based on his answer. My data and requirements are more complex now than what I was first told so I made a few changes.</strong></p> <p>CSV files look like this:</p> <pre><code>LineT;Line;Route;Day;Start_point;End_point;Adults;Children;First_visit SM55;5055;3;Weekend;15;87;21;4;0 SM02;5002;8;Weekend;AF3;89;5;0;1 ... </code></pre> <p>Script:</p> <pre><code>import os, csv, psycopg2 folder = "F:/route_project/routes" # Day type dicDay = {'Weekday':1,'Weekend':2,'Holiday':3} # Dictionary with the start and end points of each route # built from a Postgresql table (with coumns: line_route, start, end) conn = psycopg2.connect (database="test", user="test", password="test", host="###.###.#.##") cur = conn.cursor() cur.execute('select id_linroute, start_p, end_p from route_ends') recs = cur.fetchall() dicPoints = {rec[0]: rec[1:] for rec in recs} # When point labels are text, replace them with a number label in dicPoints # Text is not important: they are special text labels for start and end # of routes (for athletes), so we replace them with labels for start or # the end of each route def convert_point(line, route, point, i): if point.isdigit(): return point else: return dicPoints["%s_%s" % (line,route)][i] # Points with text labels mean athletes made the whole or part of this route, # we keep them as adults but also keep this number as an extra value # for further purposes def num_athletes(start_p, end_p, adults): if not start_p.isdigit() or not end_p.isdigit(): return adults else: return 0 # Data is taken for CSV files in subfolders for root, dirs, files in os.walk(folder): for file in files: if file.endswith(".csv"): file_path = (os.path.join(root, file)) with open(file_path, 'rb') as csvfile: rows = csv.reader(csvfile, delimiter=';', quotechar='"') # Skips the CSV header row rows.next() # linT is not used, yet it's found in every CSV file # There's an unused last column in every file, I take advantage out of it # to store the number of athletes in the generator gen =((lin, route, dicDay[tday], convert_point(lin,route,s_point,0), convert_point(lin,route,e_point,1), adults, children, num_athletes(s_point,e_point,adults)) for linT, lin, route, tday, s_point, e_point, adults, children, athletes in rows) dicCSV = {} for lin, route, tday, s_point, e_point, adults, children, athletes in gen: visitors = dicCSV.get(("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday), (0, 0, 0)) dicCSV[("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday)] = (visitors[0] + int(adults), visitors[1] + int(children), visitors[2] + int(athletes)) for k,v in dicCSV.iteritems(): print k, v </code></pre>
1
2016-10-13T12:11:14Z
40,021,745
<p>To handle this more efficiently it's best to sort the input list by the start and end points, so that rows which have matching start and end points are grouped together. Then we can easily use the <code>groupby</code> function to process those groups efficiently.</p> <pre><code>from operator import itemgetter from itertools import groupby tripInfo_csv = [ ['1', '2', 6, 2], ['a', 'h', 4, 2], ['1', '4', 6, 1], ['1', '8', 18, 3], ['a', '8', 2, 1], ] # Used to convert alphabetic point labels to numeric form dicPoints = {v:str(i) for i, v in enumerate('abcdefgh', 1)} def fix_points(seq): return [dicPoints.get(p, p) for p in seq] # Ensure that all point labels are numeric for row in tripInfo_csv: row[:2] = fix_points(row[:2]) # Sort on point labels keyfunc = itemgetter(0, 1) tripInfo_csv.sort(key=keyfunc) # Group on point labels and sum corresponding adult &amp; child numbers newlist = [] for k, g in groupby(tripInfo_csv, key=keyfunc): g = list(g) row = list(k) + [sum(row[2] for row in g), sum(row[3] for row in g)] newlist.append(row) # Print the condensed list for row in newlist: print(row) </code></pre> <p><strong>output</strong></p> <pre><code>['1', '2', 6, 2] ['1', '4', 6, 1] ['1', '8', 24, 6] </code></pre>
1
2016-10-13T12:59:36Z
[ "python", "nested-lists" ]
List of lists: replacing and adding up items of sublists
40,020,663
<p>I have a list of lists, let's say something like this:</p> <pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]] </code></pre> <p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p> <p>My aim is to get a list where trips with coincident start and end points get their third and fourth values added up. The start and end values should always be numbers from 1 to lets say 8. If they are letters instead, those should be replaced with the corresponding number (a=1, b=2, and so on).</p> <p>This is my code. It works but I'm sure it can be improved. The main issue for me is performance. I have quite a number of lists like this with many more sublists.</p> <pre><code>dicPoints = {'a':'1','b':'2','c':'3', 'd':'4', 'e':'5', 'f':'6', 'g':'7', 'h':'8'} def getTrips (trips): okTrips = [] for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] break else: if i == len(okTrips)-1: okTrips.append(trip) </code></pre> <p><strong>As <em>eguaio</em> mentioned the code above has a bug. It should be like this:</strong></p> <pre><code>def getTrips (trips): okTrips = [] print datetime.datetime.now() for trip in trips: if not trip[0].isdigit(): trip[0] = dicPoints[trip[0]] if not trip[1].isdigit(): trip[1] = dicPoints[trip[1]] if len(okTrips) == 0: okTrips.append(trip) else: flag = 0 for i, stop in enumerate(okTrips): if stop[0] == trip[0] and stop[1] == trip[1]: stop[2] += trip[2] stop[3] += trip[3] flag = 1 break if flag == 0: okTrips.append(trip) </code></pre> <hr> <p><strong>I got an improved version thanks to eguaio's answer that I want to share. This is my script based on his answer. My data and requirements are more complex now than what I was first told so I made a few changes.</strong></p> <p>CSV files look like this:</p> <pre><code>LineT;Line;Route;Day;Start_point;End_point;Adults;Children;First_visit SM55;5055;3;Weekend;15;87;21;4;0 SM02;5002;8;Weekend;AF3;89;5;0;1 ... </code></pre> <p>Script:</p> <pre><code>import os, csv, psycopg2 folder = "F:/route_project/routes" # Day type dicDay = {'Weekday':1,'Weekend':2,'Holiday':3} # Dictionary with the start and end points of each route # built from a Postgresql table (with coumns: line_route, start, end) conn = psycopg2.connect (database="test", user="test", password="test", host="###.###.#.##") cur = conn.cursor() cur.execute('select id_linroute, start_p, end_p from route_ends') recs = cur.fetchall() dicPoints = {rec[0]: rec[1:] for rec in recs} # When point labels are text, replace them with a number label in dicPoints # Text is not important: they are special text labels for start and end # of routes (for athletes), so we replace them with labels for start or # the end of each route def convert_point(line, route, point, i): if point.isdigit(): return point else: return dicPoints["%s_%s" % (line,route)][i] # Points with text labels mean athletes made the whole or part of this route, # we keep them as adults but also keep this number as an extra value # for further purposes def num_athletes(start_p, end_p, adults): if not start_p.isdigit() or not end_p.isdigit(): return adults else: return 0 # Data is taken for CSV files in subfolders for root, dirs, files in os.walk(folder): for file in files: if file.endswith(".csv"): file_path = (os.path.join(root, file)) with open(file_path, 'rb') as csvfile: rows = csv.reader(csvfile, delimiter=';', quotechar='"') # Skips the CSV header row rows.next() # linT is not used, yet it's found in every CSV file # There's an unused last column in every file, I take advantage out of it # to store the number of athletes in the generator gen =((lin, route, dicDay[tday], convert_point(lin,route,s_point,0), convert_point(lin,route,e_point,1), adults, children, num_athletes(s_point,e_point,adults)) for linT, lin, route, tday, s_point, e_point, adults, children, athletes in rows) dicCSV = {} for lin, route, tday, s_point, e_point, adults, children, athletes in gen: visitors = dicCSV.get(("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday), (0, 0, 0)) dicCSV[("%s_%s_%s" % (lin,route,s_point), "%s_%s_%s" % (lin,route,e_point), tday)] = (visitors[0] + int(adults), visitors[1] + int(children), visitors[2] + int(athletes)) for k,v in dicCSV.iteritems(): print k, v </code></pre>
1
2016-10-13T12:11:14Z
40,021,753
<p>The following gives much better times than yours for large lists with much merging: 2 seconds vs. 1 minute for <code>tripInfo_csv*500000</code>. We get the almost linear complexity using a dict to get the keys, that have constant lookup time. IMHO it is also more elegant. Notice that <code>tg</code> is a generator, so no significant time or memory is used when created.</p> <pre><code>def newGetTrips(trips): def convert(l): return l if l.isdigit() else dicPoints[l] tg = ((convert(a), convert(b), c, d) for a, b, c, d in trips) okt = {} for a, b, c, d in tg: # a trick to get (0,0) as default if (a,b) is not a key of the dictionary yet t = okt.get((a,b), (0,0)) okt[(a,b)] = (t[0] + c, t[1] + d) return [[a,b,c,d] for (a,b), (c,d) in okt.iteritems()] </code></pre> <p>Besides, as a side effect, you are altering the trips list and this function leaves it untouched. Also, you have a bug. You are summing twice the first item considered for each (start, end) pair (but not for the first case). I could not find the reason, but when running the example, with your <code>getTrips</code> I get:</p> <pre><code>[['1', '2', 6, 2], ['1', '8', 28, 8], ['1', '4', 12, 2]] </code></pre> <p>and with <code>newGetTrips</code> I get:</p> <pre><code>[['1', '8', 24, 6], ['1', '2', 6, 2], ['1', '4', 6, 1]] </code></pre>
1
2016-10-13T12:59:51Z
[ "python", "nested-lists" ]
Web2py Field value depends on another field - (validate while defining the model)
40,020,739
<p>Please consider the following table:</p> <pre><code>db.define_table('bio_data', Field('name', 'string'), Field('total_mark', 'integer', requires=IS_EMPTY_OR(IS_INT_IN_RANGE(0, 1e100))), Field('marks_obtained', 'integer') ) </code></pre> <p>Now the field 'marks_obtained' cannot have a value greater than the 'total_marks'.</p> <p>I have tried the following</p> <pre><code>db.bio_data.marks_obtained.requires = IS_EMPTY_OR( IS_INT_IN_RANGE(0, db.bio_data.total_mark)) </code></pre> <p>But this does not work. I get the following error:</p> <pre><code>TypeError: int() argument must be a string or a number, not 'Field' </code></pre> <p>Any help is much appreciated.</p>
0
2016-10-13T12:15:52Z
40,037,101
<p>You can easily do this using <code>onvalidation</code> callback function. Read this <a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#onvalidation" rel="nofollow">Form and validators - onvalidation</a></p> <p>Second solution is you need to combine '<em>Validators with dependencies</em>' and <code>IS_EXPR</code> validator. Read:</p> <ol> <li><p><a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#Validators-with-dependencies" rel="nofollow">Validators with dependencies</a></p></li> <li><p><a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#IS_EXPR" rel="nofollow">IS_EXPR</a></p></li> </ol> <p>Add validator in <strong>controller</strong> something like following, I have not tested this but you will get idea from this.</p> <pre><code>is_total_less = int(request.vars.marks_obtained) &lt; int(request.vars.total_mark) db.bio_data.marks_obtained.requires = IS_EMPTY_OR( IS_EXPR('%s' % is_total_less, error_message='Marks Obtained should be smaller than Totak Marks')) </code></pre> <p>Make sure that <code>request.vars</code> is available.</p>
1
2016-10-14T07:12:53Z
[ "python", "web2py", "data-access-layer" ]
Add a library in Spark in Bluemix & connect MongoDB , Spark together
40,020,767
<p><b>1) </b>I have Spark on Bluemix platform, how do I add a library there ?</p> <p>I can see the preloaded libraries but cant add a library that I want.</p> <p>Any command line argument that will install a library?</p> <blockquote> <p>pip install --package is not working there</p> </blockquote> <p><b>2) </b> I have Spark and Mongo DB running, but I am not able to connect both of them.</p> <blockquote> <p>con ='mongodb://admin:ITCW....ssl=true'<br> ssl1 ="LS0tLS ....." client = MongoClient(con,ssl=True)<br> db = client.mongo11 <br> collection = db.mongo11 <br> ff=db.sammy.find() <br></p> </blockquote> <p><b> Error I am getting is : <br> SSL handshake failed: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) </b></p>
0
2016-10-13T12:17:34Z
40,021,035
<p>In a Python notebook:</p> <p><code>!pip install &lt;package&gt;</code></p> <p>and then</p> <p><code>import &lt;package&gt;</code></p>
0
2016-10-13T12:30:11Z
[ "python", "apache-spark", "ibm-bluemix", "bluemix-plugin" ]
How to make a call to the surveygizmo API to a specific page using python surveygizmo package?
40,020,846
<p>I downloaded the surveygizmo package (1.2.1) and easily did a call to surveygizmo API like this:</p> <pre><code>import surveygizmo as sg client = sg.SurveyGizmo( api_version='v4', # example api_token = "E4F796932C2743FEBF150B421BE15EB9", api_token_secret = "A9fGMkJ5pJF1k" ) surveys = client.api.survey.list() print(surveys) </code></pre> <p>which results in something like this:</p> <pre><code>{'total_count': '8902', 'total_pages': 179, 'page': 1, # This is what I want to change 'results_per_page': 50, 'data': [ {'id': '7895426', 'team': '123456', '_subtype': 'Standard Survey', ... }, {'id': '7895427', 'team': '123456', '_subtype': 'Standard Survey', ... }, ...]} </code></pre> <p>How is it possible to access the following pages? I only see the first 50 results, which are all on the first page.</p> <p>Thanks a lot!</p>
0
2016-10-13T12:20:33Z
40,025,039
<p>Via trial and error I found this solution:</p> <pre><code>surveys = client.api.survey.list(resultsperpage=500, page=5) </code></pre>
1
2016-10-13T15:22:52Z
[ "python", "survey" ]
How to make a call to the surveygizmo API to a specific page using python surveygizmo package?
40,020,846
<p>I downloaded the surveygizmo package (1.2.1) and easily did a call to surveygizmo API like this:</p> <pre><code>import surveygizmo as sg client = sg.SurveyGizmo( api_version='v4', # example api_token = "E4F796932C2743FEBF150B421BE15EB9", api_token_secret = "A9fGMkJ5pJF1k" ) surveys = client.api.survey.list() print(surveys) </code></pre> <p>which results in something like this:</p> <pre><code>{'total_count': '8902', 'total_pages': 179, 'page': 1, # This is what I want to change 'results_per_page': 50, 'data': [ {'id': '7895426', 'team': '123456', '_subtype': 'Standard Survey', ... }, {'id': '7895427', 'team': '123456', '_subtype': 'Standard Survey', ... }, ...]} </code></pre> <p>How is it possible to access the following pages? I only see the first 50 results, which are all on the first page.</p> <p>Thanks a lot!</p>
0
2016-10-13T12:20:33Z
40,025,303
<p>I didn't take the time to set up access to SurveyGizmo. However, by importing the Python façade and poking around it and the documentation I found this possibility.</p> <pre><code>client.config.requests_kwargs={'page':2} </code></pre> <p>I'm curious to know whether it works.</p>
0
2016-10-13T15:35:27Z
[ "python", "survey" ]
IndexError in this code
40,020,897
<p>When I use this as the contents of the input file:</p> <pre><code>1,3,5,7,9,11 </code></pre> <p>I receive this error: </p> <pre><code>IndexError: li </code></pre> <hr> <pre><code>with open('fig.fig') as o: n = 6 for i in range(1, 2*n, 2): print(o.readlines()[i].replace(' ', '')) </code></pre>
-1
2016-10-13T12:23:15Z
40,021,496
<p>there is nothing wrong with the following code:</p> <pre><code>n = 6 for i in range(1, 2*n, 2): print &lt;something&gt;[i].replace(' ', '') </code></pre> <p>so the problem is in the open or reading of your file (really open? line length?). Hope that helps.</p>
0
2016-10-13T12:49:19Z
[ "python", "indexing", "file-access" ]
IndexError in this code
40,020,897
<p>When I use this as the contents of the input file:</p> <pre><code>1,3,5,7,9,11 </code></pre> <p>I receive this error: </p> <pre><code>IndexError: li </code></pre> <hr> <pre><code>with open('fig.fig') as o: n = 6 for i in range(1, 2*n, 2): print(o.readlines()[i].replace(' ', '')) </code></pre>
-1
2016-10-13T12:23:15Z
40,029,962
<p>When opening and processing a file, you should always make sure that you don't attempt to read more lines than are actually in the file. Also, you are making repeated calls to <code>readlines</code> which is quite inefficient. Try something like:</p> <pre><code>with open('fig.fig') as o: lines = o.readlines() n=6 for i in range(1, min(len(o), n*2), 2): print(lines[i].replace(' ', '')) </code></pre> <p>This will read odd numbered lines, up to n*2, or the maximum number of lines in the file, whichever is less. You should also check that the file exists (one way is to use <code>os.path.isfile('fig.fig')</code>, or wrap everything in a <a href="https://docs.python.org/3.6/reference/compound_stmts.html#try" rel="nofollow" title="try">try</a> block.</p>
0
2016-10-13T20:03:49Z
[ "python", "indexing", "file-access" ]
Not able to open Firefox using Selenium Python
40,020,913
<p>I am getting an error when trying to open <code>Firefox</code> with <code>Selenium</code>. I tried this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.firefox.webdriver import FirefoxProfile profile = FirefoxProfile('/home/usr/.mozilla/firefox') driver = webdriver.Firefox(profile) </code></pre> <p>The error was:</p> <pre><code>selenium.common.exceptions.WebdriverException: Message: Can't load the profile. Profile Dir: '...../webdriver-py-profilecopy' If you specified a log_file in the FirefoxBinary constructor, check it for details. </code></pre>
-2
2016-10-13T12:24:05Z
40,021,369
<p>Try:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get('http://google.com') </code></pre>
0
2016-10-13T12:43:32Z
[ "python", "selenium", "selenium-webdriver" ]
Not able to open Firefox using Selenium Python
40,020,913
<p>I am getting an error when trying to open <code>Firefox</code> with <code>Selenium</code>. I tried this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.firefox.webdriver import FirefoxProfile profile = FirefoxProfile('/home/usr/.mozilla/firefox') driver = webdriver.Firefox(profile) </code></pre> <p>The error was:</p> <pre><code>selenium.common.exceptions.WebdriverException: Message: Can't load the profile. Profile Dir: '...../webdriver-py-profilecopy' If you specified a log_file in the FirefoxBinary constructor, check it for details. </code></pre>
-2
2016-10-13T12:24:05Z
40,022,595
<p>I think you are using selenium 2.53.6</p> <p>The issue is compatibility of firefox with selenium, since firefox>= 48 need Gecko Driver(<a href="https://github.com/mozilla/geckodriver" rel="nofollow">https://github.com/mozilla/geckodriver</a>) to run testcases on firefox. or you can downgrade the firefox to 46..from this link <a href="https://ftp.mozilla.org/pub/firefox/releases/46.0.1/" rel="nofollow">https://ftp.mozilla.org/pub/firefox/releases/46.0.1/</a></p>
0
2016-10-13T13:37:18Z
[ "python", "selenium", "selenium-webdriver" ]
counting occurrence of elements in each sequence of the list in python
40,020,920
<p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p> <p>small example:</p> <pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE'] </code></pre> <p>do you guys know how to do that?</p>
0
2016-10-13T12:24:38Z
40,020,983
<p>You can simply use a <em>list comprehension</em>, get the count of <code>D</code> in each sequence and divide by the length of the sequence:</p> <pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE'] result = [x.count('D')/len(x) for x in l] print(result) # [0.07692307692307693, 0.125, 0.125, 0.21428571428571427, 0.17647058823529413] </code></pre> <p>To handle zero length sequences and avoid <code>ZeroDivisionError</code>, you may use a <em>ternary operator</em>:</p> <pre><code>result = [(x.count('D')/len(x) if x else 0) for x in l] </code></pre>
1
2016-10-13T12:27:39Z
[ "python" ]
counting occurrence of elements in each sequence of the list in python
40,020,920
<p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p> <p>small example:</p> <pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE'] </code></pre> <p>do you guys know how to do that?</p>
0
2016-10-13T12:24:38Z
40,020,995
<p>You're looking for something like:</p> <pre><code>def fn(x): return x.count('D') / len(x) results = ap(fn, l) </code></pre>
0
2016-10-13T12:28:03Z
[ "python" ]
counting occurrence of elements in each sequence of the list in python
40,020,920
<p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p> <p>small example:</p> <pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE'] </code></pre> <p>do you guys know how to do that?</p>
0
2016-10-13T12:24:38Z
40,021,111
<p>You can use list comprehension in order to get the expected result.</p> <p>I have iterated over each item in the list, for each one of the items in the list I've counted the number of the occurrences of the specified sub string (in this case 'D').</p> <p>Last, I've divided the number of the occurrences with the length of the item.</p> <pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE'] output = [float(item.count("D")) / float(len(item)) for item in l] </code></pre>
1
2016-10-13T12:32:56Z
[ "python" ]
Python Selenium - iterate through search results
40,020,982
<p>In the search results, I need to verify that all of them must contain the search key. This is the HTML source code:</p> <pre><code>&lt;div id="content"&gt; &lt;h1&gt;Search Results&lt;/h1&gt; &lt;a id="main-content" tabindex="-1"&gt;&lt;/a&gt; &lt;ul class="results"&gt; &lt;li&gt;&lt;img alt="Icon for Metropolitan trains" title="Metropolitan trains" src="themes/transport-site/images/jp/iconTrain.png" class="resultIcon"/&gt; &lt;strong&gt;Stop&lt;/strong&gt; &lt;a href="/next5/diva/10001218/1"&gt;Sunshine Railway Station (Sunshine)&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;img alt="Icon for Metropolitan trains" title="Metropolitan trains" src="themes/transport-site/images/jp/iconTrain.png" class="resultIcon"/&gt; &lt;strong&gt;Stop&lt;/strong&gt; &lt;a href="/next5/diva/10001003/1"&gt;Albion Railway Station (Sunshine North)&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I have written this code to enter search key and get the results but it fails to loop through the search result:</p> <pre><code>from selenium import webdriver driver = webdriver.Chrome('C:/Users/lovea/OneDrive/Documents/Semester 2 2016/ISYS1087/w3-4/chromedriver') driver.get('http://www.ptv.vic.gov.au') next5Element = driver.find_element_by_link_text('Next 5 departures') next5Element.click() searchBox = driver.find_element_by_id('Form_ModeSearchForm_Search') searchBox.click() searchBox.clear() searchBox.send_keys('Sunshine') submitBtn = driver.find_element_by_id('Form_ModeSearchForm_action_doModeSearch') submitBtn.click() assert "Sorry, there were no results for your search." not in driver.page_source results = driver.find_elements_by_xpath("//ul[@class='results']/li/a") for result in results: assert "Sunshine" in result //Error: argument of type 'WebElement' is not iterable </code></pre> <p>Anyone please tell me what is the proper way to to that? Thank you!</p>
0
2016-10-13T12:27:37Z
40,021,079
<p>You should check if <code>innerHTML</code> value of particular element contains key string, but not element itself, so try</p> <pre><code>for result in results: assert "Sunshine" in result.text </code></pre>
1
2016-10-13T12:31:39Z
[ "python", "selenium", "selenium-webdriver" ]
Python Selenium - iterate through search results
40,020,982
<p>In the search results, I need to verify that all of them must contain the search key. This is the HTML source code:</p> <pre><code>&lt;div id="content"&gt; &lt;h1&gt;Search Results&lt;/h1&gt; &lt;a id="main-content" tabindex="-1"&gt;&lt;/a&gt; &lt;ul class="results"&gt; &lt;li&gt;&lt;img alt="Icon for Metropolitan trains" title="Metropolitan trains" src="themes/transport-site/images/jp/iconTrain.png" class="resultIcon"/&gt; &lt;strong&gt;Stop&lt;/strong&gt; &lt;a href="/next5/diva/10001218/1"&gt;Sunshine Railway Station (Sunshine)&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;img alt="Icon for Metropolitan trains" title="Metropolitan trains" src="themes/transport-site/images/jp/iconTrain.png" class="resultIcon"/&gt; &lt;strong&gt;Stop&lt;/strong&gt; &lt;a href="/next5/diva/10001003/1"&gt;Albion Railway Station (Sunshine North)&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I have written this code to enter search key and get the results but it fails to loop through the search result:</p> <pre><code>from selenium import webdriver driver = webdriver.Chrome('C:/Users/lovea/OneDrive/Documents/Semester 2 2016/ISYS1087/w3-4/chromedriver') driver.get('http://www.ptv.vic.gov.au') next5Element = driver.find_element_by_link_text('Next 5 departures') next5Element.click() searchBox = driver.find_element_by_id('Form_ModeSearchForm_Search') searchBox.click() searchBox.clear() searchBox.send_keys('Sunshine') submitBtn = driver.find_element_by_id('Form_ModeSearchForm_action_doModeSearch') submitBtn.click() assert "Sorry, there were no results for your search." not in driver.page_source results = driver.find_elements_by_xpath("//ul[@class='results']/li/a") for result in results: assert "Sunshine" in result //Error: argument of type 'WebElement' is not iterable </code></pre> <p>Anyone please tell me what is the proper way to to that? Thank you!</p>
0
2016-10-13T12:27:37Z
40,021,083
<p>I got a mistake in <code>assert</code> statement.</p> <p>Because <code>result</code> is a WebElement so there is no text to look up in it.</p> <p>I just change it like: <code>assert "Sunshine" in result.text</code></p>
0
2016-10-13T12:31:54Z
[ "python", "selenium", "selenium-webdriver" ]
Django ORM, accessing the attributes of relationships
40,020,993
<p>I have on my projects two apps: account_app and image_app which have the models below.</p> <p>I am wondering if it is possible to directly access the number of likes of one profile, which has a OneToOne relation with User(django bultin) that in turn has a ManyToMany relation with Images user_like.</p> <p><strong><em>account_app/models.py</em></strong></p> <pre><code>class Profile(models.Model): # quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma # essa relacao nos permite linkar o perfil com o usuario user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) </code></pre> <p><strong><em>image_app/models.py</em></strong></p> <pre><code>class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked',blank=True) </code></pre>
0
2016-10-13T12:28:01Z
40,021,567
<p>Given a <em>Profile</em> instance <code>profile</code>, you may get the number of <code>users_like</code> with:</p> <pre><code>number_of_likes = profile.user.images_liked.count() </code></pre>
0
2016-10-13T12:52:22Z
[ "python", "django", "django-models" ]
Django ORM, accessing the attributes of relationships
40,020,993
<p>I have on my projects two apps: account_app and image_app which have the models below.</p> <p>I am wondering if it is possible to directly access the number of likes of one profile, which has a OneToOne relation with User(django bultin) that in turn has a ManyToMany relation with Images user_like.</p> <p><strong><em>account_app/models.py</em></strong></p> <pre><code>class Profile(models.Model): # quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma # essa relacao nos permite linkar o perfil com o usuario user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) </code></pre> <p><strong><em>image_app/models.py</em></strong></p> <pre><code>class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked',blank=True) </code></pre>
0
2016-10-13T12:28:01Z
40,021,754
<p>You can also introduce a property <code>likes</code> in Profile Model. </p> <pre><code>class Profile(models.Model): # quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma # essa relacao nos permite linkar o perfil com o usuario user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) @property def likes(self): self.user.images_liked.count() </code></pre>
0
2016-10-13T12:59:51Z
[ "python", "django", "django-models" ]
How can I queue a task to Celery from C#?
40,021,066
<p>As I understand message brokers like RabbitMQ facilitates different applications written in different language/platform to communicate with each other. So since celery can use RabbitMQ as message broker, I believe we can queue task from any application to Celery, even though the producer isn't written in Python.</p> <p>Now I am trying to figure out how I can queue a task to Celery from an application written in C# via RabbitMQ. But I could not find any such example yet.</p> <p>The only information close to this I found is <a href="http://stackoverflow.com/questions/14724910/can-i-use-java-send-task-to-celery-through-rabbitmq">this SO question</a></p> <p>Where the accepted answer suggests to use the Celery message format protocol to queue messages to RabbitMQ from Java. However, the link given in the answer does not have any example, only the message format.</p> <p>Also, the message format says task id (UUID) is required to communicate in this protocol. How is my C# application supposed to know the task id of the celery task? As I understand it can only know about the task name, but not the task id.</p>
1
2016-10-13T12:31:15Z
40,132,075
<p>According to this <a href="http://www.rabbitmq.com/dotnet-api-guide.html" rel="nofollow">article</a>, celery .Net client uses default TaskScheduler that comes with .Net Framework. This knows how to generate ID for your task. This article also points to some example <a href="https://msdn.microsoft.com/library/system.threading.tasks.taskscheduler.aspx" rel="nofollow">here</a>.</p>
0
2016-10-19T12:58:15Z
[ "c#", "python", "rabbitmq", "celery", "task-queue" ]
geopandas: how do I merge information only if point is inside a polygon?
40,021,140
<p>I have a <code>geopandas</code> dataframe <code>A</code> with the geometry field set to a single <code>Point</code> (x,y). Then I have a second dataframe <code>B</code> with the geometry field set to some polygon and some other information. For example:</p> <pre><code>A geometry (1,2) (3,4) ... </code></pre> <p>and </p> <pre><code>B info polygon ab &lt;some polygon&gt; bc &lt;some other polygon&gt; ... ... </code></pre> <p>How do I add a new column to <code>A</code> with <code>B</code>'s <code>info</code> field only if the point in <code>A</code> is inside the polygon in <code>B</code>?</p> <p>I would like to end up with something like</p> <pre><code>A geometry info (1,2) ab (3,4) ab (7,9) bc ... ... </code></pre>
0
2016-10-13T12:34:21Z
40,026,513
<p>Just in case someone else needs it, and assuming your geometry is well-formed, then you can do:</p> <p><code>new_df = gpd.sjoin(A,B,how="inner", op='intersects')</code></p> <p>this was enough.</p>
1
2016-10-13T16:35:09Z
[ "python", "pandas", "shapefile", "geopandas" ]
How to modify the XML file using Python?
40,021,380
<p>Actually I have got the XML string and parse the string to get the attributes from it. Now I want my XML file to change, viewing the attributes. Like I want to change the color of the stroke. Is there any way? How I will change and then again save the file.</p> <pre><code>import requests from xml.dom import minidom response = requests.get('http://localhost:8080/geoserver/rest/styles/pakistan.sld', auth=('admin', 'geoserver')) fo=open("/home/adeel/Desktop/untitled1/yes.xml", "wb") fo.write(response.text) fo.close() xmldoc = minidom.parse('yes.xml') itemlist = xmldoc.getElementsByTagName('CssParameter') print "Len : ", len(itemlist) #print "Attribute Name : ", \ itemlist[0].attributes['name'].value print "Text : ", itemlist[0].firstChild.nodeValue for s in itemlist : print "Attribute Name : ", s.attributes['name'].value print "Text : ", s.firstChild.nodeValue </code></pre>
0
2016-10-13T12:43:50Z
40,044,391
<p>You should probably read through the <a href="http://docs.geoserver.org/latest/en/user/styling/sld/cookbook/index.html" rel="nofollow">SLD Cook book</a> to get hints on how to change things like the colour of the lines in your SLD. Once you've changed it you need to make a <a href="http://docs.geoserver.org/latest/en/user/rest/api/styles.html" rel="nofollow"><code>PUT</code> request</a> to place the file back on the server.</p>
0
2016-10-14T13:28:24Z
[ "python", "xml", "django", "geoserver" ]
Python List Segregation
40,021,608
<p>I have a list of roughly 30,000 items that I am currently printing into a table with their associated relationships. I want to break apart this list into alphabetically segregated pages. </p> <p>The data comes from a database, and the list is formed with the following code:</p> <p><code>ListView.as_view(queryset=TblCompanies.objects.all().order_by("company_name"), template_name="customers/list.html"))</code></p> <p>Current list code is quite simple:</p> <pre><code>{% for TblCompanies in object_list %} &lt;tr&gt; &lt;td width="35"&gt;{{ TblCompanies.company_id }}&lt;/td&gt; &lt;td width="10"&gt; &lt;/td&gt; &lt;td&gt;{{ TblCompanies.company_name }}&lt;/td&gt; &lt;td&gt;{{ TblCompanies.phone_number }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>Could someone advise me on how to go about doing this and break down the code for me?</p> <pre><code>Name____#___#___#__ _____________________ acari | 1 | 2 | 3 | |__A__|__B__|__C__|__ ... angle | 1 | 2 | 3 | | |______________ arhat | 1 | 2 | 3 | |Name_|_#_|_#_|_#_ akkra | 1 | 2 | 3 | | amiel | 1 | 2 | 3 | TO |acari| 1 | 2 | 3 | barce | 1 | 2 | 3 | |angle| 1 | 2 | 3 | bogie | 1 | 2 | 3 | |arhat| 1 | 2 | 3 | betty | 1 | 2 | 3 | |akkra| 1 | 2 | 3 | brill | 1 | 2 | 3 | |amiel| 1 | 2 | 3 | blyth | 1 | 2 | 3 | | </code></pre>
-4
2016-10-13T12:54:11Z
40,022,881
<p>If the list is a text file, you can use pandas</p> <pre><code>df = pd.read_csv(filepath,sep='|') </code></pre> <p>I'm going to use a dummy df to show querying</p> <pre><code>df = pd.DataFrame(np.array(['alaska',1,2,'alabama',1,2,'brooklyn',1,2]).reshape(3,3)) ar2 = [df.values[n] if df.values[n][0].startswith('a') else [] for n in range(len(df.values))] df3 = pd.Dataframe(np.array(ar2)) df3.to_csv('outputfile','|') </code></pre>
0
2016-10-13T13:48:35Z
[ "python", "django" ]
Is it more reliable to rely on index of occurrence or keywords when parsing websites?
40,021,636
<p>Just started using XPath, I'm parsing a website with lxml.</p> <p>Is it preferable to do: </p> <pre><code>number_I_want = parsed_body.xpath('.//b')[6].text #or number_I_want = parsed_body.xpath('.//span[@class="class_name"]')[0].text </code></pre> <p>I'd rather find this out now, rather than much further down the line. Actually I couldn't get something like the second expression to work for my particular case. </p> <p>But essentially, the question: is it better to rely on <code>class</code> names (or other keywords) or indices of occurrence (such as 7th occurrence of bolded text)?</p>
0
2016-10-13T12:55:22Z
40,021,899
<p>I'd say that it is generally better to rely on <code>id</code> attributes, or <code>class</code> by default, than on the number and order of appearance of specific tags. That is more resilient to change in the page content.</p>
1
2016-10-13T13:06:46Z
[ "python", "xpath", "lxml" ]
Pyplot Label Scatter Plot with Coincident Points / Overlapping Annotations
40,021,676
<p>This question is a follow on to <a href="http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot">this</a>. How can I layout the annotations so they are still readable when the labeled points are exactly or nearly coincident? I need a programmatic solution, hand tuning the offsets is not an option. Sample with ugly labels:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt np.random.seed(0) N = 10 data = np.random.random((N, 4)) data[1, :2] = data[0, :2] data[-1, :2] = data[-2, :2] + .01 labels = ['point{0}'.format(i) for i in range(N)] plt.subplots_adjust(bottom = 0.1) plt.scatter( data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500, cmap = plt.get_cmap('Spectral')) for label, x, y in zip(labels, data[:, 0], data[:, 1]): plt.annotate( label, xy = (x, y), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '-&gt;', connectionstyle = 'arc3,rad=0')) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/d07k0.png" rel="nofollow"><img src="https://i.stack.imgur.com/d07k0.png" alt="enter image description here"></a></p>
0
2016-10-13T12:56:53Z
40,022,068
<p>Take the distance between the last point, set a threshold hold, and then flip the x,y text accordingly. See below.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt np.random.seed(0) N = 10 data = np.random.random((N, 4)) data[1, :2] = data[0, :2] data[-1, :2] = data[-2, :2] + .01 labels = ['point{0}'.format(i) for i in range(N)] plt.subplots_adjust(bottom = 0.1) plt.scatter( data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500, cmap = plt.get_cmap('Spectral')) old_x = old_y = 1e9 # make an impossibly large initial offset thresh = .1 #make a distance threshold for label, x, y in zip(labels, data[:, 0], data[:, 1]): #calculate distance d = ((x-old_x)**2+(y-old_y)**2)**(.5) #if distance less than thresh then flip the arrow flip = 1 if d &lt; .1: flip=-2 plt.annotate( label, xy = (x, y), xytext = (-20*flip, 20*flip), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '-&gt;', connectionstyle = 'arc3,rad=0')) old_x = x old_y = y plt.show() </code></pre> <p>which results in:</p> <p><a href="https://i.stack.imgur.com/aR6js.png" rel="nofollow"><img src="https://i.stack.imgur.com/aR6js.png" alt="enter image description here"></a></p>
1
2016-10-13T13:15:02Z
[ "python", "matplotlib" ]
Pyplot Label Scatter Plot with Coincident Points / Overlapping Annotations
40,021,676
<p>This question is a follow on to <a href="http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot">this</a>. How can I layout the annotations so they are still readable when the labeled points are exactly or nearly coincident? I need a programmatic solution, hand tuning the offsets is not an option. Sample with ugly labels:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt np.random.seed(0) N = 10 data = np.random.random((N, 4)) data[1, :2] = data[0, :2] data[-1, :2] = data[-2, :2] + .01 labels = ['point{0}'.format(i) for i in range(N)] plt.subplots_adjust(bottom = 0.1) plt.scatter( data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500, cmap = plt.get_cmap('Spectral')) for label, x, y in zip(labels, data[:, 0], data[:, 1]): plt.annotate( label, xy = (x, y), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '-&gt;', connectionstyle = 'arc3,rad=0')) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/d07k0.png" rel="nofollow"><img src="https://i.stack.imgur.com/d07k0.png" alt="enter image description here"></a></p>
0
2016-10-13T12:56:53Z
40,025,264
<p>Here's what I ended up with. Not perfect for all situations, and it doesn't even work smoothly for this example problem, but I think it is good enough for my needs. Thanks Dan for your answer pointing me in the right direction.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.spatial import cKDTree def get_label_xy(tree, thresh, data, i): neighbors = tree.query_ball_point([data[i, 0], data[i, 1]], thresh) if len(neighbors) == 1: xy = (-30, 30) else: mean = np.mean(data[:, :2][neighbors], axis=0) if mean[0] == data[i, 0] and mean[1] == data[i, 1]: if i &lt; np.max(neighbors): xy = (-30, 30) else: xy = (30, -30) else: angle = np.arctan2(data[i, 1] - mean[1], data[i, 0] - mean[0]) if angle &gt; np.pi / 2: xy = (-30, 30) elif angle &gt; 0: xy = (30, 30) elif angle &gt; -np.pi / 2: xy = (30, -30) else: xy = (-30, -30) return xy def labeled_scatter_plot(data, labels): plt.subplots_adjust(bottom = 0.1) plt.scatter( data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500, cmap = plt.get_cmap('Spectral')) tree = cKDTree(data[:, :2]) thresh = .1 for i in range(data.shape[0]): xy = get_label_xy(tree, thresh, data, i) plt.annotate( labels[i], xy = data[i, :2], xytext = xy, textcoords = 'offset points', ha = 'center', va = 'center', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '-&gt;', connectionstyle = 'arc3,rad=0')) np.random.seed(0) N = 10 data = np.random.random((N, 4)) data[1, :2] = data[0, :2] data[-1, :2] = data[-2, :2] + .01 data[5, :2] = data[4, :2] + [.05, 0] data[6, :2] = data[4, :2] + [.05, .05] data[7, :2] = data[4, :2] + [0, .05] labels = ['point{0}'.format(i) for i in range(N)] labeled_scatter_plot(data, labels) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/wa2rc.png" rel="nofollow"><img src="https://i.stack.imgur.com/wa2rc.png" alt="enter image description here"></a></p>
0
2016-10-13T15:33:15Z
[ "python", "matplotlib" ]
How to debug silent crash
40,021,842
<p>I have a Python3.4 and PyQt5 application. This application communicate with an embedded device (Send and receive some frames).</p> <p>I have a method (run from a QThread) to retrieve the device events ( It can be 10 events or more than 600 ). This methode work well in "release" mode. But when I start the program in "debug" mode with Pycharm, it will work without breakpoint but will crash with the exit code 0 if I put a breakpoint.</p> <p>I have a retry button to launch this process. So in release mode if I retry again and again it will also fail with the the exit code 0. </p> <p>Moreover, the application doesn't crash each time at the same moment, if the amount of data to read from the device is large, the soft will crash earlier, else it will be longer.</p> <p>So I was thinking about memory, but I can't catch any exception. I tried to re-raise every exception in my program, nothing, so I tried to add thoses lines in my main :</p> <pre><code>def on_exception_triggered(type_except, value, tb): import traceback trace = "".join(traceback.format_exception(type_except, value, tb)) print("ERROR HOOKED : ", trace) sys.__excepthook__(type_except, value, tb) sys.excepthook = on_exception_triggered </code></pre> <p>But it catch nothing more</p>
0
2016-10-13T13:04:13Z
40,033,229
<p>Actually the best thing that you can do is try to make your code independent from pyqt and debug it look for issues fix them and make connection with pyqt, because otherwise even if your code works fine you will get just the interface on a screen and you can not see what happen </p>
0
2016-10-14T00:44:51Z
[ "python", "multithreading", "exception-handling", "pyqt", "pycharm" ]
tkinter get selection radiobutton
40,021,843
<p>How can I append the priority of this application to the file as seen in the code below?</p> <pre><code> #Option boxes for assigning a priority level to the request priority = StringVar() Radiobutton(self.f4, text = "High", variable=priority, value="1").grid(row = 4, column = 1, sticky = W) Radiobutton(self.f4, text = "Low", variable=priority, value="2").grid(row = 6, column = 1, sticky = W) #Button for "Confirm application" self.app_con = Button(self.f4, text=" Confirm and finish ", command=self.apphistory) self.app_con.grid(row=4, column=2 def apphistory(self): fo = open("Application_History.txt", "a") fo.writelines(["Priotiry: "+str(priority.get()),"\n"]) fo.close </code></pre>
0
2016-10-13T13:04:15Z
40,022,538
<p>Have you tried changing </p> <blockquote> <p>variable=priority</p> </blockquote> <p>to </p> <blockquote> <p>variable=self.priority</p> </blockquote> <p>This way, the Radiobutton knows where to search for the variable (in your program / class) instead of looking for it in the Radiobutton-Class itself.</p> <p>And as mentioned in the comments, you need to create the variable</p> <blockquote> <p>self.priority</p> </blockquote>
0
2016-10-13T13:35:09Z
[ "python", "tkinter" ]
Find indices of a list of values in a not sorted numpy array
40,021,914
<p>I'm referring to a similar question: <a href="http://stackoverflow.com/questions/12122639">Find indices of a list of values in a numpy array</a></p> <p>In that case we have a master array that is sorted and another array of which we want to find the index in the master array.</p> <pre><code>master = np.array([1,2,3,4,5]) search = np.array([4,2,2,3]) </code></pre> <p>The suggested solution was:</p> <pre><code>&gt;&gt;&gt; master = np.array([1,2,3,4,5]) &gt;&gt;&gt; search = np.array([4,2,2,3]) &gt;&gt;&gt;np.searchsorted(master, search) array([3, 1, 1, 2]) </code></pre> <p>But what if master is not sorted? for example if i have two arrays like this where the first one is not sorted:</p> <pre><code>&gt;&gt;&gt;master = np.array([2,3,5,4,1]) &gt;&gt;&gt;search = np.array([3,2,1,4,5]) </code></pre> <p>i get:</p> <pre><code>&gt;&gt;&gt; np.searchsorted(master, search) array([1, 0, 0, 2, 5]) </code></pre> <p>But instead i would like:</p> <pre><code>array([1,0,4,3,2]) </code></pre> <p>i.e. the indices of items in search in master.</p> <p>How do i get them possibly with a native function of numpy?(not using [np.where(master==i) for i in search] )</p> <p>Thanks</p> <p>EDIT: In this case the search array is a permutation of master. Then i would like to find how the index of master are permuted to give a permuted array like search.</p> <p>As general case, search array contain some item that maybe contained or not in the master such as:</p> <pre><code>&gt;&gt;&gt;master = np.array([2,3,5,4,1]) &gt;&gt;&gt;search = np.array([1,4,7]) </code></pre>
1
2016-10-13T13:07:37Z
40,022,097
<p>If all else fails, you need to sort your master array temporarily, then invert the sort order needed for this after matching the elements:</p> <pre><code>import numpy as np master = np.array([2,3,5,4,1]) search = np.array([3,2,1,4,5]) # sorting permutation and its reverse sorti = np.argsort(master) sorti_inv = np.empty(sorti.shape,dtype=np.int64) sorti_inv[sorti] = np.arange(sorti.size) # get indices in sorted version tmpind = np.searchsorted(master,search,sorter=sorti) # transform indices back to original array with inverse permutation final_inds = tmpind[sorti_inv] </code></pre> <p>The result of the above is correctly</p> <pre><code>array([1, 0, 4, 3, 2]) </code></pre> <hr> <p>As you noted in a comment, your specific <code>search</code> and <code>master</code> are permutations of each other. In this case you can alternatively sort <em>both</em> arrays, and use the inverse permutation combined with the other direct permutation:</p> <pre><code>sorti = np.argsort(master) sorti_inv = np.empty(sorti.shape,dtype=np.int64) sorti_inv[sorti] = np.arange(sorti.size) sorti_s = np.argsort(search) final_inds = sorti_s[sorti_inv] </code></pre> <p>One should consider the effort needed to search two arrays vs searching one array in the sorted version of another. I really can't tell which one's faster.</p>
0
2016-10-13T13:16:41Z
[ "python", "arrays", "numpy" ]
Find element by tag name within element by tag name (Selenium)
40,022,010
<p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p> <pre><code>li = driver.find_elements_by_tag_name('li') for link in li: a_childrens = link.find_element_by_tag_name('a') for a in a_children (print a.get_attribute('href')) </code></pre> <p>Thanks in advance.</p>
1
2016-10-13T13:11:44Z
40,022,084
<p>You have the right idea, but part of your problem is that <code>a_childrens = link.find_element_by_tag_name('a')</code> will get you what you're looking for, but you're basically throwing out all of them because you get them in the loop, but don't do anything with them as you're in the loop. So you're only left with the variable from the last iteration.</p> <p>Your solution, correctly implemented, might look something like this</p> <pre><code>list_items = driver.find_elements_by_tag_name("li") for li in list_items: anchor_tag = li.find_element_by_tag_name("a") print(anchor_tag.get_attribute('href')) </code></pre> <p>That is, with the understanding that the HTML layout is as you described, something like:</p> <pre><code>&lt;li&gt;&lt;a href="foo"&gt;Hello&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="bar"&gt;World!&lt;/a&gt;&lt;/li&gt; </code></pre>
1
2016-10-13T13:16:09Z
[ "python", "selenium" ]
Find element by tag name within element by tag name (Selenium)
40,022,010
<p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p> <pre><code>li = driver.find_elements_by_tag_name('li') for link in li: a_childrens = link.find_element_by_tag_name('a') for a in a_children (print a.get_attribute('href')) </code></pre> <p>Thanks in advance.</p>
1
2016-10-13T13:11:44Z
40,022,128
<p>I recommend css_selector instead of tag_name</p> <pre><code>aTagsInLi = driver.find_elements_by_css_selector('li a') for a in aTagsInLi: (print a.get_attribute('href')) </code></pre>
3
2016-10-13T13:17:55Z
[ "python", "selenium" ]
Find element by tag name within element by tag name (Selenium)
40,022,010
<p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p> <pre><code>li = driver.find_elements_by_tag_name('li') for link in li: a_childrens = link.find_element_by_tag_name('a') for a in a_children (print a.get_attribute('href')) </code></pre> <p>Thanks in advance.</p>
1
2016-10-13T13:11:44Z
40,022,176
<p>Try to select the links directly:</p> <pre><code> links = driver.find_elements_by_tag_name('a') </code></pre>
0
2016-10-13T13:19:47Z
[ "python", "selenium" ]
Find element by tag name within element by tag name (Selenium)
40,022,010
<p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p> <pre><code>li = driver.find_elements_by_tag_name('li') for link in li: a_childrens = link.find_element_by_tag_name('a') for a in a_children (print a.get_attribute('href')) </code></pre> <p>Thanks in advance.</p>
1
2016-10-13T13:11:44Z
40,022,302
<p><strong>find_element_by_xpath</strong> would do the trick...</p> <pre><code>links = driver.find_elements_by_xpath('//li/a/@href') </code></pre>
0
2016-10-13T13:24:24Z
[ "python", "selenium" ]
Remove spaces before newlines
40,022,102
<p>I need to remove all spaces before the newline character throughout a string.</p> <pre><code>string = """ this is a line \n this is another \n """ </code></pre> <p>output:</p> <pre><code>string = """ this is a line\n this is another\n """ </code></pre>
2
2016-10-13T13:16:54Z
40,022,269
<pre><code>import re re.sub('\s+\n','\n',string) </code></pre> <p>Edit: better version from comments:</p> <pre><code>re.sub(r'\s+$', '', string, flags=re.M) </code></pre>
2
2016-10-13T13:22:56Z
[ "python" ]
Remove spaces before newlines
40,022,102
<p>I need to remove all spaces before the newline character throughout a string.</p> <pre><code>string = """ this is a line \n this is another \n """ </code></pre> <p>output:</p> <pre><code>string = """ this is a line\n this is another\n """ </code></pre>
2
2016-10-13T13:16:54Z
40,022,271
<p>You can <em>split</em> the string into lines, <em>strip</em> off all whitespaces on the right using <code>rstrip</code>, then add a new line at the end of each line:</p> <pre><code>''.join([line.rstrip()+'\n' for line in string.splitlines()]) </code></pre>
6
2016-10-13T13:23:00Z
[ "python" ]
Remove spaces before newlines
40,022,102
<p>I need to remove all spaces before the newline character throughout a string.</p> <pre><code>string = """ this is a line \n this is another \n """ </code></pre> <p>output:</p> <pre><code>string = """ this is a line\n this is another\n """ </code></pre>
2
2016-10-13T13:16:54Z
40,022,448
<p>As you can find <a href="http://stackoverflow.com/questions/8270092/python-remove-all-whitespace-in-a-string">here</a>, </p> <p>To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:</p> <pre><code>sentence = ''.join(sentence.split()) </code></pre> <p>or a regular expression:</p> <pre><code>import re pattern = re.compile(r'\s+') sentence = re.sub(pattern, '', sentence) </code></pre>
-1
2016-10-13T13:31:27Z
[ "python" ]
How to integrate Django-CMS into an existing project
40,022,161
<p>I need to integrate Django-CMS 3.x into an existing project (<code>mypjc</code> hereafter). I already checked <a href="http://stackoverflow.com/questions/31167313/how-to-start-integrating-django-cms-into-existing-project">this</a> question (and other similar) but they point to a <a href="http://django-cms.readthedocs.io/en/3.0.12/how_to/integrate.html" rel="nofollow">tutorial</a> page that is no longer available.</p> <p>I'm a bit confused by the tons of infos you can find online and I have not really understood if Django-CMS <strong>can be integrated</strong> as an <strong>app</strong> into an existing and independently running Django project.</p> <p><code>mypjc</code> (using Django 1.8) would benefit from a user friendly CMS. Basically I'd the user to be able to write texts and to load in their posts images stored in the (common) database, images that are created by the user in <code>mypjc</code>.</p> <p>Is it possible? if yes, could anyone help me defying the steps needed to make the integration clean and successful?</p> <p>Thank you in advance for any help you could provide. </p>
0
2016-10-13T13:19:19Z
40,022,513
<p>With Django CMS, it is indeed possible to integrate it into an existing project. </p> <p>If you already have an existing project with URL/menu management, then you can simply integrate just the per-page CMS, which can be added as additional field to your model:</p> <pre><code>from django.db import models from cms.models.fields import PlaceholderField class MyModel(models.Model): # your fields my_placeholder = PlaceholderField('placeholder_name') # your methods </code></pre> <p>You can find more information <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/placeholders.html" rel="nofollow">here</a>.</p> <p>For any existing projects, you are likely to need to use the manual installation process outlined <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/install.html" rel="nofollow">here</a>.</p>
1
2016-10-13T13:33:59Z
[ "python", "django", "content-management-system", "django-cms" ]
How can I replace all the " " values with Zero's in a column of a pandas dataframe
40,022,178
<pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].fillna("S") </code></pre> <p>titanic_df is data frame,Embarked is a column name. I have to missing cells in my column i.e blank spaces and I want to add "S" at the missing place but the code I mentioned above is not working.Please help me.</p>
1
2016-10-13T13:19:48Z
40,022,218
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a>:</p> <pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].replace(" ", "S") </code></pre> <p>Sample:</p> <pre><code>import pandas as pd titanic_df = pd.DataFrame({'Embarked':['a','d',' ']}) print (titanic_df) Embarked 0 a 1 d 2 titanic_df['Embarked'] = titanic_df['Embarked'].replace(" ", "S") print (titanic_df) Embarked 0 a 1 d 2 S </code></pre> <hr> <p>Also you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a> with regex if need replace one or more whitespaces.<br> <code>^</code> means the beginning of whitespace(s), <code>$</code> means the end of whitespace(s):</p> <pre><code>titanic_df = pd.DataFrame({'Embarked':['a ',' d',' ', ' ']}) print (titanic_df) Embarked 0 a 1 d 2 3 titanic_df['Embarked'] = titanic_df['Embarked'].str.replace("^\s+$", "S") #same output #titanic_df['Embarked'] = titanic_df['Embarked'].replace("^\s+$", "S", regex=True) print (titanic_df) Embarked 0 a 1 d 2 S 3 S </code></pre>
3
2016-10-13T13:21:03Z
[ "python", "pandas" ]
How can I replace all the " " values with Zero's in a column of a pandas dataframe
40,022,178
<pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].fillna("S") </code></pre> <p>titanic_df is data frame,Embarked is a column name. I have to missing cells in my column i.e blank spaces and I want to add "S" at the missing place but the code I mentioned above is not working.Please help me.</p>
1
2016-10-13T13:19:48Z
40,022,351
<p>Or you could use <code>apply</code></p> <pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].apply(lambda x: "S" if x == " " else x) </code></pre>
1
2016-10-13T13:27:20Z
[ "python", "pandas" ]
Attempted relative import beyond toplevel package
40,022,220
<p>Here is my folder structure:</p> <pre><code>Mopy/ # no init.py ! bash/ __init__.py bash.py # &lt;--- Edit: yep there is such a module too bass.py bosh/ __init__.py # contains from .. import bass bsa_files.py ... test_bash\ __init__.py # code below test_bosh\ __init__.py test_bsa_files.py </code></pre> <p>In <code>test_bash\__init__.py</code> I have:</p> <pre><code>import sys from os.path import dirname, abspath, join, sep mopy = dirname(dirname(abspath(__file__))) assert mopy.split(sep)[-1].lower() == 'mopy' sys.path.append(mopy) print 'Mopy folder appended to path: ', mopy </code></pre> <p>while in <code>test_bsa_files.py</code>:</p> <pre><code>import unittest from unittest import TestCase import bosh class TestBSAHeader(TestCase): def test_read_header(self): bosh.bsa_files.Header.read_header() if __name__ == '__main__': unittest.main() </code></pre> <p>Now when I issue:</p> <pre><code>python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\path\to\Mopy\test_bash\test_bosh\test_bar.py true </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 124, in &lt;module&gt; modules = [loadSource(a[0])] File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 43, in loadSource module = imp.load_source(moduleName, fileName) File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py", line 4, in &lt;module&gt; import bosh File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\bash\bosh\__init__.py", line 50, in &lt;module&gt; from .. import bass ValueError: Attempted relative import beyond toplevel package </code></pre> <p>Since 'Mopy" is in the sys.path and <code>bosh\__init__.py</code> is correctly resolved why it complains about relative import above the top level package ? <em>Which is the top level package</em> ?</p> <p>Incidentally this is my attempt to add tests to a legacy project - had asked in <a href="http://stackoverflow.com/q/34694437/281545">Python test package layout</a> but was closed as a duplicate of <a href="http://stackoverflow.com/q/61151/281545">Where do the Python unit tests go?</a>. Any comments on my current test package layout is much appreciated !</p> <hr> <p>Well the <a href="http://stackoverflow.com/a/40022629/281545">answer below</a> does not work in my case:</p> <p>The <em>module</em> bash.py is the entry point to the application containing:</p> <pre><code>if __name__ == '__main__': main() </code></pre> <p>When I use <code>import bash.bosh</code> or <code>from Bash import bosh</code> I get:</p> <pre><code>C:\_\Python27\python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true Testing started at 3:45 PM ... usage: utrunner.py [-h] [-o OBLIVIONPATH] [-p PERSONALPATH] [-u USERPATH] [-l LOCALAPPDATAPATH] [-b] [-r] [-f FILENAME] [-q] [-i] [-I] [-g GAMENAME] [-d] [-C] [-P] [--no-uac] [--uac] [--bashmon] [-L LANGUAGE] utrunner.py: error: unrecognized arguments: C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true Process finished with exit code 2 </code></pre> <p>This usage messgae is from the main() in bash. No comments...</p>
0
2016-10-13T13:21:04Z
40,022,629
<p>TLDR: Do</p> <pre><code>import bash.bosh </code></pre> <p>or</p> <pre><code>from bash import bosh </code></pre> <p>If you also just happen to have a construct like <code>bash.bash</code>, you have to make sure your package takes precedence over its contents. Instead of appending, add it to the front of the search order:</p> <pre><code># test_bash\__init__.py sys.path.insert(0, mopy) </code></pre> <hr> <p>When you do</p> <pre><code>import bosh </code></pre> <p>it will import the <em>module</em> <code>bosh</code>. This means <code>Mopy/bash</code> is in your <code>sys.path</code>, python finds the file <code>bosh</code> there, and imports it. The module is now globally known by the name <code>bosh</code>. Whether <code>bosh</code> is itself a module or package doesn't matter for this, it only changes whether <code>bosh.py</code> or <code>bosh/__init__.py</code> is used.</p> <p>Now, when <code>bosh</code> tries to do</p> <pre><code>from .. import bass </code></pre> <p>this is <em>not</em> a file system operation ("one directory up, file bass") but a module name operation. It means "one package level up, module bass". <code>bosh</code> wasn't imported from its package, but on its own, though. So going up one package is not possible - you end up at the package <code>''</code>, which is not valid.</p> <p>Let's look at what happens when you do</p> <pre><code>import bash.bosh </code></pre> <p>instead. First, the <em>package</em> <code>bash</code> is imported. Then, <code>bosh</code> is imported as a module <em>of that package</em> - it is globally know as <code>bash.bosh</code>, even if you used <code>from bash import bosh</code>.</p> <p>When <code>bosh</code> does</p> <pre><code>from .. import bass </code></pre> <p>that one works now: going one level up from <code>bash.bosh</code> gets you to <code>bash</code>. From there, <code>bass</code> is imported as <code>bash.bass</code>.</p> <p>See also <a href="http://stackoverflow.com/a/39932711/5349916">this related answer</a>.</p>
1
2016-10-13T13:38:51Z
[ "python", "python-2.7", "python-import", "python-unittest", "relative-import" ]
How to solve TypeError: 'str' does not support the buffer interface?
40,022,354
<p>My code:</p> <pre><code>big_int = 536870912 f = open('sample.txt', 'wb') for item in range(0, 10): y = bytearray.fromhex('{:0192x}'.format(big_int)) f.write("%s" %y) f.close() </code></pre> <p>I want to convert a long int to bytes. But I am getting <code>TypeError: 'str' does not support the buffer interface</code>. </p>
1
2016-10-13T13:27:34Z
40,022,501
<p>In Python 3, strings are implicitly Unicode and are therefore detached from a specific binary representation (which depends on the encoding that is used). Therefore, the string <code>"%s" % y</code> cannot be written to a file that is opened in binary mode.</p> <p>Instead, you can just write <code>y</code> directly to the file:</p> <pre><code>y = bytearray.fromhex('{:0192x}'.format(big_int)) f.write(y) </code></pre> <p>Moreover, your code (<code>"%s" % y</code>) in fact creates a Unicode string containing the <em>string representation</em> of <code>y</code> (i.e., <code>str(y)</code>), which isn't what you think it is. For example:</p> <pre><code>&gt;&gt;&gt; '%s' % bytearray() "bytearray(b'')" </code></pre>
1
2016-10-13T13:33:38Z
[ "python" ]
How to solve TypeError: 'str' does not support the buffer interface?
40,022,354
<p>My code:</p> <pre><code>big_int = 536870912 f = open('sample.txt', 'wb') for item in range(0, 10): y = bytearray.fromhex('{:0192x}'.format(big_int)) f.write("%s" %y) f.close() </code></pre> <p>I want to convert a long int to bytes. But I am getting <code>TypeError: 'str' does not support the buffer interface</code>. </p>
1
2016-10-13T13:27:34Z
40,023,130
<p>In addition to @Will answer, it is better to use <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow"><code>with</code></a> statement in to open your files. Also, if you using python 3.2 and later, you can use <a href="https://docs.python.org/3/library/stdtypes.html#int.to_bytes" rel="nofollow"><code>int.to_bytes</code></a> or <a href="https://docs.python.org/3/library/stdtypes.html#int.from_bytes" rel="nofollow"><code>int.from_bytes</code></a> to reverse the process.</p> <p>Sample of what I said:</p> <pre><code>big_int=536870912 with open('sample.txt', 'wb') as f: y = big_int.to_bytes((big_int.bit_length() // 8) + 1, byteorder='big') f.write(y) print(int.from_bytes(y, byteorder='big')) </code></pre> <p>The last <code>print</code> is to show you how to reverse it.</p>
3
2016-10-13T13:59:04Z
[ "python" ]
.readlines() shouldn't return an array?
40,022,420
<p>I have a problem with <code>.readlines()</code>. it used to only return the line specified, i.e. if I ran</p> <pre><code>f1 = open('C:\file.txt','r') filedata = f1.readlines(2) f1.close() print filedata </code></pre> <p>it should print the second line of <strong>file.txt.</strong> However now when I run that same code, it returns the entire contents of the file in an array, with each line in the file as a separate object in the array. I am using the same PC and am running the same version of <code>python (2.7).</code></p> <p>Does anyone know of a way to fix this?</p>
0
2016-10-13T13:29:58Z
40,022,449
<p>Change this:</p> <pre><code>f1.readlines(2) </code></pre> <p>To this:</p> <pre><code>f1.readlines()[2] </code></pre>
2
2016-10-13T13:31:33Z
[ "python", "readlines" ]
.readlines() shouldn't return an array?
40,022,420
<p>I have a problem with <code>.readlines()</code>. it used to only return the line specified, i.e. if I ran</p> <pre><code>f1 = open('C:\file.txt','r') filedata = f1.readlines(2) f1.close() print filedata </code></pre> <p>it should print the second line of <strong>file.txt.</strong> However now when I run that same code, it returns the entire contents of the file in an array, with each line in the file as a separate object in the array. I am using the same PC and am running the same version of <code>python (2.7).</code></p> <p>Does anyone know of a way to fix this?</p>
0
2016-10-13T13:29:58Z
40,022,680
<p>Don't use <code>readlines</code>; it reads the entire file into memory, <em>then</em> selects the desired line. Instead, just read the first <code>n</code> lines, then break.</p> <pre><code>n = 2 with open('C:\file.txt','r') as f1: for i, filedata in enumerate(f1, 1): if i == n: break print filedata.strip() </code></pre> <p>The <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code> documentation</a> also provides a recipe for consuming the first <em>n</em> items of an sequence:</p> <pre><code>def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(islice(iterator, n, n), None) </code></pre> <p>You might use it like this:</p> <pre><code>n = 2 with open('C:\file.txt','r') as f1: consume(f1, n-1) filedata = next(f1) print filedata.strip() </code></pre>
3
2016-10-13T13:40:42Z
[ "python", "readlines" ]
My version of the quicksort algorithm from Wikipedia does not work
40,022,487
<pre><code>def partition(A,lo,hi): pivot = A[hi] i=lo #Swap for j in range(lo,hi-1): if (A[j] &lt;= pivot): val=A[i] A[i]=A[j] A[j]=val i=i+1 val=A[i] A[i]=A[hi] A[hi]=val return(i) def quicksort(A,lo,hi): if (lo&lt;hi): p=partition(A,lo,hi) quicksort(A,lo,p-1) quicksort(A,p+1,hi) return(A) </code></pre> <p>If my input is <code>[5,3,2,6,8,9,1]</code> the output is <code>[1, 2, 5, 3, 8, 9, 6]</code>, why is that?</p>
-5
2016-10-13T13:33:15Z
40,022,761
<pre><code>def partition(A,lo,hi): pivot = A[hi] i=lo #Swap for j in range(lo,hi-1): if (A[j] &lt;= pivot): val=A[i] A[i]=A[j] A[j]=val i=i+1 val=A[i] #was in for loop was suppose to be outside of for loop A[i]=A[hi] #was in for loop was suppose to be outside of for loop A[hi]=val #was in for loop was suppose to be outside of for loop return(i) def quicksort(A,lo,hi): if (lo&lt;hi): p=partition(A,lo,hi) quicksort(A,lo,p-1) quicksort(A,p+1,hi) return(A) x = [5,3,2,6,8,9,1] print(quicksort(x,0,len(x)-1)) </code></pre> <p>Simple fix, your indentation was wrong in partition.</p> <p>Outputs </p> <pre><code>[1, 2, 3, 5, 6, 8, 9] </code></pre>
2
2016-10-13T13:44:25Z
[ "python", "quicksort" ]
AWS alarm for real time values
40,022,495
<p>(AWS Beginner) </p> <p>I am connected to temperature sensors and want to trigger an email notification when temperature crosses the threshold value. </p> <p>In SNS alarms,metrics are predefined and I am not able to customize my real time alarm.</p>
0
2016-10-13T13:33:28Z
40,022,848
<p>Amazon CloudWatch supports custom CloudWatch metrics.</p> <p><a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html" rel="nofollow">http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html</a></p> <p>Once you have your metrics being pushed to CloudWatch, you can then create a CloudWatch alarm on your custom metrics to trigger alerts via SNS.</p>
2
2016-10-13T13:47:17Z
[ "python", "amazon-web-services" ]
Check the entry after the user has entered a value
40,022,499
<p>I wrote a graphical interface using Tkinter with Python 3.4. In my script, I am using ttk.Entry to generate a input space where the user can enter a value.</p> <p>Is it possible to do an action when the user has finished tipping e.g. call a function? I though about using a button if it was not possible.</p> <p>Here is a extract of the code:</p> <pre><code>ttk.Label(mainframe, text="Enter your data path", font=('Times', '14', 'bold italic')).grid(column=1, row=2, sticky=E) path_frame = StringVar() input_path_frame = ttk.Entry(mainframe, width=100, textvariable=path_frame) input_path_frame.grid(column=2, row=2, columnspan=2, sticky=(N)) </code></pre> <p>I would like to have a event when the 'input_path_frame' is fullfill.</p> <p>Thank you for your time</p>
0
2016-10-13T13:33:31Z
40,022,668
<p>You can add a <code>FocusOut</code> event manager function. This event-manager would execute as soon as the user has finished typing in the field and moved to something else: </p> <pre><code>input_path_frame.bind( '&lt;FocusOut&gt;', lambda e, strvar=path_frame: check_field(e, strvar) ) # check_field function would be executed as soon as the focus leaves the field </code></pre> <p>Here <code>check_field</code> function would be used to check if the <code>input_path_frame</code> field is empty or not.<br>.<br> It would be something like this:</p> <pre><code>def check_field(e, strvar): # do stuff # check if empty # run tests etc return strvar.get() </code></pre> <p>If you want to get result keys simultaneously, you can nest two event managing functions like <code>&lt;FocusIn&gt;</code> and <code>&lt;Key&gt;</code>. And can unbind the <code>&lt;key&gt;</code> at <code>&lt;FocusOut&gt;</code>:</p> <pre><code>input_path_frame.bind("&lt;FocusIn&gt;", lambda e: key_bind_func) input_path_frame.bind("&lt;FocusOut&gt;", lambda e: key_unbind_func) </code></pre>
1
2016-10-13T13:40:27Z
[ "python", "python-3.x", "tkinter" ]
Creating an empty Pandas DataFrame column with a fixed first value then filling it with a formula
40,022,553
<p>I'd like to create an emtpy column in an existing DataFrame with the first value in only one column to = 100. After that I'd like to iterate and fill the rest of the column with a formula, like row[C][t-1] * (1 + row[B][t])</p> <p>very similar to: <a href="http://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-then-filling-it">Creating an empty Pandas DataFrame, then filling it?</a></p> <p>But the difference is fixing the first value of column 'C' to 100 vs entirely formulas.</p> <pre><code>import datetime import pandas as pd import numpy as np todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') columns = ['A','B','C'] df_ = pd.DataFrame(index=index, columns=columns) df_ = df_.fillna(0) data = np.array([np.arange(10)]*3).T df = pd.DataFrame(data, index=index, columns=columns) df['B'] = df['A'].pct_change() df['C'] = df['C'].shift() * (1+df['B']) ## how do I set 2016-10-03 in Column 'C' to equal 100 and then calc consequtively from there? df </code></pre>
0
2016-10-13T13:35:41Z
40,023,331
<p>Try this. Unfortunately, something similar to a for loop is likely needed because you will need to calculate the next row based on the prior rows value which needs to be saved to a variable as it moves down the rows (c_column in my example):</p> <pre><code>c_column = [] c_column.append(100) for x,i in enumerate(df['B']): if(x&gt;0): c_column.append(c_column[x-1] * (1+i)) df['C'] = c_column </code></pre>
0
2016-10-13T14:07:38Z
[ "python", "pandas", "dataframe" ]
ajax returns python array response as string
40,022,582
<p>I am trying to list, in a select dropdown, some ontology elements using the following ajax:</p> <pre><code>$.ajax({ type: 'get', url:"../py/ConfigOntology.py", success: function(data){ $("#instance_image_1").append($("&lt;option&gt;&lt;/option&gt;").attr("value", data).text(data)); },}); </code></pre> <p>"ConfigOntology.py" is a simple code that extracts and prints two ontology items. However, the ajax takes these two as a single string. Parts of this .py contents that generate the output are:</p> <pre><code>import rdflib, rdfextras, cgitb from rdflib import Graph cgitb.enable() print ("Content-Type: text/plain;charset=utf-8") print("") def getImages(results): for row in results: print (row['storedImage'][50:]) sparql = "the query goes here" results = ConfigOnto.query(sparql) getImages(results) </code></pre> <p>I tried a php script with a php exec(), which gets the .py output as an array but the ajax also takes that a string. I tried JSON.parse(data) but got error saying "Uncaught SyntaxError: Unexpected token K in JSON at position 0" - referring to end of line in in .py output. </p> <p>So, my "big" question is: <strong>how can I access the ConfigOntology.py output as individual items in the ajax() rather than a string, and what could be a possible fixed code for this problem.</strong></p> <p>P.S: this is my first ajax function so please go easy on me. </p>
0
2016-10-13T13:36:49Z
40,022,925
<p>I think what you should do is to return a JSON Object in the endpoint of your ajax call. </p> <p>If I understand it correctly right now you try to read the output of a python script in an ajax request which is not the normal workflow for this. </p> <p>the normal workflow would be <strong>request</strong> (client, your browser) --> <strong>server</strong>(this is in your case the script, but it should really be a server) <strong>--> response</strong> (this can be a json Object or html, in your case it is just the console output.)</p> <p>so what you need to do is to change your pyhton script that gives a console output into an endpoint of a server, and that endpoint should return a <strong>JSON</strong> response. </p> <p>here is a simple example of json processing with Flask (a simple python webserver) <a href="http://code.runnable.com/Up77jfzqtL5FAAAu/json-dumps-and-loads-in-flask-for-python" rel="nofollow">http://code.runnable.com/Up77jfzqtL5FAAAu/json-dumps-and-loads-in-flask-for-python</a></p> <p>I hope this can get you started</p>
0
2016-10-13T13:50:16Z
[ "javascript", "php", "python", "ajax" ]
Scrapy ImportError: No module named Item
40,022,721
<p>I know that this question was already widely discussed, but I didn't find an answer. I'm getting error <strong>ImportError: No module named items</strong>. I've created a new project with <strong>$ scrapy startproject pluto</strong> and I have no equal names (in names of project, classes etc), to avoid <a href="http://stackoverflow.com/questions/10570635/scrapy-importerror-no-module-named-items">problem with naming</a>.</p> <p><em>pluto_spider.py</em> :</p> <pre><code>import scrapy from items import PlutoItem class PlutoSpider(scrapy.Spider): name = "plutoProj" allowed_domains = ['successories.com'] start_urls = [ 'http://www.successories.com/iquote/category/39/inspirational-quotes/4', 'http://www.successories.com/iquote/category/39/inspirational-quotes/6', ] def parse(self,response): items = [] for quote in response.css('div.quotebox'): item = PlutoItem() item['author'] = quote.css('span.author a::text').extract_first() item['quote'] = quote.css('div.quote a::text').extract_first() items.append(item) return items </code></pre> <p><em>item.py</em> : </p> <pre><code>import scrapy class PlutoItem(scrapy.Item): author = scrapy.Field() quote = scrapy.Field() </code></pre> <p>This my folder's hierarchy:</p> <pre><code>/pluto /pluto/scrapy.cfg /pluto/pluto/__init__.pyc /pluto/pluto/__init__.py /pluto/pluto/items.py /pluto/pluto/pipelines.py /pluto/pluto/settings.py /pluto/pluto/settings.pyc /pluto/pluto/spiders/__init__.py /pluto/pluto/spiders/__init__.pyc /pluto/pluto/spiders/pluto_spider.py /pluto/pluto/spiders/pluto_spider.pyc </code></pre>
0
2016-10-13T13:42:29Z
40,022,922
<p>First of all, make sure to <em>execute the Scrapy command from inside the top level directory of your project</em>.</p> <p>Or you may also try changing your import to:</p> <pre><code>from pluto.items import PlutoItem </code></pre>
1
2016-10-13T13:50:10Z
[ "python", "scrapy" ]
Scrapy ImportError: No module named Item
40,022,721
<p>I know that this question was already widely discussed, but I didn't find an answer. I'm getting error <strong>ImportError: No module named items</strong>. I've created a new project with <strong>$ scrapy startproject pluto</strong> and I have no equal names (in names of project, classes etc), to avoid <a href="http://stackoverflow.com/questions/10570635/scrapy-importerror-no-module-named-items">problem with naming</a>.</p> <p><em>pluto_spider.py</em> :</p> <pre><code>import scrapy from items import PlutoItem class PlutoSpider(scrapy.Spider): name = "plutoProj" allowed_domains = ['successories.com'] start_urls = [ 'http://www.successories.com/iquote/category/39/inspirational-quotes/4', 'http://www.successories.com/iquote/category/39/inspirational-quotes/6', ] def parse(self,response): items = [] for quote in response.css('div.quotebox'): item = PlutoItem() item['author'] = quote.css('span.author a::text').extract_first() item['quote'] = quote.css('div.quote a::text').extract_first() items.append(item) return items </code></pre> <p><em>item.py</em> : </p> <pre><code>import scrapy class PlutoItem(scrapy.Item): author = scrapy.Field() quote = scrapy.Field() </code></pre> <p>This my folder's hierarchy:</p> <pre><code>/pluto /pluto/scrapy.cfg /pluto/pluto/__init__.pyc /pluto/pluto/__init__.py /pluto/pluto/items.py /pluto/pluto/pipelines.py /pluto/pluto/settings.py /pluto/pluto/settings.pyc /pluto/pluto/spiders/__init__.py /pluto/pluto/spiders/__init__.pyc /pluto/pluto/spiders/pluto_spider.py /pluto/pluto/spiders/pluto_spider.pyc </code></pre>
0
2016-10-13T13:42:29Z
40,022,964
<p>It looks like your <code>items.py</code> and <code>pluto_spider.py</code> are at different levels. You should make your import either <code>from pluto import items</code> or a relative import <code>import ..items</code> per <a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a> to import the module.</p> <p>If you want the class <code>from pluto.items import PlutoItem</code></p>
1
2016-10-13T13:52:07Z
[ "python", "scrapy" ]
Finding out where analytics should be defined
40,022,757
<p>I am working with Google Analytics api in python and keep getting the error</p> <pre><code>NameError: name 'analytics' is not defined. </code></pre> <p>I have been searching for several days on the <code>analytics</code> api site and on StackOverflow for the answer. If someone could please point me in the direction of the right documentation or help me out here that would be greatly appreciated. Attached is the code that I have so far. </p> <pre><code>from apiclient.http import MediaFileUpload from apiclient.errors import HttpError try: media = MediaFileUpload('Bing_Ad_Test.csv', mimetype='application/octet-stream', resumable=False) daily_upload = analytics.management().uploads().uploadData( accountId='', webPropertyId='', customDataSourceId='', media_body=media).execute() except TypeError, error: # Handle errors in constructing a query. print 'There was an error in constructing your query : %s' % error except HttpError, error: # Handle API errors. print ('There was an API error : %s : %s' % (error.resp.status, error.resp.reason)) </code></pre>
2
2016-10-13T13:44:08Z
40,023,032
<p>The error is saying what is happening: you did not define the name <code>analytics</code> used in line 9 previously</p> <pre><code>daily_upload = analytics.management().uploads().uploadData( </code></pre> <p>You need to go over the first steps in order to use that and import it. You will also need an account since it requires auth.</p> <p><a href="https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py" rel="nofollow">https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py</a></p> <p>After you setup, you should read</p> <p><a href="https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide" rel="nofollow">https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide</a></p> <p>With that you should be ok!</p>
0
2016-10-13T13:55:18Z
[ "python", "python-2.7", "google-analytics", "google-analytics-api" ]
Any ideas why this code won't work
40,022,809
<p>I have multiple files with names and stats and a file that checks for a certain stat.</p> <pre><code>Example File 1 Eddy,23,2,4,9,AB Frank,46,2,4,5,DA Example File 2 AB B BA DA DH </code></pre> <p>I am not getting any errors but it is not writing to the new file.</p> <p>The code I am using to do this is:</p> <pre><code># Open Removal file and create a set of required removals book_removals = open("File2.csv") search_removals_col = 0 # Open the All Candidates file book_candidates = open('File1.csv') search_candidates_col = 4 # Create a New Roster file book_new = open('upload.csv') # Iterate through candidates file, looking for removals for row in range(search_candidates_col): if book_candidates == book_removals: book_new.write(row) book_new.flush book_new.close() </code></pre>
-1
2016-10-13T13:45:40Z
40,023,845
<pre><code>import csv stats = set() with open('File2.csv') as file2: for line in file2: stats.add(line) with open('File1.csv', newline='') as file1: file1_reader = csv.reader(file1) with open('output.csv', 'w+', newline='') as output: output_writer = csv.writer(output) for line in file1_reader: if any(item in stats for item in line): output_writer.writerow(line) </code></pre> <p>When dealing with .csv files, use the <code>csv</code> module. This builds a <code>set</code> out of lines in <code>File2</code>, then goes through every line in <code>File1</code>. If that line has a value from <code>File2</code>, then that line is written to <code>output.csv</code></p>
0
2016-10-13T14:29:22Z
[ "python", "python-3.5.2" ]
Python: count time of watching video
40,022,937
<p>I have a task, connected with detection time of watching video. If I watch the video, for example <code>https://www.youtube.com/watch?v=jkaMiaRLgvY</code>, is it real to get quantity of seconds, which passed from the moment you press the button to start and until stop?</p>
0
2016-10-13T13:50:46Z
40,024,596
<p>If what you are measuring is the total time the <strong>user</strong> spent watching the video (including stalls/interruptions) then your strategy would work. </p> <p>However, if you are looking to measure the video duration, then simply counting the number of seconds since "start" was pressed isn't very accurate. While your wall clock is still running, the video playback could jitter or even stall for a number of reasons.</p> <ul> <li>Slow network (buffering)</li> <li>Decoding/rendering delay. For instance, if you are trying to play a high-resolution video on a low-end device.</li> <li>Probably many other...</li> </ul>
0
2016-10-13T15:02:36Z
[ "python", "video", "youtube", "video-streaming" ]
pairing data between two files
40,022,967
<p>I'm trying to match data between two files.</p> <p>File 1:</p> <pre class="lang-none prettyprint-override"><code># number of records, name 1234, keyword </code></pre> <p>File 2:</p> <pre class="lang-none prettyprint-override"><code># date/time, name 2016-10-13| here is keyword in the name </code></pre> <p>as a result, I'd like to have File 3 written as:</p> <pre class="lang-none prettyprint-override"><code># number of records, name, date 1234, here is keyword in the name, 2016-10-13 </code></pre> <p>So the idea here is to iterate through File 1, get all keywords and check File 2 if it exists there. If that's true, take first field (date) from File 2 and put is as last item in File 1. I wrote following code to test few things but it's not working well. First issue I have is that python is not finding any <code>keyword</code> in File 2.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import csv FILE1='file1' FILE2='file2' file2data=[] with open(FILE2, 'rb') as file2file: reader = csv.reader(file2file, delimiter='|', quotechar='"') for row in reader: file2data.append(row) def check(name): print('checking: "%s"' % name) rval=[] for item in file2data: if name in item: rval.append(item) return rval with open(FILE1, 'rb') as csvfile: csvreader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in csvreader: entries=row[0] keyword=row[1].strip() checked=check(keyword) if checked: print('ok') </code></pre> <p>Anyone know why is that happening? Why inside <code>check()</code> function the following code</p> <pre><code>if name in item: </code></pre> <p>is not finding any values?</p>
1
2016-10-13T13:52:20Z
40,023,307
<p>this</p> <pre><code>if name in item: </code></pre> <p>checks if there is an item <em>cell</em> with the exact content <code>name</code> in the <code>item</code> row (list of cells) (<code>item</code> is actually the row you stored earlier, bad naming :))</p> <p>What you need is to scan each item to see if the string is contained. So write:</p> <pre><code>if any(name in cell for cell in item): </code></pre> <p>instead</p> <p><code>any</code> will return <code>True</code> as soon as if finds <code>name</code> substring in a cell of <code>item</code>. Note that this is a substring match, not a word match. <code>key</code> will match a string containing <code>keyword</code>. If you want a word match (by splitting words according to blanks):</p> <pre><code>if any(name in cell.split() for cell in item): </code></pre>
3
2016-10-13T14:06:23Z
[ "python" ]
Django - Dynamic form fields based on foreign key
40,022,982
<p>I'm working on creating a database which has programs and these programs have risks. Some background information: Programs (grandparents) have multiple Characteristics (parents) which have multiple Categories (children). I've already constructed a database containing these, however, I want to add risks to a particular program.</p> <p>That is, for example i have Risk 1 which i want to add to Program 1. I have to answer the following questions: Which characteristics do Risk 1 have? To answer this, I want to construct a dynamic form field. (Note, the amount of characteristics can by any arbitrary number, as well as the amount of categories each characteristic has).</p> <p>How do I construct such form? I've tried formsets, however I do not know how to implement those in a practical way (I'm still a bit new with Python).</p> <p>This is a printscreen of how I want it to be implemented: <a href="https://gyazo.com/40c448c0096a9ec5da751ba9883dc912" rel="nofollow">https://gyazo.com/40c448c0096a9ec5da751ba9883dc912</a><br> However, I have no idea what to do. (Note that the possible answers in the drop down menu are the categories that correspond to that particular Characteristic). This is what I'm getting: <a href="https://gyazo.com/25fd18e2f31e6931bfd3639ce4be632c" rel="nofollow">https://gyazo.com/25fd18e2f31e6931bfd3639ce4be632c</a></p> <p>This is the corresponding code I have thus far:</p> <pre><code># views.py def risk_create(request): program = get_object_or_404(Program, id=20) RiskFormSet = formset_factory(RiskForm, ... ... extra=len(Program.objects.get(id=program.id).char_set.all())) context = { 'title': 'New Risk', 'form': RiskFormSet } return render(request, 'risk_form.html', context) # forms.py class RiskForm(forms.Form): for char in Program.objects.get(id=20).char_set.all(): char = forms.ModelChoiceField(char.cat_set.all(), label=char) </code></pre> <p>I'VE FOUND MY ANSWER.</p> <pre><code>class RiskForm(forms.Form): def __init__(self, *args, **kwargs): programid = kwargs.pop('programid', None) super(RiskForm, self).__init__(*args, **kwargs) for i in range(0,len(Program.objects.get(id=programid).char_set.all())): charid = Program.objects.get(id=programid).char_set.all()[i].id charlabel = Program.objects.get(id=programid).char_set.all()[i].label self.fields['char_field_%i' %i] = forms.ModelChoiceField(Char.objects.get(id=charid).cat_set.all(), label=charlabel) </code></pre>
2
2016-10-13T13:53:18Z
40,033,424
<p>To rephrase your question, are you asking how to pre-populate the form fields? If so consider using <a href="https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset" rel="nofollow">initial values in your formsets</a></p>
0
2016-10-14T01:12:14Z
[ "python", "django", "forms", "dynamic", "formset" ]
Elasticsearch profile api in python library
40,023,005
<p>Elasticsearch has a very useful feature called profile API. That is you can get very useful information on the queries performed. I am using the python elasticsearch library to perform the queries and want to be able to get those information back but I don't see anywhere in the docs that this is possible. Have you managed to do it someway?</p>
0
2016-10-13T13:54:10Z
40,023,342
<p>adding <code>profile="true"</code> to the body did the trick. In my opinion this should be an argument like size etc in the search method of the Elasticsearch class</p>
0
2016-10-13T14:08:03Z
[ "python", "elasticsearch", "profiler" ]
Pandas Split 9GB CSV into 2 5GB CSVs
40,023,026
<p>I have a 9GB CSV and need to split it into 2 5GB CSVs. I started out doing this:</p> <pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)): chunk.drop('Unnamed: 0',axis=1,inplace=True) chunk.to_csv('chunk{}.csv'.format(i),index=False) </code></pre> <p>What I need to do is somehow tell pandas to write the chunk to a CSV until that CSV reaches a size of 6,250,000,000 (or a filesize of 5GB) then start a new CSV file with the rest of the data (without starting again from the beginning of the data from the big CSV file).</p> <p>Can this be done?</p> <p>Thanks in advance!</p>
1
2016-10-13T13:54:59Z
40,023,552
<p>Give this a try. </p> <pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=312500)): if i&lt;11: chunk.to_csv(file_name, chunksize = 312500) else chunk.to_csv(file_name_2, chunksize = 312500) </code></pre>
0
2016-10-13T14:16:40Z
[ "python", "python-3.x", "csv", "pandas" ]
Pandas Split 9GB CSV into 2 5GB CSVs
40,023,026
<p>I have a 9GB CSV and need to split it into 2 5GB CSVs. I started out doing this:</p> <pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)): chunk.drop('Unnamed: 0',axis=1,inplace=True) chunk.to_csv('chunk{}.csv'.format(i),index=False) </code></pre> <p>What I need to do is somehow tell pandas to write the chunk to a CSV until that CSV reaches a size of 6,250,000,000 (or a filesize of 5GB) then start a new CSV file with the rest of the data (without starting again from the beginning of the data from the big CSV file).</p> <p>Can this be done?</p> <p>Thanks in advance!</p>
1
2016-10-13T13:54:59Z
40,023,556
<p>Library dask could be helpful. You can find documentation here: <a href="http://dask.pydata.org/en/latest/dataframe-create.html" rel="nofollow">http://dask.pydata.org/en/latest/dataframe-create.html</a></p>
1
2016-10-13T14:16:57Z
[ "python", "python-3.x", "csv", "pandas" ]
Pandas Split 9GB CSV into 2 5GB CSVs
40,023,026
<p>I have a 9GB CSV and need to split it into 2 5GB CSVs. I started out doing this:</p> <pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)): chunk.drop('Unnamed: 0',axis=1,inplace=True) chunk.to_csv('chunk{}.csv'.format(i),index=False) </code></pre> <p>What I need to do is somehow tell pandas to write the chunk to a CSV until that CSV reaches a size of 6,250,000,000 (or a filesize of 5GB) then start a new CSV file with the rest of the data (without starting again from the beginning of the data from the big CSV file).</p> <p>Can this be done?</p> <p>Thanks in advance!</p>
1
2016-10-13T13:54:59Z
40,023,798
<p>Solution is a little messy. But this should split the data based on the ~6 billion row threshold you mentioned. </p> <pre><code>import pandas as pd from __future__ import division numrows = 6250000000 #number of rows threshold to be 5 GB count = 0 #keep track of chunks chunkrows = 100000 #read 100k rows at a time df = pd.read_csv('csv_big_file2.csv', iterator=True, chunksize=chunkrows) for chunk in df: #for each 100k rows if count &lt;= numrows/chunkrows: #if 5GB threshold has not been reached outname = "csv_big_file2_1stHalf.csv" else: outname = "csv_big_file2_2ndHalf.csv" #append each output to same csv, using no header chunk.to_csv(outname, mode='a', header=None, index=None) count+=1 </code></pre>
1
2016-10-13T14:27:01Z
[ "python", "python-3.x", "csv", "pandas" ]
Making text shrink and expand enlessly in tkinter canvas
40,023,074
<p>Basically, I wanted to make a program that would create a text in the cavas with the size 1, rotate it by 180 degrees (continuosly) and while that expand it to its full size (let's say 50) than keep rotating it and by the time it has made a full it spin it would have shrunk down to 1 again and then repeat the process.</p> <p>This is the only think I've come up with and keep in mind I've been only messing around with Python for a week or two so the code will probably need to be completly changed.</p> <pre><code>from tkinter import * import time import random size=1 angl=0 i=0 canvas=Canvas(width=600, height=600) canvas.pack() while i&lt;180: canvas.delete("all") canvas.create_text(150,150, text="kappa123",angle=angl,font=("helvetica",size)) angl+=1 size+=1 i+=1 canvas.update() time.sleep(1/360) while i&gt;=180: canvas.delete("all") canvas.create_text(150,150, text="kappa123",angle=angl,font=("helvetica",size)) angl+=1 size-=1 i+=1 canvas.update() time.sleep(1/360) </code></pre> <p>As you can see, it only works once adn then expands forever.</p>
1
2016-10-13T13:56:57Z
40,030,003
<p>I believe it is because you aren't leaving the second loop. your i variable moves on into infinity. To see an example run this and look at the output:</p> <pre><code>from tkinter import * import time j = 0 # Time spent in the first while loop k = 0 # Time spent in the second while loop size = 1 angl = 0 i = 0 canvas = Canvas(width=600, height=600) canvas.pack() while i &lt; 180: canvas.delete("all") canvas.create_text(150, 150, text="kappa123", angle=angl, font=("helvetica", size)) angl += 1 size += 1 i += 1 j += 1 print('First loop', j) canvas.update() time.sleep(1 / 360) while i &gt;= 180: canvas.delete("all") canvas.create_text(150, 150, text="kappa123", angle=angl, font=("helvetica", size)) angl += 1 size -= 1 i += 1 k += 1 print('Second loop', k) canvas.update() time.sleep(1 / 360) </code></pre> <p>A good solution to your problem, depending on your skill and comfort level, would be to create two functions, one to grow and one to shrink. Use the grow function to go from 1 to 180, then call the shrink function when you have iterated through and shrink from 180 to 1.</p> <p><strong>Edit</strong></p> <pre><code>class Spinner(Canvas): def __init__(self, parent): self.size = 1 # Other data self.pack() def expand(self): for i in range(0, 181): self.angl += 1 # increment size, update, sleep self.shrink() def shrink(self): for i in range(0, 181): # increment angle, decrease size, update, sleep self.expand() root = Tk() canvas = Spinner(root) root.mainloop() </code></pre>
0
2016-10-13T20:06:13Z
[ "python", "canvas", "tkinter", "tkinter-canvas" ]
How to define multidimensional dictionary with default value in python?
40,023,106
<p>I would like to modify next dict definition:</p> <pre><code>class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value </code></pre> <p>To be able to use it in next way:</p> <pre><code>totals[year][month] += amount </code></pre>
0
2016-10-13T13:57:57Z
40,023,158
<p>Use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> with <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>. </p> <pre><code>from collections import defaultdict, Counter d = defaultdict(Counter) d['year']['month'] += 1 </code></pre>
1
2016-10-13T14:00:26Z
[ "python", "dictionary", "autovivification" ]
How to define multidimensional dictionary with default value in python?
40,023,106
<p>I would like to modify next dict definition:</p> <pre><code>class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value </code></pre> <p>To be able to use it in next way:</p> <pre><code>totals[year][month] += amount </code></pre>
0
2016-10-13T13:57:57Z
40,103,773
<p>At the end I have used Counter with tuple as a key.</p>
0
2016-10-18T08:55:37Z
[ "python", "dictionary", "autovivification" ]
read data from a huge CSV file efficiently
40,023,133
<p>I was trying to process my huge CSV file (more than 20G), but the process was killed when reading the whole CSV file into memory. To avoid this issue, I am trying to read the second column line by line. </p> <p>For example, the 2nd column contains data like</p> <ol> <li>xxx, computer is good</li> <li><p>xxx, build algorithm</p> <pre><code>import collections wordcount = collections.Counter() with open('desc.csv', 'rb') as infile: for line in infile: wordcount.update(line.split()) </code></pre></li> </ol> <p>My code is working for the whole columns, how to only read the second column without using CSV reader?</p>
0
2016-10-13T13:59:25Z
40,049,578
<p>As far as I know, calling <code>csv.reader(infile)</code> opens and reads the whole file...which is where your problem lies.</p> <p>You can just read line-by-line and parse manually: </p> <pre><code>X=[] with open('desc.csv', 'r') as infile: for line in infile: # Split on comma first cols = [x.strip() for x in line.split(',')] # Grab 2nd "column" col2 = cols[1] # Split on spaces words = [x.strip() for x in col2.split(' ')] for word in words: if word not in X: X.append(word) for w in X: print w </code></pre> <p>That will keep a smaller chunk of the file in memory at a given time (one line). However, you may still potentially have problems with variable <code>X</code> increasing to quite a large size, such that the program will error out due to memory limits. Depends how many unique words are in your "vocabulary" list</p>
0
2016-10-14T18:11:48Z
[ "python", "csv" ]
How to pass arguments to python script similar to MATLAB function script?
40,023,143
<p>I have a python script that implements several functions, but I want to be flexible in terms of which functions I use every time. When I would run the Python Script I would want to pass some arguments that would stand as "flags" for executing my functions.</p> <p>In MATLAB would look something like this:</p> <pre><code>function metrics( Min, Max ) %UNTITLED Summary of this function goes here % Detailed explanation goes here x = [1,2,3,4,5,5]; if (Min==1) min(x) else disp('something') end if (Max==1) max(x) else disp('else') end end </code></pre> <p>Which I call from command window with (for example):</p> <pre><code>metrics(1,0) </code></pre> <p>In <strong>Python</strong> I tried using </p> <blockquote> <p>def metrics(min, max)</p> <p>argparse()</p> </blockquote> <p>and</p> <blockquote> <p>os.system("metrics.py 1,1")</p> </blockquote> <p>Any suggestion how to transpose the MATLAB function calling in the <strong>Python Shell</strong> (I am using Anaconda's Spyder for the matter)?</p>
0
2016-10-13T13:59:47Z
40,023,965
<p>You can use the results directly just like you do in MATLAB. The argument parsing stuff is for calling python scripts from the system command prompt or shell, not from the Python shell. So have a script file like <code>myscript.py</code>:</p> <pre><code>def metrics(minval, maxval): """UNTITLED Summary of this function goes here Detailed explanation goes here. """ x = [1, 2, 3, 4, 5, 5] if minval: print(min(x)) else: print('something') if maxval: print(max(x)) else: print('else') </code></pre> <p>Then, from the python or ipython shell, do:</p> <pre><code>&gt;&gt;&gt; from myscript import metrics &gt;&gt;&gt; metrics(1, 0) </code></pre> <p>Although typically in Python you would use <code>True</code> and <code>False</code>. Also, I changed the argument names since they are too easy to confuse with builtins, and in Python you don't need the <code>== 1</code>. Also, Python supports default arguments, so you could do something like this:</p> <pre><code>def metrics(minval=False, maxval=False): """UNTITLED Summary of this function goes here Detailed explanation goes here. """ x = [1, 2, 3, 4, 5, 5] if minval: print(min(x)) else: print('something') if maxval: print(max(x)) else: print('else') </code></pre> <p>then:</p> <pre><code>&gt;&gt;&gt; from myscript import metrics &gt;&gt;&gt; matrics(True) &gt;&gt;&gt; metrics(maxval=True) </code></pre> <p>Also, Python supports something called ternary expressions, which are basically <code>if...else</code> expressions. So this:</p> <pre><code> if maxval: print(max(x)) else: print('else') </code></pre> <p>Could be written as:</p> <pre><code> print(max(x) if maxval else 'else') </code></pre>
3
2016-10-13T14:33:56Z
[ "python", "matlab", "function" ]
Prints output twice when reading a file
40,023,319
<p>I have written the following code to write a file, convert it into integer values, save that file and then read and convert it back to the original string. However, it prints the output twice.</p> <p>My code is</p> <pre><code>def write(): sentence=input('What is your Statement?:') name=input('Name your file:') sentence=sentence.lower() words=sentence.split(' ') file_register=set() F_output=[] position=[] for i in words: if i not in file_register: F_output.append(i) file_register.add(i) for x in words: for y in range(len(F_output)): if x==F_output[y]: position.append(y) name+='.txt' with open(str(name),'w') as f: f.write(str(len(position)) + '\n') for c in range(len(position)): f.write(str(position[c]) + '\n') f.write(str(len(F_output)) + '\n') for d in range(len(F_output)): f.write(str(F_output[d] + '\n')) f.close global name global position def read1(): savefile=[] output=('') with open(name,'r') as file_open: num=int(file_open.readline()) while num!=0: a1=file_open.readline() a1_split=a1.split('\n') position.append(int(a1_split[0])) num-=1 file_integer=int(file_open.readline()) while file_integer!=0: word_s=file_open.readline() word_split=word_s.split() savefile.append(word_split) file_integer-=1 for n in range(len(position)): a=position[n] output+=str(savefile[a])+('') global output write() read1() print('Your file is: '+output) </code></pre> <p>I have tried searching, but I cannot find an answer for it. I am fairly new to Python and any help is appreciated.</p>
-1
2016-10-13T14:06:56Z
40,024,335
<p>In <code>write()</code>, you declare <code>position</code> as global. In <code>read1()</code>, you don't declare it as global, but since you never create a local <code>position</code> variable it's the global one that gets used. So you end up populating it twice: once in <code>write()</code> then once again in <code>read1()</code>.</p> <p>To make a long story short: dont use globals. You don't need them. </p> <p>Also, you'd find your code way easier to read, understand and debug by 1/ using better naming, 2/ writing simple, short functions that do one single thing, works on their inputs (arguments) and return values (the same arguments should produce the same output values), and 3/ properly using python's <code>for</code> loop.</p> <p>Here's an example of what your code could looks like following those rules:</p> <pre><code>def parse(sentence): sentence=sentence.lower() words=sentence.split(' ') register=set() output = [] positions = [] for word in words: if word not in register: output.append(word) register.add(word) for word in words: for index in range(len(output)): if word == output[index]: positions.append(index) return output, positions def write(path, output, positions): with open(path, 'w') as f: f.write(str(len(positions)) + '\n') for index in positions: f.write(str(index) + '\n') f.write(str(len(output)) + '\n') for word in output: f.write(word + '\n') def read(path): words = [] positions = [] with open(path, 'r') as f: poscount = int(f.readline().strip()) while poscount: line = f.readline().strip() pos = int(line) positions.append(pos) poscount -= 1 wordcount = int(f.readline().strip()) while wordcount: line = f.readline() word = line.strip() words.append(word) wordcount -= 1 output = [] for index in positions: word = words[index] output.append(word) return output, positions def main(): sentence = input('What is your Statement?:') path = input('Name your file:') if not path.endswith(".txt"): path +=".txt" source_out, source_positions = parse(sentence) write(path, source_out, source_positions) read_out, read_positions = read(path) print("your file is: {}".format(read_out)) if __name__ == "__main__": main() </code></pre> <p>This code is still overly complicated IMHO but at least it's mostly readable, doesn't use any global, and should be easier to test.</p>
0
2016-10-13T14:49:49Z
[ "python" ]
How to create new string column extracting integers from a timestamp in Spark?
40,023,381
<p>I have a spark dataframe with a timestamp column, I want a new column which has strings in the format "YYYYMM".</p> <p>I tried with: </p> <pre><code>df.withColumn('year_month',year(col("timestamp")).cast("string")+month(col("timestamp")).cast("string")) </code></pre> <p>But if my timestamp is 2016-10-12, it returns as 2020 as YYYYMM.</p>
0
2016-10-13T14:09:49Z
40,023,591
<p>You can use <code>date_format</code>:</p> <pre><code>from pyspark.sql.functions import date_format df.withColumn('year_month', date_format('timestamp', 'yyyyMM')) </code></pre>
0
2016-10-13T14:18:28Z
[ "python", "apache-spark", "pyspark", "spark-dataframe", "pyspark-sql" ]
Cannot open filename that has umlaute in python 2.7 & django 1.9
40,023,476
<p>I am trying doing a thing that goes through every file in a directory, but it crashes every time it meets a file that has an umlaute in the name. Like ä.txt</p> <p>the shortened code:</p> <pre><code>import codecs import os for filename in os.listdir(WATCH_DIRECTORY): with codecs.open(filename, 'rb', 'utf-8') as rawdata: data = rawdata.readline() # ... </code></pre> <p>And then I get this:</p> <pre><code>IOError: [Errno 2] No such file or directory: '\xc3\xa4.txt' </code></pre> <p>I've tried to encode/decode the filename variable with .encode('utf-8'), .decode('utf-8') and both combined. This usually leads to "ascii cannot decode blah blah"</p> <p>I also tried unicode(filename) with and without encode/decode.</p> <p>Soooo, kinda stuck here :)</p>
1
2016-10-13T14:13:50Z
40,023,571
<p>You are opening a <em>relative directory</em>, you need to make them absolute.</p> <p>This has nothing really to do with encodings; both Unicode strings and byte strings will work, especially when soured from <code>os.listdir()</code>.</p> <p>However, <code>os.listdir()</code> produces just the base filename, not a path, so add that back in:</p> <pre><code>for filename in os.listdir(WATCH_DIRECTORY): fullpath = os.path.join(WATCH_DIRECTORY, filename) with codecs.open(fullpath, 'rb', 'utf-8') as rawdata: </code></pre> <p>By the way, I recommend you use the <a href="https://docs.python.org/2/library/io.html#io.open" rel="nofollow"><code>io.open()</code> function</a> rather than <code>codecs.open()</code>. The <code>io</code> module is the new Python 3 I/O framework, and is a lot more robust than the older <code>codecs</code> module.</p>
4
2016-10-13T14:17:37Z
[ "python", "django", "python-2.7", "encoding", "utf-8" ]
Pulling specific string with lxml?
40,023,568
<p>I have the html: </p> <pre><code>&lt;div title="" data-toggle="tooltip" data-template=" &lt;div class=&amp;quot;tooltip infowin-tooltip&amp;quot; role=&amp;quot;tooltip&amp;quot;&gt; &lt;div class=&amp;quot;tooltip-arrow&amp;quot;&gt; &lt;div class=&amp;quot;tooltip-arrow-inner&amp;quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&amp;quot;tooltip-inner&amp;quot; style=&amp;quot;text-align: left&amp;quot;&gt; &lt;/div&gt; &lt;/div&gt;" data-html="true" data-placement="top" data-container=".snippet-container" class="font-160 line-110 text-default text-light" data-original-title="HOUSTON [US]"&gt; &lt;ahref="/en/ais/details/ports/919" class="no-underline group-ib color-inherit"&gt;USHOU&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I want to pull "HOUSTON [US]" from it using <code>lxml</code>. With <code>BeautifulSoup</code> I could do </p> <p><code>soup.find("div", class_='font-160 line-110')["title"]</code> </p> <p>is there anything similar in <code>lxml</code>? I tried </p> <pre><code>parsed_body.xpath('.//div[@class="font-160 line-110 text-default text-light")["title"]')[0].text </code></pre> <p>But this returns blank. </p>
0
2016-10-13T14:17:33Z
40,023,860
<p>You can use the XPath:</p> <pre><code>//div[@class="font-160 line-110 text-default text-light"]/@data-original-title </code></pre> <p>in XPath, square brackets represent predicates. Predicates filter <em>which</em> nodes are returned without affecting <em>what</em> is returned. i.e. so your example would return the <code>div</code> element itself.</p> <p>To get the value of an attribute you need to use a path separator (<code>/</code>) followed by an <code>@</code> symbol, and the attribute name. The <a class='doc-link' href="http://stackoverflow.com/documentation/xpath/6171/location-paths-and-axes/21420/traversing-attribute-and-namespace-nodes#t=2016101314282746108">documentation</a> hints at this, while showing that <code>@</code> is a shortcut for the <code>attribute</code> axis.</p>
1
2016-10-13T14:29:53Z
[ "python", "python-3.x", "lxml" ]
Pulling specific string with lxml?
40,023,568
<p>I have the html: </p> <pre><code>&lt;div title="" data-toggle="tooltip" data-template=" &lt;div class=&amp;quot;tooltip infowin-tooltip&amp;quot; role=&amp;quot;tooltip&amp;quot;&gt; &lt;div class=&amp;quot;tooltip-arrow&amp;quot;&gt; &lt;div class=&amp;quot;tooltip-arrow-inner&amp;quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&amp;quot;tooltip-inner&amp;quot; style=&amp;quot;text-align: left&amp;quot;&gt; &lt;/div&gt; &lt;/div&gt;" data-html="true" data-placement="top" data-container=".snippet-container" class="font-160 line-110 text-default text-light" data-original-title="HOUSTON [US]"&gt; &lt;ahref="/en/ais/details/ports/919" class="no-underline group-ib color-inherit"&gt;USHOU&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I want to pull "HOUSTON [US]" from it using <code>lxml</code>. With <code>BeautifulSoup</code> I could do </p> <p><code>soup.find("div", class_='font-160 line-110')["title"]</code> </p> <p>is there anything similar in <code>lxml</code>? I tried </p> <pre><code>parsed_body.xpath('.//div[@class="font-160 line-110 text-default text-light")["title"]')[0].text </code></pre> <p>But this returns blank. </p>
0
2016-10-13T14:17:33Z
40,140,074
<p>I ended up using <code>//div/@title[0]</code> which pulls the desired text.</p>
0
2016-10-19T19:34:37Z
[ "python", "python-3.x", "lxml" ]
Tkinter - columnspan doesn't seem to affect Message
40,023,572
<p>I've trying to create a simple interface in Python (2.7) with Tkinter featuring a user-input box, browse button and description on the first row and a multi-line explanation spanning their width on the line below. </p> <p>My issue is that the <code>columnspan</code> option doesn't seem to allow my <code>Message</code> widget to span the width of the three columns above, as can be seen below:</p> <p><a href="https://i.stack.imgur.com/Cqa97.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/Cqa97.jpg" alt="Non-spanning message box"></a></p> <p>How can I get this <code>Message</code> to span the entire width? I've additionally tried using the <code>width</code> parameter but this seems to be of a different scale to that for the <code>Entry</code> widget.</p> <p>My code is as follows:</p> <pre><code>from Tkinter import * class App(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.grid(sticky=N + W + E + S) # set up labels and buttons self.folder_text = Label( self, text='Select Folder: ', font='Arial 10', anchor=W ) self.folder_text.grid(row=0, column=0, sticky=W) self.input_folder = Entry( self, width=40, font='Arial 10' ) self.input_folder.grid(row=0, column=1) self.browse_button = Button( self, text="Browse", font='Arial 8 bold', command=lambda: self.browse_for_folder(self.input_folder) ) self.browse_button.grid(row=0, column=2) self.desc = Message( self, text='This tool will create a .csv file in the specified folder containing the Time and ' 'Latitude/Longitude (WGS84) for all TIFF, RAW and JPEG/JPG files contained in the ' 'folder with this information available.', font='Arial 8', anchor=W ) self.desc.grid(row=1, column=0, columnspan=3, sticky=E + W) self.run_button = Button( self, text="Run!", font='Arial 10 bold', fg='red', command=lambda: self.run(self.input_folder) ) self.run_button.grid(row=2, column=1) # ---SNIP--- root = Tk() root.bind('&lt;Escape&gt;', lambda e: root.destroy()) root.resizable(0, 0) root.title('Get photo geolocations') app = App(root) root.mainloop() </code></pre>
0
2016-10-13T14:17:38Z
40,024,033
<p>The <code>Message</code> uses an aspect ratio or a character width to determine its size.</p> <p>You can give it a width and then it will work:</p> <pre><code> self.desc = Message( self, text='This tool will create a .csv file in the specified folder containing the Time and ' 'Latitude/Longitude (WGS84) for all TIFF, RAW and JPEG/JPG files contained in the ' 'folder with this information available.', font='Arial 8', anchor=W, width = 400 ) </code></pre> <p><a href="https://i.stack.imgur.com/rUcdX.png" rel="nofollow"><img src="https://i.stack.imgur.com/rUcdX.png" alt="enter image description here"></a></p> <p>Alternatively, you can render the window, read out its width with <code>root.geometry()</code>, set the width on the widget, then set the text into it.</p>
1
2016-10-13T14:37:09Z
[ "python", "tkinter" ]
Tkinter - columnspan doesn't seem to affect Message
40,023,572
<p>I've trying to create a simple interface in Python (2.7) with Tkinter featuring a user-input box, browse button and description on the first row and a multi-line explanation spanning their width on the line below. </p> <p>My issue is that the <code>columnspan</code> option doesn't seem to allow my <code>Message</code> widget to span the width of the three columns above, as can be seen below:</p> <p><a href="https://i.stack.imgur.com/Cqa97.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/Cqa97.jpg" alt="Non-spanning message box"></a></p> <p>How can I get this <code>Message</code> to span the entire width? I've additionally tried using the <code>width</code> parameter but this seems to be of a different scale to that for the <code>Entry</code> widget.</p> <p>My code is as follows:</p> <pre><code>from Tkinter import * class App(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.grid(sticky=N + W + E + S) # set up labels and buttons self.folder_text = Label( self, text='Select Folder: ', font='Arial 10', anchor=W ) self.folder_text.grid(row=0, column=0, sticky=W) self.input_folder = Entry( self, width=40, font='Arial 10' ) self.input_folder.grid(row=0, column=1) self.browse_button = Button( self, text="Browse", font='Arial 8 bold', command=lambda: self.browse_for_folder(self.input_folder) ) self.browse_button.grid(row=0, column=2) self.desc = Message( self, text='This tool will create a .csv file in the specified folder containing the Time and ' 'Latitude/Longitude (WGS84) for all TIFF, RAW and JPEG/JPG files contained in the ' 'folder with this information available.', font='Arial 8', anchor=W ) self.desc.grid(row=1, column=0, columnspan=3, sticky=E + W) self.run_button = Button( self, text="Run!", font='Arial 10 bold', fg='red', command=lambda: self.run(self.input_folder) ) self.run_button.grid(row=2, column=1) # ---SNIP--- root = Tk() root.bind('&lt;Escape&gt;', lambda e: root.destroy()) root.resizable(0, 0) root.title('Get photo geolocations') app = App(root) root.mainloop() </code></pre>
0
2016-10-13T14:17:38Z
40,024,049
<p>If you change the background color of the widget you will see that it does indeed span multiple columns. </p> <p>The main feature of the <code>Message</code> widget is that it will insert linebreaks in the text so that the text maintains a specific aspect ratio if a width is not specified. The text of a <code>Message</code> window will not fill extra horizontal space if the widget is made wider than its natural size.</p> <p>The aspect ratio is ignored if you specify the width. Unlike the <code>Label</code> where the width refers to the number of characters, the <code>width</code> option of a <code>Message</code> is pixel-based (or distance: inches, centimeters, millimeters, or printer points). </p> <p>A simple way to use the <code>width</code> option is to bind to the <code>&lt;Configure&gt;</code> event of the widget, and set the width option to be the actual width of the widget (or the width minus a little for a margin)</p> <p>For example:</p> <pre><code>self.desc.bind("&lt;Configure&gt;", lambda event: event.widget.configure(width=event.width-8)) </code></pre>
1
2016-10-13T14:37:49Z
[ "python", "tkinter" ]
How to catch Cntrl + C in a shell script which runs a Python script
40,023,581
<p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p> <pre><code>#!/bin/bash rm archived_sensor_data.json python rethinkdb_monitor_batch.py trap "gedit archived_sensor_data.json" 2 </code></pre> <p>The Python script <code>rethinkdb_monitor_batch.py</code> runs indefinitely and writes (in append-only mode) to the file <code>archived_sensor_data.json</code>. In order to start on a 'clean slate' every time, I'd like to delete the file every time before running. Then after I interrupt the execution with Cntrl + C, I'd like to automatically trigger an opening of the file using Gedit.</p> <p>The problem is that when I press Cntrl+C, it doesn't seem to open Gedit automatically. Is <code>2</code> not the right exit code to use here?</p>
0
2016-10-13T14:17:53Z
40,023,883
<pre> import signal import os os.system("rm archived_sensor_data.json") def signal_handler(signal, frame): print('You pressed Ctrl+C!') os.system("gedit archived_sensor_data.json") signal.signal(signal.SIGINT, signal_handler) #your remaining code #must be placed here </pre> <p><br><br></p> <p>Just run your code using following command<br><br> $ python rethinkdb_monitor_batch.py <br><br> This must solve your problem <br>Read signal handler for more information</p>
0
2016-10-13T14:30:52Z
[ "python", "shell" ]
How to catch Cntrl + C in a shell script which runs a Python script
40,023,581
<p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p> <pre><code>#!/bin/bash rm archived_sensor_data.json python rethinkdb_monitor_batch.py trap "gedit archived_sensor_data.json" 2 </code></pre> <p>The Python script <code>rethinkdb_monitor_batch.py</code> runs indefinitely and writes (in append-only mode) to the file <code>archived_sensor_data.json</code>. In order to start on a 'clean slate' every time, I'd like to delete the file every time before running. Then after I interrupt the execution with Cntrl + C, I'd like to automatically trigger an opening of the file using Gedit.</p> <p>The problem is that when I press Cntrl+C, it doesn't seem to open Gedit automatically. Is <code>2</code> not the right exit code to use here?</p>
0
2016-10-13T14:17:53Z
40,024,168
<p>You could do this by capturing the signal inside <code>rethinkdb_monitor_batch.py</code> as follows:</p> <pre><code>#!/usr/env/bin python try: # your existing code here---let's assume it does the following: import time outfile = open( "archived_sensor_data.json", "wt" ) # NB: this already does the job of erasing previous content while True: outfile.write( "There's a horse in aisle five.\n" ) time.sleep( 1 ) outfile.write( "My house is full of traps.\n" ) time.sleep( 1 ) except KeyboardInterrupt: print( "You pressed Ctrl-C" ) </code></pre> <p>...and the wrapper script would then simply be:</p> <pre><code>#!/bin/bash python rethinkdb_monitor_batch.py gedit archived_sensor_data.json </code></pre> <p>But really, why bother with the wrapper, when you could do it all in the Python, replacing the final <code>print()</code> call as follows:</p> <pre><code>except KeyboardInterrupt: os.execlp("gedit", "archived_sensor_data.json") </code></pre> <p>...and then just call the Python script directly from the command-line.</p>
2
2016-10-13T14:43:33Z
[ "python", "shell" ]
How to catch Cntrl + C in a shell script which runs a Python script
40,023,581
<p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p> <pre><code>#!/bin/bash rm archived_sensor_data.json python rethinkdb_monitor_batch.py trap "gedit archived_sensor_data.json" 2 </code></pre> <p>The Python script <code>rethinkdb_monitor_batch.py</code> runs indefinitely and writes (in append-only mode) to the file <code>archived_sensor_data.json</code>. In order to start on a 'clean slate' every time, I'd like to delete the file every time before running. Then after I interrupt the execution with Cntrl + C, I'd like to automatically trigger an opening of the file using Gedit.</p> <p>The problem is that when I press Cntrl+C, it doesn't seem to open Gedit automatically. Is <code>2</code> not the right exit code to use here?</p>
0
2016-10-13T14:17:53Z
40,128,072
<p>The other answers involve modifying the Python code itself, which is less than ideal since I don't want it to contain code related only to the testing. Instead, I found that the following bash script useful:</p> <pre><code>#!/bin/bash rm archived_sensor_data.json python rethinkdb_monitor_batch.py ; gedit archived_sensor_data.json </code></pre> <p>This will run the <code>gedit archived_sensor_data.json</code> command after <code>python rethinkdb_monitor_batch.py</code> is finished, regardless of whether it exited successfully.</p>
0
2016-10-19T09:59:44Z
[ "python", "shell" ]
Detect the changes in a file and write them in a file
40,023,651
<p>I produced a script that detects the changes on files that are located in a specific directory. I'm trying to write all these changes to a <code>changes.txt</code> file. For this purpose I'm using the <code>sys.stdout = open('changes.txt','w')</code> instruction.</p> <p>The problem is that whenever I run the script and change a file in the directory and save it, an empty file called <code>changes.txt</code> is created. This file is never written!</p> <pre><code>#!/usr/bin/python import time import sys from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler sys.stdout = open('changes.txt','w') class MyHandler(FileSystemEventHandler): def on_modified(self, event): print "something happened!" if __name__ == "__main__": event_handler = MyHandler() observer = Observer() observer.schedule(event_handler, path='.', recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() </code></pre>
0
2016-10-13T14:20:46Z
40,023,827
<p>I'd recommend something like</p> <pre><code>#!/usr/bin/python import time import sys from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MyHandler(FileSystemEventHandler): def __init__(self, f): self.f = f def on_modified(self, event): self.f.write("something happened!\n") self.f.flush() if __name__ == "__main__": with open('changes.txt','w') as f: event_handler = MyHandler(f) observer = Observer() observer.schedule(event_handler, path='.', recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() </code></pre> <p>as you can see, the control over where your outputwill be written to has been handed to the caller (the one instanciating <code>MyHandler</code>) instead of the callee (<code>on_modified</code>).</p> <p>This means you can also do</p> <pre><code>event_handler = MyHandler(sys.stdout) </code></pre> <p>and see the output instead of the output being put into the file.</p> <p>An additional benefit: using a context manager you can be sure the file is closed properly, even if errors occurr.</p>
0
2016-10-13T14:28:15Z
[ "python", "file" ]
Python: good way to pass variable to multiple function calls
40,023,663
<p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p> <pre><code>def cmd_exec(cmd): if isDebug: commandStart = datetime.datetime.now() print commandStart print cmd ... ... exucuting commands ... if isDebug: print datetime.datetime.now() - command_start return def main(): ... if args.debug: isDebug = True ... cmd_exec(cmd1) ... cmd_exec(cmd2) ... </code></pre> <p>How can isDebug variable be simply passed to functions? Should I use "global isDebug"? </p> <p>Because </p> <pre><code> ... cmd_exec(cmd1, isDebug) ... cmd_exec(cmd2, isDebug) ... </code></pre> <p>looks pretty bad. Please help me find more elegant way.</p>
3
2016-10-13T14:21:31Z
40,023,778
<p><code>isDebug</code> is state that applies to the application of a function <code>cmd_exec</code>. Sounds like a use-case for a class to me.</p> <pre><code>class CommandExecutor(object): def __init__(self, debug): self.debug = debug def execute(self, cmd): if self.debug: commandStart = datetime.datetime.now() print commandStart print cmd ... ... executing commands ... if self.debug: print datetime.datetime.now() - command_start def main(args): ce = CommandExecutor(args.debug) ce.execute(cmd1) ce.execute(cmd2) </code></pre>
2
2016-10-13T14:26:08Z
[ "python", "function", "arguments", "global-variables" ]
Python: good way to pass variable to multiple function calls
40,023,663
<p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p> <pre><code>def cmd_exec(cmd): if isDebug: commandStart = datetime.datetime.now() print commandStart print cmd ... ... exucuting commands ... if isDebug: print datetime.datetime.now() - command_start return def main(): ... if args.debug: isDebug = True ... cmd_exec(cmd1) ... cmd_exec(cmd2) ... </code></pre> <p>How can isDebug variable be simply passed to functions? Should I use "global isDebug"? </p> <p>Because </p> <pre><code> ... cmd_exec(cmd1, isDebug) ... cmd_exec(cmd2, isDebug) ... </code></pre> <p>looks pretty bad. Please help me find more elegant way.</p>
3
2016-10-13T14:21:31Z
40,023,830
<p>Python has a built-in <code>__debug__</code> variable that could be useful.</p> <pre><code>if __debug__: print 'information...' </code></pre> <p>When you run your program as <code>python test.py</code>, <code>__debug__</code> is <code>True</code>. If you run it as <code>python -O test.py</code>, it will be <code>False</code>.</p> <p>Another option which I do in my projects is set a global <code>DEBUG</code> var at the beginning of the file, after importing:</p> <pre><code>DEBUG = True </code></pre> <p>You can then reference this <code>DEBUG</code> var in the scope of the function.</p>
2
2016-10-13T14:28:17Z
[ "python", "function", "arguments", "global-variables" ]
Python: good way to pass variable to multiple function calls
40,023,663
<p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p> <pre><code>def cmd_exec(cmd): if isDebug: commandStart = datetime.datetime.now() print commandStart print cmd ... ... exucuting commands ... if isDebug: print datetime.datetime.now() - command_start return def main(): ... if args.debug: isDebug = True ... cmd_exec(cmd1) ... cmd_exec(cmd2) ... </code></pre> <p>How can isDebug variable be simply passed to functions? Should I use "global isDebug"? </p> <p>Because </p> <pre><code> ... cmd_exec(cmd1, isDebug) ... cmd_exec(cmd2, isDebug) ... </code></pre> <p>looks pretty bad. Please help me find more elegant way.</p>
3
2016-10-13T14:21:31Z
40,024,533
<p>You can use a module to create variables that are shared. This is better than a global because it only affects code that is specifically looking for the variable, it doesn't pollute the global namespace. It also lets you define something without your main module needing to know about it.</p> <p>This works because modules are shared objects in Python. Every <code>import</code> gets back a reference to the same object, and modifications to the contents of that module get shared immediately, just like a global would.</p> <p>my_debug.py:</p> <pre><code>isDebug = false </code></pre> <p>main.py:</p> <pre><code>import my_debug def cmd_exec(cmd): if my_debug.isDebug: # ... def main(): # ... if args.debug: my_debug.isDebug = True </code></pre>
1
2016-10-13T14:59:36Z
[ "python", "function", "arguments", "global-variables" ]
Python: good way to pass variable to multiple function calls
40,023,663
<p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p> <pre><code>def cmd_exec(cmd): if isDebug: commandStart = datetime.datetime.now() print commandStart print cmd ... ... exucuting commands ... if isDebug: print datetime.datetime.now() - command_start return def main(): ... if args.debug: isDebug = True ... cmd_exec(cmd1) ... cmd_exec(cmd2) ... </code></pre> <p>How can isDebug variable be simply passed to functions? Should I use "global isDebug"? </p> <p>Because </p> <pre><code> ... cmd_exec(cmd1, isDebug) ... cmd_exec(cmd2, isDebug) ... </code></pre> <p>looks pretty bad. Please help me find more elegant way.</p>
3
2016-10-13T14:21:31Z
40,032,915
<p>Specifically for this, I would use partials/currying, basically pre-filling a variable.</p> <pre><code>import sys from functools import partial import datetime def _cmd_exec(cmd, isDebug=False): if isDebug: command_start = datetime.datetime.now() print command_start print cmd else: print 'isDebug is false' + cmd if isDebug: print datetime.datetime.now() - command_start return #default, keeping it as is... cmd_exec = _cmd_exec #switch to debug def debug_on(): global cmd_exec #pre-apply the isDebug optional param cmd_exec = partial(_cmd_exec, isDebug=True) def main(): if "-d" in sys.argv: debug_on() cmd_exec("cmd1") cmd_exec("cmd2") main() </code></pre> <p>In this case, I check for <code>-d</code> on the command line to turn on debug mode and I do pre-populate isDebug on the function call by creating a new function with <code>isDebug = True</code>.</p> <p>I think even other modules will see this modified cmd_exec, because I replaced the function at the module level.</p> <p>output:</p> <p><strong>jluc@explore$ py test_so64.py</strong><br> <code>isDebug is falsecmd1 isDebug is falsecmd2</code></p> <p><strong>jluc@explore$ py test_so64.py -d</strong><br> <code>2016-10-13 17:00:33.523016 cmd1 0:00:00.000682 2016-10-13 17:00:33.523715 cmd2 0:00:00.000009</code></p>
0
2016-10-14T00:02:17Z
[ "python", "function", "arguments", "global-variables" ]
Trying to map the 'Private IP' of my computer with python
40,023,678
<p>I want to filter the IPv4 ips and take the one which belong to my LAN (and not to my VMware network). I coded this thing:</p> <pre><code>print re.findall(r'[0-255]\.[0-255]\.[0-255]\.[0-255]', str([y for y in filter(lambda x: 'IPv4 Address' in x, os.popen("ipconfig").readlines())])) </code></pre> <p>This part:</p> <pre><code>str([y for y in filter(lambda x: 'IPv4 Address' in x, os.popen("ipconfig").readlines())]) </code></pre> <p>Its for getting first the ips I have (At least the row they are in.) So for example, just this row, will give me:</p> <blockquote> <p>[' IPv4 Address. . . . . . . . . . . : 192.168.231.1\n', ' IPv4 Address. . . . . . . . . . . : 192.168.233.1\n', ' IPv4 Address. . . . . . . . . . . : 10.100.102.8\n']</p> </blockquote> <p>(The first two are of the VMware)</p> <p>When I do the Regex thing, it isnt working. Its intended to give me just the ips from the string I gave it.</p> <p>How can I filter the only LAN ip ('10.100.102.8' in this case.) and insert it to a string?</p>
0
2016-10-13T14:22:07Z
40,023,819
<p>Watch out! <code>[0-255]</code> isn't a number range in regex ! (in fact it means <em>one</em> character in the list 0,1,2,5)</p> <p>You should use <code>\d{1,3}</code> if you want a three digit number, then extract groups if you want to check if the number is in the range.</p>
0
2016-10-13T14:27:58Z
[ "python" ]
Django url config with multiple urls matching
40,023,708
<p>in one of our Django applications we have defined multiple urls for views.</p> <p>The first URL matches a general feature with pk and a second match group. The second URL matches a subfeature with pk.</p> <p>Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, the subfeature would have its own url.py.</p> <pre><code># old urls.py url(r'^(?P&lt;pk&gt;\d+)/', views.b), url(r'^subfeature/', views.a), </code></pre> <p>After some time letters are also allowed in pk, so we now have to change <strong>\d+</strong> to <strong>[^/]+</strong>.</p> <pre><code># new urls.py url(r'^(?P&lt;pk&gt;[^/]+)/', views.b), url(r'^subfeature/', views.a), </code></pre> <p>Now the subfeature breaks because the url is not correctly matched, 'subfeature' is matched as <strong>pk</strong> in the first url.</p> <p>How to avoid breaking other urls when changing a url regex?</p>
0
2016-10-13T14:23:05Z
40,023,810
<p>There's no general answer to that. Any change that makes an url more generic may break other urls that follow it.</p> <p>In this case, you can swap the urls so <code>subfeature/</code> will match the subfeature url, and any other url will fall through and match <code>views.b</code>:</p> <pre><code>url(r'^subfeature/', views.a), url(r'^(?P&lt;pk&gt;[^/]+)/', views.b), </code></pre>
1
2016-10-13T14:27:36Z
[ "python", "django" ]
Django url config with multiple urls matching
40,023,708
<p>in one of our Django applications we have defined multiple urls for views.</p> <p>The first URL matches a general feature with pk and a second match group. The second URL matches a subfeature with pk.</p> <p>Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, the subfeature would have its own url.py.</p> <pre><code># old urls.py url(r'^(?P&lt;pk&gt;\d+)/', views.b), url(r'^subfeature/', views.a), </code></pre> <p>After some time letters are also allowed in pk, so we now have to change <strong>\d+</strong> to <strong>[^/]+</strong>.</p> <pre><code># new urls.py url(r'^(?P&lt;pk&gt;[^/]+)/', views.b), url(r'^subfeature/', views.a), </code></pre> <p>Now the subfeature breaks because the url is not correctly matched, 'subfeature' is matched as <strong>pk</strong> in the first url.</p> <p>How to avoid breaking other urls when changing a url regex?</p>
0
2016-10-13T14:23:05Z
40,031,853
<p>As a general rule, you need to take the order into consideration when defining urlpatterns.</p> <p>The thing is django will try to find the match by trying to fit a url into every pattern and will try to get to the views whenever it finds the first url matching.</p> <pre><code>url(r'^(?P&lt;pk&gt;[^/]+)/', views.b), url(r'^subfeature/', views.a), </code></pre> <p>Here, it will first match the url with the first pattern where there is a variable initially and will try to put "subfeature" as pk and will tell you that it could not find any object with id="subfeature" (one pattern tried)</p> <p>So yes, go with solution of user knbk. reverse the order and keep this in mind.</p>
0
2016-10-13T22:09:07Z
[ "python", "django" ]