title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
TypeError when converting Pandas to Spark | 39,862,211 | <p>So I have looked up this question on here but previous solutions have not worked for me. I have a DataFrame in this format</p>
<pre><code>mdf.head()
dbn boro bus
0 17K548 Brooklyn B41, B43, B44-SBS, B45, B48, B49, B69
1 09X543 Bronx Bx13, Bx15, Bx17, Bx21, Bx35, Bx4, Bx41, Bx4A,...
4 ... | 0 | 2016-10-04T21:40:38Z | 39,862,349 | <p>You could use reflection to infer the schema from an RDD of <code>Row</code> objects, e.g., </p>
<pre><code>from pyspark.sql import Row
mdfRows = mdf.map(lambda p: Row(dbn=p[0], boro=p[1], bus=p[2]))
dfOut = sqlContext.createDataFrame(mdfRows)
</code></pre>
<p>Does that achieve the desired result? </p>
| 0 | 2016-10-04T21:51:20Z | [
"python",
"pandas",
"apache-spark",
"pyspark"
] |
NMaximize in Mathematica equivalent in Python | 39,862,283 | <p>I am trying to find a equivalent of "NMaximize" optimization command in Mathematica in Python. I tried googling but did not help much. </p>
| 0 | 2016-10-04T21:46:25Z | 39,863,045 | <p>The <a href="https://reference.wolfram.com/language/ref/NMaximize.html" rel="nofollow">mathematica docs</a> describe the methods usable within <code>NMaximize</code> as: <code>Possible settings for the Method option include "NelderMead", "DifferentialEvolution", "SimulatedAnnealing", and "RandomSearch".</code>.</p>
... | 2 | 2016-10-04T23:01:46Z | [
"python",
"optimization",
"wolfram-mathematica",
"mathematical-optimization"
] |
Tensorflow: Why Doesn't Out of Graph Cost Calculation Work | 39,862,366 | <p>I have a standard experiment loop that looks like this:</p>
<pre class="lang-py prettyprint-override"><code>cross_entropy_target = tf.reduce_mean(tf.reduce_mean(tf.square(target_pred - target)))
cost = cross_entropy_target
opt_target = tf.train.AdamOptimizer(learning_rate=0.00001).minimize(cost)
for epoch in range(... | 0 | 2016-10-04T21:53:01Z | 39,878,048 | <p>In your <code>tf.train.AdamOptimizer(</code> line, it looks at <code>cost</code>, which is <code>cross_entropy_target</code>, which is a <code>tf.Variable</code> op, and creates an optimizer which does nothing, since <code>cross_entropy_target</code> doesn't depend on any variables. Modifying <code>cross_entropy</co... | 1 | 2016-10-05T15:25:24Z | [
"python",
"tensorflow"
] |
How to maintain or recover Dataframe indexing after running Pairwise Distance function? | 39,862,383 | <p>I'm using sklearn's pairwise distance function, which saved my life when computing a huge matrix, but the problem I'm having is that I lose my indices.</p>
<p>Specifically, I initially have a huge dataframe of 17000 x 300, which I break down into 4 different dataframes based on some class condition.
The 4 separate ... | 1 | 2016-10-04T21:54:55Z | 39,862,542 | <p>You can create a DataFrame with matching indices using the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">DataFrame constructor</a> taking the <code>index</code> parameter:</p>
<pre><code>pd.DataFrame(distance1, index=df1.index)
</code></pre>
<p>Furthermore, if... | 3 | 2016-10-04T22:10:25Z | [
"python",
"pandas",
"indexing",
"dataframe",
"distance"
] |
Failure during project creation using 'djangocms' command | 39,862,388 | <ul>
<li>Django CMS 3.4.1</li>
<li>Django 1.10.2</li>
<li>pip modules: <a href="http://pastebin.com/vJWvZVfA" rel="nofollow">http://pastebin.com/vJWvZVfA</a></li>
<li>pip 8.1.2</li>
<li>Python 2.7.12</li>
<li>OS: Amazon Linux AMI release 2016.03</li>
</ul>
<p>I'm new to Django CMS, Django, and Python. My previous CMS ... | -1 | 2016-10-04T21:55:08Z | 39,862,494 | <p>The error message tells me absolutely nothing. It only tells me that Django tried to use pip to install something and for whatever reason it failed. In order to figure out what went wrong, try enabling verbose mode (python -v). If that gives the same output, or that isn't an option because you're using a program ... | 0 | 2016-10-04T22:06:25Z | [
"python",
"django",
"pip",
"django-cms"
] |
Failure during project creation using 'djangocms' command | 39,862,388 | <ul>
<li>Django CMS 3.4.1</li>
<li>Django 1.10.2</li>
<li>pip modules: <a href="http://pastebin.com/vJWvZVfA" rel="nofollow">http://pastebin.com/vJWvZVfA</a></li>
<li>pip 8.1.2</li>
<li>Python 2.7.12</li>
<li>OS: Amazon Linux AMI release 2016.03</li>
</ul>
<p>I'm new to Django CMS, Django, and Python. My previous CMS ... | -1 | 2016-10-04T21:55:08Z | 39,864,076 | <h1>Original error</h1>
<p>The non-verbose error message indicates the error in a cryptic way, and using --verbose provides a more understandable message.</p>
<p>I was missing one required module (psycopg2) and four others were versions which were too new (easy_thumbnails, Django, html5lib, django-select2).</p>
<p>I... | 0 | 2016-10-05T01:24:20Z | [
"python",
"django",
"pip",
"django-cms"
] |
How to disable vertical / horizontal mouse movement in pygame? | 39,862,440 | <p>I want to prevent an object from moving vertically on the surface when moving the mouse around while horizontal movements will still be allowed. </p>
<p>How do I do that?</p>
<p>I have managed to let the object move around freely using:</p>
<pre><code> if event.type == pygame.MOUSEMOTION:
x... | 0 | 2016-10-04T22:00:37Z | 39,862,497 | <p>I don't remember much of Pygame, so I might be missing something, but it looks kinda obvious:</p>
<pre><code>if event.type == pygame.MOUSEMOTION:
x = event.pos[0]
</code></pre>
| 0 | 2016-10-04T22:06:34Z | [
"python",
"python-3.x",
"pygame"
] |
Directly write to encrypted file in Python | 39,862,516 | <p>In python, using the gnupg package, is it possible to take a value in memory, then write it an encrypted file rather than writing to file THEN encrypting? </p>
<p>I was hoping something like this would work:</p>
<pre><code>import gnupg
gpg = gnupg.GPG(gnupghome='keydirectory')
l = [['a', '1'], ['b', '2'], ['c',... | 1 | 2016-10-04T22:08:28Z | 39,862,581 | <p>Just use the <code>gpg.encrypt()</code> function instead of <code>encrypt_file()</code> and then write to a file.</p>
| 0 | 2016-10-04T22:13:24Z | [
"python",
"gnupg"
] |
Directly write to encrypted file in Python | 39,862,516 | <p>In python, using the gnupg package, is it possible to take a value in memory, then write it an encrypted file rather than writing to file THEN encrypting? </p>
<p>I was hoping something like this would work:</p>
<pre><code>import gnupg
gpg = gnupg.GPG(gnupghome='keydirectory')
l = [['a', '1'], ['b', '2'], ['c',... | 1 | 2016-10-04T22:08:28Z | 40,126,111 | <p>The <a href="https://python-gnupg.readthedocs.io/en/latest/gnupg.html#gnupg.GPG.encrypt" rel="nofollow">documentation for the <code>GPG.encrypt</code> method</a> shows that is what you want.</p>
<pre class="lang-python prettyprint-override"><code>>>> import gnupg
>>> gpg = gnupg.GPG(homedir="doct... | 0 | 2016-10-19T08:33:35Z | [
"python",
"gnupg"
] |
Determine default protocol version used by SSL package? | 39,862,559 | <p>In python, how can I determine which SSL or TLS protocol is used by SSL package, or requests, by default.</p>
<p>As in, say TLSv1 vs SSLv3.</p>
| 1 | 2016-10-04T22:11:38Z | 40,070,533 | <p>The <a href="https://docs.python.org/2/library/ssl.html#socket-creation" rel="nofollow">SSL socket creation</a> section of the Python docs has the information on the SSL package:</p>
<blockquote>
<p>The parameter <code>ssl_version</code> specifies which version of the SSL
protocol to use. Typically, the server ... | 0 | 2016-10-16T13:00:52Z | [
"python",
"ssl",
"python-requests",
"pyopenssl"
] |
How to redirect stdout to screen and at the same time save to a variable | 39,862,573 | <p>I am trying to redirect stdout to screen and at the same time save to a variable and running into error <code>AttributeError: __exit__</code> at line <code>with proc.stdout:</code>,can anyone tell me how to accomplish this?</p>
<pre><code>...............
proc = subprocess.Popen(cmd.split(' '), stderr=subprocess.PIP... | 2 | 2016-10-04T22:12:47Z | 39,862,644 | <p>When creating your Popen object you have the stderr set. When you go to open the stdout subprocess can't open it because you have stderr set instead. You can fix this by either adding <code>stdout=subprocess.PIPE</code> to the Popen object args, or by doing <code>with proc.stderr</code> instead of <code>with proc.st... | 0 | 2016-10-04T22:20:45Z | [
"python"
] |
How to redirect stdout to screen and at the same time save to a variable | 39,862,573 | <p>I am trying to redirect stdout to screen and at the same time save to a variable and running into error <code>AttributeError: __exit__</code> at line <code>with proc.stdout:</code>,can anyone tell me how to accomplish this?</p>
<pre><code>...............
proc = subprocess.Popen(cmd.split(' '), stderr=subprocess.PIP... | 2 | 2016-10-04T22:12:47Z | 39,863,094 | <p>Once you make <code>stdout</code> a <code>PIPE</code> you can just create a loop that reads the pipe and writes it to as many places as you want. Dealing with <code>stderr</code> makes the situation a little trickier because you need a background reader for it also. So, create a thread and a utility that writes to m... | 0 | 2016-10-04T23:07:07Z | [
"python"
] |
pandas.concat of multiple data frames using only common columns | 39,862,654 | <p>I have multiple pandas data frame objects cost1, cost2 , cost3 ....</p>
<ol>
<li>They have different column names (and number of columns) but have some in common.</li>
<li>Number of columns are fairly large in each dataframe, hence handpicking the common columns manually will be painful.</li>
</ol>
<p>How can I ap... | 0 | 2016-10-04T22:21:22Z | 39,862,735 | <p>You can find the common columns with Python's <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set.intersection</code></a>:</p>
<pre><code>common_cols = list(set.intersection(*(set(df.columns) for df in frames)))
</code></pre>
<p>To concatenate using only the common columns, you can use</... | 1 | 2016-10-04T22:28:34Z | [
"python",
"pandas",
"dataframe"
] |
Differences in __dict__ between classes with and without an explicit base class | 39,862,662 | <p>Why does a class that (implicitly) derives from <code>object</code> have more items in its <code>__dict__</code> attribute than a class that has an explicit base class? (python 3.5).</p>
<pre><code>class X:
pass
class Y(X):
pass
X.__dict__
'''
mappingproxy({'__dict__': <attribute '__dict__' of 'X' object... | 2 | 2016-10-04T22:21:52Z | 39,863,089 | <p>The definition of <code>__weakref__</code> and <code>__dict__</code> is so the appropriate descriptor gets invoked to access the "real" location of the weak reference list and the instance dictionary of instances of the class when Python level code looks for it. The base class <code>object</code> is bare bones, and ... | 3 | 2016-10-04T23:06:09Z | [
"python",
"python-3.x"
] |
Generate coordinates in grid that lie within a circle | 39,862,709 | <p>I've found <a href="http://stackoverflow.com/a/12364749/3928184">this answer</a>, which seems to be somewhat related to this question, but I'm wondering if it's possible to generate the coordinates one by one without the additional ~22% (1 - pi / 4) loss of comparing each point to the radius of the circle (by comput... | 0 | 2016-10-04T22:26:22Z | 39,862,846 | <p>What about simply something like this (for a circle at origin)?</p>
<pre><code>X = int(R) # R is the radius
for x in range(-X,X+1):
Y = int((R*R-x*x)**0.5) # bound for y given x
for y in range(-Y,Y+1):
yield (x,y)
</code></pre>
<p>This can easily be adapted to the general case when the circle is no... | 1 | 2016-10-04T22:39:07Z | [
"python",
"generator"
] |
How do I break down this list comprehension in Python? | 39,862,745 | <p>I seen a question earlier on how to find the characters to a specific word from a list of strings. It got deleted I think because I can't find it anymore.</p>
<p>So for example:</p>
<pre><code>>>>findTheLetters(["hello", "world"], "hold")
>>>True
>>>findTheLetters(["hello", "world"], "ho... | 0 | 2016-10-04T22:29:50Z | 39,862,884 | <p>Here's a little educative example to show you what that algorithm is doing behind the curtains:</p>
<pre><code>def findTheLetters(myList, myString):
return all((any(letter in word for word in myList)) for letter in myString)
def findTheLetters1(myList, myString):
res1 = []
for letter in myString:
... | 2 | 2016-10-04T22:43:23Z | [
"python",
"string",
"list",
"python-3.x",
"list-comprehension"
] |
Django not saving the multi-select option from form right | 39,862,882 | <p>I have a form that has a select multiple option for a model with a Many2Many. This seems to work but upon actually using the form if I select multiple things and click save, it only saves one of the items.</p>
<p>The pertinent info int he views.py is located showing where this is happening.</p>
<p>Also the output... | 0 | 2016-10-04T22:43:12Z | 39,862,898 | <p>You might try taking the return statement out of the for loop in your views.py</p>
<pre><code>def form_valid(self, form):
self.object = form.save(commit=False)
ProviderLocations.objects.filter(provider=self.object).delete()
for group_location in form.cleaned_data['group_locations']:
print("here!... | 0 | 2016-10-04T22:45:12Z | [
"python",
"django",
"django-forms",
"django-views"
] |
How do I pause this thread after x minutes | 39,862,982 | <p>How to pause this thread from running every 300 seconds for 500 seconds? I need to suspend it from running all the functions every x minutes to prevent API breaches. Timer objects seem to only start the code, whereas the objective is to pause, wait, resume.</p>
<pre><code>from TwitterFollowBot import TwitterBot
fro... | 1 | 2016-10-04T22:54:30Z | 39,865,064 | <p>Maybe something like this for your threads?</p>
<pre><code>import time
def sleep_thread(sleepWait, sleepTime):
timeStart = time.time()
timeElapsed = 0
while timeElapsed <= sleepWait:
timeElapsed = time.time() - timeStart
print 'time elapsed = ' + str(timeElapsed)
time.slee... | 1 | 2016-10-05T03:41:17Z | [
"python",
"multithreading",
"bots",
"python-multithreading"
] |
how to connect external libraries in Kivy | 39,863,004 | <p>When you try to build the application. Application normally collected and only runs if there is no outside application libraries. When you attempt to connect networkx library. Appendix normally gather. But when you try to run directly on the device. Pops saver "Loadind ..." and the application falls. What you need t... | 0 | 2016-10-04T22:56:13Z | 39,880,918 | <p>In your <code>buildozer.spec</code> file, line <code>39</code> add your third-party requirments.</p>
<pre><code>requirements = kivy,networkx, # or what ever
</code></pre>
| 1 | 2016-10-05T18:07:43Z | [
"android",
"python",
"kivy",
"networkx"
] |
Separate the words by a space in a string using python | 39,863,103 | <pre><code>text = "Avalon:Sydney 04March2009Bondi Street at a conferencemeeting room234".
</code></pre>
<p>I would like to process the above string in such as way that the words are separated and not joined. </p>
<p>I would like the string to be printed as follows:</p>
<p><code>"Avalon Sydney 04 March 2009 Bondi St... | 0 | 2016-10-04T23:08:27Z | 39,863,273 | <p>To replace the colon with a space, use <code>.replace</code>:</p>
<pre><code>text = text.replace(':', ' ')
</code></pre>
<p>To split parts of the text alternating between numbers and letters, you can use a <em>positive look behind</em> to catch words preceded by numbers or numbers preceded by words, and then subst... | 0 | 2016-10-04T23:31:37Z | [
"python"
] |
Slice a dataframe with a hierarchy index | 39,863,176 | <p>I have two dataframes. One has stock transactions (things like buy date, buy price, sell date, sell price). The other dataframe has all the prices in date order with an hierarchy index of <code>['symbol', 'date']</code> indexing <code>'close'</code> price called <code>dfPrice</code>.</p>
<p>Not knowing a better wa... | 0 | 2016-10-04T23:19:36Z | 39,863,609 | <p>There might be a more straightforward way to do so, but I managed to get <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced-indexing-with-hierarchical-index" rel="nofollow">advanced indexing</a> to work using a tuple for your hierarchical indices:</p>
<pre><code>>>> dfPrice[('A','2... | 0 | 2016-10-05T00:17:20Z | [
"python",
"indexing",
"dataframe",
"slice",
"hierarchy"
] |
How to pip install bcrypt on Azure webapp? | 39,863,193 | <p>Disclosure : First time Azure experience</p>
<p>I am deploying a Flask app to Azure Webapp. All deployment steps are fine till I hit the bcrypt package installation and it fails.</p>
<p>After much research based on error log output, I found out that I might need to install bcrypt using wheelhouse (*.WHL)</p>
<p>I... | 0 | 2016-10-04T23:22:21Z | 39,879,209 | <p>I was finally able to get the Flask app working on Azure Webapps.
Unfortunately, I couldn't do it using my usual dev tools. </p>
<p><strong>Solution</strong>:</p>
<ul>
<li>I created a VirtualEnv in Visual Studio using my <code>requirements.txt</code> file</li>
<li>Moved my Flask code to Visual Studio</li>
<li>Clic... | 0 | 2016-10-05T16:23:38Z | [
"python",
"azure",
"pip",
"virtualenv",
"bcrypt"
] |
Display output from python in aspx page | 39,863,217 | <p>Question from a .net newbie</p>
<p>Hello,</p>
<p>I am trying to display output from my python code in aspx page.</p>
<p>Below is .net c# code that executes by the click of Button1.</p>
<pre><code>protected void Button1_Click1(object sender, EventArgs e)
{
ScriptEngine eng = Python.CreateEngine();
dynamic... | 0 | 2016-10-04T23:25:48Z | 39,863,950 | <p>You can put all your result in variable a</p>
<p>Example:</p>
<p>Python</p>
<pre><code>a = ""
a += "hello world\n"
a += "==========="
</code></pre>
<p>In C#</p>
<pre><code>ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(@"C:\path\hello.py", scope);
var r... | 0 | 2016-10-05T01:05:42Z | [
"c#",
"python",
"asp.net",
"visual-studio",
"ironpython"
] |
Python Program Correction | 39,863,218 | <p>I need help I am trying to open the terminal and type ifconfig and enter then read the output on a mac then il transition this later to kali but I am getting a error with the file path to terminal and I cant start it, here is my code. </p>
<pre><code>import os,sys
#opens terminal
terminal = os.open('/Applications... | -1 | 2016-10-04T23:25:53Z | 39,863,299 | <p>I suggest you use <code>subprocess</code></p>
<pre><code>import subprocess
def popen(executable):
sb = subprocess.Popen(
'%s' % executable,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
stdout, stderr = sb.communicate()
... | 1 | 2016-10-04T23:33:59Z | [
"python",
"osx",
"terminal",
"filepath"
] |
Python Program Correction | 39,863,218 | <p>I need help I am trying to open the terminal and type ifconfig and enter then read the output on a mac then il transition this later to kali but I am getting a error with the file path to terminal and I cant start it, here is my code. </p>
<pre><code>import os,sys
#opens terminal
terminal = os.open('/Applications... | -1 | 2016-10-04T23:25:53Z | 39,863,352 | <p>I agree with using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="nofollow">subprocess</a>. To add to Amin's answer, for something this simple that you just want the output from:</p>
<pre><code>import subprocess
print(subprocess.check_output(['ifconfig']))
</code></pre>
<... | 1 | 2016-10-04T23:40:43Z | [
"python",
"osx",
"terminal",
"filepath"
] |
SQLAlchemy ORM with dynamic table schema | 39,863,337 | <p>I am trying to task <strong>SQLAlchemy ORM</strong> to create class <code>Field</code> that describes all fields in my database:</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Field(Base):
__tablename__ = 'fields'
__table_args__ = {'schema':'SCM'}
... | 0 | 2016-10-04T23:38:24Z | 39,966,105 | <p>So the problem is solvable and the solution is documented as <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">Augmenting the Base</a></p>
<pre><code>from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declared_... | 0 | 2016-10-10T20:17:50Z | [
"python",
"sqlalchemy"
] |
Having trouble finding the greatest length of whitespace in string | 39,863,377 | <p>I need to find the greatest length of white space in the string. No idea whats wrong. </p>
<pre><code>def check1(x):
cc = ()
for i in x:
if i != " ":
lis.append(cc)
cc=0
else:
cc +=1
new.append(cc)
print(cc)
</code></pre>
<p>I'm no... | 0 | 2016-10-04T23:44:50Z | 39,863,397 | <p>Use <code>regex</code>es and builtin <code>max</code>:</p>
<pre><code>import re
max_len = max(map(len, re.findall(' +', sentence)))
</code></pre>
<hr>
<p><code>re.findall(' +', sentence)</code> will find all the occurrences of one or more whitespaces.</p>
<p><code>map(len, ...)</code> will transform this array i... | 2 | 2016-10-04T23:47:17Z | [
"python",
"string"
] |
Having trouble finding the greatest length of whitespace in string | 39,863,377 | <p>I need to find the greatest length of white space in the string. No idea whats wrong. </p>
<pre><code>def check1(x):
cc = ()
for i in x:
if i != " ":
lis.append(cc)
cc=0
else:
cc +=1
new.append(cc)
print(cc)
</code></pre>
<p>I'm no... | 0 | 2016-10-04T23:44:50Z | 39,863,421 | <p>You could use a simple <code>itertools.groupby</code>:</p>
<pre><code>>>> from itertools import groupby
>>> s = 'foo bar baz lalala'
>>> max(len(list(v)) for is_sp, v in groupby(s, str.isspace) if is_sp)
10
</code></pre>
<p>The groupby will find consecutive runs of whi... | 1 | 2016-10-04T23:50:35Z | [
"python",
"string"
] |
Pandas Compare two columns matching text and printing full row of matching | 39,863,444 | <p>I am looking to take a hash from one df and find that hash in another df.hash column and print the full row of the matches. </p>
<p>df1:
<code>
hash
11dd7da7faa0130dac2560930e90c8b1
11dd7da7faa0130dac2560930e90c8b2
11dd7da7faa0130dac2560930e90c8b3
11dd7da7faa0130dac2560930e90c8b4
</code>
df2:
<code>
filepath ... | 0 | 2016-10-04T23:55:15Z | 39,863,494 | <p>what about a simple merge here?</p>
<pre><code>df1.merge(df2, on ='hash', how ='inner')
</code></pre>
| 1 | 2016-10-05T00:00:56Z | [
"python",
"pandas"
] |
AWS SDK | List of waiters for Elastic Beanstalk | 39,863,448 | <p>I'm interested in this <a href="https://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html#ElasticBeanstalk.Client.get_waiter" rel="nofollow">method</a> <code>get_waiter(waiter_name)</code>. Examples of waiters are in this <a href="http://boto3.readthedocs.io/en/latest/guide/clients.html#waiters... | 0 | 2016-10-04T23:55:55Z | 39,880,451 | <p>There are no waiters for that service yet. If there were, you would see them in the docs. For example compare the <a href="http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html" rel="nofollow">elasticbeanstalk boto3 docs</a> with the <a href="http://boto3.readthedocs.io/en/latest/reference/s... | 1 | 2016-10-05T17:39:09Z | [
"python",
"amazon-web-services",
"sdk",
"boto"
] |
PYTHON: Making an array with n-many elements | 39,863,461 | <p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements.
I am having trouble setting up this array since I... | 0 | 2016-10-04T23:57:08Z | 39,863,481 | <p>You are misusing the API for <code>list.append</code>. As it is, you are throwing away that list's <code>append</code> method and replacing it with the user's input, repeatedly. That line should be as follows:</p>
<pre><code>a.append(input("Enter value for flux: "))
</code></pre>
<p>The user's input is passed as a... | 0 | 2016-10-04T23:59:33Z | [
"python",
"arrays"
] |
PYTHON: Making an array with n-many elements | 39,863,461 | <p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements.
I am having trouble setting up this array since I... | 0 | 2016-10-04T23:57:08Z | 39,863,499 | <p>You're doing append= that is not valid, try it like this:</p>
<pre><code>N = input("How many inputs: ")
i=1
a = []
while i <= N:
value = input("Enter value for flux: ")
a.append(value)
i = i+1
</code></pre>
| 0 | 2016-10-05T00:01:21Z | [
"python",
"arrays"
] |
PYTHON: Making an array with n-many elements | 39,863,461 | <p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements.
I am having trouble setting up this array since I... | 0 | 2016-10-04T23:57:08Z | 39,863,533 | <p>Maybe the range can help you. Also be sure to int the answer and to try/except the <code>int</code>. I leave that to you.</p>
<pre><code>a = []
for i in range(N):
a.append(int(input('> ')))
i += 1
</code></pre>
| 0 | 2016-10-05T00:05:11Z | [
"python",
"arrays"
] |
PYTHON: Making an array with n-many elements | 39,863,461 | <p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements.
I am having trouble setting up this array since I... | 0 | 2016-10-04T23:57:08Z | 39,863,546 | <p>there you go.</p>
<pre><code>N = input("How many inputs: ")
a = []
for _ in xrange(N):
a.append(input("Enter value for flux: "))
</code></pre>
| 0 | 2016-10-05T00:06:26Z | [
"python",
"arrays"
] |
PYTHON: Making an array with n-many elements | 39,863,461 | <p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements.
I am having trouble setting up this array since I... | 0 | 2016-10-04T23:57:08Z | 39,863,573 | <p>Cast the inputs to integer.</p>
<pre><code>N = int(input("How many inputs: "))
a = []
for elem in range(N):
a.append(int(input("Enter value for flux: ")))
</code></pre>
| 0 | 2016-10-05T00:11:48Z | [
"python",
"arrays"
] |
Configuring a Postgresql POSTGIS database | 39,863,476 | <p>First off, I am new to django. I am trying to use GeoLite(GeoIP2) datasets in my POSTGIS database in Django 1.10. When I attempt to configure the myapp/settings.py file, i get error messages.There seem to be database backends in different paths in the django directory;Can you please clarify why?</p>
<ol>
<li>django... | 0 | 2016-10-04T23:59:06Z | 39,927,332 | <p>Installed GDAL from Christopher Gohlkeâs site (32 bit GDAL-2.0.3-cp35-cp35m-win32.whl)into the virtual environment.
Download OSGEO4W (32 bit) and install the Express Web option.
Create Environment Variables. Set the environment variables as below:</p>
<blockquote>
<p>set PYTHON_ROOT=C:\Python35-32 set GDAL_DATA... | 0 | 2016-10-08T00:05:41Z | [
"python",
"django",
"database",
"postgresql",
"geodjango"
] |
pandas reorder subset of columns from a grouped data frame | 39,863,487 | <p>I have forecast data that I grouped by month.
The original dataframe <em>something</em> like this:</p>
<pre><code>>>clean_table_grouped[0:5]
STYLE COLOR SIZE FOR
MONTH 01/17 10/16 11/16 12/16
0 ####### ###### #### 0.0 15.0 15.0 15.0
1 ... | 3 | 2016-10-05T00:00:13Z | 39,869,214 | <p>Sort the column names containing date strings and later use it as a subset to return the columns in that particular order:</p>
<pre><code>from datetime import datetime
df[sorted(df.columns, key=lambda x: datetime.strptime(x, '%m/%y'))]
</code></pre>
<p><a href="http://i.stack.imgur.com/iYDPP.png" rel="nofollow"><i... | 1 | 2016-10-05T08:41:40Z | [
"python",
"pandas",
"multiple-columns",
"swap",
"multi-index"
] |
pandas reorder subset of columns from a grouped data frame | 39,863,487 | <p>I have forecast data that I grouped by month.
The original dataframe <em>something</em> like this:</p>
<pre><code>>>clean_table_grouped[0:5]
STYLE COLOR SIZE FOR
MONTH 01/17 10/16 11/16 12/16
0 ####### ###### #### 0.0 15.0 15.0 15.0
1 ... | 3 | 2016-10-05T00:00:13Z | 39,923,156 | <p>My own solution was based upon the below post's second answer:
<a href="http://stackoverflow.com/questions/11194610/how-can-i-reorder-multi-indexed-dataframe-columns-at-a-specific-level">How can I reorder multi-indexed dataframe columns at a specific level</a></p>
<p>Pretty much... just create a new dataframe with ... | 0 | 2016-10-07T17:47:40Z | [
"python",
"pandas",
"multiple-columns",
"swap",
"multi-index"
] |
converting list to graph? | 39,863,521 | <p>suppose I have a 2D list of booleans such as:</p>
<pre><code>[[False, True , False],
[True, False, False]]
</code></pre>
<p>would it be possible to convert this into a graph such that all the adjacent vals of the list are connected to each other? adjacency meaning just another value either directly next to, abov... | -2 | 2016-10-05T00:04:04Z | 39,863,767 | <p>What exactly do you mean by 'convert into a graph'?</p>
<p>One possibility is for you to create a structure for representing the graph. I suggest you read the top answer to this question: <a href="http://stackoverflow.com/questions/19472530/representing-graphs-data-structure-in-python">Representing graphs (data str... | 1 | 2016-10-05T00:38:24Z | [
"python",
"list",
"python-2.7",
"graph"
] |
python recursion: create all possible sentence of certain length using a key-value dictionary of word | 39,863,565 | <p>So, let's say we have a dictionary</p>
<pre><code>>>> dictionary
{'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']}
</code></pre>
<p>We want to create all possible sentences of certain length (say 5 in our case), where each sentence starts with a <code>key</code> in the dictionary followed by an elem... | 0 | 2016-10-05T00:10:37Z | 39,863,733 | <p>The problem is that you are modifying <code>split_sentence</code> in your loop around the recursive call; assigning it to another variable just means you have a new name for the same list. Making a new list to make the recursive call with can be done like so:</p>
<pre><code> for value in dictionary[key]:
... | 1 | 2016-10-05T00:33:25Z | [
"python",
"dictionary",
"recursion",
"dynamic-programming",
"backtracking"
] |
context manager I/O operation in file | 39,863,577 | <p>I am using a context manager to wrap the text which would show in terminal and write to file at the same time.</p>
<p>I faced this problem and got the solution, please check
<a href="http://stackoverflow.com/questions/39629435/writing-terminal-output-to-terminal-and-to-a-file">Writing terminal output to terminal an... | 0 | 2016-10-05T00:12:25Z | 39,863,589 | <p><code>with FileWrite(..........., sys.stdout) as sys.stdout:</code></p>
<p>You are overwriting <code>sys.stdout</code>, just chose a real name for your file like <code>output</code> or whatever but <code>sys.stdout</code>.</p>
<p>Example:</p>
<pre><code>with FileWrite(..........., sys.stdout) as output:
outpu... | 1 | 2016-10-05T00:14:15Z | [
"python"
] |
context manager I/O operation in file | 39,863,577 | <p>I am using a context manager to wrap the text which would show in terminal and write to file at the same time.</p>
<p>I faced this problem and got the solution, please check
<a href="http://stackoverflow.com/questions/39629435/writing-terminal-output-to-terminal-and-to-a-file">Writing terminal output to terminal an... | 0 | 2016-10-05T00:12:25Z | 39,863,830 | <p>You don't really need (or want) to use <code>as</code> here. If the goal is to convert any write to <code>sys.stdout</code> to a write to both <code>sys.stdout</code> and your log file, you need to backup <code>sys.stdout</code> on <code>__enter__</code> and restore it on <code>__exit__</code>, but don't explicitly ... | 2 | 2016-10-05T00:48:29Z | [
"python"
] |
How to scrape 'Click to Display' fields with BeautifulSoup | 39,863,607 | <p>I am trying to scrape the number of schools and names of schools that basketball players get offers from verbalcommits.com</p>
<p>Using this page as an example: <a href="http://www.verbalcommits.com/players/jarrey-foster" rel="nofollow">http://www.verbalcommits.com/players/jarrey-foster</a></p>
<p>It's easy to acc... | 1 | 2016-10-05T00:16:51Z | 39,863,674 | <p>You can't get other data because when you click button then JavaScript reads it from server from </p>
<p><a href="http://www.verbalcommits.com/player_divs/closed_offers?player_id=17766&_=1475626846752" rel="nofollow">http://www.verbalcommits.com/player_divs/closed_offers?player_id=17766&_=1475626846752</a><... | 1 | 2016-10-05T00:26:01Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
How to scrape 'Click to Display' fields with BeautifulSoup | 39,863,607 | <p>I am trying to scrape the number of schools and names of schools that basketball players get offers from verbalcommits.com</p>
<p>Using this page as an example: <a href="http://www.verbalcommits.com/players/jarrey-foster" rel="nofollow">http://www.verbalcommits.com/players/jarrey-foster</a></p>
<p>It's easy to acc... | 1 | 2016-10-05T00:16:51Z | 39,875,254 | <p>To elaborate more on <a href="http://stackoverflow.com/a/39863674/771848">@furas's great answer</a>. Here is how you can extract the player id and make a second request to get the "closed offers". For this, we are going to <a class='doc-link' href="http://stackoverflow.com/documentation/python/1792/web-scraping-with... | 2 | 2016-10-05T13:26:07Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Twitter Streaming without Keyword | 39,863,716 | <p>I'm trying to stream Twitter using Tweepy and I was wondering if it is possible to stream without giving a keyword? Therefore I would be able to stream all tweets instead of only ones with a given keyword. The code I'm following can be found here: <a href="https://gist.github.com/bonzanini/af0463b927433c73784d" rel=... | 0 | 2016-10-05T00:31:26Z | 39,867,744 | <p>You can access a <em>sample</em> of all tweets by using this endpoint</p>
<p><code>https://dev.twitter.com/streaming/reference/get/statuses/sample</code></p>
<p>As is made clear in <a href="https://dev.twitter.com/streaming/reference/get/statuses/sample" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p... | 1 | 2016-10-05T07:21:40Z | [
"python",
"twitter",
"tweepy"
] |
How can I log outside of main Flask module? | 39,863,718 | <p>I have a Python Flask application, the entry file configures a logger on the app, like so:</p>
<pre><code>app = Flask(__name__)
handler = logging.StreamHandler(sys.stdout)
app.logger.addHandler(handler)
app.logger.setLevel(logging.DEBUG)
</code></pre>
<p>I then do a bunch of logging using </p>
<p><code>app.logger... | 3 | 2016-10-05T00:31:36Z | 39,863,901 | <p>Even though this is a possible duplicate I want to write out a tiny bit of python logging knowledge. </p>
<p>DON'T pass loggers around. You can always access any given logger by <code>logging.getLogger(<log name as string>)</code>. By default it looks like* flask uses the name you provide to the <code>Flask</... | 2 | 2016-10-05T00:58:15Z | [
"python",
"logging",
"flask"
] |
Extract Text from Javascript using Python | 39,863,723 | <p>I've been looking at examples of how to do this but can't quite figure it out. I'm using beautifulsoup to scrape some data - I am able to use it to find the data I want, but it is contained in the following block of code. I'm trying to extract the timestamp information from it. I have a feeling regular expressions w... | 0 | 2016-10-05T00:32:20Z | 39,863,780 | <p>You can't use BS to get this data - BS works only with HTML/XML, not JavaScript. </p>
<p>You have to use <code>regular expressions</code> or standart string functions.</p>
<hr>
<p><strong>EDIT:</strong></p>
<pre><code>text = '''<script class="code" type="text/javascript">
$(document).ready(function(){
... | 1 | 2016-10-05T00:39:59Z | [
"javascript",
"python",
"beautifulsoup"
] |
Extract Text from Javascript using Python | 39,863,723 | <p>I've been looking at examples of how to do this but can't quite figure it out. I'm using beautifulsoup to scrape some data - I am able to use it to find the data I want, but it is contained in the following block of code. I'm trying to extract the timestamp information from it. I have a feeling regular expressions w... | 0 | 2016-10-05T00:32:20Z | 39,875,529 | <p>One another alternative to using regular expressions to parse javascript code would be to use a JavaScript parser like <a href="https://pypi.python.org/pypi/slimit" rel="nofollow"><code>slimit</code></a>. Working code:</p>
<pre><code>import json
from bs4 import BeautifulSoup
from slimit import ast
from slimit.pars... | 0 | 2016-10-05T13:37:43Z | [
"javascript",
"python",
"beautifulsoup"
] |
Handle Fortran Character Arrays from Python with F2PY | 39,863,836 | <p>I have a legacy Fortran library I've wrapped with F2PY. However, I'm at a loss for how to properly read character arrays declared as module data, from Python. The data data comes through, but the array is transposed in such a way that it is indiscernible. How can I get Numpy to correctly handle my array? I'd be sa... | 1 | 2016-10-05T00:49:18Z | 39,863,929 | <p>I haven't tried running f2py on your module, but if I define the array you show as:</p>
<pre><code>In [11]: s = array([[b'S', b' ', b' ', b'L'],
...: [b'F', b'L', b' ', b' '],
...: [b' ', b'P', b'B', b' '],
...: [b' ', b' ', b'M', b'W'],
...: [b'W', b' ', b' ', b'B'],
...: [b'F', ... | 1 | 2016-10-05T01:02:42Z | [
"python",
"numpy",
"fortran"
] |
Handle Fortran Character Arrays from Python with F2PY | 39,863,836 | <p>I have a legacy Fortran library I've wrapped with F2PY. However, I'm at a loss for how to properly read character arrays declared as module data, from Python. The data data comes through, but the array is transposed in such a way that it is indiscernible. How can I get Numpy to correctly handle my array? I'd be sa... | 1 | 2016-10-05T00:49:18Z | 39,864,132 | <p>For completeness I'll include this alternative solution. Same results as @Warren Weckesser, but requires an additional import.</p>
<pre><code>from numpy.lib import stride_tricks
spp = stride_tricks.as_strided(jsp, strides=(jsp.shape[1],1))
# View as S4 and strip whitespace
spp = np.char.strip(spp.view('S4'))
</c... | 0 | 2016-10-05T01:31:13Z | [
"python",
"numpy",
"fortran"
] |
How do I place multiple searched tweets into string | 39,863,871 | <p>I have a program set up so it searches tweets based on the hashtag I give it and I can edit how many tweets to search and display but I can't figure out how to place the searched tweets into a string. this is the code I have so far</p>
<pre><code> while True:
for status in tweepy.Cursor(api.search, q=has... | 0 | 2016-10-05T00:54:32Z | 39,864,327 | <p>Your code looks like there's nothing to break out of the <code>while</code> loop. One method that comes to mind is to set a variable to an empty list and then with each tweet, append that to the list. </p>
<pre><code>foo = []
for status in tweepy.Cursor(api.search, q=hashtag).items(2):
tweet = status.text
... | 1 | 2016-10-05T01:59:55Z | [
"python",
"string",
"output",
"tweepy",
"tweets"
] |
psycopg2 not all arguments converted during string formatting | 39,863,881 | <p>I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.</p>
<p>The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, 23-int4). I have also made attempts with 1082-date instead of timestamp, and 21-int2 instead of int4.</p>
... | 0 | 2016-10-05T00:55:56Z | 39,864,325 | <p>Thanks to @Keith for the help. I was expecting psycopg2 to do more than it actually does. Since I am developing a script to iterate through several hundred text files for import to different tables, I want something that can work with different table sizes and made the following modification:</p>
<pre><code>sql_tex... | 0 | 2016-10-05T01:59:22Z | [
"python",
"postgresql",
"python-2.7",
"psycopg2"
] |
psycopg2 not all arguments converted during string formatting | 39,863,881 | <p>I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.</p>
<p>The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, 23-int4). I have also made attempts with 1082-date instead of timestamp, and 21-int2 instead of int4.</p>
... | 0 | 2016-10-05T00:55:56Z | 39,869,263 | <p>You can keep your original code but pass a tuple in instead of a list:</p>
<pre><code>sql_text = "INSERT INTO ssurgo.distmd VALUES %s ;"
data = ('5', date.today(), 'Successful', 4891)
print(curs.mogrify(sql_text, [data]))
</code></pre>
<p>Notice that you are passing a single value so it is necessary to wrap it in... | 0 | 2016-10-05T08:43:54Z | [
"python",
"postgresql",
"python-2.7",
"psycopg2"
] |
/usr/bin/env: python, No such file or directory | 39,863,896 | <p>I write code working with mapreduce in Ubuntu System in Vmware. Now I have two snippets of code with the same header but one is right and another one report </p>
<pre><code>/usr/bin/env: python
: No such file or directory
</code></pre>
<p>error. This is the one report error:</p>
<pre><code>#!/usr/bin/env python... | -1 | 2016-10-05T00:57:34Z | 39,864,047 | <p>You have an colon : after the /usr/bin/env you need to remove it.</p>
| -1 | 2016-10-05T01:21:18Z | [
"python",
"shell"
] |
/usr/bin/env: python, No such file or directory | 39,863,896 | <p>I write code working with mapreduce in Ubuntu System in Vmware. Now I have two snippets of code with the same header but one is right and another one report </p>
<pre><code>/usr/bin/env: python
: No such file or directory
</code></pre>
<p>error. This is the one report error:</p>
<pre><code>#!/usr/bin/env python... | -1 | 2016-10-05T00:57:34Z | 39,866,726 | <p>The fact that the error message prints the word 'python' in one line and the ': No such file or directory' in the next line, suggests that there is some invisible character after <em>python</em>. Do a hexdump of your file to find out.</p>
| 0 | 2016-10-05T06:20:58Z | [
"python",
"shell"
] |
create sub lists by grouping with conditional check on two consecutive zeros | 39,863,989 | <p>I have a list:</p>
<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
</code></pre>
<p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p>
<p>s... | 2 | 2016-10-05T01:12:57Z | 39,864,197 | <p>Here is an option with a <code>for</code> loop:</p>
<pre><code>zeros = 0
result = [0]
for i in lst:
if i == 0:
zeros += 1
elif zeros >= 2: # if there are more than two zeros, append the new
# element to the result
result.append(i)
... | 2 | 2016-10-05T01:41:45Z | [
"python",
"python-2.7"
] |
create sub lists by grouping with conditional check on two consecutive zeros | 39,863,989 | <p>I have a list:</p>
<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
</code></pre>
<p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p>
<p>s... | 2 | 2016-10-05T01:12:57Z | 39,864,265 | <p>I group pairs of adjacent numbers by whether they hold any truth. Then take the truthy groups and sum them. Might be a bit too complicated, but I like using the <code>any</code> key.</p>
<pre><code>>>> from itertools import groupby
>>> [sum(a for a, _ in g) for k, g in groupby(zip(lst, lst[1:] + [... | 6 | 2016-10-05T01:48:47Z | [
"python",
"python-2.7"
] |
create sub lists by grouping with conditional check on two consecutive zeros | 39,863,989 | <p>I have a list:</p>
<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
</code></pre>
<p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p>
<p>s... | 2 | 2016-10-05T01:12:57Z | 39,864,268 | <p>Cheesy solution if your values all occur in <code>range(-128, 128)</code> is to use the <code>split</code> and <code>replace</code> methods of <code>bytearray</code> (which conveniently converts to and from <code>int</code>) to do the splitting:</p>
<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -... | 0 | 2016-10-05T01:49:30Z | [
"python",
"python-2.7"
] |
create sub lists by grouping with conditional check on two consecutive zeros | 39,863,989 | <p>I have a list:</p>
<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
</code></pre>
<p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p>
<p>s... | 2 | 2016-10-05T01:12:57Z | 39,864,396 | <pre><code>list = lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
lastElement = None
new_list=[]
sub_list=[]
for element in list:
if element == 0 == lastElement:
if sub_list == []:
continue
... | 0 | 2016-10-05T02:08:59Z | [
"python",
"python-2.7"
] |
create sub lists by grouping with conditional check on two consecutive zeros | 39,863,989 | <p>I have a list:</p>
<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
</code></pre>
<p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p>
<p>s... | 2 | 2016-10-05T01:12:57Z | 39,867,407 | <pre><code>map(lambda x:eval(re.sub('^,','',x,1).replace(',','+')) if(len(x))>3 else eval(x.replace(',','+')),filter(lambda x:x!=',0',re.split(r',0,0,|\|',"|".join(re.split(r'(,0){3,}',l)))))
</code></pre>
| 0 | 2016-10-05T07:02:54Z | [
"python",
"python-2.7"
] |
What is the most efficient way to compare 45 Million rows of Text File to about 200k rows text file and produce non matches from the smaller file? | 39,864,096 | <p>I have a 45 million row txt file that contains hashes. What would be the most efficient way to compare the file to another file, and provide only items from the second file that are not in the large txt file? </p>
<p>Current working: </p>
<pre><code>comm -13 largefile.txt smallfile.txt >> newfile.txt
</code... | 3 | 2016-10-05T01:26:35Z | 39,865,301 | <p>Hash table. Or in Python terms, just use a <code>set</code>.</p>
<p>Put each item from the <strong><em>smaller</em></strong> file into the set. 200K items is perfectly fine. Enumerate each item in the larger file to see if it exists in the smaller file. If there is a match, remove the item from the the hash tab... | 1 | 2016-10-05T04:09:56Z | [
"python",
"pandas",
"iteration",
"large-files"
] |
What is the most efficient way to compare 45 Million rows of Text File to about 200k rows text file and produce non matches from the smaller file? | 39,864,096 | <p>I have a 45 million row txt file that contains hashes. What would be the most efficient way to compare the file to another file, and provide only items from the second file that are not in the large txt file? </p>
<p>Current working: </p>
<pre><code>comm -13 largefile.txt smallfile.txt >> newfile.txt
</code... | 3 | 2016-10-05T01:26:35Z | 39,865,306 | <p>Haven't tested, but I think this would be non memory intensive (no idea on speed): </p>
<pre><code>unique = []
with open('large_file.txt') as lf, open('small_file.txt') as sf:
for small_line in sf:
for large_line in lf:
if small_line == large_line:
break
else:
... | 0 | 2016-10-05T04:10:21Z | [
"python",
"pandas",
"iteration",
"large-files"
] |
Remove double quotes from csv row | 39,864,097 | <p>I have two files: src.csv and dst.csv. The code below reads the second row from src.csv and appends it to dst.csv. The issue is the output in dst.csv is contained within double quotes (""). </p>
<p>Expected result:</p>
<pre><code>10, 5, 5, 10, 1
</code></pre>
<p>Output:</p>
<pre><code>"10, 5, 5, 10, 1"
</code></... | 0 | 2016-10-05T01:26:38Z | 39,864,172 | <p>I think you have to use <code>csv.reader()</code> to read row as list of number - now you read row as one string and csv.writer has to add <code>""</code> because you have <code>,</code> in this string.</p>
| 0 | 2016-10-05T01:36:58Z | [
"python",
"python-3.x",
"csv"
] |
Remove double quotes from csv row | 39,864,097 | <p>I have two files: src.csv and dst.csv. The code below reads the second row from src.csv and appends it to dst.csv. The issue is the output in dst.csv is contained within double quotes (""). </p>
<p>Expected result:</p>
<pre><code>10, 5, 5, 10, 1
</code></pre>
<p>Output:</p>
<pre><code>"10, 5, 5, 10, 1"
</code></... | 0 | 2016-10-05T01:26:38Z | 39,864,180 | <p>You don't split the source file rows into columns so you just ended up writing a 1 column csv. Use a reader instead:</p>
<pre><code>import csv
with open('src.csv', 'r') as src, open('dst.csv', 'a', newline='') as dst:
wr = csv.writer(dst, dialect='excel', delimiter=',', quoting=csv.QUOTE_NONE, escapechar=' ')
... | 1 | 2016-10-05T01:38:42Z | [
"python",
"python-3.x",
"csv"
] |
I want to put tickers in brackets | 39,864,134 | <p>I want to put AEM into brackets, so that text will look like: Agnico Eagle Mines Limited (AEM)</p>
<pre><code>text = "Agnico Eagle Mines Limited AEM"
def add_brackets(test):
for word in test:
if word.isupper():
word = "(" + word + ")"
print(test)
print(add_brackets(text))
</code></p... | 0 | 2016-10-05T01:31:25Z | 39,864,152 | <p>Two things, 1 you are checking per character, not per word. 2 you are not modifying <code>text</code> you are just setting <code>word</code> and not doing anything with it. </p>
<pre><code>text = "Agnico Eagle Mines Limited AEM"
def add_brackets(test):
outstr = ""
for word in test.split(" "):
if w... | 1 | 2016-10-05T01:33:49Z | [
"python"
] |
I want to put tickers in brackets | 39,864,134 | <p>I want to put AEM into brackets, so that text will look like: Agnico Eagle Mines Limited (AEM)</p>
<pre><code>text = "Agnico Eagle Mines Limited AEM"
def add_brackets(test):
for word in test:
if word.isupper():
word = "(" + word + ")"
print(test)
print(add_brackets(text))
</code></p... | 0 | 2016-10-05T01:31:25Z | 39,887,191 | <p>This would be pretty concise with a regular expression substitution:</p>
<pre><code>>>> import re
>>> text = "Agnico Eagle Mines Limited AEM"
>>> re.sub(r'\b([A-Z]+)\b', r'(\1)', text)
'Agnico Eagle Mines Limited (AEM)'
</code></pre>
<p>This looks for multiple uppercase characters togeth... | 0 | 2016-10-06T03:45:44Z | [
"python"
] |
Renaming python.exe to python3.exe for co-existence with python2 on Windows | 39,864,184 | <p>I would like to install both python 2.7 and python 3.5 on my Windows 10 PC. Both python executables use the same name <code>python.exe</code>.</p>
<p>Is it a good idea to change <code>python.exe</code> to <code>python3.exe</code> as a quick fix for co-existence? Are there any side-effects or other things that I nee... | 2 | 2016-10-05T01:38:59Z | 39,864,221 | <p>You'll need to run <code>python3</code> instead of <code>python</code> if that's not obvious. This is definitely, as you described, a "quick fix" </p>
<p>My suggested fix is to use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> and pass in the Python executable you would like to use a... | 1 | 2016-10-05T01:43:53Z | [
"python",
"windows",
"python-2.7",
"python-3.x"
] |
Renaming python.exe to python3.exe for co-existence with python2 on Windows | 39,864,184 | <p>I would like to install both python 2.7 and python 3.5 on my Windows 10 PC. Both python executables use the same name <code>python.exe</code>.</p>
<p>Is it a good idea to change <code>python.exe</code> to <code>python3.exe</code> as a quick fix for co-existence? Are there any side-effects or other things that I nee... | 2 | 2016-10-05T01:38:59Z | 39,864,232 | <p>You don't need to rename anything for co-existence of different versions of Python.</p>
<p>The different versions of python are installed on different folders automatically.</p>
<p>When use the command prompt you can use the commands <code>py2</code> or <code>py3</code> to refer to the different versions of python... | 4 | 2016-10-05T01:45:19Z | [
"python",
"windows",
"python-2.7",
"python-3.x"
] |
How to show truncated X-axis in matplotlib (seaboard) heatmap | 39,864,211 | <p>I have the following image:</p>
<p><a href="http://i.stack.imgur.com/sUDks.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/sUDks.jpg" alt="enter image description here"></a></p>
<p>Created with this code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas ... | 0 | 2016-10-05T01:43:04Z | 39,864,505 | <p>There's a convenient way to do this through a <code>subplots_adjust</code> method: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# create some random data
data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = ['yyyyyyyy ... | 1 | 2016-10-05T02:25:27Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Nested Loops all | 39,864,292 | <p>I am using python. The assignment is simple, I understand the concept, I have zero knowledge of computer programming, so be gentle and please try to explain everything in much detail as if I know nothing, I am trying my best to learn. This is to show that with all combinations ijk, ikj, jik, jki, kij, and kji return... | 0 | 2016-10-05T01:53:06Z | 39,864,370 | <pre><code>for i in range(len(X)):
for k in range(len(Y)):
for j in range(len(Y[0])):
result[i][j] += X[i][k] * Y[k][j]
</code></pre>
<p><code>result[i][j]</code> is a <code>2x2</code> matrix <code>len(X)</code> and <code>len(Y)</code> are both <code>2</code>. Meanwhile <code>k</code> is going a... | 0 | 2016-10-05T02:05:45Z | [
"python",
"loops",
"matrix",
"indexing",
"nested"
] |
Nested Loops all | 39,864,292 | <p>I am using python. The assignment is simple, I understand the concept, I have zero knowledge of computer programming, so be gentle and please try to explain everything in much detail as if I know nothing, I am trying my best to learn. This is to show that with all combinations ijk, ikj, jik, jki, kij, and kji return... | 0 | 2016-10-05T01:53:06Z | 39,864,479 | <p>I printed <code>i</code>, <code>j</code>, <code>k</code> and <code>result[i][j]</code>, <code>X[i][k]</code>, <code>Y[k][j]</code> in 3rd set and found:</p>
<p>You forgot <code>result = empty</code></p>
<p>But there is another problem: <code>result = empty</code> doesn't duplicate list but assigns the same list t... | 0 | 2016-10-05T02:21:16Z | [
"python",
"loops",
"matrix",
"indexing",
"nested"
] |
How to use subprocess and 'cat' to read in data line by line? | 39,864,304 | <p>I'm having trouble understanding how to use <code>subprocess</code> for a problem on mine. </p>
<p>Let's say I have a tab-delimited text file <code>tabdelimited1.txt</code> in my subdiretory which I would like to read into a pandas dataframe. </p>
<p>Naturally, you could simply import the data as follows: </p>
<p... | 0 | 2016-10-05T01:56:03Z | 39,864,368 | <p>You can skip the shell completely by breaking the command into a list. Then its just a matter of iterating the process stdout:</p>
<pre><code>import subprocess
import pandas as pd
df = pd.DataFrame()
task = subprocess.Popen(["cat", "file.txt"], stdout=subprocess.PIPE)
for line in task.stdout:
df=pd.concat([df,... | 2 | 2016-10-05T02:05:42Z | [
"python",
"python-3.x",
"csv",
"subprocess",
"cat"
] |
How to use subprocess and 'cat' to read in data line by line? | 39,864,304 | <p>I'm having trouble understanding how to use <code>subprocess</code> for a problem on mine. </p>
<p>Let's say I have a tab-delimited text file <code>tabdelimited1.txt</code> in my subdiretory which I would like to read into a pandas dataframe. </p>
<p>Naturally, you could simply import the data as follows: </p>
<p... | 0 | 2016-10-05T01:56:03Z | 39,864,561 | <pre><code>import sys
for line in sys.stdin:
print(line.split())
</code></pre>
<p>can be used with a shell command like:</p>
<pre><code>0025:~/mypy$ cat x.txt | python3 stack39864304.py
['1', '3', 'test1;']
['2', '2', 'test2;']
['3', '2', 'test3;']
</code></pre>
<p>Otherwise in an interactive session I can do:</... | 0 | 2016-10-05T02:33:29Z | [
"python",
"python-3.x",
"csv",
"subprocess",
"cat"
] |
Opening a HTML file from my computer in web browser | 39,864,306 | <p>I would like to open a HTML file that is stored in my computer on a web browser but I'm getting an error (see below).</p>
<pre><code>from urllib import urlopen
from webbrowser import open as webopen
from os import getcwd
from os.path import normpath
</code></pre>
<p>I have this code:</p>
<pre><code>def open_html_... | 0 | 2016-10-05T01:56:16Z | 39,864,324 | <p><code>normpath</code> is a function, and doesn't have a <code>abspath</code> attribute.
I think you meant to do that:</p>
<pre><code>from os.path import abspath
path = abspath('New_News.html')
</code></pre>
| 0 | 2016-10-05T01:59:14Z | [
"python",
"html",
"os.path",
"python-webbrowser"
] |
Google App Engine - storing key into ndb KeyProperty | 39,864,359 | <p>I am creating a commenting system using Google App Engine with webapp2 using ndb datastore. I created a property KeyProperty so I can fetch comments associated with posts with the same key. </p>
<p>However, I keep receiving an error message whenever I try to store the key of a post into ndb.KeyProperty. I tried cha... | 1 | 2016-10-05T02:03:54Z | 39,864,532 | <p>The error tells you what's happening:</p>
<pre><code>BadValueError: Expected string, got User
</code></pre>
<p>If you look a little further back in the traceback, you see:</p>
<pre><code>post r = Reply(content=reply_content, p_key=p_key, user=user)
</code></pre>
<p>In your <code>Reply</code> class, you set <cod... | 1 | 2016-10-05T02:28:48Z | [
"python",
"google-app-engine",
"google-cloud-datastore",
"webapp2",
"google-app-engine-python"
] |
Calling functions inside a function in python? | 39,864,563 | <p>Trying to find a way to call each function inside the function, thirdQues. I don't want them to be global, and keep receiving an unexpected indentation error when I show they are nested within thirdQues in the main. I also plan to nest thirdQues in functions around the same size as itself. Any help appreciated. </p>... | -1 | 2016-10-05T02:33:35Z | 39,866,413 | <p>This indentation is wrong:</p>
<pre><code>def main():
thirdQues(a = "Questions_7.txt", b = "Questions_8.txt" ,c = "Questions_9.txt")
intro3()
</code></pre>
<p>You cannot indent <code>intro3()</code> here.</p>
<p>Besides that, use 4 spaces for indentation, rather than 8. Both are syntactic... | 0 | 2016-10-05T05:59:47Z | [
"python",
"python-3.x"
] |
Python .replace running twice | 39,864,581 | <p>Still pretty new to python and first time using .replace and I am running into a weird issue.</p>
<pre><code>url_base = 'http://sfbay.craigslist.org/search/eby/apa'
params = dict(bedrooms=1, is_furnished=1)
rsp = requests.get(url_base, params=params)
# BS4 can quickly parse our text, make sure to tell it that you'r... | 0 | 2016-10-05T02:35:34Z | 39,864,817 | <p>Now works for me. I made some modifications with <code>strip</code>, <code>split</code> and add comment <code># <- here</code></p>
<pre><code>url_base = 'http://sfbay.craigslist.org/search/eby/apa'
params = dict(bedrooms=1, is_furnished=1)
rsp = requests.get(url_base, params=params)
# BS4 can quickly parse our t... | 0 | 2016-10-05T03:08:57Z | [
"python"
] |
Python perfect number calculation | 39,864,603 | <p>I am having issues with calculating perfect numbers in python. Apparently the code is working in VBA so I am sure I am making some mistake in syntax / indentation. Please help!</p>
<p>Here is my code:</p>
<pre><code>Mynum=int(input("How many perfect numbers do you want?: "))
counter=0
k=0
j=2
i=1
while counter&l... | 0 | 2016-10-05T02:39:23Z | 39,864,774 | <p>Your screenshot code, which is the better of the two, is broken in a couple of ways: your <code>k = k + 1</code> expression should be <code>k = k + i</code> as you want to sum the factors, not count them; you <code>print(i)</code> when your should print <code>j</code> or <code>k</code>:</p>
<pre><code>Mynum = int(i... | 1 | 2016-10-05T03:03:39Z | [
"python",
"perfect-numbers"
] |
Python perfect number calculation | 39,864,603 | <p>I am having issues with calculating perfect numbers in python. Apparently the code is working in VBA so I am sure I am making some mistake in syntax / indentation. Please help!</p>
<p>Here is my code:</p>
<pre><code>Mynum=int(input("How many perfect numbers do you want?: "))
counter=0
k=0
j=2
i=1
while counter&l... | 0 | 2016-10-05T02:39:23Z | 39,864,801 | <p>Here's another solution to the perfect number:</p>
<pre><code>import itertools as it
def perfect():
for n in it.count(1):
if sum(i for i in range(1, n+1) if n%i == 0) == 2*n:
yield n
>>> list(it.islice(perfect(), 3))
[6, 28, 496]
100 loops, best of 3: 12.6 ms per loop
</code></pre... | 0 | 2016-10-05T03:06:36Z | [
"python",
"perfect-numbers"
] |
How do I execute a function in a certain way after importing it in another python file? | 39,864,618 | <p>This is a function that returns a list of length of random numbers from 0 to 9.</p>
<pre><code>import random
def makeList():
y=[]
n=int(raw_input("Enter number"))
for x in range(0,n):
x=random.randint(0,9)
y.append(x)
print y
def main():
makeList()
if __name__ == '__main__':
... | 0 | 2016-10-05T02:41:35Z | 39,864,705 | <p>Changing <code>print y</code> to <code>return y</code> in the first file. (and <code>print(makeList())</code> under <code>main()</code>) </p>
<p>In the new file, <code>new_list = makeList()</code></p>
<p>then new_list is that generated list.</p>
<p>Edit: More pythonic version</p>
<p><strong>File 1</strong></p>
... | 0 | 2016-10-05T02:53:45Z | [
"python",
"python-2.7"
] |
Parsing Messy Data | 39,864,658 | <p>I'm relatively new to python and was wondering if I could get some assistance in parsing data so that it is easier to analyze.</p>
<hr>
<p>My data is in the following form (each is an entire line):</p>
<pre><code>20160930-07:06:54.481737|I|MTP_4|CL:BF K7-M7-N7 Restrict for maxAggressive: -4.237195
20160930-07:06:... | 0 | 2016-10-05T02:46:55Z | 40,022,431 | <pre><code>infilename = "path/data.log"
outfilename = "path/OutputData.csv"
with open(infilename, 'r') as infile,\
open(outfilename, "w") as outfile:
lineCounter = 0
for line in infile:
lineCounter += 1
if lineCounter % 1000000 == 0:
print lineCounter
data = line.split(... | 0 | 2016-10-13T13:30:41Z | [
"python"
] |
Count number of occurences of specific number in numpy arrary in Excel sheet using python | 39,864,754 | <pre><code>import numpy as np
from openpyxl import load_workbook
wb = load_workbook('Book1.xlsx')
sheet_1 = wb.get_sheet_by_name('Sheet1')
x1 = np.zeros(sheet_1.max_row)
for i in range(0,sheet_1.max_row):
x1[i]=sheet_1.cell(row=i+1, column=1).value
x2[i] = np.count_nonzero(x1[i])
collections.Counter(x2[i])[0]... | 0 | 2016-10-05T03:00:41Z | 39,874,505 | <p>A straight forward numpy-only solution to the <em>"counting occurence of a specific number in a numpy array"</em> question would be this:</p>
<pre><code># Note that I cast x1 to np.int because "arr==x" is not reliable with floats
x1=np.array([5,5,3,3,4,5,5,0,0,0],dtype=np.int)
#(x1==0) is boolean array that is Tru... | 0 | 2016-10-05T12:52:15Z | [
"python",
"excel",
"numpy"
] |
How to scrape charts from a website with python? | 39,864,796 | <p><strong>EDIT:</strong> </p>
<p>So I have save the script codes below to a text file but using re to extract the data still doesn't return me anything. My code is: </p>
<pre><code>file_object = open('source_test_script.txt', mode="r")
soup = BeautifulSoup(file_object, "html.parser")
pattern = re.compile(r"^var (cha... | 0 | 2016-10-05T03:06:12Z | 39,866,327 | <p>I'd go a combination of regex and yaml parser. Quick and dirty below - you may need to tweek the regex but it works with example:</p>
<pre><code>import re
import sys
import yaml
chart_matcher = re.compile(r'^var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);$',
re.MULTILINE | re.DOTALL)
script = sys.st... | 0 | 2016-10-05T05:53:05Z | [
"python",
"graph",
"screen-scraping"
] |
How to scrape charts from a website with python? | 39,864,796 | <p><strong>EDIT:</strong> </p>
<p>So I have save the script codes below to a text file but using re to extract the data still doesn't return me anything. My code is: </p>
<pre><code>file_object = open('source_test_script.txt', mode="r")
soup = BeautifulSoup(file_object, "html.parser")
pattern = re.compile(r"^var (cha... | 0 | 2016-10-05T03:06:12Z | 39,887,073 | <p>I tried the code as you suggested but kept getting this:</p>
<pre><code>"Failed to parse chart1: while parsing a flow mapping
in "<unicode string>", line 29, column 16:
tooltip: {
^
expected ',' or '}', but got '{'"
</code></pre>
<p>My entire code: </p>
<pre><code>import json... | 0 | 2016-10-06T03:32:31Z | [
"python",
"graph",
"screen-scraping"
] |
Weighted K-means with GPS Data | 39,864,921 | <p><strong>OBJECTIVE</strong></p>
<ul>
<li><p>Aggregate store locations GPS information (longitude, latitude) </p></li>
<li><p>Aggregate size of population in surrounding store area (e.g 1,000,000
residents) </p></li>
<li>Use K-means to determine optimal distribution centers,
given store GPS data and local population ... | 0 | 2016-10-05T03:22:27Z | 39,870,707 | <p>1) You only want to do k-means in the (longitude, latitude) space. If you add population as a 3rd dimension, you will bias your centroids towards the midpoint between large population centres, which are often far apart.</p>
<p>2) The simplest hack to incorporate a weighting in k-means is to repeat a point (longitud... | 1 | 2016-10-05T09:48:28Z | [
"python",
"numpy",
"statistics",
"k-means"
] |
image_url = soup.select('.image a')[0]['href'] IndexError: list index out of range | 39,864,939 | <p>I used part of this code to retrieve the images from imgur when the URL doesn't end in an image extension like .png/.jpg. However I am getting these errors. Please have a look and suggest fixes:</p>
<p><a href="https://github.com/asweigart/imgur-hosted-reddit-posted-downloader/blob/master/imgur-hosted-reddit-posted... | 0 | 2016-10-05T03:24:54Z | 39,865,173 | <p>You have wrong selection - you need <code>soup.select('img')[0]['src']</code></p>
<pre><code>import datetime
import urllib
import requests
from bs4 import BeautifulSoup
url = 'http://imgur.com/gyUWtWP'
html_source = requests.get(url).text
soup = BeautifulSoup(html_source, "lxml")
image_url = soup.select('img')[0... | 1 | 2016-10-05T03:54:56Z | [
"python",
"html",
"beautifulsoup",
"reddit",
"imgur"
] |
How to do the modulus calculation without using mod funct in Python | 39,865,003 | <p>I am coding in Python and using Putty, I couldnt find the right way to do a program that does a modulus calculation without the mod function. </p>
<pre><code>def main()
Input1 = int(input("Type in first number"))
Input2 = int(input("Type in second number"))
q = (input1 / Input2) #finding quotient (i... | -2 | 2016-10-05T03:34:27Z | 39,865,713 | <pre><code>def main():
Input1 = int(input("Type in first number"))
Input2 = int(input("Type in second number"))
q = (Input1 / Input2)
for i in range(0, Input1, Input2):
if Input1 - i < Input2:
print(Input1-i)
</code></pre>
<p>This is a way to find what x mod y is in any given c... | 1 | 2016-10-05T04:56:13Z | [
"python"
] |
some misunderstanding about `pandas.series.drop()` | 39,865,031 | <p>I want to drop some specific rows in a <code>pandas.DataFrame</code>, while it seems that <code>pandas.Series.drop()</code>.What I have tried is as follows:</p>
<pre><code>In[1]:
a_pd = pd.DataFrame(np.array([[1,2,3], [2,'?','x'],['s','d',4]]), columns=list('abc'))
a_pd
Out[1]:
a b c
0 1 2 3
1... | 0 | 2016-10-05T03:37:40Z | 39,865,499 | <p>pandas.drop() works on the labels associated with the row you want do delete, which in this case is 0, 1, or 2. So you can delete the middle row by </p>
<pre><code>a_pd.drop([1])
</code></pre>
<p>returns</p>
<pre><code> a b c
0 1 2 3
2 s d 4
</code></pre>
<p>Similarly, for the Series version of .drop(... | 2 | 2016-10-05T04:34:32Z | [
"python",
"pandas"
] |
Python: Calculating exponents of a base | 39,865,032 | <p>I am new to python and trying to figure out how to get an exponent to times a certain time of the base, ex. 5<sup>4</sup>, without using the exponent operator, **.</p>
<p>For this, I am trying to implement the use of the for loop but the thing is I cannot figure out how to achieve this with a loop.</p>
<p>This is ... | -1 | 2016-10-05T03:37:43Z | 39,865,075 | <p><code>range(x)</code> can be used to run a loop <code>x</code> times (don't even pay attention to the values iterated). If you start with a value of 1, then multiply by <code>base</code> <code>exponent</code> times, that's naive exponentiation right there.</p>
| 2 | 2016-10-05T03:42:24Z | [
"python",
"python-3.x"
] |
Python: Calculating exponents of a base | 39,865,032 | <p>I am new to python and trying to figure out how to get an exponent to times a certain time of the base, ex. 5<sup>4</sup>, without using the exponent operator, **.</p>
<p>For this, I am trying to implement the use of the for loop but the thing is I cannot figure out how to achieve this with a loop.</p>
<p>This is ... | -1 | 2016-10-05T03:37:43Z | 39,865,307 | <p>Try this code:</p>
<pre><code>base = int(input("ENTER NUMBER: "))
exponent = int(input("ENTER EXPONENT: "))
no = base * base
for item_name in range(exponent):
if exponent == 0:
print(1)
elif exponent > 0:
no += base * exponent * base * item_name
if no == base ** exponent:
... | 0 | 2016-10-05T04:10:31Z | [
"python",
"python-3.x"
] |
Python: Calculating exponents of a base | 39,865,032 | <p>I am new to python and trying to figure out how to get an exponent to times a certain time of the base, ex. 5<sup>4</sup>, without using the exponent operator, **.</p>
<p>For this, I am trying to implement the use of the for loop but the thing is I cannot figure out how to achieve this with a loop.</p>
<p>This is ... | -1 | 2016-10-05T03:37:43Z | 39,865,631 | <p>Try</p>
<pre><code> base = float(input('Enter Num:'))
exponent = int(input('Enter Exponent:') #what if I want non integer exponent
answer = 1
if exponent != 0: #if the exponent is 0 the answer is 1
for in range(abs(exponent)):
answer*=base
if exponent < 0:
... | 0 | 2016-10-05T04:48:55Z | [
"python",
"python-3.x"
] |
Selenium Chrome, Python. Couldn't find the button on the website | 39,865,034 | <p>I am newly learning how to work with Webdriver and while I am playing with it on Eventbrite website it couldn't find the create event button while it is there(I can click it). I try lots of different things to locate button like XPath, link_text, class but they didn't work. Here is the code I am working with :</p>
... | 1 | 2016-10-05T03:37:53Z | 39,865,148 | <p>If I'm understanding your question right, the last line of your example (<code>"Create Event"</code>) is the one that doesn't work? I can say that if I use a css selector, I can click that button.
(I also tend to find css selectors are easier to work with)</p>
<pre><code>driver = self.driver
driver.get("https://www... | 1 | 2016-10-05T03:52:07Z | [
"python",
"osx",
"google-chrome",
"selenium"
] |
Applying modulo to all elements of a python list and getting some correct some incorrect elements | 39,865,185 | <p>I am implementing a function that reduces all the elements of a list modulo 3. Here is what I have:</p>
<pre><code>def reduceMod3(l):
for i in l:
l[i] = l[i] % 3
return l
</code></pre>
<p>when I call this function on L = [1,2,3,4,5,6,7,8,9] I get:</p>
<pre><code>L = [1, 2, 0, 4, 2, 6, 1, 8, 0]
</c... | 3 | 2016-10-05T03:56:01Z | 39,865,217 | <p>You're list assignment is off, <code>l[i]</code> is not saying 'the value that equals <code>i</code>' but 'position <code>i</code> in list <code>l</code>'. You also don't want to modify a list as you iterate over it. </p>
<p>I think this is more what you want. Creates a new list of mod3 items of the incoming list. ... | 1 | 2016-10-05T04:00:21Z | [
"python",
"list",
"loops"
] |
Applying modulo to all elements of a python list and getting some correct some incorrect elements | 39,865,185 | <p>I am implementing a function that reduces all the elements of a list modulo 3. Here is what I have:</p>
<pre><code>def reduceMod3(l):
for i in l:
l[i] = l[i] % 3
return l
</code></pre>
<p>when I call this function on L = [1,2,3,4,5,6,7,8,9] I get:</p>
<pre><code>L = [1, 2, 0, 4, 2, 6, 1, 8, 0]
</c... | 3 | 2016-10-05T03:56:01Z | 39,865,221 | <p>When you write <code>for i in l</code>, you are accessing each element of the list, not the index. Instead, you should write </p>
<pre><code>for i in range(len(l)):
</code></pre>
<p>You can also solve this with a list comprehension:</p>
<pre><code>return [item % 3 for item in l]
</code></pre>
| 4 | 2016-10-05T04:00:46Z | [
"python",
"list",
"loops"
] |
Merging rows in pandas | 39,865,192 | <p>Say I have a dataframe that looks something like this</p>
<pre><code>Line VarA VarB
345 Something abc
346 Something2 def
347 Something ghi
348 Something2 jkl
349 Something mno
350 Something2 pqr
351 Something stu
352 Something2 vwx
</code></pre>
<p>How can I turn this d... | 0 | 2016-10-05T03:56:31Z | 39,865,328 | <p>You can just <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow">sum</a></p>
<pre><code>print(df.groupby('VarA')['VarB'].sum())
VarA
somet... | 2 | 2016-10-05T04:12:48Z | [
"python",
"pandas",
"dataframe"
] |
Using datetime.now() in Django view | 39,865,207 | <p><strong>The Code</strong></p>
<p>I am using datetime.now() as part of a filter in a Django view as follows:</p>
<pre><code>def get_now():
return timezone.now()
class BulletinListView(ListView):
model = Announcement
template_name = 'newswire/home.html'
def get_context_data(self, **kwargs):
... | 0 | 2016-10-05T03:58:28Z | 39,888,221 | <blockquote>
<p>the value does not update each time the view is called which results
in the wrong data being filtered when the next day comes around</p>
</blockquote>
<p>You have to decide which "next day" are you talking about? Is it:</p>
<ol>
<li>The next day for the user visiting your site.</li>
<li>The next d... | 0 | 2016-10-06T05:33:04Z | [
"python",
"django",
"datetime",
"gunicorn"
] |
Grading program having problems with while loop and using different data types | 39,865,251 | <p>I'm making a program where I need to have the user input a series of homework grades (ranging from 0 to 10) until they type 'done' in which case I must calculate the average of the scores and provide a corresponding letter grade. My trouble is, I don't know how to calculate the average when I don't have the exact nu... | 0 | 2016-10-05T04:03:53Z | 39,865,272 | <p>The input is a string type so you must explicitly convert it to an integer using something like "number = int(number)".</p>
<p>You could create a separate counting variable that is incremented each time through the loop, and then use that final value to divide when you are done.</p>
| 0 | 2016-10-05T04:06:28Z | [
"python"
] |
Grading program having problems with while loop and using different data types | 39,865,251 | <p>I'm making a program where I need to have the user input a series of homework grades (ranging from 0 to 10) until they type 'done' in which case I must calculate the average of the scores and provide a corresponding letter grade. My trouble is, I don't know how to calculate the average when I don't have the exact nu... | 0 | 2016-10-05T04:03:53Z | 39,865,320 | <p>Outside of your <code>while</code> loop, you can keep an array of grades you've seen so far. It will start out empty. </p>
<pre><code>arr = []
</code></pre>
<p>Every time you see a new grade, you can append it to the array. </p>
<pre><code>newGrade = input("Enter your homework grade")
arr.append(float(newGrade)*1... | 0 | 2016-10-05T04:12:05Z | [
"python"
] |
Grading program having problems with while loop and using different data types | 39,865,251 | <p>I'm making a program where I need to have the user input a series of homework grades (ranging from 0 to 10) until they type 'done' in which case I must calculate the average of the scores and provide a corresponding letter grade. My trouble is, I don't know how to calculate the average when I don't have the exact nu... | 0 | 2016-10-05T04:03:53Z | 39,865,322 | <p>Kevin's tells you to make an integer, say count = 0, and increment it every time you ask for a grade.</p>
<p>In the end, you take the sum / count.</p>
<p>Here is a slightly improved way on top of that:
start with count = 0</p>
<pre><code> Do:
Ask for grade
AVG = (AVG*count + new grade)/(count+1)
count... | 0 | 2016-10-05T04:12:30Z | [
"python"
] |
Adding counter/index to a list of lists in Python | 39,865,305 | <p>I have a list of lists of strings:</p>
<pre><code>listBefore = [['4', '5', '1', '1'],
['4', '6', '1', '1'],
['4', '7', '8', '1'],
['1', '2', '1', '1'],
['2', '3', '1', '1'],
['7', '8', '1', '1'],
['7', '9', '1', '1'],
... | 1 | 2016-10-05T04:10:15Z | 39,865,388 | <p>You can perform this with a list comprehension</p>
<pre><code>listAfter = [listBefore[i][:len(listBefore[i])/2] + [str(i+1)] + listBefore[i][len(listBefore[i])/2:] for i in range(len(listBefore))]
</code></pre>
| 1 | 2016-10-05T04:20:15Z | [
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.