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 to override clean method of a form generated by UpdateView?
38,884,616
<p>Is it possible to override a <code>clean method</code> of the form which is generated by <strong>Class Based View</strong> - <code>UpdateView</code>?</p> <p>In <code>form</code>, I would override <code>clean</code> method to check, whether either first or second field is filled. </p> <p>Form would be like:</p> <p...
0
2016-08-10T22:33:16Z
38,884,798
<p>You can make your view use your form by setting <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.form_class" rel="nofollow"><code>form_class</code></a>.</p> <pre><code>class EditOrderView(UpdateView): model = Job form_class = MyForm ...
2
2016-08-10T22:50:28Z
[ "python", "django", "django-views" ]
How to set sys.modules["m"]=<current module>
38,884,630
<p>I have this structure:</p> <pre><code>merged.py: everything main.py: import merged sys.modules['othermodule'] = merged othermodule.f() </code></pre> <p>If I merged this into single file <code>main.py</code>, is there any way to tell <code>othermodule</code> resolve to <code>main</code> while inside of <co...
2
2016-08-10T22:34:37Z
38,884,716
<pre><code>sys.modules['othermodule'] = sys.modules[__name__] </code></pre> <p>Gets the current module you are in and sets as othermodule. Now you can:</p> <pre><code>import othermodule othermodule.f() </code></pre> <p>If you prefer to assign module to variable you can simply:</p> <pre><code>othermodule = sys.modul...
1
2016-08-10T22:41:09Z
[ "python" ]
How to calculate timedelta pairs from a dictionary
38,884,651
<p>I have a dictionary with key-value pairs of type timedelta in '%H:%M:%S'</p> <p>i.e.</p> <pre><code>myDict = {'0:00:12': '0:40:10', '0:00:18': '0:04:58', '0:00:50': '0:02:35'} </code></pre> <p>What I want to be able to do is calculate the difference between the key and the value for each pair and save those those...
0
2016-08-10T22:35:36Z
38,884,668
<p>Use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a></p> <pre><code>[datetime.strptime(value, FMT) - datetime.strptime(key, FMT) for key, value in myDict.iteritems()] </code></pre>
1
2016-08-10T22:37:07Z
[ "python", "datetime", "dictionary" ]
How to calculate timedelta pairs from a dictionary
38,884,651
<p>I have a dictionary with key-value pairs of type timedelta in '%H:%M:%S'</p> <p>i.e.</p> <pre><code>myDict = {'0:00:12': '0:40:10', '0:00:18': '0:04:58', '0:00:50': '0:02:35'} </code></pre> <p>What I want to be able to do is calculate the difference between the key and the value for each pair and save those those...
0
2016-08-10T22:35:36Z
38,884,687
<p>Initialise a container to collect the results, and append them inside the loop</p> <pre><code>results = [] for key, value in myDict.iteritems(): result = datetime.strptime(value, FMT) - datetime.strptime(key, FMT) results.append(result) </code></pre> <p>This is the most basic way to get your desired result...
0
2016-08-10T22:38:33Z
[ "python", "datetime", "dictionary" ]
How to calculate timedelta pairs from a dictionary
38,884,651
<p>I have a dictionary with key-value pairs of type timedelta in '%H:%M:%S'</p> <p>i.e.</p> <pre><code>myDict = {'0:00:12': '0:40:10', '0:00:18': '0:04:58', '0:00:50': '0:02:35'} </code></pre> <p>What I want to be able to do is calculate the difference between the key and the value for each pair and save those those...
0
2016-08-10T22:35:36Z
38,885,351
<p>Combining the answers of @wim @user35269 and @RandyTek Here is the final code. Note that converting the datetime object to string will give you the desired output, to save or print out later:</p> <pre><code>from datetime import datetime myDict = {'0:00:12': '0:40:10', '0:00:18': '0:04:58', '0:00:50': '0:02:35'} FM...
0
2016-08-11T00:01:24Z
[ "python", "datetime", "dictionary" ]
Writing multiple files into one file using Python, while taking input from the user to choose the files to scan
38,884,686
<p>Ok, so I have code that looks like this:</p> <pre><code>input_name="PLACEHOLDER" while input_name != "": input_name=input('Part Name: ') with open("/pathway/%s.txt" %input_name ,"r") as read_data, open("output.txt","w") as output: if part_name != "": f=input_data.read() print(input_data) outpu...
1
2016-08-10T22:38:19Z
38,884,788
<p>You can keep the <code>output.txt</code> open from the beginning of the execution and open each file after the user input its name.</p> <p>Example (not tested): </p> <pre><code>with open("output.txt","w") as output: while True: input_name = input('Part Name: ').strip() if input_name == '': ...
1
2016-08-10T22:49:18Z
[ "python", "python-3.x" ]
Writing multiple files into one file using Python, while taking input from the user to choose the files to scan
38,884,686
<p>Ok, so I have code that looks like this:</p> <pre><code>input_name="PLACEHOLDER" while input_name != "": input_name=input('Part Name: ') with open("/pathway/%s.txt" %input_name ,"r") as read_data, open("output.txt","w") as output: if part_name != "": f=input_data.read() print(input_data) outpu...
1
2016-08-10T22:38:19Z
38,884,862
<p>Just going to mockup some code for you to help guide you, no guarantees this will work to any degree, but should get you started.</p> <p>First off, lets store all the part names in a list so we can loop over them later on:</p> <pre><code>input_name = [] user_input = input('Part Name: ') while user_input != "": ...
1
2016-08-10T22:57:25Z
[ "python", "python-3.x" ]
Replace each letter in a last name by the consecutive letter in the alphabet
38,884,715
<p>How to replace each letter in a last name by the consecutive letter in the alphabet? I need this script as a masking tool.</p> <p>Logic for last name: (a change to b, b change to c, ...., z change to a)</p> <p>Example: John Doe will become John Epf</p> <p>Input File: <code>names.txt</code></p> <pre><code>John yi...
-3
2016-08-10T22:41:09Z
38,884,746
<p>This is called <a href="https://en.wikipedia.org/wiki/Caesar_cipher" rel="nofollow">Caesar's cipher</a>.</p> <p>Take a look at how it's done here: <a href="http://stackoverflow.com/a/8895517/6664393">http://stackoverflow.com/a/8895517/6664393</a></p> <p>You'll have change it a little to allow uppercase characters ...
1
2016-08-10T22:44:11Z
[ "python", "python-3.x" ]
Replace each letter in a last name by the consecutive letter in the alphabet
38,884,715
<p>How to replace each letter in a last name by the consecutive letter in the alphabet? I need this script as a masking tool.</p> <p>Logic for last name: (a change to b, b change to c, ...., z change to a)</p> <p>Example: John Doe will become John Epf</p> <p>Input File: <code>names.txt</code></p> <pre><code>John yi...
-3
2016-08-10T22:41:09Z
38,884,767
<p>The problem as defined in your question can be solved as follows:</p> <pre><code>parts = name.split() parts[1]=''.join([chr((ord(c) - 65 + 1) % 26 + 65) if ord(c) &lt; 91 else chr((ord(c) - 97 + 1) % 26 + 97) for c in parts[1]]) ' '.join(parts) </code></pre> <p...
0
2016-08-10T22:47:11Z
[ "python", "python-3.x" ]
Calculate every 5 minute returns using 1 minute data in pandas dataframe
38,884,807
<p>I have 1 minute price data as Python pandas dataframe like this:</p> <pre><code> Date Time Open High Low Close 390 2004-04-13 1900-01-01 09:31:00 1146.210 1147.020 1146.210 1147.020 391 2004-04-13 1900-01-01 09:32:00 1147.120 1147.339 1147.120 1147.219 392...
1
2016-08-10T22:51:20Z
38,884,926
<p>User <code>pd.TimeGrouper('5T')</code></p> <pre><code>df = df.set_index(df.Date + (df.Time - pd.to_datetime(df.Time.dt.date))) cols = ['Open', 'High', 'Low', 'Close'] agg = np.log(df[cols]).groupby(pd.TimeGrouper('5T')).agg(['first', 'last']) agg.stack(0).T.diff().dropna().squeeze().unstack() </code></pre> <p><a ...
0
2016-08-10T23:05:27Z
[ "python", "pandas" ]
How to merge multiple JSON data rows based on a field in pyspark with a given reduce function
38,884,857
<p>How do I merge the JSON data rows as shown below using the merge function below with pyspark? </p> <p>Note: Assume this is just a minutia example and I have 1000s of rows of data to merge. What is the most performant solution? For better or for worse, I must use pyspark.</p> <p>Input:</p> <pre><code>data = [ ...
1
2016-08-10T22:56:50Z
38,886,011
<p>I think it would be something like this:</p> <pre><code>sc.parallelize(data).groupBy(lambda x: x['name']).map(lambda t: {'name':t[0],'addresses':[(x['timestamp'], x['address']) for x in t[1]]}).collect() </code></pre>
1
2016-08-11T01:40:22Z
[ "python", "json", "apache-spark", "merge", "pyspark" ]
How to merge multiple JSON data rows based on a field in pyspark with a given reduce function
38,884,857
<p>How do I merge the JSON data rows as shown below using the merge function below with pyspark? </p> <p>Note: Assume this is just a minutia example and I have 1000s of rows of data to merge. What is the most performant solution? For better or for worse, I must use pyspark.</p> <p>Input:</p> <pre><code>data = [ ...
1
2016-08-10T22:56:50Z
38,886,629
<p>All right, using maxymoo's example, I put together my own reusable code. It's not exactly what I was looking for, but it gets me closer to how I want to solve this particular problem: without lambdas and with reusable code.</p> <pre><code>#!/usr/bin/env pyspark # -*- coding: utf-8 -*- data = [ {'timestamp': '...
0
2016-08-11T03:08:30Z
[ "python", "json", "apache-spark", "merge", "pyspark" ]
Django access request.user in class based view
38,884,887
<p>I'm currently working on the following issue: The user can access the page <code>test.com/BlogPostTitle</code>. Where <code>BlogPostTitle</code> is a slug. If a Blog post with the fitting title exists, Django should render the DetailView of said blog post. If it doesn't exist, Django should render a form to create a...
0
2016-08-10T23:01:00Z
38,885,049
<p>Is the error occurred at template rendering? If so I wonder you've make iter over attributes on single <code>User</code> object. I think you may need <code>user.values()</code>.</p> <p>BTW, <code>check_user_editor</code> should be simpler:</p> <pre><code>def check_user_editor(user): return user.groups.filter(n...
0
2016-08-10T23:21:13Z
[ "python", "django" ]
Django access request.user in class based view
38,884,887
<p>I'm currently working on the following issue: The user can access the page <code>test.com/BlogPostTitle</code>. Where <code>BlogPostTitle</code> is a slug. If a Blog post with the fitting title exists, Django should render the DetailView of said blog post. If it doesn't exist, Django should render a form to create a...
0
2016-08-10T23:01:00Z
38,885,193
<p>Your error is in line 74 in <code>mediwiki.views</code>:</p> <pre><code>view = HttpResponse(request.user) </code></pre> <p><code>HttpResponse</code> expects a string or an iterable. Since <code>request.user</code> is not a string, it tries to use it as an iterable, which fails.</p> <p>I can't say much without the...
0
2016-08-10T23:38:37Z
[ "python", "django" ]
Parsing a header file using swig
38,884,979
<p>I have a header file with struct definitions that I'd like to be able to parse in python. In order to do this I turned to Swig.</p> <p>Lets say the header file is named "a.h". I first renamed it to "a.c" and added an empty "a.h" file in the same folder.</p> <p>Next, I added in an "a_wrap.i" file with the following...
0
2016-08-10T23:12:45Z
39,067,693
<p>The global variables <code>a_a</code>, <code>a_b and</code>a_c<code>should be accessible from [within your SWIG Python module via</code>cvar`]<a href="http://www.swig.org/Doc1.3/Python.html#Python_nn16" rel="nofollow">1</a>:</p> <pre><code>import a print a.cvar.a_a print a.cvar.a_b # etc. </code></pre>
0
2016-08-21T18:45:33Z
[ "python", "swig" ]
sphinx-apidoc picks up submodules, but autodoc doesn't document them
38,885,106
<p>I've been working on a project for PyQt5 ( found here: <a href="https://github.com/MaVCArt/StyledPyQt5" rel="nofollow">https://github.com/MaVCArt/StyledPyQt5</a> ) which uses a package structure to make imports a bit more logical. I've been relatively successful in documenting the code so far with Sphinx, at least u...
1
2016-08-10T23:28:07Z
38,947,318
<p>I ended up fixing this problem eventually - it seems I was overlooking some errors, and sphinx worked just fine. I added all the paths the package contains in the conf.py and it just worked from there:</p> <p>conf.py:</p> <pre><code>sys.path.insert(0, os.path.abspath('../StyledPyQt5')) sys.path.insert(0, os.path.a...
0
2016-08-14T22:52:34Z
[ "python", "python-sphinx", "autodoc" ]
Value Counts of Column Slice to Contain All Possible Unique Values in Column
38,885,214
<p>I have a df that looks like this:</p> <pre><code>group val A 1 A 1 A 2 B 1 B 2 B 3 </code></pre> <p>I want to get the value_counts for each group separately, but want to show all possible values for each value_count group:</p> <pre><code>&gt; df[df['group']=='A']['val'].value...
0
2016-08-10T23:42:02Z
38,885,482
<p>This works:</p> <pre><code>from io import StringIO import pandas as pd import numpy as np data = StringIO("""group,val A,1 A,1 A,2 B,1 B,2 B,3""") df = pd.read_csv(data) print(df, '\n') res_idx = pd.MultiIndex.from_product([df['group'].unique(), df['val'].unique()]) res = pd.concat([pd.DataFrame(index=res_idx), ...
1
2016-08-11T00:20:57Z
[ "python", "pandas" ]
Value Counts of Column Slice to Contain All Possible Unique Values in Column
38,885,214
<p>I have a df that looks like this:</p> <pre><code>group val A 1 A 1 A 2 B 1 B 2 B 3 </code></pre> <p>I want to get the value_counts for each group separately, but want to show all possible values for each value_count group:</p> <pre><code>&gt; df[df['group']=='A']['val'].value...
0
2016-08-10T23:42:02Z
38,885,652
<pre><code>In [185]: df.groupby('group')['val'].value_counts().unstack('group') Out[185]: group A B val 1 2.0 1.0 2 1.0 1.0 3 NaN 1.0 In [186]: df.groupby('group')['val'].value_counts().unstack('group')['A'] Out[186]: val 1 2.0 2 1.0 3 NaN Name: A, dtype: float64 </code><...
1
2016-08-11T00:46:01Z
[ "python", "pandas" ]
Django form validation not redirecting to the correct url
38,885,260
<p>I'm using Django 1.9.8 and having some trouble validating a form for registering users. If there are validation errors, the redirect back to the form is to the incorrect url. The registration url is <code>localhost:8000/register</code>. When errors are found (I think that's what's happening, anyway), the page is red...
0
2016-08-10T23:48:26Z
38,885,440
<p>The <code>action</code> on your form points to a relative path, <code>register</code>. If an url path does not begin with a slash, it will append it after the last slash of the current url. Since the form is being posted to <code>/register/register</code>, and your url pattern matches that, that's the url you'll see...
0
2016-08-11T00:14:16Z
[ "python", "django", "validation" ]
Running py2exe says run-py3.4-win32.exe is missing
38,885,292
<p>I tried to follow <a href="http://www.py2exe.org/index.cgi/Tutorial" rel="nofollow">this tutorial</a> and I got stuck. These are the steps I followed:</p> <ol> <li>I installed Anaconda 32 bit</li> <li>I executed <code>conda create -n test py2exe -c sasview</code>, which installed Python 3.4.5-0, py2exe 0.9.2.2-py34...
0
2016-08-10T23:52:42Z
38,903,773
<p>Executing <code>conda create -n test py2exe -c silg2</code> installs pytnon 3.4.5 instead of the most recent 3.5.2, which makes me think that conda knows which version works with py2exe. Apparently this is not true.</p> <p>This works:</p> <pre><code>conda create -n test python=3.4 activate test pip install py2exe ...
0
2016-08-11T18:33:02Z
[ "python", "python-3.x", "py2exe", "conda" ]
Rename/Backup old directory in python
38,885,370
<p>I have a script that creates a new directory regularly. I would like to check if it already exists and if so move the existing folder to a backup. My first iteration was</p> <pre><code>if os.path.isdir(destination_path): os.rename(destination_path,destination_path + '_old') </code></pre> <p>However, if there al...
0
2016-08-11T00:04:16Z
38,942,968
<p>If you need to move the old directory aside, renumbering can easily be done by listing all directories by the same name, then picking last one by extracting the numeric maximum from the matching names.</p> <p>Listing the directories can be done by using the <a href="https://docs.python.org/2/library/glob.html#glob....
1
2016-08-14T14:00:26Z
[ "python", "directory", "rename" ]
Rename/Backup old directory in python
38,885,370
<p>I have a script that creates a new directory regularly. I would like to check if it already exists and if so move the existing folder to a backup. My first iteration was</p> <pre><code>if os.path.isdir(destination_path): os.rename(destination_path,destination_path + '_old') </code></pre> <p>However, if there al...
0
2016-08-11T00:04:16Z
38,959,796
<p>Based on the more general answer given I ended up using something more streamlined for my specific case</p> <pre><code>if os.path.isdir(destination_path): n = len(glob.glob(destination_path + '*')) os.rename(destination_path, destination_path + '_' + str(n)) </code></pre>
0
2016-08-15T17:20:23Z
[ "python", "directory", "rename" ]
Need explanation difference between json and dict in Python
38,885,375
<p>I am just curious to understand JSON and Dict in Python more deeply.</p> <p>I have a JSON response from a server like this:</p> <pre><code>`{"city":"Mississauga","country":"Canada","countryCode":"CA"}` </code></pre> <p>And I want to work with it as a dictionary. For this, I use <code>.json()</code> function. Why ...
1
2016-08-11T00:04:33Z
38,885,501
<p>In Python, dictionary values are not accessible using the <code>my_dict.key</code> syntax. This is reserved for attributes of the <code>dict</code> class, such as <code>dict.get</code> and <code>dict.update</code>. Dictionary values are only accessible via the <code>my_dict[key]</code> syntax.</p>
3
2016-08-11T00:23:31Z
[ "python", "json", "dictionary", "implicit", "explicit" ]
Writing a dictionary to a csv file in python 2.7
38,885,376
<p>I want to write a dictionary that looks like this: {'2234': '1', '233': '60'} into a new csv file that has been created. I found a page where this was answered and I tried this out in python 2.7 but this still gives me an error whilst executing my code:</p> <pre><code>with open('variabelen.csv', 'w') as csvfile: ...
0
2016-08-11T00:04:34Z
38,885,387
<p>You are concatenating a list <code>[name]</code> with a string <code>items</code> - hence the error.</p> <p>Instead, you can simply write <code>items()</code> via <a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>.writerows()</code></a>:</p> <pre><code>with open('var...
1
2016-08-11T00:06:54Z
[ "python", "csv", "dictionary" ]
Python class inheritance
38,885,378
<p>I have this code:</p> <pre><code>class A(object): def __init__(self): print " A" class B(A): def __init__(self): print "B" x=B() print "Done" </code></pre> <p>the result is: "B" gets printed why does it not print "A", eventhough class B inheritance A</p>
2
2016-08-11T00:04:53Z
38,885,405
<p>If you want to use A's <code>__init__</code> while also using B's <code>__init__</code>, then try:</p> <pre><code>class A(object): def __init__(self): print " A" class B(A): def __init__(self): A.__init__(self) print "B" x=B() print "Done" </code></pre> <p>Or, if you would prefer n...
6
2016-08-11T00:08:55Z
[ "python", "class" ]
Can't output Python Print in PHP
38,885,431
<p>I'm really stuck on this one, but I am a python (and Raspberry Pi) newbie. All I want is to output the <code>print</code> output from my python script. The problem is (I believe) that a function in my python script takes half a second to execute and PHP misses the output.</p> <p>This is my php script:</p> <pre><co...
1
2016-08-11T00:12:51Z
38,885,490
<blockquote> <ol> <li>How to make PHP wait for Python completion</li> </ol> </blockquote> <p><code>shell_exec</code> will wait the command to finish</p> <blockquote> <ol start="2"> <li>Why does the PHP command line differ from the browser?</li> </ol> </blockquote> <p>My best guess is the difference of th...
1
2016-08-11T00:22:05Z
[ "php", "python", "linux" ]
Can't output Python Print in PHP
38,885,431
<p>I'm really stuck on this one, but I am a python (and Raspberry Pi) newbie. All I want is to output the <code>print</code> output from my python script. The problem is (I believe) that a function in my python script takes half a second to execute and PHP misses the output.</p> <p>This is my php script:</p> <pre><co...
1
2016-08-11T00:12:51Z
38,886,247
<p>This is not an answer, but added info to show why Pedro Lobito is correct.</p> <p>I edited my Python script to be:</p> <pre><code>#!/usr/bin/env python import sys import Adafruit_DHT import time print 'static text ' # humidity, temperature = Adafruit_DHT.read(11, 4) time.sleep(10) # print 'Temp: {0:0.1f}C Hum...
2
2016-08-11T02:13:13Z
[ "php", "python", "linux" ]
Python - Loop through non-blank Excel cells
38,885,466
<p>Very frustrated new Python user here. I had code running at one point then went on to do some other things and now it's not working.</p> <p>This is looping through non-blank cells in the 'J' column of an .xlsx file. For the cells that contain text, it looks at the date in column 'A'. If the date in column A is e...
1
2016-08-11T00:18:50Z
38,885,830
<p>Nevermind...I had a blank value in J3 with a string in A3 that was throwing it off. So I need to keep learning and check to see if a value is a date first and if not, ignore.</p>
1
2016-08-11T01:14:24Z
[ "python", "excel", "openpyxl", "xlrd" ]
Parallel processing of lists
38,885,570
<p>I'm trying to get my head around multiprocessing. I have a list, I divide it in two equally long parts, I sort them in two separate processes. I know that this part works because printing <code>saveto</code> gives me the two lists. But I can't access them because in the end I get two empty lists. Why can't I access ...
1
2016-08-11T00:33:55Z
38,887,015
<p>Use <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow">multiprocessing.Queue</a> to share data between processes</p> <pre><code>import multiprocessing import random def sort(l, queue): queue.put(sorted(l)) if __name__ == '__main__': l = [int(100000*rando...
2
2016-08-11T03:55:55Z
[ "python", "multiprocessing" ]
Longest Collatz (or Hailstone) sequence optimization - Python 2.7
38,885,614
<p>I've made a program that prints out a list of numbers, each one with a greater number of steps (according to the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture#Examples" rel="nofollow">Collatz Conjecture</a>) needed to reach 1 than the previous:</p> <pre><code>limit = 1000000000 maximum = 0 known = {} fo...
2
2016-08-11T00:40:51Z
38,886,383
<p>It appears to be inherently hard to speed up Collatz programs enormously; the best programs I'm aware of <a href="http://www.ericr.nl/wondrous/search.html" rel="nofollow">are distributed</a>, using idle cycles on hundreds (thousands ...) of PCs around the world.</p> <p>There are some easy things you can do to optim...
5
2016-08-11T02:30:35Z
[ "python", "algorithm", "caching", "optimization", "collatz" ]
Longest Collatz (or Hailstone) sequence optimization - Python 2.7
38,885,614
<p>I've made a program that prints out a list of numbers, each one with a greater number of steps (according to the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture#Examples" rel="nofollow">Collatz Conjecture</a>) needed to reach 1 than the previous:</p> <pre><code>limit = 1000000000 maximum = 0 known = {} fo...
2
2016-08-11T00:40:51Z
38,888,580
<p>You only really need to cache the odd numbers. Consider in your program what happens when you start working on a number.</p> <p>If you take your beginning number, X, and do a <code>mod 4</code>, you end up with one of four cases:</p> <ul> <li>0 or 2: Repeatedly dividing by 2 will eventually result in an odd number...
3
2016-08-11T06:16:13Z
[ "python", "algorithm", "caching", "optimization", "collatz" ]
Program to transform a string in hexadecimal?
38,885,640
<pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys try: string=sys.argv[1] cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&amp;/g'" os.system(cmd) except IndexError: print("\nInforme a string!\n") </code></pre> <p>I found this code on Internet. I tried ha...
0
2016-08-11T00:44:05Z
38,886,432
<p>This code is meant to be executed from the command line. It takes the first argument passed to the script and spits out that string encoded in ASCII. Let's break down the shell <code>cmd</code> so we can understand how it manages this.</p> <pre><code>echo -n "+string+" </code></pre> <p>Takes the variable <code>str...
1
2016-08-11T02:37:43Z
[ "python", "bash", "python-3.x", "hacking" ]
Program to transform a string in hexadecimal?
38,885,640
<pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys try: string=sys.argv[1] cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&amp;/g'" os.system(cmd) except IndexError: print("\nInforme a string!\n") </code></pre> <p>I found this code on Internet. I tried ha...
0
2016-08-11T00:44:05Z
38,886,443
<p>For the line:</p> <pre><code>cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&amp;/g'" </code></pre> <ul> <li><code>echo</code> sends the text to the standard output,</li> <li><code>|</code> pipes that output to <code>xxd</code>, which translates binary to hexadecimal (think hex editors); the <...
3
2016-08-11T02:39:31Z
[ "python", "bash", "python-3.x", "hacking" ]
Program to transform a string in hexadecimal?
38,885,640
<pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys try: string=sys.argv[1] cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&amp;/g'" os.system(cmd) except IndexError: print("\nInforme a string!\n") </code></pre> <p>I found this code on Internet. I tried ha...
0
2016-08-11T00:44:05Z
38,889,049
<p>Use this, should fix your probs</p> <pre><code>cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&amp;/g'" </code></pre>
0
2016-08-11T06:42:37Z
[ "python", "bash", "python-3.x", "hacking" ]
Program to transform a string in hexadecimal?
38,885,640
<pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys try: string=sys.argv[1] cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&amp;/g'" os.system(cmd) except IndexError: print("\nInforme a string!\n") </code></pre> <p>I found this code on Internet. I tried ha...
0
2016-08-11T00:44:05Z
38,889,556
<p>The explain is already done by @Nick Bull and @pzp, here I just want to say something about the implementation, it's trivial and can hardly satisfy the purpose.</p> <p>The original code would fail if the string contains unbalanced quote(single quote or double quote).</p> <p>And I suppose a snippet of python code t...
1
2016-08-11T07:09:36Z
[ "python", "bash", "python-3.x", "hacking" ]
Pandas Dataframe: get a multiindex row above the current column headings and merge the cells into a single cell
38,885,649
<p>I want to use pandas dataframe to add a a row above the current column heading. The first row should be a singly-merged cell that contains today's date.</p> <p>My current dataframe looks like below</p> <pre><code>index name field1 field2 1 John blah blah 2 Dave blah blah .........
1
2016-08-11T00:45:46Z
38,885,750
<p>Something along the lines of</p> <pre><code>df.columns = pd.MultiIndex.from_tuples([("Today's date", field) for field in df.colums]) </code></pre> <p>ought to work.</p> <p>Note what this does: it is not possible to merge a cell in pandas. It's just that repeated values don't get shown in this case.</p> <p>If you...
0
2016-08-11T01:01:54Z
[ "python", "pandas", "dataframe", "multi-index" ]
Pandas Dataframe: get a multiindex row above the current column headings and merge the cells into a single cell
38,885,649
<p>I want to use pandas dataframe to add a a row above the current column heading. The first row should be a singly-merged cell that contains today's date.</p> <p>My current dataframe looks like below</p> <pre><code>index name field1 field2 1 John blah blah 2 Dave blah blah .........
1
2016-08-11T00:45:46Z
38,888,790
<p>Another solution is set <code>column name</code>, then <code>MultiIndex</code> is not necessary:</p> <pre><code>import pandas as pd df = pd.DataFrame({'name':['John','Dave'], 'field1':['blah','blah'], 'field2':['blah','blah']}, index=[1,2], ...
0
2016-08-11T06:28:40Z
[ "python", "pandas", "dataframe", "multi-index" ]
Boolean expression for if list is within other list
38,885,658
<p>What is a efficient way to check if a list is within another list? Something like:</p> <pre><code>[2,3] in [1,2,3,4] #evaluates True [1,5,4] in [5,1,5,4] #evaluates True [1,2] in [4,3,2,1] #evaluates False </code></pre> <p>Order within the list matters.</p>
2
2016-08-11T00:47:09Z
38,885,803
<pre><code>def check_ordered_sublist_in_list(sub_list, main_list): sub_list = np.array(sub_list) main_list = np.array(main_list) return any(all(main_list[n:(n + len(sub_list))] == sub_list) for n in range(0, len(main_list) - len(sub_list) + 1)) &gt;&gt;&gt; check_ordered_sublist_in_list([2,...
3
2016-08-11T01:10:31Z
[ "python", "list", "contains", "sub-array" ]
Boolean expression for if list is within other list
38,885,658
<p>What is a efficient way to check if a list is within another list? Something like:</p> <pre><code>[2,3] in [1,2,3,4] #evaluates True [1,5,4] in [5,1,5,4] #evaluates True [1,2] in [4,3,2,1] #evaluates False </code></pre> <p>Order within the list matters.</p>
2
2016-08-11T00:47:09Z
38,885,964
<p>You could use this:</p> <pre><code>def is_in(short, long): return any(short==long[i:i+len(short)] for i in range(len(long)-len(short)+1)) is_in([2,3], [1,2,3,4]) # True is_in([1,5,4], [5,1,5,4]) # True is_in([1,2], [4,3,2,1]) # False </code></pre> <p>If you really care about speed, these expressions are 2...
2
2016-08-11T01:33:08Z
[ "python", "list", "contains", "sub-array" ]
How can I add Windows Credentials using Python?
38,885,666
<p>I am trying to create a program that automatically installs a network shortcut onto my desktop and downloads a driver (it is a print server for my work), but in order to access the shortcut after it is installed I need to enter my work credentials under the printer network's domain. I tried using the keyring library...
2
2016-08-11T00:48:22Z
38,885,841
<p>I'm pretty sure you can achieve this by creating a .bat file and executing it in your program.</p> <p>For Ex.</p> <pre><code>def bat_create_with_creds(id, pwd): """create Batch file to init printer domain creds with variables""" auth_print= open("auth_print.bat", "w") auth_print.write("NET USE \\prin...
0
2016-08-11T01:15:16Z
[ "python", "windows", "python-2.7" ]
Histogram from NetworkX Degree Values - Python 2 vs. Python 3
38,885,670
<p>I have the following code, which worked in Python 2.7, using NetworkX. Basically, it just plots a histogram of degree nodes like so:</p> <pre><code>plt.hist(nx.degree(G).values()) plt.xlabel('Degree') plt.ylabel('Number of Subjects') plt.savefig('network_degree.png') #Save as file, format specified in argument </co...
0
2016-08-11T00:48:56Z
38,885,810
<p>In Python2 the <code>dict.values</code> method returns a list. In Python3, it returns <a href="http://stackoverflow.com/q/7296716/190597">a <code>dict_values</code> object</a>:</p> <pre><code>In [197]: nx.degree(G).values() Out[197]: dict_values([2, 2, 2, 2]) </code></pre> <p>Since <code>plt.hist</code> accepts a ...
2
2016-08-11T01:11:10Z
[ "python", "matplotlib", "networkx" ]
Numpy NDPointer: Don't know how to convert parameter 1
38,885,719
<p>I am trying to push a Numpy array into C++ code.</p> <p>The C++ function is,</p> <pre><code>extern "C" void propagate(float * __restrict__ H, const float * __restrict__ W, const float * __restrict__ U, const float * __restrict__ x, float a, int h_len, int samples); </code></pre> <p>M...
0
2016-08-11T00:57:30Z
38,903,914
<p>Stupid typos ... should be argtypes. This fixed the mysterious error leading to other errors that already have answers on StackOverflow.</p> <pre><code>propagate = lib.propagate propagate.restype = None propagate.argtypes = [ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ndpointer(ctypes.c_f...
0
2016-08-11T18:40:17Z
[ "python", "c++", "numpy" ]
An easy way to show images in Django on deployment (DEBUG=false)
38,885,761
<p>I am using DJango 1.8 and python 3.4.3, and I have been running my app on Debug mode, and found a way to show images inside a directory configured on MEDIA_ROOT, this was my first question and the solution I have found: <a href="http://stackoverflow.com/questions/38866687/correct-way-to-save-an-image-in-admin-and-sh...
1
2016-08-11T01:03:28Z
38,885,937
<p>1) in urls.py add:</p> <pre><code>(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), </code></pre> <p>and open url <a href="http://myhost.com/media/" rel="nofollow">http://myhost.com/media/</a></p> <p>2) Never deploy ...
1
2016-08-11T01:30:18Z
[ "python", "django", "image" ]
An easy way to show images in Django on deployment (DEBUG=false)
38,885,761
<p>I am using DJango 1.8 and python 3.4.3, and I have been running my app on Debug mode, and found a way to show images inside a directory configured on MEDIA_ROOT, this was my first question and the solution I have found: <a href="http://stackoverflow.com/questions/38866687/correct-way-to-save-an-image-in-admin-and-sh...
1
2016-08-11T01:03:28Z
38,885,974
<p>Django runserver is not intended for serving up static files in a production environment. It should be limited to development and testing environments.</p> <p>If you are intending to use django's runserver to server up static files with DEBUG=False then use the <a href="https://docs.djangoproject.com/en/dev/ref/con...
3
2016-08-11T01:34:12Z
[ "python", "django", "image" ]
Weather "events" grouped based on time differences in Pandas
38,885,770
<p>I have a dataframe of surface weather observations (fzraHrObs) organized by a station identifier code ('usaf') and date. fzraHrObs has several columns of weather data. The station code and date (datetime objects) look like:</p> <pre><code>usaf dat 716270 2014-11-23 12:00:00 2015-12-20 08:00:00 ...
1
2016-08-11T01:04:19Z
38,900,053
<p>The answer in your comment means it is easy to avoid a loop, as you only need to look back to the previous event.</p> <pre><code>df['new_event'] = df.groupby('usaf')['dat'].apply(lambda s: s.diff().dt.seconds &gt; 6*3600) </code></pre> <p>Output:</p> <pre><code> usaf dat new_event 0 716270 20...
2
2016-08-11T15:06:48Z
[ "python", "pandas" ]
Def help, trying to define pieces of code
38,885,867
<p>Not sure if/or how to do this, excuse the mess I'm new.</p> <p>If I can get something like this to work it would clear a lot of my code.</p> <p>Thanks in advance</p> <pre><code>def on() GPIO.output(4, 0) def off() GPIO.output(4, 1) On Off </code></pre>
-4
2016-08-11T01:20:23Z
38,986,509
<p>You should research how to define Python functions. First, on the <code>def</code> statement after the parentheses, add a colon at the very end of the line. Next, all code inside your function must be indented. Third, to call the function, you need to put parentheses at the end.</p>
0
2016-08-17T00:42:39Z
[ "python" ]
Why wasn't my file opened?
38,885,891
<p>I'm working on a project at the end of a book I read for Python, so in case this hasn't given it away for you, I'm still quite new to this.</p> <p>I'm trying to use the <code>open</code> command to open a file that I know exists. I know that the code understands the file is there, because when I switch over to writ...
2
2016-08-11T01:23:47Z
38,885,908
<p>Your function isn't valid Python, as <code>split</code> isn't a globally defined function, but a built-in function of the type <code>str</code>. Try changing your function to something like this.</p> <pre><code>def getUserPoint(name): for line in openFile: line_split = line.split(",") print(lin...
1
2016-08-11T01:27:09Z
[ "python", "python-3.x" ]
How to deal with backslash apostrophes in a string?
38,885,909
<p>This has been talked about in other posts but I have a string that goes:</p> <pre><code>u' yeah its gucci, wassup baby yellow everything this time you know what im talking about yellow rims, yellow big booty, yellow bones yellow lambs, yellow mp\'s,' </code></pre> <p>I want to turn mp\'s --> mp's. I understand t...
-1
2016-08-11T01:27:15Z
38,888,859
<p>Just do this "yeah its gucci, wassup baby yellow everything this time you know what im talking about yellow rims, yellow big booty, yellow bones yellow lambs, yellow mp\'s,".</p>
0
2016-08-11T06:32:46Z
[ "python", "string" ]
slice df where column looks like [(A, 3), (-A, 1), (-C, 4)] using criteria like all rows such that A>5 etc
38,885,935
<p>I have a dataframe that has a column that looks something like the following:</p> <pre><code>dct = {} for x in range(0,1000000): test = {'A': np.random.randint(1,5), '-A': np.random.randint(1,5), '-C': np.random.randint(1,5)} dct[str(x)+'_key'] = test df = pd.DataFrame([[d.items()] for d in dct.values()]) ...
0
2016-08-11T01:29:54Z
38,886,130
<p>Easy, convert the column to a dictionary:</p> <pre><code>df[0] = df[0].apply(dict) </code></pre> <p>Now, whatever your query, you can write it as:</p> <pre><code>def query(row, key, value, cond): return eval(str(row.get(key)) + cond + str(value)) df.apply(query, key='A', value=2, cond='&gt;', axis=1) </code>...
-1
2016-08-11T01:57:51Z
[ "python", "pandas", "tuples", "slice" ]
slice df where column looks like [(A, 3), (-A, 1), (-C, 4)] using criteria like all rows such that A>5 etc
38,885,935
<p>I have a dataframe that has a column that looks something like the following:</p> <pre><code>dct = {} for x in range(0,1000000): test = {'A': np.random.randint(1,5), '-A': np.random.randint(1,5), '-C': np.random.randint(1,5)} dct[str(x)+'_key'] = test df = pd.DataFrame([[d.items()] for d in dct.values()]) ...
0
2016-08-11T01:29:54Z
38,886,356
<p>If you can split the column of tuples, this should work, just replace the conditionals with your numbers. I used these for the example data:</p> <pre><code>def f(x, var): tup_list = list(x) for t in tup_list: if t[0] == var: return t[1] return np.NaN df.columns = ['col'] for var in ['A...
1
2016-08-11T02:26:56Z
[ "python", "pandas", "tuples", "slice" ]
Data analysis of log files – How to find a pattern?
38,885,944
<p>My company has slightly more than 300 vehicle based windows CE 5.0 mobile devices that all share the same software and usage model of Direct Store Delivery during the day then doing a Tcom at the home base every night. There is an unknown event(s) that results in the device freaking out and rebooting itself in the ...
0
2016-08-11T01:30:43Z
38,886,144
<p>There is no input data at all to this problem so this answer will be basically pure theory, a little collection of ideas you could consider.</p> <ol> <li><p>To analize patterns out of a bunch of many logs you could definitely creating some graphs displaying relevant data which could help to narrow the problem, pyth...
0
2016-08-11T02:00:21Z
[ "python", "logging", "windows-ce", "data-analysis" ]
Data analysis of log files – How to find a pattern?
38,885,944
<p>My company has slightly more than 300 vehicle based windows CE 5.0 mobile devices that all share the same software and usage model of Direct Store Delivery during the day then doing a Tcom at the home base every night. There is an unknown event(s) that results in the device freaking out and rebooting itself in the ...
0
2016-08-11T01:30:43Z
38,886,198
<p>was wondering if you'd looked at the ELK stack? It's an acronym for elasticsearch, kibana and log stash and fits your use case closely; it's often used for analysis of large numbers of log files. </p> <p>Elasticsearch and kibana gives you a UI that lets you interactively explore and chart data for trends. Very p...
0
2016-08-11T02:07:33Z
[ "python", "logging", "windows-ce", "data-analysis" ]
Python: Pandas Series - Why use loc?
38,886,080
<p>Why do we use 'loc' for pandas dataframes? it seems the following code with or without using loc both compile anr run at a simulular speed</p> <pre><code>%timeit df_user1 = df.loc[df.user_id=='5561'] 100 loops, best of 3: 11.9 ms per loop </code></pre> <p>or</p> <pre><code>%timeit df_user1_noloc = df[df.user_id=...
2
2016-08-11T01:51:08Z
38,886,211
<ul> <li><p>Explicit is better than implicit. </p> <p><code>df[boolean_mask]</code> selects rows where <code>boolean_mask</code> is True, but there is a corner case when you might not want it to: when <code>df</code> has boolean-valued column labels:</p> <pre><code>In [229]: df = pd.DataFrame({True:[1,2,3],False:[3,4...
4
2016-08-11T02:08:40Z
[ "python", "pandas", "series", "loc" ]
load variables from a local file in ansible
38,886,086
<p>I want ansible to run several shell commonds(like: rm/ yum install ) over remote servers. But instead of putting commonds inside the playbook, I want ansible to read shell commands from a file , thereby other people only need to swap the commands in this file with no need to know how playbook works. file could in an...
0
2016-08-11T01:52:12Z
38,888,372
<p>You may want to use <a href="http://docs.ansible.com/ansible/include_vars_module.html" rel="nofollow">include_vars</a> module.</p> <p>If you want only pure shell commands to be executed without any processing, there is a <a href="http://docs.ansible.com/ansible/script_module.html" rel="nofollow">script</a> module t...
0
2016-08-11T06:03:30Z
[ "python", "ansible", "ansible-playbook", "ansible-2.x" ]
how to update a text file in a loop in python
38,886,168
<p>I write a function that can update a text file only for once but I need to repeatedly do it . In order to avoid frequently copy a temporary file to a target file , I want to update all words in a loop for only once .How can i can do it? Here is my python code(but only update once):</p> <pre><code>import io from ...
0
2016-08-11T02:04:26Z
38,887,033
<p>There can be many way to do this. 1 of the approach inline to what you have done can be to use *argv to get the list of words to be replaced and replace the words in same line as you are doing currenty. I am adding kind of pseudo code here, it is not tested for the errors. Please note 2 changes 1. in the input par...
0
2016-08-11T03:58:46Z
[ "python", "python-2.7", "nlp", "text-mining" ]
Automatically assign color to nodes in Graphviz
38,886,173
<p>I'm using python and Graphviz to draw some cluster graph consist of nodes. I want to assign different colors (depends on an attribute , for example the x coordinate, of each node) to nodes.</p> <p>Here's the way I produce graph</p> <pre><code>def add_nodes(graph, nodes): for n in nodes: if isinstance(n...
0
2016-08-11T02:04:49Z
38,909,236
<p>Oh I figured out a way to get what I want. Just for recording and for someone else may have a same problem(?) Can just rescale a color map and assign the corresponding index (of color) to the nodes.</p> <pre><code>def add_nodes(graph, nodes): for n in nodes: if isinstance(n, tuple): graph.node(n[0], **n...
0
2016-08-12T03:08:53Z
[ "python", "matplotlib", "plot", "graphviz" ]
Not able to get two if statements and an else statement to execute
38,886,269
<p>So currently I am trying to make a personal buddy program. I want it to be two if statements and one else. The two if statements have different word triggers, so that's why there is two. The problem arises when I want to make an else statement, so if the certain word triggers weren't typed, it would still say someth...
0
2016-08-11T02:16:29Z
38,886,321
<pre><code>sport = input("What sports do you play?\n") if sport in ['soccer','baseball','dance','basketball','golf','skiing','surfing']: print(sport, "sounds fun") elif sport in ['none','not at the moment','nope','none atm','natm']: print("Im not really into sports either") else: print(sport, "is a sport?")...
3
2016-08-11T02:22:11Z
[ "python", "if-statement" ]
Not able to get two if statements and an else statement to execute
38,886,269
<p>So currently I am trying to make a personal buddy program. I want it to be two if statements and one else. The two if statements have different word triggers, so that's why there is two. The problem arises when I want to make an else statement, so if the certain word triggers weren't typed, it would still say someth...
0
2016-08-11T02:16:29Z
38,886,435
<p>Use an <code>if-elif-else</code> statement to distinguish more than two cases, instead of the conditional statement <code>if-else</code>:</p> <pre><code>if sport in ['soccer','baseball','dance','basketball','golf','skiing','surfing']: print(sport, "sounds fun") elif sport in ['none','not at the moment','nope','...
3
2016-08-11T02:38:30Z
[ "python", "if-statement" ]
How to make a dictionary the value component or a numpy array
38,886,394
<p>I am a new Python 2.7 user. I recently learned about numpy arrays, and now I am now just learning about dictionaries. Please excuse me if my syntax is not correct.</p> <p>Let's say we have a dictionary:</p> <pre><code>dict1 = {'Ann': {'dogs': '3', 'cats': '4'}, 'Bob': {'dogs': '5', 'cats': '6'}, ...
0
2016-08-11T02:32:02Z
38,886,474
<h3>Inverting values in the dictionary</h3> <blockquote> <p><em>"I want each of the values for dogs and cats to be the inverse meaning 1/3, 1/5, 1/7, 1/9, etc."</em></p> </blockquote> <pre><code>&gt;&gt;&gt; {name:{key:1./float(value) for key,value in d.items()} for name,d in dict1.items()} {'Ann': {'cats': 0.25, ...
0
2016-08-11T02:45:27Z
[ "python", "arrays", "python-2.7", "numpy", "dictionary" ]
How to make a dictionary the value component or a numpy array
38,886,394
<p>I am a new Python 2.7 user. I recently learned about numpy arrays, and now I am now just learning about dictionaries. Please excuse me if my syntax is not correct.</p> <p>Let's say we have a dictionary:</p> <pre><code>dict1 = {'Ann': {'dogs': '3', 'cats': '4'}, 'Bob': {'dogs': '5', 'cats': '6'}, ...
0
2016-08-11T02:32:02Z
38,886,483
<p>If you just need the values as arrays you can use <code>pandas</code> to help convert to a <code>numpy</code> array. Alternatively, you can just use <code>pandas</code> to meet your requirements. <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html" rel="nofollow">Pandas</a> provides a data analysis lib...
5
2016-08-11T02:47:04Z
[ "python", "arrays", "python-2.7", "numpy", "dictionary" ]
How to make a dictionary the value component or a numpy array
38,886,394
<p>I am a new Python 2.7 user. I recently learned about numpy arrays, and now I am now just learning about dictionaries. Please excuse me if my syntax is not correct.</p> <p>Let's say we have a dictionary:</p> <pre><code>dict1 = {'Ann': {'dogs': '3', 'cats': '4'}, 'Bob': {'dogs': '5', 'cats': '6'}, ...
0
2016-08-11T02:32:02Z
38,890,272
<p>Based on your question and comments I think you just want the same dictionary structure, but with the numbers inverted:</p> <pre><code>dict1 = {'Ann': {'dogs': '3', 'cats': '4'}, 'Bob': {'dogs': '5', 'cats': '6'}, 'Chris': {'dogs': '7', 'cats': '8'}, 'Dan': {'dogs': '9', 'cats': '10'}} f...
1
2016-08-11T07:44:37Z
[ "python", "arrays", "python-2.7", "numpy", "dictionary" ]
How to make a dictionary the value component or a numpy array
38,886,394
<p>I am a new Python 2.7 user. I recently learned about numpy arrays, and now I am now just learning about dictionaries. Please excuse me if my syntax is not correct.</p> <p>Let's say we have a dictionary:</p> <pre><code>dict1 = {'Ann': {'dogs': '3', 'cats': '4'}, 'Bob': {'dogs': '5', 'cats': '6'}, ...
0
2016-08-11T02:32:02Z
38,901,973
<p>I know you said in the comments you weren't ready to start learning pandas but it would be quite a nice way to work with this data rather than a dictionary of dictionaries.</p> <p>Pandas has some nice built in functionality for constructing data frames from dictionaries. Once in a Pandas DataFrame, it's quite easy...
0
2016-08-11T16:44:19Z
[ "python", "arrays", "python-2.7", "numpy", "dictionary" ]
python group same values in a dictionary and give each a mark (or assign them into a new dict)
38,886,472
<p>Suppose I have a dictionary like this</p> <pre><code>origin_dict={0:[],1:[],2:['bus'],3:['bus'],4:['bus'],5:[],6:[],7:['train'],8:['train'],9:['train'],10:[],11:[],12:['train'],13:['train'],14:[]} </code></pre> <p>I want to group thme by the same value, but only when they are consecutive.</p> <pre><code>new_dict=...
0
2016-08-11T02:44:53Z
38,886,800
<pre><code>from collections import defaultdict from operator import itemgetter from itertools import groupby origin_dict = {0: [], 1: [], 2: ['bus'], 3: ['bus'], 4: ['bus'], 5: [], 6: [], 7: [ 'train'], 8: ['train'], 9: ['train'], 10: [], 11: [], 12: ['train'], 13: ['train'], 14: []} result = defaultdict(list) fo...
1
2016-08-11T03:30:15Z
[ "python", "list", "dictionary", "group", "itertools" ]
python group same values in a dictionary and give each a mark (or assign them into a new dict)
38,886,472
<p>Suppose I have a dictionary like this</p> <pre><code>origin_dict={0:[],1:[],2:['bus'],3:['bus'],4:['bus'],5:[],6:[],7:['train'],8:['train'],9:['train'],10:[],11:[],12:['train'],13:['train'],14:[]} </code></pre> <p>I want to group thme by the same value, but only when they are consecutive.</p> <pre><code>new_dict=...
0
2016-08-11T02:44:53Z
38,887,593
<p>This is mine simple and efficient solution.</p> <pre><code>#! /usr/bin/python origin_dict={0:[],1:[],2:['bus'],3:['bus'],4:['bus'],5:[],6:[],7:['train'],8:['train'],9:['train'],10:[],11:[],12:['train'],13:['train'],14:[]} dict_out = {} int_dict = {} mine_keys = [key for key in origin_dict.keys() if not origin_dic...
0
2016-08-11T05:02:27Z
[ "python", "list", "dictionary", "group", "itertools" ]
Python Scrapy Print Item Keys as Header in CSV
38,886,499
<p>I have a scrapy project I'm working on and I'm trying to export data to a csv file using a pipeline and I would like to print the item keys as the first row of the csv file. My pipeline code is below (I can post more code if necessary but I imagine this would suffice). Thanks in advance.</p> <pre><code>import csv...
0
2016-08-11T02:49:44Z
38,887,346
<p>Scrapy already adds header to csv export if you are outputting csv via:</p> <pre><code>scrapy crawl spidername --output results.csv </code></pre> <p>If you want to do it manually in a the pipeline you can create file and write headers in pipelines <a href="http://doc.scrapy.org/en/latest/topics/item-pipeline.html#...
1
2016-08-11T04:36:47Z
[ "python", "csv", "scrapy" ]
How to write a bash script which calls itself with python?
38,886,505
<p>Can someone explain how this bash script works? The part I don't understand is <code>""":"</code>, what does this syntax mean in bash?</p> <pre><code>#!/bin/sh """:" echo called by bash exec python $0 ${1+"$@"} """ import sys print 'called by python, args:',sys.argv[1:] </code></pre> <p>test running result:</...
1
2016-08-11T02:50:37Z
38,886,537
<p>That's clever! <strong>In Bash</strong>, the <code>""":"</code> will be expanded into only <code>:</code>, which is the empty command (it doesn't do anything). So, the next few lines will be executed, leading to <code>exec</code>. At that point, Bash <em>ceases to exist</em>, and the file is re-read by Python (its n...
2
2016-08-11T02:56:38Z
[ "python", "linux", "bash", "shell", "sh" ]
How to write a bash script which calls itself with python?
38,886,505
<p>Can someone explain how this bash script works? The part I don't understand is <code>""":"</code>, what does this syntax mean in bash?</p> <pre><code>#!/bin/sh """:" echo called by bash exec python $0 ${1+"$@"} """ import sys print 'called by python, args:',sys.argv[1:] </code></pre> <p>test running result:</...
1
2016-08-11T02:50:37Z
38,886,573
<p>This is an example for <a href="https://en.wikipedia.org/wiki/Polyglot_(computing)" rel="nofollow">polyglot</a>, where you write multiple programing languages in a file and still make it valid.</p> <p><strong>How is it valid in python</strong></p> <pre><code>""":" echo called by bash exec python $0 ${1+"$@"} """...
1
2016-08-11T03:00:58Z
[ "python", "linux", "bash", "shell", "sh" ]
How to write a bash script which calls itself with python?
38,886,505
<p>Can someone explain how this bash script works? The part I don't understand is <code>""":"</code>, what does this syntax mean in bash?</p> <pre><code>#!/bin/sh """:" echo called by bash exec python $0 ${1+"$@"} """ import sys print 'called by python, args:',sys.argv[1:] </code></pre> <p>test running result:</...
1
2016-08-11T02:50:37Z
38,886,587
<p><a href="http://stackoverflow.com/questions/3224878/what-is-the-purpose-of-the-colon-gnu-bash-builtin">What is the purpose of the : (colon) GNU Bash builtin?</a></p> <p>Also, once exec is called, the rest of the code is not executed because exec replaces the shell with the program, in this case the python process. ...
0
2016-08-11T03:02:28Z
[ "python", "linux", "bash", "shell", "sh" ]
Julia string format "if"
38,886,506
<p>In Python, <code>if</code> may be used in a situation such as the following for optional string formatting.</p> <pre><code>bar = 3 "{n} bar{s}".format(n=bar, s='s' if bar != 1 else '') # "3 bars" bar = 1 "{n} bar{s}".format(n=bar, s='s' if bar != 1 else '') # "1 bar" </code></pre> <p>Julia uses the dollar sign fo...
2
2016-08-11T02:50:51Z
38,893,387
<p>Yes. The <code>$</code> interpolation method works with expressions in parenthesis. In this case, <code>$bar bar$(bar != 1 ? 's' : "")</code> is equivalent to the Python results.</p> <p>As @Oxinabox mentioned, Python's inline <code>if</code> corresponds to Julia's ternary operator. In Julia the ternary operator <co...
5
2016-08-11T10:09:55Z
[ "python", "string", "if-statement", "format", "julia-lang" ]
Julia string format "if"
38,886,506
<p>In Python, <code>if</code> may be used in a situation such as the following for optional string formatting.</p> <pre><code>bar = 3 "{n} bar{s}".format(n=bar, s='s' if bar != 1 else '') # "3 bars" bar = 1 "{n} bar{s}".format(n=bar, s='s' if bar != 1 else '') # "1 bar" </code></pre> <p>Julia uses the dollar sign fo...
2
2016-08-11T02:50:51Z
38,899,410
<p>In addition to everything @DanGetz said, you may also want to check out the <a href="https://github.com/JuliaLang/Formatting.jl" rel="nofollow">Formatting package</a> – it's explicitly designed to offer more Python-like formatting facilities for Julia.</p>
2
2016-08-11T14:37:50Z
[ "python", "string", "if-statement", "format", "julia-lang" ]
Form Validation message not being displayed - Flask
38,886,525
<p>I'm having trouble getting error messages in Flask to render. I suspect this is related to the blueprints. Previously, the logic seen in views.py was in the users blueprint, but I've since ported it over to the main blueprint. Anyhow, since then, I am unable to get error messages to render.</p> <p>The specific line...
-1
2016-08-11T02:54:49Z
38,887,023
<p>Got it to work, @glls, you were correct.Rewrote the code as:</p> <pre><code>@main_blueprint.route('/', methods=['GET', 'POST']) @main_blueprint.route('/&lt;referrer&gt;', methods=['GET', 'POST']) def home(referrer=None): # prepares response resp = make_response(render_template('main/index.html', form=form)...
0
2016-08-11T03:57:13Z
[ "python", "flask", "flask-wtforms" ]
How to parse a single-column text file into a table using python?
38,886,546
<p>I'm new here to StackOverflow, but I have found a LOT of answers on this site. I'm also a programming newbie, so i figured i'd join and finally become part of this community - starting with a question about a problem that's been plaguing me for hours.</p> <p>I login to a website and scrape a big body of text within...
4
2016-08-11T02:57:59Z
38,887,835
<p>I had a code written for a website scrapping which may help you. Basically what you need to do is write click on the web page go to html and try to find the tag for the table you are looking for and using the module (i am using beautiful soup) extract the information. I am creating a json as I need to store it into...
-2
2016-08-11T05:23:54Z
[ "python", "web-scraping" ]
How to parse a single-column text file into a table using python?
38,886,546
<p>I'm new here to StackOverflow, but I have found a LOT of answers on this site. I'm also a programming newbie, so i figured i'd join and finally become part of this community - starting with a question about a problem that's been plaguing me for hours.</p> <p>I login to a website and scrape a big body of text within...
4
2016-08-11T02:57:59Z
38,911,274
<p>A simple custom parser like the following should do the trick. </p> <pre><code>from __future__ import print_function def parse_body(s): line_sep = '\n' getting_bins = False inv_code = '' for l in s.split(line_sep): if l.startswith('INVENTORY CODE:') and not getting_bins: inv_d...
0
2016-08-12T06:26:46Z
[ "python", "web-scraping" ]
How to parse a single-column text file into a table using python?
38,886,546
<p>I'm new here to StackOverflow, but I have found a LOT of answers on this site. I'm also a programming newbie, so i figured i'd join and finally become part of this community - starting with a question about a problem that's been plaguing me for hours.</p> <p>I login to a website and scrape a big body of text within...
4
2016-08-11T02:57:59Z
38,928,262
<p>A rather complex one, but this might get you started:</p> <pre><code>import re, pandas as pd from pandas import DataFrame rx = re.compile(r''' (?:INVENTORY\ CODE:)\s* (?P&lt;inv&gt;.+\S) [\s\S]+? ^BIN.+[\n\r] (?P&lt;bin_msg&gt;(?:(?!^...
0
2016-08-13T01:09:59Z
[ "python", "web-scraping" ]
Unable to parse the value of an element from response in python?
38,886,574
<pre><code>import requests from bs4 import BeautifulSoup s = requests.Session() content = s.get('https://nucleus.niituniversity.in/Default.aspx').content soup = BeautifulSoup(content,"html5lib") print("viewState = " + str(soup.select_one("#__VIEWSTATE")["value"])) print("UserDet = " + str(soup.select_one("#SchSel_hidCo...
0
2016-08-11T03:01:00Z
38,886,753
<p>No, the element with <code>id="SchSel_hidCoreUserDet"</code> does not have a <code>value</code>. Here is what I see if I open this page in the browser:</p> <pre><code>&lt;input type="hidden" name="SchSel$hidCoreUserDet" id="SchSel_hidCoreUserDet" value=""&gt; </code></pre> <p>The value is actually empty - it is th...
0
2016-08-11T03:24:42Z
[ "python", "asp.net", "beautifulsoup", "python-requests", "python-3.4" ]
convert string representation of array to numpy array in python
38,886,641
<p>I can <a href="http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python">convert a string representation of a list to a list</a> with <code>ast.literal_eval</code>. Is there an equivalent for a numpy array?</p> <pre><code>x = arange(4) xs = str(x) xs '[0 1 2 3]' # how do I ...
0
2016-08-11T03:09:22Z
38,886,759
<p>Numpy has a function called <code>fromstring</code>, document <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html#numpy.fromstring" rel="nofollow">here</a>. Briefly you can parse string like this:</p> <pre><code>s = '0 1 2 3' a = np.fromstring(s, dtype=np.int, sep=' ') print(a) # [0 1...
1
2016-08-11T03:25:59Z
[ "python", "numpy" ]
convert string representation of array to numpy array in python
38,886,641
<p>I can <a href="http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python">convert a string representation of a list to a list</a> with <code>ast.literal_eval</code>. Is there an equivalent for a numpy array?</p> <pre><code>x = arange(4) xs = str(x) xs '[0 1 2 3]' # how do I ...
0
2016-08-11T03:09:22Z
38,887,164
<p>Starting with this:</p> <pre><code> x = arange(4) xs = str(x) xs '[0 1 2 3]' </code></pre> <p>Try this:</p> <pre><code>import re, ast xs = re.sub('\s+', ',', xs) a = np.array(ast.literal_eval(xs)) a array([0, 1, 2, 3]) </code></pre>
3
2016-08-11T04:14:44Z
[ "python", "numpy" ]
How to convert a list of data frames to a panel in python-pandas?
38,886,698
<p>Given a list of data frames with the following format:</p> <pre><code>id age weight score date 01 11 50 90 2011-01-23 01 12 52 89 2012-03-23 ... </code></pre> <p>Please note that the <code>id</code> in a data frame is same. And I wish to get a panel, integrating all the data frames in ...
0
2016-08-11T03:17:25Z
38,886,856
<p>First step is to <code>concat</code> your frames together:</p> <pre><code> concated = pd.concat(list_of_frames) </code></pre> <p>Then, you can simply:</p> <pre><code>items = ['age', 'weight', 'score'] pd.Panel(dict(zip(items, [concated.pivot(index='date', columns='id', values=i) for i in items]))) </code></pre> ...
1
2016-08-11T03:37:00Z
[ "python", "pandas", "dataframe", "panel" ]
Python - scapy packet size difference
38,886,709
<p>I'm sending and recieving a packet with the module scapy.</p> <pre><code>a = sr(IP(src="192.168.1.100",dst="8.8.4.4")/UDP(sport=RandShort(),dport=53)/DNS(rd=1,qd=DNSQR(qname="google.com",qtype="ALL",qclass="IN"),ar=DNSRROPT(rclass=3000)),timeout=1) </code></pre> <p>If I display the packet size of of the command an...
3
2016-08-11T03:19:19Z
38,890,631
<p> When you are using the <code>.len</code> attribute of the packet, which, in your case, happen to be the value of the <code>len</code> field of the <code>IP</code> layer. It does not contain the <code>Ether</code> layer (14 bytes).</p> <p>You should use <code>len()</code> (as you do in your example) to get the pack...
1
2016-08-11T08:03:27Z
[ "python", "size", "packet", "scapy", "packet-sniffers" ]
Sequential Iterator
38,886,739
<p>I currently have the need for a certain type of Iterator / generator (not actually sure which is the appropriate term) that will generate a character sequence such as the following: </p> <p><br>axxx <br>bxxx <br>cxxx <br>dxxx <br>... <br>aaxx <br>abxx <br> and so on</p> <p>So for every iteration through the alphab...
2
2016-08-11T03:23:18Z
38,886,851
<p>OK, break this down into two problems. I'm cribbing from</p> <p><a href="http://code.activestate.com/recipes/65212-convert-from-decimal-to-any-base-number/" rel="nofollow">http://code.activestate.com/recipes/65212-convert-from-decimal-to-any-base-number/</a></p> <p>for the actual baseN code.</p> <p>First, generat...
0
2016-08-11T03:36:42Z
[ "python", "loops", "iteration", "generator" ]
Python and how to get specific text from HTML using Selenium
38,886,774
<p>I am trying to get a specific text content in html page by using Selenium webdriver class name. The HTML code are below:-</p> <pre><code>&lt;tr&gt; &lt;th&gt; &lt;td class="max-captured"&gt;174.26 kp/s&lt;/td&gt; &lt;td class="max-captured"&gt;0 p/s &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I want to capt...
-2
2016-08-11T03:27:45Z
38,900,735
<p>you can use css_selector</p> <pre><code>driver.find_element_by_css_selector('tr th .max_captured:nth-child(2)').text </code></pre>
0
2016-08-11T15:37:37Z
[ "python", "selenium", "selenium-webdriver" ]
Method to Return List of Instances Without Self
38,886,784
<p>I am frequently running an operation to determine a list of "live" instances of a class. To determine if an instance is live, it is testing against the is_live method of my current class -- please see below. </p> <pre><code>class Game(models.Model): def is_live(self): now = timezone.now() now.a...
1
2016-08-11T03:28:29Z
38,886,937
<p>Declare the class method as static using the <code>@staticmethod</code> decorator. You then don't need to pass <code>self</code> to the function. Rather than use <code>Game</code> directly within the function, why don't you pass the game objects as a parameter to the function. I've used a conditional list compreh...
0
2016-08-11T03:47:31Z
[ "python", "django", "methods", "instance" ]
Method to Return List of Instances Without Self
38,886,784
<p>I am frequently running an operation to determine a list of "live" instances of a class. To determine if an instance is live, it is testing against the is_live method of my current class -- please see below. </p> <pre><code>class Game(models.Model): def is_live(self): now = timezone.now() now.a...
1
2016-08-11T03:28:29Z
38,886,983
<p>In order to do this, you will need to keep track of all <code>Game</code> instances outside of the individual instances themselves. You can do this anywhere, but one option is to have a class-level list:</p> <pre><code>class Game(models.Model): all_game_instances = [] def __init__(self, *args, **kwargs): ...
0
2016-08-11T03:52:30Z
[ "python", "django", "methods", "instance" ]
How to assign a value to a property in django
38,886,788
<p>i have a new property in my model however I'd like to assign a test value in it for my test script. </p> <p>this is my code:</p> <p>models.py</p> <pre><code>mycode = models.UUIDField(null=True) @property def haveCode(self): if self.mycode == uuid.UUID('{00000000-0000-0000-0000-000000000000}'): return Fa...
0
2016-08-11T03:29:05Z
38,886,871
<p>You can 'mock' that property using the mock library</p> <pre><code>from mock import patch, PropertyMock @patch.object(Test, 'haveCode', new_callable=PropertyMock) def myTest(test_haveCode_mock): test_haveCode_mock.return_value = True checkTest = Test() assertEqual(checkTest.haveCode, True) patch.st...
1
2016-08-11T03:38:33Z
[ "python", "django" ]
problems with subprocess.call
38,887,000
<p>The blow command works well in the shell/terminal, but something goes wrong when it is called in my python script using subprocess.call() method.</p> <pre><code>-- command in shell/terminal $ th neural_style.lua -gpu 0 -style_image input/style.jpg -content_image input/img.jpg -- subprocess.call() in python script ...
-2
2016-08-11T03:53:50Z
38,887,254
<p>As the error message says, it failed to read an image. The error is (presumably) coming from the <code>th</code> program you're calling. I'd guess that there's additional information in the error message you haven't shared, but the most likely explanation is that you're running your Python script from a different di...
-1
2016-08-11T04:24:50Z
[ "python", "subprocess" ]
How do I change default text in a Qt lineEdit by entering data into the running frame in order to re-run functions with the new value?
38,887,007
<p>I am new to Python, and even more new to PyQt4. (I've created a similar GUI with wxPython, but I can't make this work.) I've spent hours trying to figure this out, and I've tried so many tips from searches here and elsewhere, including the instruction docs, that I'm dizzy.</p> <p>The window I created in Qt Designer...
0
2016-08-11T03:54:43Z
38,899,938
<p>Fabio's comment has the answer, but an option to accept it as answered didn't appear (maybe because it was a comment and not an answer??), so I'm "answering" to mark this as answered, but it was his response that is the answer, which I'll quote for simplicity, highlighting the key code: </p> <blockquote> <p>Not s...
0
2016-08-11T15:00:53Z
[ "python", "qt" ]
How to insert dictionary items into a PostgreSQL table
38,887,025
<p>So I've connected my Postgresql database into Python with Psycopg2, and I've pulled two specific columns to update. The first column I have used as the keys in a Python dictionary, and I have run some functions on the second one and use the results as the values in the dictionary. Now what I want to do is add those ...
2
2016-08-11T03:57:54Z
38,887,180
<p>You want an <code>UPDATE</code> statement something like the following:</p> <pre><code>import psycopg2 con = psycopg2.connect('your connection string') cur = connection.cursor() # add newcol cur.execute('ALTER TABLE your_table ADD COLUMN newcol text;') con.commit() for k,v in your_dict.iteritems(): cursor.exec...
0
2016-08-11T04:16:33Z
[ "python", "postgresql", "dictionary", "key-value", "psycopg2" ]
How to insert dictionary items into a PostgreSQL table
38,887,025
<p>So I've connected my Postgresql database into Python with Psycopg2, and I've pulled two specific columns to update. The first column I have used as the keys in a Python dictionary, and I have run some functions on the second one and use the results as the values in the dictionary. Now what I want to do is add those ...
2
2016-08-11T03:57:54Z
38,894,429
<p>Update all the rows in a single query. First turn the dictionary into a list of tuples:</p> <pre><code>l = [(k,v) for k,v in my_dict.items()] </code></pre> <p>A Python list of tuples is adapted to an array of records by Psycopg. Then <code>unnest</code> the array in the <code>from</code> clause:</p> <pre><code>qu...
0
2016-08-11T10:55:50Z
[ "python", "postgresql", "dictionary", "key-value", "psycopg2" ]
Troubleshooting Amazon's Alexa Skill Kit (ASK) Lambda interaction
38,887,061
<p>I'm starting with ASK development. I'm a little confused by some behavior and I would like to know how to debug errors from the "service simulator" console. How can I get more information on the <code>The remote endpoint could not be called, or the response it returned was invalid.</code> errors?</p> <p>Here's my s...
0
2016-08-11T04:02:31Z
38,895,935
<p>My guess would be that you missed a step on setup. There's one where you have to set the "event source". IF you don't do that, I think you get that message.</p> <p>But the debug options are limited. I wrote EchoSim (the original one on GitHub) before the service simulator was written and, although it is a bit out o...
0
2016-08-11T12:06:33Z
[ "python", "amazon-web-services", "amazon-dynamodb", "aws-lambda", "alexa-skills-kit" ]
Troubleshooting Amazon's Alexa Skill Kit (ASK) Lambda interaction
38,887,061
<p>I'm starting with ASK development. I'm a little confused by some behavior and I would like to know how to debug errors from the "service simulator" console. How can I get more information on the <code>The remote endpoint could not be called, or the response it returned was invalid.</code> errors?</p> <p>Here's my s...
0
2016-08-11T04:02:31Z
38,902,127
<p>tl;dr: <code>The remote endpoint could not be called, or the response it returned was invalid.</code> also means there may have been a timeout waiting for the endpoint. </p> <p>I was able to narrow it down to a timeout. Seems like the Alexa service simulator (and the Alexa itself) is less tolerant to long response...
0
2016-08-11T16:54:18Z
[ "python", "amazon-web-services", "amazon-dynamodb", "aws-lambda", "alexa-skills-kit" ]
Troubleshooting Amazon's Alexa Skill Kit (ASK) Lambda interaction
38,887,061
<p>I'm starting with ASK development. I'm a little confused by some behavior and I would like to know how to debug errors from the "service simulator" console. How can I get more information on the <code>The remote endpoint could not be called, or the response it returned was invalid.</code> errors?</p> <p>Here's my s...
0
2016-08-11T04:02:31Z
39,245,816
<p>I think the problem you having for ARN:1 is you probably didn't set a trigger to alexa skill in your lambda function.</p> <p>Or it can be the alexa session timeout which is by default set to 8 seconds.</p>
0
2016-08-31T09:31:25Z
[ "python", "amazon-web-services", "amazon-dynamodb", "aws-lambda", "alexa-skills-kit" ]
find a pattern in html and replace it with php code
38,887,079
<p>I am looking at finding this pattern </p> <pre><code>&lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt; &lt;/div&gt; &lt;div id="downloadlinks"&gt; &lt;!-- downloadli...
0
2016-08-11T04:04:49Z
38,887,184
<p>You can use <code>replace</code>.</p> <pre><code>html_files = ['a.html', ...] copyright = '&lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt;' new_copyright = """ &lt;?php $year = date("Y"); echo "&lt;p class='text-muted'&gt;© $year. Core Team&lt;/p&gt;"; ?&gt;""" for html_f...
2
2016-08-11T04:17:06Z
[ "php", "python", "bash", "sed" ]
find a pattern in html and replace it with php code
38,887,079
<p>I am looking at finding this pattern </p> <pre><code>&lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt; &lt;/div&gt; &lt;div id="downloadlinks"&gt; &lt;!-- downloadli...
0
2016-08-11T04:04:49Z
38,887,778
<p>sed is for simple substitutions on individual lines so your task is certainly not a job for sed. You could use awk if your files are all that well formatted:</p> <pre><code>$ cat old &lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p cl...
2
2016-08-11T05:19:06Z
[ "php", "python", "bash", "sed" ]
Filter a dataframe for a specific range of date in Pandas
38,887,118
<p>I have a dataframe say <code>df1</code> which has three fields that contain date type data. Call them <code>'Date 1', 'OC_Date', 'Date 2'</code>. I want to filter this dataframe to obtain another dataframe such that it gives me the rows where <code>'OC_Date'</code> is between <code>'Date 1'</code> and <code>'Date 2'...
1
2016-08-11T04:09:56Z
38,888,055
<p>You can first convert columns from strings <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> and then filter by dates with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>...
2
2016-08-11T05:40:39Z
[ "python", "python-2.7", "pandas" ]
error in labelled point object pyspark
38,887,157
<p>I am writing a function </p> <ol> <li>which takes a RDD as input</li> <li>splits the comma separated values</li> <li>then convert each row into labelled point object</li> <li><p>finally fetch the output as a dataframe</p> <pre><code>code: def parse_points(raw_rdd): cleaned_rdd = raw_rdd.map(lambda line: lin...
0
2016-08-11T04:13:46Z
38,887,635
<p>The reason you had no errors until you execute the action:</p> <pre><code> output.take(5) </code></pre> <p>Is due to the nature of spark, which is lazy. i.e. nothing was execute in spark until you execute the action "take(5)"</p> <p>You have a few issues in your code, and I think that you are failing due to extra...
0
2016-08-11T05:05:05Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
error in labelled point object pyspark
38,887,157
<p>I am writing a function </p> <ol> <li>which takes a RDD as input</li> <li>splits the comma separated values</li> <li>then convert each row into labelled point object</li> <li><p>finally fetch the output as a dataframe</p> <pre><code>code: def parse_points(raw_rdd): cleaned_rdd = raw_rdd.map(lambda line: lin...
0
2016-08-11T04:13:46Z
38,906,839
<p>Try:</p> <pre><code>&gt;&gt;&gt; raw_rdd.map(lambda line: line.split(",")) \ ... .map(lambda line:LabeledPoint(line[0], [float(x) for x in line[1:]]) </code></pre>
0
2016-08-11T22:06:10Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
incrementing an integer inside an array gives me TypeError: 'int' object is not iterable
38,887,208
<p>I have an array that looks like the following: ["string", int , [] ] but when I try to increment the int Python gives me an error. (by the way I am new to python so this might be a simple question)</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Here is my problematic part of the...
0
2016-08-11T04:18:32Z
38,887,451
<p>I checked your code you have problem at this statement:-</p> <pre><code>responseid_container[1] += 1 </code></pre> <p>convert this line to:- </p> <pre><code>responseid_container[0][1] += 1 </code></pre> <p>Check it carefully:-</p> <pre><code>responseid_container = [ 0 =&gt; [ ...
1
2016-08-11T04:48:41Z
[ "python", "arrays", "increment" ]
The returned value not defined
38,887,226
<p>I am creating a guessing game and I have created two functions. One to take the user input and the other to check whether the user input is correct.</p> <pre><code>def getGuess(maxNum): if maxNum == "10": count=0 guess = -1 guessnum = [ ] while guess &gt;10 or guess&lt;0: ...
1
2016-08-11T04:21:10Z
38,887,422
<p>First, you are returning two values. A <code>return</code> statement also acts as a <code>break</code>, so the second <code>return</code> will not be called. Also, you are not storing the returned value anywhere, so it just disappears. </p> <p>Here is your edited code:</p> <pre><code>def getGuess(maxNum): if m...
0
2016-08-11T04:45:19Z
[ "python", "python-3.x" ]
The returned value not defined
38,887,226
<p>I am creating a guessing game and I have created two functions. One to take the user input and the other to check whether the user input is correct.</p> <pre><code>def getGuess(maxNum): if maxNum == "10": count=0 guess = -1 guessnum = [ ] while guess &gt;10 or guess&lt;0: ...
1
2016-08-11T04:21:10Z
38,887,745
<p>You have a programming style I call "type and hope". <code>maxNum</code> seems to bounce between a number and a string indicating you haven't thought through your approach. Below is a rework where each routine tries do something obvious and useful without extra variables. (I've left off the initial <code>choice</...
0
2016-08-11T05:15:39Z
[ "python", "python-3.x" ]
Zip file automation with bash/git
38,887,388
<p>I have a directory like <code>/home/folder1/folder2/index.html</code></p> <p>In the end I have to give the files that have changes and zip it. So I have to create a folder name 2016/11/8 and the content is <code>home/folder1/folder2/css/style.css</code></p> <p>if says I changed the style. It's tedious but I couldn...
0
2016-08-11T04:41:42Z
38,887,478
<p>I assume that you want to get the files that have difference between 2 coimmitss, </p> <pre><code>git archive --format=zip HEAD `git diff --name-only &lt;SHA&gt; HEAD` &gt; difference.zip </code></pre> <p>Following will give you the difference between current and given SHA </p> <pre><code>git diff --name-only &lt...
1
2016-08-11T04:51:23Z
[ "python", "bash", "automation" ]