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 |
|---|---|---|---|---|---|---|---|---|---|
How can i solve this regular expression, Python? | 39,991,485 | <p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p>
<pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
</code></pre>
<p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278.... | 0 | 2016-10-12T06:02:42Z | 39,993,094 | <p>The solutions posted so far only work (if at all) for numbers that are preceded and followed by whitespace. They will fail if a number occurs at the very start or end of the string, or if a number appears at the end of a sentence, for example. This can be avoided using <a href="http://www.regular-expressions.info/wo... | 0 | 2016-10-12T07:40:59Z | [
"python",
"regex"
] |
Data Compression Model | 39,991,511 | <p>I am working on an exercise where we are to model Data Compression via a list. Say we were given a list: <code>[4,4,4,4,4,4,2,9,9,9,9,9,5,5,4,4]</code>
We should apply Run-length encoding, and get a new list of <code>[4,6,2,1,9,5,5,2,4,2]</code> where it shows how many 4's (6) 2's(1) 9's (5) 5's (2), etc.. jointly n... | 0 | 2016-10-12T06:04:30Z | 39,991,625 | <p>Your code is really confusing with all these counters. What you need to do is implement the algorithm as it is defined. You need just a single index <code>i</code> which keeps track at what position of the list you are currently at and at each step compare the number to the previous number.</p>
<ul>
<li>if they are... | 0 | 2016-10-12T06:12:23Z | [
"python",
"encoding",
"compression"
] |
Data Compression Model | 39,991,511 | <p>I am working on an exercise where we are to model Data Compression via a list. Say we were given a list: <code>[4,4,4,4,4,4,2,9,9,9,9,9,5,5,4,4]</code>
We should apply Run-length encoding, and get a new list of <code>[4,6,2,1,9,5,5,2,4,2]</code> where it shows how many 4's (6) 2's(1) 9's (5) 5's (2), etc.. jointly n... | 0 | 2016-10-12T06:04:30Z | 39,993,618 | <p>You're on the right track, but this is easier with an index-based loop:</p>
<pre><code>def rle_encode(ls):
# Special case: the empty list.
if not ls:
return []
result = []
# Count the first element in the list, whatever that is.
count = 1
# Loop from 1; we're considering the first ... | 0 | 2016-10-12T08:10:21Z | [
"python",
"encoding",
"compression"
] |
Python: display subarray divisible by k , how do I solve with hashtable? | 39,991,540 | <p>I am looking for <strong>Python</strong> solution</p>
<p>For example, For A=[2, -3, 5, 4, 3, -1, 7]. The for k = 3 there is a subarray for example {-3, 5, 4}. For, k=5 there is subarray {-3, 5, 4, 3, -1, 7} etc.</p>
| -1 | 2016-10-12T06:06:20Z | 39,991,891 | <p>This is the solution. You can try to figure it out yourself.</p>
<pre><code>def solve(a, k):
tbl = {0 : -1}
sum = 0
n = len(a)
for i in xrange(n):
sum = (sum + a[i]) % k
if sum in tbl:
key = tbl[sum]
result = a[key+1: i+1]
return result
... | 0 | 2016-10-12T06:31:56Z | [
"python",
"hashtable"
] |
Output is blank | 39,991,565 | <pre><code>def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
... | 0 | 2016-10-12T06:08:04Z | 39,991,621 | <p>To run a python module as a program, you should run it like the below one. In your program main is just like other functions and won't be executed automatically.</p>
<pre><code>if __name__ == '__main__':
load()
calc()
print()
</code></pre>
<p>What we are doing is, we check if the module name is <code>_... | 0 | 2016-10-12T06:12:10Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Output is blank | 39,991,565 | <pre><code>def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
... | 0 | 2016-10-12T06:08:04Z | 39,991,683 | <p>You are not calling <code>main()</code> & also change <code>print()</code> function name, here I have changed it to <code>fprint()</code> </p>
<pre><code>def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
... | 0 | 2016-10-12T06:17:19Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Output is blank | 39,991,565 | <pre><code>def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
... | 0 | 2016-10-12T06:08:04Z | 39,991,860 | <p>Along with the problem of using built-in function, you've scope problem too. So, you must make the variables defined in each function <code>global</code> so that they can be assessed in other functions.</p>
<pre><code>def load():
global name
global count
global shares
global pp
global sp
... | 1 | 2016-10-12T06:29:15Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Why does python not have a awgn function like Matlab does? | 39,991,590 | <p>I want to add noise to my synthetic data set in python. I am used to MATLAB but I noticed that python (nor numpy) the option of using <code>awgn</code> (which to my understanding can automatically determine the signal to noise ratio when adding Gaussian Noise, I guess this how it makes sure it doesn't destroy the si... | -8 | 2016-10-12T06:10:02Z | 39,992,624 | <p>As per your link, <code>awgn</code> is part of the MATLAB Communications toolbox, <a href="https://www.mathworks.com/help/comm/ref/awgn.html" rel="nofollow">https://www.mathworks.com/help/comm/ref/awgn.html</a>. It isn't part of the basic MATLAB package.</p>
<p>Similarly, in Python you'll have to go looking at som... | 6 | 2016-10-12T07:15:24Z | [
"python",
"matlab",
"numpy",
"machine-learning",
"statistics"
] |
How to get the reference of one variable of one class in another class in python? | 39,991,676 | <p>I have a class C1, and another class C2 which takes one instance of C1 as a variable. If I want to get the variable of C1 in C2, I have to use <code>self.c1.variable</code>. How can I get a reference of the variable of C1 in C2 so that I can get it directly?</p>
<pre><code>class C1():
def __init__(self,a):
... | 0 | 2016-10-12T06:16:37Z | 39,991,734 | <p>You can use <code>@property</code> decorator to achieve that:</p>
<pre><code>class C2():
def __init__(self, c1):
self.c1 = c1
@property
def variable(self):
return self.c1.variable
</code></pre>
<p>In case you want to modify the <code>variable</code> in C2 instance:</p>
<pre><code> ... | 0 | 2016-10-12T06:20:25Z | [
"python",
"class",
"reference"
] |
Pygame pressing key to move a Rect | 39,991,867 | <p>I am trying to keep pressing a key and move the square automatically. I've tried to change <code>pygame.key.get.pressed()</code> to <code>pygame.key.get.focused()</code>, but still nothing.</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hac... | 0 | 2016-10-12T06:29:32Z | 39,992,198 | <p>You can't use <code>get_pressed()</code> in <code>for evento</code> loop because when you keep pressed key then key doesn't generate events and <code>pygame.event.get()</code> returns empty list so <code>for</code> does nothing.</p>
<p>When you start pressing key then system generates single even <code>KEYDOWN</cod... | 0 | 2016-10-12T06:51:06Z | [
"python",
"keyboard",
"pygame"
] |
Pygame pressing key to move a Rect | 39,991,867 | <p>I am trying to keep pressing a key and move the square automatically. I've tried to change <code>pygame.key.get.pressed()</code> to <code>pygame.key.get.focused()</code>, but still nothing.</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hac... | 0 | 2016-10-12T06:29:32Z | 40,117,388 | <p>From what I understand (correct me if I'm wrong, I may not be quite understanding what you asked), but it looks like what you are trying to do is press a key, keep the key held down, and have pygame continually process KEYDOWN events as you are holding the key down. In pygame, this does not work, but you <em>can</e... | 0 | 2016-10-18T20:21:03Z | [
"python",
"keyboard",
"pygame"
] |
Reducing time complexity of contiguous subarray | 39,991,921 | <p>I was wondering how I could reduce the time complexity of this algorithm.
It calculates the length of the max subarray having elements that sum to the k integer.</p>
<p>a = an array of integers</p>
<p>k = max integer</p>
<p>ex: a = [1,2,3], k= 3</p>
<p>possible subarrays = [1],[1,2]</p>
<p>length of the max sub... | 0 | 2016-10-12T06:33:59Z | 39,992,681 | <p>You can use <code>sliding window</code> algorithm for this.</p>
<p>Start at <code>index 0</code>, and calculate sum of subarray as you move forward. When sum exceeds <code>k</code>, start decrementing the initial elements till sum is again less than <code>k</code> and start summing up again.</p>
<p>Find below the ... | 0 | 2016-10-12T07:19:10Z | [
"python",
"algorithm",
"optimization"
] |
Splitting list items and adding value to them in python | 39,992,009 | <p>I want to split list items then add values to them. To do this I am required to take the first sentence; split it into a list; use the <code>isdigit()</code> to determine if the list element is a digit then add 1 to the element; join the new list elements together using <code>join()</code>. It needs to be done using... | 0 | 2016-10-12T06:38:43Z | 39,992,205 | <p>Looks like you want something like this<br>
I have replaced <code>li[0]</code> and other variables with a string "Some_Value" because I did not knew the value of those variables</p>
<pre><code>a="You would like to visit " + "Some_Value" +" as city 1 and " + "Some_Value" + " as city 2 and "+ "Some_Value" + " as city... | 1 | 2016-10-12T06:51:16Z | [
"python"
] |
Splitting list items and adding value to them in python | 39,992,009 | <p>I want to split list items then add values to them. To do this I am required to take the first sentence; split it into a list; use the <code>isdigit()</code> to determine if the list element is a digit then add 1 to the element; join the new list elements together using <code>join()</code>. It needs to be done using... | 0 | 2016-10-12T06:38:43Z | 39,992,754 | <p>Here is another way to look at solution <em>(with comments added)</em></p>
<pre><code>li = ["New York", "London", "Tokyo"] #This is an example list for li
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city 2 and "+li[2]+" as city 3 on your trip"
print a
printer = a.split(" ")
print printe... | 0 | 2016-10-12T07:23:49Z | [
"python"
] |
Splitting list items and adding value to them in python | 39,992,009 | <p>I want to split list items then add values to them. To do this I am required to take the first sentence; split it into a list; use the <code>isdigit()</code> to determine if the list element is a digit then add 1 to the element; join the new list elements together using <code>join()</code>. It needs to be done using... | 0 | 2016-10-12T06:38:43Z | 39,993,388 | <pre><code>' '.join([ str( int(i)+1 ) if i.isdigit() else i for i in a.split() ] )
</code></pre>
| 0 | 2016-10-12T07:57:19Z | [
"python"
] |
How to add a named keyword argument to a function signature | 39,992,169 | <p>Can I use a mixin class to add a named keyword to the signature of a function in the base? At the moment I can't work out how to avoid overwriting the base function's signature:</p>
<pre><code>from inspect import signature
class Base(object):
def __init__(self, foo='bar', **kwargs):
pass
class Mixin(b... | 0 | 2016-10-12T06:49:22Z | 39,993,173 | <p>When subclassing, you can either extend or override the methods of the superclass, but you can't* modify them directly. Overiding is achieved by simply writing a new method of the same name; extension is achieved by overriding the method and then calling the superclass's method as a part of your replacement.</p>
<p... | 0 | 2016-10-12T07:45:12Z | [
"python",
"oop"
] |
How to add a named keyword argument to a function signature | 39,992,169 | <p>Can I use a mixin class to add a named keyword to the signature of a function in the base? At the moment I can't work out how to avoid overwriting the base function's signature:</p>
<pre><code>from inspect import signature
class Base(object):
def __init__(self, foo='bar', **kwargs):
pass
class Mixin(b... | 0 | 2016-10-12T06:49:22Z | 39,997,698 | <p>@jonrsharpe answered this in the comment, but if you want to require a parameter you could do this as a dynamic check in the mixin's method:</p>
<pre><code>class Base(object):
def __init__(self, foo='bar', **kwargs):
pass
class Mixin(base):
def __init__(self, **kwargs):
kwargs.pop('required... | 0 | 2016-10-12T11:40:42Z | [
"python",
"oop"
] |
WindowsError: [Error 5] Access is denied in Flask | 39,992,222 | <p>I am trying to move an uploaded file to a specific folder in my Windows system and it gives me WindowsError: [Error 5] Access is denied error. The solutions I happen to see for such problems are run python as Administrator from cmd line. I am not sure if that is possible since it's a web app and i am using the defau... | 0 | 2016-10-12T06:52:17Z | 39,993,019 | <p>I had been running the application directly from Pycharm, which doesn't run it in administrator mode</p>
<p>I tried running it using command prompt as administrator and it worked for me.</p>
| 0 | 2016-10-12T07:37:13Z | [
"python",
"flask"
] |
WindowsError: [Error 5] Access is denied in Flask | 39,992,222 | <p>I am trying to move an uploaded file to a specific folder in my Windows system and it gives me WindowsError: [Error 5] Access is denied error. The solutions I happen to see for such problems are run python as Administrator from cmd line. I am not sure if that is possible since it's a web app and i am using the defau... | 0 | 2016-10-12T06:52:17Z | 39,996,819 | <p>Running the application 'directly in pycharm' is the equivlant of running it on the command prompt, but with a few caveats. <em>Personally I don't like running python in pycharm as I find it can cause errors.</em></p>
<p>Ideally you don't want to run as administrator, but you might find you have a couple of problem... | 0 | 2016-10-12T10:54:56Z | [
"python",
"flask"
] |
Python not recognised as an internal or external command in windows 7 | 39,992,339 | <p>I have installed python 2.7.11 from <strong><a href="https://www.python.org/downloads/release/python-2711/" rel="nofollow">this</a></strong> link and then restarted my system. However when I go to cmd and run <code>python --version</code>. It gives me an error that </p>
<blockquote>
<p>python not recognized as an... | 0 | 2016-10-12T06:59:06Z | 39,992,394 | <p>Changes in PATH variable do not affect already open programs. Close your command line (or powershell) window and reopen it in order to use new PATH variable.</p>
| 1 | 2016-10-12T07:02:17Z | [
"python",
"cmd",
"path"
] |
Python not recognised as an internal or external command in windows 7 | 39,992,339 | <p>I have installed python 2.7.11 from <strong><a href="https://www.python.org/downloads/release/python-2711/" rel="nofollow">this</a></strong> link and then restarted my system. However when I go to cmd and run <code>python --version</code>. It gives me an error that </p>
<blockquote>
<p>python not recognized as an... | 0 | 2016-10-12T06:59:06Z | 39,992,468 | <p>Please run the following command in the command prompt.</p>
<blockquote>
<p>echo %PATH%
It should have whatever path you have set manually. Otherwise Open a new Command prompt and try the same command.
Run python</p>
</blockquote>
<p>If it is not working after that.</p>
<p>Please kindly check the Python.exe... | 2 | 2016-10-12T07:06:03Z | [
"python",
"cmd",
"path"
] |
Python not recognised as an internal or external command in windows 7 | 39,992,339 | <p>I have installed python 2.7.11 from <strong><a href="https://www.python.org/downloads/release/python-2711/" rel="nofollow">this</a></strong> link and then restarted my system. However when I go to cmd and run <code>python --version</code>. It gives me an error that </p>
<blockquote>
<p>python not recognized as an... | 0 | 2016-10-12T06:59:06Z | 39,993,065 | <p>Easiest way to fix this is to reinstall Python and check "Add to Path" button during the installation.</p>
| 0 | 2016-10-12T07:39:44Z | [
"python",
"cmd",
"path"
] |
Python not recognised as an internal or external command in windows 7 | 39,992,339 | <p>I have installed python 2.7.11 from <strong><a href="https://www.python.org/downloads/release/python-2711/" rel="nofollow">this</a></strong> link and then restarted my system. However when I go to cmd and run <code>python --version</code>. It gives me an error that </p>
<blockquote>
<p>python not recognized as an... | 0 | 2016-10-12T06:59:06Z | 39,993,424 | <p>Finally after lot of searching I found that python comes with a script for adding to path variable. So I just ran the script with</p>
<pre><code>c:\python27\tools\scripts\win_add2path.py
</code></pre>
<p>and it works now.</p>
| 0 | 2016-10-12T07:59:01Z | [
"python",
"cmd",
"path"
] |
to_datetime Value Error: at least that [year, month, day] must be specified Pandas | 39,992,411 | <p>I am reading from two different CSVs each having date values in their columns. After read_csv I want to convert the data to datetime with the to_datetime method. The formats of the dates in each CSV are slightly different, and although the differences are noted and specified in the to_datetime format argument, the o... | 2 | 2016-10-12T07:02:54Z | 39,992,492 | <p>For me works <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>
<pre><code>print (dtd)
... | 2 | 2016-10-12T07:08:02Z | [
"python",
"csv",
"pandas"
] |
to_datetime Value Error: at least that [year, month, day] must be specified Pandas | 39,992,411 | <p>I am reading from two different CSVs each having date values in their columns. After read_csv I want to convert the data to datetime with the to_datetime method. The formats of the dates in each CSV are slightly different, and although the differences are noted and specified in the to_datetime format argument, the o... | 2 | 2016-10-12T07:02:54Z | 39,992,541 | <p>You can <code>stack</code> / <code>pd.to_datetime</code> / <code>unstack</code></p>
<pre><code>pd.to_datetime(dte.stack()).unstack()
</code></pre>
<p><a href="https://i.stack.imgur.com/V9daD.png" rel="nofollow"><img src="https://i.stack.imgur.com/V9daD.png" alt="enter image description here"></a></p>
<p><strong><... | 2 | 2016-10-12T07:10:34Z | [
"python",
"csv",
"pandas"
] |
Saving images with pixels in django | 39,992,420 | <p>I want to save images with specific pixels, when someone uploads image on django models it will be resized and then save according to id. I want them to be saved in path product/medium/id. I have tried defining path in it which saves image but not on the path I want. </p>
<p><strong>Here is my models.py</strong></p... | 1 | 2016-10-12T07:03:29Z | 39,993,056 | <pre><code>from PIL import Image
import StringIO
import os
from django.core.files.uploadedfile import InMemoryUploadedFile
class Product(models.Model):
pass # your model description
def save(self, *args, **kwargs):
"""Override model save."""
if self.product_medium:
img = Image.op... | 0 | 2016-10-12T07:39:05Z | [
"python",
"django",
"image",
"file-upload",
"image-resizing"
] |
How to rename (exposed in API) filter field name using django-filters? | 39,992,515 | <p>As the question states - I'm trying to rename the filter field name exposed in my API.</p>
<p>I have the following models:</p>
<pre><code>class Championship(Model):
...
class Group(Model):
championship = ForeignKey(Championship, ...)
class Match(Model):
group = ForeignKey(Group, ...)
</code></pre>
<... | 1 | 2016-10-12T07:09:03Z | 39,992,704 | <p>You need to provide model field as name in django_filters with field type. I am considering you are trying to filter by championship id.</p>
<pre><code>class MatchFilterSet(FilterSet):
championship = django_filters.NumberFilter(name='group__championship_id')
class Meta:
model = Match
fields... | 2 | 2016-10-12T07:20:25Z | [
"python",
"django",
"rest",
"django-filter"
] |
How to rename (exposed in API) filter field name using django-filters? | 39,992,515 | <p>As the question states - I'm trying to rename the filter field name exposed in my API.</p>
<p>I have the following models:</p>
<pre><code>class Championship(Model):
...
class Group(Model):
championship = ForeignKey(Championship, ...)
class Match(Model):
group = ForeignKey(Group, ...)
</code></pre>
<... | 1 | 2016-10-12T07:09:03Z | 39,993,081 | <p>After <a href="http://stackoverflow.com/users/3805509/naresh">Naresh</a> response I have figured out the source of error.</p>
<p>It was the implementation of the model's view:</p>
<pre><code>class MatchViewSet(ModelViewSet):
filter = MatchFilterSet
(...)
</code></pre>
<p>For <code>django-filter</code> it ... | 0 | 2016-10-12T07:40:31Z | [
"python",
"django",
"rest",
"django-filter"
] |
How to display specific digit in pandas dataframe | 39,992,653 | <p>I have dataframe like below</p>
<pre><code> month
0 1
1 2
2 3
3 10
4 11
</code></pre>
<p>for example,I would like to display this dataframe in 2 digit like this</p>
<pre><code> month
0 01
1 02
2 03
3 10
4 11
</code></pre>
<p>I tried many method but didn't work well. How c... | 3 | 2016-10-12T07:17:00Z | 39,992,665 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html"><code>str.zfill</code></a>:</p>
<pre><code>print (df['month'].astype(str).str.zfill(2))
0 01
1 02
2 03
3 10
4 11
Name: month, dtype: object
</code></pre>
| 5 | 2016-10-12T07:18:00Z | [
"python",
"pandas",
"dataframe"
] |
How to display specific digit in pandas dataframe | 39,992,653 | <p>I have dataframe like below</p>
<pre><code> month
0 1
1 2
2 3
3 10
4 11
</code></pre>
<p>for example,I would like to display this dataframe in 2 digit like this</p>
<pre><code> month
0 01
1 02
2 03
3 10
4 11
</code></pre>
<p>I tried many method but didn't work well. How c... | 3 | 2016-10-12T07:17:00Z | 39,992,806 | <p>I'd still pick @jezrael's answer over this, but I like this answer too</p>
<pre><code>df.month.apply('{:02d}'.format)
0 01
1 02
2 03
3 10
4 11
Name: month, dtype: object
</code></pre>
| 2 | 2016-10-12T07:27:10Z | [
"python",
"pandas",
"dataframe"
] |
Calculate MRR in Python Pandas dataframe | 39,992,771 | <p>I have a Pandas dataframe with the following columns</p>
<p><code>date | months | price</code></p>
<p>I calculate some basic BI metrics. I did the Net Revenue by grouping the dataframe on date and sum the price:</p>
<p><code>df = df[["Date", "Price"]].groupby(df['Date'])["Price"].sum().reset_index()</code></p>
<... | 2 | 2016-10-12T07:24:51Z | 39,993,747 | <p>I don't know any way around using a loop. However, I can suggest a way to make the code pretty clean and efficient.</p>
<p>First, let's load the example data you supplied in the question text:</p>
<pre><code>df = pd.DataFrame({'date': ['01-01-2016', '05-01-2016', '10-01-2016','04-02-2016'],
'mo... | 1 | 2016-10-12T08:19:19Z | [
"python",
"pandas",
"dataframe",
"business-intelligence"
] |
why it is not entering to "for loop" | 39,992,899 | <pre><code>page = requests.get('http://anywebsite/anysearch/')
tree = html.fromstring(page.content)
lists = tree.xpath('.//div[@class="normal-view"]')
print "lists"
for i in lists:
print "1"
title = i.xpath('.//div[@class="post-entry"/h1//a/@href]//text()')
print title,"2"
print "3"
</code></pre>
<p>i h... | -2 | 2016-10-12T07:31:24Z | 39,996,037 | <p>The following Python 2 code successfully prints the title of the film under review using the URL you provided.</p>
<pre><code>from lxml import etree
parser = etree.HTMLParser()
tree = etree.parse("http://boxofficeindia.co.in/review-mirzya/", parser)
title = tree.xpath("string(//h1)")
print title
</code></pre>
<p>E... | 0 | 2016-10-12T10:12:40Z | [
"python",
"python-2.7",
"xpath",
"python-2.x"
] |
Check if two nodes are on the same path in constant time for a DAG | 39,992,937 | <p>I have a DAG (directed acyclic graph) which is represented by an edge list e.g.</p>
<pre><code>edges = [('a','b'),('a','c'),('b','d')]
</code></pre>
<p>will give the graph </p>
<pre><code>a - > b -> d
|
v
c
</code></pre>
<p>I'm doing many operations where I have to check if two nodes are on the same path (... | 2 | 2016-10-12T07:32:50Z | 39,994,424 | <p>You actually want to find the <a href="https://en.wikipedia.org/wiki/Transitive_closure" rel="nofollow">transitive closure</a> of the graph. </p>
<blockquote>
<p>In computer science, the concept of transitive closure can be thought
of as constructing a data structure that makes it possible to answer
reachabil... | 3 | 2016-10-12T08:55:04Z | [
"python",
"algorithm",
"graph-algorithm",
"directed-acyclic-graphs",
"graph-traversal"
] |
Questions on pandas moving average | 39,992,985 | <p>I am a beginner of python and pandas. I am having difficulty with making volatility adjusted moving average, so I need your help.</p>
<p>Volatility adjusted moving average is a kind of moving average, of which moving average period is not static, but dynamically adjusted according to volatility.</p>
<p>What I'd li... | 2 | 2016-10-12T07:35:23Z | 39,993,814 | <p>first of all: you need to calculate <code>pct_change</code> on <code>price</code> to calculate <code>volatility</code> of <code>returns</code></p>
<p><strong><em>my solution</em></strong></p>
<pre><code>def price(stock, start):
price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close']
... | 2 | 2016-10-12T08:22:29Z | [
"python",
"pandas"
] |
maximum recursion depth exceeded getter Django | 39,993,144 | <p>I have some class with custom getter for specific attr:</p>
<pre><code>class Item(a, b, c, d, models.Model):
title = Field()
description = Field()
a = Field()
_custom_getter = ['title','description']
def __getattribute__(self, name):
if name in self.custom_getter:
ret... | 1 | 2016-10-12T07:43:53Z | 39,993,276 | <p>Because <code>__getattribute__</code> gets called when you do <code>self.custom_getter</code>. You can use <code>self.__dict__</code> for this. Read more <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method#371833">Python - Using __getattribute__ method</a></p>
<pre><code>class Item(a... | 3 | 2016-10-12T07:50:43Z | [
"python",
"django",
"recursion",
"django-models",
"attributes"
] |
I need to cut strings from a line(xml file) and save them in an array | 39,993,147 | <p>i have another question regarding python. I need to save a specific string of a xml file(the string appears several times in the file) in a list.</p>
<pre><code>def parse_xml(self):
file_ = open("ErrorReactions_TestReport_20160831_165153.xml", "r")
for line in file_:
line.rstrip()
if "result... | 0 | 2016-10-12T07:44:00Z | 39,993,398 | <p>Regex is one of many ways of doing this. I'm sure there are excellent tried and tested XML parsers out there though. This code will print <code>Passed</code>:</p>
<pre><code>import re
line='''< verdict time="1472654306.7" result_str="Passed" result="2">Generator run successfully< /verdict> < verdict... | 0 | 2016-10-12T07:57:43Z | [
"python",
"xml",
"string",
"list",
"split"
] |
vlookup between 2 Pandas dataframes | 39,993,238 | <p>I have 2 pandas Dataframes as follows.</p>
<p>DF1:</p>
<pre><code>Security ISIN
ABC I1
DEF I2
JHK I3
LMN I4
OPQ I5
</code></pre>
<p>and DF2:</p>
<pre><code>ISIN Value
I2 100
I3 200
I5 300
</code></pre>
<p>I would like to end up ... | 2 | 2016-10-12T07:48:39Z | 39,993,273 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, by default is inner join, so <code>how=inner</code> is omit and if there is only one common column in both <code>Dataframes</code>, you can also omit parameter <code>on='ISIN'</code>:<... | 2 | 2016-10-12T07:50:21Z | [
"python",
"pandas"
] |
vlookup between 2 Pandas dataframes | 39,993,238 | <p>I have 2 pandas Dataframes as follows.</p>
<p>DF1:</p>
<pre><code>Security ISIN
ABC I1
DEF I2
JHK I3
LMN I4
OPQ I5
</code></pre>
<p>and DF2:</p>
<pre><code>ISIN Value
I2 100
I3 200
I5 300
</code></pre>
<p>I would like to end up ... | 2 | 2016-10-12T07:48:39Z | 39,993,574 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>pd.merge</code></a> to automatically do an inner join on <code>ISIN</code>. The following line of code should get you going:</p>
<pre><code>df3 = pd.merge(df1, df2)[['Security', 'Value']]
</code></pre>... | 1 | 2016-10-12T08:07:28Z | [
"python",
"pandas"
] |
Sony QX1 Contents Transfer - Internal Server Error 500 | 39,993,338 | <p>I have been trying to use the Sony Camera Remote SDK for controlling a Sony QX1 using python (using <a href="https://github.com/Bloodevil/sony_camera_api" rel="nofollow">https://github.com/Bloodevil/sony_camera_api</a>) </p>
<p>I managed to take pictures, set all the modes etc. Everything works. When I take a pictu... | 0 | 2016-10-12T07:54:41Z | 40,112,704 | <p>I have found the solution: the mode of the camera was "Contents Transfer".
Apparently, you can only access the images when the camera is in "Remote Shooting" mode. </p>
| 0 | 2016-10-18T15:47:55Z | [
"python",
"sony"
] |
Tensorflow gradients: without automatic implicit sum | 39,993,377 | <p>In tensorflow, if one has two tensors <code>x</code> and <code>y</code> and one want to have the gradients of <code>y</code> with respect to <code>x</code> using <code>tf.gradients(y,x)</code>. Then what one actually gets is :</p>
<pre><code>gradient[n,m] = sum_ij d y[i,j]/ d x[n,m]
</code></pre>
<p>There is a sum... | 2 | 2016-10-12T07:56:46Z | 40,003,139 | <p>There isn't a way. TensorFlow 0.11 <code>tf.gradients</code> implements standard reverse-mode AD which gives the derivative of a scalar quantity. You'd need to call <code>tf.gradients</code> for each <code>y[i,j]</code> separately</p>
| 1 | 2016-10-12T15:59:28Z | [
"python",
"tensorflow",
"gradients"
] |
Tensorflow gradients: without automatic implicit sum | 39,993,377 | <p>In tensorflow, if one has two tensors <code>x</code> and <code>y</code> and one want to have the gradients of <code>y</code> with respect to <code>x</code> using <code>tf.gradients(y,x)</code>. Then what one actually gets is :</p>
<pre><code>gradient[n,m] = sum_ij d y[i,j]/ d x[n,m]
</code></pre>
<p>There is a sum... | 2 | 2016-10-12T07:56:46Z | 40,005,908 | <p>Here is my work around just taking the derivative of each component (as also mentionned by @Yaroslav) and then packing them all together again in the case of rank 2 tensors (Matrices):</p>
<pre><code>import tensorflow as tf
def twodtensor2list(tensor,m,n):
s = [[tf.slice(tensor,[j,i],[1,1]) for i in range(n)] ... | 3 | 2016-10-12T18:31:36Z | [
"python",
"tensorflow",
"gradients"
] |
Can't load Django static files in view | 39,993,410 | <p>I'm a new player in Django and Python. I want to load the static files from the project level static folder. The problem is I can't but I still can load the static of an app.
This is the structure of my project:</p>
<pre><code>Yaas
__init__.py
settings.py
urls.py
wsgi.py
templates
base.h... | -1 | 2016-10-12T07:58:26Z | 39,994,149 | <p>I made this work by adding the following:</p>
<pre><code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
</code></pre>
<p>From the <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#configuring-static-files" rel="nofollow">docs</a> (after point 4):</p>
<blockquote>
<p>Your project will pr... | 0 | 2016-10-12T08:40:09Z | [
"python",
"django"
] |
Similar errors in MultiProcessing. Mismatch number of arguments to function | 39,993,436 | <p>I couldn't find a better way to describe the error I'm facing, but this error seems to come up everytime I try to implement Multiprocessing to a loop call.</p>
<p>I've used both sklearn.externals.joblib as well as multiprocessing.Process but error are similar though different.</p>
<p><strong>Original Loop on which... | 2 | 2016-10-12T07:59:30Z | 40,022,304 | <p>You actually get the exact same error in both case but as you use a <code>Pool</code> in one example (<code>joblib</code>) and a <code>Process</code> in the other you don't get the same failure/traceback in your main thread as they do not manage the Process failure the same way.<br>
In both cases, your process seems... | 0 | 2016-10-13T13:24:28Z | [
"python",
"multiprocessing",
"pickle",
"joblib"
] |
Why does pandas dataframe indexing change axis depending on index type? | 39,993,460 | <p>when you index into a pandas dataframe using a list of ints, it returns columns.</p>
<p>e.g. <code>df[[0, 1, 2]]</code> returns the first three columns.</p>
<p>why does indexing with a boolean vector return a list of rows?</p>
<p>e.g. <code>df[[True, False, True]]</code> returns the first and third rows. (and er... | 2 | 2016-10-12T08:00:53Z | 39,993,488 | <p>Because if use:</p>
<pre><code>df[[True, False, True]]
</code></pre>
<p>it is called <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> by mask:</p>
<pre><code>[True, False, True]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.D... | 2 | 2016-10-12T08:02:15Z | [
"python",
"pandas"
] |
Why does pandas dataframe indexing change axis depending on index type? | 39,993,460 | <p>when you index into a pandas dataframe using a list of ints, it returns columns.</p>
<p>e.g. <code>df[[0, 1, 2]]</code> returns the first three columns.</p>
<p>why does indexing with a boolean vector return a list of rows?</p>
<p>e.g. <code>df[[True, False, True]]</code> returns the first and third rows. (and er... | 2 | 2016-10-12T08:00:53Z | 39,994,038 | <p>There are very specific slicing accessors to target rows and columns in specific ways.</p>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/5962/mixed-position-and-label-based-selection#t=201610120828283711024">Mixed position and label based selection</a></... | 2 | 2016-10-12T08:34:15Z | [
"python",
"pandas"
] |
How do I memoize this LIS python2.7 algorithm properly? | 39,993,507 | <p>I'm practicing Dynamic Programming and I am writing the Longest Increasing Subsequence problem.</p>
<p>I have the DP solution:</p>
<pre><code>def longest_subsequence(lst, lis=[], mem={}):
if not lst:
return lis
if tuple(lst) not in mem.keys():
if not lis or lst[0] > lis[-1]:
mem[tuple(lst)] = ... | 3 | 2016-10-12T08:03:02Z | 39,993,904 | <p>Your state depends on both <code>lst</code> and previous item you have picked. But you are only considering the <code>lst</code>. That is why you are getting incorrect results. To fix it you just have to add previous item to your dynamic state.</p>
<pre><code>def longest_subsequence(lst, prev=None, mem={}):
if no... | 4 | 2016-10-12T08:27:32Z | [
"python",
"algorithm",
"dynamic-programming",
"memoization"
] |
How do I memoize this LIS python2.7 algorithm properly? | 39,993,507 | <p>I'm practicing Dynamic Programming and I am writing the Longest Increasing Subsequence problem.</p>
<p>I have the DP solution:</p>
<pre><code>def longest_subsequence(lst, lis=[], mem={}):
if not lst:
return lis
if tuple(lst) not in mem.keys():
if not lis or lst[0] > lis[-1]:
mem[tuple(lst)] = ... | 3 | 2016-10-12T08:03:02Z | 40,008,192 | <p>So I had just discovered that Tempux's answer did not work for all cases.</p>
<p>I went back and through about encapsulating the entire state into the memoization dictionary and thus added <code>tuple(lis)</code> as part of the key. Also, the <code>lst</code> index trick may not be as easy to implement since I am ... | 0 | 2016-10-12T20:54:53Z | [
"python",
"algorithm",
"dynamic-programming",
"memoization"
] |
Cython efficient cycle 'for' for a given list instead of range(N) | 39,993,593 | <p>I'm coding on cython (python 2.7) and I'm dealing with 'for' cycles. As long as I use the standard <code>for i in range(N)</code>, I got a cool code: no yellow warning on the cythonized <code>code.html</code>.</p>
<p>When I create a list of integer (as range(N) is, isn't it?), for example:</p>
<pre><code>cdef long... | 0 | 2016-10-12T08:08:48Z | 40,005,818 | <p>You're best off just looping over it by index</p>
<pre><code>cdef Py_ssize_t i
cdef long val
with cython.boundscheck(False): # these two lines are optional but may increase speed
with cython.wraparound(False):
for i in range(lista.shape[0]):
val = lista[i]
</code></pre>
<p>Another optimization you coul... | 0 | 2016-10-12T18:26:28Z | [
"python",
"python-2.7",
"optimization",
"cython"
] |
Replicating results with different artificial neural network frameworks (ffnet, tensorflow) | 39,993,598 | <p>I'm trying to model a technical process (a number of nonlinear equations) with artificial neural networks. The function has a number of inputs and a number of outputs (e.g. 50 inputs, 150 outputs - all floats).</p>
<p>I have tried the <a href="http://ffnet.sourceforge.net/overview.html" rel="nofollow">python librar... | 0 | 2016-10-12T08:09:11Z | 39,996,371 | <p>I understand you are trying to re-train the same architecture from scratch, with a different library. The first fundamental issue to keep in mind here is that neural nets <a href="http://stackoverflow.com/q/24161525/777285">are not necessarily reproducible</a>, when weights are initialized randomly.</p>
<p>For exam... | 0 | 2016-10-12T10:30:12Z | [
"python",
"neural-network",
"tensorflow",
"keras"
] |
python re expression confusion | 39,993,628 | <p>When reading book: web scraping with python, the re expression confused me,</p>
<blockquote>
<pre><code>webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE)
</code></pre>
</blockquote>
<p>And a link in usually looks like:</p>
<pre><code><a href="/view/Afghanistan-1">
</code></pre>
... | -1 | 2016-10-12T08:11:16Z | 39,994,124 | <ol>
<li><p><code>[>]+</code> matches any other attributes and their corresponding values inside the tag.</p></li>
<li><p><code>*?</code> matches between zero and unlimited times, as few times as possible, expanding as needed. so it will only capture the text that would before the NEXT <code>["\']</code></p></li>
</... | 0 | 2016-10-12T08:38:55Z | [
"python",
"python-2.7"
] |
How to not import imported submodules in a Python module? | 39,993,663 | <p>In my Python modules I often use sub-modules such as <code>datetime</code>. The issue is that these modules become accessible from outside: </p>
<pre><code># module foo
import datetime
def foosay(a):
print "Foo say: %s" % a
</code></pre>
<p>From IPython:</p>
<pre><code>import foo
foo.datetime.datetime.now()
... | 1 | 2016-10-12T08:13:40Z | 39,993,835 | <p>You can do the import datetime within the function that uses it in module foo:</p>
<pre><code>def foodate():
import datetime
print datetime.datetime.now()
def foosay(a):
print "Foo say: %s" % a
</code></pre>
<p>Now importing foo will not import datetime.</p>
<p><strong>EDIT:</strong> You can also red... | 1 | 2016-10-12T08:23:47Z | [
"python",
"import",
"module",
"visibility"
] |
user.is_authenticated always returns False for inactive users on template | 39,993,714 | <p>In my template, <code>login.html</code>, I have:</p>
<pre><code>{% if form.errors %}
{% if user.is_authenticated %}
<div class="alert alert-warning"><center>Your account doesn't have access to this utility.</center></div>
{% else %}
<div class="alert alert-warning"><... | 1 | 2016-10-12T08:17:01Z | 39,994,258 | <p>There isn't any point checking <code>{% if user.is_authenticated %}</code> in your login template. If the user is authenticated, then your <code>custom_login</code> view would have redirected them to the homepage.</p>
<p>If the account is inactive, then the form will be invalid and the user will not be logged in. T... | 2 | 2016-10-12T08:45:07Z | [
"python",
"django",
"django-templates",
"django-authentication"
] |
user.is_authenticated always returns False for inactive users on template | 39,993,714 | <p>In my template, <code>login.html</code>, I have:</p>
<pre><code>{% if form.errors %}
{% if user.is_authenticated %}
<div class="alert alert-warning"><center>Your account doesn't have access to this utility.</center></div>
{% else %}
<div class="alert alert-warning"><... | 1 | 2016-10-12T08:17:01Z | 39,994,473 | <p>Just to complement Alasdair's very sensible answer, if you <strong>really</strong> want to explicitely check whether the user exists but is inactive, you can use <code>AuthenticationForm.get_user()</code>, ie:</p>
<pre><code>{% if form.errors %}
{% with form.get_user as user %}
{% if user %}
{# the use... | 1 | 2016-10-12T08:57:03Z | [
"python",
"django",
"django-templates",
"django-authentication"
] |
Python: machine learning without imputing missing data | 39,993,738 | <p>I am currently working with a quite particular dataset : it has about 1000 columns and 1M rows, but about 90% of the values are Nan.
This is not because the records are bad, but because the data represent measurement made on individuals and only about 100 features are relevant for each individual. As such, imputing... | 2 | 2016-10-12T08:18:54Z | 40,019,480 | <p>You can use gradient boosting packages which handle missing values and are ideal for your case.Since you asked for packages gbm in R and xgboost in python can be used.If you want to know how missing values are handled automatically in xgboost go through section 3.4 of <a href="https://arxiv.org/pdf/1603.02754v3.pdf"... | 1 | 2016-10-13T11:16:17Z | [
"python",
"machine-learning",
"pca",
"missing-data"
] |
How to create list of 3 or 4 columns of Dataframe in Pandas when we have 20 to 50 colums? | 39,993,744 | <p>When we create list using the below code, we get the list of all the columns but I want to get the list of only 3 to 5 specific columns.</p>
<p>col_list= list(df)</p>
| 3 | 2016-10-12T08:19:08Z | 39,993,766 | <p>Use slicing of <code>list</code>:</p>
<pre><code>df[df.columns[2:5]]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
... | 2 | 2016-10-12T08:20:09Z | [
"python",
"pandas",
"data-science"
] |
python preserving output csv file column order | 39,993,900 | <p>The issue is common, when I import a csv file and process it and finally output it, the order of column in the output csv file may be different from the original one,for instance:</p>
<pre><code>dct={}
dct['a']=[1,2,3,4]
dct['b']=[5,6,7,8]
dct['c']=[9,10,11,12]
header = dct.keys()
rows=pd.DataFrame(dct).to_dict('r... | 0 | 2016-10-12T08:27:18Z | 39,993,960 | <p>Instead of <code>dct={}</code> just do this:</p>
<pre><code>from collections import OrderedDict
dct = OrderedDict()
</code></pre>
<p>The keys will be ordered in the same order you define them.</p>
<p>Comparative test:</p>
<pre><code>from collections import OrderedDict
dct = OrderedDict()
dct['a']=[1,2,3,4]
dct['... | 3 | 2016-10-12T08:30:55Z | [
"python",
"csv",
"order"
] |
python preserving output csv file column order | 39,993,900 | <p>The issue is common, when I import a csv file and process it and finally output it, the order of column in the output csv file may be different from the original one,for instance:</p>
<pre><code>dct={}
dct['a']=[1,2,3,4]
dct['b']=[5,6,7,8]
dct['c']=[9,10,11,12]
header = dct.keys()
rows=pd.DataFrame(dct).to_dict('r... | 0 | 2016-10-12T08:27:18Z | 39,994,021 | <p>Try using <code>OrderedDict</code> instead of <code>dictionary</code>. <code>OrderedDict</code> is part of <code>collections</code> module.</p>
<p>Docs: <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">link</a></p>
| 1 | 2016-10-12T08:33:10Z | [
"python",
"csv",
"order"
] |
What's the best way to separate each stone in an image with many stones (some above the others) | 39,993,910 | <p>I need to make a study of the floor of a lake, and have to calculate the number and average size of the stones on the floor.</p>
<p>I have been studying morphological procedures to solve it in OpenCV but still need to find a way to try to separate the stones and make a binary image that precisely shows theirs conto... | -1 | 2016-10-12T08:27:53Z | 39,994,108 | <p>Wathershed is probably what will give you an approximation to the solution.</p>
<p>Other thing that you may do is try labelling images with the number of flakes and particles you can count and feed it to a deep neural net and let it findout how to count the flakes, if you have enough training cases you may endup wi... | 0 | 2016-10-12T08:38:11Z | [
"python",
"opencv",
"image-processing",
"image-segmentation"
] |
What's the best way to separate each stone in an image with many stones (some above the others) | 39,993,910 | <p>I need to make a study of the floor of a lake, and have to calculate the number and average size of the stones on the floor.</p>
<p>I have been studying morphological procedures to solve it in OpenCV but still need to find a way to try to separate the stones and make a binary image that precisely shows theirs conto... | -1 | 2016-10-12T08:27:53Z | 40,010,811 | <p>You should start with the "basic" contour detection based on Canny filter:
<a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html" rel="nofollow">http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html</a>
This simple met... | 0 | 2016-10-13T01:21:03Z | [
"python",
"opencv",
"image-processing",
"image-segmentation"
] |
Match a substring in Pandas wit str.extract method | 39,993,921 | <p>I have a string looking like:</p>
<pre><code>29818-218705-61709-2
</code></pre>
<p>I want to extract the second to last 5 digits number between the two dashes</p>
<pre><code>61709
</code></pre>
<p>each string is contained in a pandas series:</p>
<p>I came up with:</p>
<pre><code>df.id.str.extract(r'[.-]([0... | 2 | 2016-10-12T08:28:35Z | 39,993,970 | <p>You may use</p>
<pre><code>[.-]([0-9]{5})[.-][0-9]+$
</code></pre>
<p>See <a href="https://regex101.com/r/UHzTOq/1" rel="nofollow">this regex demo</a></p>
<p><strong>Details</strong>:</p>
<ul>
<li><code>[.-]</code> - a <code>.</code> or <code>-</code> separator</li>
<li><code>([0-9]{5})</code> - Group 1 capturin... | 0 | 2016-10-12T08:31:25Z | [
"python",
"regex",
"string",
"pandas"
] |
Match a substring in Pandas wit str.extract method | 39,993,921 | <p>I have a string looking like:</p>
<pre><code>29818-218705-61709-2
</code></pre>
<p>I want to extract the second to last 5 digits number between the two dashes</p>
<pre><code>61709
</code></pre>
<p>each string is contained in a pandas series:</p>
<p>I came up with:</p>
<pre><code>df.id.str.extract(r'[.-]([0... | 2 | 2016-10-12T08:28:35Z | 39,994,193 | <p>you can use <code>split</code></p>
<pre><code>df.id.str.split('-').str[-2]
</code></pre>
<hr>
<p><strong><em>demo</em></strong> </p>
<pre><code>df = pd.DataFrame(dict(id=['29818-218705-61709-2'] * 1000))
df.id.str.split('-').str[-2].head()
0 61709
1 61709
2 61709
3 61709
4 61709
Name: id, dtype... | 2 | 2016-10-12T08:42:30Z | [
"python",
"regex",
"string",
"pandas"
] |
Match a substring in Pandas wit str.extract method | 39,993,921 | <p>I have a string looking like:</p>
<pre><code>29818-218705-61709-2
</code></pre>
<p>I want to extract the second to last 5 digits number between the two dashes</p>
<pre><code>61709
</code></pre>
<p>each string is contained in a pandas series:</p>
<p>I came up with:</p>
<pre><code>df.id.str.extract(r'[.-]([0... | 2 | 2016-10-12T08:28:35Z | 39,994,257 | <p>You can try:</p>
<pre><code>>>> s = "29818-218705-61709-2 "
>>> s.split("-")[2]
'61709'
</code></pre>
| 1 | 2016-10-12T08:45:06Z | [
"python",
"regex",
"string",
"pandas"
] |
Edit HTML, inserting CSS reference | 39,993,959 | <p>It's possible to create HTML page from a CSV file, with the following:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('../data.csv',delimiter=';', engine='python')
df.to_html('csv.html')
</code></pre>
<p>I would like to make that HTML to respect some CSS pre... | 0 | 2016-10-12T08:30:45Z | 39,994,259 | <p>The <code>to_html</code> method does not output an entire HTML document. Instead, it just creates a single <code>table</code> element.</p>
<p>If you want to include CSS, you have to create additional HTML elements, and insert them yourself before writing the data. One of the simplest ways is as follows:</p>
<pre><... | 1 | 2016-10-12T08:45:15Z | [
"python",
"html",
"python-2.7",
"pandas"
] |
How to include __build_class__ when creating a module in the python C API | 39,994,010 | <p>I am trying to use the <a href="https://docs.python.org/3/c-api/" rel="nofollow">Python 3.5 C API</a> to execute some code that includes constructing a class. Specifically this:</p>
<pre><code>class MyClass:
def test(self):
print('test')
MyClass().test()
</code></pre>
<p>The problem I have is that it... | 0 | 2016-10-12T08:32:46Z | 39,995,510 | <p>Their are (at least) two ways to solve this it seems...</p>
<h2>Way 1</h2>
<p>Instead of:</p>
<pre><code>pGlobal = PyDict_New();
</code></pre>
<p>You can import the <code>__main__</code> module and get it's globals dictionary like this:</p>
<pre><code>pGlobal = PyModule_GetDict(PyImport_AddModule("__main__"));
... | 0 | 2016-10-12T09:45:57Z | [
"python",
"c",
"python-3.x",
"python-c-api"
] |
How could you refactor current_user in User.query.all() in Flask-Security? | 39,994,099 | <p>Index page should be shown only to logged in users and redirect other users to landing page.</p>
<pre><code>@app.route('/')
def index():
if current_user in User.query.all():
return render_template('index.html')
else:
return render_template('landing.html')
</code></pre>
<p>So how could you r... | 0 | 2016-10-12T08:37:35Z | 39,998,142 | <p>Use <code>current_user.is_authenticated</code> property. e.g </p>
<pre><code>if current_user.is_authenticated:
return render_template('index.html')
else:
return render_template('landing.html')
</code></pre>
| 3 | 2016-10-12T12:03:15Z | [
"python",
"flask",
"flask-security"
] |
Pandas: using groupby if values in columns are dictionaries | 39,994,110 | <p>I have dataframe</p>
<pre><code>category dictionary
moto {'motocycle':10, 'buy":8, 'motocompetition':7}
shopping {'buy':200, 'order':20, 'sale':30}
IT {'iphone':214, 'phone':1053, 'computer':809}
shopping {'zara':23, 'sale':18, 'sell':20}
IT {'lenovo':200, 'iphone':300, 'mac':200}
</code></pre>
<p>I need... | 2 | 2016-10-12T08:38:11Z | 39,994,459 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>nlargest</code></a> and <a href=... | 3 | 2016-10-12T08:56:28Z | [
"python",
"pandas",
"dictionary"
] |
Pandas: using groupby if values in columns are dictionaries | 39,994,110 | <p>I have dataframe</p>
<pre><code>category dictionary
moto {'motocycle':10, 'buy":8, 'motocompetition':7}
shopping {'buy':200, 'order':20, 'sale':30}
IT {'iphone':214, 'phone':1053, 'computer':809}
shopping {'zara':23, 'sale':18, 'sell':20}
IT {'lenovo':200, 'iphone':300, 'mac':200}
</code></pre>
<p>I need... | 2 | 2016-10-12T08:38:11Z | 39,994,485 | <pre><code>df = pd.DataFrame(dict(category=['moto', 'shopping', 'IT', 'shopping', 'IT'],
dictionary=[
dict(motorcycle=10, buy=8, motocompetition=7),
dict(buy=200, order=20, sale=30),
dict(iphone=214, phone=1053, comp... | 2 | 2016-10-12T08:57:27Z | [
"python",
"pandas",
"dictionary"
] |
What happen after recursion found base condition? | 39,994,167 | <p>I am trying to understand recursion , I am following stackoverflow answer <a href="http://stackoverflow.com/questions/717725/understanding-recursion">Understanding recursion</a> but i am not getting what i am looking. until i have learned this : <code>" if recursion is in program then below block of code will not... | 0 | 2016-10-12T08:41:09Z | 39,994,500 | <p>The recursion is quite easy to understand...in your example the function is calling itself multiple times, but with different values:</p>
<p>F(4)-> F(3) -> F(2) -> F(1) -> F(0) when you reach the last one (printing 4 3 2 1), then the function after printing also 0 it is just "return" so it reaches the last iteratio... | -1 | 2016-10-12T08:58:05Z | [
"python",
"recursion"
] |
What happen after recursion found base condition? | 39,994,167 | <p>I am trying to understand recursion , I am following stackoverflow answer <a href="http://stackoverflow.com/questions/717725/understanding-recursion">Understanding recursion</a> but i am not getting what i am looking. until i have learned this : <code>" if recursion is in program then below block of code will not... | 0 | 2016-10-12T08:41:09Z | 39,997,613 | <p>Sometimes the most basic information is important. What it appears you may <em>not</em> yet have realised is that Python creates a <strong>new (local) namespace</strong> for each function call. Not only that, but the function you use as an example doesn't even really take much advantage of recursion. But consider th... | 2 | 2016-10-12T11:36:05Z | [
"python",
"recursion"
] |
What happen after recursion found base condition? | 39,994,167 | <p>I am trying to understand recursion , I am following stackoverflow answer <a href="http://stackoverflow.com/questions/717725/understanding-recursion">Understanding recursion</a> but i am not getting what i am looking. until i have learned this : <code>" if recursion is in program then below block of code will not... | 0 | 2016-10-12T08:41:09Z | 39,999,929 | <p>What you have is simply a <em>call stack</em>. Whenever a function calls another function, that new call is pushed onto the call stack.</p>
<pre><code>def a():
b()
def b():
c()
def c():
pass
a()
</code></pre>
<p><code>a</code> calls <code>b</code>, <code>b</code> calls <code>c</code>. You now have a... | 1 | 2016-10-12T13:29:35Z | [
"python",
"recursion"
] |
What happen after recursion found base condition? | 39,994,167 | <p>I am trying to understand recursion , I am following stackoverflow answer <a href="http://stackoverflow.com/questions/717725/understanding-recursion">Understanding recursion</a> but i am not getting what i am looking. until i have learned this : <code>" if recursion is in program then below block of code will not... | 0 | 2016-10-12T08:41:09Z | 40,050,211 | <p>@deceze already clear the points but i would like to add few points more:</p>
<p>For Understanding this , You have to the understand fundamental of stack , i have <a href="http://stackoverflow.com/a/40049954/5904928">answered here</a> in detail. </p>
<blockquote>
<p>After recursion find its base condition then w... | 1 | 2016-10-14T18:54:03Z | [
"python",
"recursion"
] |
what is the purpose of solid_i18n_patterns? | 39,994,217 | <p>i am new to <strong>python/django</strong> and i just want to know the purpose of below function/code (<code>solid_i18n_patterns</code>). </p>
<pre><code>from django.conf.urls import url
from solid_i18n.urls import solid_i18n_patterns
urlpatterns =
solid_i18n_patterns(<appname.views>,<urlpattern>,<... | -2 | 2016-10-12T08:43:32Z | 39,994,836 | <p>solid_i18n is a helper package for internationalization.
Suppose you have an English website and you want to serve it also in French. By default, If you make your site bilingual, you should specify language code at the beginning of your URLs:</p>
<pre><code>www.example.com/en/* - serves English
www.example.com/fr/*... | 1 | 2016-10-12T09:13:54Z | [
"python",
"django",
"url-pattern"
] |
Sorting Bigram by number of occurrence NLTK | 39,994,312 | <p>I am currently running this code for search for bigram for entire of my text processing.</p>
<p>Variable alltext is really long text (over 1 million words)</p>
<p>I ran this code to extract bigram</p>
<pre><code>from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import re
tokenizer = R... | 2 | 2016-10-12T08:48:51Z | 39,994,755 | <p>It looks like <code>finder.ngram_fd</code> is a dictionary. In that case, in Python 3 the <code>items()</code> method does not return a list, so you'll have to cast it to one.</p>
<p>Once you have a list, you can simply use the <code>key=</code> parameter of the <a href="https://docs.python.org/3/library/stdtypes.h... | 2 | 2016-10-12T09:10:08Z | [
"python",
"nltk"
] |
Create n strings in Python | 39,994,332 | <p>I get a number (n) from user.
Just</p>
<pre><code>n = int(input())
</code></pre>
<p>After that, I have to to create <strong>n</strong> strings and get their values from user.</p>
<pre><code>i = 0;
while (i < n):
word = input() # so here is my problem:
# i don't know how to create n di... | 1 | 2016-10-12T08:49:57Z | 39,994,385 | <p>You need to use a list, like this:</p>
<pre><code>n = int(input())
i = 0
words = []
while ( i < n ):
word = input()
words.append(word)
i += 1
</code></pre>
<p>Also, this loop is better created as a for loop:</p>
<pre><code>n = int(input())
words = []
for i in range(n):
words.append(input())
</... | 3 | 2016-10-12T08:52:46Z | [
"python"
] |
Create n strings in Python | 39,994,332 | <p>I get a number (n) from user.
Just</p>
<pre><code>n = int(input())
</code></pre>
<p>After that, I have to to create <strong>n</strong> strings and get their values from user.</p>
<pre><code>i = 0;
while (i < n):
word = input() # so here is my problem:
# i don't know how to create n di... | 1 | 2016-10-12T08:49:57Z | 39,994,400 | <p>Try this (python 3):</p>
<pre><code>n = int(input())
s = []
for i in range(n):
s.append(str(input()))
</code></pre>
<p>The lits s will contains all the n strings.</p>
| 2 | 2016-10-12T08:53:37Z | [
"python"
] |
Create n strings in Python | 39,994,332 | <p>I get a number (n) from user.
Just</p>
<pre><code>n = int(input())
</code></pre>
<p>After that, I have to to create <strong>n</strong> strings and get their values from user.</p>
<pre><code>i = 0;
while (i < n):
word = input() # so here is my problem:
# i don't know how to create n di... | 1 | 2016-10-12T08:49:57Z | 39,994,585 | <p>If you are aware of <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehensions</a>, you can do this in a single line</p>
<pre><code>s = [str(input()) for i in range(int(input()))]
</code></pre>
<p>int(input()) - This gets the input on the number of strings. Then the f... | 2 | 2016-10-12T09:02:35Z | [
"python"
] |
How to convert huge binary data into ASCII format? | 39,994,357 | <p>I want to read a file which contains huge binary data. I want to convert this binary data into ASCII format. At the time of start, I want to read 2 bytes which indicates size of message, message is ahead of size. After reading this whole message, again repeat same action, 2 bytes for size of message and then actual ... | 2 | 2016-10-12T08:51:26Z | 39,994,615 | <p>from the <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' mea... | 1 | 2016-10-12T09:03:46Z | [
"python",
"struct",
"python-2.x",
"binascii"
] |
How to convert huge binary data into ASCII format? | 39,994,357 | <p>I want to read a file which contains huge binary data. I want to convert this binary data into ASCII format. At the time of start, I want to read 2 bytes which indicates size of message, message is ahead of size. After reading this whole message, again repeat same action, 2 bytes for size of message and then actual ... | 2 | 2016-10-12T08:51:26Z | 39,995,465 | <p>It depends on how your two byte length is stored in the data, for example, if the first two bytes of your file (as hex) were <code>00 01</code> does this mean a message following is <code>1</code> byte long or <code>256</code> bytes long? This is referred to as either big or little endian format. Try both of the fol... | 2 | 2016-10-12T09:44:06Z | [
"python",
"struct",
"python-2.x",
"binascii"
] |
How to convert huge binary data into ASCII format? | 39,994,357 | <p>I want to read a file which contains huge binary data. I want to convert this binary data into ASCII format. At the time of start, I want to read 2 bytes which indicates size of message, message is ahead of size. After reading this whole message, again repeat same action, 2 bytes for size of message and then actual ... | 2 | 2016-10-12T08:51:26Z | 39,996,499 | <p>Try:</p>
<pre><code>import struct
with open('abc.dat', 'rb') as f:
while True:
try:
msg_len = struct.unpack('h', f.read(2))[0] # assume native byte order
msg_data = f.read(msg_len) # just read 'msg_len' bytes
print repr(msg_data)
except:
# somethi... | 0 | 2016-10-12T10:37:28Z | [
"python",
"struct",
"python-2.x",
"binascii"
] |
python decorators and static methods | 39,994,468 | <p>I want to add decorator with my python static method, like following:</p>
<pre><code>class AdminPanelModel(db.Model):
id = db.Column('id', db.Integer, primary_key=True)
visible = db.Column(db.Boolean,)
def decor_init(func):
def func_wrapper(*kargs, **kwargs):
for l in model.all():... | 0 | 2016-10-12T08:56:57Z | 39,994,743 | <p>You need to use a <code>classmethod</code> instead:</p>
<pre><code>@classmethod
@decor_init
def all_newscollection_at_adminpanel(cls):
pass
</code></pre>
<p>The call is the same, but <code>classmethod</code>s implicitly receive the class as the first argument, which will then also be passed into the decorated ... | 2 | 2016-10-12T09:09:41Z | [
"python",
"sqlalchemy"
] |
iterate through classes in selenium python | 39,994,489 | <p>** Im running this on a popup page. therefore cant simply use "entry" class as it clashes with the original page.</p>
<p>I want to iterate through classes to pick out the text, from the "entry" class</p>
<pre><code>from selenium import webdriver
driver=webdriver.Firefox()
</code></pre>
<p><a href="https://i.stack... | 1 | 2016-10-12T08:57:39Z | 39,994,611 | <p>Consider using this:</p>
<pre><code>for div in driver.find_elements_by_class_name("entry"):
do_something(div.text)
</code></pre>
<p>After edited question:
This then must be solved using xpath.</p>
<pre><code>for div in driver.find_elements_by_xpath("//span/div/div/div[@class='entry']"):
do_something(div)
... | 0 | 2016-10-12T09:03:29Z | [
"python",
"selenium",
"web-scraping"
] |
iterate through classes in selenium python | 39,994,489 | <p>** Im running this on a popup page. therefore cant simply use "entry" class as it clashes with the original page.</p>
<p>I want to iterate through classes to pick out the text, from the "entry" class</p>
<pre><code>from selenium import webdriver
driver=webdriver.Firefox()
</code></pre>
<p><a href="https://i.stack... | 1 | 2016-10-12T08:57:39Z | 39,994,983 | <p>Try this xpath it will locate correctly : </p>
<pre><code>".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']"
</code></pre>
<p>Example use:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
fro... | 1 | 2016-10-12T09:20:52Z | [
"python",
"selenium",
"web-scraping"
] |
Python TCP Server sending message to all clients | 39,994,533 | <p>I have been trying to make a TCP python server over my LAN, but I've constantly run into issues with this project. My question is: Is it possible to send a message (over TCP) to multiple clients from 1 server? (I.e. client-1 sends a message "Hello world" and it shows the message on all other clients [clients-2, clie... | 0 | 2016-10-12T09:00:12Z | 39,994,796 | <p>Your code is... very weird. First thing is that you create a new thread on <code>accept</code> but you send listener to that thread instead of the client. Thus your threads never die and you have a memory and cpu leak. It's even worse: in your code the number of threads is equal to the number of <strong>all</strong>... | 1 | 2016-10-12T09:12:34Z | [
"python",
"sockets",
"tcp"
] |
Matrix Form Representation of Results | 39,994,660 | <p>I have 7 csv files which has list of words. I have taken all the words from 7 csv and put in a new file called Total_Words_list. </p>
<p>The issue is that I need an output in the following matrix:</p>
<pre><code> APPLE BALL CAT DOG....
A 0 1 1 0
B 1 1 0 1
C 1 1 1 0
</code></pre>
... | 1 | 2016-10-12T09:05:55Z | 39,995,060 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> for concating all <code>DataFrames</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> wi... | 4 | 2016-10-12T09:25:10Z | [
"python",
"csv",
"pandas"
] |
Edit table programmatically to fit content | 39,994,686 | <p>It's possible to create HTML page from a CSV file, with the following:</p>
<pre><code>import pandas as pd
df = pd.read_csv('../data.csv',delimiter=';', engine='python')
df.to_html('csv.html')
</code></pre>
<p>Column width of this table seems to respect the header (column title) size but for some columns content i... | 2 | 2016-10-12T09:07:16Z | 39,995,375 | <p>Answer is based on <a href="http://stackoverflow.com/questions/39993959/edit-html-inserting-css-reference">this</a>.</p>
<pre><code>import pandas as pd
filename = 'csv.html'
df = pd.read_csv('../data.csv',delimiter=';', engine='python')
html_begin = '\
<meta charset="UTF-8">\n\
<html>\n\
<head>... | 1 | 2016-10-12T09:40:27Z | [
"python",
"html",
"css",
"python-2.7",
"pandas"
] |
Python child class constructor argument | 39,994,689 | <p>I have a parent class whose constructor has three argument, now I want to have a child class whose constructor only has two argument, but it's telling me it has to be given three arguments when I try to create the child object.</p>
<pre><code>class Parent(Exception):
def _init_(self, a, b):
...
super(Pa... | 0 | 2016-10-12T09:07:30Z | 39,994,858 | <p>you should be able to use: </p>
<pre><code>class Parent(Exception):
def __init__(self, a, b):
self.a = a
self.b = b
class Child(Parent):
a = 123
def __init__(self, b):
super().__init__(self.a, b)
</code></pre>
| 0 | 2016-10-12T09:14:51Z | [
"python",
"inheritance",
"constructor"
] |
python equivalent to PHP Post | 39,994,694 | <p>I am working with legacy system the previous programer was gone.<br>
Here is the test he left and I have no idea how to imitate his test using <code>python</code>. My background is <code>iOS, Android, Java, Python, Django, C/C++, PLSQL, SQL</code> but no PHP at all</p>
<p>Here is <code>test.php</code></p>
<pre><co... | 1 | 2016-10-12T09:07:43Z | 39,994,842 | <p>Edited:</p>
<pre><code>notification_data = [{
"host": i.host,
"host_name": i.host_name,
"incident_created": i.incident_created,
"component_type": i.component_type,
"component_status": i.component_status
}]
r = requests.post(NOC_BEENETS_URL, data = {'params': json.dumps(no... | 2 | 2016-10-12T09:14:08Z | [
"php",
"python"
] |
Difference between cv2.findNonZero and Numpy.NonZero | 39,994,831 | <p>Silly question here.</p>
<p>I want to find the locations of the pixels from some black and white images and found this two functions from Numpy library and OpenCV.</p>
<p>The example I found on the internet (<a href="http://docs.opencv.org/trunk/d1/d32/tutorial_py_contour_properties.html" rel="nofollow">http://doc... | 0 | 2016-10-12T09:13:39Z | 39,996,246 | <p>There is an error in the documentation:</p>
<blockquote>
<p>Numpy gives coordinates in (row, column) format, while OpenCV gives coordinates in (x,y) format. So basically the answers will be interchanged. <s>Note that, row = x and column = y.</s> <strong>Note that, row = y and column = x.</strong></p>
</blockquote... | 2 | 2016-10-12T10:23:59Z | [
"python",
"opencv",
"numpy"
] |
get the name of most recent file in linux - PYTHON | 39,994,863 | <p>I want to get the name of the most recent file from a particular directory in python?</p>
<p>I used this</p>
<pre><code>import os
import glob
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
print... | 0 | 2016-10-12T09:15:01Z | 39,995,466 | <p>with your last line you just retrieve the files with .png extension</p>
<pre><code>get_latest_file('ocr', 'uploads', '*.png')
</code></pre>
<p>if you want to retrieve all files not depending on the extension, you just need to remove your extension specification in code to glob.glob('<em>'). This will retrieve all ... | 2 | 2016-10-12T09:44:07Z | [
"python"
] |
get the name of most recent file in linux - PYTHON | 39,994,863 | <p>I want to get the name of the most recent file from a particular directory in python?</p>
<p>I used this</p>
<pre><code>import os
import glob
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
print... | 0 | 2016-10-12T09:15:01Z | 39,995,583 | <p>If you don't care about the extension a simple os.walk iteration will do. You can extend this to filter extensions if you need.</p>
<pre><code>import os
all_files = {}
root = 'C:\workspace\werkzeug-master'
for r, d, files in os.walk(root):
for f in files:
fp = os.path.join(root, r, f)
all_files... | 0 | 2016-10-12T09:49:24Z | [
"python"
] |
Just heard of Jupyter - is it possible to use Javascript and keep it in the cloud? | 39,994,971 | <p>I heard of Jupyter last night and was using it with Python last night. Looks like a great notebook for coding, something I have been searching for, but I'm unsure if I can use JavaScript with it? It looks like there are npm packages, but I would assume that would then stop me from saving it all in the cloud and havi... | 0 | 2016-10-12T09:20:09Z | 39,995,115 | <p>IJavascript is an npm package that implements a Javascript kernel for the Jupyter notebook (formerly known as IPython notebook). A Jupyter notebook combines the creation of rich-text documents (including equations, graphs and videos) with the execution of code in a number of programming languages (including Javascri... | 1 | 2016-10-12T09:27:51Z | [
"javascript",
"python",
"node.js",
"jupyter",
"jupyter-notebook"
] |
Python decorator logger | 39,995,207 | <p>I have the following code:</p>
<pre><code>def log(func):
def wrapper(*args, **kwargs):
func_str = func.__name__
args_str = ', '.join(args)
kwargs_str = ', '.join([':'.join([str(j) for j in i]) for i in kwargs.iteritems()])
with open('log.txt', 'w') as f:
f.write(func_... | 1 | 2016-10-12T09:32:09Z | 39,995,248 | <p>Because you are calling it here:</p>
<pre><code>return wrapper()
</code></pre>
<p>It should be:</p>
<pre><code>return wrapper
</code></pre>
| 4 | 2016-10-12T09:33:54Z | [
"python",
"decorator"
] |
Python decorator logger | 39,995,207 | <p>I have the following code:</p>
<pre><code>def log(func):
def wrapper(*args, **kwargs):
func_str = func.__name__
args_str = ', '.join(args)
kwargs_str = ', '.join([':'.join([str(j) for j in i]) for i in kwargs.iteritems()])
with open('log.txt', 'w') as f:
f.write(func_... | 1 | 2016-10-12T09:32:09Z | 39,995,253 | <p>You should return the <code>wrapper</code> function without calling it:</p>
<pre><code>return wrapper
</code></pre>
<p>Calling it implies the call to <code>wrapper</code> has to be evaluated, which you're however calling with the wrong signature.</p>
| 3 | 2016-10-12T09:34:02Z | [
"python",
"decorator"
] |
Error with given arguments and numpy - Python | 39,995,225 | <p>I have the following father class and method:</p>
<pre><code>import SubImage
import numpy as np
from scipy import misc
import random
class Image():
# Class constructor
def __init__(self):
self.__image = np.empty(0)
self.__rows = 0
self.__cols = 0
self.__rows_pixels = 0
... | 0 | 2016-10-12T09:32:47Z | 39,995,679 | <p>If you're importing <code>SubImage</code> from another file, i.e. a module, you will have to reference that in the import. In this case, assuming <code>SubImage</code> is in a file called <code>SubImage.py</code>, the import should be</p>
<pre><code>from SubImage import SubImage
</code></pre>
<p>so that <code>SubI... | 0 | 2016-10-12T09:54:08Z | [
"python",
"numpy",
"arguments"
] |
Error with given arguments and numpy - Python | 39,995,225 | <p>I have the following father class and method:</p>
<pre><code>import SubImage
import numpy as np
from scipy import misc
import random
class Image():
# Class constructor
def __init__(self):
self.__image = np.empty(0)
self.__rows = 0
self.__cols = 0
self.__rows_pixels = 0
... | 0 | 2016-10-12T09:32:47Z | 39,996,023 | <p>Your main problem is the way you import both Image and Subimage into each other. </p>
<p>Subimage should be imported this way:</p>
<pre><code>from myprojectSubImage import SubImage
</code></pre>
<p>Image should be imported this way:</p>
<pre><code>from FILENAME import Image
</code></pre>
<p>that being said, th... | 0 | 2016-10-12T10:12:11Z | [
"python",
"numpy",
"arguments"
] |
How to delete data from a RethinkDB database using its changefeed | 39,995,308 | <p>I'm working on a 'controller' for a database which continuously accrues data, but only uses recent data, defined as less than 3 days old. As soon as data becomes more than 3 days old, I'd like to dump it to a JSON file and remove it from the database.</p>
<p>To simulate this, I've done the following. The 'controlle... | 0 | 2016-10-12T09:36:54Z | 39,996,157 | <p>I used the fact that each <code>change</code> contains the ID of the corresponding document in the database, and created a selection using <code>get</code> with this ID:</p>
<pre><code>with open(output_file, 'a') as f:
for change in data_to_archive.changes().run(conn, time_format="raw"): # The time_forma... | 0 | 2016-10-12T10:18:57Z | [
"python",
"rethinkdb"
] |
Python numpy array integer indexed flat slice assignment | 39,995,309 | <p>Was experimenting with numpy and found this strange behavior.
This code works ok:</p>
<pre><code>>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a[:, 1].flat[:] = np.array([-1, -1])
>>> a
array([[ 1, -1, 3],
[ 4, -1, 6]])
</code></pre>
<p>But why this code doesn't change to -1... | 0 | 2016-10-12T09:36:56Z | 39,995,368 | <p>In first example by flattening the slice you don't change the shape and actually the <strike>python</strike> Numpy doesn't create a new object. so assigning to flattened slice is like assigning to actual slice. But by flattening a 2d array you're changing the shape and hence numpy makes a copy of it.</p>
<p>also y... | 2 | 2016-10-12T09:40:10Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"slice"
] |
Python numpy array integer indexed flat slice assignment | 39,995,309 | <p>Was experimenting with numpy and found this strange behavior.
This code works ok:</p>
<pre><code>>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a[:, 1].flat[:] = np.array([-1, -1])
>>> a
array([[ 1, -1, 3],
[ 4, -1, 6]])
</code></pre>
<p>But why this code doesn't change to -1... | 0 | 2016-10-12T09:36:56Z | 39,995,832 | <p>You could just remove the <code>flat[:]</code> <code>from a[:, [0, 2]].flat[:] += 100</code>:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a[:, 1].flat[:] += 100
>>> a
array([[ 1, 102, 3],
[ 4, 105, 6]])
>>> a[:, [0, 2]]... | 0 | 2016-10-12T10:02:41Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"slice"
] |
Python numpy array integer indexed flat slice assignment | 39,995,309 | <p>Was experimenting with numpy and found this strange behavior.
This code works ok:</p>
<pre><code>>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a[:, 1].flat[:] = np.array([-1, -1])
>>> a
array([[ 1, -1, 3],
[ 4, -1, 6]])
</code></pre>
<p>But why this code doesn't change to -1... | 0 | 2016-10-12T09:36:56Z | 39,996,210 | <p>As others has pointed out <code>.flat</code> may create a copy of the original vector, so any updates to it would be lost. But <code>flat</code>tening a 1D slice is fine, so you can use a <code>for</code> loop to update multiple indexes.</p>
<pre><code>import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
a[:, 1... | 1 | 2016-10-12T10:21:40Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"slice"
] |
access docker container in kubernetes | 39,995,335 | <p>I have a docker container with an application exposing port 8080.
I can run it and access it on my local computer:</p>
<pre><code>$ docker run -p 33333:8080 foo
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
</code></pre>
<p>I can test it with:</p>
<pre><code>$ nc -v locahost 33333
connection succeed... | 0 | 2016-10-12T09:38:23Z | 40,000,085 | <p>The problem was that the application was listening on IP <code>127.0.0.1</code>.
It needs to listen on <code>0.0.0.0</code> to work in kubernetes. A change in the application code did the trick.</p>
| 1 | 2016-10-12T13:35:54Z | [
"python",
"docker",
"kubernetes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.