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
Applying strptime function to padas series
38,797,854
<p>I have a pandas DataSeries that contains a contains a string formatted date in the form of:</p> <p><code>2016-01-14 11:39:54</code></p> <p>I would like to convert the string to a timestamp.</p> <p>I am using the <code>apply</code> method to attemp to pass 'datetime.strptime' to each element of the series</p> <p>...
2
2016-08-05T21:15:20Z
38,797,881
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pd.to_datetime</code></a>:</p> <pre><code>date_series = pd.to_datetime(date_string) </code></pre> <p>In general it's best have your dates as Pandas' <code>pd.Timestamp</code> instead of Python's <code>d...
3
2016-08-05T21:18:00Z
[ "python", "pandas", "strptime" ]
django - factory_boy AttributeError: 'NoneType' object has no attribute '_meta'
38,797,868
<p>I'm writing unit tests for my <code>Django REST Framework</code> app and I'm creating my fake testing data using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow"><code>factory_boy</code></a>. I've come across the following error message when I try to run my tests</p> <pre><code>File "...
0
2016-08-05T21:16:27Z
38,800,936
<p>You need to add correct relations (<code>SubFactory</code>) in the factory definition first. </p> <p>Please read this part carefully:</p> <p><a href="http://factoryboy.readthedocs.io/en/latest/recipes.html#copying-fields-to-a-subfactory" rel="nofollow">http://factoryboy.readthedocs.io/en/latest/recipes.html#copyin...
0
2016-08-06T05:40:14Z
[ "python", "django", "django-rest-framework" ]
Concurrently parse in-memory xml tree with lxml
38,797,933
<p>Say I have a program that looks like this:</p> <pre><code>from lxml import etree class ParseXmlFile(object): def __init__(self, xml_to_parse): self.xml = etree.parse(xml_to_parse) def a(self): return self.xml.xpath('//something') def b(self): return self.xml.xpath('//something...
0
2016-08-05T21:21:50Z
38,797,995
<p>Functions are data, so you can do something like this:</p> <pre><code>from multiprocessing import Pool def f1(xml): print "applying f1 to xml" def f2(xml): print "applying f2 to xml" if __name__ == '__main__': xml = "the xml" def applyf(f): f(xml) p = Pool(5) print(p.map(applyf, [f1,...
1
2016-08-05T21:28:03Z
[ "python", "multithreading", "multiprocessing", "lxml" ]
get the amplitude data from an mp3 audio files using python
38,797,934
<p>I have an mp3 file and I want to basically plot the amplitude spectrum present in that audio sample. I know that we can do this very easily if we have a wav file. There are lot of python packages available for handling wav file format. However, I do not want to convert the file into wav format then store it and then...
0
2016-08-05T21:21:56Z
38,798,166
<p>MP3 is encoded wave (+ tags and other stuff). All you need to do is decode it using MP3 decoder. Decoder will give you whole audio data you need for further processing.</p> <p>How to decode mp3? I am shocked there are so few available tools for Python. Although I found a good one in <a href="http://stackoverflow.co...
0
2016-08-05T21:45:02Z
[ "python", "audio", "matplotlib", "mp3", "pyaudio" ]
Multiprocessing, what does pool.ready do?
38,797,938
<p>Suppose I have a pool with a few processes inside of a class that I use to do some processing, like this:</p> <pre><code>class MyClass: def __init_(self): self.pool = Pool(processes = NUM_PROCESSES) self.pop = [] self.finished = [] def gen_pop(self): self.pop = [ self.pool....
2
2016-08-05T21:22:22Z
38,798,333
<p>Multiprocessing uses <code>pickle</code> module internally to pass data between processes, so your data must be <em>picklable</em>. See <a href="https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled" rel="nofollow">the list of what is considered picklable</a>, object method is not in that ...
3
2016-08-05T22:02:34Z
[ "python", "multiprocessing", "pool" ]
Multiprocessing, what does pool.ready do?
38,797,938
<p>Suppose I have a pool with a few processes inside of a class that I use to do some processing, like this:</p> <pre><code>class MyClass: def __init_(self): self.pool = Pool(processes = NUM_PROCESSES) self.pop = [] self.finished = [] def gen_pop(self): self.pop = [ self.pool....
2
2016-08-05T21:22:22Z
38,799,262
<p>To answer the question you asked, <code>.ready()</code> is really telling you whether <code>.get()</code> <em>may</em> block: if <code>.ready()</code> returns <code>True</code>, <code>.get()</code> will <em>not</em> block, but if <code>.ready()</code> returns <code>False</code>, <code>.get()</code> <em>may</em> blo...
2
2016-08-06T00:00:57Z
[ "python", "multiprocessing", "pool" ]
Creating pairs of objects in a list
38,797,998
<p>I have a list of objects:</p> <pre><code>object_list = ['distance', 'alpha1', 'alpha2', 'gamma'] </code></pre> <p>I want to obtain a new list with a pair combination of those objects, such as:</p> <pre><code>new_list = [ ['distance', 'alpha1'], ['distance', 'alpha2'], ['distance', 'gamma'],['alpha1', 'alpha2'], [...
0
2016-08-05T21:28:21Z
38,798,051
<p>Have a look at <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow">itertools</a> - <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a> seems to be the thing you are looking for. use like</p> <pre><code>import itertools obj...
0
2016-08-05T21:34:03Z
[ "python" ]
Creating pairs of objects in a list
38,797,998
<p>I have a list of objects:</p> <pre><code>object_list = ['distance', 'alpha1', 'alpha2', 'gamma'] </code></pre> <p>I want to obtain a new list with a pair combination of those objects, such as:</p> <pre><code>new_list = [ ['distance', 'alpha1'], ['distance', 'alpha2'], ['distance', 'gamma'],['alpha1', 'alpha2'], [...
0
2016-08-05T21:28:21Z
38,798,085
<p><a href="https://docs.python.org/dev/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a> if order isn't important or <a href="https://docs.python.org/dev/library/itertools.html#itertools.permutations" rel="nofollow">itertools.permutations</a> if order matters</p> <h2>itertools.c...
1
2016-08-05T21:37:51Z
[ "python" ]
translate Growing Recursion to Iteration?
38,798,004
<p>I am writing a program for a process in Minecraft, it's supposed to edit the world and "clean it up" by replacing the blocks you can't see.</p> <p>So the situation is a 3D world of cubic blocks. The program needs to identify a body of air and propagate in all directions from each block to see if there's more air to...
0
2016-08-05T21:28:52Z
38,798,534
<p>You could use data structures such as stacks to pass from recursive algorithms to iterative algorithms:</p> <pre><code>Stack&lt;Object&gt; stack; stack.push(first_object); while( !stack.isEmpty() ) { // Do something my_object = stack.pop(); // Push other objects on the stack. } </code></pre>
0
2016-08-05T22:26:33Z
[ "java", "python", "recursion" ]
Fast query in formatted data
38,798,033
<p>In my program I need to query through metadata.</p> <p>I read data into <code>numpy</code> record array <code>A</code> from csv-like text file ** without duplicate rows**.</p> <pre><code>var1|var2|var3|var4|var5|var6 'a1'|'b1'|'c1'|1.2|2.2|3.4 'a1'|'b1'|'c4'|3.2|6.2|3.2 'a2'|''|'c1'|1.4|5.7|3.8 'a2'|'b1'|'c2'|1.2|...
2
2016-08-05T21:31:51Z
38,799,154
<p>Use <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a>, it is built for tasks like this:</p> <pre><code># Import import pandas as pd # Read CSV df = pd.read_csv('/path/to/file.csv') # Selection criteria # using `.query` method: df.query('var1 == "a2" &amp; var3 == "c1"') df.query('var2 == "b1" &amp; 1 ...
0
2016-08-05T23:42:17Z
[ "python", "database", "numpy", "indexing", "mapping" ]
Fast query in formatted data
38,798,033
<p>In my program I need to query through metadata.</p> <p>I read data into <code>numpy</code> record array <code>A</code> from csv-like text file ** without duplicate rows**.</p> <pre><code>var1|var2|var3|var4|var5|var6 'a1'|'b1'|'c1'|1.2|2.2|3.4 'a1'|'b1'|'c4'|3.2|6.2|3.2 'a2'|''|'c1'|1.4|5.7|3.8 'a2'|'b1'|'c2'|1.2|...
2
2016-08-05T21:31:51Z
38,808,983
<p>With your file sample ('b' for py3)</p> <pre><code>In [51]: txt=b"""var1|var2|var3|var4|var5|var6 ...: 'a1'|'b1'|'c1'|1.2|2.2|3.4 ...: 'a1'|'b1'|'c4'|3.2|6.2|3.2 ...: 'a2'|''|'c1'|1.4|5.7|3.8 ...: 'a2'|'b1'|'c2'|1.2|2.2|3.4 ...: 'a3'|''|'c2'|1.2|2.2|3.4 ...: 'a1'|'b2'|'c4'|7.2|6.2|3.2""" </c...
0
2016-08-06T21:45:17Z
[ "python", "database", "numpy", "indexing", "mapping" ]
drop first and last row from within each group
38,798,058
<p>This is a follow up question to <a href="http://stackoverflow.com/q/38797271/2336654">get first and last values in a groupby</a></p> <p>How do I drop first and last rows within each group?</p> <p>I have this <code>df</code></p> <pre><code>df = pd.DataFrame(np.arange(20).reshape(10, -1), [['a', '...
3
2016-08-05T21:34:37Z
38,798,076
<p>I'd apply a similar technique to what I did for the other question:</p> <pre><code>def first_last(df): return df.ix[1:-1] df.groupby(level=0, group_keys=False).apply(first_last) </code></pre> <p><a href="http://i.stack.imgur.com/AJZLH.png" rel="nofollow"><img src="http://i.stack.imgur.com/AJZLH.png" alt="ente...
3
2016-08-05T21:36:45Z
[ "python", "pandas", "group-by" ]
Rasterising a TTF font
38,798,080
<p>I'm on the Raspberry Pi with a screen attached.</p> <p>Rather than using X, I'm writing pixel data directly to the frame buffer. I've been able to draw images and primitive shapes, blend, use double buffering, etc...</p> <p>Where I'm hitting a problem is drawing text. The screen is just a byte array from this leve...
0
2016-08-05T21:37:09Z
38,798,177
<p>Consider using the <a href="https://cairographics.org/" rel="nofollow">Cairo</a> graphics library, either for all your graphics, or as a tool to generate the font atlases. Cairo has extensive support for rendering fonts using TTF fonts, as well as for other useful graphics operations.</p> <p>At a lower level, you c...
0
2016-08-05T21:46:15Z
[ "python", "python-3.x", "fonts", "true-type-fonts", "rasterizing" ]
Python/Pandas - creating new variable based on several variables and if/elif/else function
38,798,115
<p>I am trying to create a new variable that is conditional based on values from several other values. I'm writing here because I've tried writing this as a nested ifelse() statement in R, but it had too many nested ifelse's so it threw an error, and I think there should be an easier way to sort this out in Python. </p...
3
2016-08-05T21:40:20Z
38,798,255
<h3>Setup</h3> <pre><code>df = pd.DataFrame([[0, 0, 0, 0, 1, 1, 1, 240], [0, 0, 0, 0, 0, 0, 0, 218], [0, 0, 0, 0, 1, 1, 1, 236], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 206]], pd.Index(range(1, 6), name='ID'), ...
3
2016-08-05T21:54:42Z
[ "python", "pandas", "numpy" ]
Python/Pandas - creating new variable based on several variables and if/elif/else function
38,798,115
<p>I am trying to create a new variable that is conditional based on values from several other values. I'm writing here because I've tried writing this as a nested ifelse() statement in R, but it had too many nested ifelse's so it threw an error, and I think there should be an easier way to sort this out in Python. </p...
3
2016-08-05T21:40:20Z
38,798,340
<p>Without getting into streamlining your logic (which @piRSquared gets into): you can apply your <code>test_func</code> to the rows by issuing <code>.apply(test_func, axis=1)</code> to your dataframe.</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ ID Sept_2015 Oct_2015 Nov_2015 Dec_2015 ...
2
2016-08-05T22:03:15Z
[ "python", "pandas", "numpy" ]
Python packet sniffer using ctypes crashes when copying socket buffer
38,798,135
<p>I'm trying to capture the first 20 bytes (full packet minus the options) of an IP packet, populate a <code>struct</code> of <code>ctype</code> members, and print the information I want to the screen (protocol, source and destination address). My IP class is as follows:</p> <pre><code>import socket import os import...
0
2016-08-05T21:42:26Z
38,801,790
<p>The size of <code>IP</code> should be verified, i.e.</p> <pre><code>print(sizeof(IP)) </code></pre> <p>should return 20 bytes. Since <code>ctypes.u_long</code> is 8 in case of 64bit linux, the size will be 32 bytes (4 bytes extra due to padding, 8 bytes due to integer sizes). Either use <code>ctypes.u_int</code> o...
1
2016-08-06T07:39:32Z
[ "python", "sockets", "buffer", "ctypes", "packet-sniffers" ]
iPython- Is there a way to answer "y" to (or ignore) all y/n prompts?
38,798,181
<p>So I have an ipython notebook that has a lot of large variables, and at one point I want to get rid of all the ones I'm done with. I'm using %reset_selective variablename to clear each one, but there's 60 of these variables and when I run the block that has all 60 prompts, it asks me to enter y/n for every clear.</p...
2
2016-08-05T21:46:45Z
38,798,497
<p>Reading from <a href="https://ipython.org/ipython-doc/2/api/generated/IPython.core.magics.namespace.html#IPython.core.magics.namespace.NamespaceMagics.reset_selective" rel="nofollow">here</a>:</p> <blockquote> <p>%reset_selective [-f] regex</p> <p>No action is taken if regex is not included</p> <p>Optio...
3
2016-08-05T22:21:29Z
[ "python", "ipython", "command-prompt", "jupyter-notebook" ]
How to do Python , PostgreSQL integration?
38,798,238
<p>I want to call PostgreSQL queries and return results for python APIs? Basically , do a python and PostgreSQL integration/Connectivity. So, for specific Python API /calls want to execute the queries n return result.</p> <p>Also, want to achieve abstraction of PostgreSQL DB.</p> <p>Thanks.</p>
-3
2016-08-05T21:53:10Z
38,798,357
<p>To add to klin's comment:</p> <p><a href="https://pypi.python.org/pypi/psycopg2" rel="nofollow">psycopg2</a> - This is the most popular psql adapter for python. It was build to address heavy concurrency issues with psql database usage. Several extensions are available for added functionality with the DB API.</p> ...
0
2016-08-05T22:05:03Z
[ "python", "postgresql" ]
Is python smart enough to replace function calls with constant result?
38,798,244
<p>Coming from the beautiful world of <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>, I am trying understand this behavior:</p> <pre><code>In [1]: dataset = sqlContext.read.parquet('indir') In [2]: sizes = dataset.mapPartitions(lambda x: [len(list(x))]).collect...
6
2016-08-05T21:53:43Z
38,798,786
<p>I'm by no means an expert on the inner workings of python, but from my understanding thus far you'd like to compare the speed of</p> <pre><code>for item in sizes: if(item == min(sizes)): count = count + 1 </code></pre> <p>and</p> <pre><code>min_item = min(sizes) for item in sizes: if(item == min_i...
5
2016-08-05T22:55:51Z
[ "python", "c", "performance", "optimization", "apache-spark" ]
Django Rest Framework does not decode JSON fields in Multipart requests like it does with standard POST requests
38,798,251
<p>When I'm submitting a POST request with a <code>Content-Type</code> of <code>application/json</code>, my data at the server is decoded into native Python as it should - JSON objects are presented as dicts, arrays as arrays etc. That's great.<br> However, when I'm doing a MultiPart post request to my API, which of co...
0
2016-08-05T21:54:09Z
38,808,608
<p>I created a new Parser object to deal with this scenario of MultiPart file upload with fields containing JSON. Code is below if anyone ever needs it. </p> <pre><code>import json from rest_framework.parsers import BaseParser, DataAndFiles from django.conf import settings from django.http.multipartparser import Multi...
0
2016-08-06T20:54:00Z
[ "python", "json", "django", "django-rest-framework" ]
python multiprocessing.Array: huge temporary memory overhead
38,798,330
<p>If I use python's multiprocessing.Array to create a 1G shared array, I find that the python process uses around 30G of memory during the call to multiprocessing.Array and then decreases memory usage after that. I'd appreciate any help to figure out why this is happening and to work around it. </p> <p>Here is code t...
1
2016-08-05T22:02:13Z
38,798,376
<p>From the format of your print statements, you are using python 2</p> <p>Replace <code>range(n)</code> by <code>xrange(n)</code> to save some memory.</p> <pre><code>data=multiprocessing.Array(ctypes.c_ubyte,xrange(n)) </code></pre> <p>(or use python 3)</p> <p>1 billion range takes roughly 8GB (well I just tried t...
3
2016-08-05T22:06:54Z
[ "python", "arrays", "memory", "multiprocessing", "overhead" ]
python multiprocessing.Array: huge temporary memory overhead
38,798,330
<p>If I use python's multiprocessing.Array to create a 1G shared array, I find that the python process uses around 30G of memory during the call to multiprocessing.Array and then decreases memory usage after that. I'd appreciate any help to figure out why this is happening and to work around it. </p> <p>Here is code t...
1
2016-08-05T22:02:13Z
38,809,592
<p>Unfortunately, the problem is not so much with the range, as I just put that in as a simple illustration. In reality, that data will be read from disk. I could also use n*["a"] and specify c_char in multiprocessing.Array as another example. That still uses around 16G when I'm only have 1G of data in the list I'm pas...
1
2016-08-06T23:28:10Z
[ "python", "arrays", "memory", "multiprocessing", "overhead" ]
Unable to replace python string using the Template module
38,798,351
<p>I am trying to replace the following using the python Template module.</p> <p><code>start_date BETWEEN DATEADD(days,-14,'${DATE_YYYY-MM-DD}') AND '${DATE_YYYY-MM-DD}'</code></p> <p>I am using the ConfigParser to read the values and store it into a dictionary(config_params) which i am successfully able to do. Then ...
0
2016-08-05T22:04:33Z
38,799,116
<p>According to <a href="https://docs.python.org/3.4/library/string.html#template-strings" rel="nofollow">the doc</a>, the default pattern that identifiers should follow is: <code>[_a-z][_a-z0-9]*</code>. Using <code>substitute</code> instead of <code>safe_substitute</code> warns about this.</p> <p>However, you can fi...
1
2016-08-05T23:37:16Z
[ "python" ]
Call xcopy with parameters?
38,798,404
<p>I'm trying to call <code>xcopy</code> with <code>subprocess</code> which will be equal to bat command.</p> <p>Every time I get errors: "invalid number of parameters" or "file not found".</p> <p>How can I do this?</p> <p><strong>PYTHON</strong></p> <pre><code>subprocess.call([ "xcopy", str(C...
1
2016-08-05T22:09:23Z
38,798,528
<p>Can you do something similar to this, by using sys and env cmds instead?:-</p> <pre><code>import sys,os PATHTOFILE1="Some_path" PATHTOFILE2="some other path" os.environ['PATHTOFILE1'] = PATHTOFILE1 os.environ['PATHTOFILE2'] = PATHTOFILE2 os.system('xcopy "$PATHTOFILE1" "$PATHTOFILE2" /s /y /q &gt;nul') </code></pre...
0
2016-08-05T22:25:39Z
[ "python", "windows", "xcopy" ]
How do I make a primary key without auto-increment?
38,798,411
<p>I've been trying to create a model that has a primary key, but I don't want that primary key to auto increment.</p> <p>I know I can specify the value each time, but I want the field to be required that I specify it (hopefully enforced by the database and django), and fail fast if I forget.</p> <p>It seemed logical...
1
2016-08-05T22:10:40Z
38,798,432
<p>Just create <code>id</code> field with <code>primary_key=True</code> explicitly in your model:</p> <pre><code>class SomeModel(models.Model): id = models.IntegerField(primary_key=True) </code></pre> <p>That way it won't be auto-incremented, but it will still be an primary key.</p>
3
2016-08-05T22:13:29Z
[ "python", "django", "auto-increment" ]
Machine Learning - Stratified K-Fold CV
38,798,415
<p>I've unbalanced binary classifier data and want to Stratified K-Fold CV. I'm getting the below error:</p> <pre><code>data = DataFrame(df,columns=names) train,test = cross_validation.train_test_split(df,test_size=0.20) train_data,test_data = pd.DataFrame(train,columns=names),pd.DataFrame(test,columns=names) y = test...
0
2016-08-05T22:11:24Z
38,809,881
<p>You are not passing valid <strong>labels</strong>, in fact in your code labels and data is the same thing:</p> <pre><code>train_text = train.iloc[train_indices] train_y = train.iloc[train_indices] </code></pre> <p>while probably you wanted something among the lines of</p> <pre><code>train_y = y[train_indices] </c...
0
2016-08-07T00:37:12Z
[ "python", "machine-learning" ]
Hex to signed Decimal
38,798,427
<p>If I have a log file named log1 with hex values in the format below: </p> <pre><code>D8 D4 D4 D2 D6 D4 D4 D2 D6 D4 D4 D2 D6 D4 D4 D1 ...............etc </code></pre> <p>how can i convert this values to signed decimal ( see format below) and then save them to another file named log2?</p...
0
2016-08-05T22:12:46Z
38,798,520
<p>Assuming those are two's complement bytes:</p> <pre><code>return value - 256 if value &gt; 127 else value </code></pre>
0
2016-08-05T22:24:05Z
[ "python", "python-2.7" ]
Do I need install appium client in python virtualenv for deployment in Amazon Device Farm (ADF)?
38,798,526
<p>Instructions at <a href="http://docs.aws.amazon.com/es_es/devicefarm/latest/developerguide/test-types-android-appium-python.html" rel="nofollow">http://docs.aws.amazon.com/es_es/devicefarm/latest/developerguide/test-types-android-appium-python.html</a> does not tell anything about adding appium (appium wheel) into t...
0
2016-08-05T22:25:13Z
38,959,105
<p>I work for the AWS Device Farm team.</p> <p>Short Answer to main question in subject line: Yes</p> <p><strong>Explanation:</strong></p> <p><strong>Python virtualenv usage</strong></p> <p>The confusion seems to around that the virtual environment is needed "just" for packaging. Our recommendation is to actually m...
0
2016-08-15T16:33:23Z
[ "python", "amazon-web-services", "python-appium" ]
Can VirtualEnv create symlinks in the current directory?
38,798,568
<p>I'm trying to use VirtualEnv more and more, and I'm coming across a few projects that invoke python via something like <code>popen()</code>, and for whatever reason the scripts aren't finding the site packages correctly.</p> <p>For such projects, symlinking the site package in a similar manner as</p> <pre><code>ln...
0
2016-08-05T22:30:56Z
38,801,779
<p>I am not 100% sure that I am answering your exact question, because it is not explicit about what type of packages. However, having been working in VirtualEnv all week, I have had to use a number of modules that live elsewhere (for me in anaconda), so I will give it a go.</p> <p>What I have been doing is, when I cr...
0
2016-08-06T07:38:18Z
[ "python", "virtualenv" ]
Need to get timed input to break out of loop
38,798,645
<p>I have a loop that times user input, when the loop is done I want to break out of it:</p> <pre><code>import sys import time import msvcrt from random import randint import random def time_input(caption, timeout=3): start_time = time.time() sys.stdout.write('%s: ' % (caption)) input = '' while True:...
0
2016-08-05T22:38:14Z
38,798,722
<p>Use <code>return</code> to escape the <code>battle</code>-function. My guess is right here</p> <pre><code>if animal_health &lt;= 0: win_battle(animal, weapon) return &lt;------------------------------ </code></pre> <p>Maybe you want to return your current hp if the battle was successful? This should ...
0
2016-08-05T22:47:10Z
[ "python", "loops", "timeout" ]
web2py form with list:reference not working with {{=form}}
38,798,741
<p>Using web2py, I am having trouble submitting (?) a form based on a table using list:reference. I have a table <em>db.game</em> that references to <em>db.game_events</em> in one of its columns called <em>game_event</em>.</p> <p>The form for <em>db.game</em> is accepted, but when I try to reach the data in the column...
0
2016-08-05T22:50:06Z
38,804,216
<p>When you define a <code>reference</code> or <code>list:reference</code> field, if you don't specify the <code>requires</code> attribute within the call to <code>Field()</code>, you will get a default <code>requires</code> attribute (i.e., validator) as well as a default <code>represent</code> attribute that controls...
0
2016-08-06T12:16:35Z
[ "python", "forms", "web2py", "foreign-key-relationship", "web2py-modules" ]
Issue with split function
38,798,763
<p>I have a list variable <code>name</code>:</p> <pre><code>name = ['Ny-site-1-145237890-service'] </code></pre> <p>I want to split this list in a way so I can get <code>name = ['Ny-site-1']</code>. To do this I am using the below code:</p> <pre><code>import re name = ['Ny-site-1-145237890-service'] site_name = re.s...
0
2016-08-05T22:52:39Z
38,798,783
<p>First of all, <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a> requires <em>2 arguments</em>, you are providing a single one.</p> <p>Also, you need to add <code>+</code> quantifier (means "1 or more") for the <code>[0-9]</code> set of characters:</p> <pre><cod...
2
2016-08-05T22:55:31Z
[ "python" ]
Issue with split function
38,798,763
<p>I have a list variable <code>name</code>:</p> <pre><code>name = ['Ny-site-1-145237890-service'] </code></pre> <p>I want to split this list in a way so I can get <code>name = ['Ny-site-1']</code>. To do this I am using the below code:</p> <pre><code>import re name = ['Ny-site-1-145237890-service'] site_name = re.s...
0
2016-08-05T22:52:39Z
38,798,785
<p>Try adding a <code>+</code> in your regex to match multiple numbers.</p> <pre><code>name = 'Ny-site-1-145237890-service' site_name = re.split('(-[0-9]+-service)', name)[0] </code></pre> <p>If you want to use an array to store your name(s), you can use</p> <pre><code>name = ['Ny-site-1-145237890-service'] site_nam...
0
2016-08-05T22:55:33Z
[ "python" ]
Pyspark command not recognised
38,798,816
<p>I have anaconda installed and also I have downloaded Spark 1.6.2. I am using the following instructions from this answer to configure spark for Jupyter <a href="http://stackoverflow.com/questions/33064031/link-spark-with-ipython-notebook">enter link description here</a></p> <p>I have downloaded and unzipped the spa...
1
2016-08-05T22:58:37Z
38,827,548
<p>1- You need to set <code>JAVA_HOME</code> and spark paths for the shell to find them. After setting them in your <code>.profile</code> you may want to</p> <pre><code>source ~/.profile </code></pre> <p>to activate the setting in the current session. From your comment I can see you're already having the <code>JAVA_H...
2
2016-08-08T11:02:34Z
[ "python", "apache-spark", "pyspark" ]
Pyspark command not recognised
38,798,816
<p>I have anaconda installed and also I have downloaded Spark 1.6.2. I am using the following instructions from this answer to configure spark for Jupyter <a href="http://stackoverflow.com/questions/33064031/link-spark-with-ipython-notebook">enter link description here</a></p> <p>I have downloaded and unzipped the spa...
1
2016-08-05T22:58:37Z
39,070,669
<p>Here's my environment vars, hope it will help you:</p> <pre><code># path to JAVA_HOME export JAVA_HOME=$(/usr/libexec/java_home) #Spark export SPARK_HOME="/usr/local/spark" #version 1.6 export PATH=$PATH:$SPARK_HOME/bin export PYSPARK_SUBMIT_ARGS="--master local[2]" export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPAT...
0
2016-08-22T02:37:13Z
[ "python", "apache-spark", "pyspark" ]
parallel program in python using Threads
38,798,910
<p>Generating the sum from adding integer numbers successively up to n where n = 2000 given by the following formula: n(n+1)/2 so far i have don it in serial.I need help on how to make it compute in parallel such that it adaptively make use of all the available processors/cores on the host computer.</p> <pre><code>...
0
2016-08-05T23:11:52Z
38,799,424
<p>To do this, you need to use <code>multiprocessing</code>, which lets you create processes and assign procedures to them. Here's a code snippet that does part of what you want:</p> <pre><code>#!/usr/bin/env python3 from datetime import datetime MAX_NUM = 10000000 NUMPROCS = 1 # LINEAR VERSION start_time = datetim...
0
2016-08-06T00:30:50Z
[ "python" ]
Write Nested Dictionary to CSV
38,798,987
<p>I am trying to write a nested dictionary to CSV in Python. I looked at the csv.DictWriter documentation on python.org and some of the examples here on stackoverflow but I can't figure out the last part. Here is a representative data set: </p> <pre><code>data = {u'feeds': [{u'feed_code': u'free', u'feed_name': u'F...
1
2016-08-05T23:20:48Z
38,799,131
<p>The problem in your code is the loop. You want to loop over all the feeds, but you were actually looping over the data. Your for:</p> <pre><code>for item in data: print item w.writerow({field: data[item]}) ## Part I am stuck on </code></pre> <p>This would give you</p> <pre><code>feeds code </code></pre> ...
0
2016-08-05T23:39:14Z
[ "python", "csv", "dictionary" ]
Write Nested Dictionary to CSV
38,798,987
<p>I am trying to write a nested dictionary to CSV in Python. I looked at the csv.DictWriter documentation on python.org and some of the examples here on stackoverflow but I can't figure out the last part. Here is a representative data set: </p> <pre><code>data = {u'feeds': [{u'feed_code': u'free', u'feed_name': u'F...
1
2016-08-05T23:20:48Z
38,799,941
<p>This tricky part about what you want to do is that the dictionaries in the list of <code>u'feeds'</code> in your data structure do not have the <code>u'code'</code> value in each of them. This can be easily remedied by updating each of them which will allow you to write all of them out at one time (although it does ...
0
2016-08-06T02:06:14Z
[ "python", "csv", "dictionary" ]
Executing Terminal Command from Python (cURL)
38,799,007
<p>I know this has been asked before, but I'm not finding the answer I'm looking for. Here's what I'm trying to do.. and before you respond, <em>full disclosure</em>: this is my first python script.</p> <p><strong>Big picture:</strong> Concatenate 2 text strings with clipboard text, and run this concatenated string ...
0
2016-08-05T23:22:38Z
38,799,032
<p>use the python requests library</p> <pre><code>import requests x = requests.post('http://something', json={}) </code></pre> <p><a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a></p>
0
2016-08-05T23:25:18Z
[ "python", "osx", "curl" ]
utf-8 encoding and getting a string slice
38,799,045
<p>I'm parsing a twitter and there's a need to encode the text since in case there is no encoding, there is an exception. But when I use 'utf-8' it doesn't only add b symbol to the console output, but also makes it impossible to access parts of the string. What can I do to fix it or what other encoding should I try?</p...
0
2016-08-05T23:27:44Z
38,799,101
<p>you are confused about when to <code>encode</code> and when to <code>decode</code></p> <p>if you have a bytestring then you <code>decode</code> it into unicode</p> <pre><code>a="a string" b = a.decode('utf8') #b is now UNICODE </code></pre> <p>if you have unicode you <code>encode</code> it to an encoded bytestr...
1
2016-08-05T23:35:14Z
[ "python", "encoding", "utf-8", "beautifulsoup" ]
In pygame/python, is there a way to detect which key are pressed earlier or latter?
38,799,175
<p>For example, if I hold down w then hold down a, is there a way for pygame to tell me which key i holded down first? </p> <p>I need to know this because for the game im trying to make using pygame, the character doesnt have smooth movements. The example code of movement is below.</p> <p>I first detect the and set t...
0
2016-08-05T23:46:31Z
38,799,498
<p>If you loop through the event loop you'll receive the events in the order they were created. What you then could do is create a list that queues the keys you press and removes them when you release them. The first element in the list will always be the first key you've pressed and not yet released. </p> <pre><code>...
1
2016-08-06T00:44:09Z
[ "python", "pygame" ]
Why are my manual PCA reconstructions not matching python's sklearn's reconstructions?
38,799,205
<p>I was trying to check my implementation of PCA to see if I understood it and I tried to do PCA with 12 components on the MNIST data set (which I got using the tensorflow interface that normalized it for me). I obtained the principal components given by sklearn and then made reconstructions as follow:</p> <pre><code...
3
2016-08-05T23:50:51Z
38,805,942
<p>I see a couple of issues:</p> <ol> <li><p>The dot product should be <code>X_pca.dot(pca.components_)</code>. <code>PCA</code> factorizes your <code>X_train</code> matrix using SVD:</p> <p><em>X<sub>train</sub> = U·S·Vᵀ</em>.</p> <p>Here, <code>pca.components_</code> corresponds to <em>Vᵀ</em> (a <code>(k, n...
0
2016-08-06T15:38:27Z
[ "python", "machine-learning", "scipy", "scikit-learn", "pca" ]
Python for loop appending to every key in dictionary
38,799,212
<p>I'm iterating over a list of tuples and a list of strings. The strings are identifiers for the items in the list. I have a dictionary that has the strings identifiers as keys and has an initially empty list for each value. I want to append something from the tuple list to each key. A simplified version of what I'm d...
3
2016-08-05T23:52:17Z
38,799,301
<p>The problem is that when you call <code>dict.fromkeys</code> and pass it a list as a default item for each key, python uses the same list, lists are not immutable so one change to a list affects it everywhere it is referenced, what you can do to get around this is to call <code>dict.fromkeys</code> without any argum...
2
2016-08-06T00:07:49Z
[ "python", "list", "dictionary", "iteration" ]
Python for loop appending to every key in dictionary
38,799,212
<p>I'm iterating over a list of tuples and a list of strings. The strings are identifiers for the items in the list. I have a dictionary that has the strings identifiers as keys and has an initially empty list for each value. I want to append something from the tuple list to each key. A simplified version of what I'm d...
3
2016-08-05T23:52:17Z
38,799,314
<p>Your problem is that you share the list between the two keys by reference.</p> <p>What happens is that <code>dict.fromkeys</code> doesn't create a new list for each key, but gives the reference to the same list to all the keys. the rest of your code looks correct :)</p> <p>Instead of doing that you should use a <a...
4
2016-08-06T00:09:18Z
[ "python", "list", "dictionary", "iteration" ]
Parse string to identify kwargs and args
38,799,223
<p>I am new to python and looking for a elegant way to do the below job.</p> <p>I have a string say:</p> <pre><code>s = u'(鞋子="AAA", last = "BBB", abcd)' </code></pre> <p>I am thinking of a function which can parse the above string and give output in the following format.</p> <pre><code>arg, kwarg = foo(s) def...
-3
2016-08-05T23:54:01Z
38,799,275
<pre><code>def foo(s): data={"kwargs":[],"args":[]} for item in s: if "=" in item: data['kwargs'].append(item) else: data['args'].append(item) return data s = u'(鞋子="AAA", last = "BBB", abcd)' s = s[1:-1] # get rid of the parenthesis print foo(s) </code></pre>
0
2016-08-06T00:02:56Z
[ "python", "string", "parsing" ]
Parse string to identify kwargs and args
38,799,223
<p>I am new to python and looking for a elegant way to do the below job.</p> <p>I have a string say:</p> <pre><code>s = u'(鞋子="AAA", last = "BBB", abcd)' </code></pre> <p>I am thinking of a function which can parse the above string and give output in the following format.</p> <pre><code>arg, kwarg = foo(s) def...
-3
2016-08-05T23:54:01Z
38,799,618
<p>A nice way to parse a string that follows some grammar rules is the 3rd party <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> library. This is very generic lacking a formal grammar definition of allowed user input:</p> <pre><code>#coding:utf8 from pyparsing import * # Names for symbols _lp...
2
2016-08-06T01:04:31Z
[ "python", "string", "parsing" ]
Change default Django REST Framework home page title
38,799,315
<p>I am following the <a href="http://www.django-rest-framework.org/tutorial/quickstart/" rel="nofollow">article</a> to set up a new Djangon REST framework project. I got it working but I would like to change the default home page title from <code>Django REST Framework v3.3.2 to</code> my own, I am sure it's just a set...
0
2016-08-06T00:09:25Z
38,799,809
<p>From <a href="https://github.com/tomchristie/django-rest-framework/blob/3.3.2/rest_framework/templates/rest_framework/base.html#L38" rel="nofollow">the code</a>, it looks like it's actually not a setting. You'll need to override the 'branding' block in the base template with your own content.</p> <p>Basically you w...
2
2016-08-06T01:40:44Z
[ "python", "django", "django-rest-framework" ]
buffering of process output causing truncation?
38,799,347
<p>I have a sample file with 100 lines which I am reading using subprocess with <code>cat</code>. However, the output in a queue is always truncated. I suspect it might be due to <code>cat</code> buffering its output because it detects a pipe.</p> <pre><code>p = subprocess.Popen("cat file.txt", st...
0
2016-08-06T00:16:01Z
38,799,637
<p>I'm sure your main thread is exiting the try block before all of the output from <code>cat</code> has been read and placed on the queue.</p> <p>Note that <code>cat</code> can exit even if you haven't read all of its output. Consider this sequence of events:</p> <ol> <li><code>cat</code> writes out its last line</l...
1
2016-08-06T01:06:42Z
[ "python", "multithreading", "multiprocessing", "cat" ]
Printing indices within two dimensional array relative to specific array coordinates?
38,799,430
<p>Let's say I have an array consisting of multiple lists of <code>.</code>'s, that represent something like a world map. <code>world_array = [['.' * 50 for _ in xrange(50)]</code> </p> <p>Inside of this array, at index <code>(0, 0)</code>, a player variable exists -- a letter <code>p</code>. </p> <p>How can I go ab...
0
2016-08-06T00:31:59Z
38,799,505
<p>Break down your problem. Take a 2D array <code>array[x][y]</code>. If you're wanting to display the tiles up to 5 positions around the player then you must iterate over and print all of those tiles. So, starting from 5 before the player's position and ending 5 afterwards. Logically, it would go as follows (x is firs...
0
2016-08-06T00:45:12Z
[ "python", "arrays" ]
Printing indices within two dimensional array relative to specific array coordinates?
38,799,430
<p>Let's say I have an array consisting of multiple lists of <code>.</code>'s, that represent something like a world map. <code>world_array = [['.' * 50 for _ in xrange(50)]</code> </p> <p>Inside of this array, at index <code>(0, 0)</code>, a player variable exists -- a letter <code>p</code>. </p> <p>How can I go ab...
0
2016-08-06T00:31:59Z
38,799,626
<p>First, be careful if you want to modify your map, you should not use strings for the rows because they're immutable. You won't be able to modify your map - unles you rewrite entirely each line.</p> <p>So I suggest you use this: (A 2D array of chars)</p> <pre><code>world_map = [['.']*n_cols for _ in xrange(n_rows)]...
1
2016-08-06T01:05:28Z
[ "python", "arrays" ]
how to replace the uncommon characters between two strings with 'x'?
38,799,440
<p>I have a dictionary of string counts: <code>{"abcd12efgh":1,"abcd23efgh":1,"abcd567efgh":1,"abcdkljefgh":1, "dog":1, "cat":1}</code></p> <p>I need to group together similar strings and aggregate the counts to get something like: <code>{"abcdxxxefgh":4,"dog":1,"cat":1}.</code></p> <p>Which is the most elegant way t...
-2
2016-08-06T00:34:55Z
38,799,572
<p>The answer depends on how you assumed two keys match, however you can have a separate function decide that. I have written one that might be what you are looking for: check if the key has certain prefix and suffix. You can add more constraints like, the sub string in between has certian lengths or another pattern.</...
0
2016-08-06T00:56:27Z
[ "python", "string", "pattern-matching" ]
Flip left-right Plotly Horizontal Histogram
38,799,469
<p>I've made a horizontal histogram as shown <a href="https://plot.ly/python/histograms/#horizontal-histogram" rel="nofollow">here</a>. Is it possible to flip the x-axis, such that the base of the bars is on the right, and the bars extend out to the left, like the blue histogram <a href="http://blogs.sas.com/content/gr...
0
2016-08-06T00:40:43Z
38,800,469
<p>Look at the xanchor (options are 'left', 'right' 'center') of layout.</p> <pre><code>https://plot.ly/python/reference/#bar </code></pre> <p>By setting the xanchor on a horizontal bar chart to right, you should be able to get that effect.</p>
0
2016-08-06T04:12:47Z
[ "python", "plotly" ]
How to do a search using sqlalchemy from chinese character Column?
38,799,483
<p>code </p> <pre><code>result=Minicomputer.query.filter_by(u'名称'='CC670a').first() </code></pre> <p>error</p> <pre><code>Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; app = create_app(os.getenv('FLASK_CONFIG') or 'default') File "/mnt/hgfs/python/flask/Project/__init_...
0
2016-08-06T00:42:09Z
38,799,749
<p><code>filter_by</code> is a function taking in keyword arguments. <code>filter</code> is a function that takes in an expression. So, either</p> <pre><code>Minicomputer.query.filter_by(名称='CC670a') </code></pre> <p>or</p> <pre><code>Minicomputer.query.filter(Minicomputer.名称 == 'CC670a') </code></pre> <p>Y...
0
2016-08-06T01:30:30Z
[ "python", "flask", "sqlalchemy" ]
How to do a search using sqlalchemy from chinese character Column?
38,799,483
<p>code </p> <pre><code>result=Minicomputer.query.filter_by(u'名称'='CC670a').first() </code></pre> <p>error</p> <pre><code>Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; app = create_app(os.getenv('FLASK_CONFIG') or 'default') File "/mnt/hgfs/python/flask/Project/__init_...
0
2016-08-06T00:42:09Z
38,800,311
<p>do a column mapping solved this error</p> <pre><code>class Minicomputer(Base): __table__ = Base.metadata.tables['minicomputer'] name = __table__.c[u'名称'] def __repr__(self): return '&lt;Minicomputer %r&gt;' % self.name </code></pre>
0
2016-08-06T03:35:38Z
[ "python", "flask", "sqlalchemy" ]
Find parent with certain combination of child rows - SQLite with Python
38,799,560
<p>There are several parts to this question. I am working with sqlite3 in Python 2.7, but I am less concerned with the exact syntax, and more with the methods I need to use. I think the best way to ask this question is to describe my current database design, and what I am trying to accomplish. I am new to databases in ...
0
2016-08-06T00:54:52Z
38,800,413
<p>Simply join the necessary tables. Your schema properly reflects normalization (separating tables into logical groupings) and can scale for one-to-many relationships. Specifically, to answer your question --<em>So, how would I query this database efficiently to find if there is a design that matches a long list (let'...
1
2016-08-06T04:01:10Z
[ "python", "sql", "database", "sqlite" ]
Can I asynchronously duplicate a webapp2.RequestHandler Request to a different url?
38,799,566
<p>For a percentage of production traffic, I want to <strong>duplicate</strong> the received request to a different version of my application. This needs to happen asynchronously so I don't double service time to the client.</p> <p>The reason for doing this is so I can compare the responses generated by the prod versi...
1
2016-08-06T00:55:39Z
38,800,284
<p>The URL Fetch service supports asynchronous requests. From <a href="https://cloud.google.com/appengine/docs/python/issue-requests#issuing_an_asynchronous_request" rel="nofollow">Issuing an asynchronous request</a>:</p> <blockquote> <p>HTTP(S) requests are synchronous by default. To issue an asynchronous request...
1
2016-08-06T03:29:10Z
[ "python", "google-app-engine", "asynchronous", "webapp2" ]
Efficient merge for many huge csv files
38,799,704
<p>I have a script that takes all the csv files in a directory and merges them side-by-side, using an outer join. The problem is that my computer chokes (MemoryError) when I try to use it on the files I need to join (about two dozen files 6-12 Gb each). I am aware that itertools can be used to make loops more efficient...
1
2016-08-06T01:21:32Z
38,799,711
<p>There is a chance <a href="http://dask.pydata.org" rel="nofollow">dask</a> will be well-suited to your use. It might depend on what you want to do after the merge.</p>
0
2016-08-06T01:24:26Z
[ "python", "pandas", "merge", "large-files", "itertools" ]
Efficient merge for many huge csv files
38,799,704
<p>I have a script that takes all the csv files in a directory and merges them side-by-side, using an outer join. The problem is that my computer chokes (MemoryError) when I try to use it on the files I need to join (about two dozen files 6-12 Gb each). I am aware that itertools can be used to make loops more efficient...
1
2016-08-06T01:21:32Z
38,799,737
<p>You should be able to do this with python but i don't think reading the csv's at once will be the most efficient use of your memory.</p> <p><a href="http://stackoverflow.com/questions/6556078/how-to-read-a-csv-file-from-a-stream-and-process-each-line-as-it-is-written">How to read a CSV file from a stream and proces...
0
2016-08-06T01:28:21Z
[ "python", "pandas", "merge", "large-files", "itertools" ]
Efficient merge for many huge csv files
38,799,704
<p>I have a script that takes all the csv files in a directory and merges them side-by-side, using an outer join. The problem is that my computer chokes (MemoryError) when I try to use it on the files I need to join (about two dozen files 6-12 Gb each). I am aware that itertools can be used to make loops more efficient...
1
2016-08-06T01:21:32Z
38,799,791
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-hdf5" rel="nofollow">HDF5</a>, that in my opinion would suit your needs very well. It also handles <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#querying" rel="nofollow">out-of-core queries</a>, so you won't have to face <code>MemoryE...
2
2016-08-06T01:37:56Z
[ "python", "pandas", "merge", "large-files", "itertools" ]
Mocking a function with a certain argument in Python
38,799,714
<p>I have a module a.py:</p> <pre><code>def add(x, y): return x + y def do_math(x): sum1 = add(x, 1) sum2 = add(x, 2) sum3 = add(x, 3) return sum1 + sum2 + sum3 </code></pre> <p>Running the do_math function in a test results in the following:</p> <pre><code>print a.do_math(1) 9 </code></pre> ...
0
2016-08-06T01:25:08Z
38,799,967
<p>Why not just save the function before the call?</p> <pre><code>from mock.mock import patch import a original = a.add def mock_add(*args, **kwargs): x = args[0] y = args[1] if y == 2: return 4 else: return original(x, y) with patch('a.add', side_effect=mock_add): a.do_math(1) </...
0
2016-08-06T02:12:49Z
[ "python", "mocking" ]
No module named 'model_utils'
38,799,718
<p>I'm using Python 3.4.3 and django 1.9.8.</p> <p>In my models.py, I have</p> <blockquote> <p>from model_utils.managers import InheritanceManager</p> </blockquote> <p>But this error occurs:</p> <blockquote> <p>ImportError: No module named 'model_utils'</p> </blockquote>
0
2016-08-06T01:25:35Z
38,799,833
<p>You need to install django-model-utils:</p> <pre><code>pip install django-model-utils </code></pre> <p>(<a href="https://django-model-utils.readthedocs.io/en/latest/index.html" rel="nofollow">documentation</a>)</p>
0
2016-08-06T01:45:20Z
[ "python", "django", "python-3.x", "django-model-utils" ]
What is the correct way to use .apply with pandas?
38,799,723
<p>I'm working with a million-row CSV dataset that includes columns "latitude" and "longitude", and I want to create a new column based on that called "state", which is the US state that contains those coordinates.</p> <pre><code>import pandas as pd import numpy as np import os from uszipcode import ZipcodeSearchEngin...
2
2016-08-06T01:26:27Z
38,799,846
<p>I believe this will be a faster implementation of your program:</p> <pre><code>import pandas as pd import numpy as np import os from uszipcode import ZipcodeSearchEngine def convert_to_state(lat, lon): lat, lon = round(lat, 7), round(lon, 7) res = search.by_coordinate(lat, lon, radius=1, returns=1) sta...
3
2016-08-06T01:49:28Z
[ "python", "pandas" ]
How to balance my data across the partitions?
38,799,753
<p><em>Edit</em>: The answer helps, but I described my solution in: <a href="https://gsamaras.wordpress.com/code/memoryoverhead-issue-in-spark/" rel="nofollow">memoryOverhead issue in Spark</a>.</p> <hr> <p>I have an RDD with 202092 partitions, which reads a dataset created by others. I can manually see that the data...
6
2016-08-06T01:31:37Z
38,803,350
<p>The memory overhead limit exceeding issue I think is due to DirectMemory buffers used during fetch. I think it's fixed in 2.0.0. (We had the same issue, but stopped digging much deeper when we found that upgrading to 2.0.0 resolved it. Unfortunately I don't have Spark issue numbers to back me up.)</p> <hr> <p>The ...
3
2016-08-06T10:39:39Z
[ "python", "hadoop", "apache-spark", "bigdata", "distributed-computing" ]
Ansible + 10.11.6
38,799,807
<p>I'm having a weird issue with Ansible on a (very) clean install of 10.11.6. I've installed brew, zsh, oh-my-zsh, Lil' snitch and 1password (and literally nothing else). I installed ansible with...</p> <p><code>brew install ansible</code></p> <p>... which was successful. I then went to a preexisting (and crazy simp...
0
2016-08-06T01:40:33Z
39,583,152
<p>I had a similar issue, but the "fix" was stranger yet: remove Python3 from the host, as Ansible currently supports up to Python 2.7.</p>
1
2016-09-19T22:41:25Z
[ "python", "osx", "ansible", "ansible-playbook" ]
assign variables to an array
38,799,855
<p>I have the following line (note: the convert function returns an array):</p> <pre><code>question, answer = convert(snippet, phrase) </code></pre> <p>Does this assign the first two values in the array to <code>question</code> and <code>answer</code> variables respectively?</p>
2
2016-08-06T01:51:20Z
38,799,874
<p>If the function returns a list of at least two values, you can do:</p> <pre><code>question, answer = convert(snippet, phrase)[:2] #or question, answer, *_ = convert(snippet, phrase) </code></pre> <p>For example:</p> <pre><code># valid multiple assignment/unpacking x,y = 1, 2 x,y = [1,2,3][:2] x,y, *z = [1, 2, 3,...
0
2016-08-06T01:55:22Z
[ "python", "list" ]
assign variables to an array
38,799,855
<p>I have the following line (note: the convert function returns an array):</p> <pre><code>question, answer = convert(snippet, phrase) </code></pre> <p>Does this assign the first two values in the array to <code>question</code> and <code>answer</code> variables respectively?</p>
2
2016-08-06T01:51:20Z
38,799,912
<p>This is referred to as <em><a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">unpacking</a></em> in Python.</p> <pre><code>a, b, c = 1, 2, 3 # a -&gt; 1 # b -&gt; 2 # c -&gt; 3 </code></pre>
1
2016-08-06T02:01:34Z
[ "python", "list" ]
Creation of basic lists?
38,799,901
<p>I am trying to create a list in Python from a text file. I would like to open the file, read the lines, use the <code>split</code> method, append them to a list. This is what I have so far. All it does is print the text file:</p> <pre><code>lines = [] folder = open("test.txt") word = folder.readlines() for line in ...
-1
2016-08-06T02:00:16Z
38,799,985
<p>As other commentors have observed, variable naming should provide the <strong>context</strong> of what your variable is <em>assigned</em> to. Even though you can name a variable a multitude of names, they <em>should</em> be relevant! </p> <p>You can use the <a href="https://docs.python.org/3/tutorial/inputoutput.ht...
4
2016-08-06T02:16:18Z
[ "python", "python-3.x" ]
Creation of basic lists?
38,799,901
<p>I am trying to create a list in Python from a text file. I would like to open the file, read the lines, use the <code>split</code> method, append them to a list. This is what I have so far. All it does is print the text file:</p> <pre><code>lines = [] folder = open("test.txt") word = folder.readlines() for line in ...
-1
2016-08-06T02:00:16Z
38,800,050
<p>If your file only consists of one line then you don't need to do nearly as much work as you seem to think.</p> <p><code>str.split</code> returns a list, so there is no need to <code>append</code> the individual elements. When you call <code>.split()</code> without any arguments it will split by any whitespace (spa...
1
2016-08-06T02:35:38Z
[ "python", "python-3.x" ]
From JSON file to CSV file
38,799,928
<p>I have a snippet of my json file below. Is there any way to use Python and transform this to a nice CSV file? So things like text and sentiment would have its own columns?</p> <pre><code>{ "status":"OK", "totalTransactions":"1", "language":"english", "url":"http://well.com", "results":[ { ...
-1
2016-08-06T02:04:45Z
38,799,986
<p>The JSON is indeed not valid, notice in line 15: <code>}{</code></p> <p>You are ending the first / outer object and beginning a new one, basically concatenating 2 distinct JSON strings.</p> <p>To fix this you could create an array out of them by surrounding them with square brackets and add a comma between the two...
2
2016-08-06T02:16:58Z
[ "python", "json", "csv" ]
From JSON file to CSV file
38,799,928
<p>I have a snippet of my json file below. Is there any way to use Python and transform this to a nice CSV file? So things like text and sentiment would have its own columns?</p> <pre><code>{ "status":"OK", "totalTransactions":"1", "language":"english", "url":"http://well.com", "results":[ { ...
-1
2016-08-06T02:04:45Z
38,800,039
<p>With corrected CSV as chrki pointed out, the full python source would be:</p> <pre><code>#!/usr/bin/python import json with open('data.json') as data_file: data = json.load(data_file) out = open('out.csv', 'w+') out.write("url;totalTransactions;language;status;text;score;type\n") for entry in d...
0
2016-08-06T02:32:58Z
[ "python", "json", "csv" ]
From JSON file to CSV file
38,799,928
<p>I have a snippet of my json file below. Is there any way to use Python and transform this to a nice CSV file? So things like text and sentiment would have its own columns?</p> <pre><code>{ "status":"OK", "totalTransactions":"1", "language":"english", "url":"http://well.com", "results":[ { ...
-1
2016-08-06T02:04:45Z
38,800,393
<p>You are on the right track with loading the json into a python dictionary. Consider using the python csv module to write the csv output file. </p> <pre><code>https://docs.python.org/2/library/csv.html </code></pre> <p>The keys will become the header row and then for each item, you can create a row and input them i...
0
2016-08-06T03:55:59Z
[ "python", "json", "csv" ]
From JSON file to CSV file
38,799,928
<p>I have a snippet of my json file below. Is there any way to use Python and transform this to a nice CSV file? So things like text and sentiment would have its own columns?</p> <pre><code>{ "status":"OK", "totalTransactions":"1", "language":"english", "url":"http://well.com", "results":[ { ...
-1
2016-08-06T02:04:45Z
38,800,443
<p>Here's an answer to the first part of your question that addresses the improperly formatted JSON file problem. It attempts to convert what's in the file into list of objects (dictionaries) and names the result <code>data</code>:</p> <pre><code>import json import tempfile # Fix the invalid json data and load it. wi...
0
2016-08-06T04:06:55Z
[ "python", "json", "csv" ]
Getting Error when trying to run python code on zapier
38,799,935
<p>I have the following address:</p> <pre><code>556_StreetName_Ave_CityName_11111 </code></pre> <p>I want to use code to trim off the last part, <code>_Ave_CityName_11111</code></p> <p>so basically I want to remove anything with the last 3 underscores.</p> <p>Here is my code:</p> <pre><code>output = "_".join(input...
1
2016-08-06T02:05:27Z
38,809,886
<p>output = {'street_name': "_".join(input['street_name'].split("_")[:-3])}</p> <p>This actually is the code that allowed it to work if anyone needed help. </p> <p>Thanks to nedbat on IRC phython channel for help!!</p>
0
2016-08-07T00:38:15Z
[ "python", "zapier" ]
pyparsing removing some text and how to capture text with whitespace
38,799,948
<p>I am new to using pyparsing (python 2.7) and have a couple of questions about this code:</p> <pre><code>import pyparsing as pp openBrace = pp.Suppress(pp.Literal("{")) closeBrace = pp.Suppress(pp.Literal("}")) ident = pp.Word(pp.alphanums + "_" + ".") otherStuff = pp.Suppress(pp.Word(pp.alphanums + "_" + "." + "-"...
1
2016-08-06T02:07:53Z
38,800,083
<p>To answer your first query:</p> <pre><code>&gt;&gt;&gt; import pyparsing as pp &gt;&gt;&gt; &gt;&gt;&gt; openBrace = pp.Suppress(pp.Literal("{")) &gt;&gt;&gt; closeBrace = pp.Suppress(pp.Literal("}")) &gt;&gt;&gt; ident = pp.Word(pp.alphanums + "_" + ".") &gt;&gt;&gt; otherStuff = pp.Suppress(pp.Word(pp.alphanums ...
2
2016-08-06T02:46:22Z
[ "python", "python-2.7", "parsing", "pyparsing" ]
pyparsing removing some text and how to capture text with whitespace
38,799,948
<p>I am new to using pyparsing (python 2.7) and have a couple of questions about this code:</p> <pre><code>import pyparsing as pp openBrace = pp.Suppress(pp.Literal("{")) closeBrace = pp.Suppress(pp.Literal("}")) ident = pp.Word(pp.alphanums + "_" + ".") otherStuff = pp.Suppress(pp.Word(pp.alphanums + "_" + "." + "-"...
1
2016-08-06T02:07:53Z
38,806,036
<p>A couple of points:</p> <ol> <li><p><code>messageKw</code> should be defined using the pyparsing Keyword class. Right now you are just matching the literal "msg", so even when that is the leading part of "msgName2", it will match. Change this to:</p> <pre><code>messageKw = pp.Suppress(pp.Keyword("msg")) </code></...
2
2016-08-06T15:47:21Z
[ "python", "python-2.7", "parsing", "pyparsing" ]
Why does matplotlib choose the wrong range in y using log scale?
38,799,968
<p>Using matplotlib version 1.5.1 and python 2.7.11 I noticed that I need to specify the limits in y manually or else only the largest y-value point is plotted. Arrays behave the same way.</p> <p>If I remove the first point, I get a few more points, but not all of them.</p> <p>I don't recall ever having to manually s...
0
2016-08-06T02:12:56Z
38,800,011
<p>The problem arises because you have first drawn the scatter plot and then set the scales as logarithmic which results in a zooming in effect. This removes the problem:</p> <pre><code>plt.xscale('log') plt.yscale('log') plt.scatter(X, Y) </code></pre> <p>This produces the intended result. (2nd subplot in your quest...
3
2016-08-06T02:25:09Z
[ "python", "python-2.7", "matplotlib" ]
Why does matplotlib choose the wrong range in y using log scale?
38,799,968
<p>Using matplotlib version 1.5.1 and python 2.7.11 I noticed that I need to specify the limits in y manually or else only the largest y-value point is plotted. Arrays behave the same way.</p> <p>If I remove the first point, I get a few more points, but not all of them.</p> <p>I don't recall ever having to manually s...
0
2016-08-06T02:12:56Z
38,800,032
<p>It seems like <code>matplotlib</code> is creating the y-axis ticks before converting to a log scale, and then not recreating the ticks based on the change. The y-axis on your first subplot starts at 10e1, not 10e-3. So change the scales before you plot.</p> <pre><code>plt.xscale('log') plt.yscale('log') plt.scatter...
1
2016-08-06T02:30:34Z
[ "python", "python-2.7", "matplotlib" ]
Django assert failure: assertInHTML('hello', '<html>hello</html>')
38,800,089
<p>In Django shell:</p> <pre><code>from django.test import SimpleTestCase c = SimpleTestCase() haystack = '&lt;html&gt;&lt;b&gt;contribution&lt;/b&gt;&lt;/html&gt;' c.assertInHTML('&lt;b&gt;contribution&lt;/b&gt;', haystack) c.assertInHTML('contribution', haystack) </code></pre> <p>I don't understand why the first ...
4
2016-08-06T02:49:20Z
38,801,320
<p>This is a <a href="https://code.djangoproject.com/ticket/24112" rel="nofollow">bug in Django</a>:</p> <blockquote> <p><code>assertInHTML(needle, haystack)</code> has the following behaviour</p> <p><code>assertInHTML('&lt;p&gt;a&lt;/p&gt;', '&lt;div&gt;&lt;p&gt;a&lt;/p&gt;&lt;p&gt;b&lt;/p&gt;&lt;/div&gt;')</c...
3
2016-08-06T06:37:03Z
[ "python", "django", "assert" ]
The difference between these 2 strings?
38,800,125
<p>I have recently started to learn Python and I am hoping that you will be able to help me with a question that has been bothering me. I have been learning Python online with <a href="http://learnpythonthehardway.org/book/" rel="nofollow">Learn Python The Hard Way</a>. In Exercise 6, I came across a problem where I wa...
1
2016-08-06T02:57:19Z
38,800,146
<p><code>%r</code> is getting the <code>repr</code> version of the string:</p> <pre><code>&gt;&gt;&gt; x = 'here' &gt;&gt;&gt; print repr(x) 'here' </code></pre> <p>You see, single quotes are what are normally used. In the case of <code>y</code>, however, you have a single quote (apostrophe) inside the string. Well...
1
2016-08-06T03:03:33Z
[ "python", "string", "printing", "string-formatting" ]
The difference between these 2 strings?
38,800,125
<p>I have recently started to learn Python and I am hoping that you will be able to help me with a question that has been bothering me. I have been learning Python online with <a href="http://learnpythonthehardway.org/book/" rel="nofollow">Learn Python The Hard Way</a>. In Exercise 6, I came across a problem where I wa...
1
2016-08-06T02:57:19Z
38,800,147
<p>Notice this line -> <code>do_not = "don't"</code>. There is a single quote in this string, that means that single quote has to be escaped; otherwise where would the <strong>interpreter</strong> know where a string <em>began</em> and <em>ended</em>? Python knows to use <code>""</code> to represent this string literal...
2
2016-08-06T03:03:34Z
[ "python", "string", "printing", "string-formatting" ]
List comprehension with list and list of tuples
38,800,133
<p>In my Python 2.7.5 code I have the following data structures:</p> <p>A simple list...</p> <pre><code>&gt;&gt;&gt; data["parts"] ['com', 'google', 'www'] </code></pre> <p>...and a list of tuples...</p> <pre><code>&gt;&gt;&gt; data["glue"] [(1L, 'com'), (3L, 'google')] </code></pre> <p>When entering the code wher...
1
2016-08-06T02:59:21Z
38,800,208
<p>You can use list comprehensions here. Maybe the simplest thing would be to create a set of all indices, then return the missing indices. Note this answer will give you all the missing components, even if there are duplicates in the parts array (for example, if "www" appeared twice in parts). This would not be the ca...
0
2016-08-06T03:15:54Z
[ "python", "list", "tuples", "list-comprehension" ]
List comprehension with list and list of tuples
38,800,133
<p>In my Python 2.7.5 code I have the following data structures:</p> <p>A simple list...</p> <pre><code>&gt;&gt;&gt; data["parts"] ['com', 'google', 'www'] </code></pre> <p>...and a list of tuples...</p> <pre><code>&gt;&gt;&gt; data["glue"] [(1L, 'com'), (3L, 'google')] </code></pre> <p>When entering the code wher...
1
2016-08-06T02:59:21Z
38,800,219
<p>You can use <a href="http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch16s03.html" rel="nofollow">set difference</a> operations.</p> <pre><code>print set(data['parts'])-set(i[1] for i in data['glue']) &gt;&gt;&gt; set(['www']) </code></pre> <p>or with simply using <a href="https:...
5
2016-08-06T03:17:02Z
[ "python", "list", "tuples", "list-comprehension" ]
Django app server hangs / won't start in Docker Compose
38,800,238
<p>I am trying to launch a straightforward Django app server in Docker Compose, paired with a Postgres container. It goes through as I would expect, launching the entrypoint script, but it never seems to actually run the Django app server (which should be the last step, and remain running).</p> <p>I know it runs the e...
0
2016-08-06T03:20:34Z
38,800,574
<p>Use the exec form for <code>CMD</code> in your Dockerfile</p> <pre><code>CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] </code></pre> <p>The <code>entrypoint.sh</code> scripts <code>exec</code> is currently trying to run:</p> <pre><code>/bin/sh -c python3 manage.py runserver 0.0.0.0:8000 </code></pre> ...
1
2016-08-06T04:35:21Z
[ "python", "django", "docker", "docker-compose" ]
Python currying with any number of variables
38,800,245
<p>I am trying to use currying to make a simple functional add in Python. I found this curry decorator <a href="https://gist.github.com/JulienPalard/021f1c7332507d6a494b" rel="nofollow">here</a>.</p> <pre><code>def curry(func): def curried(*args, **kwargs): if len(args) + len(kwargs) &gt;= func.__code...
2
2016-08-06T03:22:46Z
38,800,354
<p>Arguably, <code>explicit is better than implicit</code>:</p> <pre><code>from functools import partial def example(*args): print("This is an example function that was passed:", args) one_bound = partial(example, 1) two_bound = partial(one_bound, 2) two_bound(3) </code></pre> <p>@JohnKugelman explained the des...
3
2016-08-06T03:47:42Z
[ "python", "python-2.7", "currying" ]
Python currying with any number of variables
38,800,245
<p>I am trying to use currying to make a simple functional add in Python. I found this curry decorator <a href="https://gist.github.com/JulienPalard/021f1c7332507d6a494b" rel="nofollow">here</a>.</p> <pre><code>def curry(func): def curried(*args, **kwargs): if len(args) + len(kwargs) &gt;= func.__code...
2
2016-08-06T03:22:46Z
38,800,519
<p>You can implement the same thing as the <code>functools.partial</code> example for yourself like this:</p> <pre><code>def curry (prior, *additional): def curried(*args): return prior(*(args + additional)) return curried def add(*args): return sum(args) x = curry(add, 3,4,5) y = curry(b, 100) p...
0
2016-08-06T04:22:01Z
[ "python", "python-2.7", "currying" ]
Improve performance of constraint-adding in Gurobi (Python-Interface)
38,800,280
<p>i got this decision variable:</p> <pre><code>x={} for j in range(10): for i in range(500000): x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%d%d" %(i,j)) </code></pre> <p>so i need to add constraints for each x[i,j] variable like this:</p> <pre><code>for p in range(10): for u in range(500000): ...
0
2016-08-06T03:29:05Z
38,804,906
<h2>General Remark:</h2> <ul> <li>It looks quite costly to add 5 million constraints in general</li> </ul> <h2>Specific Remark:</h2> <h3>Approach</h3> <ul> <li>You are wasting time and space by using <em>dictionaries</em> <ul> <li>Despite having constant-access complexity, these constants are big</li> <li>They are...
1
2016-08-06T13:42:38Z
[ "python", "constraints", "linear-programming", "gurobi" ]
Improve performance of constraint-adding in Gurobi (Python-Interface)
38,800,280
<p>i got this decision variable:</p> <pre><code>x={} for j in range(10): for i in range(500000): x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%d%d" %(i,j)) </code></pre> <p>so i need to add constraints for each x[i,j] variable like this:</p> <pre><code>for p in range(10): for u in range(500000): ...
0
2016-08-06T03:29:05Z
38,816,516
<p>Most likely, you are running out of physical memory and using virtual (swap) memory. This would not cause your computer to report an out-of-memory warning or error.</p> <p>I rewrote your code as follows:</p> <pre><code>from gurobipy import * m = Model() x={} for j in range(10): for i in range(500000): x[i...
1
2016-08-07T17:04:45Z
[ "python", "constraints", "linear-programming", "gurobi" ]
BeautifulSoup <span>foo</span> result
38,800,307
<p>HTML Code: <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="descProdotto"&gt; &lt;img alt="Mont Blanc Eyewear" class="logoDesc" src="http://151.9.39.27/nfs/Immagin...
0
2016-08-06T03:34:17Z
38,800,387
<p>Find the <code>span</code> element <em>by text</em> and get the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow">next sibling</a>:</p> <pre><code>soup.find("span", text="Nome:").next_sibling </code></pre> <p>This is also covered in the <a class='doc-...
0
2016-08-06T03:54:50Z
[ "python", "html", "beautifulsoup" ]
Cannot validate boolean field if value = false (missing field)
38,800,338
<p>I can't validate POST data with boolean field value "false" only, this works fine with "true". I was already try to force '0', 'False' and 'false' but is_valid() method return false with error "This field is required". </p> <p>My post data dict is : </p> <pre><code>&lt;QueryDict: {u'vote': [u'false'], u'csrfmiddle...
0
2016-08-06T03:42:54Z
38,800,383
<p>If I understand your question correctly, you would need to parse the input from a string to bool value. The following: <code>bool('false')</code> and <code>bool('true')</code> will always return <code>True</code> due to their implicit <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel=...
2
2016-08-06T03:54:35Z
[ "python", "django", "django-forms" ]
Cannot validate boolean field if value = false (missing field)
38,800,338
<p>I can't validate POST data with boolean field value "false" only, this works fine with "true". I was already try to force '0', 'False' and 'false' but is_valid() method return false with error "This field is required". </p> <p>My post data dict is : </p> <pre><code>&lt;QueryDict: {u'vote': [u'false'], u'csrfmiddle...
0
2016-08-06T03:42:54Z
38,804,363
<p><strong>Solved</strong> : Using NullBooleanField instead of BooleanField... </p>
0
2016-08-06T12:35:11Z
[ "python", "django", "django-forms" ]
'WSGIRequest' object has no attribute 'flash'
38,800,379
<p>I badly need your help. I am currently trying to pass a string value using flash but I am not sure if I got it correctly. </p> <p>This is my code:</p> <pre><code>def first_view(request): request.flash['message'] = 'Operation succeeded!' return HttpResponseRedirect(reverse(second_view)) def second_view(req...
0
2016-08-06T03:53:12Z
38,800,858
<p>By default the django HttpRequest object doesn't have an attribute named flash. That's why you are getting this error. You can see available attributes here: <a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#httprequest-objects" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/request-resp...
1
2016-08-06T05:25:55Z
[ "python", "django" ]
Python: Loop Prompt Back Around
38,800,385
<p>A lot of the errors of this Python file have been fixed but there is one last thing it's not working. I need the else statement to loop back to ask the question again if neither Yes or No is entered. You can probably see by the code what I was going for but I'm probably not even on the right track. Can someone help ...
-1
2016-08-06T03:54:45Z
38,800,426
<p>I would encourage to you always break to a new line after a conditional...</p> <pre><code>if game_status == "YES": print "\"You know I got it, man!\" I said. \"Awesome! Let's play it,\" he said. \"I heard " + game_name + " is supposed to be amazing!\" We went back inside and took turns playing until " + friend ...
2
2016-08-06T04:04:02Z
[ "python", "if-statement" ]
Python: Loop Prompt Back Around
38,800,385
<p>A lot of the errors of this Python file have been fixed but there is one last thing it's not working. I need the else statement to loop back to ask the question again if neither Yes or No is entered. You can probably see by the code what I was going for but I'm probably not even on the right track. Can someone help ...
-1
2016-08-06T03:54:45Z
38,800,484
<p>This:</p> <pre><code>if game_status: "YES" </code></pre> <p>isn't how you make an <code>if</code> statement. You're treating it like the syntax is</p> <pre><code>if some_variable: some_value </code></pre> <p>and if the variable has that value, the if statement triggers. In fact, the syntax is</p> <pre><code>if ...
2
2016-08-06T04:16:08Z
[ "python", "if-statement" ]
How to read hadoop map file using python?
38,800,430
<p>I have map file that is block compressed using DefaultCodec. The map file is created by java application like this:</p> <pre><code>MapFile.Writer writer = new MapFile.Writer(conf, path, MapFile.Writer.keyClass(IntWritable.class), MapFile.Writer.valueClass(BytesWri...
0
2016-08-06T04:04:49Z
38,800,680
<p>I would suggest using Spark which has a function called textFile() which can read files from HDFS and turn them into RDDs for further processing using other Spark libraries.</p> <p>Here's the documentation : <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html" rel="nofollow">Pyspark</a></p>
0
2016-08-06T04:54:14Z
[ "python", "hadoop" ]
How to read hadoop map file using python?
38,800,430
<p>I have map file that is block compressed using DefaultCodec. The map file is created by java application like this:</p> <pre><code>MapFile.Writer writer = new MapFile.Writer(conf, path, MapFile.Writer.keyClass(IntWritable.class), MapFile.Writer.valueClass(BytesWri...
0
2016-08-06T04:04:49Z
38,803,884
<p>Create a reader as follow:</p> <pre><code>path = '/hdfs/path/to/file' key = LongWritable() value = LongWritable() reader = MapFile.Reader(path) while reader.next(key, value): print key, value </code></pre> <p>Check out these <a href="http://nullege.com/codes/show/src%40h%40a%40Hadoop-HEAD%40python-hadoop%4...
0
2016-08-06T11:40:33Z
[ "python", "hadoop" ]
Function not returning a value
38,800,462
<p>Please help. I am having issues with my <code>getroofCalcs()</code> function not returning variables. Specifically the <code>roofArea</code> variable at the moment. This is a basic program for my intro to programming class and I can not figure out why when I run this I keep getting the error that <code>roofArea</...
0
2016-08-06T04:11:53Z
38,800,538
<p><code>getroofCalcs()</code> <em>is</em> returning a value - it's returning a tuple consisting of the three calculated values. The problem is, however, that the return value is not bound to any variable and so is lost. You can change the code where the call to <code>getroofCalcs()</code> is made in <code>main()</code...
1
2016-08-06T04:25:08Z
[ "python", "function", "return" ]
Flask on GAE - Connect to Google API - Can't use JSON file
38,800,487
<p>I'm fairly new to Flask, GAE and the use of API. I'm trying to build a basic Web App that can connect to one of Google's API.</p> <p>My folder structure looks like this (I've kept it to the main files):<br> app-webemotions:<br> -app.yaml<br> -main.py<br> -lib<br> --sentimentanalysis.py<br> -static<br> --credential....
1
2016-08-06T04:16:36Z
38,837,697
<p>If you are running on Google App Engine, then your code automatically has the credentials it needs. Do not set GOOGLE_APPLICATION_CREDENTIALS and do not call .from_json_keyfile_name. Instead, call:</p> <pre><code>credentials = GoogleCredentials.get_application_default() </code></pre> <p>As shown here: <a href="h...
0
2016-08-08T20:10:05Z
[ "python", "google-app-engine", "flask", "google-api" ]
Python Inheritance: Calling Methods Inside Methods
38,800,491
<p>I'm new to Python and trying to understand the best "Pythonic" practices for OO and inheritance.</p> <p>Here's a simplified version of something I'm trying to do: Let's say I have a base class <code>A</code> that has an initialization method, which, in turn, calls another method that sets some internal parameters -...
3
2016-08-06T04:17:34Z
38,800,659
<p>Yeah, designing for inheritance is tricky like that. People don't put as much thought as they really should into what overridden methods do or don't affect, and they don't do enough to document how overriding methods affects other methods.</p> <p>If you want to bypass overrides for that <code>set_params</code> call...
3
2016-08-06T04:49:51Z
[ "python", "inheritance" ]
python how to sum up values in list by condition
38,800,497
<p>I have in python the following list:</p> <pre><code>[{'a':4,'b':40},{'a':6, 'b':60}, {'a':3, 'b':90}, {'a':7, 'b':95}] </code></pre> <p>the 'b' values are in ascending order.</p> <p>Also I have a num variable, say <code>num=25</code>.</p> <p>what I need is to build a list in which I sum up all the 'a's until the...
-3
2016-08-06T04:19:05Z
38,986,531
<p>The only way to make your code more "pythonic" is probably to use <code>enumerate()</code> instead of <code>rang(len(object))</code>. Other than that it's pretty much as pythonic as possible.</p>
0
2016-08-17T00:46:39Z
[ "python", "list" ]
Plot color NaN values
38,800,532
<p>I'm trying to plot color some array, and convert some of the values to np.nan (for easier interpretation) and expecting different color when plotted (white?), instead it causes problem with the plot and the colorbar. </p> <pre><code>#this is before converted to nan array = np.random.rand(4,10) plt.pcolor(array) ...
4
2016-08-06T04:24:06Z
38,800,580
<p>One of the solution is to plot masked array, like here:</p> <pre><code>import matplotlib.pylab as plt import numpy as np #conditional value converted to nan array = np.random.rand(4,10) array[array&lt;0.5]=np.nan m = np.ma.masked_where(np.isnan(array),array) plt.pcolor(m) plt.colorbar(orientation='horizontal') ...
4
2016-08-06T04:36:17Z
[ "python", "numpy", "matplotlib", null, "colorbar" ]