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 |
|---|---|---|---|---|---|---|---|---|---|
Scrapy: overwrite DEPTH_LIMIT variable based on value read from custom config | 38,635,787 | <p>I am using <code>InitSpider</code> and read a custom <code>json</code> configuration within the <code>def __init__(self, *a, **kw):</code> method.</p>
<p>The json config file contains a directive with which I can control the crawling depth. I can already successfully read this configuration file and extract the val... | 0 | 2016-07-28T12:01:54Z | 38,734,764 | <p><code>DEPTH_LIMIT</code> is used in <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/spidermiddlewares/depth.py" rel="nofollow"><code>scrapy.spidermiddlewares.depth.DepthMiddleware</code></a>. As you might have had a quick look at the code, you'll see that the <code>DEPTH_LIMIT</code> value is read only ... | 1 | 2016-08-03T05:03:18Z | [
"python",
"scrapy"
] |
Its saying the variable i have defined was "referenced before assignment" | 38,635,843 | <p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it wil... | 1 | 2016-07-28T12:03:45Z | 38,636,202 | <p>For now, just do <code>global houseCount</code> within the <code>housePlay()</code> function - that should get you over the hump. </p>
| 1 | 2016-07-28T12:20:42Z | [
"python",
"python-3.x",
"blackjack"
] |
Its saying the variable i have defined was "referenced before assignment" | 38,635,843 | <p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it wil... | 1 | 2016-07-28T12:03:45Z | 38,636,208 | <p><code>def housePlay(houseCount):</code>
Pass houseCount as argument in your function defination </p>
<pre><code> housePlay(houseCount)
</code></pre>
<p>call housePlay function like this.</p>
| 3 | 2016-07-28T12:21:03Z | [
"python",
"python-3.x",
"blackjack"
] |
Its saying the variable i have defined was "referenced before assignment" | 38,635,843 | <p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it wil... | 1 | 2016-07-28T12:03:45Z | 38,636,260 | <p>Add <code>global houseCount</code> at the beginning of your function <code>housePlay()</code> </p>
<p>Explanation : as it is said in a comment, the variable you are trying to look at, <code>houseCount</code>, is not found in the function before being assigned a value. You can use the other variables (<code>a</code... | 1 | 2016-07-28T12:22:52Z | [
"python",
"python-3.x",
"blackjack"
] |
Its saying the variable i have defined was "referenced before assignment" | 38,635,843 | <p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it wil... | 1 | 2016-07-28T12:03:45Z | 38,649,379 | <p>A good design practice to follow when coding in Python is to break up as much as possible into small, self-contained functions. This is what you have started to do with your <code>housePlay</code> function. Unfortunately for you and your code, Python also has <strong>scoping rules</strong>. That is, a variable defin... | 0 | 2016-07-29T01:59:51Z | [
"python",
"python-3.x",
"blackjack"
] |
better maintainable way to combine strings from multiple options | 38,635,893 | <p>I have a scenario where the user can pass in multiple options. For each option passed in, I will get the text and then finally merge the text from multiple options and return a single string. Here is how I'm doing it for three options that I accept today. The code already looks unmaintainable and as I add more optio... | 0 | 2016-07-28T12:06:20Z | 38,636,177 | <p>Use a <code>dict</code> to map your option names to the appropriate function which returns the option text, join those together, then take the unique words, eg:</p>
<pre><code>from collections import OrderedDict
options = {
'option1': get_text_for_option1,
'option2': get_text_for_option2,
'option3': ge... | 2 | 2016-07-28T12:19:29Z | [
"python",
"python-2.7",
"dry"
] |
better maintainable way to combine strings from multiple options | 38,635,893 | <p>I have a scenario where the user can pass in multiple options. For each option passed in, I will get the text and then finally merge the text from multiple options and return a single string. Here is how I'm doing it for three options that I accept today. The code already looks unmaintainable and as I add more optio... | 0 | 2016-07-28T12:06:20Z | 38,642,258 | <pre><code>if (len(self.options.passedin.split(",")) > 0): #multiple options were passed in
ops = self.options.passedin.split(",")
opts = {
'op1': get_text_for_option1() if 'option1' in ops else ' '
'op2': get_text_for_option2() if 'option2' in ops else ' '
'op3': get_text_for_option3... | 0 | 2016-07-28T16:44:11Z | [
"python",
"python-2.7",
"dry"
] |
Python class, data structure and proper architecture | 38,635,975 | <p>I'm writing a program, which request user information from different services, puts them together in some ways. manages stuff and does some slack interaction.
All my python projects get problematic at a certain size. imports start to become recursive and handling data around becomes annoying. </p>
<p>A quick exampl... | 0 | 2016-07-28T12:10:40Z | 38,636,063 | <p>You have <strong>two</strong> copies of the main module now, each a separate entry in <code>sys.modules</code>:</p>
<ol>
<li><p>The initial Python script, started from the command-line, is always called <code>__main__</code>.</p></li>
<li><p>You imported the <code>A.py</code> file as the <code>A</code> module. This... | 3 | 2016-07-28T12:14:59Z | [
"python",
"import",
"architecture"
] |
How to implement non overlapping rolling functionality on MultiIndex DataFrame | 38,636,293 | <p>So far I've found <a href="http://stackoverflow.com/questions/25879735/how-to-implement-a-function-with-non-overlapping-and-rolling-features-simultaneo">this question</a> but it doesn't solve my problem due to the facts that: </p>
<ol>
<li>I have a MultiIndex DataFrame </li>
<li>The inner level has different amount... | 1 | 2016-07-28T12:24:26Z | 38,637,845 | <p>Ok, roll up your sleeve, this takes a bit of work:</p>
<pre><code>new_level0 = []
new_level1 = []
new_values = []
for level0 in df.index.levels[0].values:
#this will loop with A and B
#retrieve the values
level1_values = df[level0]['Value'].values
#retrieve the index, we will keep some of the val... | 0 | 2016-07-28T13:27:18Z | [
"python",
"python-3.x",
"pandas"
] |
How to implement non overlapping rolling functionality on MultiIndex DataFrame | 38,636,293 | <p>So far I've found <a href="http://stackoverflow.com/questions/25879735/how-to-implement-a-function-with-non-overlapping-and-rolling-features-simultaneo">this question</a> but it doesn't solve my problem due to the facts that: </p>
<ol>
<li>I have a MultiIndex DataFrame </li>
<li>The inner level has different amount... | 1 | 2016-07-28T12:24:26Z | 38,637,883 | <h1>Groupby with custom resample function</h1>
<p>You will most likely need custom resampling to do this. It is a little <em>hacky</em> but might work.</p>
<ol>
<li>Remove all <code>MulitIndex</code>ing to deal with just regular column <code>groupby()</code>s</li>
<li><a href="http://pandas.pydata.org/pandas-docs/st... | 1 | 2016-07-28T13:28:19Z | [
"python",
"python-3.x",
"pandas"
] |
Application python.exe had been blocked from accessing graphics devices - OpenCL | 38,636,308 | <p>I have an OpenCL programm <a href="https://github.com/john-hu/gpgpu/tree/master/opencl/trade" rel="nofollow">here</a>. It works good at Intel integrated GPU but not at NVidia GTX950M. The question is "my windows 10 always saying my app is blocked". These are what I had done and found:</p>
<ol>
<li><p>I got a GPU cr... | 0 | 2016-07-28T12:25:10Z | 38,656,366 | <p>I found the answer finally. We are pretty close to the answer: TdrDelay.</p>
<p>In Windows, there is another registry key to disable TDR (Timeout Detection and Recovery): <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff569918(v=vs.85).aspx" rel="nofollow">TdrLevel</a>. Once this registry key se... | 0 | 2016-07-29T10:19:26Z | [
"python",
"windows",
"opencl",
"nvidia"
] |
Python Pandas self join for merge cartesian product to produce all combinations and sum | 38,636,460 | <p>I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems.</p>
<p>Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) and that does not seem to be optimal for this data processing.</p>
<p>I made a datafra... | 3 | 2016-07-28T12:31:29Z | 38,638,273 | <p>I ran this for combinations of 6 and found no teams that satisfied. I used 5 instead.</p>
<p>This should get you there:</p>
<pre><code>from itertools import combinations
import pandas as pd
s = df.set_index('Name').squeeze()
combos = pd.DataFrame([c for c in combinations(s.index, 5)])
combo_salary = combos.appl... | 2 | 2016-07-28T13:43:55Z | [
"python",
"python-2.7",
"pandas",
"linear-programming"
] |
Python Pandas self join for merge cartesian product to produce all combinations and sum | 38,636,460 | <p>I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems.</p>
<p>Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) and that does not seem to be optimal for this data processing.</p>
<p>I made a datafra... | 3 | 2016-07-28T12:31:29Z | 38,638,795 | <p>Here's a non-Pandas solution using a simple algorithm. It generates combinations recursively from a list of players sorted by salary. This lets it skip generating combinations that exceed the salary cap.</p>
<p>As piRSquared mentions, there are no teams of 6 that fall within the salary limits stated in the question... | 1 | 2016-07-28T14:04:10Z | [
"python",
"python-2.7",
"pandas",
"linear-programming"
] |
Python Pandas self join for merge cartesian product to produce all combinations and sum | 38,636,460 | <p>I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems.</p>
<p>Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) and that does not seem to be optimal for this data processing.</p>
<p>I made a datafra... | 3 | 2016-07-28T12:31:29Z | 38,642,499 | <p>As mentioned in the comments, this is a constraint satisfaction problem. It has a combinatorial part but since you defined no objectives to minimize or maximize, it is not an optimization problem (yet). You can approach this problems in many ways: you can try brute-force like piRSquared or use a heuristic algorithm ... | 1 | 2016-07-28T16:56:49Z | [
"python",
"python-2.7",
"pandas",
"linear-programming"
] |
Solving simultaneous equations in python | 38,636,482 | <p>I have following test program. My query is two folded: (1) Some how the solution is giving zero and (2) Is it appropriate to use this <code>x2= np.where(x > y, 1, x)</code> kind of conditions on variables ? Are there any constrained optimization routines in Scipy ? </p>
<pre><code>a = 13.235
b = 70.678
def sys... | 2 | 2016-07-28T12:32:28Z | 39,234,606 | <p>First up, your <code>system</code> function is an identity, since you <code>return X</code> instead of <code>return f</code>. The return should be the same shape as the <code>X</code> so you had better have </p>
<pre><code>f = np.array([2*x2 - y - a, 3*x2 + 2*y- b])
</code></pre>
<p>Next the function, as written h... | 1 | 2016-08-30T18:25:20Z | [
"python",
"python-3.x",
"numpy"
] |
Histogram of my cam in real time | 38,636,520 | <p>Im trying to show the histogram in real time from grayscale of my webcam, the problem is that histogram is not being update and my cam stop until i close histogram's window. How can i fix this? I want to show the grayscale img from my webcam and its histogram in same time, is possible do that?</p>
<pre><code>import... | 0 | 2016-07-28T12:34:09Z | 38,709,401 | <p>I have been working for a while in the same task. After some time, I have a piece of code that works very good. It displays the camera image in a window and a histogram in other. Since I'm interested in finding colors, I'm working with the "hue" channel of each frame.</p>
<pre><code># import the necessary packages
... | 2 | 2016-08-01T23:06:19Z | [
"python",
"opencv",
"histogram"
] |
Python Webdriver -unexpected EOF while parsing (<string>, line 1) | 38,636,729 | <p>I'm using Python with webdriver</p>
<p>I'm trying to locate element with find element with xpath and get :"unexpected EOF while parsing (, line 1)"</p>
<p>When I try to locate it by finding element with class name, it works well.</p>
<p>The problem is that I can't use it since I have several classes with the same... | 2 | 2016-07-28T12:43:32Z | 38,639,400 | <p>The following query will look for a <code>path</code> with the parent tree of <code>div/svg/g/g[1]</code>, with a class equalling <code>st0</code> and at index <code>[1]</code>:</p>
<pre><code>self.SELENIUM_DRIVER.find_element_by_xpath('//div/svg/g/g[1]/path[@class=st0][1]')
</code></pre>
<p>If the parent tree is ... | 0 | 2016-07-28T14:32:34Z | [
"python",
"selenium-webdriver"
] |
Python Webdriver -unexpected EOF while parsing (<string>, line 1) | 38,636,729 | <p>I'm using Python with webdriver</p>
<p>I'm trying to locate element with find element with xpath and get :"unexpected EOF while parsing (, line 1)"</p>
<p>When I try to locate it by finding element with class name, it works well.</p>
<p>The problem is that I can't use it since I have several classes with the same... | 2 | 2016-07-28T12:43:32Z | 38,645,197 | <p>I think this is the problem with your provided Id <code>j_id0:j_id5:j_id6:j_id36</code> and as you are saying class name is same for some other elements as well, So you should try using <code>xpath</code> by passing index as below :-</p>
<pre><code>self.SELENIUM_DRIVER.find_element_by_xpath('(//path[@class=st0])[1]... | 0 | 2016-07-28T19:29:55Z | [
"python",
"selenium-webdriver"
] |
ValueError: too many values to unpack - Is it possible to ignore one value? | 38,636,765 | <p>The following line returns an error:</p>
<pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True)
</code></pre>
<p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only... | 2 | 2016-07-28T12:44:57Z | 38,636,821 | <p>You can use <code>*rest</code> from Python 3.</p>
<pre><code>>>> x, y, z, *rest = 1, 2, 3, 4, 5, 6, 7
>>> x
1
>>> y
2
>>> rest
[4, 5, 6, 7]
</code></pre>
<p>This way you can always be sure to not encounter unpacking issues.</p>
| 7 | 2016-07-28T12:47:06Z | [
"python",
"unpack"
] |
ValueError: too many values to unpack - Is it possible to ignore one value? | 38,636,765 | <p>The following line returns an error:</p>
<pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True)
</code></pre>
<p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only... | 2 | 2016-07-28T12:44:57Z | 38,636,933 | <p>It's common to use <code>_</code> to denote unneeded variables.</p>
<pre><code>a, b, c, d, e, _ = my_func_that_gives_6_values()
</code></pre>
<p>This is also often used when iterating a certain number of times.</p>
<pre><code>[random.random() for _ in range(10)] # gives 10 random values
</code></pre>
| 2 | 2016-07-28T12:51:17Z | [
"python",
"unpack"
] |
ValueError: too many values to unpack - Is it possible to ignore one value? | 38,636,765 | <p>The following line returns an error:</p>
<pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True)
</code></pre>
<p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only... | 2 | 2016-07-28T12:44:57Z | 38,636,953 | <p>Just <a class='doc-link' href="http://stackoverflow.com/documentation/python/289/indexing-and-slicing#t=201607281251592864833">slice</a> the last one out:</p>
<pre><code>self.m, self.userCodeToUserNameList, \
self.itemsList, self.userToKeyHash, \
self.fileToKeyHash = readUserFileMatrixFromFile(x,True)[:-1]
</code>... | 0 | 2016-07-28T12:52:03Z | [
"python",
"unpack"
] |
ValueError: too many values to unpack - Is it possible to ignore one value? | 38,636,765 | <p>The following line returns an error:</p>
<pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True)
</code></pre>
<p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only... | 2 | 2016-07-28T12:44:57Z | 38,637,039 | <p>Just, use the <strong>throw-away</strong> variable '_'</p>
<pre><code> self.m,
self.userCodeToUserNameList,
self.itemsList,
self.userToKeyHash,
self.fileToKeyHash,
_ = readUserFileMatrixFromFile(x,True)
</code></pre>
<p>here '_' is deliberately ignored.</p>
| -1 | 2016-07-28T12:55:53Z | [
"python",
"unpack"
] |
Phantomjs click on checkbox | 38,636,770 | <p>I'm using selenium and phantomjs and I would like to learn how to click a checkbox properly. For exemple in this page: <a href="https://www.udacity.com/courses/android" rel="nofollow">https://www.udacity.com/courses/android</a></p>
<p>I would like to check "Free Courses", so I tried this:</p>
<pre><code>from selen... | 2 | 2016-07-28T12:45:08Z | 38,637,148 | <p>Your <code>xpath</code> locates to <code>label</code> element while you want to click on <code>checkbox</code> element, As I'm seeing in your provided <a href="https://www.udacity.com/courses/android" rel="nofollow">website</a>, there is no need to create <code>xpath</code> to select <code>Free Course</code> checkbo... | 0 | 2016-07-28T13:00:19Z | [
"python",
"selenium-webdriver",
"click",
"phantomjs"
] |
Filter on index in spark rdd | 38,636,896 | <p>Is it possible to filter on an specific column value in an RDD
.Eg:</p>
<pre><code>[(u'62d45630-587a-4290-91e1-a86fbe019bb5', (Row(process_id=1, event_id=u'62d45630-587a-4290-91e1-a86fbe019bb5', event_type=u'PlannedCustomerChoiceWasUpdated', publishedDate=u'2016-07-27T04:16:13.650Z', tgt_tbl_n=u'raw_plan', subj_are... | -2 | 2016-07-28T12:49:45Z | 38,638,243 | <p>I do not quite understand what you want to accomplish as your question is a little unclear to me but there are different ways to filter on an RDD.</p>
<p>An RDD itself does not have a schema so you cannot filter columnwise here as far as i know. If you want to run SQL queries on an RDD you can turn the RDD into a D... | 0 | 2016-07-28T13:42:27Z | [
"python",
"apache-spark",
"pyspark",
"rdd"
] |
Automatically run another script after i run main code in PyCharm | 38,636,905 | <p>I have been looking for a feature where PyCharm notifies me that a script has finished running in the console after each run. At present, I have to add <code>print('done')</code> after each code.</p>
<p>I got smarter so I defined <code>d = 'done'</code> once and after each run I simply add a <code>d</code> so it pr... | 3 | 2016-07-28T12:50:03Z | 38,686,877 | <p>All Intellij-based IDEs support shell integration, scripting, plugins etc. I bet you can insert your notifications in a build script.
<em>Run</em> menu-> <em>edit configurations</em></p>
<p>Actually, CLion shows notification on failed/successful build, but I did make something like this with PhpStorm. </p>
<p>Yo... | 0 | 2016-07-31T17:56:34Z | [
"python",
"pycharm"
] |
Design pattern for transformation of array data in Python script | 38,637,020 | <p>I currently have a Python class with many methods each of which performs a transformation of time series data (primarily arrays). Each method must be called in a specific order, since the inputs of each function specifically rely on the outputs of the previous. Hence my code structure looks like the following:</p>
... | 0 | 2016-07-28T12:55:12Z | 38,637,784 | <p>One option is to define your methods like this:</p>
<pre><code>def perform_transformation(self, data=None):
if data is None:
perform action on self.data
else:
perform action on data
</code></pre>
<p>This way, you have the ability to call them at any time you want.</p>
| 0 | 2016-07-28T13:25:32Z | [
"python",
"algorithm",
"functional-programming",
"time-series"
] |
Design pattern for transformation of array data in Python script | 38,637,020 | <p>I currently have a Python class with many methods each of which performs a transformation of time series data (primarily arrays). Each method must be called in a specific order, since the inputs of each function specifically rely on the outputs of the previous. Hence my code structure looks like the following:</p>
... | 0 | 2016-07-28T12:55:12Z | 38,639,220 | <pre><code>class Algorithm:
@staticmethod
def perform_transformation_a(data):
return 350 * data
@staticmethod
def perform_transformation_b(data):
return 400 * data
def perform_transformations(data):
transformations = (Algorithm.perform_transformation_a,
Algo... | 1 | 2016-07-28T14:22:55Z | [
"python",
"algorithm",
"functional-programming",
"time-series"
] |
pandas Panel max | 38,637,032 | <p>I have pandas.Panel4D object and I would like to find the maximum of the all values.</p>
<p>The current way:</p>
<pre><code>p4d.max().max().max().max()
</code></pre>
<p>In there a better way to achieve the same result?</p>
<p>(np.max(p4d) does not work.)</p>
<p>Also is there is an equivalent for idxmax for pane... | 2 | 2016-07-28T12:55:43Z | 38,637,324 | <p>Use <code>max</code> on the <code>values</code> attribute.</p>
<pre><code>pd.Panel4D(np.arange(16).reshape(2, 2, 2, 2)).values.max()
15
</code></pre>
<p>numpy <code>ndarray</code> <code>max</code> method returns the maximum over the entire structure unless you specify an axis. You can access the underlying <code... | 3 | 2016-07-28T13:07:10Z | [
"python",
"numpy",
"pandas",
"panel"
] |
Join two dataframes. Add a column value if index value of first matches the second | 38,637,059 | <p>I have two dataframes, call them 1st and 2nd.
1st has index - 'customer'. 2nd also has index - 'customer' with some similar and some different values.
1st has columns 'P' and 'Q'. 2nd also has columns by the name 'P' and 'Q'.
I want to join both dataframes like, if any index value of 1st matches index value of 2nd, ... | 0 | 2016-07-28T12:56:42Z | 38,637,683 | <pre><code>np.random.seed([3,1415])
A = pd.DataFrame(np.random.rand(3, 2),
pd.Index(list('abc'),name='customer'),
list('PQ'))
B = pd.DataFrame(np.random.rand(3, 2),
pd.Index(list('bcd'),name='customer'),
list('PQ'))
A
</code></pre>
<p><a href="http:/... | 2 | 2016-07-28T13:21:49Z | [
"python",
"pandas"
] |
Complete the relative paths to absolute using Python | 38,637,191 | <p>I have rewritten the complete code to fetch the href and src link using beautifulsoup this time by the request of many SO users instead of regex. Here is the code:</p>
<pre><code>import os
from bs4 import BeautifulSoup
from urllib.parse import urlparse
path = urlpars(http://www.example.com/dynamic/search.aspx?sear... | 1 | 2016-07-28T13:01:59Z | 38,653,668 | <p>Its final code and everything is working perfectly thanks to <a href="http://stackoverflow.com/users/4559110/akash-karothiya">akash karothiya</a>'s solution.</p>
<p>This code changes all kinds of relative links into absolute links in any given html code. </p>
<pre><code>import os, re
from bs4 import BeautifulSo... | 0 | 2016-07-29T08:07:23Z | [
"python",
"html",
"beautifulsoup"
] |
How can I speed up my program created in Jupyter Notebook? | 38,637,263 | <p>I have a python program which is created in a Jupter Notebook. Due to the datasize and the optimization algo I used, a 4-fold custom cross validation within some range takes about 30 minutes to finish.</p>
<p>My computer's environment: CPU i5 3.3 GHz, 8 GB DDR3 RAM, SSD.</p>
<p>I'm wondering </p>
<ol>
<li><p>If i... | 0 | 2016-07-28T13:04:51Z | 38,637,367 | <p>1: There are a couple paid HPC servers such as Amazon, but this is off topic for SO.</p>
<p>2: The iteration of the cross validation can be done in parallel.</p>
<p>As the cross validations are not connected, i would suggest something like this:</p>
<pre><code>import multiprocessing
def validation_function(args)... | 0 | 2016-07-28T13:09:10Z | [
"python",
"jupyter-notebook"
] |
multiprocessing.Queue seems to go away? OS (pipe destruction) vs Python? | 38,637,282 | <p>I'm using multiprocessing.queues.JoinableQueue as follows:</p>
<p>A very long-running thread (multiple days) polls an API for XML. The thread that does this simply parses the XML into objects and shoves these into the queue.</p>
<p>The handling of each object takes significantly more time than parsing the XML and... | 1 | 2016-07-28T13:05:35Z | 38,796,547 | <p>The issue was being caused by a subtle reality with multiprocessing.Queue. ANY process which called queue.put will be running a background thread that writes to the named pipe.</p>
<p>In my particular case, while there isn't a significant amount of data being posted to the results queue (items that couldn't be han... | 0 | 2016-08-05T19:28:33Z | [
"python",
"linux",
"multiprocessing"
] |
cx_Freeze: shortcutDir gives error | 38,637,337 | <p>I'm creating a single file exe form my Python program. I'm using cx_Freeze.
Everything works perfect except one little agnoying thing.</p>
<p>When I install my program everything installs as it should do, including the shortcut on my desktop.</p>
<p>BUT...When I want to start the program with the shortcut on the d... | 0 | 2016-07-28T13:07:45Z | 38,645,738 | <p>After a long search I found a solution.</p>
<p><a href="http://stackoverflow.com/questions/24195311/how-to-set-shortcut-working-directory-in-cx-freeze-msi-bundle">How to set shortcut working directory in cx_freeze msi bundle?</a></p>
<p>I was able to fix the problem by making a small change to cx_Freeze/windist.py... | 0 | 2016-07-28T20:03:15Z | [
"python",
"cx-freeze"
] |
Why client socket connection is not closed after all data received from server? | 38,637,365 | <p>I'm learning socket programming in python, </p>
<p><strong>Server Code:</strong> </p>
<pre><code>import socket
srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srvsock.bind(('', 23000))
srvsock.listen(5)
while True:
clisock, (rem_host, rem_port) = srvsock.accept()
print "conection established ... | 1 | 2016-07-28T13:09:05Z | 38,637,900 | <p>The issue is caused because the server keeps reading data from the client until it reads no data. This only happens when the connected client closes its connection. Until then, the server socket will block (i.e. temporarily suspect operations) until the client sends more data.</p>
<p>Bottom line: either the client ... | 0 | 2016-07-28T13:29:10Z | [
"python",
"sockets"
] |
Why client socket connection is not closed after all data received from server? | 38,637,365 | <p>I'm learning socket programming in python, </p>
<p><strong>Server Code:</strong> </p>
<pre><code>import socket
srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srvsock.bind(('', 23000))
srvsock.listen(5)
while True:
clisock, (rem_host, rem_port) = srvsock.accept()
print "conection established ... | 1 | 2016-07-28T13:09:05Z | 38,638,251 | <p>server code:</p>
<pre><code>while True:
clisock, (rem_host, rem_port) = srvsock.accept()
print "conection established with host %s and port %s" % (rem_host, rem_port)
while True:
strg = clisock.recv(20)
print '[message from client:] %s'%strg
clisock.send(strg)
print 'abou... | 0 | 2016-07-28T13:42:54Z | [
"python",
"sockets"
] |
Map over a dict | 38,637,415 | <p>I'm trying to do this:</p>
<pre><code>list(map(lambda x: x.name, my_dict))
</code></pre>
<p>where <code>my_dict</code> is a dict of form <code>k, v</code> where <code>v</code> is an object and <code>v.name</code> is defined.</p>
<p>The problem is it is using the key <code>k</code> for <code>x</code> where I reall... | 2 | 2016-07-28T13:11:02Z | 38,637,557 | <p>You don't need to use <code>map()</code> and then convert the result to a list. Instead you can use simply use a list comprehension by looping over the dictionary values:</p>
<pre><code>[v.name for v in my_dict.values()]
</code></pre>
<p>Or still if you are looking for a functional approach you can use <code>attrg... | 2 | 2016-07-28T13:17:14Z | [
"python",
"python-3.x"
] |
Map over a dict | 38,637,415 | <p>I'm trying to do this:</p>
<pre><code>list(map(lambda x: x.name, my_dict))
</code></pre>
<p>where <code>my_dict</code> is a dict of form <code>k, v</code> where <code>v</code> is an object and <code>v.name</code> is defined.</p>
<p>The problem is it is using the key <code>k</code> for <code>x</code> where I reall... | 2 | 2016-07-28T13:11:02Z | 38,637,577 | <p>To retrieve view of values, you may use <code>.values</code> method.</p>
<pre><code>map(callable, my_dict.values())
</code></pre>
<p>Obviously, <code>map</code> with trivial callables usually can be avoided in Python by using list or generator comprehensions.</p>
<pre><code>[x.name for x in my_dict.values()] # c... | 3 | 2016-07-28T13:17:56Z | [
"python",
"python-3.x"
] |
extracting values in a specific column and processing other columns values in pandas | 38,637,420 | <p>The following is a simplified blob of my dataframe. I want to process</p>
<p><a href="https://gist.github.com/ecenm/97248a1d1f6f301d662c6f238b6168df#file-first-csv" rel="nofollow">first.csv</a></p>
<pre class="lang-none prettyprint-override"><code>No.,Time,Source,Destination,Protocol,Length,Info,src_dst_pair
32577... | 0 | 2016-07-28T13:11:13Z | 38,643,363 | <pre><code>import pandas as pd
def extract_flows(g):
# Find the location of SYN packets
is_syn = g['Info'].fillna('').str.contains('\[SYN\]')
syn = g[is_syn].index.values
# Find the location of the FIN-ACK packets
is_finack = g['Info'].fillna('').str.contains('\[FIN, ACK\]')
finack = g[is_fin... | 1 | 2016-07-28T17:46:00Z | [
"python",
"csv",
"pandas"
] |
How to execute multiple update queries once in pymongo? | 38,637,480 | <p>I have more than 100000 update queries need to be execute, <code>db.collection_name.update(upsert=True)</code> can only execute one query statement,it is too slow if I execute all queries one by one.</p>
<p>Is there any way to collect multiple queries into a list then execute once in pymongo?</p>
<p>I tried use <... | 0 | 2016-07-28T13:13:53Z | 38,637,753 | <p>You could introduce a counter variable that ensures the updates are sent in batches because write commands can accept no more than 1000 operations so there's need to group operations to have at most 1000 operations and re-intialise the bulk operation when the loop hits the 1000 iteration. Also, DRY (Don't Repeat You... | 0 | 2016-07-28T13:24:37Z | [
"python",
"mongodb",
"pymongo"
] |
join file binary with text to create POST request body - python | 38,637,543 | <p>I'm trying to upload file to Google Drive using their API.</p>
<p>According to their specification, the body of the POST request should look like this:</p>
<pre><code>--foo_bar_baz
Content-Type: application/json; charset=UTF-8
{
"name": "My File"
}
--foo_bar_baz
Content-Type: image/jpeg
JPEG data
--foo_bar_ba... | 0 | 2016-07-28T13:16:40Z | 38,655,900 | <p>As discussed in <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">Advanced Usage</a>, </p>
<blockquote>
<p>Requests supports streaming uploads, which allow you to send large streams or files without reading them into memory. To stream and upload, simply provide a file-like object f... | 0 | 2016-07-29T09:58:35Z | [
"python",
"google-drive-sdk",
"python-requests"
] |
django-haystack with elastic search not building index for newly add index model | 38,637,635 | <p>I'm using Haystack 2.3.1 and trying to figure out multiple indexes.</p>
<p>I've got elasticsearch cores set up and defined each in HAYSTACK_CONNECTIONS, and
then I've created three SearchIndexes in search_indexes.py.</p>
<p>When I run the command manage.py rebuild_index, I see this warning.</p>
<p>Thanks for any ... | 0 | 2016-07-28T13:20:17Z | 38,656,368 | <p>Make sure that which version of <code>elasticsearch</code> you are using? If you are using <code>django-haystack</code> then your <code>elasticsearch</code> should be less than 2.00.</p>
| 0 | 2016-07-29T10:19:34Z | [
"python",
"django",
"elasticsearch"
] |
pyimage2 does not exist error when I try to insert an image to window | 38,637,637 | <p>I am trying to insert an image to window but I get an error.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Afro\Desktop\h.py", line 151, in start
pic_lab = Label(win... | 0 | 2016-07-28T13:20:24Z | 38,644,109 | <p>The string 'money.jpg' that is assigned to the variable name is missing a single quotation mark on the left.</p>
| 1 | 2016-07-28T18:26:20Z | [
"python",
"python-3.x",
"tkinter",
"python-imaging-library"
] |
Using a list of tuples on a function which take tuples | 38,637,638 | <p>I want to use a function which takes tuples as an argument, however I have a list of tuples and whenever I try feeding the list of tuples to the function it returns </p>
<pre><code> s = s.join(x)
TypeError: sequence item 0: expected str instance, tuple found
</code></pre>
<p>However with just one tupl... | -1 | 2016-07-28T13:20:26Z | 38,637,720 | <p>If you want to join the tuples separately you can use a list comprehension:</p>
<pre><code>[delimiter.join(x) for x in list_of_tup] # delimiter should be a string
</code></pre>
<p>Otherwise you need to unpack the tuples then join them all. Which for that aim you can use a nested list comprehension or <code>itertoo... | 0 | 2016-07-28T13:23:23Z | [
"python"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,637,795 | <p>Because you changed the value of y on the second example by setting y = test(6). Set y = test(y) on the first and you will get the same result.</p>
| 0 | 2016-07-28T13:25:59Z | [
"python",
"return",
"return-value"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,637,796 | <p>The only difference between the two snippets is that in the second one you reassign <code>y</code> to to the result of calling the function. That is all you need to do.</p>
| 0 | 2016-07-28T13:26:01Z | [
"python",
"return",
"return-value"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,637,857 | <p>In the first code, you have a global variable named  <code>y</code>, which you assign the value 6 to. When going into the function, you create a local variable, also called <code>y</code>, which you assign the value 6*6=36 to. When you leave the function, you return this value, but do not use it. Then, you print th... | 0 | 2016-07-28T13:27:39Z | [
"python",
"return",
"return-value"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,637,894 | <blockquote>
<p>Why does the first code snippet provide 36, 6 and not 36, 36 as in the second case?</p>
</blockquote>
<p>Because you defined an entirely new y variable whose value is 36, meanwhile the value outside the function is 6.</p>
<p>In the second case, you still have two y variables, but the one towards the... | 0 | 2016-07-28T13:28:59Z | [
"python",
"return",
"return-value"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,637,911 | <p>You don't assign the result of <code>test(y)</code> the variable y in your code</p>
<pre><code>y=int(raw_input('Enter: '))
# y= 6
# here you need to assign y= test(y)
test(y)
# test result is 36, but not saved to y
print 'Outside the function', y
# print 6
</code></pre>
| 0 | 2016-07-28T13:29:30Z | [
"python",
"return",
"return-value"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,638,015 | <p><strong>case #1 explained</strong></p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y; # returning 36
y=int(raw_input('Enter: ')) # here y is 6 as you read from user
test(y) # you are passing 6 and which computes y to be 36, though test is returni... | 1 | 2016-07-28T13:33:06Z | [
"python",
"return",
"return-value"
] |
Python passing arguments - a confused beginner | 38,637,687 | <p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p>
<pre><code>#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y
y = int(raw_input('Enter: '))
test(y)
print 'Outside t... | 0 | 2016-07-28T13:21:54Z | 38,638,563 | <p>There are two reasons the output is not the same:
- the scopes are different, in your first example, the y you assign in the function is <em>not</em> the same the y outside of it, even if they have the same name. To (over)simplify, you can think that, when you start a new function, there is a brand new memory spac... | 0 | 2016-07-28T13:54:41Z | [
"python",
"return",
"return-value"
] |
Python Regex to find image source | 38,637,734 | <p>I am new to Python and I am trying to get <strong>alt</strong> and <strong>images source</strong> from a website, but I am facing problem with the quote <code>'</code> and <code>"</code></p>
<pre><code>import requests,urllib,urllib2,re
rule = re.compile(r'^[^*$<,>?!\']*$')
r = requests.get('http://www.hotst... | -3 | 2016-07-28T13:23:48Z | 38,638,055 | <p>Use a parser instead:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
r = requests.get('http://www.hotstar.com/channels/star-plus')
soup = BeautifulSoup(r.text, "lxml")
imgs = soup.findAll('img')
for img in imgs:
print(img["alt"])
</code></pre>
| 0 | 2016-07-28T13:34:47Z | [
"python",
"regex"
] |
Python Regex to find image source | 38,637,734 | <p>I am new to Python and I am trying to get <strong>alt</strong> and <strong>images source</strong> from a website, but I am facing problem with the quote <code>'</code> and <code>"</code></p>
<pre><code>import requests,urllib,urllib2,re
rule = re.compile(r'^[^*$<,>?!\']*$')
r = requests.get('http://www.hotst... | -3 | 2016-07-28T13:23:48Z | 38,638,284 | <p>I took a quick look at this problem and I tried to look in to and I found a few different ways to go about it from looking at the links below. It looks like something like this has happened to other people. I took a quick glance at it, and thought maybe these might help. Try looking at a few of the pages below:</p>
... | 0 | 2016-07-28T13:44:05Z | [
"python",
"regex"
] |
BeautifulSoap to get first value using string/text | 38,637,792 | <p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautifulsoup</a> is handy for html parsing in python, but I meet problem to have clean code to get the value directly using <code>string</code> or <code>text</code></p>
<pre><code>from bs4 import BeautifulSoup
tr ="""
<table>
<... | 1 | 2016-07-28T13:25:55Z | 38,638,078 | <p>You could try this:</p>
<pre><code>for row in table.findAll("tr"):
td = row.findAll("td")
t = td[0]
print t.contents[0]
</code></pre>
<p>But that will only work if you are always looking for the text <em>before</em> the div tag</p>
| 1 | 2016-07-28T13:35:38Z | [
"python",
"beautifulsoup",
"html-parsing"
] |
BeautifulSoap to get first value using string/text | 38,637,792 | <p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautifulsoup</a> is handy for html parsing in python, but I meet problem to have clean code to get the value directly using <code>string</code> or <code>text</code></p>
<pre><code>from bs4 import BeautifulSoup
tr ="""
<table>
<... | 1 | 2016-07-28T13:25:55Z | 38,638,729 | <p>You could simply use the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find" rel="nofollow"><code>.find()</code></a> function by setting the <code>text</code> and <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument" rel="nofollow"><code>recursive</code></a> argume... | 2 | 2016-07-28T14:01:24Z | [
"python",
"beautifulsoup",
"html-parsing"
] |
BeautifulSoup4 fails to parse multiple tables | 38,637,870 | <p>I'd like to systematically scrape the privacy breach data found <a href="https://www.privacyrights.org/data-breach/new?title=" rel="nofollow">here</a> which is directly embedded in the HTML of the page. I've found various links on StackOverflow about <a href="http://stackoverflow.com/questions/37021747/missing-html-... | 0 | 2016-07-28T13:28:01Z | 38,638,148 | <p>Looking at the HTML delivered from the URL it appears that there only IS one table in it, which is precisely why Beautiful Soup can't find two!</p>
| 0 | 2016-07-28T13:38:26Z | [
"python",
"html",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
Conversion from U3 dtype to ascii | 38,638,013 | <p>I am reading data from a .mat file. The data is in form on numpy array.</p>
<pre><code>[array([u'ABT'], dtype='<U3')]
</code></pre>
<p>This is one element of the array. I want to get only the value 'ABT' from the array. Unicode normalize and Encode to ascii functions do not work.</p>
| 1 | 2016-07-28T13:32:59Z | 38,641,632 | <p><code>encode</code> is a string method, so can't work directly on an array of strings. But there are several ways of applying it to each string</p>
<p>Here I'm working Py3, so the default is unicode.</p>
<pre><code>In [179]: A=np.array(['one','two'])
In [180]: A
Out[180]:
array(['one', 'two'],
dtype='<... | 0 | 2016-07-28T16:11:50Z | [
"python",
"numpy",
"unicode",
"ascii"
] |
format Date in pandas style render | 38,638,025 | <p>I have a pandas dataframe with three columns of which the first is the Date. To produce a html output I use this: </p>
<pre><code>html_string = df.style.format({'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render()
</code></pre>
<p>how is it possible to specifiy the format of the Date as well.... | 2 | 2016-07-28T13:33:43Z | 38,638,369 | <p>You can do:</p>
<pre><code>html_string = df.style.format({'Date': "{:%Y.%m}",
'second': "{:0,.0f}",
'third': "{:0,.0f}"}).set_table_styles(styles).render()
</code></pre>
| 1 | 2016-07-28T13:47:19Z | [
"python",
"pandas"
] |
format Date in pandas style render | 38,638,025 | <p>I have a pandas dataframe with three columns of which the first is the Date. To produce a html output I use this: </p>
<pre><code>html_string = df.style.format({'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render()
</code></pre>
<p>how is it possible to specifiy the format of the Date as well.... | 2 | 2016-07-28T13:33:43Z | 38,638,417 | <p>For me works:</p>
<pre><code>html_string = df.style.format({'first': lambda x: "{}".format(x.strftime('%Y.%m')) ,
'second': "{:0,.0f}",
'third': "{:0,.0f}"}).set_table_styles('styles').render()
print (html_string)
</code></pre>
<p>Sample:</p>
<pre><co... | 1 | 2016-07-28T13:49:04Z | [
"python",
"pandas"
] |
format Date in pandas style render | 38,638,025 | <p>I have a pandas dataframe with three columns of which the first is the Date. To produce a html output I use this: </p>
<pre><code>html_string = df.style.format({'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render()
</code></pre>
<p>how is it possible to specifiy the format of the Date as well.... | 2 | 2016-07-28T13:33:43Z | 38,638,708 | <p>Actually it takes a string as argument...so this should work:</p>
<pre><code>html_string = df.style.format({'Date': "{:%Y.%m}",'second': "{:0,.0f}",'third': "{:0,.0f}"}).set_table_styles(styles).render()
</code></pre>
<p>thanks though</p>
| 0 | 2016-07-28T14:00:41Z | [
"python",
"pandas"
] |
How do I multiply a map of a variable in Python? | 38,638,054 | <p>Here's my code:</p>
<pre><code>elif cmd == "pay for dog":
name = input("Dog name? ")
for d in dogs:
if d["name"] == name:
print(d["name"] + " owes $" + d["days"])
</code></pre>
<p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, ... | -2 | 2016-07-28T13:34:41Z | 38,638,198 | <p>You can use casting. Assuming <code>d["days"]</code> is a number, <code>print("$"+str(d["days"]*30))</code> will show you the amount to pay.</p>
| 0 | 2016-07-28T13:40:35Z | [
"python",
"maps"
] |
How do I multiply a map of a variable in Python? | 38,638,054 | <p>Here's my code:</p>
<pre><code>elif cmd == "pay for dog":
name = input("Dog name? ")
for d in dogs:
if d["name"] == name:
print(d["name"] + " owes $" + d["days"])
</code></pre>
<p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, ... | -2 | 2016-07-28T13:34:41Z | 38,638,217 | <p>If I unterstand you correctly, you want </p>
<pre><code>print("%s owes $%.2f" % (d["name"], (30 * float(d["days"]))))
</code></pre>
| 0 | 2016-07-28T13:41:15Z | [
"python",
"maps"
] |
How do I multiply a map of a variable in Python? | 38,638,054 | <p>Here's my code:</p>
<pre><code>elif cmd == "pay for dog":
name = input("Dog name? ")
for d in dogs:
if d["name"] == name:
print(d["name"] + " owes $" + d["days"])
</code></pre>
<p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, ... | -2 | 2016-07-28T13:34:41Z | 38,638,682 | <p>I think this would do the needful</p>
<pre><code>for d in dogs:
if d['name'] == name:
print(d['name']+ " owes $" +str(int(d['day']) * 30))
</code></pre>
| 0 | 2016-07-28T14:00:04Z | [
"python",
"maps"
] |
How do I multiply a map of a variable in Python? | 38,638,054 | <p>Here's my code:</p>
<pre><code>elif cmd == "pay for dog":
name = input("Dog name? ")
for d in dogs:
if d["name"] == name:
print(d["name"] + " owes $" + d["days"])
</code></pre>
<p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, ... | -2 | 2016-07-28T13:34:41Z | 38,638,771 | <p>As I see, <code>d["days"]</code> is string.</p>
<p>Try this:</p>
<pre><code>print(d["name"] + " owes $" + str(30 * int(d["days"])))
</code></pre>
<p>or this:</p>
<pre><code>print("%s owes $%d" % (d["name"], (30 * int(d["days"]))))
</code></pre>
| 1 | 2016-07-28T14:03:16Z | [
"python",
"maps"
] |
over-plot dataframes with seaborn | 38,638,107 | <p>I have a few dataframes to plot, do I need to aggregate them before initializing something like JointGrid or can I access the axis ala matplotlib's ax.plot() style?</p>
| -1 | 2016-07-28T13:36:40Z | 38,638,336 | <p>The interest of using Seaborn is that the axes generated are data-aware, i.e. it inspects the full dataset, and creates Facets and plot properties that are linked to the properties of your data. </p>
<p>You could technically access each subplot and plot your individual dataframes in each of them, but you would lose... | 1 | 2016-07-28T13:46:11Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
How to avoid printing unnecessary newline in python2? | 38,638,109 | <p>Here iam writing a code snippet <a href="http://ideone.com/cM10zZ" rel="nofollow">Code here</a>which takes some input and for each test case a particular operation has to be performed.Iam done with the job but here the actual output does not produce any newlines in between the test cases ,but my code is either putti... | -1 | 2016-07-28T13:36:47Z | 38,638,316 | <p>To be able to use the print function in a Python 2.x program, insert at the beginning of your module file this:</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>This "Python 3 updated" <code>print</code> to becomes a function, and it works much better that way.</p>
<p>For the print function, ... | 1 | 2016-07-28T13:45:17Z | [
"python",
"python-2.7",
"format",
"newline"
] |
How to avoid printing unnecessary newline in python2? | 38,638,109 | <p>Here iam writing a code snippet <a href="http://ideone.com/cM10zZ" rel="nofollow">Code here</a>which takes some input and for each test case a particular operation has to be performed.Iam done with the job but here the actual output does not produce any newlines in between the test cases ,but my code is either putti... | -1 | 2016-07-28T13:36:47Z | 38,640,527 | <p>Py2:</p>
<pre><code>print '\n',
</code></pre>
<p>Py3:</p>
<pre><code>print("\n", end="")
</code></pre>
<p>That's all.</p>
| 0 | 2016-07-28T15:20:03Z | [
"python",
"python-2.7",
"format",
"newline"
] |
How to avoid printing unnecessary newline in python2? | 38,638,109 | <p>Here iam writing a code snippet <a href="http://ideone.com/cM10zZ" rel="nofollow">Code here</a>which takes some input and for each test case a particular operation has to be performed.Iam done with the job but here the actual output does not produce any newlines in between the test cases ,but my code is either putti... | -1 | 2016-07-28T13:36:47Z | 38,640,675 | <p><code>print</code> will append <code>\n</code> automatically, so <code>print('\n')</code> will give two new lines. We just need print a blank string <code>print ''</code> to replace <code>print('\n')</code></p>
| 0 | 2016-07-28T15:26:47Z | [
"python",
"python-2.7",
"format",
"newline"
] |
How works is and id in python using integers above preallocated -5, 255 range | 38,638,180 | <p>Running interpretator</p>
<pre><code>>>> x = 5000
>>> y = 5000
>>> print(x is y)
>>> False
</code></pre>
<p>running the same in code using <code>python test.py</code> returns <code>True</code></p>
<p>The heck?</p>
| 0 | 2016-07-28T13:39:40Z | 38,638,392 | <p>The <code>is</code> operator only returns <code>True</code> when the two operands reference the exact same object. Whether the interpreter chooses to create new values or re-use existing ones is an implementation detail. CPython (the most commonly used implementation) is clearly quite happy having several different ... | 0 | 2016-07-28T13:48:07Z | [
"python"
] |
How works is and id in python using integers above preallocated -5, 255 range | 38,638,180 | <p>Running interpretator</p>
<pre><code>>>> x = 5000
>>> y = 5000
>>> print(x is y)
>>> False
</code></pre>
<p>running the same in code using <code>python test.py</code> returns <code>True</code></p>
<p>The heck?</p>
| 0 | 2016-07-28T13:39:40Z | 38,638,402 | <p>Python allocates some numbers at start.</p>
<pre><code>for x,y in zip(range(256,258),range(256,258)):
print(x is y)
x=y=5000
print(x is y)
</code></pre>
<p>This will print on my machine:</p>
<pre><code>True
False
True
</code></pre>
<p>The first print is True because it was in the allocated range and both x ... | 0 | 2016-07-28T13:48:28Z | [
"python"
] |
add one column (subtraction) to a dataframe with python | 38,638,199 | <p>I try to add one column in a dataframe df2 which contains the value 0 <code>if(df2['P_ACT_KW'] - df2['P_SOUSCR']) < 0 else df2['P_ACT_KW']- df2['P_SOUSCR']</code>.</p>
<pre><code>if (df2['P_ACT_KW'] - df2['P_SOUSCR']) <0:
df2['depassement']=0
else:
df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSC... | 1 | 2016-07-28T13:40:40Z | 38,638,308 | <p>You need to do:</p>
<pre><code>df2['depassement'] = np.where((df2['P_ACT_KW'] - df2['P_SOUSCR']) < 0), 0, df2['P_ACT_KW'] - df2['P_SOUSCR'])
</code></pre>
<p><code>if</code> doesn't understand how to compare array like structures hence the error, here we can use <code>np.where</code> to compare all rows to pro... | 0 | 2016-07-28T13:44:52Z | [
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
add one column (subtraction) to a dataframe with python | 38,638,199 | <p>I try to add one column in a dataframe df2 which contains the value 0 <code>if(df2['P_ACT_KW'] - df2['P_SOUSCR']) < 0 else df2['P_ACT_KW']- df2['P_SOUSCR']</code>.</p>
<pre><code>if (df2['P_ACT_KW'] - df2['P_SOUSCR']) <0:
df2['depassement']=0
else:
df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSC... | 1 | 2016-07-28T13:40:40Z | 38,638,579 | <p>IIUC:</p>
<pre><code>df2['depassement'] = df2['P_ACT_KW'] - df2['P_SOUSCR']
df2[df2['depassement'] < 0, 'depassement'] = 0
</code></pre>
<p>This should also work:</p>
<pre><code>df2['depassement'] = df2.P_ACT_KW.sub(df2.P_SOUSCR).apply(lambda x: max(x, 0))
</code></pre>
| 1 | 2016-07-28T13:55:35Z | [
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
How to get full text even after clicking on link to expand text using selenium? | 38,638,252 | <p>I am trying to scrape reviews from tripadvisor website. Reviews which have longer text are shown partially with 'More' link. I have used selenium to hit 'More' link and it's working but I am again getting half reviews in my final output file. </p>
<p>I figured out that full reviews are stored in different class bu... | -1 | 2016-07-28T13:42:56Z | 38,638,427 | <p>When you do <code>requests.get(full_url).content</code> you are getting the raw markup of the page. This has nothing to do with the state the <code>driver</code> is in (notice how the <code>get</code> call is neither passed the <code>driver</code> nor run <em>on</em> the <code>driver</code>). It's in a very real sen... | 0 | 2016-07-28T13:49:36Z | [
"python",
"selenium",
"web-scraping"
] |
Python: process flow avoiding nested IF statements | 38,638,292 | <p>I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:</p>
<pre><code>def run(self):
status = False
if step_1():
if step_2... | 1 | 2016-07-28T13:44:15Z | 38,638,440 | <p>You would place your steps in a list:</p>
<pre><code>my_plan = (step1, step2, step3, ..., stepN)
</code></pre>
<p>And then execute them in a loop:</p>
<pre><code>for step in my_plan:
if not step():
print 'Error in %s' % step.__name__
status = False
break
else:
status = True
</code></pre>
| 8 | 2016-07-28T13:49:58Z | [
"python",
"python-2.7",
"design-patterns"
] |
Python: process flow avoiding nested IF statements | 38,638,292 | <p>I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:</p>
<pre><code>def run(self):
status = False
if step_1():
if step_2... | 1 | 2016-07-28T13:44:15Z | 38,639,306 | <p>Think of it as failing returning False instead of passing returning True.</p>
<pre><code>def run(self):
if not step_1():
self.logger.error('Error in step 1')
return False
if not step_2():
self.logger.error('Error in step 2')
return False
if not step_3():
self.logg... | -2 | 2016-07-28T14:27:36Z | [
"python",
"python-2.7",
"design-patterns"
] |
trying to log in and scrape a website through asp.net | 38,638,319 | <p>I have wrote a program with the aim of logging into one of my companies websites and then scraping data with aim of making data collection quicker. this is using requests and beautiful soup.</p>
<p>I can get it to print out the html code for a page but I cant get it to log in past the aspx and then print the html o... | -3 | 2016-07-28T13:45:23Z | 38,638,503 | <p>change the line </p>
<pre><code>r = requests.get("http://mycompanywebsitespageafterthelogin.co.uk/Secure/")
</code></pre>
<p>to use your session object</p>
<pre><code>r = s.get("http://mycompanywebsitespageafterthelogin.co.uk/Secure/")
</code></pre>
| 1 | 2016-07-28T13:52:07Z | [
"python",
"asp.net",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
How do i write a mock configuration file in the setUp for my unittesting? | 38,638,322 | <p>I am trying to make my setUp-method create a mock configuration file, write a bunch of mock variables to it, and then use this file to instantiate the class (called Producer) i am running my tests on. </p>
<pre><code>path_to_file =("/path/to/unit.Config")
unitTest = open (path_to_file, 'w')
unitTest.write("a string... | 0 | 2016-07-28T13:45:32Z | 38,638,600 | <p>Perhaps if you closed the file before trying to read the configuration from it you might get better results.</p>
| 0 | 2016-07-28T13:56:16Z | [
"python",
"unit-testing"
] |
How do i write a mock configuration file in the setUp for my unittesting? | 38,638,322 | <p>I am trying to make my setUp-method create a mock configuration file, write a bunch of mock variables to it, and then use this file to instantiate the class (called Producer) i am running my tests on. </p>
<pre><code>path_to_file =("/path/to/unit.Config")
unitTest = open (path_to_file, 'w')
unitTest.write("a string... | 0 | 2016-07-28T13:45:32Z | 38,638,640 | <p>To guarantee that the content that you write to a file is actually available to any process reading the file you need to <code>close</code> the file handle after writing to it. The easiest way to remember to do this is to use a <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel... | 1 | 2016-07-28T13:58:13Z | [
"python",
"unit-testing"
] |
Python - CodeAcademy Madlibs Exercise | 38,638,429 | <p>This code is for Code Academy's Madlibs exercise, which is supposed to take a number of inputs from the user and then print a very funny output.</p>
<p>There is a story already provided in the site and I have not modified it.</p>
<p>When I run the script, I am getting the following error:</p>
<p>.................... | 1 | 2016-07-28T13:49:38Z | 38,638,632 | <p>You have many more arguments in your tuple (the (a1,name......) argument) than you have %s in your string. Make sure that each argument matches up with exactly 1 %s for the string formatting to work.</p>
| 0 | 2016-07-28T13:57:55Z | [
"python",
"raw-input"
] |
Python - CodeAcademy Madlibs Exercise | 38,638,429 | <p>This code is for Code Academy's Madlibs exercise, which is supposed to take a number of inputs from the user and then print a very funny output.</p>
<p>There is a story already provided in the site and I have not modified it.</p>
<p>When I run the script, I am getting the following error:</p>
<p>.................... | 1 | 2016-07-28T13:49:38Z | 38,638,655 | <p>This <a href="https://discuss.codecademy.com/t/codeacademy-python-4-11-madlibs/39512/10" rel="nofollow">link</a> provides a solution. Read toward the bottom. It seems that you need to replace all the _ with %s. </p>
<p>So for example instead of</p>
<pre><code>print "This morning I woke up and felt %s because _ was... | 0 | 2016-07-28T13:58:40Z | [
"python",
"raw-input"
] |
pip freeze not showing packages | 38,638,487 | <p>For example if after installing Tornado with pip like this:</p>
<pre><code>pip install tornado
Collecting tornado
...
Successfully installed backports-abc certifi singledispatch six tornado
</code></pre>
<p><code>pip freeze</code> doesn't return tornado package in list, it just shows:</p>
<pre><code>PyMySQL==0.7.... | 1 | 2016-07-28T13:51:27Z | 38,640,526 | <ol>
<li><p>I suppose reinstalling pip may help you:</p>
<pre><code>pip install --upgrade pip
</code></pre></li>
<li><p>To fix easy_install problem add <code>/lib/python2.7/site-packages/</code> to your PYTHONPATH:</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:/lib/python2.7/site-packages/
</code></pre></li>
</ol>
<p... | 0 | 2016-07-28T15:19:58Z | [
"python",
"pip"
] |
Beautiful Soup Tree Backward Navigation | 38,638,519 | <p><a href="http://i.stack.imgur.com/cKR4l.jpg" rel="nofollow">Shell screen shot</a></p>
<p>Hello:</p>
<p>I am a Python neophyte so apologies in advance if this question is too easy. Iâve been searching like crazy for an answer but cannot seem to find an example that is applicable to my case.</p>
<p>In Python 3 ru... | 1 | 2016-07-28T13:52:41Z | 38,641,174 | <p>The format of the file is a number of tables, the one you are interested in being the second. Since you know the value of the <code>href</code> attribute you want to match on, one way to access the parts you need would be to iterate over the table rows, first of all checking in the <code>href</code> value is the one... | 0 | 2016-07-28T15:49:26Z | [
"python",
"html",
"beautifulsoup"
] |
Beautiful Soup Tree Backward Navigation | 38,638,519 | <p><a href="http://i.stack.imgur.com/cKR4l.jpg" rel="nofollow">Shell screen shot</a></p>
<p>Hello:</p>
<p>I am a Python neophyte so apologies in advance if this question is too easy. Iâve been searching like crazy for an answer but cannot seem to find an example that is applicable to my case.</p>
<p>In Python 3 ru... | 1 | 2016-07-28T13:52:41Z | 38,644,885 | <p>First select the anchor using the <em>href</em>, then find the six previous td's:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm'
soup = BeautifulSoup(requests.get(url).content,"html.parser")
anchor = soup.select_one("a[href=./hist/LeafHan... | 0 | 2016-07-28T19:11:34Z | [
"python",
"html",
"beautifulsoup"
] |
unable to import win32com.client | 38,638,552 | <p>I am trying to import win32com.client library gives me the following error:</p>
<pre><code>>>> import win32com.client
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
import win32com.client
File "C:\Python27\lib\site-packages\win32com\__init__.py", line 5, i... | 0 | 2016-07-28T13:54:16Z | 38,638,742 | <p>Did you install the <a href="http://python.net/crew/skippy/win32/Downloads.html" rel="nofollow">Win32 Extensions for Python</a>? Make sure you pick the correct installer for your system and version of Python otherwise it may not work correctly.</p>
| 0 | 2016-07-28T14:01:53Z | [
"python",
"python-2.7",
"winapi"
] |
filtering dataframe on multiple conditions | 38,638,565 | <pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'],
'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'],
'retailer_name': ['Walmart', 'Walmart', '... | 5 | 2016-07-28T13:54:49Z | 38,638,624 | <p>Actually as <code>filter</code> expects a scalar <code>bool</code> you can just add the condition in the <code>lambda</code> like a normal <code>if</code> style statement:</p>
<pre><code>In [180]:
stores_grouped.filter(lambda x: (len(x) == 1 and x['id'] == 10))
â
Out[180]:
amo... | 3 | 2016-07-28T13:57:21Z | [
"python",
"pandas",
"dataframe"
] |
filtering dataframe on multiple conditions | 38,638,565 | <pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'],
'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'],
'retailer_name': ['Walmart', 'Walmart', '... | 5 | 2016-07-28T13:54:49Z | 38,638,626 | <p>i'd do it this way:</p>
<pre><code>In [348]: stores_grouped.filter(lambda x: (len(x) == 1)).query('id == 10')
Out[348]:
amount id
retailer_name store_number year
Walmart 1944 11:23:19 5 10
1945 11:23:19 5 10
1949 ... | 1 | 2016-07-28T13:57:34Z | [
"python",
"pandas",
"dataframe"
] |
filtering dataframe on multiple conditions | 38,638,565 | <pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'],
'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'],
'retailer_name': ['Walmart', 'Walmart', '... | 5 | 2016-07-28T13:54:49Z | 38,638,630 | <p>You can use:</p>
<pre><code>print (stores_grouped.filter(lambda x: (len(x) == 1) & (x.id == 10).all()))
amount id
retailer_name store_number year
Walmart 1944 11:23:19 5 10
1945 11:23:19 5 10
19... | 3 | 2016-07-28T13:57:54Z | [
"python",
"pandas",
"dataframe"
] |
filtering dataframe on multiple conditions | 38,638,565 | <pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'],
'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'],
'retailer_name': ['Walmart', 'Walmart', '... | 5 | 2016-07-28T13:54:49Z | 38,638,932 | <p>Thinking outside the box, use <code>drop_duplicates</code> with <code>keep=False</code>:</p>
<pre><code>df.drop_duplicates(subset=['retailer_name', 'store_number', 'year'], keep=False) \
.query('id == 10')
</code></pre>
<p><a href="http://i.stack.imgur.com/6hBn5.png" rel="nofollow"><img src="http://i.stack.img... | 2 | 2016-07-28T14:10:30Z | [
"python",
"pandas",
"dataframe"
] |
Python - Parameter checking with Exception Raising | 38,638,642 | <p>I am attempting to write exception raising code blocks into my Python code in order to ensure that the parameters passed to the function meet appropriate conditions (i.e. making parameters mandatory, type-checking parameters, establishing boundary values for parameters, etc...). I understand satisfactorily how to <a... | 5 | 2016-07-28T13:58:18Z | 38,639,156 | <p>You could create a decorator function and pass the expected types and (optional) ranges as parameters. Something like this:</p>
<pre><code>def typecheck(types, ranges=None):
def __f(f):
def _f(*args, **kwargs):
for a, t in zip(args, types):
if not isinstance(a, t):
... | 2 | 2016-07-28T14:19:43Z | [
"python",
"if-statement",
"exception",
"typechecking"
] |
Python - Parameter checking with Exception Raising | 38,638,642 | <p>I am attempting to write exception raising code blocks into my Python code in order to ensure that the parameters passed to the function meet appropriate conditions (i.e. making parameters mandatory, type-checking parameters, establishing boundary values for parameters, etc...). I understand satisfactorily how to <a... | 5 | 2016-07-28T13:58:18Z | 38,639,246 | <p>I think you can use decorator to check the parameters.</p>
<pre><code>def parameterChecker(input,output):
... def wrapper(f):
... assert len(input) == f.func_code.co_argcount
... def newfun(*args, **kwds):
... for (a, t) in zip(args, input):
... assert isinstance(a, t... | 1 | 2016-07-28T14:24:35Z | [
"python",
"if-statement",
"exception",
"typechecking"
] |
How to mock object attributes and complex fields and methods? | 38,638,744 | <p>I have a following function which needs to be unit tested.</p>
<pre><code>def read_all_fields(all_fields_sheet):
entries = []
for row_index in xrange(2, all_fields_sheet.nrows):
d = {'size' : all_fields_sheet.cell(row_index,0).value,\
'type' : all_fields_sheet.cell(row_index,1).value,\... | 0 | 2016-07-28T14:02:02Z | 38,639,015 | <p>Just mock the calls and attributes directly on a mock object; adjust to cover your test needs:</p>
<pre><code>mock_sheet = MagicMock()
mock_sheet.nrows = 3 # loop once
cells = [
MagicMock(value=42), # row_index, 0
MagicMock(value='foo'), # row_index, 1
MagicMock(value='bar'), # row_index, 3
M... | 1 | 2016-07-28T14:13:58Z | [
"python",
"python-2.7",
"unit-testing",
"mocking"
] |
python console closes before it starts | 38,639,095 | <p>I am learning Python and came across this problem. I know that i can put "input()" at the bottom of the program, but the problem is that it IS there, but console terminates nevertheless. It seems like the programm never starts at all. I am using the 3.5 version of Python.</p>
| -3 | 2016-07-28T14:16:53Z | 38,639,192 | <p>Open a terminal, navigate to the directory of your file, and type <code>python myfile.py</code>. If you just double click the file in your system explorer it will run and close when it finishes, which is often too fast to see what's going on.</p>
| -1 | 2016-07-28T14:21:30Z | [
"python",
"console"
] |
python console closes before it starts | 38,639,095 | <p>I am learning Python and came across this problem. I know that i can put "input()" at the bottom of the program, but the problem is that it IS there, but console terminates nevertheless. It seems like the programm never starts at all. I am using the 3.5 version of Python.</p>
| -3 | 2016-07-28T14:16:53Z | 38,639,194 | <p>I think you are starting the programme by clicking on it don't do that to run your programme follow following steps</p>
<p>1.open command prompt
2. go to the path where you have your python programme
3. use command for python for eg: python programme.py in linux
4. if it says python command not recognised probably... | -1 | 2016-07-28T14:21:35Z | [
"python",
"console"
] |
How to validate data based on conditions | 38,639,175 | <pre><code>a = int(input("Enter mark of BIOLOGY: "))
b = int(input("Enter mark of CHEMISTRY: "))
c = int(input("Enter mark of PHYSICS: "))
sum = a + b + c
x = sum
y = 3
avg = x / y
print("Total marks = ", sum)
print("Average marks = ", avg)
</code></pre>
<p>I want to limit the user's input so it only accepts int... | -1 | 2016-07-28T14:20:35Z | 38,639,296 | <p>If you are wanting to limit the sum variable, at the end of your code you could simply put an if statement checking that the variable is within the boundary..</p>
<pre><code>if sum > 90:
sum = 90
elif sum < 0:
sum = 0
</code></pre>
| 0 | 2016-07-28T14:27:17Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to validate data based on conditions | 38,639,175 | <pre><code>a = int(input("Enter mark of BIOLOGY: "))
b = int(input("Enter mark of CHEMISTRY: "))
c = int(input("Enter mark of PHYSICS: "))
sum = a + b + c
x = sum
y = 3
avg = x / y
print("Total marks = ", sum)
print("Average marks = ", avg)
</code></pre>
<p>I want to limit the user's input so it only accepts int... | -1 | 2016-07-28T14:20:35Z | 38,639,300 | <p>To limit the user's input to 0 to 90, you will need to repeatedly ask the user to re-input the data until it meets the 0 to 90 criteria. You can do that by implementing a <code>while</code> loop and then <code>break</code> if the criteria is met. Here's the code:</p>
<pre><code># Data validation for the variable "a... | 1 | 2016-07-28T14:27:19Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to validate data based on conditions | 38,639,175 | <pre><code>a = int(input("Enter mark of BIOLOGY: "))
b = int(input("Enter mark of CHEMISTRY: "))
c = int(input("Enter mark of PHYSICS: "))
sum = a + b + c
x = sum
y = 3
avg = x / y
print("Total marks = ", sum)
print("Average marks = ", avg)
</code></pre>
<p>I want to limit the user's input so it only accepts int... | -1 | 2016-07-28T14:20:35Z | 38,639,426 | <p>The following code will ensure that the user inputs the number in the specified range:</p>
<pre><code>while True:
a = int(input("enter mark of BIOLOGY = "))
if 0 <= a <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
b = int(input("enter mark of CHEMISTRY... | 0 | 2016-07-28T14:33:52Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python : IndexError: list index out of range | 38,639,217 | <p>I'm relatively new to python. I was getting this error when I tried implementing the following code. I don't understand the error. </p>
<pre><code>def coinChange(S,m,n):
dp = [[0 for x in range(m)] for x in range(n+1)]
for i in range(m):
dp[0][i] = 1
for i in range(1,n+1):
for j in ra... | -7 | 2016-07-28T14:22:44Z | 38,639,283 | <p>The error means you have tried to retrieve the value of an index in a list (as in <code>my_list[index]</code>) which <strong>does not exist.</strong> This is assumed to be a fatal error by sensible languages, and as such the program terminates immediately. Read the rest of the exception message to get a better idea ... | 0 | 2016-07-28T14:26:38Z | [
"python"
] |
How to read files in the directory using glob pattern in python? | 38,639,254 | <p>I want read files in one directory. </p>
<p><strong>Directory contains :</strong> </p>
<pre><code>ABC1.csv
ABC1_1.csv
ABC1_2.csv
ABC11.csv
ABC11_1.csv
ABC11_3.csv
ABC11_2.csv
ABC13_4.csv
ABC13_1.csv
ABC17_6.csv
ABC17_2.csv
ABC17_4.csv
ABC17_8.csv
</code></pre>
<p>While running script I want to give command line a... | 0 | 2016-07-28T14:25:11Z | 38,640,450 | <p>I have a solution. It's not perfect, depends if you have other files in the folder:</p>
<pre><code>file_pattern = 'ABC1'
files_list = glob(os.path.join('<directory name>', str(file_pattern)+'[!0-9]*'))
# output: ABC1.csv, ABC1_1.csv, ABC1_2.csv
file_pattern = 'ABC11'
files_list = glob(os.path.join('<direc... | 0 | 2016-07-28T15:17:10Z | [
"python",
"file",
"directory",
"glob"
] |
How to read files in the directory using glob pattern in python? | 38,639,254 | <p>I want read files in one directory. </p>
<p><strong>Directory contains :</strong> </p>
<pre><code>ABC1.csv
ABC1_1.csv
ABC1_2.csv
ABC11.csv
ABC11_1.csv
ABC11_3.csv
ABC11_2.csv
ABC13_4.csv
ABC13_1.csv
ABC17_6.csv
ABC17_2.csv
ABC17_4.csv
ABC17_8.csv
</code></pre>
<p>While running script I want to give command line a... | 0 | 2016-07-28T14:25:11Z | 38,651,789 | <p>I tried with different Scenarios,and finally got exact solution which satisfies all my conditions. First I'm checking for user input file is available or not in the specified directory, If it is available then globing all files with same file with (_) all at the end appending match file to same list. </p>
<p>If use... | 1 | 2016-07-29T06:19:58Z | [
"python",
"file",
"directory",
"glob"
] |
How to read files in the directory using glob pattern in python? | 38,639,254 | <p>I want read files in one directory. </p>
<p><strong>Directory contains :</strong> </p>
<pre><code>ABC1.csv
ABC1_1.csv
ABC1_2.csv
ABC11.csv
ABC11_1.csv
ABC11_3.csv
ABC11_2.csv
ABC13_4.csv
ABC13_1.csv
ABC17_6.csv
ABC17_2.csv
ABC17_4.csv
ABC17_8.csv
</code></pre>
<p>While running script I want to give command line a... | 0 | 2016-07-28T14:25:11Z | 38,651,863 | <p>You might want to add a simple check for the additional "special" case, something like this:</p>
<pre><code>if file_pattern.startswith('ABC',0,3):
csv_path = os.path.join('.', str(file_pattern))
files_list = glob(csv_path + '_*.csv')
# Just check the special case that's not included in the glob above
cs... | 0 | 2016-07-29T06:25:00Z | [
"python",
"file",
"directory",
"glob"
] |
How can I stop my program from generating the same key? | 38,639,395 | <p>I writing a password generator and I ran into this annoying issue, and it is the repeating a a number or letter on the same line. The user gives the program a format on how they want their password to be generated ex "C@@d%%%"
where @ is only letters and where % is only numbers, and the user also inputs the numbers ... | 1 | 2016-07-28T14:32:19Z | 38,639,640 | <p><code>GenPass.replace(GenPass[Pos],number)</code> will replace <em>every</em> occurrence of the character at <code>GenPass[Pos]</code> with the value of <code>number</code>. You need to make sure you replace one character at a time.</p>
| 0 | 2016-07-28T14:42:05Z | [
"python",
"passwords",
"generator"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.