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
add() argument after * must be a sequence, not Settings
38,658,684
<p>I'm trying to build a game that moves a ship left and right with the arrow keys and fires bullets when the spacebar is pressed. When I press the spacebar my game crashes and this error is shown: Traceback (most recent call last):</p> <pre><code>TypeError: add() argument after * must be a sequence, not Settings </co...
2
2016-07-29T12:19:23Z
38,662,125
<p>Yes Jokab is right, you forgot the extra underscore. However, for future practice it is important to learn to read the Python <code>TrackBack</code>. It usually gives you a good idea of where the problem is. For example, take the <code>TrackBack</code> you pasted here. Python first tells you it had a problem running...
1
2016-07-29T15:11:20Z
[ "python", "pygame", "sprite", "add" ]
Pandas: append symbol to cells in column
38,658,752
<p>I create dataframe with </p> <pre><code>df3 = np.round(df2[["All"]]/df['Gender'].count()*100, 2).rename(columns={"All":'%'}) </code></pre> <p>and I want to add <code>%</code> after every number. How can I do it? <code>df</code>:</p> <pre><code>Third party unique identifier Qsex Gender 9ea3e3cb6719f3d336d324c...
0
2016-07-29T12:22:48Z
38,660,163
<p>I think you need first add <code>normalize</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html" rel="nofollow"><code>round</code></a>, m...
1
2016-07-29T13:28:46Z
[ "python", "pandas" ]
Remapping `numpy.array` with missing values
38,658,811
<p>I'm dealing with some large data sets - observations as a function of time - which are not continuous in time (i.e., there is a lot of missing data, where the complete record is absent). To make things fun, there are a lot of data sets, all with missing records, all at random places... </p> <p>I somehow need to get...
1
2016-07-29T12:25:50Z
38,667,956
<p>If you do <code>d2 = np.intersect1d(dc, d2)</code> before calling <code>dc.searchsorted(d2)</code> it will remove all elements in d2 that are not in dc.</p>
1
2016-07-29T21:48:13Z
[ "python", "numpy" ]
How to improve performance for large lists in python
38,659,123
<p>I have a large list with say 10 million of integers (sorted) "alist". What I need is to get the smallest distance between some of the integers (from a "blist") and the neighbours in the list. I do it by finding the position of the integer I look for, get the item before and after and measure the difference:</p> <pr...
0
2016-07-29T12:39:57Z
38,659,683
<p>I really like the Numpy module for this kind of computing.</p> <p>In your case, that would be (this is the long answer, could be factorized to be more efficient): </p> <pre><code>import numpy as np alist = [1, 4, 30, 1000, 2000] blist = [4, 30, 1000] a_array = np.asarray(alist) b_array = np.asarray(blist) a_ind...
1
2016-07-29T13:05:01Z
[ "python", "performance", "list", "optimization" ]
How to improve performance for large lists in python
38,659,123
<p>I have a large list with say 10 million of integers (sorted) "alist". What I need is to get the smallest distance between some of the integers (from a "blist") and the neighbours in the list. I do it by finding the position of the integer I look for, get the item before and after and measure the difference:</p> <pr...
0
2016-07-29T12:39:57Z
38,659,932
<p>I suggest using <strong>binary search</strong>. Makes it much faster, doesn't cost extra memory, and only requires a little change. Instead of <code>alist.index(b)</code>, simply use <a href="https://docs.python.org/3.5/library/bisect.html#bisect.bisect_left" rel="nofollow"><code>bisect_left(alist, b)</code></a>.</p...
4
2016-07-29T13:17:26Z
[ "python", "performance", "list", "optimization" ]
Remove text below barcode in python barcode.py library
38,659,202
<p>Does anyone know how to remove text below a bar-code? Bar-code is generated using <code>barcode.py</code> library. I was trying to check in <a href="https://bitbucket.org/whitie/python-barcode" rel="nofollow">https://bitbucket.org/whitie/python-barcode</a> but could not find solution,what properties should be writt...
1
2016-07-29T12:43:12Z
38,690,298
<p>Looking at the code, it appears you can set the attribute <code>'human'</code> (human-readable text) to a non-empty string to override the text at the bottom. If this is set to a string with a single blank, <code>' '</code>, the text will be empty.</p>
0
2016-08-01T02:40:11Z
[ "python", "python-2.7", "barcode" ]
Numpy suddenly uses all CPUs
38,659,217
<p>Until recently when I used numpy methods like np.dot(A,B), only a single core was used. However, since today suddently all 8 cores of my linux machine are being used, which is a problem.</p> <p>A minimal working example:</p> <pre><code>import numpy as np N = 100 a = np.random.rand(N,N) b = np.random.rand(N,N) fo...
2
2016-07-29T12:44:07Z
38,659,540
<p>This could be because <code>numpy</code> is linking against multithreaded openBLAS libraries. Try setting the global environment variable to set threading affinity as:</p> <pre><code>export OPENBLAS_MAIN_FREE=1 # Now run your python script. </code></pre> <p>Another workaround could to use <code>ATLAS</code> inste...
2
2016-07-29T12:58:36Z
[ "python", "numpy" ]
Numpy suddenly uses all CPUs
38,659,217
<p>Until recently when I used numpy methods like np.dot(A,B), only a single core was used. However, since today suddently all 8 cores of my linux machine are being used, which is a problem.</p> <p>A minimal working example:</p> <pre><code>import numpy as np N = 100 a = np.random.rand(N,N) b = np.random.rand(N,N) fo...
2
2016-07-29T12:44:07Z
38,662,889
<p>Assuming you have root access, Pankaj Daga's answer is propably ok.</p> <p>In my case I reinstalled my local numpy version, which turned out to solve the problem.</p>
0
2016-07-29T15:51:41Z
[ "python", "numpy" ]
.join() elements of a user generated list using range in Python
38,659,238
<p>In my program user enters a number (input_n) that will go through :<br> 0+1+2+ ... + n = n*(n+1)/2 axiom.</p> <p>My desired output for an input_n &lt;= 10 (in this case : 5)</p> <pre><code>[0, 1, 2, 3, 4, 5] 0 + 1 + 2 + 3 + 4 + 5 = 15 5*(5+1)/2 = 15 </code></pre> <p>My desired output for an input_n > 10 (in thi...
0
2016-07-29T12:44:54Z
38,659,315
<p>The traceback is showing you this:</p> <blockquote> <pre><code>....join(str(i) for i in range(input_n-5,input_n+1), sum(input_list))) </code></pre> </blockquote> <p>What is written here makes no sense. Revise it until it does.</p>
3
2016-07-29T12:48:14Z
[ "python", "list", "range" ]
.join() elements of a user generated list using range in Python
38,659,238
<p>In my program user enters a number (input_n) that will go through :<br> 0+1+2+ ... + n = n*(n+1)/2 axiom.</p> <p>My desired output for an input_n &lt;= 10 (in this case : 5)</p> <pre><code>[0, 1, 2, 3, 4, 5] 0 + 1 + 2 + 3 + 4 + 5 = 15 5*(5+1)/2 = 15 </code></pre> <p>My desired output for an input_n > 10 (in thi...
0
2016-07-29T12:44:54Z
38,659,469
<p>You forgot to close the bracket of the <code>join</code> built-in method, so I guess this is what you want:</p> <pre><code>&gt;&gt;&gt; input_list = list(range(21)) &gt;&gt;&gt; &gt;&gt;&gt; input_n = 20 &gt;&gt;&gt; print("+".join(str(i) for i in range(5)) + " + ... +" + "+".join(str(i) for i in range(input_n-5,i...
1
2016-07-29T12:55:35Z
[ "python", "list", "range" ]
Explode list of lists into separate lists python
38,659,375
<p>I currently have a list of lists like </p> <pre><code>L = [['E2', 'C1', 'A1', 'B1', 'C2'], ['C1', 'D1', 'A1'], ['C1', 'C2']] </code></pre> <p>My aim is to compare L[i] against L[i+1] to make groups. For example, L[2] is a subset of L[0] so I would eliminate it. My two different list will be L[0] and L[1].</p> <p...
0
2016-07-29T12:51:40Z
38,659,798
<p>You could map your list of list to create a list of sets. if you then iterate over that list, it would be possible to check if they are subsets of each other</p> <pre class="lang-python prettyprint-override"><code>LSets = map(set, L) filteredL = filter(lambda s: not any(s.issubset(s2) for s2 in LSets if s != s2), ...
0
2016-07-29T13:11:07Z
[ "python", "list", "python-2.7", "split" ]
How do I get a Python distribution URL?
38,659,408
<p>In their setup.py Python packages provides some information. This information can then be found in the PKG_INFO file of the egg.</p> <p>How can I access them once I have installed the package?</p> <p>For instance, if I have the following module:</p> <pre><code>setup(name='myproject', version='1.2.0.dev0', ...
0
2016-07-29T12:52:43Z
38,659,619
<p>There is apparently a private API that let you do that with <code>pkg_resources</code>:</p> <pre><code>import pkg_resources d = pkg_resources.get_distribution(__package__) metadata = d._get_metadata(d.PKG_INFO) home_page = [m for m in metadata if m.startswith('Home-page:')] url = home_page[0].split(':', 1)[1].strip...
0
2016-07-29T13:02:09Z
[ "python", "setuptools", "pkg-resources" ]
Python: How to remove a comment line and write on the same file?
38,659,425
<p>I've a list of commented file where I need to remove the comment lines in that files(#) and need to write on that same file.</p> <p><strong>comment file:</strong></p> <pre><code>#Hi this the comment define host { use template host_name google_linux address 192.168....
0
2016-07-29T12:53:33Z
38,659,546
<p>I don't think you can write lines to a file that you are looping over, you'll need to write out to a different file, which you can move over the original file after the loop. </p> <p>Or, you can read all lines into memory, close and reopen the file and write over the lines with the newly processed lines </p>
0
2016-07-29T12:58:43Z
[ "python" ]
Python: How to remove a comment line and write on the same file?
38,659,425
<p>I've a list of commented file where I need to remove the comment lines in that files(#) and need to write on that same file.</p> <p><strong>comment file:</strong></p> <pre><code>#Hi this the comment define host { use template host_name google_linux address 192.168....
0
2016-07-29T12:53:33Z
38,660,015
<p>Some pseudocode</p> <p>open file in read open a new file in write mode call it temp loop through and do some operation (delete comments, add what ever you need to add) and write to the temp file close the original file and delete it then rename your temp file to your old file so it would be like </p> <pre><code>fi...
0
2016-07-29T13:21:59Z
[ "python" ]
Dictionary of pair in python
38,659,513
<p>I am new to python and was trying to make a <code>dict of pairs</code> in python. What I would have done in <code>c++</code> is</p> <pre><code>dist[make_pair(a,b)]=1 </code></pre> <p>I am not sure how I can do the same in python</p> <p><strong>Edit</strong> What I basically want to do is to map a pair of two inte...
1
2016-07-29T12:57:31Z
38,659,609
<p>You can use the data structure "tuple" as a key in the dictionary. If you want to define a function that returns a n-tuple given n inputs, you can do that also.</p> <pre><code>a = 4 b = 5 dict_example = dict() dict_example[(a,b)] = 1 print dict_example[(a,b)] </code></pre> <p>This prints the value of key (a,b), ...
4
2016-07-29T13:01:47Z
[ "python" ]
Dictionary of pair in python
38,659,513
<p>I am new to python and was trying to make a <code>dict of pairs</code> in python. What I would have done in <code>c++</code> is</p> <pre><code>dist[make_pair(a,b)]=1 </code></pre> <p>I am not sure how I can do the same in python</p> <p><strong>Edit</strong> What I basically want to do is to map a pair of two inte...
1
2016-07-29T12:57:31Z
38,659,641
<p>To create an element having the tuple (a,b) as key, and 1 as a value, you just have to do :</p> <pre><code>new_dict = {(a,b) : 1} </code></pre> <p>If such a dict already exist, and you want to add the pair a,b as a key and 1 as a value, you have to do :</p> <pre><code>existing_dict[(a,b)] = 1 </code></pre> <p>Yo...
2
2016-07-29T13:03:04Z
[ "python" ]
Dictionary of pair in python
38,659,513
<p>I am new to python and was trying to make a <code>dict of pairs</code> in python. What I would have done in <code>c++</code> is</p> <pre><code>dist[make_pair(a,b)]=1 </code></pre> <p>I am not sure how I can do the same in python</p> <p><strong>Edit</strong> What I basically want to do is to map a pair of two inte...
1
2016-07-29T12:57:31Z
38,660,098
<p>I guess you tried using an array as a dict key, like:</p> <pre><code>&gt;&gt;&gt; d = {} &gt;&gt;&gt; pair = [0, 1] &gt;&gt;&gt; d[pair] = 'foo' TypeError: unhashable type: 'list' </code></pre> <p>Ok, what is that? Python dict keys must not be mutable. They can be numbers, strings and other hashable types - you ca...
1
2016-07-29T13:26:08Z
[ "python" ]
IPython 5.0 and key bindings in console
38,659,721
<p>The new release of IPython does not depend any more on <code>readline</code> but uses the pure Python library <code>prompt-toolkit</code>, solving maintenance problems on Apple's and Windows' systems.</p> <p>A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the co...
17
2016-07-29T13:07:07Z
39,015,985
<p>The <kbd>ctrl</kbd>+<kbd>j</kbd> or <kbd>ctrl</kbd>+<kbd>m</kbd> keyboard shortcuts are validating the entry.</p>
2
2016-08-18T10:35:20Z
[ "python", "ipython", "keyboard-shortcuts", "xterm" ]
IPython 5.0 and key bindings in console
38,659,721
<p>The new release of IPython does not depend any more on <code>readline</code> but uses the pure Python library <code>prompt-toolkit</code>, solving maintenance problems on Apple's and Windows' systems.</p> <p>A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the co...
17
2016-07-29T13:07:07Z
39,029,256
<p>You could change xterm's configuration.</p> <p>xterm is configurable (and documented). In the xterm manual, the <a href="http://invisible-island.net/xterm/manpage/xterm.html#h3-Default-Key-Bindings" rel="nofollow"><em>Default Key Bindings</em></a> section shows the default binding for this key:</p> <pre><code> ...
4
2016-08-19T00:02:18Z
[ "python", "ipython", "keyboard-shortcuts", "xterm" ]
IPython 5.0 and key bindings in console
38,659,721
<p>The new release of IPython does not depend any more on <code>readline</code> but uses the pure Python library <code>prompt-toolkit</code>, solving maintenance problems on Apple's and Windows' systems.</p> <p>A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the co...
17
2016-07-29T13:07:07Z
39,154,587
<p>Modifying keyboard shortcuts in configuration when using prompt_toolkit is not (yet) possible; though it is pretty easy if you install IPython from source. If you look at the file <code>IPython/terminal/shortcuts.py</code> you will see that it contains the various logic; in particular you will find:</p> <pre><code...
0
2016-08-25T20:55:58Z
[ "python", "ipython", "keyboard-shortcuts", "xterm" ]
place values by condition with numpy
38,659,742
<p>I have a three channel matrix and I want to place the value which is less than 27</p> <pre><code>a=numpy.arange(27).reshape(3,3,3) a[a&lt;27]=0 </code></pre> <p>However, If I want to replace only on first channel, the way I can do is to write a for loop</p> <pre><code>for i in range(3): for j in range(3): ...
0
2016-07-29T13:08:08Z
38,659,823
<p>You can try with:</p> <pre><code>a=numpy.arange(27).reshape(3,3,3) a[a[:,:,0]&lt;27, 0]=0 </code></pre>
2
2016-07-29T13:12:07Z
[ "python", "numpy" ]
place values by condition with numpy
38,659,742
<p>I have a three channel matrix and I want to place the value which is less than 27</p> <pre><code>a=numpy.arange(27).reshape(3,3,3) a[a&lt;27]=0 </code></pre> <p>However, If I want to replace only on first channel, the way I can do is to write a for loop</p> <pre><code>for i in range(3): for j in range(3): ...
0
2016-07-29T13:08:08Z
38,659,861
<p>I think, you were looking for this: <code>a[:,:,0][a[:,:,0]&lt;27]=0</code></p>
1
2016-07-29T13:14:07Z
[ "python", "numpy" ]
Factorial code not working
38,659,842
<p>Don't know what's wrong, code is giving 12 instead of 24</p> <pre><code>def factorial(x): m=x-1 while m&gt;0: t=x*m m-=1 return t else: return 1 print factorial(4) </code></pre>
-6
2016-07-29T13:13:09Z
38,660,008
<p>your code return value at first iteration and you assign new value to t every iteration </p> <pre><code>def factorial(x): ... t = 1 ... while x&gt;0: ... t *= x ... x-=1 ... ... return t print factorial(4) output: 24 </code></pre> <p>----or----</p> <pre><code>from operator import mu...
1
2016-07-29T13:21:18Z
[ "python" ]
Make undirected graph from adjacency list
38,659,961
<p>I'm trying to make an undirected graph from an adjacency list to practice the Karger's Min Cut algorithm. The following is my code</p> <pre><code>class Vertex(object): '''Represents a vertex, with the indices of edges incident on it''' def __init__(self,name,edgeIndices=[]): self.name = name ...
0
2016-07-29T13:18:59Z
38,661,626
<p>First error comes from the Vertex init. When passing a list as default argument, Python instantiates it once, and share this instance with all future instances of Vertex. Pass None, and use a local list if no list is given.</p> <pre><code>class Vertex(object): def __init__(self,name,edgeIndices=None): s...
0
2016-07-29T14:44:07Z
[ "python", "graph", "undirected-graph" ]
Make undirected graph from adjacency list
38,659,961
<p>I'm trying to make an undirected graph from an adjacency list to practice the Karger's Min Cut algorithm. The following is my code</p> <pre><code>class Vertex(object): '''Represents a vertex, with the indices of edges incident on it''' def __init__(self,name,edgeIndices=[]): self.name = name ...
0
2016-07-29T13:18:59Z
38,664,193
<p>I would recommend to take a look at Dict, OrderedDict, Linked List based graph implementations. The are far more effective then based on lists and indexes. To make you code work you can do the following:</p> <p>Change a Vertex to avoid issue described in previous answer:</p> <pre><code>class Vertex(object): de...
0
2016-07-29T17:13:53Z
[ "python", "graph", "undirected-graph" ]
save() got an unexpected keyword argument
38,660,128
<p>Calling LocationDescription.l_edit returns error "save() got an unexpected keyword argument 'location'". Keyword name looks random though and may point to different fields at different times. The method l_edit was stripped of functionality, but the error persists. Curiously, self.location = kwargs['location'] follow...
1
2016-07-29T13:27:10Z
38,660,288
<p><code>save</code> does not require those named arguments you're passing. Besides, since you're not overriding the default <code>save</code> method I don't see the need for <code>super</code>.</p> <p>You can simply set those attributes on that instance of your model and call <code>save</code> like would with a model...
2
2016-07-29T13:35:26Z
[ "python", "django" ]
python __new__ - how to implement when not subclassing
38,660,148
<p><strong>Part A</strong></p> <p>I want to do some checking on arguments to a class instantiation and possibly return <code>None</code> if it doesn't make sense to even create the object.</p> <p>I've read the docs but I don't understand <strong>what to return</strong> in this case.</p> <pre><code>class MyClass: ...
1
2016-07-29T13:27:53Z
38,660,327
<p>(I'm assuming you are using Python 3 because you provided a link to Python 3 docs)</p> <p><code>X</code> could be <code>super().__new__(cls)</code>.</p> <p><code>super()</code> returns the parent class (in this case it is simply <code>object</code>). Most of the times when you are overriding methods you will need ...
0
2016-07-29T13:37:20Z
[ "python" ]
python __new__ - how to implement when not subclassing
38,660,148
<p><strong>Part A</strong></p> <p>I want to do some checking on arguments to a class instantiation and possibly return <code>None</code> if it doesn't make sense to even create the object.</p> <p>I've read the docs but I don't understand <strong>what to return</strong> in this case.</p> <pre><code>class MyClass: ...
1
2016-07-29T13:27:53Z
38,660,455
<p>You could just return the instance of cls like this <code>return object.__ new__(cls)</code>. Because every class is subclass of <code>object</code>, you can use that as a object creator for your class. The returnes object is passed as a first argument to the <code>__init__()</code> with the any number of positional...
0
2016-07-29T13:43:50Z
[ "python" ]
Keep Columns When Aggregating an Empty DataFrame
38,660,332
<p>I'm working in pandas 0.18.0 on python 2.7.9.</p> <p>Take a sample <code>DataFrame</code> and group by a few columns, then sum over a different column for the result, like this:</p> <pre><code>&gt;&gt;&gt; df = pandas.DataFrame([[1,2,3],[4,5,6],[1,2,9]], columns=['a','b','c']) &gt;&gt;&gt; print df a b c 0 1...
2
2016-07-29T13:37:25Z
38,661,437
<p>I believe this is a standard result of groupby.sum() (see here <a href="http://pandas.pydata.org/pandas-docs/stable/missing_data.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/missing_data.html</a>).</p> <p>The only way I can think would be to write an if statement checking if the dataframe is emp...
1
2016-07-29T14:33:28Z
[ "python", "pandas", "group-by" ]
Rearranging numbers from list in python3
38,660,437
<p>Lets say I have an list of numbers </p> <p>a = [ 1,2,3,4,5,6,7,8,9,10]</p> <p>and I want to print the output as </p> <pre><code>1 2 3 4 5 6 7 8 9 10 </code></pre> <p>How can I do it in python3.</p> <p><strong><em>My attempt:</em></strong></p> <pre><code>a = [1,2,3,4,5,6,7,8,9,10] for i in a: print(a[i]," ...
-3
2016-07-29T13:42:35Z
38,661,254
<p>One way to do this in Python 3 is to use <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>islice</code></a> on an <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow"><code>iterator</code></a> :</p> <pre><code>from itertools import islice a ...
3
2016-07-29T14:25:25Z
[ "python", "list", "python-3.x" ]
Uploading files to S3 bucket - Python Django
38,660,525
<p>I want to put a string (which is an xml response) into a file and then upload it to a amazon s3 bucket. Following is my function in Python3</p> <pre><code>def excess_data(user, resume): res_data = BytesIO(bytes(resume, "UTF-8")) file_name = 'name_of_file/{}_resume.xml'.format(user.id) s3 = S3Storage(buc...
1
2016-07-29T13:47:10Z
38,660,786
<p>I am using <a href="https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html" rel="nofollow">s3boto</a> (requires python-boto) in my Django projects to connect with S3. </p> <p>Using boto is easy to do what you want to do:</p> <pre><code>&gt;&gt;&gt; from boto.s3.key import Key &gt;&gt;&gt; k = Key...
2
2016-07-29T14:00:46Z
[ "python", "django", "amazon-web-services", "amazon-s3" ]
Putting gif image in tkinter window
38,660,528
<p>I'm trying to insert a gif image in a new tkinter window when a button is clicked but I keep getting this error</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\idlelib\run.py", line 119, in main seq, request = rpc.request...
2
2016-07-29T13:47:19Z
38,660,769
<p>You are trying to create two instances of <code>Tk</code> window. You <em>can't</em> do that. If you want second window or pop-up window you should use <a href="http://effbot.org/tkinterbook/toplevel.htm" rel="nofollow">Toplevel()</a> widget.</p> <p>Also, <code>self</code> doesn't mean anything in this context. Usi...
2
2016-07-29T13:59:37Z
[ "python", "python-3.x", "tkinter" ]
Executing root-required script from non-root user
38,660,561
<p>I'm using the Apache CGI mod to allow execution of python scripts via HTTP(S) request. The problem is that the script I want to be executed, <strong>backup.py</strong>, at one point executes a subprocess call where a <strong>mysqldump</strong> command is being piped into <strong>sudo -i</strong>. The problem is that...
1
2016-07-29T13:48:53Z
38,660,731
<p>One way of elevating the permissions for a specific script, is to use the sudoers file.</p> <p>Create a file containing the script you wan't to execute with root permissions, lets say at <code>/path/to/script.sh</code>.</p> <p>Then, edit the <code>sudoers</code> file with <code>sudo visudo</code>, and add the foll...
2
2016-07-29T13:57:49Z
[ "python", "bash", "cgi", "sudo", "sudoers" ]
When/How does an anonymous file object close?
38,660,609
<p>In the comments of <a href="http://stackoverflow.com/questions/38234224/learning-python-the-hard-way-ex-17-i-got-the-one-liner-but?">this question</a> about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question:</p> <pre><code>open(to_file, 'w').write(ope...
4
2016-07-29T13:51:43Z
38,660,804
<p>The files will get closed after the garbage collector collects them, CPython will collect them immediately because it uses reference counting, but this is not a guaranteed behavior.</p> <p>If you use files without closing them in a loop you might run out of file descriptors, that's why it's recommended to use the w...
1
2016-07-29T14:01:47Z
[ "python", "file", "filesystems" ]
When/How does an anonymous file object close?
38,660,609
<p>In the comments of <a href="http://stackoverflow.com/questions/38234224/learning-python-the-hard-way-ex-17-i-got-the-one-liner-but?">this question</a> about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question:</p> <pre><code>open(to_file, 'w').write(ope...
4
2016-07-29T13:51:43Z
38,660,881
<p>Monitoring the file descriptor on Linux (by checking /proc/$$/fds) and the File Handle on Windows (using SysInternals tools) it appears that the file is closed immediately after the statement.</p> <p>This cannot be guarenteed however, since the garbage collector has to execute. In the testing I have done it does g...
4
2016-07-29T14:05:55Z
[ "python", "file", "filesystems" ]
How to run a script as a File in Java?
38,660,690
<p>I have a Python script which is a resource in my project. Along with the script is an XML file that the script needs in order to run properly. I am reading in both files as an InputStream and then creating temp files for both:</p> <pre><code>InputStream is = (this.getClass().getClassLoader().getResourceAsStream("In...
0
2016-07-29T13:55:53Z
38,660,845
<p>Basically, you're asking yourself for trouble since you ask it for the absolute path, but then prefix it with ".", which is generally a <em>relative path</em> modifier. Try <code>.exec(script.getAbsolutePath())</code> for starters. Also, depending on your operating system and/or configuration, <code>.py</code> files...
1
2016-07-29T14:04:21Z
[ "java", "python", "maven" ]
Copy whitespace from string to string in Python
38,660,812
<p>I want to copy whitespace like spaces and tabs from string to string in Python 2. For example if I have a string with 3 spaces at first and one tab at the end like " Hi\t" I want to copy those whitespace to another string for example string like "hello" would become " hello\t" Is that possible to do easily?</p>
0
2016-07-29T14:02:18Z
38,660,996
<p>Yes, this is of course possible. I would use <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regex</a> for that.</p> <pre><code>import re hi = " Hi\t" hello = "hello" spaces = re.match(r"^(\s*).+?(\s*)$", hi) if spaces: left, right = spaces.groups() string = "{}{}{}".format(left, hello,...
1
2016-07-29T14:12:00Z
[ "python", "string", "python-2.7", "whitespace" ]
Python Threading/Thread Implementation
38,660,815
<p>I have been trying to make my first attempt at a threaded script. Its going to eventually be a web scraper that hopefully works a little faster then the original linear scraping script I previously made.</p> <p>After hours of reading and playing with some example code. Im still not sure what is considered correct a...
2
2016-07-29T14:02:25Z
38,661,233
<p>On Python 2.x <a href="https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy" rel="nofollow">multiprocessing.dummy</a> (which uses threads) is a good choice as it is easy to use (also possible in Python 3.x)</p> <p>If you find out scraping is CPU-limited and you have multiple CPU cores...
2
2016-07-29T14:24:12Z
[ "python", "multithreading" ]
pandas read_csv raises ValueError
38,660,900
<p>I want to read txt data seperated by ',' and '\t', and I use code below: </p> <p><code>io_df = pd.read_csv('input_output.txt',sep='\D|\t',engine = 'python')</code></p> <p>This triggered error information below:</p> <p><code>--------------------------------------------------------------------------- ValueError ...
0
2016-07-29T14:06:46Z
38,660,990
<p>For me works <code>sep=",|\t"</code>:</p> <pre><code>pd.read_csv('test.csv', sep=",|\t", engine = 'python') </code></pre> <p>Sample:</p> <pre><code>import pandas as pd df = pd.read_csv('https://dl.dropboxusercontent.com/u/84444599/test.csv', sep=",|\t", engine = 'python') print...
0
2016-07-29T14:11:34Z
[ "python", "pandas" ]
Python __new__ - how can cls be different than class that __new__ is in
38,661,030
<p><a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">Documentation for <code>object.__new__(cls[, ...])</code> says:</a></p> <blockquote> <p>Called to create a new instance of class <code>cls</code>. __ <code>new</code> __ is a static method (special-cased so you need not d...
1
2016-07-29T14:13:32Z
38,661,152
<p>Try this:</p> <pre><code>class MyClass: def __new__(cls): print(cls) class Yac(MyClass): pass x = Yac() print(x) </code></pre> <p>We get:</p> <pre><code>&lt;class '__main__.Yac'&gt; None </code></pre> <p>By the way, this is fine in Python 3, but will not work in Python 2. In Python 2 <code>__n...
2
2016-07-29T14:20:31Z
[ "python" ]
Proper way to use weak references in Python
38,661,039
<p>I have two classes Parent and Child. At any point in time, there will only be one Parent but there can be multiple Child objects. The Parent will need to keep reference to the Child objects in a dictionary indexed by the Child name. The Child also needs a reference to the Parent since it can call one of the Parent's...
0
2016-07-29T14:13:55Z
38,661,345
<p>Do you really need weak references here? If you used your method one with just </p> <pre><code>self.parent = parent </code></pre> <p>you would achieve what you intend to do. A weak reference to parent would allow the parent object to be destroyed if it isn't referenced anywhere strongly anymore, but in this case c...
0
2016-07-29T14:29:33Z
[ "python", "weak-references" ]
Proper way to use weak references in Python
38,661,039
<p>I have two classes Parent and Child. At any point in time, there will only be one Parent but there can be multiple Child objects. The Parent will need to keep reference to the Child objects in a dictionary indexed by the Child name. The Child also needs a reference to the Parent since it can call one of the Parent's...
0
2016-07-29T14:13:55Z
38,661,377
<p>Your two approaches are equivalent, they evaluate to the exact same result.</p> <p>Weak references are used, when you want referred objects to be garbage collected even though your (<em>weak</em>) references do still exist. In your case, your <code>Parent</code> has regular references to your <code>Child</code> ins...
0
2016-07-29T14:31:00Z
[ "python", "weak-references" ]
Proper way to use weak references in Python
38,661,039
<p>I have two classes Parent and Child. At any point in time, there will only be one Parent but there can be multiple Child objects. The Parent will need to keep reference to the Child objects in a dictionary indexed by the Child name. The Child also needs a reference to the Parent since it can call one of the Parent's...
0
2016-07-29T14:13:55Z
38,662,122
<p>In answer to your questions:</p> <ol> <li>Methods 1 and 2 are equivalent.</li> <li>In general, there is no need to call <code>weakref.proxy()</code> directly. In this case you can use a <a href="https://docs.python.org/2/library/weakref.html#weakref.WeakValueDictionary" rel="nofollow" title="WeakValueDictionary">We...
0
2016-07-29T15:11:14Z
[ "python", "weak-references" ]
Splat operator in conjuction with function
38,661,053
<p>I have this program in python which prints the sum of numbers.I have used the splat operator(*). When i print the result i get the result as <strong>None</strong>? Can anyone correct this? I have tried many things like passing multiple arguments but it simply doesn't work.</p> <pre><code> def addition(*no): ...
0
2016-07-29T14:14:42Z
38,661,123
<p>You need to return your <code>sum</code> variable using a <code>return</code> statement:</p> <pre><code>def addition(*no): sum = 0 for n in no: sum=sum+n return sum print addition(4) </code></pre> <p>You're getting <code>None</code> because a function which never uses a <code>return</code> ret...
0
2016-07-29T14:18:46Z
[ "python" ]
Connection closes immediately on open
38,661,067
<p>I am running a very simple echo websocket server as below:</p> <pre><code>#!/usr/bin/python import datetime import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web class WSHandler(tornado.websocket.WebSocketHandler): clients = [] def open(self): print('new con...
4
2016-07-29T14:15:35Z
38,662,232
<p>Not sure if this is helpful in any way, but I ran your code and it works exactly as you would expect it to work. I don't get the connection closed message as indicated in your question, until I call <code>ws.close()</code>. (tornado 4.4.1). </p> <p>Whatever the issue is, it seems to be in your environment, not you...
0
2016-07-29T15:16:48Z
[ "javascript", "python", "websocket", "tornado", "python-3.4" ]
lxml removes unwrapped text inside tag
38,661,087
<p>Here is my python code with lxml</p> <pre><code>import urllib.request from lxml import etree #import lxml.html as html from copy import deepcopy from lxml import etree from lxml import html some_xml_data = "&lt;span&gt;text1&lt;div&gt;ddd&lt;/div&gt;text2&lt;div&gt;ddd&lt;/div&gt;text3&lt;/span&gt;" root = etree....
0
2016-07-29T14:16:52Z
38,661,479
<p>The text after <strong></strong> node is called <strong>tail</strong>, and they can be reserved by appending to parent's text, here is a sample:</p> <pre><code>In [1]: from lxml import html In [2]: s = "&lt;span&gt;text1&lt;div&gt;ddd&lt;/div&gt;text2&lt;div&gt;ddd&lt;/div&gt;text3&lt;/span&gt;" ...: In [3]: ...
1
2016-07-29T14:35:26Z
[ "python", "lxml" ]
Best way to store scraped data in Python for analysis
38,661,144
<p>I am scraping data of football player statistics from the web using python and Beautiful Soup. I will be scraping from multiple sources, and each source will have a variety of variables about each player which include strings, integers, and booleans. For example player name, position drafted, pro bowl pick (y/n).</p...
-1
2016-07-29T14:20:05Z
38,661,572
<p>Use a layered approach: downloading, parsing, storage, analysis.</p> <p>Separate the layers. Most importantly, don't just download data and then store it in the final parsed format. You will inevitably realise you missed something and need to scrape it all over again. Use something like <code>requests</code> + <cod...
1
2016-07-29T14:41:02Z
[ "python", "database", "numpy", "web-scraping" ]
Succinct way to access a single value from a Pandas DataFrame by index
38,661,164
<p>Suppose I have a DataFrame generated like so:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) </code></pre> <p>which looks like</p> <pre><code> C D A 1.764052 0.400157 B 0.978738 2...
2
2016-07-29T14:20:53Z
38,661,204
<p>You can use <code>.at</code> for accessing/setting scalars. Take a look at <a href="http://stackoverflow.com/questions/28757389/loc-vs-iloc-vs-ix-vs-at-vs-iat">this answer</a> for a comparison of them.</p> <pre><code>df Out: C D A 1.764052 0.400157 B 0.978738 2.240893 df.at['A', 'C'] += 1 d...
1
2016-07-29T14:22:27Z
[ "python", "pandas" ]
Succinct way to access a single value from a Pandas DataFrame by index
38,661,164
<p>Suppose I have a DataFrame generated like so:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) </code></pre> <p>which looks like</p> <pre><code> C D A 1.764052 0.400157 B 0.978738 2...
2
2016-07-29T14:20:53Z
38,661,206
<p>You can use <code>loc</code> directly on the col:</p> <pre><code>In [298]: df['C'].loc['A'] += 1 df Out[298]: C D A 2.764052 0.400157 B 0.978738 2.240893 </code></pre> <p>or compound it by passing the row label as first arg on the df and select the col of interest after the comma:</p> <pre>...
3
2016-07-29T14:22:29Z
[ "python", "pandas" ]
Succinct way to access a single value from a Pandas DataFrame by index
38,661,164
<p>Suppose I have a DataFrame generated like so:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) </code></pre> <p>which looks like</p> <pre><code> C D A 1.764052 0.400157 B 0.978738 2...
2
2016-07-29T14:20:53Z
38,661,211
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p> <pre><code>np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) df.ix['A','C'] += 1 print (df) C D A 2.764052 ...
2
2016-07-29T14:22:47Z
[ "python", "pandas" ]
How to open folder and place text files in dataframe and rename dataframe based on file name?
38,661,182
<p>I am trying to open a folder which has multiple text files and put each file in its own dataframe and name each dataframe by the filename. </p> <p>My code so far is recognizing the 5 files in the folder but is not putting the data in the files into dataframes based on their file names. could someone show me how to ...
1
2016-07-29T14:21:32Z
38,661,520
<p>Something like this should create a dict where each key (= filename) holds the dataframe with the respective file's contents.</p> <pre><code>filedfs = {} for f in files: filedfs[f] = pd.read_csv(os.path.join(loc, f)) </code></pre> <p>Or, as a one-liner as proposed by @MaxU:</p> <pre><code>dfs = {os.path.basename(...
4
2016-07-29T14:37:21Z
[ "python", "pandas", "dataframe", "python-3.5" ]
How to open folder and place text files in dataframe and rename dataframe based on file name?
38,661,182
<p>I am trying to open a folder which has multiple text files and put each file in its own dataframe and name each dataframe by the filename. </p> <p>My code so far is recognizing the 5 files in the folder but is not putting the data in the files into dataframes based on their file names. could someone show me how to ...
1
2016-07-29T14:21:32Z
38,661,619
<p><strong><em>input:</em></strong></p> <pre><code>0010010000013,1,CITY OF HOUSTON,1.000 0010020000001,1,CURRENT OWNER,1.000 </code></pre> <p><strong><em>code:</em></strong></p> <pre><code>import os import pandas loc = 'folder/' list_of_df = [] for f in os.listdir(loc): if f.endswith(".txt"): df = pa...
0
2016-07-29T14:43:46Z
[ "python", "pandas", "dataframe", "python-3.5" ]
FileNotFoundError WinError 3
38,661,464
<p>I'm trying to learn how to edit files, but I'm a bit of a python novice, and not all that bright, so when I get a FileNotFoundError I can't figure out how to fix it despite several searches on the interwebz.</p> <pre><code>import os old = 'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n' new = 'Us...
-1
2016-07-29T14:34:54Z
38,661,671
<p><code>'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n'</code> is a relative path. </p> <p>Unless you are running your code from the directory that contains the <code>Users</code> dir (which if you are using Windows would most probably be the root <code>C:</code> dir), Python isn't going to find th...
1
2016-07-29T14:46:55Z
[ "python", "windows-7", "rename" ]
Some anomaly in printing result for list
38,661,490
<p>Hi I have two list snip and phras. I tried to run them in for loop in two different ways. I was expecting them to give the same output but they are giving different. How so ?</p> <pre><code>snip = ['Hi john', 'Hi sam', 'Hi lila'] phras = ['lets play','lets paint'] for s in snip,phras: result = s[:] print resu...
-5
2016-07-29T14:35:47Z
38,661,532
<p>Your print statement is outside of your first loop so it only shows the last value assigned to <code>result</code> whereas the second print statement is inside of the loop and therefore prints <em>each</em> value of <code>result</code></p>
5
2016-07-29T14:38:01Z
[ "python", "python-2.7" ]
how to predict binary outcome with categorical and continuous features using scikit-learn?
38,661,631
<p>I need advice choosing a model and machine learning algorithm for a classification problem. </p> <p>I'm trying to predict a binary outcome for a subject. I have 500,000 records in my data set and 20 continuous and categorical features. Each subject has 10--20 records. The data is labeled with its outcome.</p> <p>S...
1
2016-07-29T14:44:28Z
38,666,799
<p>Choosing an algorithm and optimizing the parameter is a difficult task in any data mining project. Because it must customized for your data and problem. Try different algorithm like SVM,Random Forest, Logistic Regression, KNN and... and test Cross Validation for each of them and then compare them. You can use <a hre...
0
2016-07-29T20:13:37Z
[ "python", "machine-learning" ]
how to predict binary outcome with categorical and continuous features using scikit-learn?
38,661,631
<p>I need advice choosing a model and machine learning algorithm for a classification problem. </p> <p>I'm trying to predict a binary outcome for a subject. I have 500,000 records in my data set and 20 continuous and categorical features. Each subject has 10--20 records. The data is labeled with its outcome.</p> <p>S...
1
2016-07-29T14:44:28Z
38,671,098
<h2>Features</h2> <p>If your categorical features don't have too many possible different values, you might want to have a look at <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow"><code>sklearn.preprocessing.OneHotEncoder</code></a>.</p> <h2>Model choic...
0
2016-07-30T06:37:02Z
[ "python", "machine-learning" ]
ctypes struct returned from library
38,661,635
<p>Given a simple C file:</p> <pre><code>#include &lt;stdio.h&gt; typedef struct point { int x; int y; } POINT; POINT get_point() { POINT p = {1, 2}; return p; } </code></pre> <p>And I have a simple python file:</p> <pre><code>from ctypes import * import os lib_name = '/testlib.so' test_lib = C...
1
2016-07-29T14:44:37Z
38,663,141
<p>What you ar asking is nto the sole problem in your example. Just to answer just what you asked first: you have to annotate the C function return type, so that ctypes know it is a memory address - otherwise it is a (4 byte) integer by default (while in any 64 byte OS, pointers are 8 bytes long).</p> <p>Then you can ...
1
2016-07-29T16:05:45Z
[ "python", "c", "python-2.7", "wrapper", "ctypes" ]
Issue with a global variable setting
38,661,669
<p>The program is supposed to update the value of the global variable <code>int_choice</code> every time a player scores (it's a pong game)</p> <p><code>int_choice</code> can only have a value of 1 or 0. If it's 1, the function <code>left_or_right</code> "tells" the ball to go right, if it's 0, the ball goes left.</p>...
0
2016-07-29T14:46:54Z
38,661,817
<p>Your problem exists because you update the variable at the wrong time in your code. Let's look at an example of what happens after a game ends.</p> <pre><code>int_choice = 0 spawn_ball(direc) </code></pre> <p>You set int_choice to 0, then you call spawn_ball(direc), but direc is the <strong>old</strong> direction ...
1
2016-07-29T14:54:34Z
[ "python", "global-variables", "pong" ]
Issue with a global variable setting
38,661,669
<p>The program is supposed to update the value of the global variable <code>int_choice</code> every time a player scores (it's a pong game)</p> <p><code>int_choice</code> can only have a value of 1 or 0. If it's 1, the function <code>left_or_right</code> "tells" the ball to go right, if it's 0, the ball goes left.</p>...
0
2016-07-29T14:46:54Z
38,661,849
<p>You pass in the <strong>old</strong> value of <code>direc</code>, before <code>left_or_right</code> is called.</p> <p>Say, you set <code>int_cohice</code> to 1:</p> <pre><code>int_choice = 1 spawn_ball(direc) # old value of `direc`, nothing changed this yet </code></pre> <p>then in <code>spawn_ball()</code>:</p>...
4
2016-07-29T14:56:09Z
[ "python", "global-variables", "pong" ]
Where is the xml file generated saved after running xmlrunner?
38,661,688
<p>I have my unittest suite and this piece of code. Where is the xml file saved?</p> <pre><code> if __name__ == '__main__': unittest.main(verbosity=2, testRunner=xmlrunner.XMLTestRunner(filename='test-reports.xml')) </code></pre> <p>Thanks in advance</p>
0
2016-07-29T14:47:45Z
39,506,176
<p>The problem was that I was running the tests with PyCharm's predefined running settings for unittest, however this requires the following command to run and generate the files:</p> <pre><code>python -m &lt;name-of-the-test&gt; </code></pre>
0
2016-09-15T08:16:34Z
[ "python", "unit-testing" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"Non...
1
2016-07-29T14:48:09Z
38,661,814
<p>You can use the following <em>positive lookahead</em> assertion <code>'\\(?=")'</code>:</p> <pre><code>import re my_str = "\"abc INC\\\",\"None\", \"0\", \"test\"" p = re.sub(r'\\(?=")', '|', my_str) print(p) # '"abc INC|","None", "0", "test"' </code></pre> <p>Try not to use builtin names as names for variables, ...
0
2016-07-29T14:54:29Z
[ "python", "regex", "python-3.x" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"Non...
1
2016-07-29T14:48:09Z
38,661,827
<p>See Jamie Zawinksi's <a href="https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/" rel="nofollow">famous quote about regular expressions</a>. Try to only resort to the use of re's when absolutely necessary. In this case, it isn't.</p> <p>The actual content of string <code>str</code> (bad na...
2
2016-07-29T14:55:07Z
[ "python", "regex", "python-3.x" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"Non...
1
2016-07-29T14:48:09Z
38,662,101
<p>This must solve your problem:</p> <pre><code>import re s = "\"abc INC\\\",\"None\", \"0\", \"test\"" s = re.sub(r"\\", "|", s) </code></pre> <p>Also don't use str as a variable name, it is a reserved keyword.</p>
0
2016-07-29T15:09:53Z
[ "python", "regex", "python-3.x" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"Non...
1
2016-07-29T14:48:09Z
38,662,113
<p>For literal backslashes in python regexes you need to escape twice, giving you the pattern <code>'\\\\"'</code> or <code>"\\\\\""</code>. The first escaping is needed for python to actually put a backslash into the string. But regex patterns themself use backshlashes as a special character (for things like <code>\w...
0
2016-07-29T15:10:45Z
[ "python", "regex", "python-3.x" ]
how to convert a scientific notation number preserving precision
38,661,903
<p>I have a some numbers like:</p> <pre><code>1.8816764231589208e-06 &lt;type 'float'&gt; </code></pre> <p>how I can convert to </p> <pre><code>0.00000018816764231589208 </code></pre> <p>Preserving all precision</p>
-1
2016-07-29T14:58:40Z
38,662,359
<p>This is not an easy problem, because binary floating point numbers cannot always represent decimal fractions exactly, and the number you have chosen is one such.</p> <p>Therefore, you need to know how many digits of precision you want. In your exact case, see what happens when I try to print it with various formats...
1
2016-07-29T15:23:52Z
[ "python", "math", "scientific-notation" ]
how to convert a scientific notation number preserving precision
38,661,903
<p>I have a some numbers like:</p> <pre><code>1.8816764231589208e-06 &lt;type 'float'&gt; </code></pre> <p>how I can convert to </p> <pre><code>0.00000018816764231589208 </code></pre> <p>Preserving all precision</p>
-1
2016-07-29T14:58:40Z
38,662,807
<p>The value you presented is not properly stored as Rory Daulton suggests in his comment. So your float <code>1.8816764231589208e-06 &lt;type 'float'&gt;</code> could be explained by this example:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; a = 1.8816764231589208e-06 &gt;&gt;&gt; g = 0.00000...
0
2016-07-29T15:48:01Z
[ "python", "math", "scientific-notation" ]
Why is python 3 looking in my python 2.7 package directory for packages?
38,661,908
<p>OS (Linux): Ubuntu 14.04.4 LTS</p> <p>For some reason, my python 3.5.2 is looking into the python 2.7 packages directory instead of its own:</p> <pre><code>] python3 -m ensurepip Ignoring indexes: https://pypi.python.org/simple Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/loca...
5
2016-07-29T14:58:56Z
38,666,432
<p>PYTHONPATH might have been set to 2.7 distribution packages, which might be causing this.</p>
1
2016-07-29T19:45:42Z
[ "python", "python-3.x", "pip", "python-3.5", "python-3.5.2" ]
Rock Paper Scissors 2 player
38,661,984
<p>Here is my code for my 2 player game. What I'm having trouble with is no matter what, player 2 always wins and gives points to player 2. Can someone help me make it so Player 1 can also win and be assigned points.</p> <pre><code>def vshuman(): score = [0,0] while True: while True: user1_ch...
-1
2016-07-29T15:03:14Z
38,662,445
<pre><code>score = [0,0] while 1: c1 = int(input("Player 1 choose a weapon (1,2,3) : ")) c2 = int(input("Player 2 choose a weapon (1,2,3) : ")) if c1 == c2: print('tie') score[0] += 1 score[1] += 1 elif (c1 - 1) % 3 == c2 % 3: print('Player 1 won') score[0] += 1 ...
0
2016-07-29T15:27:48Z
[ "python" ]
How to update a PySpark RDD of dictionaries based on some condition
38,662,209
<p>Firstly I understand the concept of persistent data structures and immutability with regards to RDD's.. update is the only word I could think of :)</p> <p>My question is:</p> <p>Given an RDD of dictionaries (or Row objects) how can I loop/map across and apply some transformation login on that RDD and receive back ...
1
2016-07-29T15:15:56Z
38,662,423
<ul> <li><code>update_virtual_cash_balance</code> doesn't return anything so you get <code>None</code></li> <li><code>update</code> method doesn't return anything so you would get <code>None</code> even if <code>update_virtual_cash_balance</code> returned value</li> <li>you shouldn't modify data in place. RDD is immuta...
1
2016-07-29T15:26:49Z
[ "python", "pyspark" ]
Using functions with raw inputs
38,662,274
<p>I was experimenting with what I have learned so far and I wanted to create something that is interactive, using <code>raw_input()</code>. </p> <p>What I wanted to do was creating a function that will create a conversation which will go different directions based on input. However, I was unable to figure out how to ...
1
2016-07-29T15:19:22Z
38,662,406
<p>Are you looking for something like this?</p> <pre><code>drink = raw_input("Coffee or Tea?") def drinktype(drink): if drink == "Coffee": usercoffeetype = raw_input("What type of coffee do you drink?") coffee(usercoffeetype) elif drink == "Tea": print "Here is your tea." else: ...
0
2016-07-29T15:26:07Z
[ "python", "function" ]
Using functions with raw inputs
38,662,274
<p>I was experimenting with what I have learned so far and I wanted to create something that is interactive, using <code>raw_input()</code>. </p> <p>What I wanted to do was creating a function that will create a conversation which will go different directions based on input. However, I was unable to figure out how to ...
1
2016-07-29T15:19:22Z
38,662,434
<p>The request for americano or latte is something you only need to do if coffee is requested; it is irrelevant if the user requests tea. Once that is moved under the Coffee case, you can simply pass the returned value to your call to <code>coffee()</code>. The return value also needs to be printed.</p> <pre><code>def...
1
2016-07-29T15:27:16Z
[ "python", "function" ]
Using functions with raw inputs
38,662,274
<p>I was experimenting with what I have learned so far and I wanted to create something that is interactive, using <code>raw_input()</code>. </p> <p>What I wanted to do was creating a function that will create a conversation which will go different directions based on input. However, I was unable to figure out how to ...
1
2016-07-29T15:19:22Z
38,662,502
<p>Looks like you are trying to get something like the following</p> <pre><code>def coffee(): x = raw_input("Americano or Latte?") if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." def dri...
0
2016-07-29T15:31:20Z
[ "python", "function" ]
Unexpected '{' in field name when doing string formatting
38,662,296
<p>I'm trying to write a small script that will automate some PHP boilerplate that I need to write. It should write a copy of the string <code>code</code> to the output file with the various replacement fields filled in for each dict in the <code>fields</code> list.</p> <p>However, I'm getting the error:</p> <pre><co...
1
2016-07-29T15:20:29Z
38,662,335
<p>You need to <em>double</em> any <code>{</code> or <code>}</code> that are not part of a formatting placeholder. For example, you have:</p> <pre><code>function admin_add_{fieldname}_field( $fields ) { [....] } </code></pre> <p>in the string. The <code>{</code> and <code>}</code> there are not part of a placehol...
4
2016-07-29T15:22:28Z
[ "python", "python-3.x", "string-formatting" ]
Python: Is it possible to create a package out of multiple external libraries?
38,662,331
<p>This issue has been driving me insane for the past few days.</p> <p>So basically, I'm trying to port over a Pure Python project to a proper PyCharm project. This is to basically improve code quality and project structure. </p> <p>I wish it was as simple as basically creating a virtualenv to house everything, but i...
0
2016-07-29T15:22:19Z
38,670,374
<p><strong>Note: Not full solution.</strong></p> <p>The addition of the template code below forces the file containing the code to be in the same directory as the libs folder.</p> <p>For Pycharm, all I had to do was mark the libs folder as a source folder. Even with the addition of the template code to the file, the ...
0
2016-07-30T04:36:32Z
[ "python", "git", "pycharm", "packages" ]
How to speed this up: Searching through multiple lists of dates to find closest match. [Python]
38,662,494
<p>I have one list of dates, <code>master_time</code>. For each date in <code>master_time</code>, I am searching for the closest match in four other lists of dates; <code>time1</code>,<code>time2</code>,<code>time3</code>, and <code>time4</code>. The results are appended to "closestmatch" lists which will later be used...
0
2016-07-29T15:31:01Z
38,665,727
<pre><code>import random def find_best_match(master_list, secondary_list): master_list.sort() secondary_list.sort() secondary_len = len(secondary_list) - 1 secondary_index = 0 closests = [] for master_value in master_list: while True: delta_current = abs(master_value - sec...
0
2016-07-29T18:51:51Z
[ "python", "datetime", "search", "matching" ]
pandas.DataFrame.replace with wildcards
38,662,509
<p>Does the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>pandas.DataFrame.replace</code></a> regex replace support wildcards and "capture groups"?</p> <p>E.g., to replace <code>([A-Z])(\w+)</code> with <code>\2\1</code>?</p> <p>What kind of regular...
3
2016-07-29T15:31:35Z
38,662,618
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">pandas documentation</a>:</p> <blockquote> <p>Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same.</p> </blockquote> <p>So, yes,...
2
2016-07-29T15:37:31Z
[ "python", "regex", "pandas", "replace", "dataframe" ]
NameError: name 'Name' is not defined in django form
38,662,514
<p>I want to render the following form but django throws out a error and i dont understand why. Thanks in advance. </p> <p>forms.py:</p> <pre><code>from django import forms from .models import equipment class neweqForm(forms.ModelForm): class Meta: model = equipment name = forms.CharField(labe...
0
2016-07-29T15:31:55Z
38,662,572
<p>You are having <code>label</code> for each field, but you are using <code>Name</code>, <code>Hersteller</code>, etc to assign the value. You might have major misunderstanding about variables and strings. If you don't quote something, they are treated as variables in python. But they not defined anywhere else, so pyt...
3
2016-07-29T15:34:57Z
[ "python", "django" ]
Improve parsing speed of delimited configuration block
38,662,521
<p>I have a quite large configuration file that consists of blocks delimited by</p> <p><code>#start &lt;some-name&gt; ... #end &lt;some-name&gt;</code> were <code>some-name</code> has to be the same for the block. The block can appear multiple times but is never contained within itself. Only some other blocks may appe...
1
2016-07-29T15:32:18Z
38,679,130
<p>First of all, this code as posted doesn't work for me:</p> <pre><code>blocks = Keyword('#start') + block </code></pre> <p>Changing to this:</p> <pre><code>blocks = Keyword('#start') + MatchFirst(block) </code></pre> <p>at least runs against your sample text.</p> <p>Rather than hard-code all the keywords, you ca...
1
2016-07-30T22:40:00Z
[ "python", "pyparsing" ]
I can't install pycharm due to Sub-process /usr/bin/dpkg returned an error code (1)
38,662,559
<p>I've recently install anaconda and I'm using PyCharm as my IDE, but when I go to import some modules, they don't seem to exist, even though they were downloaded with anaconda. When I tried to download Matplotlib via the terminal I get this </p> <pre><code> Errors were encountered while processing: python-six pyth...
1
2016-07-29T15:34:09Z
38,662,632
<p>Below codes can be solved your problem;</p> <pre><code>sudo apt-get clean sudo apt-get install -f </code></pre>
0
2016-07-29T15:38:17Z
[ "python", "matplotlib", "pycharm", "anaconda" ]
lpsolve - results are different every time I change the order of constraints
38,662,613
<p>I have noticed a strange behaviour of lpsolve library (using it in python 3.4).</p> <p>When I <strong>change the order of constraints</strong> which I add to the lpsolve model the results are also slightly different.</p> <p>Will be glad for any hints why this is happening.</p> <p>Adding both models to reproduce t...
1
2016-07-29T15:37:02Z
38,665,683
<p>This could be because your model is not completely numerically stable. You probably have inputs variable who are not in the same range (eg: x1 can be -1..+1 and x2 can be -1000000..+1000000)</p>
1
2016-07-29T18:48:47Z
[ "python", "lpsolve" ]
Getting Turtle in Python to recognize click events
38,662,630
<p>I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the screen and try again. I've tried a couple different options ...
0
2016-07-29T15:38:16Z
38,663,552
<p>I'm assuming that your using <strong>Turtle</strong> in python(hence the name.) If that's the case, Here's a link to a helpful post: <a href="http://stackoverflow.com/questions/17864085/turtle-in-python-trying-to-get-the-turtle-to-move-to-the-mouse-click-position-a">Turtle in python- Trying to get the turtle to move...
0
2016-07-29T16:30:56Z
[ "python", "turtle-graphics" ]
Getting Turtle in Python to recognize click events
38,662,630
<p>I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the screen and try again. I've tried a couple different options ...
0
2016-07-29T15:38:16Z
38,664,006
<p>Assuming you're using <code>turtle</code> as mentioned in your title:</p> <pre><code>&gt;&gt;&gt; import turtle &gt;&gt;&gt; help(turtle.onscreenclick) Help on function onscreenclick in module turtle: onscreenclick(fun, btn=1, add=None) Bind fun to mouse-click event on canvas. Arguments: fun -- a fun...
0
2016-07-29T17:01:23Z
[ "python", "turtle-graphics" ]
Getting Turtle in Python to recognize click events
38,662,630
<p>I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the screen and try again. I've tried a couple different options ...
0
2016-07-29T15:38:16Z
38,676,484
<p>As well intentioned as the other answers are, I don't believe either addresses the actual problem. You've locked out events by introducing an infinite loop in your code:</p> <pre><code>is_winner = False while is_winner == False: </code></pre> <p>You can't do this with turtle graphics -- you set up the event handl...
1
2016-07-30T17:10:35Z
[ "python", "turtle-graphics" ]
Return with argument inside generator
38,662,643
<p>I know there's a similar question already asked, but doesn't answer what I need, as mine is a little different.</p> <p>My code:</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: return json.load(f) for line in f: yield line.rstrip('\n...
3
2016-07-29T15:38:43Z
38,662,904
<p>The first solution that came to my mind was to explicitly return a generator object which would provide the exact behavior you tried to achieve.</p> <p>The problem is: if you explicitly returned a generator object like this <code>return (line.rstrip('\n') for line in f)</code> the file would be closed after returni...
1
2016-07-29T15:52:34Z
[ "python", "json", "generator", "readfile" ]
Return with argument inside generator
38,662,643
<p>I know there's a similar question already asked, but doesn't answer what I need, as mine is a little different.</p> <p>My code:</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: return json.load(f) for line in f: yield line.rstrip('\n...
3
2016-07-29T15:38:43Z
38,663,237
<p>You could <code>yield from</code> the dictionary loaded with JSON, thus iterating over the key-value-pairs in the dict, but this would not be your desired behaviour.</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: yield from json.load(f).items() # work...
0
2016-07-29T16:12:14Z
[ "python", "json", "generator", "readfile" ]
Finding Row with No Empty Strings
38,662,656
<p>I am trying to determine the type of data contained in each column of a <code>.csv</code> file so that I can make <code>CREATE TABLE</code> statements for MySQL. The program makes a list of all the column headers and then grabs the first row of data and determines each data type and appends it to the column header f...
0
2016-07-29T15:39:08Z
38,663,479
<p>I cannot really decipher your code. This is what I would do to only get rows without the empty string.</p> <pre><code>import csv def g(name): with open('file.csv', 'r') as f: r = csv.reader(f) # Skip headers row = next(r) for row in r: if '' not in row: ...
2
2016-07-29T16:25:48Z
[ "python", "python-3.x", "csv" ]
matplotlib and subplots properties
38,662,667
<p>I'm adding a matplotlib figure to a canvas so that I may integrate it with pyqt in my application. I were looking around and using <code>plt.add_subplot(111)</code> seem to be the way to go(?) But I cannot add any properties to the subplot as I may with an "ordinary" plot</p> <p>figure setup</p> <pre><code>self.fi...
1
2016-07-29T15:39:57Z
38,662,845
<p><code>plt.subplot</code> returns a subplot object which is a type of axes object. It has two methods for adding axis labels: <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xlabel" rel="nofollow"><code>set_xlabel</code></a> and <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axe...
2
2016-07-29T15:49:36Z
[ "python", "matplotlib" ]
Summing values from array and get a double
38,662,685
<p>I'm trying to run this loop to get <code>n</code> to be a decimal number. However, if I call values from the vector <code>p</code>, <code>n</code> also becomes a vector. </p> <p>How do I fix that?</p> <p>lamb=linspace(400,800,num=20)</p> <pre><code>for k in 1/lamb: AR2 = 1.55 p = [-0.003396, 0.6518, 66.0...
0
2016-07-29T15:41:07Z
38,662,843
<p><code>linspace(400,800,num=20)</code> is an array. Performing operations on it does it element-wise. For example:</p> <pre><code>&gt;&gt;&gt; linspace(400,800,num=20) array([ 400. , 421.05263158, 442.10526316, 463.15789474, 484.21052632, 505.26315789, 526.31578947, 547.36842105, 568.42105263, ...
1
2016-07-29T15:49:32Z
[ "python", "arrays", "loops", "for-loop", "vector" ]
Summing values from array and get a double
38,662,685
<p>I'm trying to run this loop to get <code>n</code> to be a decimal number. However, if I call values from the vector <code>p</code>, <code>n</code> also becomes a vector. </p> <p>How do I fix that?</p> <p>lamb=linspace(400,800,num=20)</p> <pre><code>for k in 1/lamb: AR2 = 1.55 p = [-0.003396, 0.6518, 66.0...
0
2016-07-29T15:41:07Z
38,663,053
<p>If I set <code>lamb</code> and <code>AR2</code> to be numbers then I don't see <code>n</code> becoming an array i.e </p> <pre><code>AR2 = 1.55 p = [-0.003396, 0.6518, 66.01, 2435] n = 0.00 lamb = 0.97 AR2 = 1 for i in range(0, 3): n = n + AR2+ p[i]*lamb**(10-i) print(n) </code></pre> <p>Returns: </p> ...
0
2016-07-29T16:00:11Z
[ "python", "arrays", "loops", "for-loop", "vector" ]
Array Map to a unique key after discretization
38,662,744
<p>I have A 1D numpy observation array example [a,b,c,d]. a,b,c,d takes continous values, with each of them belonging to different finite domain.Example a lies from -2. to 2. etc.</p> <p>My goal is to map any such observation to a single number. Example [1,2,-3,4] and [1,2,-2.7,4] gets mapped to same number x, with t...
0
2016-07-29T15:44:15Z
38,664,358
<p>If your discretization process is taking the nearest whole number (rounding towards minus infinity rather than towards zero) then you could do something like this</p> <pre><code>&gt;&gt;&gt; a = np.array([-1.6, -0.5, 1.2, 2.2]) &gt;&gt;&gt; (np.floor(a + 0.5) * [1000, 100, 10, 1]).sum() -1988.0 </code></pre>
0
2016-07-29T17:25:56Z
[ "python", "arrays", "numpy" ]
wxpython wx.Slider: how to fire an event only if a user pauses for some predetermined time
38,662,800
<p>I have a <code>wx.Slider</code> widget that is bound to an event handler. As a user moves the slider, some process will run. However, because the process can take up to 3 seconds to run, I don't want the event to fire continuously as the user moves the slider. Instead, I want the event to fire only if the user stops...
0
2016-07-29T15:47:25Z
38,666,741
<p>Delaying with <code>time.sleep</code> will block your GUI. Use <code>wx.CallLater</code> instead, which in the sample below will trigger the delayed event until it has been restarted again.</p> <pre><code> def InitUi(self): # ... # Add a delay timer, set it up and stop it self.delay_slid...
1
2016-07-29T20:09:49Z
[ "python", "events", "event-handling", "slider", "wxpython" ]
Sort pandas DataFrame with function over column values
38,662,826
<p>Based on <a href="http://stackoverflow.com/questions/24988873/python-sort-descending-dataframe-with-pandas">python, sort descending dataframe with pandas</a>:</p> <p>Given:</p> <pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b...
2
2016-07-29T15:48:43Z
38,663,274
<p>Have you tried to create a new column and then sorting on that. I cannot comment on the original post, so i am just posting my solution.</p> <pre><code>df['c'] = df.a**2 + df.b**2 df = df.sort_values('c') </code></pre>
0
2016-07-29T16:14:37Z
[ "python", "sorting", "pandas", "dataframe" ]
Sort pandas DataFrame with function over column values
38,662,826
<p>Based on <a href="http://stackoverflow.com/questions/24988873/python-sort-descending-dataframe-with-pandas">python, sort descending dataframe with pandas</a>:</p> <p>Given:</p> <pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b...
2
2016-07-29T15:48:43Z
38,663,354
<p>You can create a temporary column to use in sort and then drop it:</p> <pre><code>df.assign(f = df['one']**2 + df['two']**2).sort_values('f').drop('f', axis=1) Out: letter one two 2 b 1 3 3 b 4 2 1 a 3 4 4 c 5 1 0 a 2 5 </code></pre>
3
2016-07-29T16:18:44Z
[ "python", "sorting", "pandas", "dataframe" ]
Sort pandas DataFrame with function over column values
38,662,826
<p>Based on <a href="http://stackoverflow.com/questions/24988873/python-sort-descending-dataframe-with-pandas">python, sort descending dataframe with pandas</a>:</p> <p>Given:</p> <pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b...
2
2016-07-29T15:48:43Z
38,663,355
<pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b','c']} df = pd.DataFrame(d) #f = lambda x,y: x**2 + y**2 array = [] for i in range(5): array.append(df.ix[i,1]**2 + df.ix[i,2]**2) array = pd.DataFrame(array, columns = ['Sum ...
1
2016-07-29T16:18:44Z
[ "python", "sorting", "pandas", "dataframe" ]
Directory browser and entry bar using Tkinter
38,662,829
<p>I have managed to have an opening page, followed by a second page which contains a file browser button. I would like to have the option for user entry to this file browser (copy and paste into an entry bar). Following either the directory being user entered, or browsed using the button, I would like the directory to...
0
2016-07-29T15:49:04Z
38,663,497
<p>I believe this is a duplicate of <a href="http://stackoverflow.com/questions/25282883/how-can-i-use-the-output-from-tkfiledialog-askdirectory-to-fill-a-tkinter-entry">this question</a>. What it boils down to is the following.</p> <ol> <li><p>Create a <a href="http://effbot.org/tkinterbook/variable.htm" rel="nofollo...
1
2016-07-29T16:27:18Z
[ "python", "tkinter", "entry", "file-browser" ]
how to query sympy constraints?
38,662,859
<p>At some point in my code, I add an upper constraint on a sympy symbol. <code>sympy.refine(x, sympy.Q.positive(upper_bound - x))</code></p> <p>I would liketo retrieve programmaticaly from the symbol "x" the value of upper_bound (and other constraints). Any idea as how to achieve this ?</p> <p>cheers</p>
2
2016-07-29T15:50:21Z
38,735,025
<p>The refine function does not work that way - it just simplifies an expression given a constraint. For example:</p> <pre><code>In [54]: import sympy In [55]: x = sympy.S('x') In [56]: expr = sympy.S('sqrt(x**2)') In [57]: sympy.refine(expr, sympy.Q.positive(x)) Out[57]: x In [58]: sympy.refine(expr, sympy.Q.nega...
1
2016-08-03T05:24:18Z
[ "python", "sympy" ]
Create array with elements inserted without using np.insert
38,662,999
<p>I have two arrays, say,</p> <pre><code>n = [1,2,3,4,5,6,7,8,9] nc = [3,0,2,0,1,2,0,0,0] </code></pre> <p>The nonzero elements in nc are <code>ncz = [3,2,1,2]</code>. The elements in n corresponding to non zero elements in nc are <code>p = [1,3,5,6]</code>. I need to create a new array with elements of <code>p[1:]<...
0
2016-07-29T15:57:37Z
38,667,908
<p>Because of its generality <code>np.insert</code> is rather complex (but available for study), but for your case, with a 1d array, and order insert points, it can be simplified to</p> <p><code>np.insert(n, i, p1)</code> with:</p> <pre><code>In [688]: n Out[688]: array([1, 2, 3, 4, 5, 6, 7, 8, 9]) In [689]: p1 Out[6...
1
2016-07-29T21:44:09Z
[ "python", "arrays", "numpy" ]
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However...
6
2016-07-29T15:59:48Z
38,663,883
<p>First time answering a Question here (if I made a mistake please indicate).But it would seems that what David commented is correct in that "star is always in list1 (and s is always in list2". So I would suggest comparing and appending to a newlist1/newlist1 that keeps track of star and s.</p> <pre><code>newlist1 = ...
0
2016-07-29T16:53:51Z
[ "python", "numpy" ]
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However...
6
2016-07-29T15:59:48Z
38,664,333
<p>I would change your approach entirely to fit the fact that these are astronomical objects you are talking about. I will ignore the loading functionality and assume that you already have your input lists <code>Astar</code> and <code>wStar</code>.</p> <p>We will find the <em>closest</em> star in <code>wStar</code> to...
1
2016-07-29T17:24:30Z
[ "python", "numpy" ]
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However...
6
2016-07-29T15:59:48Z
38,665,487
<p>I haven't fully absorbed your issues, but I'll start with trying to simplify your calculation.</p> <p>Looks like <code>Apstars</code> and <code>data1</code> are structured arrays, both 1d with the same <code>dtype</code>.</p> <p>This list iteration could be replaced with:</p> <pre><code>Astars = list() for s in A...
0
2016-07-29T18:36:27Z
[ "python", "numpy" ]