title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How to construct a numpy array from multiple vectors with data aligned by id
38,415,354
<p>I am using <strong>Python</strong>, <strong>numpy</strong> and <strong>scikit-learn</strong>. I have data of <em>keys</em> and <em>values</em> that are stored in an SQL table. I retrieve this as a list of tuples returned as: <code>[(id, value),...]</code>. Each id appears only once in the list and the tuples appear...
1
2016-07-16T20:30:51Z
38,415,514
<p>You can convert each element in the dataset to a dictionary and then use pandas data frame which will return the result close to the desired output. If <code>2D</code> numpy array is desired we can use <code>as_matrix()</code> method to convert the data frame to numpy array:</p> <pre><code>import pandas as pd pd.Da...
0
2016-07-16T20:51:37Z
[ "python", "numpy", "machine-learning", "scikit-learn" ]
How to construct a numpy array from multiple vectors with data aligned by id
38,415,354
<p>I am using <strong>Python</strong>, <strong>numpy</strong> and <strong>scikit-learn</strong>. I have data of <em>keys</em> and <em>values</em> that are stored in an SQL table. I retrieve this as a list of tuples returned as: <code>[(id, value),...]</code>. Each id appears only once in the list and the tuples appear...
1
2016-07-16T20:30:51Z
38,415,564
<p>Here's a NumPy based approach to create a sparse matrix <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.coo_matrix.html" rel="nofollow"><code>coo_matrix</code></a> with memory efficiency in focus -</p> <pre><code>from scipy.sparse import coo_matrix # Construct row IDs lens = np.arr...
3
2016-07-16T20:57:53Z
[ "python", "numpy", "machine-learning", "scikit-learn" ]
Axis don't show the ticks I want
38,415,424
<p>I want to plot a Ramachandron plot. On this kind of graph, x goes from -180° to 180°, and so does y. I want a tick every 60 degrees. So here is the code I use:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.colors import LogNorm x = [-179, 179] y = [-179, 179] fig = plt.figure(1) ax = plt.subplo...
0
2016-07-16T20:39:04Z
38,415,479
<p>You use hist2d, set axis ticks after plotting:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.colors import LogNorm x = [-179, 179] y = [-179, 179] fig = plt.figure(1) ax = plt.subplot(111) # 1 bim = 1 degree # !!! Logarithmic normalization of the colors plt.hist2d(x, y, bins=180, norm=LogNorm())...
0
2016-07-16T20:45:58Z
[ "python", "matplotlib" ]
ImportError: No module named 'numpy'
38,415,459
<p>I am trying to import NumPy in the IPython 3 terminal, and receiving the following error. </p> <pre><code>In [16]: import numpy as np --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-16-4ee716103...
-5
2016-07-16T20:43:06Z
38,417,387
<p>Download pip:</p> <p><a href="https://packaging.python.org/installing/" rel="nofollow">https://packaging.python.org/installing/</a></p> <p>run <code>python get-pip.py</code> after downloading the file from the instructions. Then:</p> <pre><code>pip install numpy scipy pandas </code></pre> <p>Then you should be g...
1
2016-07-17T02:35:16Z
[ "python" ]
Python 3 csv.reader empty response
38,415,577
<p>Hello I got the following code but the loop won't work because the <code>csv.reader</code> is empty. The file with the csv data is opened correctly.</p> <p>For Understanding: var pokemon can be any pokemon name as string. bot, logger and event are vars comming from the Hangoutsbot. All needed libaries a...
0
2016-07-16T21:00:12Z
38,415,593
<p>your <code>list(reader)</code> call consumes the reader, which is empty on the for loop.</p> <p>just replace</p> <pre><code> reader = csv.reader(f) rows = list(reader) for row in reader: </code></pre> <p>by</p> <pre><code> reader = csv.reader(f) rows = list(reader) for row in rows: </code><...
1
2016-07-16T21:02:05Z
[ "python", "python-3.x", "csv", "parsing", "for-loop" ]
How can I manually create a signature for record editing?
38,415,582
<p>The <code>SQLFORM.grid</code> method generates an <em>Edit</em> button with the following generic URL:</p> <pre><code>a/c/f/table/record_id?_signature=md5 </code></pre> <p>(Where a=application, c=controller and f=function.)</p> <p>How can I obtain, given the record id, such URL (or at least the <code>_signature</...
0
2016-07-16T21:01:02Z
38,424,011
<p>The following should generate the proper URL:</p> <pre><code>URL('a', 'c', 'f', args=['table', record_id], user_signature=True, hash_vars=False) </code></pre> <p>In this case, <code>hash_vars=False</code> isn't strictly necessary, as there are no URL variables, but just in case...</p>
1
2016-07-17T17:29:00Z
[ "python", "web2py" ]
Is there a way to break out of list comprehension?
38,415,586
<p>When using infinite generators, I can use <code>if</code> to prevent items from entering the list, but not in order to break the loop.</p> <p>This will actually crash and hang. Not even <code>KeyboardInterrupt</code> can save me (why is that BTW?)</p> <pre><code>import itertools a = [x for x in itertools.count() i...
2
2016-07-16T21:01:25Z
38,415,611
<p>Use <code>itertools.takewhile</code> to cease iteration after a condition is no longer met...:</p> <pre><code>import itertools a = [x for x in itertools.takewhile(lambda L: L &lt; 10, itertools.count())] # a = list(itertools.takewhile(lambda L: &lt; 10, itertools.count())) </code></pre> <p>There's isn't per-se a ...
6
2016-07-16T21:04:10Z
[ "python" ]
python syntax error with the version 2.5 any idea how to fix it?
38,415,590
<p>first i tried to run it by pressing F5. it said the syntax error is in the first line. i tried running the program from the command line but it said the same thing. any idea what's wrong or how to fix it ?</p> <p><img src="http://i.stack.imgur.com/2nDTz.png" alt="hello.py"></p>
-1
2016-07-16T21:01:35Z
38,415,725
<p>F5 runs the script in the current window, but the current window doesn't display a script: it displays an interactive interpreter (also known as a REPL: Read, Evaluate, Print Loop).</p> <p>In this window, you simply type valid Python statements, and they execute immediately. There is not way, or need, to run the co...
0
2016-07-16T21:18:40Z
[ "python" ]
Interpretation of numpy polyfit on a big dataset
38,415,741
<p>I'm analyzing a publicly available dataset: an assessment of properties in San Francisco for tax purposes (<a href="https://data.sfgov.org/Housing-and-Buildings/Historic-Secured-Property-Tax-Rolls/wv5m-vpq2" rel="nofollow">https://data.sfgov.org/Housing-and-Buildings/Historic-Secured-Property-Tax-Rolls/wv5m-vpq2</a>...
1
2016-07-16T21:20:16Z
38,415,913
<pre><code>Returns ------- p : ndarray, shape (M,) or (M, K) Polynomial coefficients, highest power first. If `y` was 2-D, the coefficients for `k`-th data set are in ``p[:,k]``. </code></pre> <p>This tells me that the <code>4.2%</code> is the coefficient on the log term.</p> <p>My first reaction would be to...
5
2016-07-16T21:42:30Z
[ "python", "numpy", "pandas" ]
Python target for Java grammar in antlr
38,415,765
<p>I want to run a Lexer for Java in Python using Antlr</p> <p>For Antlr4, I am using the Java8 grammar from <a href="https://github.com/antlr/grammars-v4/tree/master/java8" rel="nofollow">https://github.com/antlr/grammars-v4/tree/master/java8</a>.</p> <p>I am generating the parser using</p> <p><code>java -jar antlr...
0
2016-07-16T21:23:45Z
38,415,816
<p>Just remove strings wich start with <a href="https://github.com/antlr/grammars-v4/blob/master/java8/Java8.g4#L1742" rel="nofollow">Character.isJavaIdentifierStart</a> from your Java8 grammar.</p>
0
2016-07-16T21:28:55Z
[ "java", "python", "antlr4" ]
ipython : get access to current figure()
38,415,774
<p>I want to add more fine grained grid on a plotted graph. The problem is all of the examples require access to the axis object. I want to add specific grid to already plotted graph (from inside ipython).</p> <p>How do I gain access to the current figure and axis in ipython ?</p>
0
2016-07-16T21:25:01Z
38,417,834
<p>With the <code>plt?</code> example (assuming <code>ipython --pylab</code>)</p> <pre><code>In [44]: x=np.arange(0,5,.1) In [45]: y=np.sin(x) In [46]: plt.plot(x,y) Out[46]: [&lt;matplotlib.lines.Line2D at 0xb09418cc&gt;] </code></pre> <p>displays <code>figure 1</code>; get its handle with:</p> <pre><code>In [47]: ...
2
2016-07-17T04:10:50Z
[ "python", "matplotlib", "ipython", "axis", "figure" ]
ipython : get access to current figure()
38,415,774
<p>I want to add more fine grained grid on a plotted graph. The problem is all of the examples require access to the axis object. I want to add specific grid to already plotted graph (from inside ipython).</p> <p>How do I gain access to the current figure and axis in ipython ?</p>
0
2016-07-16T21:25:01Z
38,433,583
<p><code>plt.gcf()</code> to get current figure</p> <p><code>plt.gca()</code> to get current axis</p>
3
2016-07-18T09:49:25Z
[ "python", "matplotlib", "ipython", "axis", "figure" ]
Autogenerate wrapper classes in Python
38,415,928
<p>I do a lot of work with a library in which almost all classes are uninheritable, yet I want to extend them.</p> <p>Say class A is uninheritable. I frequently create "wrapper" classes by storing a <code>self._obj</code> as an atrribute, then manually implementing all the methods and all the attributes (with <code>@p...
0
2016-07-16T21:44:29Z
38,416,034
<p>Yes: just define <code>__getattr__</code> to lookup the attribute on <code>self._cell</code>.</p>
1
2016-07-16T21:59:00Z
[ "python", "python-3.x", "inheritance", "wrapper" ]
Raspberry-pi - DHT11 + Relay trigger
38,416,049
<p>I am a complete noob when it comes to Python and the Raspberry Pi unit but I am figuring it out. </p> <p>I am working on a script to monitor the current temperature of my greenhouse that I am building. When the temp gets to 28C, I would like for it to activate my relay which will turn on the fan. At 26C the relay s...
-1
2016-07-16T22:01:16Z
38,416,173
<p>For the current error you're facing, keep in mind that <strong>Python relies <em>heavily</em> on indentation</strong>. It's not like other languages such as C++ and Java that use curly braces to arrange statements.</p> <p>To fix the indentation in your code, please see below:</p> <pre><code>import RPi.GPIO as GPIO...
1
2016-07-16T22:18:44Z
[ "python", "raspberry-pi" ]
Enthought Installtion Issue -- Error Writing to File
38,416,087
<p><a href="http://i.stack.imgur.com/FShsW.png" rel="nofollow">enter image description here</a></p> <p>Enthought is showing the error in the picture when installing. </p>
-1
2016-07-16T22:07:12Z
38,416,121
<p>I think it's because you need to install as an administrator. If you are using the comand shell use this code:</p> <p><code>runas /noprofile /user:Administrator cmd</code></p> <p>To run the administrator shell. Otherwise right click the program and select Use as Administrator.</p>
0
2016-07-16T22:11:56Z
[ "python", "enthought" ]
Enthought Installtion Issue -- Error Writing to File
38,416,087
<p><a href="http://i.stack.imgur.com/FShsW.png" rel="nofollow">enter image description here</a></p> <p>Enthought is showing the error in the picture when installing. </p>
-1
2016-07-16T22:07:12Z
38,427,790
<p>Either your system has been corrupted, or your account has been configured with unusually strict security constraints, forbidding any executables from being copied into your home directory. In the latter case, the best solution would probably be to install as a Managed Common Install, as described here: <a href="htt...
0
2016-07-18T02:25:28Z
[ "python", "enthought" ]
Browser cancels HLS Stream while VLC accepts it
38,416,184
<p>I recorded a HSL stream by writing the MPEG-TS streams contents into GridFS filesystem.</p> <p>i'm now trying to serve this content back to the browser using <code>aiohttp</code>s <code>SessionResponse</code> which fails for different reasons.</p> <pre><code> async def get_video(request): stream_res...
0
2016-07-16T22:20:43Z
38,423,265
<p>I have no experience with HLS personally but even vast overview of <a href="https://tools.ietf.org/html/draft-pantos-http-live-streaming-13" rel="nofollow">RFC draft</a> displays that you breaks the protocol.</p> <p>It's not about sending video chunks all together in single endless response but about sending multip...
1
2016-07-17T16:11:19Z
[ "python", "video-streaming", "http-live-streaming", "m3u8", "aiohttp" ]
PRAW Program not reading posts and comments correctly
38,416,226
<p>Here is my code. Please note that it does not raise any errors, but does not work in the correct manner either.</p> <pre class="lang-py prettyprint-override"><code>import praw import time r = praw.Reddit(user_agent = "This is a program to check if anyone is cursing on the forum.") r.login("BottyMcFooFoo","991319")...
0
2016-07-16T22:29:37Z
38,416,372
<p>I believe that, at least in part, your problem begins here:</p> <pre><code>for x in comment: commentText = x.body.lower() </code></pre> <p>This loop simply amounts to taking <code>commentText</code> to denote the lower-text of the <em>last</em> comment body. You probably wanted to aggregate the comments in a l...
0
2016-07-16T22:53:53Z
[ "python", "python-3.x" ]
Elasticsearch-Python 2.7-Configure an index for analyzer
38,416,262
<p>I am trying to build an index using the python API, with the following code (In particular I am trying to configure an analyzer):</p> <pre><code>doc = { "settings": { "analysis": { "analyzer": { "folding": { "tokenizer": "standard", "filter": [ "lowercase", "asciifolding" ] } } } ...
0
2016-07-16T22:35:01Z
38,421,801
<p>After several attempt I found the solution. It was a syntax problem. The correct answer is:</p> <pre><code>doc = { "index" : { "analysis" : { "analyzer" : { "default" : { "tokenizer" : "standard", ...
1
2016-07-17T13:34:25Z
[ "python", "python-2.7", "elasticsearch", "elasticsearch-plugin" ]
Manage.py utitliy not working properly within Pycharm
38,416,336
<p>I happened to change the name of a django's app (just the name of the directory) so everytime I wanted to make the migrations of the models within that app, I couldn't. </p> <p>After updating every occurence of the string within the project, I run <code>makemigrations</code> succesfully within the terminal. But I h...
0
2016-07-16T22:47:55Z
38,419,275
<p>Is maybe not the best solution to your problem but I had something similar in the past with PyCharm and what I did was to recreate the virtualenv within PyCharm and reinstall all the modules. Make sure that you export your installed modules using the following command:</p> <pre><code>pip freeze &gt; requirements.tx...
0
2016-07-17T08:25:30Z
[ "python", "django" ]
Need to disable Sympy output of 'False' (0, False) in logical operator 'not'
38,416,381
<p>I am using Sympy to process randomly generated expressions which may contain the boolean operators 'and', 'or', and 'not'.</p> <p>'and' and 'or' work well:</p> <blockquote> <p>a = 0</p> <p>b = 1</p> <p>a and b</p> </blockquote> <p>0</p> <blockquote> <p>a or b</p> </blockquote> <p>1</p> <p>But 'no...
1
2016-07-16T22:56:00Z
38,416,665
<p><code>a, not b</code> doesn't do what you think it does. You are actually asking for, and correctly receiving, a tuple of two items containing:</p> <ol> <li><code>a</code></li> <li><code>not b</code></li> </ol> <p>As the result shows, <code>a</code> is <code>0</code> and <code>not b</code> is <code>False</code>, <...
1
2016-07-16T23:53:02Z
[ "python", "sympy", "logical-operators" ]
Need to disable Sympy output of 'False' (0, False) in logical operator 'not'
38,416,381
<p>I am using Sympy to process randomly generated expressions which may contain the boolean operators 'and', 'or', and 'not'.</p> <p>'and' and 'or' work well:</p> <blockquote> <p>a = 0</p> <p>b = 1</p> <p>a and b</p> </blockquote> <p>0</p> <blockquote> <p>a or b</p> </blockquote> <p>1</p> <p>But 'no...
1
2016-07-16T22:56:00Z
38,424,476
<p>If you use the operators <code>&amp;</code>, <code>|</code>, and <code>~</code> for and, or, and not, respectively, you will get a symbolic boolean expression. I also recommend using <code>sympy.true</code> and <code>sympy.false</code> instead of 1 and 0. </p>
0
2016-07-17T18:19:32Z
[ "python", "sympy", "logical-operators" ]
Projecting a point onto the intersection of n-dimensional spaces in Python
38,416,382
<p>(forgive my terminology - it has been a long time since I took an advanced math class)</p> <p>Let's say I have <em>n</em> "planes" each "perpendicular" to a single axis in <em>m</em>-dimensional space. No two planes are perpendicular to the same axis. I believe I can safely assume that there will be some intersecti...
1
2016-07-16T22:56:05Z
38,416,939
<p>Your "planes" in <em>m</em>-dimensional space are <em>(m-1)</em>-dimensional objects. They are usually referred to as <a href="https://en.wikipedia.org/wiki/Hyperplane" rel="nofollow"><em>hyperplanes</em></a> &mdash; a generalization of <em>planes</em>, 2-dimensional objects in 3-dimensional space. To define a hyper...
0
2016-07-17T00:46:49Z
[ "python", "numpy" ]
Projecting a point onto the intersection of n-dimensional spaces in Python
38,416,382
<p>(forgive my terminology - it has been a long time since I took an advanced math class)</p> <p>Let's say I have <em>n</em> "planes" each "perpendicular" to a single axis in <em>m</em>-dimensional space. No two planes are perpendicular to the same axis. I believe I can safely assume that there will be some intersecti...
1
2016-07-16T22:56:05Z
38,416,971
<p>The projection can be computed by solving an overdetermined system in the sense of least squares, with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq" rel="nofollow">lstsq</a>. The columns of the matrix of the system is formed by normal vectors, used as colum...
0
2016-07-17T00:54:56Z
[ "python", "numpy" ]
I use python social auth with django. I can't disconnect from Steam
38,416,577
<p>My template:</p> <pre><code>{{ backends.associated }} {{ backends.not_associated }} {{ backends.backends }} {{ status_page }} {% if page_status == 'login' %} {% for soc in backends.backends %} &lt;form action="{% url 'social:disconnect' soc %}" method="post"&gt; {% csrf_token %} ...
0
2016-07-16T23:30:29Z
38,723,773
<p>All your code is doing is disassociating your steam account from your local django user, not disconnecting from steam as such. If you're really trying to disconnect from steam, there's no need, all that's happened when you executed the social:begin link is that a steam supplied token was associated with your local ...
1
2016-08-02T14:50:29Z
[ "python", "django", "steam", "python-social-auth" ]
Python 3.4 subprocess
38,416,594
<p>The following has worked in Python 2.7, I believe that is what I was using. I'm currently trying to update everything to Python 3.4 and this doesn't work at all. When I run the program it just stops and doesn't appear to run any of processes I'm asking for it to run. I want it to run the certain process multiple ...
0
2016-07-16T23:36:42Z
38,416,852
<p>A print in a subprocess won't show.</p> <p>If you'd like to get a subprocess output, you could use <code>subprocess.check_output()</code> or use <code>stdout</code> parameter in your call to <code>subprocess.Popen</code></p> <pre><code>#!/usr/bin/python3.4 import sys import subprocess procs=[] for i in range(3): ...
-1
2016-07-17T00:28:15Z
[ "python", "subprocess" ]
Python 3.4 subprocess
38,416,594
<p>The following has worked in Python 2.7, I believe that is what I was using. I'm currently trying to update everything to Python 3.4 and this doesn't work at all. When I run the program it just stops and doesn't appear to run any of processes I'm asking for it to run. I want it to run the certain process multiple ...
0
2016-07-16T23:36:42Z
38,417,032
<p>The problem is possibly due to the way you invoke python for the subprocess. When the interpreter is explicitly invoked as <code>python script.py</code> the "hashbang" is ignored and the interpreter will be <code>python</code>. Depending on your system that might be a different version of Python.</p> <p>In your cod...
0
2016-07-17T01:06:08Z
[ "python", "subprocess" ]
Python Injection - is there such a thing?
38,416,671
<p>I've been doing some penetration testing on my own site and have been doing a lot of research on common vulnerabilities.</p> <p>SQL injection comes up a lot but I was wondering, could there possibly be such a thing as python injection? Say for example that a web form submitted a value that was entered in a dictiona...
0
2016-07-16T23:53:42Z
38,416,692
<p>This depends entirely on what you <em>do</em> with the input from the webform. In normal use the form gets encoded as <code>x-www-form-urlencoded</code> or <code>json</code> -- Both formats which <em>can</em> be deserialized into a python dictionary completely safely. Of course, they <em>could</em> be deserialized...
0
2016-07-16T23:57:07Z
[ "python", "code-injection" ]
urllib2 bypassing cloudflare
38,416,764
<p>I have wrote a script to grab the data from a php file on a website. I wrote the script so that it only outputs the data if the current data on the page has changed from what it was the last time it grabbed data from the page. The page does require authentication, which is why I have the PHPSESSID added in. That wil...
0
2016-07-17T00:11:00Z
38,417,157
<p>The purpose of CloudFlare's "detecting your browser" page is, essentially, to block bots.</p> <p>It's working correctly here. You will need to ask the owner of the web site to disable this protection for their site, or to make an exception for you.</p>
0
2016-07-17T01:37:12Z
[ "python", "python-2.7", "urllib2", "cloudflare" ]
Result of .join in dask dataframes seems to depend on the way, the dask dataframe was generated
38,416,836
<p>I got unexpected results when applying <code>join</code> to dask dataframes which were generated by the .from_delayed method. I want to demonstrate this by the following example, which consists of three parts. </p> <ol> <li>Generate dask dataframe via the <code>from_delayed</code> method and join it with a dask dat...
2
2016-07-17T00:25:25Z
38,623,047
<p>There were indeed some issues with <code>dd.merge</code>. These have been resolved in dask version 0.10.2</p> <pre><code>In [10]: print(dask_from_delayed_join.compute()) A B A0 1 1 B1 2 2 C3 4 3 In [11]: print(pandas_join) A B A0 1 1 B1 2 2 C3 4 3 In [12]: print(dask_from_pandas_join.comput...
1
2016-07-27T20:57:06Z
[ "python", "pandas", "dask" ]
Generating a random, non-prime number in python
38,416,864
<p>How would I generate a non-prime random number in a range in Python?</p> <p>I am confused as to how I can create an algorithm that would produce a non-prime number in a certain range. Do I define a function or create a conditional statement? I would like each number in the range to have the same probability. For ex...
3
2016-07-17T00:30:49Z
38,416,997
<p>Now, you didn't say anything about efficiency, and this could surely be optimized, but this should solve the problem. This should be an efficient algorithm for testing primality:</p> <pre><code>import random def isPrime(n): if n % 2 == 0 and n &gt; 2: return False return all(n % i for i in range(...
3
2016-07-17T01:00:03Z
[ "python", "python-3.x", "random", "primes" ]
Generating a random, non-prime number in python
38,416,864
<p>How would I generate a non-prime random number in a range in Python?</p> <p>I am confused as to how I can create an algorithm that would produce a non-prime number in a certain range. Do I define a function or create a conditional statement? I would like each number in the range to have the same probability. For ex...
3
2016-07-17T00:30:49Z
38,422,171
<p>The algorithm and ideas to choose is very dependent on your exact use-case, as mentioned by @smarx.</p> <h3>Assumptions:</h3> <ul> <li>Each non-prime within the range has the same probability of beeing chosen / <strong>uniformity</strong></li> <li>It is sufficient that the sampled number is not a prime with a <str...
1
2016-07-17T14:15:08Z
[ "python", "python-3.x", "random", "primes" ]
Why is my program glitching and lagging out on me?
38,416,974
<p>I'm working on a drawing app in python, and I recently added in a mousedrag function to make it so that you could drag the turtle and it would draw. It often gets a little bit laggy, and can go in other directions when I'm dragging it. Here's the code:</p> <pre><code> import sys import turtle from tkinter import...
0
2016-07-17T00:55:41Z
38,417,513
<p>The turtle documentation is a little oversimplified when it suggests <code>turtle.ondrag(turtle.goto)</code> to draw freehand. To make it work you need to define your own event handler that immediately disables drag events on entry, moves the turtle and then reenables drag events on exit:</p> <pre><code>import tur...
1
2016-07-17T03:02:37Z
[ "python", "turtle-graphics" ]
When using flask, what is the best way to remembering parameters while paginating?
38,417,040
<p>Say that I have a results page that has several filters. The filters are passed to flask as URL parameters. But once I press Next Page, this will be forgotten. What is the best way to keep these parameters as you go from page to page?</p> <p>I'm sure javascript frameworks exist to do this, but I'd rather not use ja...
0
2016-07-17T01:09:19Z
38,417,233
<p>Assuming you're rendering HTML and not JSON (which it seems like you are from the tag), why not just add the filter query parameters from the request into the rendered page?</p> <p>For example, something like this:</p> <p>Python:</p> <pre><code>@app.route('/search') def search(): page_no = request.args.get('p...
1
2016-07-17T01:54:49Z
[ "javascript", "python", "flask", "query-string" ]
Python Pygame forces
38,417,061
<p>I've been wanting to create a physics engine for my game, and decided I should first cover forces. I'm using pygame on python to accomplish this.</p> <p>For example, I want to be able to program a force of a certain magnitude, that acts on an object. I haven't been able to think of any way to do this. After I get t...
1
2016-07-17T01:14:36Z
38,417,482
<p>There are a few points I can see. Firstly, if you want an effect to occur while you hold a key down then you should query if that key is down, rather than just pressed. Ignore KEYDOWN events and use <a href="http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed" rel="nofollow">http://www.pygame.org/docs/r...
1
2016-07-17T02:54:46Z
[ "python", "pygame" ]
Python Pygame forces
38,417,061
<p>I've been wanting to create a physics engine for my game, and decided I should first cover forces. I'm using pygame on python to accomplish this.</p> <p>For example, I want to be able to program a force of a certain magnitude, that acts on an object. I haven't been able to think of any way to do this. After I get t...
1
2016-07-17T01:14:36Z
38,532,381
<p>When a force is applied, it adds an acceleration to the object in terms of the mass in the direction of the force.</p> <p>First of all, I would suggest creating variables for your object's mass, x and y velocity and its x and y resultant force components. When a force is added to the object, it would be easier to a...
0
2016-07-22T17:38:39Z
[ "python", "pygame" ]
How to detect url callback request
38,417,077
<p>I have a locally-run app that makes API calls to a website (<a href="https://tumblr.com" rel="nofollow"><code>tumblr.com</code></a>). This involves setting some OAuth credentials; one step along the way requires extracting a key from a callback url that the server directs the browser to. So what I currently have the...
0
2016-07-17T01:19:18Z
38,417,209
<p>okay first thing first, for http requests, a good python module is <code>requests</code></p> <p><a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a></p> <p>Then, your app gives a callback address to tumblr so that tumblr can tell to your app client info...
1
2016-07-17T01:48:37Z
[ "python", "network-programming" ]
Pandas unexpected scientific notion
38,417,091
<p>I have a large csv file contains some bus network information.</p> <p>The stop code are made of a large number with a certain letter in the end. However, some of them are only numbers. When I read them into pandas, the large numbers become in scientific notion. like</p> <pre><code>code_o lat_o lon_o code_d 49...
0
2016-07-17T01:22:34Z
38,417,133
<p>IIUC, try forcing <code>object</code> type for the <code>code_d</code> column on import:</p> <pre><code>import numpy as np import pandas as pd df = pd.read_csv('your_original_file.csv', dtype={'code_d': 'object'}) </code></pre> <p>You can then parse that column, discarding the letter at the end and casting the re...
0
2016-07-17T01:32:51Z
[ "python", "string", "pandas", "format", "scientific-notation" ]
Pandas unexpected scientific notion
38,417,091
<p>I have a large csv file contains some bus network information.</p> <p>The stop code are made of a large number with a certain letter in the end. However, some of them are only numbers. When I read them into pandas, the large numbers become in scientific notion. like</p> <pre><code>code_o lat_o lon_o code_d 49...
0
2016-07-17T01:22:34Z
38,418,600
<p>Keep it simple: <code>df=pd.read_csv('myfile.csv',dtype=str)</code> and it will read everything in as strings. Or as was posted earlier by @Alberto to specify that column only just: <code>df=pd.read_csv('myfile.csv',dtype={'code_o':str})</code></p>
0
2016-07-17T06:40:26Z
[ "python", "string", "pandas", "format", "scientific-notation" ]
Parsing inner td tag with Beautifulsoop4 in python
38,417,155
<p>I am working on a small project, and I am having a hard time parsing the needed rows from an html code using bs4. </p> <p>HTML:</p> <pre><code> &lt;div id="results_box"&gt; &lt;table class="genTbl closedTbl historicalTbl" id="curr_table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="first lef...
2
2016-07-17T01:37:07Z
38,417,182
<p>The reason your current approach does not work is that the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class" rel="nofollow"><code>class</code></a> is a special <em>multi-valued attribute</em> in <code>BeautifulSoup</code> and a regular expression would not be applied to the comp...
2
2016-07-17T01:42:23Z
[ "python", "regex", "beautifulsoup" ]
Check if string contains any list element
38,417,161
<p>So I am doing a for loop of a list. Every single string, I want to .find, but instead of .find one item for a string, I want to check that string for anything in my list. </p> <p>For example.</p> <pre><code>checkfor = ['this','that','or the other'] </code></pre> <p>then do</p> <p>string.find(checkfor) or someth...
-1
2016-07-17T01:38:04Z
38,417,218
<blockquote> <p>I want to check that string for anything in my list</p> </blockquote> <p>Python has <code>in</code> for that. </p> <pre><code>for s in checkfor: if s in email: # do action </code></pre>
0
2016-07-17T01:50:37Z
[ "python", "list" ]
Check if string contains any list element
38,417,161
<p>So I am doing a for loop of a list. Every single string, I want to .find, but instead of .find one item for a string, I want to check that string for anything in my list. </p> <p>For example.</p> <pre><code>checkfor = ['this','that','or the other'] </code></pre> <p>then do</p> <p>string.find(checkfor) or someth...
-1
2016-07-17T01:38:04Z
38,417,229
<p>You could try using list comprehension to accomplish this. </p> <pre><code>occurrences = [i for i, x in enumerate(email) if x =='this'] </code></pre>
1
2016-07-17T01:54:20Z
[ "python", "list" ]
Check if string contains any list element
38,417,161
<p>So I am doing a for loop of a list. Every single string, I want to .find, but instead of .find one item for a string, I want to check that string for anything in my list. </p> <p>For example.</p> <pre><code>checkfor = ['this','that','or the other'] </code></pre> <p>then do</p> <p>string.find(checkfor) or someth...
-1
2016-07-17T01:38:04Z
38,417,251
<p>Use the <code>in</code> clause:</p> <pre><code>If checkfor not in email: do_some_thing() </code></pre>
0
2016-07-17T02:00:30Z
[ "python", "list" ]
Check if string contains any list element
38,417,161
<p>So I am doing a for loop of a list. Every single string, I want to .find, but instead of .find one item for a string, I want to check that string for anything in my list. </p> <p>For example.</p> <pre><code>checkfor = ['this','that','or the other'] </code></pre> <p>then do</p> <p>string.find(checkfor) or someth...
-1
2016-07-17T01:38:04Z
38,417,333
<p>If you just want to know if at least one value in the list exists in the string then a simple way to do that would be:</p> <pre><code>any(email.find(check) &gt; -1 for check in checkfor) </code></pre> <p>If you want to check that all of them exist in the string then do</p> <pre><code>all(email.find(check) &gt; -1...
1
2016-07-17T02:22:37Z
[ "python", "list" ]
Serving interactive bokeh figure on heroku
38,417,200
<p>I'm trying to serve an interactive <code>bokeh</code> figure via heroku. The figure I'm trying to have served is essentially equivalent to this one (<a href="https://demo.bokehplots.com/apps/movies" rel="nofollow">example</a>, <a href="https://github.com/bokeh/bokeh/blob/master/examples/app/movies/main.py" rel="nofo...
2
2016-07-17T01:47:14Z
38,447,618
<p>I'm just going to answer my own question since I was eventually able to get this to work and nobody else has answered it yet.</p> <p>I ended up with a <code>Procfile</code> that looked like this:</p> <pre><code>web: bokeh serve --port=$PORT --host=myapp.herokuapp.com --host=* \ --address=0.0.0.0 --use-xheader...
3
2016-07-18T23:58:16Z
[ "python", "heroku", "flask", "bokeh" ]
Unexpected Indent Error - trying to tweak someone else code
38,417,223
<p>Here the code. I don't know pyton and trying to tweak someone else code </p> <p>I am trying to write what is printed in for loop</p> <pre><code> for poke in visible: other = LatLng.from_degrees(poke.Latitude, poke.Longitude) diff = other - origin # print(diff) difflat = diff....
-2
2016-07-17T01:51:49Z
38,417,283
<p>In Python, there is no brackets to define blocks. It is done with whitespace. So if you have lines with a different amount of indentation than other lines, or you are missing indentation where there is supposed to be some, then the interpreter will raise an IndentationError.</p> <p>Assuming your code was pasted pro...
1
2016-07-17T02:11:43Z
[ "python", "python-2.7" ]
Unexpected Indent Error - trying to tweak someone else code
38,417,223
<p>Here the code. I don't know pyton and trying to tweak someone else code </p> <p>I am trying to write what is printed in for loop</p> <pre><code> for poke in visible: other = LatLng.from_degrees(poke.Latitude, poke.Longitude) diff = other - origin # print(diff) difflat = diff....
-2
2016-07-17T01:51:49Z
38,417,293
<p>You have to change the start - Where it has the for statement. In python, anything requiring a colon at the end MUST be indented.</p> <p>The easiest way is to go through each line in the for statement and press the TAB key. This will indent the code for you. Hope it helps!</p> <p>Id also watch or read a basic tut...
0
2016-07-17T02:12:57Z
[ "python", "python-2.7" ]
Unexpected Indent Error - trying to tweak someone else code
38,417,223
<p>Here the code. I don't know pyton and trying to tweak someone else code </p> <p>I am trying to write what is printed in for loop</p> <pre><code> for poke in visible: other = LatLng.from_degrees(poke.Latitude, poke.Longitude) diff = other - origin # print(diff) difflat = diff....
-2
2016-07-17T01:51:49Z
38,417,299
<p>Ok, so I'm hopefully assuming you've got more code than what you have shown all of us (it's actually quite hard to answer these questions without more code sometimes), then if you have already declared all of your variables and what not behind the scenes then all you should have to do is fix the indentation like so:...
0
2016-07-17T02:14:13Z
[ "python", "python-2.7" ]
Subclassed object results in NoneType
38,417,289
<p>I'm trying to subclass the Chrome WebDriver to include some initialization and cleanup code, but then Python complains that the created object is set to <code>None</code>:</p> <pre><code>import glob import selenium import subprocess from selenium.webdriver.common.by import By class WebDriver(selenium.webdriver.Ch...
1
2016-07-17T02:12:39Z
38,417,307
<p>Your <code>__enter__()</code> magic method should return <code>self</code> for the <code>driver</code> variable to be pointed to the instance of the <code>WebDriver</code> class:</p> <pre><code>def __enter__(self): self.get(self.url) self.implicitly_wait(15) return self </code></pre> <p>To get more inf...
2
2016-07-17T02:15:42Z
[ "python", "python-3.x", "selenium", "subclass" ]
Having trouble with a 'list index out of range' error in my code
38,417,314
<p>For some context on this assignment I was given, I basically have to create a program that checks the answers given by a user and says if they've gotten it correct or not and which ones they got wrong as an output. I've mostly solved it out to where my problem is in how I have the 'user's' answers stored in the tex...
2
2016-07-17T02:17:16Z
38,417,331
<p>I found a few issues and fixed them all below:</p> <ol> <li>You weren't closing the file after writing to it.</li> <li>You were writing all the answers on one line but then trying to read them as though they were on separate lines.</li> <li>You weren't stripping off the newline on the lines read from the file. (Ans...
2
2016-07-17T02:22:16Z
[ "python" ]
Having trouble with a 'list index out of range' error in my code
38,417,314
<p>For some context on this assignment I was given, I basically have to create a program that checks the answers given by a user and says if they've gotten it correct or not and which ones they got wrong as an output. I've mostly solved it out to where my problem is in how I have the 'user's' answers stored in the tex...
2
2016-07-17T02:17:16Z
38,417,391
<p>I've fixed your code (but it appears smarx beat me too it)</p> <p>Here's what I found you were doing wrong:</p> <ul> <li><p>Not closing all of your files.</p></li> <li><p>Not correctly reading your data back. (cause of the IndexOutOfRange error)</p></li> <li><p>Bad indentation in the while loop.</p></li> </ul> <p...
1
2016-07-17T02:35:58Z
[ "python" ]
python selenium scraping tbody
38,417,462
<p>The below is the HTML code which I'm trying to scrape</p> <pre><code>&lt;div class="data-point-container section-break"&gt; # some other HTML div classes here which I don't need &lt;table class data-bind="showHidden: isData"&gt; &lt;!-- ko foreach : sections --&gt; &lt;thead&gt;...&lt;/the...
1
2016-07-17T02:50:31Z
38,417,528
<p>Strictly speaking, <a href="http://stackoverflow.com/a/16155425/771848">one should not have more than one <code>thead</code> element</a> per table according to the <code>table</code> element specification.</p> <p>If you still have this <code>thead</code> followed by corresponding <code>tbody</code> structure, I wou...
1
2016-07-17T03:06:17Z
[ "python", "selenium", "pandas" ]
How does bup (git-based image backup) computes hashes of stored objects
38,417,492
<p>There is <code>bup</code> backup program (<a href="https://github.com/bup/bup" rel="nofollow">https://github.com/bup/bup</a>) based on some ideas and some functions from <code>git</code> version control system for compact storage of virtual machine images. </p> <p>In <code>bup</code> there is <code>bup ls</code> su...
2
2016-07-17T02:57:20Z
38,419,612
<p><code>bup</code> stores all data in a bare git repository (which by default is located at <code>~/.bup</code>). Therefore <code>bup</code>'s hash computation method exactly replicates the one used by <code>git</code>.</p> <p>However, an important difference from git is that <code>bup</code> may split files into chu...
0
2016-07-17T09:08:42Z
[ "python", "git", "backup", "sha1", "git-annex" ]
Q: google app engine app.yaml how to handle urls from within main.py?
38,417,523
<p>I have a web site up and running with about 100 urls specified in my app.yaml file. Because app.yaml is limited to 100 urls, I am trying to figure out how to transfer the app.yaml specified routing instructions into main.py. I want modify (shorten) the app.yaml file to send all requests to main.py and then I want ...
2
2016-07-17T03:04:52Z
38,417,582
<p>The precedence hierarchy goes from app.yaml -> handlers specified in the program.</p> <ul> <li>When you hit <code>/test1</code>, <code>app.yaml</code> routes your request to <code>test1.app</code> (because it matches the <code>/test1</code> route) which routes your request to <code>test1.MainHandler</code>.</li> <l...
0
2016-07-17T03:18:55Z
[ "python", "url-routing", "app.yaml" ]
Python pint module with multiprocessing
38,417,527
<p>The python pint module implements physical quantities. I would like to use it together with multiprocessing. However, I don't know how to handle creating a UnitRegistry in the new process. If I do the intuitive:</p> <pre><code>from multiprocessing import Process from pint import UnitRegistry, set_application_regist...
1
2016-07-17T03:05:53Z
38,418,040
<p>I never used <code>pint</code> before, but this looked interesting ;-) First thing I noted is that I have no problem if I stick to units explicitly listed by this line:</p> <pre><code>print(dir(ureg.sys.mks)) </code></pre> <p>For example, "hour" and "second" are both in the output of that, and your program runs f...
1
2016-07-17T04:57:16Z
[ "python", "python-multiprocessing", "pint" ]
Dynamically generate Flask routes
38,417,563
<p>I am trying to dynamically generate routes in Flask from a list. I want to dynamically generate view functions and endpoints and add them with <code>add_url_rule</code>.</p> <p>This is what I am trying to do but I get a "mapping overwrite" error:</p> <pre><code>routes = [ dict(route="/", func="index", page="i...
3
2016-07-17T03:14:32Z
38,417,709
<p>You have one problem with two possible solutions. Either:</p> <ol> <li>Have <code>route[func]</code> directly reference a function, not a string. In this case, you don't have to assign anything to <code>app.view_functions</code>.</li> </ol> <p>Or:</p> <ol start="2"> <li><p>Leave out the third argument of <code>ap...
3
2016-07-17T03:44:06Z
[ "python", "flask" ]
Dynamically generate Flask routes
38,417,563
<p>I am trying to dynamically generate routes in Flask from a list. I want to dynamically generate view functions and endpoints and add them with <code>add_url_rule</code>.</p> <p>This is what I am trying to do but I get a "mapping overwrite" error:</p> <pre><code>routes = [ dict(route="/", func="index", page="i...
3
2016-07-17T03:14:32Z
38,418,023
<p>Not too familiar with Flask, so it is possible that there is a cleaner way to do this. (If someone who is knowledgeable about Flask thinks that my method is inherently wrong, I'll gladly delete my answer if they explain why in a comment.) Now that I got that disclaimer out of the way, here are my thoughts:</p> <p><...
2
2016-07-17T04:53:12Z
[ "python", "flask" ]
Dynamically generate Flask routes
38,417,563
<p>I am trying to dynamically generate routes in Flask from a list. I want to dynamically generate view functions and endpoints and add them with <code>add_url_rule</code>.</p> <p>This is what I am trying to do but I get a "mapping overwrite" error:</p> <pre><code>routes = [ dict(route="/", func="index", page="i...
3
2016-07-17T03:14:32Z
38,418,151
<p>This is how i got it to work @this-vidor and @PZP, the get page method is querying an sqlite db (but it could be any db), the generic function def is being looped over and in my actual code list of dictionaries is also being pulled from a db. So basically what I accomplished what I needed. The routes are dynamic. I ...
0
2016-07-17T05:20:25Z
[ "python", "flask" ]
How to trace what cause "IndexError: list index out of range" and how to find prod(column)?
38,417,565
<p>Here is the list and I have already convert it to 20 x 20 list.. ?</p> <pre><code>import numpy as np a = \ '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 '\ '49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 '\ '81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 '\ '52 70 95 23 04 ...
0
2016-07-17T03:14:40Z
38,417,649
<p>First, your initialization of the array could be done much easier:</p> <pre><code>aa = np.array(list(map(int, a.split())), dtype = np.int) aa.shape = [20, 20] </code></pre> <p>You used <code>][</code>, which means that first you create a view of 4 rows, then you try to select the 19th row from this -- obviously no...
0
2016-07-17T03:31:39Z
[ "python", "python-3.x" ]
While loop incrementer not functioning properly
38,417,577
<p>Right now, my code is correctly spitting out the first game (identified by start_id) in games. I am trying to increment in the bottom two lines, but the while loop doesn't seem to read the fact that I'm incrementing. So the input of this with start_id 800 and end_id 802 is just the information from 800, for some rea...
0
2016-07-17T03:18:17Z
38,417,713
<p>Your problem is that you initialize the increment-er <code>i</code> inside the <code>while</code> loop so every time your loop iterates <code>i</code> is reset to zero.</p> <p>Try changing it to:</p> <pre><code>i = 0 while start_id &lt; (end_id + 1): ... </code></pre>
0
2016-07-17T03:44:49Z
[ "python", "while-loop", "iteration", "increment" ]
write console output to excel sheet using DataFrame python
38,417,609
<pre><code>for foo in root.finadall(xpath): print (foo.name[xpath], foo.country[xpath]) df = DataFrame({'Name': foo.name[xpath], 'conutry': foo.country[xpath]}) df.to_excel('foo.xlsx', sheet_name='sheet1', index=False) </code></pre> <p>The output prints the lots of names in the console. But In exc...
0
2016-07-17T03:23:10Z
38,419,139
<p>You are overwriting your excel file in each iteration of the loop, so try to collect all your data first, then generate a single DataFrame based on collected data and save it as Excel</p> <pre><code>DataFrame({'Name': collected_data_list}).to_excel('foo.xlsx', sheet_name='sheet1', index=False) </code></pre> <p>PS ...
1
2016-07-17T08:04:54Z
[ "python", "pandas", "dataframe", "python-3.5" ]
Why is timeit slower when called from a python file with map and a predefined function over being called via cli with map and a lambda expression?
38,417,622
<p>I am checking whether lambda expressions are faster compared to predefined functions. Here is my code to test predefined function</p> <pre><code>import timeit def ad(x): return x + 2 def test(): xs = range(10) map(ad, xs) print timeit.timeit("test()", setup="from __main__ import ad, test") </code><...
0
2016-07-17T03:25:36Z
38,417,650
<p>In your commandline version, you're creating the <code>xs</code> list in your setup code, so it's creation is not getting timed. In the non-commandline version, <code>xs</code> is created within <code>test</code> which is the function being timed. Because of this, the two versions aren't timing the same thing.</p>...
1
2016-07-17T03:31:45Z
[ "python" ]
Finding if user input has key words from a list
38,417,627
<p>My code:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) if answer in positiveList: print "Pass" else: print "FAIL" </code></pre> <p>What I'm trying to figure out is if the user inp...
0
2016-07-17T03:26:34Z
38,417,651
<p>You should change the code to:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) flag = 0 for word in positiveList: if word in answer: flag = 1 break if flag == 1: print...
0
2016-07-17T03:31:57Z
[ "python", "python-2.7" ]
Finding if user input has key words from a list
38,417,627
<p>My code:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) if answer in positiveList: print "Pass" else: print "FAIL" </code></pre> <p>What I'm trying to figure out is if the user inp...
0
2016-07-17T03:26:34Z
38,417,653
<p>One possible answer:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) if any(word in answer for word in positiveList): print "Pass" else: print "FAIL" </code></pre> <p>Note that "nic...
0
2016-07-17T03:32:42Z
[ "python", "python-2.7" ]
Finding if user input has key words from a list
38,417,627
<p>My code:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) if answer in positiveList: print "Pass" else: print "FAIL" </code></pre> <p>What I'm trying to figure out is if the user inp...
0
2016-07-17T03:26:34Z
38,417,685
<p>If you use sets, then no looping or list comprehension is necessary:</p> <pre><code>positiveList = set(('love', 'nice', 'relaxing', 'okay')) print "How is the weather?" answer = str(raw_input()).lower() if set(answer.split()).intersection(positiveList): print "Pass" else: print "FAIL" </code></pre> <p>Th...
1
2016-07-17T03:40:27Z
[ "python", "python-2.7" ]
Finding if user input has key words from a list
38,417,627
<p>My code:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) if answer in positiveList: print "Pass" else: print "FAIL" </code></pre> <p>What I'm trying to figure out is if the user inp...
0
2016-07-17T03:26:34Z
38,417,748
<p>This statement, # if answer in positiveList: is incorrect because if you type "i love it," it will compare the whole phase with the list. Use smarx's method.</p>
-1
2016-07-17T03:53:01Z
[ "python", "python-2.7" ]
Finding if user input has key words from a list
38,417,627
<p>My code:</p> <pre><code>positiveList = ['love', 'nice', 'relaxing', 'okay'] negativeList = ['hate', "don't like", 'not good'] print "How is the weather?" answer = str(raw_input()) if answer in positiveList: print "Pass" else: print "FAIL" </code></pre> <p>What I'm trying to figure out is if the user inp...
0
2016-07-17T03:26:34Z
38,417,869
<p>If you have the module re (I'd recommend it if you do that much with text), you could do this:</p> <pre><code>import re positiveList = ['love','nice'] answer = input() passList = [word for word in positiveList if re.search(word, answer)] </code></pre> <p>The line above assigns the words from postiveList which mat...
1
2016-07-17T04:18:01Z
[ "python", "python-2.7" ]
transfer dictionary to DataFrame?
38,417,647
<p>I have following dictionary, how can I transform it into a four column DataFrame? (columns=['country','date','2y','10y']</p> <pre><code>temp {'Germany': date 2y 10y 0 2004-02-01 2.47 4.22 1 2004-03-01 2.22 4.05 2 2004-04-01 2.20 3.96 .. ... ... ... 149 ...
1
2016-07-17T03:30:54Z
38,417,740
<p>It seems that your dictionary has data frame as values. If that is the case, one way to reduce the dictionary to a data frame is to loop through the dictionary, create a new column for each sub dictionary and concatenate them:</p> <pre><code>import pandas as pd df = pd.DataFrame() for k, v in temp.items(): v['c...
1
2016-07-17T03:50:56Z
[ "python", "pandas" ]
transfer dictionary to DataFrame?
38,417,647
<p>I have following dictionary, how can I transform it into a four column DataFrame? (columns=['country','date','2y','10y']</p> <pre><code>temp {'Germany': date 2y 10y 0 2004-02-01 2.47 4.22 1 2004-03-01 2.22 4.05 2 2004-04-01 2.20 3.96 .. ... ... ... 149 ...
1
2016-07-17T03:30:54Z
38,417,980
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and <code>rename</code>:</p> <pre><...
2
2016-07-17T04:43:05Z
[ "python", "pandas" ]
Connecting to YouTube API and download URLs - getting KeyError
38,417,664
<p>My goal is to connect to Youtube API and download the URLs of specific music producers.I found the following script which I used from the following link: <a href="https://www.youtube.com/watch?v=_M_wle0Iq9M" rel="nofollow">https://www.youtube.com/watch?v=_M_wle0Iq9M</a>. In the video the code works beautifully. But ...
0
2016-07-17T03:34:12Z
38,423,609
<p>The problem is most likely a combination of using an RTF file instead of a plain text file for the API key and you seem to be confused whether to use urllib or urllib2 since you imported both. </p> <p>Personally, I would recommend <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>, but...
0
2016-07-17T16:49:11Z
[ "python" ]
Why am I getting a syntax error for this conditional statement in Python?
38,417,677
<p>I've recently been practicing using map() in Python 3.5.2, and when I tried to run the module it said the comma separating the function and the iterable was a syntax error. Here's the code:</p> <pre><code>eng_swe = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"Ã¥r"} d...
0
2016-07-17T03:37:34Z
38,417,692
<p>In your first example, you don't specify what should be returned if the condition <em>isn't</em> true. Since python <em>can't</em> yield nothing from an expression, that is a syntax error. e.g:</p> <pre><code>a if b # SyntaxError. a if b else c # Ok. </code></pre> <p><sup>You might argue that it could be usefu...
4
2016-07-17T03:41:33Z
[ "python", "python-3.x", "lambda", "syntax-error", "map-function" ]
Why am I getting a syntax error for this conditional statement in Python?
38,417,677
<p>I've recently been practicing using map() in Python 3.5.2, and when I tried to run the module it said the comma separating the function and the iterable was a syntax error. Here's the code:</p> <pre><code>eng_swe = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"Ã¥r"} d...
0
2016-07-17T03:37:34Z
38,417,698
<p>You're getting the <code>SyntaxError</code> because you're using a conditional expression without supplying the <code>else</code> clause which is mandatory. </p> <p><a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow">The grammar</a> for conditional expressions (i.e ...
3
2016-07-17T03:41:51Z
[ "python", "python-3.x", "lambda", "syntax-error", "map-function" ]
Why am I getting a syntax error for this conditional statement in Python?
38,417,677
<p>I've recently been practicing using map() in Python 3.5.2, and when I tried to run the module it said the comma separating the function and the iterable was a syntax error. Here's the code:</p> <pre><code>eng_swe = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"Ã¥r"} d...
0
2016-07-17T03:37:34Z
38,417,918
<p>While the others' explanations of why your code is causing a <code>SyntaxError</code> are completely accurate, the goal of my answer is to aid you in your goal "to at least learn how to use map() correctly."</p> <p>Your use of <code>map</code> in this context does not make much sense. As you noted in your answer it...
0
2016-07-17T04:30:03Z
[ "python", "python-3.x", "lambda", "syntax-error", "map-function" ]
Purpose of some boilerplate code in __main__.py
38,417,694
<p>I've seen the following code in a couple Python projects, in <code>__main__.py</code>. Could someone explain the purpose? Of course it puts the directory containing <code>__main__.py</code> at the head of <code>sys.path</code>, but why? And why the tests (<code>__package__ is None and not hasattr(sys, 'frozen')</cod...
0
2016-07-17T03:41:38Z
38,417,741
<p><code>os.path.dirname(os.path.dirname(path))</code> - Gets the grand-parent directory (the directory containing the directory of the given <code>path</code> variable); this is being added to the system's <code>PATH</code> variable.</p> <p><code>os.path.realpath(os.path.abspath(__file__))</code> - Gets the <code>rea...
2
2016-07-17T03:50:58Z
[ "python", "main", "pythonpath" ]
Purpose of some boilerplate code in __main__.py
38,417,694
<p>I've seen the following code in a couple Python projects, in <code>__main__.py</code>. Could someone explain the purpose? Of course it puts the directory containing <code>__main__.py</code> at the head of <code>sys.path</code>, but why? And why the tests (<code>__package__ is None and not hasattr(sys, 'frozen')</cod...
0
2016-07-17T03:41:38Z
38,417,803
<p>The test for <code>__package__</code> lets the code run when <code>package/__main__.py</code> has been run with a command like <code>python __main__.py</code> or <code>python package/</code> (naming the file directly or naming the package folder's path), not the more normal way of running the main module of a packag...
1
2016-07-17T04:04:16Z
[ "python", "main", "pythonpath" ]
Application wrapper for Mac app to log open and close times for files (launch using double click)
38,417,712
<p>Here's my specific problem. I use Mplayer OSX to open video files. I want to do the following: when I double click a video file, it opens in Mplayer OSX but additionally it also logs the name of the file (plus time, etc) to some log file. The main problem is that I want all this to happen on double clicking the vide...
0
2016-07-17T03:44:37Z
38,419,403
<p>I suggest you try the following:</p> <ol> <li><p>Pack your python script (that starts <code>MPlayer</code> and logs the time for you) as an application package for Mac OS X. You can do that with: <a href="https://pythonhosted.org/py2app/" rel="nofollow"><code>py2app</code></a></p> <pre><code># install py2app pip i...
0
2016-07-17T08:41:14Z
[ "python", "osx", "video", "logging", "double-click" ]
Are there anything similar to "perl -pe" option in python?
38,417,743
<p><strong>TL;DR I want to know what is an option in Python, which might roughly correspond to the "-pe" option in Perl.</strong></p> <p>I used to use PERL for some time, but these days, I have been switching to PYTHON for its easiness and simplicity. When I needed to do simple text processing on the shell prompt, I ...
4
2016-07-17T03:51:39Z
38,417,923
<p><code>-pe</code> is a combination of two arguments, <code>-p</code> and <code>-e</code>. The <code>-e</code> option is roughly equivalent to Python's <code>-c</code> option, which lets you specify code to run on the command line. There is no Python equivalent of <code>-p</code>, which effectively adds code to run ...
3
2016-07-17T04:31:45Z
[ "python", "shell" ]
Are there anything similar to "perl -pe" option in python?
38,417,743
<p><strong>TL;DR I want to know what is an option in Python, which might roughly correspond to the "-pe" option in Perl.</strong></p> <p>I used to use PERL for some time, but these days, I have been switching to PYTHON for its easiness and simplicity. When I needed to do simple text processing on the shell prompt, I ...
4
2016-07-17T03:51:39Z
38,417,978
<p>Perl, although a fully fledged as programming language, was initially thought, and evolved as, a tool for text manipulation.</p> <p>Python, on th other hand, has always been a general purpose programing language. It can handle text and text flexibility, with enormous flexibility, when compared with, say Java or C++...
1
2016-07-17T04:42:49Z
[ "python", "shell" ]
Are there anything similar to "perl -pe" option in python?
38,417,743
<p><strong>TL;DR I want to know what is an option in Python, which might roughly correspond to the "-pe" option in Perl.</strong></p> <p>I used to use PERL for some time, but these days, I have been switching to PYTHON for its easiness and simplicity. When I needed to do simple text processing on the shell prompt, I ...
4
2016-07-17T03:51:39Z
38,418,909
<p>It's a little more wordy in Python but not as wordy as other's suggest if you're simply manipulating strings rather than patterns:</p> <pre><code>&gt; grep "foo" *.txt | python3 -c "while True: exec('''try: print(input().replace('foo','bar'))\nexcept: exit(0)''')" </code></pre> <p>I miss the -p feature of Perl in ...
0
2016-07-17T07:30:19Z
[ "python", "shell" ]
An if statement for an array
38,417,783
<p>How do I make a two dimensional array an if statement.</p> <pre><code>for row in range(6): for column in range(7): if board[row][column] &gt; 0: Draw = True </code></pre> <p>I have a grid of blank squares, 7 by 6, and if a square is clicked its given a value of 1 and if not it stays 0. When...
-1
2016-07-17T03:59:40Z
38,417,808
<p>If you mean check the whole board if all are 1's, then its a simple fix.</p> <pre><code>DRAW = True for row in range(6): for column in range(7): if board[row][column] == 0: DRAW = False </code></pre> <p>Going about it the other way is easier.</p>
1
2016-07-17T04:05:22Z
[ "python", "arrays", "python-3.x", "if-statement" ]
An if statement for an array
38,417,783
<p>How do I make a two dimensional array an if statement.</p> <pre><code>for row in range(6): for column in range(7): if board[row][column] &gt; 0: Draw = True </code></pre> <p>I have a grid of blank squares, 7 by 6, and if a square is clicked its given a value of 1 and if not it stays 0. When...
-1
2016-07-17T03:59:40Z
38,417,818
<p>What you want is only when all <code>board</code> values are 1, the <code>Draw</code> is set to True. You code will set <code>Draw</code> to 1 if there is ANY grid clicked.</p> <p>The solution is simple, you can think reversely, preset the <code>Draw</code> to True and whenever the grid is not 1, set it to False.</...
1
2016-07-17T04:07:30Z
[ "python", "arrays", "python-3.x", "if-statement" ]
An if statement for an array
38,417,783
<p>How do I make a two dimensional array an if statement.</p> <pre><code>for row in range(6): for column in range(7): if board[row][column] &gt; 0: Draw = True </code></pre> <p>I have a grid of blank squares, 7 by 6, and if a square is clicked its given a value of 1 and if not it stays 0. When...
-1
2016-07-17T03:59:40Z
38,417,820
<p>If you need to check that all values in a collection have a value that is <code>True</code> you could always use the built in <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a> function which checks that all values in an iterable satisfy a given condition (which, in ...
1
2016-07-17T04:07:59Z
[ "python", "arrays", "python-3.x", "if-statement" ]
An if statement for an array
38,417,783
<p>How do I make a two dimensional array an if statement.</p> <pre><code>for row in range(6): for column in range(7): if board[row][column] &gt; 0: Draw = True </code></pre> <p>I have a grid of blank squares, 7 by 6, and if a square is clicked its given a value of 1 and if not it stays 0. When...
-1
2016-07-17T03:59:40Z
38,417,824
<p>You can use <code>all</code> as another way to @Wboy's forloop:</p> <pre><code>all(x for y in z for x in y) #or x !=0 but that's redundant here since 1 equates to True. </code></pre> <p>Here, z would be your two dimensional list. You can evaluate uneven dimensions this way as well without getting "bogged" down in...
1
2016-07-17T04:08:32Z
[ "python", "arrays", "python-3.x", "if-statement" ]
Extracting hidden element in Selenium
38,417,787
<p>I have an element of type <code>hidden</code> in an iframe. I am wondering if there would be any way to get this value as I am using selenium. More specifically it is a captcha field. I've tried pulling it with something along the lines of </p> <pre><code>#!/usr/bin/env python from selenium import webdriver driver...
-1
2016-07-17T04:00:12Z
38,417,867
<pre><code>driver.switch_to_frame('undefined') token_value = driver.find_element_by_id('recaptcha-token').get_attribute('value') driver.switch_to_default_content() </code></pre> <p><a href="http://selenium-python.readthedocs.io/navigating.html#moving-between-windows-and-frames" rel="nofollow">Moving between windows an...
2
2016-07-17T04:17:41Z
[ "python", "html", "selenium", "captcha", "recaptcha" ]
Python sqlite loop index out of range
38,417,960
<pre><code>dbCursor = dbConnection.execute("SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL") dbCursor1 = dbConnection.execute("SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL") myList = dbCu...
0
2016-07-17T04:40:13Z
38,418,006
<p>Check your SQL queries are correct (hint: you only need one cursor since your queries are the same) and print out the result of <code>fetchall</code>, then try this to print out the rows and their indices. </p> <pre><code>for i, row in enumerate(dbCursor.fetchall()): print(i, row) </code></pre> <p>Although, yo...
0
2016-07-17T04:48:53Z
[ "python", "sqlite", "loops" ]
Python sqlite loop index out of range
38,417,960
<pre><code>dbCursor = dbConnection.execute("SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL") dbCursor1 = dbConnection.execute("SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL") myList = dbCu...
0
2016-07-17T04:40:13Z
38,463,822
<p>cricket_007 explained that obtaining <code>len</code> from cursor changes cursor, so I changed code adding one more cursor. Now no more <code>out of range</code>:</p> <pre><code>mySQL = "SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL" dbCursor = dbCo...
0
2016-07-19T16:21:22Z
[ "python", "sqlite", "loops" ]
Runnuing a python script within another script many times
38,418,002
<p>I have a python script that includes some data:</p> <p>-My_Directory/Data.py:</p> <pre><code>Parameter=10 </code></pre> <p>I also have a <code>Main.py</code> script, in which the <code>Data.py</code> should be called many times:</p> <p>My_Directory/Main.py</p> <pre><code>call the Data.py to access parameter Ma...
0
2016-07-17T04:48:35Z
38,418,102
<h2>reading parameters from another file</h2> <p>you can use</p> <pre><code>import Data </code></pre> <p>or</p> <pre><code>from Data import * </code></pre> <p>to explicitly import all the variables and functions of the <code>Data.py</code>. (if the importing file is in the same dir)</p> <p>or if you want to impor...
1
2016-07-17T05:11:38Z
[ "python", "multifile" ]
Runnuing a python script within another script many times
38,418,002
<p>I have a python script that includes some data:</p> <p>-My_Directory/Data.py:</p> <pre><code>Parameter=10 </code></pre> <p>I also have a <code>Main.py</code> script, in which the <code>Data.py</code> should be called many times:</p> <p>My_Directory/Main.py</p> <pre><code>call the Data.py to access parameter Ma...
0
2016-07-17T04:48:35Z
38,418,220
<p>You can also use <code>execfile(filename)</code>, where everything is added to the current namespace.</p> <p><strong>Main.py</strong></p> <pre><code>while True: execfile('Data.py') if Parameter &lt; whatever: #depends on your needs Parameter -= 1 # depends on your needs f = open('Data.py','w') ...
1
2016-07-17T05:35:31Z
[ "python", "multifile" ]
Python behavior in loops
38,418,058
<p>I have the following code: </p> <pre><code>a = ['bobby', 'freddy', 'jason'] b = ['pep', 'lin', 'cat'] for a in b: for b in a: print a,b </code></pre> <p>I'd assume that after the first iteration of the outer loop, since the global variable <code>b</code> has been modified, and is now a <code>...
2
2016-07-17T05:01:06Z
38,418,085
<blockquote> <p>when the for loop is created, does it store a copy of the iterator and then loop through that even if the original variable now "points" to a different value?</p> </blockquote> <p>Yes! You identified it correctly. Typically, when such looping constructs occur, the interpreter calls <a href="https://d...
3
2016-07-17T05:07:46Z
[ "python", "loops", "iteration" ]
Python behavior in loops
38,418,058
<p>I have the following code: </p> <pre><code>a = ['bobby', 'freddy', 'jason'] b = ['pep', 'lin', 'cat'] for a in b: for b in a: print a,b </code></pre> <p>I'd assume that after the first iteration of the outer loop, since the global variable <code>b</code> has been modified, and is now a <code>...
2
2016-07-17T05:01:06Z
38,418,411
<p>Just to add, you can think of the <em>iterator protocol</em>, which controls the for-loop, to work like the following Python code:</p> <pre><code>iterator = iter(collection) while True: try: x = next(iterator) # do something except StopIteration as e: break </code></pre> <p>Thus, th...
0
2016-07-17T06:05:43Z
[ "python", "loops", "iteration" ]
how to use 'redirect' and 'message' on django, python
38,418,065
<p>I am following the following tutorial link in order to create a page where there is login box, as well as a post form.</p> <p>what im trying to accomplish here is to have only the people who are logged into the site be able to write on the post form, and submit the content.</p> <p><a href="https://docs.djangoproje...
0
2016-07-17T05:03:47Z
38,418,675
<p>As I understand, in simplest case you need something like this.</p> <pre><code>from django import forms from django.contrib.auth import authenticate class AuthenticationForm(forms.Form): username = forms.CharField(max_length=254) password = forms.CharField(widget=forms.PasswordInput) def clean(self): ...
1
2016-07-17T06:53:44Z
[ "python", "django" ]
What does !r do in str() and repr()?
38,418,070
<p>According to the <a href="https://docs.python.org/2/tutorial/inputoutput.html#fancier-output-formatting" rel="nofollow">Python 2.7.12 documentation</a>:</p> <blockquote> <p><code>!s</code> (apply <code>str()</code>) and <code>!r</code> (apply <code>repr()</code>) can be used to convert the value before it is fo...
0
2016-07-17T05:04:42Z
38,418,132
<p>In order to format something <em>in</em> a string, a string representation of that something must first be created. "convert the value" is basically talking about how the string representation is to be constructed. In python, there are two fairly natural choices to get a string representation of something ... <cod...
1
2016-07-17T05:15:53Z
[ "python", "string", "python-2.7", "formatting", "repr" ]
How do I control a python script through a web interface?
38,418,140
<p>For a college project I'm tasked with getting a Raspberry Pi to control an RC car over WiFi, the best way to do this would be through a web interface for the sake of accessibility (one of the key reqs for the module). However I keep hitting walls, I can make a python script control the car, however doing this throug...
0
2016-07-17T05:18:03Z
38,418,381
<p>I can suggest a way to handle that situation but I'm not sure how much will it suit for your scenario.</p> <p>Since you are trying to use a wifi network, I think it would be better if you can use a sql server to store commands you need to give to the vehicle to follow from the web interface sequentially. Make the v...
0
2016-07-17T06:00:32Z
[ "javascript", "python", "html", "raspberry-pi2" ]
Get a value from solution set returned as finiteset by Sympy
38,418,205
<p>I`m creating a script in Python Sympy library and trying to access the result returned by solveset() and linsolve() functions. My problem is that the object returned by these functions is of type finiteset and I want to select some results automaticaly to re-enter it in other equations. Any body could help me...
2
2016-07-17T05:33:00Z
38,423,159
<p>You can use <code>iter</code> to get an iterator based on the set, and then <code>next</code> to return one element of that set (if you only need one element).</p> <p>Example:</p> <pre><code>from sympy import * var('x y') sol = linsolve([x+y-2, 2*x-3*y], x, y) (x0, y0) = next(iter(sol)) </code></pre> <p>Now x0 is...
1
2016-07-17T15:59:09Z
[ "python", "sympy" ]
How to mount local host directory in docker container using remote api
38,418,319
<p>So I'm using the docker remote api. I'm sending request from the host machine that's running the docker and it's listening on localhost and the usually unix socket.</p> <p>So instead of using the docker cli command to start a container. I'm using <code>POST /containers/create</code> and <code>POST /containers/(id o...
2
2016-07-17T05:51:35Z
38,422,522
<p>You need to send the following request, followed by a start:</p> <pre><code>POST /containers/create?name=web HTTP/1.1 Content-Type: application/json { "Cmd": [ "python", "app.py" ], "Image": "training/webapp", "Volumes": { "/webapp": {} }, } </code></pre>
1
2016-07-17T14:50:58Z
[ "python", "api", "docker" ]
Trouble with time requirement for url opening using python
38,418,497
<p>I have designed a python program that will open a url and fetch data like email and numbers from that url. Main problem is that it is very slow, I want to know if there is a way to increase speed of fetching data from url.</p> <p>Some specifications:</p> <ol> <li>Program is in python. </li> <li>I am using urllib2...
0
2016-07-17T06:19:17Z
38,418,548
<p>What are you doing now? without seeing what exactly your program is doing its hard to say exactly.</p> <p>but</p> <p>In general try to limit calls to urls, if your fetching lots of data from a page try to grab everything you'll need at once and save it to a variable, that way if your making multiple calls it takes...
0
2016-07-17T06:29:45Z
[ "python", "beautifulsoup" ]
Error when redirecting from Facebook login with python-social-auth, SqlAlchemy and Flask
38,418,546
<p>I am trying to implement social login in Flask using python-social-auth. It works in development on localhost, but not in production.</p> <p>The error occurs when redirecting from login with Facebook. After debugging it seems to be caused by decoding in sql type pickle or json. I dug into the <code>json</code> mod...
1
2016-07-17T06:29:08Z
38,740,957
<p>just do dirty fix at sqltype.py of sqlalchemy package after debugging. I found out the different of type of value in method below. so I decided to skip and return the value if it is already dict. </p> <pre><code>1245 def result_processor(self, dialect, coltype): 1246 impl_processor = self.impl.result_pr...
0
2016-08-03T10:26:17Z
[ "python", "facebook", "flask", "sqlalchemy", "python-social-auth" ]
Creating a delete button for each record
38,418,713
<p>I have a website which I have a bunch of records in the database. There are two fields, <code>Name</code> and <code>Comment</code>. <code>models.py</code>:</p> <pre><code>class Db_test(models.Model): name = models.CharField(max_length=50) comment = models.CharField(max_length=200) created = models.DateF...
0
2016-07-17T07:00:02Z
38,419,104
<p>I would suggest a different approach altogether. </p> <p>In your view, pass the object itself:</p> <pre><code>objects = Db_test.objects.all() return render(request, "models_test/delete.html", {"values": objects}) </code></pre> <p>In your template:</p> <pre><code>{% for obj in object %} &lt;form method="POST"...
1
2016-07-17T07:58:52Z
[ "python", "django", "post" ]
How to remove a dict objects(letter) that remain in another str?
38,418,765
<p>Suppose I have this dictionary:</p> <pre><code>x = {'a':2, 'b':5, 'g':7, 'a':3, 'h':8}` </code></pre> <p>And this input string:</p> <pre><code>y = 'agb' </code></pre> <p>I want to delete the keys of <code>x</code> that appear in <code>y</code>, such as, if my input is as above, output should be:</p> <pre><code>...
-3
2016-07-17T07:07:37Z
38,418,846
<p>You're close, but try this instead:</p> <pre><code>def x_remove(input_dict, word): output_dict = input_dict.copy() for letter in word: if letter in output_dict: del output_dict[letter] return output_dict </code></pre> <p>For example:</p> <pre><code>In [10]: x_remove({'a':...
1
2016-07-17T07:21:06Z
[ "python", "python-2.7", "dictionary" ]
How to remove a dict objects(letter) that remain in another str?
38,418,765
<p>Suppose I have this dictionary:</p> <pre><code>x = {'a':2, 'b':5, 'g':7, 'a':3, 'h':8}` </code></pre> <p>And this input string:</p> <pre><code>y = 'agb' </code></pre> <p>I want to delete the keys of <code>x</code> that appear in <code>y</code>, such as, if my input is as above, output should be:</p> <pre><code>...
-3
2016-07-17T07:07:37Z
38,418,905
<p>Dictionary must have unique keys. You may use list of tuples for your data instead.</p> <p><code>x = [('a',2), ('b',5), ('g',7), ('a',3), ('h',8)]</code></p> <p>Following code then deletes the desired entries:</p> <pre><code>for letter in y: idx = 0 for item in x.copy(): if item[0] == letter: ...
1
2016-07-17T07:29:57Z
[ "python", "python-2.7", "dictionary" ]