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
comparing two pandas dataframes with list in column
39,148,941
<p>I have two data frames df1 and df2:</p> <pre><code>df1 : Name A_list abcd (apple,orange,banana) bcde (orange,mango) cdef (apple,pineapple) df2 : City B_list C1 (apple,mango,banana) C2 (mango) C3 (pineapple,banana) </code></pre> <p>I want to make a new dataframe df3</p> <pre><code>Name A_list City abcd (apple,orange,banana) (C1,C3) bcde (orange,mango) (C1,C2) cdef (apple,pineapple) (C1,C3) </code></pre> <p>i.e going through A_list in Df1 and identifying the City from which each fruit came. I am not sure how to merge df1 and df2 using the lists A_list and B_list</p>
0
2016-08-25T15:14:14Z
39,150,169
<h3>Setup</h3> <pre><code>df1 = pd.DataFrame([ ['abcd', ('apple', 'orange', 'banana')], ['bcde', ('orange', 'mango')], ['cdef', ('apple', 'pineapple')] ], columns=['Name', 'A_list']) df2 = pd.DataFrame([ ['C1', ('apple', 'mango', 'banana')], ['C2', ('mango')], ['C3', ('pineapple', 'banana')] ], columns=['City', 'B_list']) </code></pre> <p><strong><em>massage data</em></strong></p> <pre><code>s2 = df2.set_index('City').squeeze() \ .apply(pd.Series) \ .stack().reset_index(1, drop=True) s2 City C1 apple C1 mango C1 banana C2 mango C3 pineapple C3 banana dtype: object </code></pre> <hr> <pre><code>s1 = df1.set_index('Name').squeeze() \ .apply(pd.Series) \ .stack().reset_index(1, drop=True) s1 Name abcd apple abcd orange abcd banana bcde orange bcde mango cdef apple cdef pineapple dtype: object </code></pre> <hr> <pre><code>df3 = pd.merge(*[s.rename('fruit').reset_index() for s in [s1, s2]]) df3 </code></pre> <p><a href="http://i.stack.imgur.com/kQzTW.png" rel="nofollow"><img src="http://i.stack.imgur.com/kQzTW.png" alt="enter image description here"></a></p> <pre><code>def tuplify(series): return tuple(set(series)) df3.groupby('Name') \ .apply(lambda df: df.drop('Name', axis=1).apply(tuplify)) \ .rename(columns=dict(fruit='A_list')).reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/Apbuz.png" rel="nofollow"><img src="http://i.stack.imgur.com/Apbuz.png" alt="enter image description here"></a></p> <p>Notice that <code>'orange'</code> is missing because it wasn't represented by a <code>'City'</code>. If you want the same <code>A_list</code></p> <pre><code>df3 = pd.merge(*[s.rename('fruit').reset_index() for s in [s1, s2]]) df3 = df3.groupby('Name') \ .apply(lambda df: df.drop('Name', axis=1).apply(tuplify)) \ .rename(columns=dict(fruit='A_list')) df3['A_list'] = df1.set_index('Name')['A_list'] df3.reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/F8amD.png" rel="nofollow"><img src="http://i.stack.imgur.com/F8amD.png" alt="enter image description here"></a></p>
2
2016-08-25T16:15:30Z
[ "python", "pandas" ]
Delete file start with
39,148,963
<p>I want this function to delete files. It does this correctly, but it <em>also</em> deletes folders, which I do not want.</p> <p>I also get an error during execution:</p> <pre><code>Access is denied: 'C:/temp3\\IDB_KKK </code></pre> <p>In folder temp3 i have:</p> <pre><code>IDB_OPP.txt IDB_KKK - folder </code></pre> <p>Code:</p> <pre><code>def delete_Files_StartWith(Path,Start_With_Key): my_dir = Path for fname in os.listdir(my_dir): if fname.startswith(Start_With_Key): os.remove(os.path.join(my_dir, fname)) delete_Files_StartWith("C:/temp3","IDB_") </code></pre>
0
2016-08-25T15:15:45Z
39,149,112
<p>Use the following, to check if it is a directory: <br></p> <pre><code>os.path.isdir(fname) //if is a directory </code></pre>
1
2016-08-25T15:23:17Z
[ "python" ]
Delete file start with
39,148,963
<p>I want this function to delete files. It does this correctly, but it <em>also</em> deletes folders, which I do not want.</p> <p>I also get an error during execution:</p> <pre><code>Access is denied: 'C:/temp3\\IDB_KKK </code></pre> <p>In folder temp3 i have:</p> <pre><code>IDB_OPP.txt IDB_KKK - folder </code></pre> <p>Code:</p> <pre><code>def delete_Files_StartWith(Path,Start_With_Key): my_dir = Path for fname in os.listdir(my_dir): if fname.startswith(Start_With_Key): os.remove(os.path.join(my_dir, fname)) delete_Files_StartWith("C:/temp3","IDB_") </code></pre>
0
2016-08-25T15:15:45Z
39,152,326
<p>Do you want to delete files recursively (i.e. including files that live in <em>subdirectories</em> of <code>Path</code>) without deleting those subdirectories themselves?</p> <pre><code>import os def delete_Files_StartWith(Path, Start_With_Key): for dirPath, subDirs, fileNames in os.walk(Path): for fileName in fileNames: # only considers files, not directories if fileName.startswith(Start_With_Key): os.remove(os.path.join(dirPath, fileName)) </code></pre>
0
2016-08-25T18:24:42Z
[ "python" ]
Delete file start with
39,148,963
<p>I want this function to delete files. It does this correctly, but it <em>also</em> deletes folders, which I do not want.</p> <p>I also get an error during execution:</p> <pre><code>Access is denied: 'C:/temp3\\IDB_KKK </code></pre> <p>In folder temp3 i have:</p> <pre><code>IDB_OPP.txt IDB_KKK - folder </code></pre> <p>Code:</p> <pre><code>def delete_Files_StartWith(Path,Start_With_Key): my_dir = Path for fname in os.listdir(my_dir): if fname.startswith(Start_With_Key): os.remove(os.path.join(my_dir, fname)) delete_Files_StartWith("C:/temp3","IDB_") </code></pre>
0
2016-08-25T15:15:45Z
39,152,456
<p>To remove a directory and all its contents, <a href="https://docs.python.org/3/library/shutil.html" rel="nofollow">use <code>shutil</code></a>.</p> <blockquote> <p>The shutil module offers a number of high-level operations on files and collections of files.</p> </blockquote> <p>Refer to the question <a href="http://stackoverflow.com/a/303225/137650">How do I remove/delete a folder that is not empty with Python?</a></p> <pre><code>import shutil .. if fname.startswith(Start_With_Key): shutil.rmtree(os.path.join(my_dir, fname)) </code></pre>
0
2016-08-25T18:32:45Z
[ "python" ]
Delete file start with
39,148,963
<p>I want this function to delete files. It does this correctly, but it <em>also</em> deletes folders, which I do not want.</p> <p>I also get an error during execution:</p> <pre><code>Access is denied: 'C:/temp3\\IDB_KKK </code></pre> <p>In folder temp3 i have:</p> <pre><code>IDB_OPP.txt IDB_KKK - folder </code></pre> <p>Code:</p> <pre><code>def delete_Files_StartWith(Path,Start_With_Key): my_dir = Path for fname in os.listdir(my_dir): if fname.startswith(Start_With_Key): os.remove(os.path.join(my_dir, fname)) delete_Files_StartWith("C:/temp3","IDB_") </code></pre>
0
2016-08-25T15:15:45Z
39,153,632
<p>I fixed it by the following:</p> <pre><code>def delete_Files_StartWith(Path,Start_With_Key): os.chdir(Path) for fname in os.listdir("."): if os.path.isfile(fname) and fname.startswith(Start_With_Key): os.remove(fname) </code></pre> <p>thanks you all.</p>
0
2016-08-25T19:49:38Z
[ "python" ]
Python - Object call uses wrong list
39,149,021
<p>I'm new to python and have the following problem:</p> <p>Every Class 'Neuron' has two lists (map_dendrites, map_axons) in which I want to store IDs from other Neurons.</p> <p>My Problem is that if 'map_synapses' calls 'add_axon' it writes the given ID in the list 'map_dendrites' from the calling Neuron-Object and not in the map of the called Neuron. Surprisingly it works otherwise when 'add_dendrites' is called although the code is the same (but executed first).</p> <p>Does anybody know how to fix this? Thank you for your support.</p> <pre><code># coding=utf-8 class Neuron(object): "Klasse Neuron" c_dendrites = 1 # Inputs c_axons = 1 # Outputs c_unmap_dendrites = c_dendrites # Unmapped entspricht am Anfang der Gesamtanzahl der vorhandenen Dednrites c_unmap_axons = c_axons # same here but axons map_dendrites = [0 for i in range(10)] # Verkabelung Dendrites map_axons = [0 for i in range(10)] # Verkabelung Axons def __init__(self, id, x, y, z): # 3D-Koordinaten "Konstruktor Neuron" self.id = id # Jedes Neuron besitzt eine eindeutige ID print 'Neuron ID %d (%d/%d/%d) erstellt' % (id, x, y, z) def add_dendrite(self, id): # Aus Sicht des Neurons (add_dendrite fügt an ein self.axon ein dendrite des anfragenden Neurons) success = False if(self.c_unmap_axons != 0): #print 'range %d - %d' % (self.c_axons, self.c_unmap_axons) print 'Übergebene ID: %d' % id #print 'Self ID: %d' % self.id #print len(self.map_axons) self.map_axons[self.c_axons - self.c_unmap_axons] = id # Auffüllen von 0 bis self.c_axons print 'testX: %d' % self.map_axons[0] self.c_unmap_axons -= 1 success = True return success def add_axon(self, id): # Aus Sicht des Neurons (add_axon fügt an ein self.dendrite ein Axon des anfragenden Neurons) success = False if (self.c_unmap_dendrites != 0): #print 'range %d - %d' % (self.c_axons, self.c_unmap_axons) print 'Übergebene ID: %d' % id #print 'Self ID: %d' % self.id #print len(self.map_axons) print 'test5: %d' % self.map_dendrites[0] self.map_dendrites[self.c_dendrites - self.c_unmap_dendrites] = id # Auffüllen von 0 bis self.c_dendrites print 'test6: %d' % self.map_dendrites[0] # Er nimmt hier die falsche Map self.c_unmap_dendrites -= 1 success = True return success def map_synapses(self, anzahl_neuronen, ar_neurons): import Tools print 'map_synapses: Mappe Dendrites' # 1. Dendrites verkabeln aus self-Perspektive while (0 != self.c_unmap_dendrites): # print control1.anzahl_neuronen ran_neuron = Tools.randomInt(0, anzahl_neuronen - 1) # Neuron würfeln while (self.id == ran_neuron): # Gewürfeltes Neuron darf nicht das neuron selbst sein ran_neuron = Tools.randomInt(0, anzahl_neuronen - 1) # Neuron würfeln if(ar_neurons[ran_neuron].add_dendrite(self.id)): #print 'range %d - %d' % (self.c_dendrites, self.c_unmap_dendrites) print 'Speichere %d in map_dendrites an Stelle %d' % (ran_neuron, self.c_dendrites - self.c_unmap_dendrites) self.map_dendrites[self.c_dendrites - self.c_unmap_dendrites] = ran_neuron print 'test1: %d' % self.map_dendrites[0] self.c_unmap_dendrites -= 1 print 'Dendrite mapped' print 'map_synapses: Mappe Dendrites abgeschlossen' # 2. Axons verkabeln aus self-Perspektive print 'test2: %d' % self.map_dendrites[0] print 'map_synapses: Mappe Axons' while (0 != self.c_unmap_axons): ran_neuron = Tools.randomInt(0, anzahl_neuronen - 1) # Neuron würfeln while (self.id == ran_neuron): # Gewürfeltes Neuron darf nicht das neuron selbst sein ran_neuron = Tools.randomInt(0, anzahl_neuronen - 1) # Neuron würfeln print 'test3: %d' % self.map_dendrites[0] # 1. Dendrites verkabeln aus self-Perspektive print 'ran %d' % ran_neuron if (ar_neurons[ran_neuron].add_axon(self.id)): ## add_axon fehlerhaft !!!!!!!!!!!!!!!!! print 'test4: %d' % self.map_dendrites[0] print 'Speichere %d in map_axons an Stelle %d' % (ran_neuron, self.c_axons - self.c_unmap_axons) self.map_axons[self.c_axons - self.c_unmap_axons] = ran_neuron self.c_unmap_axons -= 1 print 'Axon mapped' print 'map_synapses: Mappe Axons abgeschlossen' print 'map_synpases: ID %d abgeschlossen' % self.id self.getStatus() return ar_neurons def getStatus(self): print 'getStatus: Neuron ID %d' % self.id print 'getStatus: Dendrites_Map:' print ''.join(map(str, self.map_dendrites)) print 'getStatus: Axons_Map:' print ''.join(map(str, self.map_axons)) </code></pre>
0
2016-08-25T15:18:27Z
39,149,299
<p>It think the issue might be the scope of your variables. You are assigning them like this at the beginning of the class</p> <pre><code>class Neuron(object): c_dendrites = 1 # Inputs c_axons = 1 # Outputs c_unmap_dendrites = c_dendrites # Unmapped entspricht am Anfang der Gesamtanzahl der vorhandenen Dednrites c_unmap_axons = c_axons # same here but axons map_dendrites = [0 for i in range(10)] # Verkabelung Dendrites map_axons = [0 for i in range(10)] # Verkabelung Axons </code></pre> <p>but that makes them just for the class itself they aren't specific to any instance. Static?</p> <p>You should use your init function and use self to define the variables that means it will be tied to the instance and then whenever you need to use them also use self.</p> <pre><code>def __init__(self, id, x, y, z): # 3D-Koordinaten "Konstruktor Neuron" self.c_dendrites = 1 # Inputs self.c_axons = 1 # Outputs self.c_unmap_dendrites = c_dendrites # Unmapped entspricht am Anfang der Gesamtanzahl der vorhandenen Dednrites self.c_unmap_axons = c_axons # same here but axons self.map_dendrites = [0 for i in range(10)] # Verkabelung Dendrites self.map_axons = [0 for i in range(10)] # Verkabelung Axons self.id = id # Jedes Neuron besitzt eine eindeutige ID print 'Neuron ID %d (%d/%d/%d) erstellt' % (id, x, y, z) </code></pre>
2
2016-08-25T15:32:49Z
[ "python" ]
Converting a string to a list of lists
39,149,117
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p>I did manage to do just that, but it seems sloppy.</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [') &gt;&gt;&gt; val2 ['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1'] &gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]] &gt;&gt;&gt; val_final [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p> <p>Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).</p> <hr> <p><strong>Edit:</strong> Alternative value could contain floats like so:</p> <pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
3
2016-08-25T15:23:22Z
39,149,180
<p>You can use <code>replace</code> + <code>eval</code>:</p> <pre><code>value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" result = eval(value.replace(" ", ",")) result #output: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] </code></pre> <p>And to convert the integers to floats:</p> <pre><code>[list(map(float, l)) for l in result] #if you're using python 2 you can remove the "list" wrapping the "map" #output [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
4
2016-08-25T15:26:15Z
[ "python", "python-2.7" ]
Converting a string to a list of lists
39,149,117
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p>I did manage to do just that, but it seems sloppy.</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [') &gt;&gt;&gt; val2 ['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1'] &gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]] &gt;&gt;&gt; val_final [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p> <p>Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).</p> <hr> <p><strong>Edit:</strong> Alternative value could contain floats like so:</p> <pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
3
2016-08-25T15:23:22Z
39,149,462
<pre><code>value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" eval(value.replace(" ", ",")) </code></pre> <p>Output :</p> <pre><code>[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] </code></pre> <p>for return float values </p> <pre><code>import numpy as np l=np.array(eval(value.replace(" ", ",")))+0. l.tolist() </code></pre> <p>Output </p> <pre><code>[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
0
2016-08-25T15:39:41Z
[ "python", "python-2.7" ]
Converting a string to a list of lists
39,149,117
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p>I did manage to do just that, but it seems sloppy.</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [') &gt;&gt;&gt; val2 ['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1'] &gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]] &gt;&gt;&gt; val_final [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p> <p>Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).</p> <hr> <p><strong>Edit:</strong> Alternative value could contain floats like so:</p> <pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
3
2016-08-25T15:23:22Z
39,149,504
<p>Use <a href="https://docs.python.org/3.4/library/json.html#json.loads" rel="nofollow">json.loads</a> from the standard library, with a little bit of preparation (replace spaces with commas) and asking it to convert all found integers as floats:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; result = json.loads(value.replace(' ', ','), parse_int=float) [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] </code></pre> <p>That should be safer than eval and easier than manually parsing the string and convert it to the right datatypes, the json parser will do that for you.</p>
6
2016-08-25T15:41:44Z
[ "python", "python-2.7" ]
Converting a string to a list of lists
39,149,117
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p>I did manage to do just that, but it seems sloppy.</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [') &gt;&gt;&gt; val2 ['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1'] &gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]] &gt;&gt;&gt; val_final [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p> <p>Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).</p> <hr> <p><strong>Edit:</strong> Alternative value could contain floats like so:</p> <pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
3
2016-08-25T15:23:22Z
39,150,745
<p>Well the most flexible and extensible way would be to implement an <a href="https://en.wikipedia.org/wiki/LL_parser" rel="nofollow">LL(1) parser</a>. It requires a bit of work though. Here is a rough implementation in Python 2.7:</p> <pre><code>value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" class ParseError(ValueError): pass def tokenize(s): buf = "" while s: if s[0] == '[': yield s[0] elif s[0].isalnum(): buf += s[0] elif s[0] == ']': if buf: yield buf buf = "" yield ']' elif s[0] == ' ': if buf: yield buf buf = "" else: raise ParseError() s = s[1:] def parse_array(tokens): if tokens[0] != '[': raise ParseError() tokens = tokens[1:] elements = [] while tokens[0] != ']': element, tokens = parse(tokens) elements.append(element) if not tokens: raise ParseError() return elements, tokens[1:] def parse_number(tokens): return float(tokens[0]), tokens[1:] def parse(tokens): if tokens[0] == '[': return parse_array(tokens) elif tokens[0].isalnum(): return parse_number(tokens) else: raise ParseError() tokens = list(tokenize(value)) print tokens # ['[', '[', '1', '0', '0', '0', ']', '[', '0', '1', '0', '0', ']', '[', '0', '0', '1', '0', ']', '[', '0', '0', '0', '1', ']', ']'] parsed, tokens = parse(tokens) print parsed # [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p>Note : haven't tested all the edge cases, but it should give an idea of how it may look like.</p> <p>Here I'm assuming that:</p> <ul> <li>there can be any number of spaces between the numbers or brackets</li> <li>brackets don't need to be followed by a space</li> <li>the format represents <a href="https://en.wikipedia.org/wiki/Jagged_array" rel="nofollow">jagged arrays</a> (they can have rows of different lengths) of any dimensions (they can be arbitrarily nested).</li> </ul> <p>This is pretty much the most permissive assumptions I can make about this format, so it's probably overkill if you don't need to handle these use cases. But if this is what you need, then congratulations, you have an LL(1) grammar (in other words, a small language), and you need this kind of solution.</p> <p>There are two steps:</p> <ol> <li>Tokenization: transforms a string to a sequence of symbols (brackets, number, and potentially other things like identifiers).</li> <li>Parsing: transforms the sequence of symbols in an expression tree. To do that you need to read one symbol ahead before knowing how to interpret the following symbols (thus the 1 in LL1).</li> </ol>
1
2016-08-25T16:49:19Z
[ "python", "python-2.7" ]
Converting a string to a list of lists
39,149,117
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p>I did manage to do just that, but it seems sloppy.</p> <pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [') &gt;&gt;&gt; val2 ['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1'] &gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]] &gt;&gt;&gt; val_final [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre> <p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p> <p>Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).</p> <hr> <p><strong>Edit:</strong> Alternative value could contain floats like so:</p> <pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" &gt;&gt;&gt; ... &gt;&gt;&gt; result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
3
2016-08-25T15:23:22Z
39,154,550
<p>Similar to the Johan Dahlin's answer:</p> <p>Instead of using <em>json</em> parser, you can user the integrated Python <a href="https://docs.python.org/2/library/ast.html" rel="nofollow">Abstract Syntax Trees</a> parser:</p> <p>Like this:</p> <pre><code>value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]" import ast matrix = ast.literal_eval(value.replace(" ", ", ")) print(matrix) # -&gt; [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] </code></pre> <p>With floats values:</p> <pre><code># -&gt; [[9.231, -0.123, -2, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] </code></pre> <p>To "force" conversion to <strong>float</strong>, just write:</p> <pre><code>matrix = [[float(x) for x in row] for row in matrix] print(matrix) # -&gt; [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] </code></pre>
1
2016-08-25T20:52:38Z
[ "python", "python-2.7" ]
How to set inset_axes position in matplotlib
39,149,188
<p>I would like to place colorbar inside axes, because room is scarce in scientific publication. inset_axes seems like a good choice to creat sub axes, but I cannot find an easy way to place with other coordinate than 'loc = 0,1,2,3,4' : Results, the colormap label lay outside of the figures. I would like to use similar tool as the (x,y) coordinates find in ax.annotate() for example, that allow comprehensive positioning.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.inset_locator import inset_axes plt.close('all') ##### build some fake data to map ########## x = np.linspace(-0.7,0.7,num = 50) y = np.linspace(0,1,num = 100) ext = (x[0],x[-1],y[-1],y[0]) xx,yy = np.meshgrid(x,y,indexing = 'ij') U = np.cos(xx**2 + yy**2) #### build figures and axes ########### fig, ax = plt.subplots(1,1) fig.set_size_inches(4, 3) #### plot ############ im = ax.imshow(U,interpolation = 'nearest', extent = ext, aspect = 'equal',vmin=0,vmax=np.amax(U)) #### insert colorbar ###### cax = inset_axes(ax,width = '5%',height = '17%',loc = 1) cbar = plt.colorbar(im, ax = ax,cax = cax ,format = '%.1f' ,ticks = [0,np.amax(U)]) cax = inset_axes(ax,width = '5%',height = '17%',loc = 3) cbar = plt.colorbar(im, ax = ax,cax = cax,format = '%.1f' ,ticks = [0,np.amax(U)]) ### stuff #### fig.tight_layout() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/zZ67n.png" rel="nofollow"><img src="http://i.stack.imgur.com/zZ67n.png" alt="enter image description here"></a></p> <p>Regards,</p>
0
2016-08-25T15:26:40Z
39,150,161
<p>One possible solution which does not use <code>inset_axes</code> is to simply use matplotlib's <code>colorbar</code> but allow it to appear inside the figure. </p> <pre><code>x = np.linspace(-0.7,0.7,num = 50) y = np.linspace(0,1,num = 100) ext = (x[0],x[-1],y[-1],y[0]) xx,yy = np.meshgrid(x,y,indexing = 'ij') U = np.cos(xx**2 + yy**2) #### build figures and axes ########### fig1, ax = plt.subplots(1,1) fig1.set_size_inches(4, 3) #### plot ############ plt.imshow(U,interpolation = 'nearest', extent = ext, aspect = 'equal',vmin=0,vmax=np.amax(U)) #### insert colorbar ###### cax = fig1.add_axes([0.12, 0.52, 0.86, 0.3]) #change the position and size of the colorbar here cax.get_xaxis().set_visible(False) cax.get_yaxis().set_visible(False) cax.set_frame_on(False) cbar = plt.colorbar() cbar.set_ticks([0,np.max(U)]) #set the colorbar ticks ### stuff #### plt.show() </code></pre> <p>This gives the following graph:</p> <p><a href="http://i.stack.imgur.com/cUTqm.png" rel="nofollow"><img src="http://i.stack.imgur.com/cUTqm.png" alt="enter image description here"></a></p>
0
2016-08-25T16:15:11Z
[ "python", "python-2.7", "matplotlib" ]
Python: Printing value after .upper
39,149,218
<p>I am trying to print a string in all uppercase letters. When I run the print command it prints the type of x and the location. </p> <p>Why does it print the operation instead of the result?</p> <pre><code>x = 'bacon' x = x.upper print x &gt;&gt;&gt; &lt;built-in method upper of str object at 0x02A95F60&gt; </code></pre>
2
2016-08-25T15:28:39Z
39,149,238
<p><code>upper</code> (and all other methods) is something like "function ready to use", that way you can do:</p> <pre><code>x = 'bacon' x = x.upper print x() </code></pre> <p>But the most common to see, and the way I think you want is:</p> <pre><code>x = 'bacon' x = x.upper() print x </code></pre> <p>"Ridiculous" example using <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="nofollow">lambda</a>:</p> <pre><code>upper_case = lambda x: x.upper() print(upper_case) # &lt;function &lt;lambda&gt; at 0x7f2558a21938&gt; print(upper_case('bacon')) # BACON </code></pre>
4
2016-08-25T15:29:45Z
[ "python", "python-2.7" ]
Python: Printing value after .upper
39,149,218
<p>I am trying to print a string in all uppercase letters. When I run the print command it prints the type of x and the location. </p> <p>Why does it print the operation instead of the result?</p> <pre><code>x = 'bacon' x = x.upper print x &gt;&gt;&gt; &lt;built-in method upper of str object at 0x02A95F60&gt; </code></pre>
2
2016-08-25T15:28:39Z
39,149,302
<p>Everything in Python is an object, including functions and methods. <code>x.upper</code> is the <code>upper</code> attribute of <code>x</code>, which happens to be a function object. <code>x.upper()</code> is the result of trying to call that attribute as a function, so you are trying to do</p> <pre><code>print x.upper() </code></pre> <p>As an aside, you can try to call any object in Python, not just functions. It will not always work, but the syntax is legitimate. You can do</p> <pre><code>x = 5 x() </code></pre> <p>or even</p> <pre><code>5() </code></pre> <p>but of course you will get an error (the exact same one in both cases). However, you can actually call objects as functions as long as they define a <code>__call__</code> method (as normal functions do). Your example can actually be rewritten as</p> <pre><code>print x.upper.__call__() </code></pre>
3
2016-08-25T15:32:50Z
[ "python", "python-2.7" ]
How do I connect to a SQL server database with python?
39,149,243
<p>Im trying to conennect to an sql database that its already created an that its located on a server. How can I connect to this database using python. Ive tried using java but I cant seem to get working either.</p>
0
2016-08-25T15:29:54Z
39,149,561
<p>Well depending on what sql database you are using you can pip install pymssql for microsoft sql (mssql), psycopg2 for postgres (psql) or mysqldb for mysql databases Here are a few examples of using it</p> <p>Microsoft sql</p> <pre><code>import pymssql conn = pymssql.connect(server=server, user=user, password=password, database=db) cursor = conn.cursor() cursor.execute("SELECT COUNT(MemberID) as count FROM Members WHERE id = 1") row = cursor.fetchone() conn.close() print(row) </code></pre> <p>Postgres</p> <pre><code>import psycopg2 conn = psycopg2.connect(database=db, user=user, password=password, host=host, port="5432") cursor = conn.cursor() cursor.execute('SELECT COUNT(MemberID) as count FROM Members WHERE id = 1') row = cursor.fetchone() conn.close() print(row) </code></pre> <p>mysql</p> <pre><code>import MySQLdb conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor = conn.cursor() cursor.execute('SELECT COUNT(MemberID) as count FROM Members WHERE id = 1') row = cursor.fetchone() conn.close() print(row) </code></pre>
0
2016-08-25T15:44:27Z
[ "python", "sql-server", "database", "database-connection" ]
Travis CI encodes ü as ü
39,149,245
<p>I'm writing some Unicode strings to HTML in Python. The way I do it is to use Unicode internally and only encode when output. So something like:</p> <pre><code>with open(filename, 'w') as f: f.write(s.encode("utf-8")) </code></pre> <p>This works just as expect on my local machine. But when it's put on to Travis CI, the generated files have <code>ü</code> in place of <code>ü</code>. Any idea?</p> <p>Here is my <code>.travis.yml</code>:</p> <pre><code>language: python python: 2.7.10 install: pip install -r requirements.txt script: python main.py -d deploy: provider: s3 access_key_id: XXX secret_access_key: secure: XXX bucket: www.my.org region: us-east-1 skip_cleanup: true default_text_charset: 'utf-8' local-dir: output </code></pre> <h2>Update</h2> <p>The minimal Python code that can reproduce the problem is following:</p> <pre><code>from pyquery import PyQuery as pq argurl = 'http://hackingdistributed.com/tag/bitcoin/' d = pq(url=argurl) authors = [] for elem in d.find("h2.post-title a"): pubinfo = pq(elem).parent().parent().find(".post-metadata .post-published") author = pq(pubinfo).find(".post-authors").html().strip() authors.append(author) with open('output/test.html', 'w') as f: f.write(': '.join(authors).encode('utf-8')) </code></pre> <p>Check out the <code>output/test.html</code> to see the <code>ü</code>.</p>
1
2016-08-25T15:29:58Z
39,162,171
<p>This seems to be because your browser is likely wrongly reading the file. Easiest fix to this is to encode it as UTF-8 BOM by adding the BOM marker to the start of the file.</p> <p>Here's the fixed code for writing to the file:</p> <pre><code>with open('output/test.html', 'w') as f: f.write(u'\ufeff'.encode('utf-8')) # BOM marker f.write(': '.join(authors).encode('utf-8')) </code></pre>
-1
2016-08-26T08:49:28Z
[ "python", "unicode", "travis-ci", "python-unicode" ]
How to reshape a 1-d array into a an array of shape (1,4,5)?
39,149,251
<p>I have these vectors :</p> <pre><code>a = [1,2,3,4] b = [1,2,3,5] </code></pre> <p>and I could like to have this at the end :</p> <pre><code>A = [ [1,0,0,0,0] [0,1,0,0,0] [0,0,1,0,0] [0,0,0,1,0] ] B = [ [1,0,0,0,0] [0,1,0,0,0] [0,0,1,0,0] [0,0,0,0,1] ] </code></pre> <p>I have been using np.reshape from python this way:</p> <pre><code>A = np.reshape(a,(1,4,1)) B = np.reshape(b,(1,4,1)) </code></pre> <p>And it does just partially the job as I have the following result:</p> <pre><code>A = [[1] [2] [3] [4]] B = [[1] [2] [3] [5]] </code></pre> <p>Ideally I would like something like this:</p> <pre><code>A = np.reshape(a,(1,4,(1,5)) </code></pre> <p>but when reading the docs, this is not possible.</p> <p>Thanks in advance for your help</p>
0
2016-08-25T15:30:31Z
39,149,448
<p>What you're trying to do is not actually a reshape, as you alter the structure of the data. Make a new array with the shape you want:</p> <pre><code>A = np.zeros(myshape) B = np.zeros(myshape) </code></pre> <p>and then index those arrays</p> <pre><code>n = 0 for i_a, i_b in zip(a, b): A[n, i_a - 1] = 1 B[n, i_b - 1] = 1 n += 1 </code></pre> <p>The <code>i_a/i_b - 1</code> in the assignment is only there to make 1 index the 0th element. This also only works if <code>a</code> and <code>b</code> have the same length. Make this two loops if they are not the same length. There might be a more elegant solution but this should get the job done :)</p>
1
2016-08-25T15:39:09Z
[ "python", "numpy", "reshape", "encoder" ]
How to reshape a 1-d array into a an array of shape (1,4,5)?
39,149,251
<p>I have these vectors :</p> <pre><code>a = [1,2,3,4] b = [1,2,3,5] </code></pre> <p>and I could like to have this at the end :</p> <pre><code>A = [ [1,0,0,0,0] [0,1,0,0,0] [0,0,1,0,0] [0,0,0,1,0] ] B = [ [1,0,0,0,0] [0,1,0,0,0] [0,0,1,0,0] [0,0,0,0,1] ] </code></pre> <p>I have been using np.reshape from python this way:</p> <pre><code>A = np.reshape(a,(1,4,1)) B = np.reshape(b,(1,4,1)) </code></pre> <p>And it does just partially the job as I have the following result:</p> <pre><code>A = [[1] [2] [3] [4]] B = [[1] [2] [3] [5]] </code></pre> <p>Ideally I would like something like this:</p> <pre><code>A = np.reshape(a,(1,4,(1,5)) </code></pre> <p>but when reading the docs, this is not possible.</p> <p>Thanks in advance for your help</p>
0
2016-08-25T15:30:31Z
39,150,279
<p>Alternatively, numpy can assign value to multiple indexes on rows/columns in one go, example:</p> <pre><code>In [1]: import numpy as np In [2]: b = [1,2,3,5] ...: ...: In [3]: zero = np.zeros([4,5]) In [4]: brow, bcol = range(len(b)), np.array(b) -1 # logical transform In [5]: zero[brow, bcol] = 1 In [6]: zero Out[6]: array([[ 1., 0., 0., 0., 0.], [ 0., 1., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 1.]]) </code></pre>
3
2016-08-25T16:21:30Z
[ "python", "numpy", "reshape", "encoder" ]
Need to cut out all characters in between 2 brackets in a string
39,149,286
<p>I have a string in python 2.7:</p> <pre><code>a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' </code></pre> <p>I would like to use a regex to get the ' - 1' out of this string. </p> <p>I've tried but can't find it, thanks for your help, I've tried: </p> <pre><code>re.search(r'.*?\((.*)\).*', a) </code></pre> <p>But that didn't work. Mind you there's a second ( ) in the string but I only need the first one. </p> <p>THANK YOU!</p>
0
2016-08-25T15:32:01Z
39,149,369
<p>regexes are greedy by default. Your expression gets the first <code>(</code> to the last <code>)</code></p> <p>you did that:</p> <pre><code>re.search(r'.*?\((.*)\).*', a) </code></pre> <p>instead, use</p> <pre><code>re.search(r'.*?\((.*?)\).*', a) </code></pre> <p>note the non-greedy version of the match <code>.*?</code> (I just added a question mark to your regex to make it work)</p> <p>Variant: avoid closing parenthesis in your group capture</p> <pre><code>re.search(r'.*?\(([^)]*)\).*', a) </code></pre>
1
2016-08-25T15:35:55Z
[ "python", "regex" ]
Need to cut out all characters in between 2 brackets in a string
39,149,286
<p>I have a string in python 2.7:</p> <pre><code>a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' </code></pre> <p>I would like to use a regex to get the ' - 1' out of this string. </p> <p>I've tried but can't find it, thanks for your help, I've tried: </p> <pre><code>re.search(r'.*?\((.*)\).*', a) </code></pre> <p>But that didn't work. Mind you there's a second ( ) in the string but I only need the first one. </p> <p>THANK YOU!</p>
0
2016-08-25T15:32:01Z
39,149,383
<p>This would do it:</p> <pre><code>out = re.match('.*?\((.*?)\)', a).groups()[0] </code></pre> <p>if you wanted to remove from the original string,</p> <pre><code>a.replace(out, '') </code></pre>
0
2016-08-25T15:36:31Z
[ "python", "regex" ]
Need to cut out all characters in between 2 brackets in a string
39,149,286
<p>I have a string in python 2.7:</p> <pre><code>a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' </code></pre> <p>I would like to use a regex to get the ' - 1' out of this string. </p> <p>I've tried but can't find it, thanks for your help, I've tried: </p> <pre><code>re.search(r'.*?\((.*)\).*', a) </code></pre> <p>But that didn't work. Mind you there's a second ( ) in the string but I only need the first one. </p> <p>THANK YOU!</p>
0
2016-08-25T15:32:01Z
39,149,397
<p>Below code will return all the match in string:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' &gt;&gt;&gt; regex = re.compile(".*?\((.*?)\)") &gt;&gt;&gt; result = re.findall(regex, mystring) &gt;&gt;&gt; result [' - 1', '0:0'] </code></pre> <p>To get first (or whatever value you want), access it by corresponding index:</p> <pre><code>&gt;&gt;&gt; result[0] '-1' </code></pre>
0
2016-08-25T15:37:04Z
[ "python", "regex" ]
Need to cut out all characters in between 2 brackets in a string
39,149,286
<p>I have a string in python 2.7:</p> <pre><code>a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' </code></pre> <p>I would like to use a regex to get the ' - 1' out of this string. </p> <p>I've tried but can't find it, thanks for your help, I've tried: </p> <pre><code>re.search(r'.*?\((.*)\).*', a) </code></pre> <p>But that didn't work. Mind you there's a second ( ) in the string but I only need the first one. </p> <p>THANK YOU!</p>
0
2016-08-25T15:32:01Z
39,149,762
<p>You can use <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> to replace the first match found in the string, by using the optional <code>count</code> argument.</p> <pre><code>&gt;&gt;&gt;a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' &gt;&gt;&gt;re.sub(r'\(.+?\)','',a,count=1) </code></pre>
0
2016-08-25T15:54:03Z
[ "python", "regex" ]
Need to cut out all characters in between 2 brackets in a string
39,149,286
<p>I have a string in python 2.7:</p> <pre><code>a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text' </code></pre> <p>I would like to use a regex to get the ' - 1' out of this string. </p> <p>I've tried but can't find it, thanks for your help, I've tried: </p> <pre><code>re.search(r'.*?\((.*)\).*', a) </code></pre> <p>But that didn't work. Mind you there's a second ( ) in the string but I only need the first one. </p> <p>THANK YOU!</p>
0
2016-08-25T15:32:01Z
39,152,447
<p>What about:</p> <pre><code>tmp_1 = str.split('(', mystring ) tmp_2 = str.split(')', tmp[1]) result = tmp[0] </code></pre> <p>This process is simpler, and can be generalized if the brackets are nested.</p>
-1
2016-08-25T18:31:48Z
[ "python", "regex" ]
Tkinter Attribute Error when configuring tk Buttons
39,149,303
<p>I'm building an SMTP mail sender and when I started building the login window, I stumbled uppon an <strong>Attribute Error</strong> when trying to set a button state to '<em>disabled</em>'.</p> <p>The first function in this example is the root and the second one is the one causing problems.</p> <pre><code>class smtp_gui(tk.Tk): is_logged_in = False user_email = '' user_passwd = '' def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.wm_title("SMTP Mail Sender") self.resizable(False, False) self.iconbitmap('at.ico') self.container = tk.Frame(self) self.btn_container = tk.Frame(self) self.bind('&lt;Control-s&gt;', self.send) self.bind('&lt;Control-h&gt;', self.get_help) self.container.pack(side="top", padx=1, pady=1) self.container.columnconfigure(1, weight=1) self.btn_container.pack(side="bottom", padx=1, pady=1, fill='x') tk.Label(self.container, text='From:').grid(row=0, column=0, sticky='e') tk.Label(self.container, text='To:').grid(row=1, column=0, sticky='e') tk.Label(self.container, text='Subject:').grid(row=2, column=0, sticky='e') self.refresh() self.To = tk.Entry(self.container) self.To.grid(row=1, column=1, sticky="we", pady=3, padx=2) self.Subject = tk.Entry(self.container) self.Subject.grid(row=2, column=1, sticky="we", pady=2, padx=2) self.Msg = tk.Text(self.container, width=40, height=5) self.Msg.grid(columnspan=2, padx=3, pady=3) send_btn = tk.Button(self.btn_container, text="Send", command=self.send) send_btn.pack(side='right', padx=2, pady=1) quit_btn = tk.Button(self.btn_container, text="Quit", command=self.quit) quit_btn.pack(side='right', padx=2, pady=1) def send(self, event=None): print(self.Msg.get("0.0", "end")) def refresh(self): if self.logged_in(): try: self.login_btn.destroy() except AttributeError: pass self.mailabel = tk.Label(self.container, bd=1, text=smtp_gui.user_email, relief='sunken') self.mailabel.grid(row=0, column=1, pady=3, padx=2, sticky='we') else: try: self.mailabel.destroy() except AttributeError: pass self.login_btn = tk.Button(self.container, text="login before sending", command=self.get_login) self.login_btn.grid(row=0, column=1, sticky="we", pady=3, padx=2) def logged_in(self): return smtp_gui.is_logged_in def get_login(self): login = LoginWindow() self.refresh() def get_help(self, event=None): get_help = HelpWindow() class LoginWindow(tk.Toplevel): def __init__(self, *args, **kwargs): # Window config tk.Toplevel.__init__(self, *args, **kwargs) self.grab_set() self.wm_title("Email login") self.resizable(False, False) self.iconbitmap('login.ico') # Containers self.container = tk.Frame(self) self.btn_container = tk.Frame(self) self.container.pack(padx=2, pady=2) self.btn_container.pack(side="bottom", padx=1, pady=1, fill='x') # Tracers self.tracetest = tk.StringVar() self.tracetest.trace('w', self.tracer) # Window elements tk.Label(self.container, text="Gmail address:").grid(row=0, column=0) tk.Label(self.container, text="Password:").grid(row=1, column=0) # Entries self.Address = tk.Entry(self.container, width=44, textvariable=self.tracetest) self.Address.grid(row=0, column=1, sticky="we", pady=3, padx=2) self.Address.insert(0, "your address") self.Passwd = tk.Entry(self.container, show="*", textvariable=None) self.Passwd.grid(row=1, column=1, sticky="we", pady=3, padx=2) # Buttons self.login_btn = tk.Button(self.btn_container, text="Login", command=self.get_credentials) self.login_btn.pack(side='right', padx=2, pady=3) storno_btn = tk.Button(self.btn_container, text="Storno", command=self.destroy) storno_btn.pack(side='right', padx=2, pady=3) def get_credentials(self): user_address = self.Address.get() try: assert(match(r'[a-zA-Z0-9]+@gmail.com', user_address)) except AssertionError: messagebox.showwarning("Invalid login", "This is not a valid gmail address!") def tracer(self, *args): address = match(r'[a-zA-Z0-9]+@gmail.com', self.Address.get()) passwd = '' if passwd and address: self.login_btn.config(state='enabled') # Attribute error here, the program says these buttons don't exist in the functions even tough I defined them above else: self.login_btn.config(state='disabled') </code></pre> <p>The problematic function is at <strong>the very end</strong> (in the tracer function), you should be able to reproduce the problem with this code ( just import tkinter as tk and regex )</p> <p>I'm guessing there is some kind of a reference problem. </p> <h1><strong>EDIT - FULL TRACEBACK</strong></h1> <pre><code>Traceback (most recent call last): File "C:\Users\david\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__ return self.func(*args) File "C:\Users\david\Documents\Git_repositories\smtp_client\main_menu.py", line 129, in tracer self.login_btn.config(state='disabled') AttributeError: 'LoginWindow' object has no attribute 'login_btn' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\david\Documents\Git_repositories\smtp_client\main_menu.py", line 160, in &lt;module&gt; root.mainloop() File "C:\Users\david\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1131, in mainloop self.tk.mainloop(n) File "C:\Users\david\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1554, in __call__ self.widget._report_exception() AttributeError: 'StringVar' object has no attribute '_report_exception' </code></pre> <h1>FOUND A SOLUTION</h1> <p>The traceback occured because the tracer was called before the creation of the button, when I moved the tracer after the initiation of the button, it worked perfectly, thanks guys!</p>
0
2016-08-25T15:32:58Z
39,149,653
<p>The trace fires when the value changes. The value changes when you do <code>self.address.insert(0, "your address")</code> because that widget is tied to the variable. All of this happens before you define <code>self.login_btn</code>.</p> <p>You need to define the button before you enable the trace, or before you change the value of the traced variable.</p>
2
2016-08-25T15:49:27Z
[ "python", "class", "tkinter", "attributeerror" ]
How can I use an existing git repository in heroku
39,149,413
<p>I'm using heroku for creating a web application in python-django. I need to use an existing git repository in heroku. The name of my repository is <code>first-blog</code>. When I'm using </p> <pre><code>git clone https://github.com/heroku/first-blog.git </code></pre> <p>I got </p> <pre><code>Cloning into 'first-blog'... Username for 'https://github.com': AparnaBalagopal Password for 'https://AparnaBalagopal@github.com': remote: Repository not found. fatal: repository 'https://github.com/heroku/first-blog.git/' not found </code></pre> <p>this. I connect my github to the heroku account. How can I possible to connect this repository to my app in heroku.</p>
1
2016-08-25T15:37:34Z
39,149,527
<p>The repository you are trying to clone does not exist, you'd get the same result trying to clone it on your local machine.</p> <p>You probably meant to clone <code>https://github.com/AparnaBalagopal/first-blo‌​g.git</code></p>
1
2016-08-25T15:42:43Z
[ "python", "django", "heroku", "github" ]
How can I use an existing git repository in heroku
39,149,413
<p>I'm using heroku for creating a web application in python-django. I need to use an existing git repository in heroku. The name of my repository is <code>first-blog</code>. When I'm using </p> <pre><code>git clone https://github.com/heroku/first-blog.git </code></pre> <p>I got </p> <pre><code>Cloning into 'first-blog'... Username for 'https://github.com': AparnaBalagopal Password for 'https://AparnaBalagopal@github.com': remote: Repository not found. fatal: repository 'https://github.com/heroku/first-blog.git/' not found </code></pre> <p>this. I connect my github to the heroku account. How can I possible to connect this repository to my app in heroku.</p>
1
2016-08-25T15:37:34Z
39,150,010
<p>It looks like you're trying to clone a non-existent Git repository, which is why you're seeing that error. As some other users have mentioned already, you need to make sure you've got the right Github URL first of all, then you will be able to clone the repository no problem.</p> <p>Once you've cloned the repository down locally, you can deploy it to Heroku by doing the following:</p> <pre><code>cd &lt;directory-name&gt; heroku create git push heroku master heroku open </code></pre> <p>The above commands will:</p> <ul> <li>Move you into the project directory you just downloaded (make sure you use the right directory name).</li> <li>Create a new Heroku project.</li> <li>Push your code to Heroku and deploy it.</li> <li>Open up your new Heroku app in your web browser.</li> </ul> <p>You may also need to install Heroku addons (like Postgres, etc.) if your project requires it. You can do this by running:</p> <pre><code>heroku addons:create &lt;addon-name&gt; </code></pre> <p>That should do it!</p>
0
2016-08-25T16:07:29Z
[ "python", "django", "heroku", "github" ]
Scapy BGP Flags Attribute
39,149,455
<p><strong>Is there any other way I could use Scapy to configure a packet with multiple flag attributes?</strong></p> <p>I am trying to set up a BGP Layer with both optional and transitive attributes. I am using this github file: <a href="https://github.com/levigross/Scapy/blob/master/scapy/contrib/bgp.py" rel="nofollow">https://github.com/levigross/Scapy/blob/master/scapy/contrib/bgp.py</a>. On line 107, is the flags I am trying to add. </p> <p>Past failed attempts include:</p> <pre><code>&gt;&gt;&gt;a=BGPPathAttribute(flags=["Optional","Transitive"]) &gt;&gt;&gt;send(a) TypeError: unsupported operand type(s) for &amp;: 'str' and 'int' &gt;&gt;&gt;a=BGPPathAttribute(flags=("Optional","Transitive")) &gt;&gt;&gt;send(a) TypeError: unsupported operand type(s) for &amp;: 'tuple' and 'int' &gt;&gt;&gt;a=BGPPathAttribute(flags="Optional")/BGPPathAttribute(flags="Transitive") Creates 2 separate path attributes: One which is Optional and Non-Transitive and the other which is Well Known and Transitive. &gt;&gt;&gt;a=BGPPathAttribute(flags="Optional", flags="Transitive") SyntaxError: keyword argument repeated &gt;&gt;&gt;a=BGPPathAttribute(flags="OT") ValueError: ['OT'] is not in list </code></pre>
0
2016-08-25T15:39:23Z
39,150,893
<p>It is possible to configure multiple flag attributes by enumerating them in a single string, delimited with the <code>'+'</code> sign:</p> <pre class="lang-py prettyprint-override"><code>In [1]: from scapy.all import * WARNING: No route found for IPv6 destination :: (no default route?) In [2]: from scapy.contrib.bgp import BGPPathAttribute In [3]: BGPPathAttribute(flags='Optional+Transitive') Out[3]: &lt;BGPPathAttribute flags=Transitive+Optional |&gt; In [4]: send(_) WARNING: Mac address to reach destination not found. Using broadcast. . Sent 1 packets. </code></pre> <hr> <p>An alternative method, to directly calculate the numerical value of the desired combination of flags, is provided for completeness' sake:</p> <pre><code>In [1]: from scapy.all import * WARNING: No route found for IPv6 destination :: (no default route?) In [2]: from scapy.contrib.bgp import BGPPathAttribute In [3]: BGPPathAttribute(flags='Optional').flags | BGPPathAttribute(flags='Transitive').flags Out[3]: 192 In [4]: BGPPathAttribute(flags=_) Out[4]: &lt;BGPPathAttribute flags=Transitive+Optional |&gt; In [5]: send(_) WARNING: Mac address to reach destination not found. Using broadcast. . Sent 1 packets. </code></pre>
1
2016-08-25T16:58:10Z
[ "python", "networking", "scapy", "bgp" ]
Maya Python: name not defined with floatSliderGrp
39,149,465
<p>I'm trying to get a scale slider steup, and whenever I change the slider value, I'd like for the new value to be printed out:</p> <pre><code> scaleSlider = cmds.floatSliderGrp(label='Curve Scale', field=True, minValue=0.0, maxValue=2.0, fieldMinValue=0.0, fieldMaxValue=2.0, value=1, cc="print cmds.floatSliderGrp(scaleSlider, q=True, v=True)" ) </code></pre> <p>This seems pretty simple, but I'm getting this error:</p> <pre><code>// Error: name 'scaleSlider' is not defined # Traceback (most recent call last): # File "&lt;maya console&gt;", line 1, in &lt;module&gt; # NameError: name 'scaleSlider' is not defined // </code></pre> <p>The error is not very descriptive, unfortunately. I'm having trouble tracking down what the issue might be. At first I thought it was self-referential, but the error would tell me if so, correct?</p>
0
2016-08-25T15:39:49Z
39,162,776
<p>work with dict and lambda, </p> <pre><code>def get_ui_value(ui_id, ui_type): mcds = globals()["cmds"] method = getattr(mcds, ui_type) print method(ui_id, q=True, v=True) ui_dict = {} ui_dict["flt_slider_xy"] = cmds.floatSliderGrp(label='Curve Scale', field=True, minValue=0.0, maxValue=2.0, fieldMinValue=0.0, fieldMaxValue=2.0, value=1) ui_dict["int_slider_xy"] = cmds.intSliderGrp(label='Curve Scale', field=True, minValue=0, maxValue=10, fieldMinValue=0, fieldMaxValue=2, value=1) cmds.floatSliderGrp(ui_dict["flt_slider_xy"], e=True, cc= (lambda message:get_ui_value(ui_dict[flt_slider_xy], "floatSliderGrp"))) cmds.floatSliderGrp(ui_dict["int_slider_xy"], e=True, cc= (lambda message:get_ui_value(ui_dict[int_slider_xy], "intSliderGrp"))) </code></pre>
2
2016-08-26T09:20:10Z
[ "python", "user-interface", "maya" ]
Maya Python: name not defined with floatSliderGrp
39,149,465
<p>I'm trying to get a scale slider steup, and whenever I change the slider value, I'd like for the new value to be printed out:</p> <pre><code> scaleSlider = cmds.floatSliderGrp(label='Curve Scale', field=True, minValue=0.0, maxValue=2.0, fieldMinValue=0.0, fieldMaxValue=2.0, value=1, cc="print cmds.floatSliderGrp(scaleSlider, q=True, v=True)" ) </code></pre> <p>This seems pretty simple, but I'm getting this error:</p> <pre><code>// Error: name 'scaleSlider' is not defined # Traceback (most recent call last): # File "&lt;maya console&gt;", line 1, in &lt;module&gt; # NameError: name 'scaleSlider' is not defined // </code></pre> <p>The error is not very descriptive, unfortunately. I'm having trouble tracking down what the issue might be. At first I thought it was self-referential, but the error would tell me if so, correct?</p>
0
2016-08-25T15:39:49Z
39,379,495
<p>Your problem is in the <code>cc</code> argument. First, you've passed a <em>statement</em> not a function: you'd need to wrap the whole thing in a def or a lambda to work correctly. Second, you're passing it a string reference to <code>scaleSlider</code>, but at the time the callback is defined that variable doesn't exist. There are circumstances under which this code <em>would</em> work and others under which it won't (inside a function, for example, it will fail). Using string callback arguments is an invitation to these kinds of problems. </p> <p>It's easier to do it like this:</p> <pre><code>w = cmds.window() c = cmds.columnLayout() s = cmds.floatSliderGrp("example") def callback(*_): print s, "=", cmds.floatSliderGrp(s, q=True, v=True) cmds.floatSliderGrp(s, e=True, cc=callback) cmds.showWindow(w) </code></pre> <p>Because <code>callback</code> is defined after <code>cmds.floatSliderGrp("example")</code> has executed, it knows the value of <code>s</code> (don't use single-letter variables in real code!) . Because <code>cmds.floatSliderGrp(s, e=True, cc=callback) </code> executes after that, it passes the version of the callback which knows the correct value of <code>s</code> to this particular float slider group. This example will work in the listener or wrapped inside a function because the scoping is consistent.</p> <p>@AriGold's solution will also work, although <code>lambdas</code> can't be used in a loop -- if you tried to run his solution in a loop all of the callbacks may end up pointing at the last UI element because lambda's bind very late. </p> <p>Lots more detail on the different ways to set up UI callbacks <a href="http://theodox.github.io/2014/maya_callbacks_cheat_sheet" rel="nofollow">here</a></p>
1
2016-09-07T21:46:11Z
[ "python", "user-interface", "maya" ]
get best line when coordinates overlap
39,149,479
<p>I have a dataset like this:</p> <pre><code> FBti0018875 2031 2045 - TTCCAGAAACTGTTG hsf 62 0.9763443383736672 FBti0018875 2038 2052 + TTCTGGAATGGCAAC hsf 61 0.96581136371138 FBti0018925 2628 2642 - GACTGGAACTTTTCA hsf 60 0.9532992561656318 FBti0018925 2828 2842 + AGCTGGAAGCTTCTT hsf 63 0.9657036377575696 FBti0018949 184 198 - TTCGAGAAACTTAAC hsf 61 0.965931072979605 FBti0018986 2036 2050 + TTCTAGCATATTCTT hsf 63 0.9943559469645551 FBti0018993 1207 1221 - TTCTAGCATATTCTT hsf 63 0.9943559469645575 FBti0018996 2039 2053 + TTCTAGCATATTCTT hsf 63 0.9943559469645575 FBti0019092 2985 2999 - TTCTAGCATATTCTT hsf 63 0.9943559469645409 FBti0019118 1257 1271 + TTCCAGAATCTTGGA hsf 60 0.9523907773798134 </code></pre> <p>The first column is an identifier, and the second and third are coordinates. I only want to keep one line for each range of coordinates. Meaning that I want to keep the best identifier if there is an overlap for it (the best is defined based on the last column, higher value = better).</p> <p>For example for identifier FBti0018875 I would keep the first one because a) there is overlap with the second line and b) its last column value is higher (0.97>0.96).</p> <p>If there was not an overlap between the first and second line I would keep both. Sometimes I can have 5 or 6 lines for each identifier, so it's not as simple as comparing the current one with the previous.</p> <p>So far I have this code that doesn't work.</p> <pre><code>def test(lista, listb): #Compare lists of coordinates a = 0 b = 0 found = False while a&lt;len(lista) and b&lt;len(listb): result = check( lista[a] , listb[b] ) if result &lt; 0: a += 1 continue if result &gt; 0: b += 1 continue # we found overlapping intervals found = True return (found, a, lista[a], b, listb[b] ) return found def check( (astart, aend) , (bstart, bend) ): if aend &lt; bstart: return -1 if bend &lt; astart: return 1 return 0 refine = open("tffm/tffm_te_hits95.txt", "r") refined = open("tffm/tffm_te_unique_hits95.txt", "w") current_TE=[] for hit in refine: info=hit.rstrip().split('\t') if len(current_TE)==0 or info[0]==current_TE[0][0]: current_TE.append(info) elif info[0]!=current_TE[0][0]: to_keep=[] i=0 if len(current_TE)==1: to_keep.append(0) else: for i in range(len(current_TE)-1): if [current_TE[i][1], current_TE[i][2]] == [current_TE[i+1][1], current_TE[i+1][2]]: if current_TE[i][7]&lt;current_TE[i+1][7]: to_keep.append(i+1) elif test([(current_TE[i][1], current_TE[i][2])], [(current_TE[i+1][1], current_TE[i+1][2])])!='False': if current_TE[i][7]&lt;current_TE[i+1][7]: to_keep.append(i+1) try: to_keep.remove(i) except: pass else: to_keep.append(i) else: to_keep.append(i) if i==len(current_TE)-1: to_keep.append(i+1) for item in set(to_keep): print current_TE[item] current_TE=[] </code></pre> <p>The expected outcome in this case would be (only losing one FBti0018875)</p> <pre><code>FBti0018875 2031 2045 - TTCCAGAAACTGTTG hsf 62 0.9763443383736672 FBti0018925 2628 2642 - GACTGGAACTTTTCA hsf 60 0.9532992561656318 FBti0018925 2828 2842 + AGCTGGAAGCTTCTT hsf 63 0.9657036377575696 FBti0018949 184 198 - TTCGAGAAACTTAAC hsf 61 0.965931072979605 FBti0018986 2036 2050 + TTCTAGCATATTCTT hsf 63 0.9943559469645551 FBti0018993 1207 1221 - TTCTAGCATATTCTT hsf 63 0.9943559469645575 FBti0018996 2039 2053 + TTCTAGCATATTCTT hsf 63 0.9943559469645575 FBti0019092 2985 2999 - TTCTAGCATATTCTT hsf 63 0.9943559469645409 FBti0019118 1257 1271 + TTCCAGAATCTTGGA hsf 60 0.9523907773798134 </code></pre> <p>I have tried (with the code) to generate a list containing several lines with the same identifier and then parse it for the ones with overlapping coordinates and if that was the case select one according to the last column. It succeeds in checking the overlap but I only retrieve a handful of lines in some versions of it or:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 29, in &lt;module&gt; IndexError: list index out of range </code></pre>
0
2016-08-25T15:40:32Z
39,162,210
<p>Finally I solved. There was a silly mistake with 'False' instead of False.</p> <p>Here is the solution:</p> <pre><code>def test(lista, listb): a = 0 b = 0 found = False while a&lt;len(lista) and b&lt;len(listb): result = check( lista[a] , listb[b] ) if result &lt; 0: a += 1 continue if result &gt; 0: b += 1 continue # we found overlapping intervals found = True return (found, a, lista[a], b, listb[b] ) return found def check( (astart, aend) , (bstart, bend) ): if aend &lt; bstart: return -1 if bend &lt; astart: return 1 return 0 def get_unique_sre(current_TE): to_keep = range(0,len(current_TE)) for i in range(len(current_TE)-1): if [current_TE[i][1], current_TE[i][2]] == [current_TE[i+1][1], current_TE[i+1][2]]: if current_TE[i][7]&lt;current_TE[i+1][7]: try: to_keep.remove(i) except: pass elif test([(current_TE[i][1], current_TE[i][2])], [(current_TE[i+1][1], current_TE[i+1][2])])!=False: if current_TE[i][7]&lt;current_TE[i+1][7]: try: to_keep.remove(i) except: pass else: to_keep.remove(i+1) final_TE=[] for i in to_keep: final_TE.append(current_TE[i]) return final_TE refine = open("tffm/tffm_te_hits95.txt", "r") refined = open("tffm/tffm_te_unique_hits95.txt", "w") current_TE=[] for hit in refine: info=hit.rstrip().split('\t') if len(current_TE)==0 or info[0]==current_TE[0][0]: current_TE.append(info) else: if len(current_TE)==1: print&gt;&gt;refined, current_TE[0] current_TE=[] else: final_TE = get_unique_sre(current_TE) for item in final_TE: print&gt;&gt;refined, item current_TE=[] refined.close() </code></pre>
0
2016-08-26T08:51:50Z
[ "python", "coordinates" ]
brew python versus non-brew ipython
39,149,554
<p>I installed python via brew, and made it my default python. If I run <code>which python</code>, I obtain <code>/usr/local/bin/python</code>. Also pip is installed via brew, <code>which pip</code> returns <code>/usr/local/bin/pip</code>.</p> <p>I do not remember how I installed ipython, but I didn't do it via brew, since when I type <code>which ipython</code>, I obtain <code>/opt/local/bin/ipython</code>. Is it the OS X version of ipython?</p> <p>I installed all libraries on this version of ipython, for example I have matplotlib on ipython but not on python. I do not want to re-install everything again on the brew python, rather continue to install libraries on this version of ipython. How can I install new libraries there? For example, Pthon Image Library, or libjpeg? </p> <p>If possible, I would like an exhaustive answer so to understand my problem, and not just a quick fix tip. </p>
0
2016-08-25T15:44:13Z
39,149,676
<p>To transfer all your packages you can use pip to freeze all of your packages installed in ipython and then install them all easily from the file that you put them in.</p> <p><code>pip freeze &gt; requirements.txt</code></p> <p>then to install them from the file <code>pip install -r requirements.txt</code></p> <p>I'm not entirely sure if I understood what you're asking so if this isn't what you want to do please tell me.</p>
0
2016-08-25T15:50:33Z
[ "python", "osx", "ipython", "homebrew" ]
brew python versus non-brew ipython
39,149,554
<p>I installed python via brew, and made it my default python. If I run <code>which python</code>, I obtain <code>/usr/local/bin/python</code>. Also pip is installed via brew, <code>which pip</code> returns <code>/usr/local/bin/pip</code>.</p> <p>I do not remember how I installed ipython, but I didn't do it via brew, since when I type <code>which ipython</code>, I obtain <code>/opt/local/bin/ipython</code>. Is it the OS X version of ipython?</p> <p>I installed all libraries on this version of ipython, for example I have matplotlib on ipython but not on python. I do not want to re-install everything again on the brew python, rather continue to install libraries on this version of ipython. How can I install new libraries there? For example, Pthon Image Library, or libjpeg? </p> <p>If possible, I would like an exhaustive answer so to understand my problem, and not just a quick fix tip. </p>
0
2016-08-25T15:44:13Z
39,149,915
<blockquote> <p>I installed <code>python</code> via <code>brew</code>, and made it my default python. If I run <code>which python</code>, I obtain <code>/usr/local/bin/python</code>. </p> </blockquote> <p>Okay, good so far. </p> <blockquote> <p>Also <code>pip</code> is installed via <code>brew</code>, which pip returns <code>/usr/local/bin/pip</code>.</p> </blockquote> <p>Actually, not quite <code>brew install python</code> would have installed <code>pip</code> because even doing <code>brew search pip</code> comes up with this warning.</p> <pre><code>If you meant "pip" precisely: Homebrew provides pip via: `brew install python`. However you will then have two Pythons installed on your Mac, so alternatively you can install pip via the instructions at: https://pip.readthedocs.io/en/stable/installing/ </code></pre> <p>So, Python came with pip, not <code>brew install</code></p> <blockquote> <p>when I type <code>which ipython</code>, I obtain <code>/opt/local/bin/ipython</code>. Is it the OSX version of ipython?</p> </blockquote> <p>There is no "OSX version of ipython"... </p> <blockquote> <p>I installed all libraries on this version of ipython, for example I have <code>matplotlib</code> on ipython but not on python. </p> </blockquote> <p>You actually did install them to your brew installed Python. IPython is not a new installation of Python. </p> <p>You can even start a <code>python</code> interpreter from the terminal and <code>import matplotlib</code> to check this</p> <blockquote> <p>I do not want to re-install everything again on the brew python</p> </blockquote> <p>What exactly needs re-installed? It's already installed into the brew python</p>
0
2016-08-25T16:01:20Z
[ "python", "osx", "ipython", "homebrew" ]
brew python versus non-brew ipython
39,149,554
<p>I installed python via brew, and made it my default python. If I run <code>which python</code>, I obtain <code>/usr/local/bin/python</code>. Also pip is installed via brew, <code>which pip</code> returns <code>/usr/local/bin/pip</code>.</p> <p>I do not remember how I installed ipython, but I didn't do it via brew, since when I type <code>which ipython</code>, I obtain <code>/opt/local/bin/ipython</code>. Is it the OS X version of ipython?</p> <p>I installed all libraries on this version of ipython, for example I have matplotlib on ipython but not on python. I do not want to re-install everything again on the brew python, rather continue to install libraries on this version of ipython. How can I install new libraries there? For example, Pthon Image Library, or libjpeg? </p> <p>If possible, I would like an exhaustive answer so to understand my problem, and not just a quick fix tip. </p>
0
2016-08-25T15:44:13Z
39,151,146
<p>OK, so I solved by uninstalling macport (and so the ipython I was using, which was under /opt/local/bin) and installing ipython via pip. Then I re-install what I needed (e.g. jupyter) via pip.</p>
0
2016-08-25T17:14:31Z
[ "python", "osx", "ipython", "homebrew" ]
python package error when running from sublime
39,149,570
<p>I installed the python package <code>isochrones</code> using <code>pip install isochrones</code>.</p> <p>When I type <code>from isochrones.dartmouth import Dartmouth_Isochrone</code> in the <code>Sublime text editor</code> I get the following error:</p> <pre><code>from isochrones.dartmouth import Dartmouth_Isochrone ImportError: No module named dartmouth </code></pre> <p>However, the same command works when I run it from <code>ipython</code>. </p> <p>What's going on?! I have a long code, so working in <code>ipython</code> is not possible. I want to use <code>sublime</code>.</p>
0
2016-08-25T15:45:00Z
39,151,493
<p>You need to create a new <a href="http://docs.sublimetext.info/en/latest/file_processing/build_systems.html" rel="nofollow">build system</a> for Anaconda. Select <strong><code>Tools → Build System → New Build System...</code></strong> and replace the contents of the file that opens with the following:</p> <pre class="lang-js prettyprint-override"><code>{ "cmd": ["/Applications/anaconda/bin/python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" } </code></pre> <p>When you hit save, it should automatically open your User directory (<code>~/Library/Application Support/Sublime Text 2/Packages/User</code>). Save the file there as <code>Anaconda Python.sublime-build</code>. Finally, select <strong><code>Tools → Build System → Anaconda Python</code></strong> so the proper system will run when you select Build.</p> <p>Now that the build system is all set up, you need to ensure that you're installing things under the right Python distribution. OS X comes with Python built-in as <code>/usr/bin/python</code>, with system packages residing in a range of possible directories, depending on which build of OS X you're using. From the command line, run</p> <pre><code>which pip </code></pre> <p>to ensure it points to the Anaconda installation. If it doesn't, you'll have to alter your <code>PATH</code> variable to put <code>/Applications/anaconda/bin</code> at the front, before <code>/usr/bin</code> and <code>/usr/local/bin</code>. How to do that is beyond the scope of this answer, but it's easy to find out by a quick Google search.</p> <p>You should now be able to use your Anaconda <code>pip</code>-installed packages with Sublime Text.</p>
0
2016-08-25T17:35:17Z
[ "python", "python-2.7", "sublimetext2", "anaconda" ]
read an excel file and create a final text file from it including polish characters
39,149,572
<p>I need to be able to read in an excel file that has lots of polish characters. Then I need to be able to write this file to a text file keeping the polish characters. So far I can only open the file an write it but every time it wants to write the unicode values. As you can see from my code I strip out the u' before I write the file but the unicode values are another thing.</p> <p>I end up something like this when I open the text file</p> <blockquote> <p>[29178.0, Firma handlowa', Sklep farbiarsko-chemiczny', A-ZET ZHU CIEBIELSKI ZENO', LWOWEK', 7880005802.0, CW PS', \u0141uczak Rafa\u0142', ciebielski1@wp.pl', Nie', ', 17242.364799999999, 1061.48, 0.061562321196220141, Nie', 0.0, 1.0]</p> </blockquote> <p>But I want it to look like this...</p> <blockquote> <p>29,178 Firma handlowa Sklep farbiarsko-chemiczny A-ZET ZHU CIEBIELSKI ZENO LWOWEK 7880005802 CW PS Łuczak Rafał ciebielski1@wp.pl Nie</p> </blockquote> <pre><code>wb = xlrd.open_workbook(xl_workbook.xls) #Get the sheet names sheets = wb.sheet_names() sheet1=[] for sheet in sheets: sheet1.append(sheet) #open the first sheet sh = wb.sheet_by_name(sheet1[0]) with open(xl_workbook.txt', "wb") as f: stri_line='' for rownum in xrange(sh.nrows): stri_line=str([val for val in sh.row_values(rownum)]) stri =str(stri_line.replace("u'","")) f.write(stri) </code></pre> <p>There must be a way to do this. Any help is very much appreciated. </p>
0
2016-08-25T15:45:05Z
39,149,876
<p>Replace the last part of your code with this:</p> <pre><code>with open(xl_workbook+'.csv.txt', "wb") as f: sep=u"\t" #tab character for rownum in xrange(sh.nrows): stri_line=sep.join(unicode(val) for val in sh.row_values(rownum)) stri=stri_line.encode("utf8") # or any encoding you want that supports polish characters f.write(stri) f.write("\n") #newline </code></pre>
1
2016-08-25T15:59:31Z
[ "python", "excel", "text", "unicode" ]
read an excel file and create a final text file from it including polish characters
39,149,572
<p>I need to be able to read in an excel file that has lots of polish characters. Then I need to be able to write this file to a text file keeping the polish characters. So far I can only open the file an write it but every time it wants to write the unicode values. As you can see from my code I strip out the u' before I write the file but the unicode values are another thing.</p> <p>I end up something like this when I open the text file</p> <blockquote> <p>[29178.0, Firma handlowa', Sklep farbiarsko-chemiczny', A-ZET ZHU CIEBIELSKI ZENO', LWOWEK', 7880005802.0, CW PS', \u0141uczak Rafa\u0142', ciebielski1@wp.pl', Nie', ', 17242.364799999999, 1061.48, 0.061562321196220141, Nie', 0.0, 1.0]</p> </blockquote> <p>But I want it to look like this...</p> <blockquote> <p>29,178 Firma handlowa Sklep farbiarsko-chemiczny A-ZET ZHU CIEBIELSKI ZENO LWOWEK 7880005802 CW PS Łuczak Rafał ciebielski1@wp.pl Nie</p> </blockquote> <pre><code>wb = xlrd.open_workbook(xl_workbook.xls) #Get the sheet names sheets = wb.sheet_names() sheet1=[] for sheet in sheets: sheet1.append(sheet) #open the first sheet sh = wb.sheet_by_name(sheet1[0]) with open(xl_workbook.txt', "wb") as f: stri_line='' for rownum in xrange(sh.nrows): stri_line=str([val for val in sh.row_values(rownum)]) stri =str(stri_line.replace("u'","")) f.write(stri) </code></pre> <p>There must be a way to do this. Any help is very much appreciated. </p>
0
2016-08-25T15:45:05Z
39,149,893
<p>The string.replace() function is purposely stripping out the unicode chars that would let python know how to to encode those chars. Define the encoding for the file handle, and python will take care of it for you.</p> <pre><code>with open('xl_workbook.txt', "w", encode="utf-8") as f: for rownum in xrange(sh.nrows): stri_line=str([val for val in sh.row_values(rownum)]) f.write(stri) </code></pre>
0
2016-08-25T16:00:24Z
[ "python", "excel", "text", "unicode" ]
Delete data in csv file using python?
39,149,585
<p>I have two csv files with a single column of data. How can I remove data in the second csv file in-place by comparing it with the data in the first csv file? For example: </p> <pre><code> import csv reader1 = csv.reader(open("file1.csv", "rb")) reader = csv.reader(open("file2.csv", "rb"))f for line in reader: if line in reader1: print line </code></pre> <p><a href="http://i.stack.imgur.com/TE8L8.png" rel="nofollow"><img src="http://i.stack.imgur.com/TE8L8.png" alt="File 2"></a></p>
0
2016-08-25T15:46:02Z
39,149,801
<p>if both files are just single columns, then you could use <code>set</code> to remove the differences. However, this presumes that the entries in each file do not need to be duplicated and their order doesn't really matter. </p> <pre><code>#since each file is a column, unroll each file into a single list: dat1 = [x[0] for x in reader1] dat2 = [y[0] for y in reader] #take the set difference dat1_without_dat2 = set(dat1).difference(dat2) </code></pre>
0
2016-08-25T15:55:42Z
[ "python", "csv" ]
How to track class version numbers
39,149,658
<p>I have a file (call it munging.py) containing multiple functions and classes that all apply to munging data into a standardized format. I generally do not make substantial changes to this file, or the classes, but now and then a major change is needed. Suppose the file has the following contents: </p> <pre><code>def function_1() '''common function for all classes''' def function_2() '''another common function''' class_1() def __init__() class_2() def __init__() </code></pre> <p>When I update "munging.py" I want to keep a record of the last version, but I do not want to increment a version number in the file name to keep track of this (e.g. I can rename munging.py to munging_v1.py, munging_v2.py, but I would rather not have to change all of my scripts to load munging_v2 instead of munging_v1).</p> <p>I suppose another option is to not change the file name, instead only change the class names (e.g. class_1_v1, class_1_v2, etc.), but I run into the same problem of changing the class call in all of my dependent scripts. </p> <p>Bear in mind that I have no formal programming training, so I may be asking an overly simple question. Is there a simple, or standard, or intuitive way to keep a record of all my previous class/script versions while implementing the newest version when called? Is this where svn, etc. come to play?</p>
0
2016-08-25T15:49:35Z
39,149,758
<p>For versioning the code, you do not need to make any change in code. Use any version control tool like <code>git</code> or <code>mercurial</code>. These are open-source and you can use it for free.</p> <p>Use below links to download any of them:</p> <ul> <li><a href="https://git-scm.com/downloads" rel="nofollow">Git</a></li> <li><a href="https://www.mercurial-scm.org/wiki/Download" rel="nofollow">Mercurial</a></li> </ul>
0
2016-08-25T15:53:41Z
[ "python", "version" ]
How to display mb/s instead of b/s in progressbar and Python?
39,149,701
<p>I am trying to change the way progressbar (version 2) displays the transferred/total file size in Python 3. Here's the code: </p> <pre><code>import progressbar import requests url = 'http://download.openbricks.org/sample/H264/big_buck_bunny_1080p_H264_AAC_25fps_7200K_short.MP4' request = requests.get(url, stream=True) file = open('test.mp4', 'wb') file_size = int(request.headers['Content-Length']) file_size_mb = round(file_size / 1024 / 1024,2) chunk_sz = 512 widgets = [progressbar.Bar(marker="#",left="[",right="]"), progressbar.Percentage()," | ", progressbar.FileTransferSpeed()," | ", progressbar.SimpleProgress()," | ", progressbar.ETA()] bar = progressbar.ProgressBar(widgets=widgets, maxval=file_size).start() i = 0 for chunk in request.iter_content(chunk_size=chunk_sz): file.write(chunk) i += len(chunk) bar.update(i) bar.finish() print('File size: {0} MB'.format(file_size_mb)) file.close() </code></pre> <p>The output:</p> <blockquote> <p>[#########################] 91% | 741.3 KiB/s | 3397632 of 3714474 | Time: 00:00:08</p> <p>File size: 3.54 MB</p> </blockquote> <p>I want to be able to make the "<strong>3397632</strong> of <strong>3714474</strong>" be displayed in the MB format (like in the <em>file_size_mb</em> variable), not in Bytes as it is being displayed by progressbar by default.</p> <p>I've read the docs in <a href="http://progressbar-2.readthedocs.io/en/latest/" rel="nofollow" title="Welcome to Progress Bar’s documentation!">Progress Bar’s documentation</a> but I couldn't find the answer to my question in any of the examples given there.</p>
0
2016-08-25T15:51:08Z
39,150,055
<p>From <code>progressbar</code> documentation :</p> <pre><code>class progressbar.widgets.SimpleProgress(format=’%(value)d of %(max_value)d’, max_width=None, **kwargs) Bases: progressbar.widgets.FormatWidgetMixin, progressbar.widgets.WidgetBase Returns progress as a count of the total (e.g.: “5 of 47”) </code></pre> <p>So I'd assume you can use the <code>format</code> parameter to do what you need.</p> <pre><code>widgets = [progressbar.Bar(marker="#",left="[",right="]"), progressbar.Percentage()," | ", progressbar.FileTransferSpeed()," | ", progressbar.SimpleProgress(format='%(value/1024/1024)d of %(max_value/1024/1024)d')," | ", progressbar.ETA()] </code></pre> <p>Another way would consist in getting getting the output from simpleProgress, parse it to get the values, and do the maths manually.</p>
0
2016-08-25T16:09:51Z
[ "python", "python-3.x", "format", "progress-bar", "transfer" ]
How to display mb/s instead of b/s in progressbar and Python?
39,149,701
<p>I am trying to change the way progressbar (version 2) displays the transferred/total file size in Python 3. Here's the code: </p> <pre><code>import progressbar import requests url = 'http://download.openbricks.org/sample/H264/big_buck_bunny_1080p_H264_AAC_25fps_7200K_short.MP4' request = requests.get(url, stream=True) file = open('test.mp4', 'wb') file_size = int(request.headers['Content-Length']) file_size_mb = round(file_size / 1024 / 1024,2) chunk_sz = 512 widgets = [progressbar.Bar(marker="#",left="[",right="]"), progressbar.Percentage()," | ", progressbar.FileTransferSpeed()," | ", progressbar.SimpleProgress()," | ", progressbar.ETA()] bar = progressbar.ProgressBar(widgets=widgets, maxval=file_size).start() i = 0 for chunk in request.iter_content(chunk_size=chunk_sz): file.write(chunk) i += len(chunk) bar.update(i) bar.finish() print('File size: {0} MB'.format(file_size_mb)) file.close() </code></pre> <p>The output:</p> <blockquote> <p>[#########################] 91% | 741.3 KiB/s | 3397632 of 3714474 | Time: 00:00:08</p> <p>File size: 3.54 MB</p> </blockquote> <p>I want to be able to make the "<strong>3397632</strong> of <strong>3714474</strong>" be displayed in the MB format (like in the <em>file_size_mb</em> variable), not in Bytes as it is being displayed by progressbar by default.</p> <p>I've read the docs in <a href="http://progressbar-2.readthedocs.io/en/latest/" rel="nofollow" title="Welcome to Progress Bar’s documentation!">Progress Bar’s documentation</a> but I couldn't find the answer to my question in any of the examples given there.</p>
0
2016-08-25T15:51:08Z
39,160,964
<p>you can obtain this kind of display relatively easily with <a href="http://progressbar-2.readthedocs.io/en/latest/progressbar.widgets.html#progressbar.widgets.DataSize" rel="nofollow">DataSize</a> widget:</p> <pre><code>[###### ] 17% | 256.0 KiB/s | 631.0 KiB / 3.5 MiB | ETA: 0:00:11 </code></pre> <p>you can do this by replacing the <a href="http://progressbar-2.readthedocs.io/en/latest/progressbar.widgets.html#progressbar.widgets.SimpleProgress" rel="nofollow">SimpleProgress</a> widgets by two <a href="http://progressbar-2.readthedocs.io/en/latest/progressbar.widgets.html#progressbar.widgets.DataSize" rel="nofollow">DataSize</a> widgets, as shown below:</p> <pre><code>widgets = [progressbar.Bar(marker="#",left="[",right="]"), progressbar.Percentage(), " | ", progressbar.FileTransferSpeed(), " | ", progressbar.DataSize(), " / ", progressbar.DataSize(variable="max_value"), " | ", progressbar.ETA()] </code></pre> <p>By default, the <a href="http://progressbar-2.readthedocs.io/en/latest/progressbar.widgets.html#progressbar.widgets.DataSize" rel="nofollow">DataSize</a> widget displays the current value, but you can specify that you want it to display the max value by passing it "max_value" as <em>variable</em> parameter.</p> <p>The problem is that it is not documented and you have to inspect the code to find this information. So this could be changed one day and no more work with a later version of the module.</p> <p>Considering <a href="http://progressbar-2.readthedocs.io/en/latest/progressbar.widgets.html#progressbar.widgets.DataSize" rel="nofollow">the DataSize doc</a>, it seems you can alter the default format by passing a custom value to <em>format</em> parameter. The default format is</p> <pre><code>format='%(scaled)5.1f %(prefix)s%(unit)s' </code></pre> <p>I think you could get two decimal numbers by specifying this format:</p> <pre><code>format='%(scaled)5.2f %(prefix)s%(unit)s' </code></pre> <p>Concerning the displayed unit, the doc mentions the prefixes parameter which defaults to</p> <pre><code>prefixes=('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi') </code></pre> <p>You could probably pass another tuple with the prefixes you want. But consider this <a href="https://en.wikipedia.org/wiki/Binary_prefix" rel="nofollow">article discussing about binary prefixes</a> before doing that. If you use powers of 1024 to convert your units, and if you want to be exact, then you probably wants to use the IEC binary prefixes with the "i" character.</p> <hr> <p>An other, but longer, way to achieve what you want would be to derive the <a href="http://progressbar-2.readthedocs.io/en/latest/progressbar.widgets.html#progressbar.widgets.SimpleProgress" rel="nofollow">SimpleProgress</a> class to make one which fits you needs.</p>
0
2016-08-26T07:42:18Z
[ "python", "python-3.x", "format", "progress-bar", "transfer" ]
Put labels in the center of each bar
39,149,829
<p>I've created a bar plot with <code>matplotlib</code> pyplot library, using the following code: </p> <pre><code>fig = plt.figure(figsize=(15, 15), facecolor='white') ax_left = fig.add_subplot(221) ax_left.grid() ax_left.bar( [ix for ix in range(len(resp_tx.keys()))], resp_tx.values, #align='center', tick_label=resp_tx.keys(), color='#A6C307', edgecolor='white', ) ax_left.tick_params(axis='x', labelsize=10) for label in ax_left.get_xticklabels(): label.set_rotation(45) </code></pre> <p>Where resp_tx is a <code>pandas</code> Series that looks like this: </p> <pre><code>APPROVED 90 ABANDONED_TRANSACTION 38 INTERNAL_PAYMENT_PROVIDER_ERROR 25 CANCELLED_TRANSACTION_MERCHANT 24 ENTITY_DECLINED 6 CANCELLED_TRANSACTION_PAYER 2 Name: resp_tx, dtype: int64 </code></pre> <p>This is the result but I'm not able to put the labels in the right place. How can I put the tick labels in the center of the bar?</p> <p><a href="http://i.stack.imgur.com/gOv3N.png" rel="nofollow"><img src="http://i.stack.imgur.com/gOv3N.png" alt="enter image description here"></a></p>
0
2016-08-25T15:57:05Z
39,152,931
<p>I resolved the issue with the following modifications: </p> <pre><code> resp_tx = self.tx_per_account[account].resp_tx.value_counts() ax_left = fig.add_subplot(221) ax_left.grid() ax_left.bar( [ix for ix in range(len(resp_tx.keys()))], resp_tx.values, color='#A6C307', edgecolor='white', ) ax_left.set_xticks([ix+0.4 for ix in range(len(resp_tx.keys()))]) ax_left.set_xticklabels(resp_tx.keys(), rotation=40, ha='right') ax_left.set_ylim(top=(max(resp_tx.values)+max(resp_tx.values)*0.05)) ax_left.set_xlim(left=-0.2) #ax_left.spines['top'].set_visible(False) ax_left.spines['right'].set_visible(False) #ax_left.spines['bottom'].set_visible(False) ax_left.spines['left'].set_visible(False) </code></pre> <p><a href="http://i.stack.imgur.com/FfE1d.png" rel="nofollow"><img src="http://i.stack.imgur.com/FfE1d.png" alt="enter image description here"></a></p>
0
2016-08-25T19:03:31Z
[ "python", "python-2.7", "matplotlib" ]
JSON serialization error in Django Rest Framework when using pagination
39,149,941
<p>I just tried to add pagination using <code>pagination_class = TenItemsSetPagination</code> to my class-based-view. As a result, I get an error trying to access my endpoint: <code>&lt;Response status_code=200, "text/html; charset=utf-8"&gt; is not JSON serializable</code></p> <p>views.py:</p> <pre><code>class AllCartsView(ListModelMixin, generics.GenericAPIView): permission_classes = [AllowAny] authentication_classes = [] queryset = Cart.objects.all() serializer_class = carts_serializers.DataCartSerializer renderer_classes = (BrowsableAPIRenderer, JSONRenderer,) pagination_class = TenItemsSetPagination def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) </code></pre> <p>paginators.py</p> <pre><code>class TenItemsSetPagination(PageNumberPagination): page_size = 10 </code></pre> <ul> <li>Versions : Django 1.9.9 / DRF 3.3</li> </ul> <p>Any idea? Thanks.</p>
0
2016-08-25T16:02:58Z
39,150,229
<p>Just noticed that using <code>(ListModelMixin, generics.GenericAPIView)</code> instead of <code>(ListAPIView)</code> is responsible for the error.</p>
0
2016-08-25T16:19:05Z
[ "python", "django", "django-rest-framework" ]
Connect mongodb from Python in authorized mode
39,149,973
<p>I've created a user for my database in mongodb. I've tested with mongo shell to make sure that the user has proper privileges to access the database. Now I want to use my Python program to access the database, and I use <a href="http://api.mongodb.com/python/current/tutorial.html" rel="nofollow">PyMongo</a>. If I run mongod in unauthorized mode (without option <code>--auth</code>), the Python client works fine. However, when I use <code>--auth</code> option, the Python client doesn't work any more. In fact, it reports <code>unauthorized error</code>, which is easy to understand because I didn't change anything in the code. Here is the code to connect my <code>test</code> database:</p> <pre><code>from pymongo import MongoClient client = MongoClient() db = client.test cursor = db.restaurants.find() for document in cursor: print(document) </code></pre> <p>My question is how can I change the Python code to use username/password created previously? I've looked at the client documentation but there is not information for it.</p>
2
2016-08-25T16:05:05Z
39,150,113
<pre><code>client = MongoClient("mongodb://username:password@server/dbname") </code></pre> <p>This is the normal format for telling the client where and how to connect. The way you are using (with no parameters at all) defaults to a local mongo install, on the default port, with no authentication. </p>
2
2016-08-25T16:12:58Z
[ "python", "mongodb" ]
Connect mongodb from Python in authorized mode
39,149,973
<p>I've created a user for my database in mongodb. I've tested with mongo shell to make sure that the user has proper privileges to access the database. Now I want to use my Python program to access the database, and I use <a href="http://api.mongodb.com/python/current/tutorial.html" rel="nofollow">PyMongo</a>. If I run mongod in unauthorized mode (without option <code>--auth</code>), the Python client works fine. However, when I use <code>--auth</code> option, the Python client doesn't work any more. In fact, it reports <code>unauthorized error</code>, which is easy to understand because I didn't change anything in the code. Here is the code to connect my <code>test</code> database:</p> <pre><code>from pymongo import MongoClient client = MongoClient() db = client.test cursor = db.restaurants.find() for document in cursor: print(document) </code></pre> <p>My question is how can I change the Python code to use username/password created previously? I've looked at the client documentation but there is not information for it.</p>
2
2016-08-25T16:05:05Z
39,238,224
<p>Besides <a href="http://stackoverflow.com/a/39150113/4385621">Danielle's answer</a> you can also use <a href="http://api.mongodb.com/python/current/examples/authentication.html#scram-sha-1-rfc-5802" rel="nofollow">authenticate</a> method for that. Your code would look like this:</p> <pre><code>from pymongo import MongoClient client = MongoClient() db = client.test db.authenticate('user', 'password', mechanism=&lt;either 'SCRAM-SHA-1' or 'MONGODB-CR', being 'MONGODB-CR' the default authentication mechanism Before MongoDB 3.0&gt;) cursor = db.restaurants.find() for document in cursor: print(document) </code></pre>
1
2016-08-30T22:46:27Z
[ "python", "mongodb" ]
Login to Twitter using requests
39,150,015
<p>I am trying to login to Twitter with <code>requests</code> module in Python (2.7), and after I am logged in, I want to visit another directory on Twitter.</p> <p>So:</p> <ol> <li>Visit: <a href="https://twitter.com/login" rel="nofollow">https://twitter.com/login</a></li> <li>Locate username/pass elements</li> <li>Input Twitter Credentials</li> <li>Visit: <a href="https://twitter.com/settings/your_twitter_data" rel="nofollow">https://twitter.com/settings/your_twitter_data</a></li> <li>Input Twitter Password</li> </ol> <p>My code so far:</p> <pre><code>import requests import sys import os #LOGIN data = {"session[username_or_email]":"MY_USERNAME", "session[password]":"MY_PASSWORD"} r = requests.post("https://twitter.com/login/", data=data) if ("success" in r.json()): print "Logged in successfully!" else: print "Failed to login!" sys.exit(0) #CHANGE URL AND INPUT PASSWORD data = {"auth_password":"MY_PASSWORD"} r = requests.post("https://twitter.com/settings/your_twitter_data", data=data) if ("success" in r.json()): print "Success!" sys.exit(0) </code></pre> <p>When run, this is the error I get:</p> <pre><code>Traceback (most recent call last): File "twitter.py", line 10, in &lt;module&gt; if ("success" in r.json()): File "/usr/lib/python2.7/dist-packages/requests/models.py", line 808, in json return complexjson.loads(self.text, **kwargs) File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 516, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 373, in decode raise JSONDecodeError("Extra data", s, end, len(s)) simplejson.scanner.JSONDecodeError: Extra data: line 1 column 5 - line 1 column 81 (char 4 - 80) </code></pre>
0
2016-08-25T16:07:39Z
39,150,142
<p>You are using <code>r.json()</code> though response is HTML, try <code>r.text</code> instead.</p> <p>Also if you want to know you are successfully logged in, you'd rather check for your profile picture or something alike.</p> <p>Then, you should use <code>requests.Session()</code>, more info there : <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/</a></p>
0
2016-08-25T16:14:40Z
[ "python", "twitter", "python-requests" ]
Pandas select columns and data dependant on header
39,150,020
<p>I have a large .csv file. I want to select only the column with he time/date and 20 other columns which I know by header. </p> <p>As a test I try to take only the column with the header 'TIMESTAMP' I know this is 4207823 rows long in the .csv and it only contains dates and times. The code below selects the TIMESTAMP column but also carries on to take values from other columns as shown below:</p> <pre><code>import csv import numpy as np import pandas low_memory=False f = pandas.read_csv('C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - NaN2.csv', dtype = object)#convert file to variable so it can be edited time = f[['TIMESTAMP']] time = time[0:4207823]#test to see if this stops time taking other data print time </code></pre> <p>output</p> <pre><code> TIMESTAMP 0 2007-08-15 21:10:00 1 2007-08-15 21:20:00 2 2007-08-15 21:30:00 3 2007-08-15 21:40:00 4 2007-08-15 21:50:00 5 2007-08-15 22:00:00 6 2007-08-15 22:10:00 7 2007-08-15 22:20:00 8 2007-08-15 22:30:00 9 2007-08-15 22:40:00 10 2007-08-15 22:50:00 11 2007-08-15 23:00:00 12 2007-08-15 23:10:00 13 2007-08-15 23:20:00 14 2007-08-15 23:30:00 15 2007-08-15 23:40:00 16 2007-08-15 23:50:00 17 2007-08-16 00:00:00 18 2007-08-16 00:10:00 19 2007-08-16 00:20:00 20 2007-08-16 00:30:00 21 2007-08-16 00:40:00 22 2007-08-16 00:50:00 23 2007-08-16 01:00:00 24 2007-08-16 01:10:00 25 2007-08-16 01:20:00 26 2007-08-16 01:30:00 27 2007-08-16 01:40:00 28 2007-08-16 01:50:00 29 2007-08-16 02:00:00 #these are from the TIMESTAMP column ... ... 679302 221.484 #This is from another column 679303 NaN 679304 2015-09-23 06:40:00 679305 NaN 679306 NaN 679307 2015-09-23 06:50:00 679308 NaN 679309 NaN 679310 2015-09-23 07:00:00 </code></pre>
0
2016-08-25T16:08:11Z
39,252,835
<p>The problem was due to an error in the input file so simple use of <code>usecols</code> in <code>pandas.read_csv</code> worked.</p> <p>code below demonstrates the selection of a few columns of data</p> <pre><code>import csv import pandas low_memory=False #read only the selected columns df = pandas.read_csv('DataB - Copy - Copy.csv',delimiter=',', dtype = object, usecols=['TIMESTAMP', 'igmmx_U_77m', 'igmmx_U_58m', ]) print df # see what the data looks like outfile = open('DataB_GreaterGabbardOnly.csv','wb')#somewhere to write the data to df.to_csv(outfile)#save selection to the blank .csv created above </code></pre>
0
2016-08-31T14:50:20Z
[ "python", "python-2.7", "csv", "pandas", "columnheader" ]
Python input() unresponsive after plink
39,150,054
<p>On Windows, I'm running the following Python 3.5 script from <code>cmd.exe</code>:</p> <pre><code>subprocess.run(['C:\\Program Files (x86)\\Putty\\plink.exe', 'root@server', '-P', '54022', '-i', 'key.ppk', 'exit']) input('Press Enter...') </code></pre> <p>But when it's time to press Enter, the console is unresponsive. <kbd>Enter</kbd> does nothing. Text can't be entered. <kbd>Ctrl+C</kbd> doesn't do anything either. Python has to be killed in the task manager.</p> <p>I suspect <code>plink</code> is leaving the console in a bad state. Can I prevent or repair this? Or can I run the ssh command in its own console? That's not ideal, but it'll do.</p> <p>Or maybe there's a better solution for running remote commands via SSH using Python?</p> <p>When running the same <code>plink</code> command directly from <code>cmd</code> (no Python), it does remain responsive.</p>
1
2016-08-25T16:09:47Z
39,161,970
<p>A process might modify the console state and then for some reason fail to restore the original state when it exits. If this is a problem, the easiest solution is to spawn the child process with its own console by adding the parameter <code>creationflags=subprocess.CREATE_NEW_CONSOLE</code>. </p> <p>If that's not an option, or at least not a preferred option, you could instead capture the current modes of the console's input and screen buffer prior to running the program. Then restore the previous modes after the child exits. See <a href="https://msdn.microsoft.com/en-us/library/ms683167" rel="nofollow"><code>GetConsoleMode</code></a> and <a href="https://msdn.microsoft.com/en-us/library/ms686033" rel="nofollow"><code>SetConsoleMode</code></a> on MSDN. </p> <p>Here's a context manager to restore the console's input and output modes. </p> <pre><code>import ctypes import msvcrt import contextlib kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) def _check_bool(result, func, args): if not result: raise ctypes.WinError(ctypes.get_last_error()) return args kernel32.GetConsoleMode.errcheck = _check_bool kernel32.SetConsoleMode.errcheck = _check_bool @contextlib.contextmanager def restore_console(): if not kernel32.GetConsoleWindow(): yield # nothing to do return with open(r'\\.\CONIN$', 'r+') as coni: with open(r'\\.\CONOUT$', 'r+') as cono: hI = msvcrt.get_osfhandle(coni.fileno()) hO = msvcrt.get_osfhandle(cono.fileno()) imode = ctypes.c_ulong() omode = ctypes.c_ulong() kernel32.GetConsoleMode(hI, ctypes.byref(imode)) kernel32.GetConsoleMode(hO, ctypes.byref(omode)) yield try: kernel32.SetConsoleMode(hI, imode) finally: kernel32.SetConsoleMode(hO, omode) </code></pre> <p>This could be expanded to restore the input and output codepages via <code>GetConsoleCP</code>, <code>GetConsoleOutputCP</code>, <code>SetConsoleCP</code>, and <code>SetConsoleOutputCP</code>. It could also restore the screen dimensions, title, and so on. This is all global state in conhost.exe that a child process can meddle with. On the other hand, the console's input history and aliases are stored per attached executable, so you shouldn't have to restore them.</p>
1
2016-08-26T08:38:37Z
[ "python", "windows", "putty", "windows-console", "plink" ]
Python - file lines - pallindrome
39,150,139
<p>I have been doing python tasks for learning and I came across this task where I have to read a file that includes few words and if a line is palindrome (same when written backwards: lol > lol) so I tried with this code but It doesn't print anything on the terminal:</p> <pre><code>with open("words.txt") as f: for line in f: if line == line[::-1]: print line </code></pre> <p>But if I print like this, without an if condition, it prints the words:</p> <pre><code>with open("words.txt") as f: for line in f: print line </code></pre> <p>I wonder why It wont print the words that I've written in the file:</p> <pre><code>sefes kurwa rawuk lol bollob </code></pre>
1
2016-08-25T16:14:31Z
39,150,224
<p>The last character of each <code>line</code> is a newline character ("\n"). You need to strip trailing newlines (<code>"foo\n".strip()</code>) before checking whether the line is a palindrome.</p>
1
2016-08-25T16:18:40Z
[ "python", "python-2.7", "palindrome" ]
Python - file lines - pallindrome
39,150,139
<p>I have been doing python tasks for learning and I came across this task where I have to read a file that includes few words and if a line is palindrome (same when written backwards: lol > lol) so I tried with this code but It doesn't print anything on the terminal:</p> <pre><code>with open("words.txt") as f: for line in f: if line == line[::-1]: print line </code></pre> <p>But if I print like this, without an if condition, it prints the words:</p> <pre><code>with open("words.txt") as f: for line in f: print line </code></pre> <p>I wonder why It wont print the words that I've written in the file:</p> <pre><code>sefes kurwa rawuk lol bollob </code></pre>
1
2016-08-25T16:14:31Z
39,150,228
<p>This is because those lines contain <code>"\n"</code> on the end. <code>"\n"</code> means new line. Therefore none of those are palindromes according to python.</p> <p>You can strip off the <code>"\n"</code> first by doing:</p> <pre><code>with open("words.txt") as f: for line in f: if line.strip() == line.strip()[::-1]: print line </code></pre>
1
2016-08-25T16:18:57Z
[ "python", "python-2.7", "palindrome" ]
Python - file lines - pallindrome
39,150,139
<p>I have been doing python tasks for learning and I came across this task where I have to read a file that includes few words and if a line is palindrome (same when written backwards: lol > lol) so I tried with this code but It doesn't print anything on the terminal:</p> <pre><code>with open("words.txt") as f: for line in f: if line == line[::-1]: print line </code></pre> <p>But if I print like this, without an if condition, it prints the words:</p> <pre><code>with open("words.txt") as f: for line in f: print line </code></pre> <p>I wonder why It wont print the words that I've written in the file:</p> <pre><code>sefes kurwa rawuk lol bollob </code></pre>
1
2016-08-25T16:14:31Z
39,150,258
<p>When you read a line from a file like this, you also get the newline character. So, e.g., you're seeing <code>'sefes\n'</code>, which when reversed is <code>'\nsefes'</code>. These two lines are of course not equal. One way to solve this is to use <code>rstrip</code> to remove these newlines:</p> <pre><code>with open("words.txt") as f: for line in f: line = line.rstrip() if line == line[::-1]: print line </code></pre>
1
2016-08-25T16:20:25Z
[ "python", "python-2.7", "palindrome" ]
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured
39,150,159
<p>I’m using Django 1.10 with Python 2.7. I have a problem running a Python script that uses Django models.</p> <pre><code> $ python contentui_app/content-util.py --sig Traceback (most recent call last): File "contentui_app/content-util.py", line 9, in &lt;module&gt; from models import * File "/var/django-project/contentui/contentui_app/models.py", line 12, in &lt;module&gt; class AuthGroup(models.Model): File "/var/django-project/contentui/contentui_app/models.py", line 13, in AuthGroup name = models.CharField(unique=True, max_length=80) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1043, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. </code></pre> # <p>this is the code</p> <pre><code>from django.conf import settings settings.configure() from optparse import OptionParser from pprint import pprint import sys, os, hashlib, re, datetime, inspect, time, string, django sys.path.append("/var/alertlogic/django-project/contentui") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentui.settings") django.setup() from contentui_app.models import * </code></pre>
0
2016-08-25T16:15:10Z
39,150,385
<p>This is caused when you don’t initialize Django. Try running this:</p> <pre><code>from django.conf import settings from contentui import settings settings.configure(settings) </code></pre> <p>before the rest of your code.</p>
0
2016-08-25T16:28:03Z
[ "python", "django" ]
Matplotlib subplots where one graph has multiple lines with and one doesn't
39,150,193
<p>currently trying this:</p> <pre><code>fig, ax1, ax3 = plt.subplots(1, 2, figsize=(10,5)) # share rate line and ax ax1.plot(temp_df.index, temp_df['share_rate'], 'b-') ax1.set_ylim([0,.03]) # % of total video views line and ax ax2 = ax1.twinx() ax2.plot(temp_df.index, temp_df['percent_of_total_views'], 'r-') # third plot ax3.plot([1,2,3,4], [1,2,3,4]) plt.show() </code></pre> <p>but receiving this error:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-62-a8364e1f65f8&gt; in &lt;module&gt;() 10 print "average share rate: " 11 ---&gt; 12 fig, ax1, ax3 = plt.subplots(1, 2, figsize=(10,5)) 13 14 # share rate line and ax ValueError: need more than 2 values to unpack </code></pre>
0
2016-08-25T16:16:36Z
39,150,494
<p>You are using matplotlibs <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots" rel="nofollow">subplots-function</a> in a wrong way.</p> <p>The statement of yours</p> <pre><code>fig, ax1, ax3 = plt.subplots(1, 2, figsize=(10,5)) # WRONG 3 vars on left, 2 are returned </code></pre> <p>expects a tuple of size 3 returned, which are put into <code>fig, ax1, ax3</code>.</p> <p>But the function returns only a tuple of size 2, <code>fig, ax</code> where ax can be a single axis, or a sequence of axis-objects (see docs).</p> <p>If you know, that this ax is a sequence of size 2, you could unpack it directly on the left side with:</p> <pre><code>fig, (ax1, ax3) = plt.subplots(1, 2, figsize=(10,5)) # CORRECT because 2nd return-value unpacked </code></pre>
1
2016-08-25T16:33:44Z
[ "python", "matplotlib" ]
Load all modules (files) in directory without prefixes
39,150,206
<p>I am using python 2.7. I have a folder with a number of .py files in it that define functions, load objects, etc. that I would like to use in my main script. I want to accomplish the following two objectives:</p> <ol> <li>Load all objects from all .py files in this directory, without knowing the file names in advance.</li> <li>Access these objects in my main script without prefixing, e.g. without needing to use <code>filename.function_name()</code></li> </ol> <p>I understand that this does not conform to accepted best practices for python modules. Nevertheless:</p> <ul> <li><p>I am writing code purely for my own use. It will never be shared with or used by others.</p></li> <li><p>In the course of my development work, I frequently change the names of files, move object definitions from one file to another, etc. Thus, it is cumbersome to need to go to my main script and change the names of the function name prefixes each time I do this.</p></li> <li><p>I am an adult. I understand the concept of risks from name conflicts. I employ my own naming conventions with functions and objects I create to ensure they won't conflict with other names.</p></li> </ul> <p>My first shot at this was to just loop through the files in the directory using <code>os.listdir()</code> and then call <code>execfile()</code> on those. When this did not work, I reviewed the responses here: <a href="http://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python">Loading all modules in a folder in Python</a> . I found many helpful things, but none get me quite where I want. Specifically, if include in my <code>__init__.py</code> file the response <a href="http://stackoverflow.com/a/1057534/3541976">here</a>:</p> <pre><code>from os.path import dirname, basename, isfile import glob modules = glob.glob(dirname(__file__)+"/*.py") __all__ = [ basename(f)[:-3] for f in modules if isfile(f)] </code></pre> <p>and then use in my main script:</p> <pre><code>os.chdir("/path/to/dir/") # folder that contains `Module_Dir` from Module_Dir import * </code></pre> <p>then I can gain access to all of the objects defined in the files in my directory without needing to know the names of those files ahead of time (thus satisfying #1 from my objectives). But, this still requires me to call upon those functions and objects using <code>filename.function_name()</code>, etc. Likewise, if I include in my <code>__init__.py</code> file explicitly:</p> <pre><code>from filename1 import * from filename2 import * etc. </code></pre> <p>Then I can use in my main script the same <code>from Module_Dir import *</code> as above. Now, I get access to my objects without the prefixes, but it requires me to specify explicitly the names of the files in <code>__init__.py</code>.</p> <p>Is there a solution that can combine these two, thus accomplishing both of my objectives? I also tried (as suggested <a href="http://stackoverflow.com/a/1057765/3541976">here</a>, for instance, including the following in <code>__init__.py</code>:</p> <pre><code>import os for module in os.listdir(os.path.dirname(__file__)): if module == '__init__.py' or module[-3:] != '.py': continue __import__(module[:-3], locals(), globals()) del module </code></pre> <p>But again, this still required the name prefixing. I tried to see if there were optional arguments or modifications to how I use <code>__import__</code> here, or applications using python 2.7's importlib, but did not make progress on either front.</p>
0
2016-08-25T16:17:19Z
39,151,529
<p>Ok, here is the solution that I came up with based on the suggestion from @meetaig. I'd be delighted though to accept and upvote any other ideas or suggested implementations for this situation:</p> <pre><code>import os def Load_from_Script_Dir(DirPath): os.chdir(os.path.dirname(os.path.dirname(DirPath))) ## so that the from .. import syntax later properly finds the directory. with open(DirPath + "__init__.py", 'w') as f: Scripts = [FileName for FileName in os.listdir(DirPath) if FileName[-3:] == '.py' and '__init__' not in FileName] for Script in Scripts: f.write('from %s import *\n' % Script.replace('.py','')) # Script_Dir = "/path/to/Script_Dir/" ## specify location of Script_Dir manually Script_Dir = os.path.dirname(os.path.abspath(__file__)) + "/Script_Dir/" ## assume Script_Dir is in same path as main.py that is calling this. Note: won't work when used in REPL. Load_from_Script_Dir(Script_Dir) from Script_Dir import * </code></pre> <p>Notes: </p> <ol> <li><p>this will also require that the .py files in the Script_Dir conform to naming conventions for python objects, i.e. they cannot start with numbers, cannot have spaces, etc.</p></li> <li><p>the .py files in Script_Dir here that get loaded won't have access to objects defined in the main script (even if they are defined before calling <code>from Script_Dir import *</code>). Likewise, they won't have access to objects defined in other scripts within Script_Dir. Thus, it may still be necessary to use a syntax such as <code>from filename import objectname</code> within those other .py files. This is unfortunate and partially defeats some of the convenience I was hoping to achieve, but it at least is a modest improvement over the status quo.</p></li> </ol>
0
2016-08-25T17:37:03Z
[ "python", "python-2.7", "module" ]
Load all modules (files) in directory without prefixes
39,150,206
<p>I am using python 2.7. I have a folder with a number of .py files in it that define functions, load objects, etc. that I would like to use in my main script. I want to accomplish the following two objectives:</p> <ol> <li>Load all objects from all .py files in this directory, without knowing the file names in advance.</li> <li>Access these objects in my main script without prefixing, e.g. without needing to use <code>filename.function_name()</code></li> </ol> <p>I understand that this does not conform to accepted best practices for python modules. Nevertheless:</p> <ul> <li><p>I am writing code purely for my own use. It will never be shared with or used by others.</p></li> <li><p>In the course of my development work, I frequently change the names of files, move object definitions from one file to another, etc. Thus, it is cumbersome to need to go to my main script and change the names of the function name prefixes each time I do this.</p></li> <li><p>I am an adult. I understand the concept of risks from name conflicts. I employ my own naming conventions with functions and objects I create to ensure they won't conflict with other names.</p></li> </ul> <p>My first shot at this was to just loop through the files in the directory using <code>os.listdir()</code> and then call <code>execfile()</code> on those. When this did not work, I reviewed the responses here: <a href="http://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python">Loading all modules in a folder in Python</a> . I found many helpful things, but none get me quite where I want. Specifically, if include in my <code>__init__.py</code> file the response <a href="http://stackoverflow.com/a/1057534/3541976">here</a>:</p> <pre><code>from os.path import dirname, basename, isfile import glob modules = glob.glob(dirname(__file__)+"/*.py") __all__ = [ basename(f)[:-3] for f in modules if isfile(f)] </code></pre> <p>and then use in my main script:</p> <pre><code>os.chdir("/path/to/dir/") # folder that contains `Module_Dir` from Module_Dir import * </code></pre> <p>then I can gain access to all of the objects defined in the files in my directory without needing to know the names of those files ahead of time (thus satisfying #1 from my objectives). But, this still requires me to call upon those functions and objects using <code>filename.function_name()</code>, etc. Likewise, if I include in my <code>__init__.py</code> file explicitly:</p> <pre><code>from filename1 import * from filename2 import * etc. </code></pre> <p>Then I can use in my main script the same <code>from Module_Dir import *</code> as above. Now, I get access to my objects without the prefixes, but it requires me to specify explicitly the names of the files in <code>__init__.py</code>.</p> <p>Is there a solution that can combine these two, thus accomplishing both of my objectives? I also tried (as suggested <a href="http://stackoverflow.com/a/1057765/3541976">here</a>, for instance, including the following in <code>__init__.py</code>:</p> <pre><code>import os for module in os.listdir(os.path.dirname(__file__)): if module == '__init__.py' or module[-3:] != '.py': continue __import__(module[:-3], locals(), globals()) del module </code></pre> <p>But again, this still required the name prefixing. I tried to see if there were optional arguments or modifications to how I use <code>__import__</code> here, or applications using python 2.7's importlib, but did not make progress on either front.</p>
0
2016-08-25T16:17:19Z
39,157,365
<p>Here is another solution, based on the same general principle as in my other implementation (which is inspired by the suggestion from @meetaig in comments). This one bypasses attempts to use the python module framework, however, and instead develops a workaround to be able to use <code>execfile()</code>. It seems much preferable for my purposes because:</p> <ol> <li><p>If one support script defines functions that use functions or objects defined in other scripts, there is no need to add an extra set of <code>from filename import ...</code> to it (which as I noted in my other answer, defeated a lot of the convenience I had hoped to gain). Instead, just as would happen if the scripts were all together in a single big file, the functions / objects only need be defined by the time a given function is called. </p></li> <li><p>Likewise, the support scripts can make use of objects in the main script that are created prior to the support scripts being run.</p></li> <li><p>This avoids creating a bunch of .pyc files that just go and clutter up my directory.</p></li> <li><p>This similarly bypasses the need (from my other solution) of making sure to navigate the interpreter's working directory to the proper location in order to ensure success of the <code>from ... import ...</code> statement in the main script.</p></li> </ol> <p>.</p> <pre><code>import os Script_List_Name = "Script_List.py" def Load_from_Script_Dir(DirPath): with open(DirPath + Script_List_Name, 'w') as f: Scripts = [FileName for FileName in os.listdir(DirPath) if FileName[-3:] == '.py' and FileName != Script_List_Name] for Script in Scripts: f.write('execfile("%s")\n' % (DirPath + Script)) Script_Dir = "/path/to/Script_Dir/" Load_from_Script_Dir(Script_Dir) execfile(Script_Dir + Script_List_Name) </code></pre> <p><strong>Alternatively</strong>, if it isn't necessary to do the loading inside a function, the following loop also works just fine if included in the main script (I was thrown off initially, because when I tried to build a function to perform this loop, I think it only loaded the objects into the scope of that function, and thus they weren't accessible elsewhere, an operation which is different from other languages like Julia, where the same function would successfully put the objects into a scope outside the function):</p> <pre><code>import os Script_Dir = "/path/to/Script_Dir/" for FileName in os.listdir(Script_Dir): if FileName[-3:] == '.py': print "Loading %s" %FileName execfile(Script_Dir + FileName) </code></pre>
0
2016-08-26T02:14:03Z
[ "python", "python-2.7", "module" ]
Is it possible to return the IDs of a multi row insert in SQL?
39,150,265
<p>With the statement below I can insert multiple rows into a table. If the tag exists already then nothing happens, and if it doesn't exist it creates the row.</p> <pre><code>INSERT INTO tags (name) VALUES ('this'),('is'),('my'),('interest'),('list'),('running'),('pokemongo'),('fighting'),('eating') ON CONFLICT DO NOTHING; </code></pre> <p>Is is possible to return the ID of all these values whether or not they exist? </p> <p>I'm using python psycopg2 with postgres 9.5.</p>
0
2016-08-25T16:20:46Z
39,150,433
<pre><code>INSERT INTO tags (name) VALUES ('this'),('is'),('my'),('interest'),('list'),('running'),('pokemongo'),('fighting'),('eating') ON CONFLICT DO NOTHING RETURNING ID; # &lt;== this is what you need. </code></pre> <p><strong>Edit:</strong> Right, with this solution you'll only get the ids of inserted rows.</p> <p>If you need all the ids, you'll have to make another query :</p> <pre><code>select ID from tags where name in ('this', 'is', 'my', 'interestest', 'list', '...') </code></pre>
0
2016-08-25T16:29:59Z
[ "python", "sql", "postgresql", "psycopg2", "postgresql-9.5" ]
Is it possible to return the IDs of a multi row insert in SQL?
39,150,265
<p>With the statement below I can insert multiple rows into a table. If the tag exists already then nothing happens, and if it doesn't exist it creates the row.</p> <pre><code>INSERT INTO tags (name) VALUES ('this'),('is'),('my'),('interest'),('list'),('running'),('pokemongo'),('fighting'),('eating') ON CONFLICT DO NOTHING; </code></pre> <p>Is is possible to return the ID of all these values whether or not they exist? </p> <p>I'm using python psycopg2 with postgres 9.5.</p>
0
2016-08-25T16:20:46Z
39,151,054
<p>This can be accomplished in one query using a WITH block (see PostgreSQL docs on <a href="https://www.postgresql.org/docs/current/static/queries-with.html" rel="nofollow">WITH</a> and <a href="https://www.postgresql.org/docs/current/static/sql-select.html" rel="nofollow">SELECT</a>). For example:</p> <pre><code>WITH t1 (c1) AS ( VALUES ('this'),('is'),... ), t2 AS (SELECT id FROM tags WHERE name IN (SELECT c1 FROM t1) ), t3 AS (INSERT INTO tags (name) SELECT c1 FROM t1 ON CONFLICT DO NOTHING RETURNING id) SELECT id from t2 UNION SELECT id from t3; </code></pre> <p>You could also replace <code>ON CONFLICT DO NOTHING</code> with <code>WHERE c1 NOT IN (SELECT name FROM tags)</code>. This would work without relying on the conflict caused by a unique index.</p>
2
2016-08-25T17:07:50Z
[ "python", "sql", "postgresql", "psycopg2", "postgresql-9.5" ]
How to see every packet that comes to our computer?
39,150,274
<p>i wrote a very very easy script that monitors the Downloads folder for .part files, if there isn't any then it shuts down the computer and sends an email or text message. But i want to develop it by analyzing the packets to do that i need every packet that comes to our computer. How can i do that? or is there an easier way?</p> <p>(If you download a file with Firefox or Chrome you will have a .part file which disappears when the download is finished.) (www.github.com/berkQ/bdown/ for script.)</p>
0
2016-08-25T16:21:11Z
39,150,769
<p>There actually is an easier way.</p> <p>The cleanest I can think off would be monitoring the file system.</p> <p>On linux you could use <code>pyinotify</code> : <a href="https://pypi.python.org/pypi/pyinotify/" rel="nofollow">https://pypi.python.org/pypi/pyinotify/</a> <a href="https://github.com/seb-m/pyinotify/blob/master/python2/examples/loop.py" rel="nofollow">https://github.com/seb-m/pyinotify/blob/master/python2/examples/loop.py</a></p> <p>On windows there are alternatives : <a href="http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html" rel="nofollow">http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html</a></p> <p>You could as well write your own file watcher.</p> <p>Every n seconds and For every file in downloads, get it's size. See if it has changed since last loop, if yes, assume there still are downloads. If nothing changed during n loops, assume downloads are over.</p>
2
2016-08-25T16:50:24Z
[ "python", "network-programming" ]
why don't I get index returns from list comprehension checking truth values?
39,150,369
<p>So I have a numpy array with numeric values, floats to be exact and NaNs:</p> <pre><code>In [1]: type(myarray) Out[1]: numpy.ndarray </code></pre> <p>now I want to check where there are NaNs in this array so I try:</p> <pre><code>nan_idx = [idx for idx, tf in enumerate(myarray) if not bool(tf)] </code></pre> <p>However this returns an empty list, but when I try:</p> <pre><code>np.where(pd.isnull(mayarray))[0] </code></pre> <p>I do get as output the index of each NaN</p> <p>Why doesn't the first attempt produce any results? </p>
1
2016-08-25T16:26:51Z
39,150,393
<p>The reason your first snippet doesn't work is that <code>bool(float)</code> does not check for NaNs:</p> <pre><code>&gt;&gt;&gt; float('NaN') nan &gt;&gt;&gt; bool(float('NaN')) True &gt;&gt;&gt; not bool(float('NaN')) False </code></pre> <p>To check for NaNs, you could use <code>numpy.isnan</code> or the fact that a NaN doesn't compare equal to itself:</p> <pre><code>&gt;&gt;&gt; numpy.isnan(float('NaN')) True &gt;&gt;&gt; float('NaN') != float('NaN') True </code></pre>
3
2016-08-25T16:28:30Z
[ "python", "numpy" ]
Why reddit cloudsearch returns wrong results with timestamp search?
39,150,406
<p>I have problem with this search:</p> <pre><code>list(r.search('timestamp:{}..{}'.format(ts1,ts2), sort='new', subreddit=subreddit, syntax='cloudsearch',limit=None)) </code></pre> <p>It gets ~1000 newest submissions from timestamp <code>ts1</code> (in my case subreddit creation time) to <code>ts2</code></p> <p>What my script does is:</p> <ol> <li>Get newest submissions</li> <li>Take creation time of second newest submission and set it as <code>ts2</code></li> <li>Do the search with new timestamp</li> </ol> <p>If after first search I got submissions <code>1,2,3,4,5,6,7,8,9</code>, then after second one I expect to get <code>3,4,5,6,7,8,9</code>, unfortunately I don't get them, but get something like <code>7,8,9</code>. Any idea why?</p> <p>Below is my script and sample results.</p> <p>Results:</p> <pre><code>t3_4zh8zw, 1472107937.0 t3_4zgl1n, 1472096403.0 t3_4zgf34, 1472093883.0 t3_4zg8de, 1472091260.0 t3_4zfzun, 1472087983.0 t3_4zfysv, 1472087571.0 t3_4zf8hg, 1472077921.0 t3_4zf7g6, 1472077542.0 t3_4zf4p5, 1472076595.0 t3_4zf0d7, 1472075090.0 t3_4zeqeg, 1472071708.0 t3_4zeomz, 1472071134.0 t3_4zebse, 1472066994.0 t3_4zduso, 1472061376.0 t3_4zdtne, 1472061014.0 ####################### t3_4zebse, 1472066994.0 t3_4zduso, 1472061376.0 t3_4zdtne, 1472061014.0 t3_4zdipi, 1472057168.0 t3_4zdfj3, 1472056078.0 t3_4zd4v3, 1472052437.0 t3_4zd0l5, 1472051081.0 t3_4zctiu, 1472048701.0 t3_4zazqj, 1472016633.0 t3_4zawm3, 1472015079.0 t3_4zavyc, 1472014757.0 t3_4za5hb, 1472003960.0 t3_4z9ydt, 1472001398.0 t3_4z9xhx, 1472001065.0 t3_4z9ufa, 1471999935.0 </code></pre> <p>Script:</p> <pre><code>import praw import time user_agent = 'clodsearch-timestamp test' r = praw.Reddit(user_agent=user_agent) subreddit = r.get_subreddit('laptops') ts1 = int(subreddit.created_utc)-1 ts2 = int(time.time()) submissions = list(r.search('timestamp:{}..{}'.format(ts1,ts2), sort='new', subreddit=subreddit, syntax='cloudsearch',limit=None) ) for submission in submissions[:15]: print("{}, {}".format(submission.fullname, submission.created_utc)) ts2 = int(submissions[1].created_utc) - 1 print('#######################') submissions = list(r.search('timestamp:{}..{}'.format(ts1,ts2), sort='new', subreddit=subreddit, syntax='cloudsearch',limit=None) ) for submission in submissions[:15]: print("{}, {}".format(submission.fullname, submission.created_utc)) </code></pre>
0
2016-08-25T16:28:58Z
39,224,861
<p>For cloudsearch as far as I can gather you shouldn't use <code>created_utc</code>.</p> <p>If you change <code>submission.created_utc</code> to just <code>submission.created</code> you will get exactly the behaviour you need.</p> <p>This is due to cloudsearch using epochtime directly. There is no need to convert it to UTC or GMT, and doing so will have different effects depending on your timezone.</p>
1
2016-08-30T10:21:50Z
[ "python", "reddit", "praw" ]
Minimize the space widgets fill in a QGridLayout
39,150,459
<p>Below is a picture of my <code>QDockWidget</code>, which has a <code>QFrame</code>, and this <code>QFrame</code> has a <code>QGridLayout</code>. The single row I have in this layout places itself in the middle, but I'd like it to just sit neatly at the top instead. </p> <p>Does <code>QGridLayout</code> have any methods for its widgets to fill as little space as possible?</p> <p><a href="http://i.stack.imgur.com/ebnrc.png" rel="nofollow"><img src="http://i.stack.imgur.com/ebnrc.png" alt="enter image description here"></a></p>
0
2016-08-25T16:31:50Z
39,152,250
<p>Add a vertically expanding <a href="http://doc.qt.io/qt-4.8/qspaceritem.html" rel="nofollow">spacer-item</a> to the bottom of the grid-layout, so that it pushes the widgets above it to the top.</p>
0
2016-08-25T18:19:25Z
[ "python", "pyqt", "qgridlayout" ]
Python Multiprocessing: Child processes working at different speed
39,150,539
<p>I'm new to <code>python multiprocessing</code>. I'm trying to use a <code>third-party web-API</code> to fetch data for multiple symbols of interest. Here is my python code:</p> <pre><code>&lt;!-- language:lang-py--&gt; def my_worker(symbol, table_name): while True: # Real-time data for the symbol, third party code which is verified data = webApi.getData(symbol) query = ('insert into ' + table_name + '(var1, var2) values("%s, %s")' %(data[0], data[1])) # Execute query and store the data. Omitted for sake of brevity if __name__ == "__main__": my_symbols = get_symbols_list() # List of symbols my_tables = get_tables_list() # Corresponding list of mysql tables jobs = [] for pidx in range(len(my_symbols)): pname = 'datarecorder_' + my_symbols[pidx] # Naming the process for later identification p = multiprocessing.Process(name=pname, target=my_worker, args=(my_symbols[pidx], my_tables[pidx],)) jobs.append(p) p.start() </code></pre> <p>There are approximately <code>50 processes created</code> in this code. </p> <p><strong>Problem that I'm facing:</strong> <em>is that when I look into the corresponding tables after a certain amount of time (say 5 minutes), the number of records in each of the table in my_tables is drastically different (on the order of multiple of 10s)</em></p> <p>Since I am using the same API, the same network connection and the same code to fetch and write data to the mysql tables, I'm not sure what is causing this difference in number of records. <code>My hunch is that each of the 50 processes is getting assigned an unequal amount of RAM and other resources, and perhaps the priority is also different(?)</code></p> <p>Can someone tell me how can I ensure that each of these processes poll the webApi roughly equal number of times?</p>
0
2016-08-25T16:36:20Z
39,154,797
<p>An effective way to approach such things is to start with something vastly simpler, then <em>add</em> stuff to it until "a problem" shows up. Otherwise it's just blind guesswork.</p> <p>For example, here's something much simpler, which I'm running under Windows (like you - I'm using a current Win10 Pro) and Python 3.5.2:</p> <pre><code>import multiprocessing as mp from time import sleep NPROCS = 50 def worker(i, d): while True: d[i] += 1 sleep(1) if __name__ == "__main__": d = mp.Manager().dict() for i in range(NPROCS): d[i] = 0 ps = [] for i in range(NPROCS): p = mp.Process(target=worker, args=(i, d)) ps.append(p) p.start() while True: sleep(3) print(d.values()) </code></pre> <p>Here's the most recent output after about a minute of running:</p> <pre><code>[67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66] </code></pre> <p>So I can conclude that there's nothing "inherently unfair" about process scheduling on this box. On your box? Run it and see ;-)</p> <p>I can also see in Task Manager that all 50 processes are treated similarly, with (for example) the same RAM usage and priority. FYI, this box happens to have 8 logical cores (4 physical), and way more than enough RAM (16GB).</p> <p>Now there are worlds of additional complications in what you're doing, none of which we can guess from here. For example, maybe you're running out of RAM and so some processes are greatly delayed by pagefile swapping. Or maybe the work you're doing takes much longer for some arguments than others. Or ... but, regardless, the simplest way to find out is to incrementally make a very simple program a little fancier at a time.</p>
0
2016-08-25T21:11:46Z
[ "python", "python-multiprocessing" ]
Django1.7: ModelForm has no model class specified
39,150,568
<p>I'm getting "ModelForm has no model class specified." error in Django. I've spent hours to get this fixed, but can't see what the problem is.</p> <p>Thank you very much in advance! </p> <p><strong>Traceback:</strong><br /> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response</p> <p>111: response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/LandonKoo/code/tango_with_django_project/rango/views.py" in add_category</p> <p>71: form = CategoryForm() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/models.py" in <strong>init</strong></p> <p>312: raise ValueError('ModelForm has no model class specified.')</p> <p>Exception Type: ValueError at /rango/add_category/ <br /> Exception Value: ModelForm has no model class specified.</p> <p><strong>forms.py:</strong></p> <pre><code>from django import forms from rango.models import Page, Category class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0) slug = forms.CharField(widget=forms.HiddenInput(), required=False) print name, views, likes, slug # An inline class to provide additional information on the form. class Mata: # Provide an association between the ModelForm and a model model = Category fields = ('name',) </code></pre> <p><strong>views.py:</strong></p> <pre><code>def add_category(request): if request.method=="POST": form = CategoryForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print form.errors else: form = CategoryForm() return render(request, 'rango/add_category.html', {'form': form}) </code></pre>
0
2016-08-25T16:37:49Z
39,150,986
<p>Change </p> <pre><code>class Mata: </code></pre> <p>to </p> <pre><code>class Meta: </code></pre> <p>Also, I have never seen a print statement in a modelform. Take that out just in case too. </p>
1
2016-08-25T17:03:32Z
[ "python", "django-1.7" ]
literal_eval of tuple with a single element
39,150,590
<p>I am using <code>ast.literal_eval(str)</code> to evaluate a string containing a tuple such as <code>('a', 'b', 'c')</code>. However, if for some reason this tuple only contains a single element, the expression ignores the parenthesis and returns only the element:</p> <pre><code>&gt;&gt;&gt; string = "('a')" &gt;&gt;&gt; x = ast.literal_eval(string) &gt;&gt;&gt; x 'a' </code></pre> <p>Is there a non-hackish way to solve this? This problem is exacerbated by the fact that sometimes, I might have a tuple of tuples, like <code>(('a','b'))</code> and as such cannot just check for type. Thanks!</p>
0
2016-08-25T16:39:13Z
39,150,625
<p>That is because <code>('a')</code> is not a tuple but a string treated as <code>a</code>. Tuple with only one object is defined as <code>('a',)</code> (note the <code>,</code>)</p> <pre><code>&gt;&gt;&gt; type('a') &lt;type 'str'&gt; &lt;-- String &gt;&gt;&gt; type(('a')) &lt;type 'str'&gt; &lt;-- String &gt;&gt;&gt; type(('a',)) &lt;type 'tuple'&gt; &lt;-- Tuple </code></pre>
0
2016-08-25T16:41:01Z
[ "python", "abstract-syntax-tree" ]
representing a tree as a list in python
39,150,713
<p>I'm learning python and I'm curious about how people choose to store (binary) trees in python. </p> <p>Is there something wrong in storing the nodes of the tree as a list in python? something like:</p> <pre><code>[0,1,2,3,4,5,6,7,8] </code></pre> <p>where the 0'th position is 0 by default, 1 is the root, and for each position (i), the 2i and 2i+1 positions are the children. When no child is present, we just have a 'None' in that position. </p> <p>I've read a couple of books/notes where they represent a tree using a list of lists, or something more complicated than just a simple list like this, and I was wondering if there's something inherently wrong in how i'm looking at it?</p>
0
2016-08-25T16:47:25Z
39,150,892
<p>There's nothing wrong with storing a binary tree as a list the way you're doing - it's the same idea as storing it as a flat array in a language like C or Java. Accessing the parent of a given node is very fast, and finding the children is also pretty efficient.</p> <p>I suppose a lot of examples and tutorials will prefer to use a representation that's 'really tree shaped' (list of lists or objects) - it might be a bit more intuitive to explain.</p>
0
2016-08-25T16:58:10Z
[ "python", "binary-tree" ]
representing a tree as a list in python
39,150,713
<p>I'm learning python and I'm curious about how people choose to store (binary) trees in python. </p> <p>Is there something wrong in storing the nodes of the tree as a list in python? something like:</p> <pre><code>[0,1,2,3,4,5,6,7,8] </code></pre> <p>where the 0'th position is 0 by default, 1 is the root, and for each position (i), the 2i and 2i+1 positions are the children. When no child is present, we just have a 'None' in that position. </p> <p>I've read a couple of books/notes where they represent a tree using a list of lists, or something more complicated than just a simple list like this, and I was wondering if there's something inherently wrong in how i'm looking at it?</p>
0
2016-08-25T16:47:25Z
39,150,906
<p>You certainly COULD do this. I'd define it as a class deriving from list with a <code>get_children</code> method. However this is fairly ugly since either A) you'd have to preprocess the whole list in O(n) time to pair up indices with values or B) you'd have to call <code>list.index</code> in O(n log n) time to traverse the tree.</p> <pre><code>class WeirdBinaryTreeA(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_children(value): """Calls list.index on value to derive the children""" idx = self.index(value) # O(n) once, O(n log n) to traverse return self[idx * 2], self[idx * 2 + 1] class WeirdBinaryTreeB(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__mapping = self.processtree() def processtree(self): for idx, val in enumerate(self): self.__mapping[val] = idx def get_children(value): """Queries the mapping on value to derive the children""" idx = self.__mapping[value] # O(1) once, O(n) to traverse return self[idx * 2], self[idx * 2 + 1] </code></pre> <p>However the bigger question is <em>why</em> would you do this? What makes it better than a list of lists or a dict of dicts? What happens when you have:</p> <pre><code> A / \ B / \ C / \ D / \ E / \ F </code></pre> <p>And your list looks like:</p> <pre><code>[0, 'A', None, 'B', None, None, None, 'C', None, None, None, None, None, None, None, 'D', ...] </code></pre> <p>Instead of:</p> <pre><code>{"A": {"B": {"C": {"D": {"E": {"F": None}}}}}} </code></pre>
0
2016-08-25T16:59:02Z
[ "python", "binary-tree" ]
representing a tree as a list in python
39,150,713
<p>I'm learning python and I'm curious about how people choose to store (binary) trees in python. </p> <p>Is there something wrong in storing the nodes of the tree as a list in python? something like:</p> <pre><code>[0,1,2,3,4,5,6,7,8] </code></pre> <p>where the 0'th position is 0 by default, 1 is the root, and for each position (i), the 2i and 2i+1 positions are the children. When no child is present, we just have a 'None' in that position. </p> <p>I've read a couple of books/notes where they represent a tree using a list of lists, or something more complicated than just a simple list like this, and I was wondering if there's something inherently wrong in how i'm looking at it?</p>
0
2016-08-25T16:47:25Z
39,150,912
<p>I've seen representations like this (your flat list/array) used in C code, and representations like this could be acceptable in Python too, but it depends on the nature of the data you're handling. In C code, a balanced tree in this list representation can be very fast to access (much quicker than navigating a series of pointers), though the performance benefit in Python may be less noticeable due to all the other overhead.</p> <p>For reasonably balanced dense trees, this flat list approach is reasonable. However, as Adam Smith commented, this type of flat list tree would become extremely wasteful for unbalanced sparse trees. Suppose you have one branch with single children going down a hundred levels, and the rest of the tree had nothing. You would need 2^100 + 2^99 + 2^98 + ... + 2^1 + 1 spots in the flat list tree. For such a case, you would use up a huge amount of memory for something that could be represented much more efficiently with nested lists.</p> <p>So in essence, the choice between flat list trees vs. nested list trees is similar to the choice between flat array trees and pointer based trees in a C like language.</p>
0
2016-08-25T16:59:26Z
[ "python", "binary-tree" ]
How to look for a value in a Python DataFrame column?
39,150,783
<p>This is my first question on this forum, sorry if my English is not so good!</p> <p>I want to add a row to a DataFrame only if a specific column doesn't already contain a specific value. Let say I write this :</p> <pre><code>df = pd.DataFrame([['Mark', 9], ['Laura', 22]], columns=['Name', 'Age']) new_friend = pd.DataFrame([['Alex', 23]], columns=['Name', 'Age']) df = df.append(new_friend, ignore_index=True) print(df) Name Age 0 Mark 9 1 Laura 22 2 Alex 23 </code></pre> <p>Now I want to add another friend, but I want to make sure I don't already have a friend with the same name. Here is what I'm actually doing:</p> <pre><code>new_friend = pd.DataFrame([['Mark', 16]], columns=['Name', 'Age']) df = df.append(new_friend, ignore_index=True) print(df) Name Age 0 Mark 9 1 Laura 22 2 Alex 55 3 Mark 16 </code></pre> <p>then :</p> <pre><code>df = df.drop_duplicates(subset='Name', keep='first') df = df.reset_index(drop=True) print(df) Name Age 0 Mark 9 1 Laura 22 2 Alex 55 </code></pre> <p>Is there another way of doing this something like : </p> <p>if name in Column 'Name'is True:</p> <p>don't add friend</p> <p>else:</p> <p>add friend</p> <p>Thank you!</p>
2
2016-08-25T16:51:18Z
39,150,899
<pre><code>if 'Mark' in list(df['Name']): print('Mark already in DF') else: print('Mark not in DF') </code></pre>
0
2016-08-25T16:58:45Z
[ "python", "pandas", "dataframe" ]
defaultdict not available, implementation using an empty dictionary
39,150,818
<p>I have a code that looks like this:</p> <pre><code>abcd a1 abcd a2 abcd a3 abcd b1 abcd b2 q a1 q a2 </code></pre> <p>I have a defaultdict implementation that places them in dictionary. However, how would I do this without defaultdict(older python). My goal is to have a dictionary that looks something like this:</p> <pre><code>abcd : 'a1','a2','a3','b1','b2' q : 'a1', 'a2' </code></pre> <p>Also I need to count the number of elements in q, total number of elements in abcd and so on..</p> <p>edited.</p>
-1
2016-08-25T16:53:44Z
39,150,860
<p>Instead of <code>defaultdict</code> use <code>setdefault()</code>:</p> <pre><code>x = {} x.setdefault('abcd', []).append('a1') x.setdefault('abcd', []).append('a2') </code></pre> <p>This will result in:</p> <pre><code>abcd: ['a1', 'a2'] </code></pre> <p>and works by trying to lookup <code>'abcd'</code> as key for <code>x</code> and when not avaialable, initiating it as an empty list (<code>[]</code>). and return either the found value or the newly instantiated list. The <code>.append()</code> works on the returned value (first time on the empty list, after that on the list with <code>a1</code>).</p> <p>I am not sure when this was added but I have code from 2001 which uses <code>setdefault()</code> so your Python version will probably support this.</p>
2
2016-08-25T16:56:28Z
[ "python", "python-2.7" ]
defaultdict not available, implementation using an empty dictionary
39,150,818
<p>I have a code that looks like this:</p> <pre><code>abcd a1 abcd a2 abcd a3 abcd b1 abcd b2 q a1 q a2 </code></pre> <p>I have a defaultdict implementation that places them in dictionary. However, how would I do this without defaultdict(older python). My goal is to have a dictionary that looks something like this:</p> <pre><code>abcd : 'a1','a2','a3','b1','b2' q : 'a1', 'a2' </code></pre> <p>Also I need to count the number of elements in q, total number of elements in abcd and so on..</p> <p>edited.</p>
-1
2016-08-25T16:53:44Z
39,150,956
<p>You can implement <code>__missing__</code> on a subclass of <code>dict</code> and create an additional <code>count</code> method to count the number of occurences of a key:</p> <pre><code>class DefaultDict(dict): def __missing__(self, key): self[key] = [] return self[key] def count(self, key): return len(self[key]) &gt;&gt;&gt; a = DefaultDict() &gt;&gt;&gt; a['a'].append(1) &gt;&gt;&gt; a['a'].append(1) &gt;&gt;&gt; a['a'].append(1) &gt;&gt;&gt; a['a'].append(1) &gt;&gt;&gt; a['a'].append(1) &gt;&gt;&gt; a {'a': [1, 1, 1, 1, 1]} &gt;&gt;&gt; a.count('a') 5 </code></pre>
2
2016-08-25T17:01:51Z
[ "python", "python-2.7" ]
Python Tornado: how do I set WebSocket headers?
39,150,911
<p>I'm new to web development so let me explain:<br> I want my Python Tornado server to communicate with a web page. My web page uses WebSockets and the <code>onmessage</code> function to print what it should receive from the Tornado server. Basically, here is the HTML JavaScript part:</p> <pre class="lang-js prettyprint-override"><code>$(document).ready(function() { var myURL = "http://localhost:8888"; var source = new EventSource(myURL, { withCredentials: true }); // Access-Control-Allow-Origin ... source.onmessage = function(event) { console.log("received new event!"); }; ... }); // ready() </code></pre> <p>I'm setting the <code>withCredentials</code> parameter to <code>true</code> so <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="nofollow">CORS</a> are enabled.</p> <p>On the Tornado side, I have a WebSocket class which is supposed to answer back, but I don't know how to set the header to have <code>Access-Control-Allow-Origin</code> enabled. Here is the tornado code:</p> <pre class="lang-py prettyprint-override"><code>class EchoWebSocket(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def on_message(self, message): self.write_message(u"Received message: " + message) def make_app(): return tornado.web.Application([ ('/', EchoWebSocket), ]) if __name__ == '__main__': app = make_app() app.listen(8888) print 'listening on port 8888...' # start main loop tornado.ioloop.IOLoop.current().start() </code></pre> <p>I'm stuck with the following error in my browser!</p> <pre class="lang-none prettyprint-override"><code>GET http://localhost:8888/ [HTTP/1.1 400 Bad Request 1ms] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8888/. (Reason: CORS header 'Access-Control-Allow-Origin' missing). </code></pre> <p>What am I missing???</p>
0
2016-08-25T16:59:19Z
39,159,316
<p>Your javascript is using EventSource but your server is serving WebSockets. These are two completely different things. You need to change one of those to match the other. </p>
2
2016-08-26T06:03:58Z
[ "javascript", "python", "websocket", "cors", "tornado" ]
Program only runs when not run from a script or batch file, but works perfectly when typed in by hand in CMD
39,150,947
<p>I am trying to run the windows helpfile compiler (<code>hhc.exe</code>) from a script, but it shows very unexpected behaviour.</p> <p>When I run it from cmd.exe with <code>hhc pathtohelpproject.hpp</code>, the helpfile is compiled as expected. However, invoking the exact same command from python with the same working directory result in the program returning 0 and no output.</p> <p>But it gets even more bizarre: I've created a batch file <code>runhhc.bat</code>:</p> <pre><code>hhc "pathtohelpproject.hpp" </code></pre> <p>which I ran from the python script by invoking <code>call runhhc.bat</code>, <code>start runhhc.bat</code> and just <code>runhhc.bat</code>. </p> <p>All of them resulted in the same behaviour. However, with <code>start runhhc.bat</code> the cmd instance was still open after hhc returned, so I tried entering the command manually again, without success. But when I entered the command in a freshly, manually opened cmd, it also didn't work! In fact, it only started working once I closed the cmd opened by my script.</p> <p>What could be the explanation for this bizarre behaviour? And how can I run the compiler from a script regardless?</p>
0
2016-08-25T17:01:19Z
39,182,138
<p>It's totally down to hhc.exe, nothing else. The trick is to look at the %ERRORLEVEL% after it runs. It returns "1" despite success. This could be used in a custom command to warn the user it's spurious, if the hhc.exe run is isolated from other stuff. HHC.exe is using HHA.dll. About HHA.dll info has not been published. Microsoft grant the HHA interface information under non-disclosure agreement (NDA) to approved help ISV's.</p> <pre><code>D:\_working&gt;"C:\Program Files (x86)\HTML Help Workshop\hhc" foobar.hhp Microsoft HTML Help Compiler 4.74.8702 Compiling d:\_working\foobar.chm ... Compile time: 0 minutes, 1 second 22 Topics 87 Local links 2 Internet links 0 Graphics Created d:\_working\foobar.chm, 305,338 bytes Compression decreased file by 53,639 bytes. D:\_working&gt;echo %errorlevel% 1 </code></pre> <p>To go around this and continue you need to add <code>if not %errorlevel% 1 exit /B 1</code> in a batch file.</p> <pre class="lang-batch prettyprint-override"><code>@echo off REM ----------------------------------------- REM batch file is located in D:\_batch REM HH project file is located in D:\_working REM ----------------------------------------- cd ..\_working echo '//--- HH Compiler start -------------------------------------- "C:\Program Files (x86)\HTML Help Workshop\hhc" foobar.hhp echo '//--- HH Compiler end -------------------------------------- echo '//--- errorlevel ------------------------------------------- echo %errorlevel% echo '//------------------------------------------------------------ if not %errorlevel% 1 exit /B 1 </code></pre> <p>And a python script calling this batch:</p> <pre class="lang-python prettyprint-override"><code>print ("*******************************") print ("We compile a CHM help file ...") print ("*******************************") # First import the 'ctypes' module. ctypes module provides C compatible data types and allows calling functions in DLLs or shared libraries. import ctypes # An included library with Python install. # ctypes.windll.user32.MessageBoxW(0, "Open CHM", "Your title", 1) # OK only messageBox = ctypes.windll.user32.MessageBoxA # documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx returnValue = messageBox(None,"Compile Help Module (CHM) now?","CHM and Python",1) # 1=OK Cancel, 2=Cancel, Retry, Ignore if returnValue == 1: print("Pressed OK") # How to compile a chm file in Python? # --------------------------------- import os os.system("D:/_batch/run-hhc.bat") elif returnValue == 2: print("user pressed cancel button!") </code></pre> <p><a href="http://i.stack.imgur.com/0xyJ9.png" rel="nofollow"><img src="http://i.stack.imgur.com/0xyJ9.png" alt="enter image description here"></a></p> <p>You may be interested in calling a CHM from a python script:</p> <pre class="lang-python prettyprint-override"><code># How to open a chm file in Python? # --------------------------------- # os.system("hh.exe D:/UserData-QGIS-Python/Projekte/ConnectChm/CHM-example.chm") import os os.system("hh.exe D:/UserData-QGIS-Python/Projekte/ConnectChm/CHM-example.chm::/garden/garden.htm") </code></pre>
0
2016-08-27T14:19:00Z
[ "python", "windows", "batch-file", "cmd", "chm" ]
Dynamic attributes or custom dictionary for fixed read-only fields
39,151,007
<p>I am creating a class for retrieving details about a computer such as host_name, kernel_version, bios_version, and so on. Some details are more expensive to collect than others so I have a get_* function to retrieve them, but keep the results cached in the object if they are needed again. I am considering implementing them to look like a dictionary object so the kernel version can be retrieved as so:</p> <pre><code>system = System() kver = system['kernel_version'] </code></pre> <p>This will call the instance method <code>get_kernel_version(self)</code> internally to retrieve the data. If the kernel version is retrieved a second time from the above instantiated object, it will returned the cached result from the original call to <code>get_kernel_version(self)</code>. Note that all these key/value pairs are read-only, there are a fixed number of them based on the available get_* methods, and no new keys can be added later so it doesn't feel like a regular dictionary. There also shouldn't be a need to call something like the <code>values()</code> function which would simply cause all the get_* functions to be needlessly hit. Also, the syntax is a little more verbose than I'd like. Using <code>system.kernel_version</code> instead seems more natural for this use case. </p> <p>I'm considering whether a better approach is to use dynamic attributes on a class instance. However, I need a natural way to retrieve a list of all attributes, but not the internal methods supporting them. I would probably use the <code>__dir__</code> special method to return a list similar the <code>keys()</code> list of the dictionary. I would want to see kernel_version and host_name in the list, but not <code>__class__</code> or <code>get_kernel_version</code>. This seems to go against recommended practice for the definition of <code>__dir__</code> so I'm not sure if this is the right approach to use.</p> <p>I could return a proxy class instance whose sole job calls back to a concrete class with the get_* functions when it doesn't have the appropriate attribute already defined.</p> <p>Here is an example of a version I'm experimenting with implementing the dictionary approach:</p> <pre><code>class System(dict): def __getitem__(self, key): try: return getattr(self, 'get_'+key)() except AttributeError as ex: raise KeyError(ex.message) def __setitem__(self, key, value): raise Exception('Read-only') def __delitem__(self, key, value): raise Exception('Read-only') def keys(self): return [ x[4:] for x in dir(self) if x.startswith('get_') ] def get_host_name(self): return 'localhost' def get_kernel_version(self): return '4.7.0' system = System() print repr(system.keys()) for key in system.keys(): print '{0}: {1}'.format(key, system[key]) try: system['bios'] except Exception as ex: print str(ex) try: system['kernel_version'] = '5.0' except Exception as ex: print str(ex) </code></pre> <p>Which produced the following output:</p> <pre><code>['host_name', 'kernel_version'] host_name: localhost kernel_version: 4.7.0 "'System' object has no attribute 'get_bios'" Read-only </code></pre> <p>The code above does not yet implement the caching of values yet, but that is easy to add. However, it's feeling more like I should be doing this as attributes. I am just not sure if when doing so I should abuse <code>__dir__</code> to emulate the same functionality above I get with <code>keys()</code>.</p> <p>Should I stick with emulating a read-only dictionary or present a class instance with dynamic attributes?</p>
0
2016-08-25T17:04:45Z
39,171,820
<p>I think sticking with the read-only dictionary subclass approach you're using is fine. However your implementation could be improved somewhat by creating a generic read-only dictionary superclass from which to derive your specific subclass, and using a metaclass to create the value returned by the <code>keys()</code> method. Doing both is illustrated below.</p> <p>This means you don't have to "abuse" <code>dir()</code> (there's no such thing as a <code>__dir__</code> attribute) any longer. You can also use reuse the generic <code>MetaReadonlyDict</code> and <code>ReadonlyDict</code> classes to create other similar types.</p> <pre><code>class MetaReadonlyDict(type): def __new__(mcls, classname, bases, classdict): classobj = type.__new__(mcls, classname, bases, classdict) prefix = classdict['prefix'] _keys = set(name[len(prefix):] for name in classdict if name.startswith(prefix)) setattr(classobj, 'keys', lambda self: list(_keys)) # define keys() return classobj class ReadonlyDict(dict): def __getitem__(self, key): try: return getattr(self, self.prefix + key)() except AttributeError as ex: raise Exception( "{} object has no {!r} key".format(self.__class__.__name__, key)) def __setitem__(self, key, value): verb = "redefined" if key in self else "defined" raise Exception( "{} object is read-only: {!r} " "key can not be {}".format(self.__class__.__name__, key, verb)) def __delitem__(self, key): raise Exception( "{} object is read-only: {!r} " "key can not be deleted".format(self.__class__.__name__, key)) def __contains__(self, key): return key in self.keys() class System(ReadonlyDict): __metaclass__ = MetaReadonlyDict prefix = '_get_' def _get_host_name(self): return 'localhost' def _get_kernel_version(self): return '4.7.0' system = System() print('system.keys(): {!r}'.format(system.keys())) print('values associated with system.keys():') for key in system.keys(): print(' {!r}: {!r}'.format(key, system[key])) try: system['bios'] except Exception as ex: print(str(ex)) try: system['kernel_version'] = '5.0' except Exception as ex: print(str(ex)) try: del system['host_name'] except Exception as ex: print(str(ex)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>system.keys(): ['kernel_version', 'host_name'] values associated with system.keys(): 'kernel_version': '4.7.0' 'host_name': 'localhost' System object has no 'bios' key System object is read-only: 'kernel_version' key can not be redefined System object is read-only: 'host_name' key can not be deleted </code></pre>
0
2016-08-26T17:32:55Z
[ "python", "python-2.7", "python-2.6" ]
Connect an existing github repository to heroku app
39,151,053
<pre><code>https://github.com/AparnaBalagopal/first-blog . </code></pre> <p>This is my existing github repository. I need to use this repository on a new heroku python app. I'm new to heroku. I referred <code>https://devcenter.heroku.com/</code>. There is no description about using an existing repository on heroku in that article.</p>
0
2016-08-25T17:07:48Z
39,151,149
<p>You need to add your Heroku remote to your git repository.</p> <pre><code>git remote add heroku &lt;your-heroku-git-url&gt; </code></pre> <p>You can find that URL in your Herkou app's settings. You can then deploy to Heroku as per normal (<code>git push heroku master</code>).</p>
1
2016-08-25T17:14:39Z
[ "python", "heroku", "github" ]
Search for a partial string in an array of strings
39,151,056
<p>What is the Pythonic/quick way to search for a partial string in an array and then remove that string from the array?<br> (I can do it with a simple loop and IF IN and rebuild two array in the loop, Asking if there is a Pythonic way/function to do this)</p> <p>Example: </p> <pre><code>array = ['rule1','rule2','exception[type_a]','rule3','exception[type_b]'] res(,)=remove_exceptions(array,'exception') print(res[0]) &gt;&gt;&gt; ['rule1','rule2','rule3'] print(res[1]) &gt;&gt;&gt; ['exception[type_a]','exception[type_b]'] </code></pre>
2
2016-08-25T17:07:52Z
39,151,109
<pre><code>&gt;&gt;&gt; [x for x in array if 'exception' not in x] ['rule1', 'rule2', 'rule3'] &gt;&gt;&gt; [x for x in array if 'exception' in x] ['exception[type_a]', 'exception[type_b]'] </code></pre> <p>See also: <a href="http://stackoverflow.com/questions/949098/python-split-a-list-based-on-a-condition">Python: split a list based on a condition?</a></p>
2
2016-08-25T17:11:49Z
[ "python", "arrays", "python-3.x" ]
Search for a partial string in an array of strings
39,151,056
<p>What is the Pythonic/quick way to search for a partial string in an array and then remove that string from the array?<br> (I can do it with a simple loop and IF IN and rebuild two array in the loop, Asking if there is a Pythonic way/function to do this)</p> <p>Example: </p> <pre><code>array = ['rule1','rule2','exception[type_a]','rule3','exception[type_b]'] res(,)=remove_exceptions(array,'exception') print(res[0]) &gt;&gt;&gt; ['rule1','rule2','rule3'] print(res[1]) &gt;&gt;&gt; ['exception[type_a]','exception[type_b]'] </code></pre>
2
2016-08-25T17:07:52Z
39,151,121
<p>You may use in-built <code>filter</code> with <code>lambda</code> function to achieve this as:</p> <pre><code>&gt;&gt;&gt; my_array = array = ['rule1','rule2','exception[type_a]','rule3','exception[type_b]'] &gt;&gt;&gt; my_string = 'exception' &gt;&gt;&gt; filter(lambda x: my_string not in x, my_array) ['rule1', 'rule2', 'rule3'] </code></pre>
0
2016-08-25T17:12:36Z
[ "python", "arrays", "python-3.x" ]
Search for a partial string in an array of strings
39,151,056
<p>What is the Pythonic/quick way to search for a partial string in an array and then remove that string from the array?<br> (I can do it with a simple loop and IF IN and rebuild two array in the loop, Asking if there is a Pythonic way/function to do this)</p> <p>Example: </p> <pre><code>array = ['rule1','rule2','exception[type_a]','rule3','exception[type_b]'] res(,)=remove_exceptions(array,'exception') print(res[0]) &gt;&gt;&gt; ['rule1','rule2','rule3'] print(res[1]) &gt;&gt;&gt; ['exception[type_a]','exception[type_b]'] </code></pre>
2
2016-08-25T17:07:52Z
39,151,147
<p>If you want to separate your items you can do it with one loop and by preserving the items in a dictionary:</p> <pre><code>&gt;&gt;&gt; d = {} &gt;&gt;&gt; for i in array: ... if 'exception' in i: ... d.setdefault('exception', []).append(i) ... else: ... d.setdefault('other', []).append(i) ... &gt;&gt;&gt; &gt;&gt;&gt; d {'exception': ['exception[type_a]', 'exception[type_b]'], 'other': ['rule1', 'rule2', 'rule3']} </code></pre> <p>You can access to separated items by calling the values of the dictionary:</p> <pre><code>&gt;&gt;&gt; d.values() [['exception[type_a]', 'exception[type_b]'], ['rule1', 'rule2', 'rule3']] </code></pre>
1
2016-08-25T17:14:32Z
[ "python", "arrays", "python-3.x" ]
Search for a partial string in an array of strings
39,151,056
<p>What is the Pythonic/quick way to search for a partial string in an array and then remove that string from the array?<br> (I can do it with a simple loop and IF IN and rebuild two array in the loop, Asking if there is a Pythonic way/function to do this)</p> <p>Example: </p> <pre><code>array = ['rule1','rule2','exception[type_a]','rule3','exception[type_b]'] res(,)=remove_exceptions(array,'exception') print(res[0]) &gt;&gt;&gt; ['rule1','rule2','rule3'] print(res[1]) &gt;&gt;&gt; ['exception[type_a]','exception[type_b]'] </code></pre>
2
2016-08-25T17:07:52Z
39,151,218
<p>For list-of-strings <code>array</code> and thing-to-exclude <code>target</code>:</p> <p>List comprehensions work:</p> <pre><code>result = [s for s in array if target not in s] </code></pre> <p>Or a generator comprehension for the same:</p> <pre><code>result = (s for s in array if target not in s) </code></pre> <p>(<code>in</code> is effectively a contains operator, and <code>not in</code> is the inverse.)</p> <p>Alternately, use the <code>filter()</code> <a href="https://docs.python.org/3.5/library/functions.html#filter" rel="nofollow">built-in</a> with a lambda:</p> <pre><code>result = filter(lambda x: target not in x, array) </code></pre> <p>Either one returns a new object, rather than modifying your original list. The list comprehension returns a list, <code>filter()</code> returns a generator but you can wrap the call in <code>list()</code> if you need random access.</p>
0
2016-08-25T17:19:21Z
[ "python", "arrays", "python-3.x" ]
Search for a partial string in an array of strings
39,151,056
<p>What is the Pythonic/quick way to search for a partial string in an array and then remove that string from the array?<br> (I can do it with a simple loop and IF IN and rebuild two array in the loop, Asking if there is a Pythonic way/function to do this)</p> <p>Example: </p> <pre><code>array = ['rule1','rule2','exception[type_a]','rule3','exception[type_b]'] res(,)=remove_exceptions(array,'exception') print(res[0]) &gt;&gt;&gt; ['rule1','rule2','rule3'] print(res[1]) &gt;&gt;&gt; ['exception[type_a]','exception[type_b]'] </code></pre>
2
2016-08-25T17:07:52Z
39,151,684
<p>Seriously, just use a <code>for</code> loop, you're trying to create <em>two</em> lists so a single comprehension won't do (i.e the top solution so far iterates <em>twice</em> over the same list).</p> <p>Create two lists and append to them conditionally:</p> <pre><code>l1 = list() l2 = list() for i in array: l1.append(i) if 'exception' in i else l2.append(i) print(l1) ['exception[type_a]', 'exception[type_b]'] print(l2) ['rule1', 'rule2', 'rule3'] </code></pre>
1
2016-08-25T17:45:32Z
[ "python", "arrays", "python-3.x" ]
Single Array & Data Plotting with it
39,151,141
<p>The data I have is printed in a .txt file format and has breaks in between readings, its just one really long line. Each data point is a 16 second average of the z-component of the magnetic field of an incoming particle field. This is currently the code I have typed to ascribe the variable name to the file</p> <pre><code>Bz = np.loadtxt(r'C:\Users\Schmidt\Desktop\Project\Data\ACE\MAG\ACE_MAG_Data.txt', dtype = str) </code></pre> <p>and that works fine, but when I ask to print Bz I get </p> <pre><code>[["b'-1.3695e+01'" "b'-1.3481e+01'"] ["b'-1.3804e+01'" "b'-1.3485e+01'"] ["b'-1.3704e+01'" "b'-1.3437e+01'"] ..., ["b'1.6371e+00'" "b'6.2744e-01'"] ["b'1.6171e+00'" "b'6.1338e-01'"] ["b'1.4028e+00'" "b'3.2874e-01'"]] </code></pre> <p>What my problem is how did that "b" get there in the first place and how do I tell python that each data point is an individual point instead of pairs like it has it now.</p> <p><a href="https://www.dropbox.com/s/cev5stizmzu4w07/ACE_MAG_Data.txt?dl=0" rel="nofollow">This is the link to the file if you need to see.</a> Just remember to remove the words and the file should act appropriately.</p>
0
2016-08-25T17:14:17Z
39,151,300
<p>numpy is loading your data as bytes, and marking them as such, with the b character. I tried the following:</p> <pre><code>data = np.loadtxt("ACE_MAG_Data.txt", dtype=bytes).astype(float) </code></pre> <p>And it converts everything to floats instead:</p> <pre><code>&gt;&gt;&gt; data array([[-13.695 , -13.481 ], [-13.804 , -13.485 ], [-13.704 , -13.437 ], ..., [ 1.6371 , 0.62744], [ 1.6171 , 0.61338], [ 1.4028 , 0.32874]]) </code></pre> <p>You mention that these are individual points, not pairs. If you had saved them as points in the file, one per line, numpy wouldn't assume these are pairs - I would too :)</p> <p>However:</p> <pre><code>singles = [point for pair in data for point in pair] </code></pre> <p>Will convert it to a list of single points.</p>
0
2016-08-25T17:24:52Z
[ "python", "matplotlib", "plot" ]
How to split a list by a changing step size?
39,151,201
<p>I have a list that I want to split up in to variable steps sizes. For example, if I have a list from 1 to 100, at the end of each iteration, I would want the output to be:</p> <pre><code>[1, 2, 3] [4, 5, 6, 7, 8] [9, 10, 11, 12, ..., 15] [16, 17, ..., 25] </code></pre> <p>The length of the first list is 3, then 5, then, 7, then 9.</p> <p>What I have is this</p> <pre><code>lst = list(range(1,101)) odd = 3 for i in range(0, len(lst), odd): print(lst[i:i+odd]) odd += 2 </code></pre> <p>I know it does not work, but I don't know what needs to change.</p>
1
2016-08-25T17:18:18Z
39,151,259
<p>Since the step size varies, you need a while loop:</p> <pre><code>lst = list(range(1,101)) step = 3 idx = 0 while idx&lt;len(lst): print(lst[idx:idx+step]) idx += step step += 2 </code></pre>
2
2016-08-25T17:21:54Z
[ "python", "list", "for-loop" ]
How to split a list by a changing step size?
39,151,201
<p>I have a list that I want to split up in to variable steps sizes. For example, if I have a list from 1 to 100, at the end of each iteration, I would want the output to be:</p> <pre><code>[1, 2, 3] [4, 5, 6, 7, 8] [9, 10, 11, 12, ..., 15] [16, 17, ..., 25] </code></pre> <p>The length of the first list is 3, then 5, then, 7, then 9.</p> <p>What I have is this</p> <pre><code>lst = list(range(1,101)) odd = 3 for i in range(0, len(lst), odd): print(lst[i:i+odd]) odd += 2 </code></pre> <p>I know it does not work, but I don't know what needs to change.</p>
1
2016-08-25T17:18:18Z
39,151,336
<p>Note that the indices to begin a slice at are given by the closed form:</p> <pre><code>n**2 - 1 </code></pre> <p>Therefore:</p> <pre><code>&gt;&gt;&gt; [lst[n**2-1:(n+1)**2-1] for n in range(1, 10)] [[1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48], [49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63], [64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]] </code></pre>
4
2016-08-25T17:26:58Z
[ "python", "list", "for-loop" ]
How to split a list by a changing step size?
39,151,201
<p>I have a list that I want to split up in to variable steps sizes. For example, if I have a list from 1 to 100, at the end of each iteration, I would want the output to be:</p> <pre><code>[1, 2, 3] [4, 5, 6, 7, 8] [9, 10, 11, 12, ..., 15] [16, 17, ..., 25] </code></pre> <p>The length of the first list is 3, then 5, then, 7, then 9.</p> <p>What I have is this</p> <pre><code>lst = list(range(1,101)) odd = 3 for i in range(0, len(lst), odd): print(lst[i:i+odd]) odd += 2 </code></pre> <p>I know it does not work, but I don't know what needs to change.</p>
1
2016-08-25T17:18:18Z
39,151,384
<p>Daniel's answer is the most concise one, but I'd like to point out that sometimes, you have a more complex situation and want to have the same slices from different iterables. Then you can also go along and store the actual <code>slice(start,stop[,step])</code> objects that python generates when you write <code>[start:stop:step]</code> in a list and use that. E.g.:</p> <pre><code>r1 = range(1,101) r2 = list(reversed(r1)) slices = [slice(0,5,3)] for i in range(20): slices.append( slice( slices[-1].stop, slices[-1].stop + slices[-1].step + 1, slices[-1].step + 1) ) print [ (r1[s],r2[s]) for s in slices ] </code></pre>
0
2016-08-25T17:29:26Z
[ "python", "list", "for-loop" ]
Broadcasting mathematical operations with PYMC3/Theano
39,151,247
<p>I think this issue boils down to my lack of understanding with <code>Theano</code> works. I'm in a situation where I want to create a variable that is the result of a subtraction between a distribution and a numpy array. This works fine when I specify the shape parameter as <code>1</code></p> <pre><code>import pymc3 as pm import numpy as np import theano.tensor as T X = np.random.randint(low = -10, high = 10, size = 100) with pm.Model() as model: nl = pm.Normal('nl', shape = 1) det = pm.Deterministic('det', nl - x) nl.dshape (1,) </code></pre> <p>However, this breaks when I specify shape > 1</p> <pre><code>with pm.Model() as model: nl = pm.Normal('nl', shape = 2) det = pm.Deterministic('det', nl - X) ValueError: Input dimension mis-match. (input[0].shape[0] = 2, input[1].shape[0] = 100) nl.dshape (2,) X.shape (100,) </code></pre> <p>I tried transposing X to make it broadcastable</p> <pre><code>X2 = X.reshape(-1, 1).transpose() X2.shape (1, 100) </code></pre> <p>But now it declares a mismatch at <code>.shape[1]</code> instead of <code>.shape[0]</code></p> <pre><code>with pm.Model() as model: nl = pm.Normal('nl', shape = 2) det = pm.Deterministic('det', nl - X2) ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 100) </code></pre> <p>I can make this work if I loop over the elements of the distribution</p> <pre><code>distShape = 2 with pm.Model() as model: nl = pm.Normal('nl', shape = distShape) det = {} for i in range(distShape): det[i] = pm.Deterministic('det' + str(i), nl[i] - X) det {0: det0, 1: det1} </code></pre> <p>However this feels inelegant and constrains me to use loops for the rest of the model. I was wondering if there was a way to specify this operation so that it could work the same as with distributions.</p> <pre><code>distShape = 2 with pm.Model() as model: nl0 = pm.Normal('nl1', shape = distShape) nl1 = pm.Normal('nl2', shape = 1) det = pm.Deterministic('det', nl0 - nl1) </code></pre>
0
2016-08-25T17:21:21Z
39,159,210
<p>You can do</p> <pre><code>X = np.random.randint(low = -10, high = 10, size = 100) X = x[:,None] # or x.reshape(-1, 1) </code></pre> <p>and then</p> <pre><code>with pm.Model() as model: nl = pm.Normal('nl', shape = 2) det = pm.Deterministic('det', nl - X) </code></pre> <p>In this case the shapes of nl and X will be ((2, 1), (100,)), respectively and then broadcastable.</p> <p>Notice we get the same behavior with two NumPy arrays (not only one Theano tensor and one NumPy array)</p> <pre><code>a0 = np.array([1,2]) b0 = np.array([1,2,3,5]) a0 = a0[:,None] # comment/uncomment this line print(a0.shape, b0.shape) b0-a0 </code></pre>
1
2016-08-26T05:57:08Z
[ "python", "theano", "bayesian", "pymc3" ]
Subsetting column from pandas dataframe with indexing
39,151,266
<p>I have a large data set in a pandas dataframe I would like to subset in order to further manipulate. </p> <p>For example, I have a df that looks like this:</p> <pre><code>Sample Group AMP ADP ATP 1 A 0.3840396 0.55635504 0.5844648 2 A 0.3971521 0.57851902 -0.24603208 3 A 0.4578926 0.68118957 0.19129746 4 B 0.400222 0.58370811 0.01782915 5 B 0.4110945 0.60208593 -0.6285537 6 B 0.3307011 -0.82615087 -0.25354715 7 C 0.3485679 -0.79597002 -0.17294609 8 C 0.3408411 -0.8090222 0.76138965 9 C 0.3856457 -0.73333568 0.27364299 </code></pre> <p>Lets say I want to make a new dataframe <code>df2</code> from <code>df</code> that contains only the samples in group B and only the corresponding values for ATP. I should be able to do this from indexing alone.(?)</p> <p>I would like to do something like this:</p> <pre><code>df2 = df[(df['Group']=='B') &amp; (df['ATP'])] </code></pre> <p>I know <code>df['ATP']</code> obviously is not the correct way to do this. Printing <code>df2</code> yields this:</p> <pre><code> Sample Group AMP ADP ATP 4 B 0.400222 0.583708 0.017829 5 B 0.411094 0.602086 -0.628554 6 B 0.330701 -0.826151 -0.253547 </code></pre> <p>Ideally, <code>df2</code> would look like this:</p> <pre><code> Sample Group ATP 4 B 0.017829 5 B -0.628554 6 B -0.253547 </code></pre> <p>Is there a way to do this without resorting to some convoluted looping or simply manually deleting the unwanted columns and their values?</p> <p>Thanks!!!</p>
2
2016-08-25T17:22:31Z
39,151,359
<pre><code>df2 = df.loc[df['Group'] == 'B', ['Sample', 'Group', 'ATP']] </code></pre>
2
2016-08-25T17:28:21Z
[ "python", "pandas", "subset" ]
How to ignore NULL byte when reading a csv file
39,151,276
<p>I'm reading a csv file generated from an equipment and I got this error message:</p> <pre><code>Error: line contains NULL byte </code></pre> <p>I opened the csv file in text editor and I do see there're some NUL bytes in the header section, which I don't really care about. How can I make the csv reader function to ignore the NUL byte and just goes through the rest of the file? </p> <p>There're two blank lines between the header section and the data, maybe there's way to skip the whole header?</p> <p>My code for reading the csv file is </p> <pre><code>with open(FileName, 'r', encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) </code></pre>
-1
2016-08-25T17:23:00Z
39,151,484
<p>This will replace your NULL bytes</p> <pre><code>csvreader = csv.reader(x.replace('\0', '') for x in csvfile) </code></pre>
0
2016-08-25T17:34:42Z
[ "python", "csv" ]
Data Entry error
39,151,295
<p>l would like to create a control system for administrator on Tkinter and some functions (add, delete, update and load) are main part of control system but when l run the code , these functions do not work and there is no error message. But ,l could not figure out where the problem is. My code is still not completed yet. İf l solve it, then l will move to another step.</p> <pre><code>import tkinter from tkinter import * userlist = [ ['Meyers', '12356'], ['Smith','abcde'], ['Jones','123abc34'], ['Barnhart','12//348'], ['Nelson','1234'], ["Prefect",'1345'], ["Zigler",'8910'], ['Smith','1298']] def domain(): def whichSelected () : print ("At %s of %d" % (select.curselection(), len(userlist))) return int(select.curselection()[0]) def addEntry(): userlist.append ([nameVar.get(), passwordVar.get()]) setSelect() def updateEntry(): userlist[whichSelected()] = [nameVar.get(), passwordVar.get()] setSelect() def deleteEntry(): del userlist[whichSelected()] setSelect() def loadEntry(): name, password = userlist[whichSelected()] nameVar.set(name) passwordVar.set(password) def makeWindow(): win=Tk() global nameVar, passwordVar, select frame1 = Frame(win) frame1.pack() Label(frame1, text="Name").grid(row=0, column=0, sticky=W) nameVar = StringVar() name = Entry(frame1, textvariable=nameVar) name.grid(row=0, column=1, sticky=W) Label(frame1, text="Password").grid(row=1, column=0, sticky=W) passwordVar= StringVar() password= Entry(frame1, textvariable=passwordVar) password.grid(row=1, column=1, sticky=W) frame2 = Frame(win) # Row of buttons frame2.pack() b1 = Button(frame2,text=" Add ",command=addEntry) b2 = Button(frame2,text="Update",command=updateEntry) b3 = Button(frame2,text="Delete",command=deleteEntry) b4 = Button(frame2,text=" Load ",command=loadEntry) b1.pack(side=LEFT); b2.pack(side=LEFT) b3.pack(side=LEFT); b4.pack(side=LEFT) frame3 = Frame(win) # select of names frame3.pack() scroll = Scrollbar(frame3, orient=VERTICAL) select = Listbox(frame3, yscrollcommand=scroll.set, height=6) scroll.config (command=select.yview) scroll.pack(side=RIGHT, fill=Y) select.pack(side=LEFT, fill=BOTH, expand=1) return win def setSelect(): userlist.sort() select.delete(0,END) for name in userlist: select.insert(END,name) win=makeWindow() setSelect() win.mainloop() page1=Tk() but1=Button(page1,text="Domain",command=domain).pack() </code></pre>
0
2016-08-25T17:24:34Z
39,151,617
<p>It is bad practice to define your functions in a function and makes debugging pretty difficult. I would start by using an object to create this GUI. Object variables: </p> <ul> <li>passwordVar and nameVar, </li> <li>select</li> <li>userlist</li> <li>win</li> </ul>
0
2016-08-25T17:42:18Z
[ "python", "tkinter" ]
Data Entry error
39,151,295
<p>l would like to create a control system for administrator on Tkinter and some functions (add, delete, update and load) are main part of control system but when l run the code , these functions do not work and there is no error message. But ,l could not figure out where the problem is. My code is still not completed yet. İf l solve it, then l will move to another step.</p> <pre><code>import tkinter from tkinter import * userlist = [ ['Meyers', '12356'], ['Smith','abcde'], ['Jones','123abc34'], ['Barnhart','12//348'], ['Nelson','1234'], ["Prefect",'1345'], ["Zigler",'8910'], ['Smith','1298']] def domain(): def whichSelected () : print ("At %s of %d" % (select.curselection(), len(userlist))) return int(select.curselection()[0]) def addEntry(): userlist.append ([nameVar.get(), passwordVar.get()]) setSelect() def updateEntry(): userlist[whichSelected()] = [nameVar.get(), passwordVar.get()] setSelect() def deleteEntry(): del userlist[whichSelected()] setSelect() def loadEntry(): name, password = userlist[whichSelected()] nameVar.set(name) passwordVar.set(password) def makeWindow(): win=Tk() global nameVar, passwordVar, select frame1 = Frame(win) frame1.pack() Label(frame1, text="Name").grid(row=0, column=0, sticky=W) nameVar = StringVar() name = Entry(frame1, textvariable=nameVar) name.grid(row=0, column=1, sticky=W) Label(frame1, text="Password").grid(row=1, column=0, sticky=W) passwordVar= StringVar() password= Entry(frame1, textvariable=passwordVar) password.grid(row=1, column=1, sticky=W) frame2 = Frame(win) # Row of buttons frame2.pack() b1 = Button(frame2,text=" Add ",command=addEntry) b2 = Button(frame2,text="Update",command=updateEntry) b3 = Button(frame2,text="Delete",command=deleteEntry) b4 = Button(frame2,text=" Load ",command=loadEntry) b1.pack(side=LEFT); b2.pack(side=LEFT) b3.pack(side=LEFT); b4.pack(side=LEFT) frame3 = Frame(win) # select of names frame3.pack() scroll = Scrollbar(frame3, orient=VERTICAL) select = Listbox(frame3, yscrollcommand=scroll.set, height=6) scroll.config (command=select.yview) scroll.pack(side=RIGHT, fill=Y) select.pack(side=LEFT, fill=BOTH, expand=1) return win def setSelect(): userlist.sort() select.delete(0,END) for name in userlist: select.insert(END,name) win=makeWindow() setSelect() win.mainloop() page1=Tk() but1=Button(page1,text="Domain",command=domain).pack() </code></pre>
0
2016-08-25T17:24:34Z
39,151,693
<p>There's a lot going wrong for your code.</p> <p>For instance, you don't need to import <code>tkinter</code> twice. Your casing of the variable names doesn't follow <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>. You could benefit from an <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow">OOP</a> approach.</p> <p>I would suggest finding a good <a href="https://en.wikipedia.org/wiki/Integrated_development_environment" rel="nofollow">IDE</a> to code in that can highlight your formatting and errors.</p> <p>Take a look at the provided code:</p> <pre><code>import tkinter as tk user_list = [ ['Meyers', '12356'], ['Smith','abcde'], ['Jones','123abc34'], ['Barnhart','12//348'], ['Nelson','1234'], ["Prefect",'1345'], ["Zigler",'8910'], ['Smith','1298']] class Domain(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.parent = parent self.name_var = tk.StringVar() self.password_var = tk.StringVar() self.make_window() def which_selected(self): print("At %s of %d" % (self.select.curselection(), len(user_list))) return int(self.select.curselection()[0]) def add_entry(self): user_list.append([self.name_var.get(), self.password_var.get()]) self.set_select() def update_entry(self): user_list[self.which_selected()] = [ self.name_var.get(), self.password_var.get()] self.set_select() def delete_entry(self): del user_list[self.which_selected()] self.set_select() def load_entry(self): name, password = user_list[self.which_selected()] self.name_var.set(name) self.password_var.set(password) def make_window(self): frame1 = tk.Frame(self.parent) frame1.pack() tk.Label(frame1, text="Name").grid(row=0, column=0, sticky=tk.W) name = tk.Entry(frame1, textvariable=self.name_var) name.grid(row=0, column=1, sticky=tk.W) tk.Label(frame1, text="Password").grid(row=1, column=0, sticky=tk.W) password = tk.Entry(frame1, textvariable=self.password_var) password.grid(row=1, column=1, sticky=tk.W) frame2 = tk.Frame(self.parent) # Row of buttons frame2.pack() b1 = tk.Button(frame2, text=" Add ", command=self.add_entry) b2 = tk.Button(frame2, text="Update", command=self.update_entry) b3 = tk.Button(frame2, text="Delete", command=self.delete_entry) b4 = tk.Button(frame2, text=" Load ", command=self.load_entry) b1.pack(side=tk.LEFT) b2.pack(side=tk.LEFT) b3.pack(side=tk.LEFT) b4.pack(side=tk.LEFT) frame3 = tk.Frame(self.parent) # select of names frame3.pack() scroll = tk.Scrollbar(frame3, orient=tk.VERTICAL) self.select = tk.Listbox(frame3, yscrollcommand=scroll.set, height=6) scroll.config(command=self.select.yview) scroll.pack(side=tk.RIGHT, fill=tk.Y) self.select.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) def set_select(self): user_list.sort() self.select.delete(0, tk.END) for name in user_list: self.select.insert(tk.END, name) if __name__ == '__main__': root = tk.Tk() Domain(root) root.mainloop() </code></pre> <p><em>Note:</em> There's still errors here, but I don't exactly know what you're trying to do so I've just restructured it here so you can start on a better path.</p>
0
2016-08-25T17:46:13Z
[ "python", "tkinter" ]
sum columns in dataframe with pandas
39,151,443
<p>I have a dataframe df_F1</p> <p>df_F1.info()</p> <pre><code> &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 7 columns): class_energy 2 non-null object ACT_TIME_AERATEUR_1_F1 2 non-null float64 ACT_TIME_AERATEUR_1_F3 2 non-null float64 dtypes: float64(6), object(1) memory usage: 128.0+ bytes </code></pre> <p>df_F1.head()</p> <pre><code> class_energy ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 low 5.875550 431 medium 856.666667 856 </code></pre> <p>I try to create a dataframe Ratio wich contain for each class_energy the value of energy of each ACT_TIME_AERATEUR_1_Fx devided by the sum of energy of all class_energy for each ACT_TIME_AERATEUR_1_Fx. For example :</p> <blockquote> <pre><code>ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 low 5.875550/(5.875550 + 856.666667) 431/(431+856) medium 856.666667/(5.875550+856.666667) 856/(431+856) </code></pre> </blockquote> <p>Can you help me please to resolve it?</p> <p>Thank you in advancce</p> <p>Best regards</p>
0
2016-08-25T17:31:55Z
39,151,574
<p>you can do this:</p> <pre><code>In [20]: df.set_index('class_energy').apply(lambda x: x/x.sum()).reset_index() Out[20]: class_energy ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 0 low 0.006812 0.334887 1 medium 0.993188 0.665113 </code></pre>
1
2016-08-25T17:39:40Z
[ "python", "pandas", "dataframe", "sum" ]
How to execute some code and have data global available to modules on import
39,151,468
<p>I'm trying to build a package and what I would like is that on import some code would parse some data from a set of files and then have some dictionaries available to my modules. I was wondering what the best way to do something like this would be. Thanks for the help.</p> <p>So if my package is:</p> <pre><code>Package __init__.py *maybe other files* module1 __init__.py foo.py module2 __init__.py bar.py </code></pre> <p>How could I make it so that when I import Package, some set up code will run that reads some files and generates some dictionaries that would then be available to foo.py or bar.py, etc.</p>
0
2016-08-25T17:33:42Z
39,151,938
<pre><code># run.py File where you are trying to display variable from other "global" module import imp def load_module(myglobals, path): with open(path, 'rb') as f: return imp.load_source(myglobals, path, f) filename_path = '/home/turkus/myglobals.py' module = load_module('myglobals', filename_path) print module.CONSTANT # myglobals.py (located in /home/turkus/myglobals.py CONSTANT = 'something' </code></pre> <p>Then run:</p> <pre><code>python run.py </code></pre>
1
2016-08-25T18:00:01Z
[ "python" ]
Calling jsonify on a variable for use in an html file renders incorrectly
39,151,472
<p>Is there any way to store "jsonify" in a variable? I dislike the pure json format of doing "return jsonify(data)" but I like the indentation so I'm trying to pretty it up using a rendered HTML template. Here is my python code:</p> <pre><code>from flask import Flask, jsonify, render_template app = Flask(__name__) @app.route("/") def return_json(): data = {"One": 1, "Two": 2, "Three": 3, "Letters": ['a', 'b', 'c']} html_item = jsonify(data) return render_template("file.html", html_item=html_item) if __name__ == "__main__": app.run() </code></pre> <p>Here is my (at this point very basic) HTML file (file.html):</p> <pre><code>&lt;html&gt; {{ html_item }} &lt;/html&gt; </code></pre> <p>And here is the output I get on my browser at <a href="http://127.0.0.1:5000/" rel="nofollow">http://127.0.0.1:5000/</a></p> <pre><code>&lt;Response 92 bytes [200 OK]&gt; </code></pre> <p>If there isn't a way to store jsonify in a variable, does any one know how I display "data" in a pretty way on the browser? All I can figure out is (1) jsonify and (2) "return data" which is the same as jsonify just without the indentation.</p>
1
2016-08-25T17:34:03Z
39,151,552
<p><code>jsonify()</code> produces a <em>response object</em>, one that <em>contains</em> the JSON data. From the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.json.jsonify" rel="nofollow"><code>flask.json.jsonify()</code> documentation</a>:</p> <blockquote> <p>This function wraps <code>dumps()</code> to add a few enhancements that make life easier. <strong>It turns the JSON output into a <code>Response</code> object with the <code>application/json</code> mimetype.</strong></p> </blockquote> <p>Bold emphasis mine. This is very useful when your route is supposed to produce JSON as the final result, not all that useful when you wanted to use the JSON data in a template.</p> <p>You'd use <a href="http://flask.pocoo.org/docs/0.11/api/#flask.json.dumps" rel="nofollow"><code>flask.json.dumps()</code></a> directly instead:</p> <pre><code>from flask import json @app.route("/") def return_json(): data = {"One": 1, "Two": 2, "Three": 3, "Letters": [a, b, c]} html_item = json.dumps(data, indent=2, separators=(', ', ': ')) return render_template("file.html", html_item=html_item) </code></pre> <p>The <code>indent</code> and <code>separators</code> arguments are what <code>flask.json.jsonify()</code> uses when <code>JSONIFY_PRETTYPRINT_REGULAR</code> is enabled (the default) and this is not an AJAX request.</p> <p>Alternatively, turn the data to JSON <em>in the template</em>, with the <a href="http://flask.pocoo.org/docs/0.11/templating/#standard-filters" rel="nofollow"><code>tojson</code> filter</a>:</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; {{ data|tojson|safe }} &lt;/html&gt; </code></pre> <p>This assumes that <code>data</code> was passed into the template rather than the <code>html_item</code> JSON string. Also note the use of the <code>safe</code> filter there; this makes sure you get the unescaped JSON data you could load with JavaScript code, not an HTML-escaped version.</p> <p>You can pass in the same configuration to that filter:</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; {{ data|tojson(indent=2, separators=(', ', ': '))|safe }} &lt;/html&gt; </code></pre>
3
2016-08-25T17:38:29Z
[ "python", "html", "json", "flask" ]
matplotlib not saving pdf w/ latex
39,151,477
<p>I am having an issue simular to <a href="http://stackoverflow.com/questions/37533912/error-saving-matplotlib-figures-to-pdf-str-object-has-no-attribute-decode">Error saving matplotlib figures to pdf: &#39;str&#39; object has no attribute &#39;decode&#39;</a>, but without the cyrillic letters. My code is below:</p> <pre><code># -*- coding: utf-8 -*- import matplotlib as mpl mpl.rcParams['backend'] = 'pdf' mpl.rc('font',**{'family':'serif'}) mpl.rc('text', usetex=True) mpl.rc('text.latex',unicode=True) import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FuncFormatter millionFormatter = FuncFormatter(lambda x, pos:'\$%1.0fM' % (x*1e-6)) percentFormatter = FuncFormatter(lambda x, pos:'{:.2%}'.format(x)) errorDF = pd.DataFrame({'% Diff':[ -6.12256893e-13, 1.27849915e-12, 6.29839396e-06, 3.38728472e-05, 6.23072435e-06, 5.03582306e-06, -1.09295890e-05, 2.04080118e-04], 'Difference': [ -2.43408203e-01, 4.77478027e-01, 2.31911964e+06, 1.26799125e+07, 2.25939726e+06, 1.55594653e+06, -3.10751878e+06, 5.58644987e+07]} ,index = np.arange(2008,2016)) sns.set_style('ticks') fig = plt.figure(figsize=(5,2)) ax = fig.add_subplot(111) ax2 = ax.twinx() errorDF['% Diff'].plot(kind='bar', position=1, ax=ax, color = 'r', legend=True, label = 'Percent Error',ylim=(0,0.0005), **{'width':0.3}) errorDF.Difference.plot(kind='bar', position=0, ax=ax2,ylim=(0,80000000), legend=True, label = 'Absolute Error [secondary y-axis]', **{'width':0.3}) ax2.legend(loc= 'upper left') ax.set_xlabel('') ax2.set_xlabel('') ax.legend(bbox_to_anchor= (0.286,0.85)) ax.yaxis.set_major_formatter(percentFormatter) ax2.yaxis.set_major_formatter(millionFormatter) ax.yaxis.set_ticks([0,0.0001,0.0002,0.0003, 0.0004]) ax2.yaxis.set_ticks([0,20000000,40000000,60000000]) fig.savefig(r'C:\ . . .\dataerrors.pdf', bbox_inches='tight') </code></pre> <p>When i try to save the figure to a pdf, i get the following traceback.</p> <pre><code>Traceback (most recent call last): File "&lt;ipython-input-46-ee8c792b07cc&gt;", line 21, in &lt;module&gt; fig.savefig(r'C:\Users\Chris\Documents\MIT\Dissertation\FPDS\Visualizations\USASpending\dataerrors.pdf', bbox_inches='tight',dpi=150) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\figure.py", line 1565, in savefig self.canvas.print_figure(*args, **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backend_bases.py", line 2180, in print_figure **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2536, in print_pdf self.figure.draw(renderer) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\figure.py", line 1159, in draw func(*args) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\axes\_base.py", line 2324, in draw a.draw(renderer) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\axis.py", line 1111, in draw tick.draw(renderer) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\axis.py", line 254, in draw self.label2.draw(renderer) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\text.py", line 792, in draw mtext=mtext) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backends\backend_pdf.py", line 1866, in draw_tex psfont = self.tex_font_mapping(dvifont.texname) File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backends\backend_pdf.py", line 1568, in tex_font_mapping return self.tex_font_map[texfont] File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\dviread.py", line 701, in __getitem__ result = self._font[texname.decode('ascii')] AttributeError: 'str' object has no attribute 'decode' </code></pre> <p>The figure will show fine in the console, but the above error is generated when i try to save it to pdf.</p> <p>Python 3.4 Matplotlib 1.5.1 OS Windows 7</p>
1
2016-08-25T17:34:20Z
39,154,293
<p>It seems that I had the same issue caused by the lack of some necessary fonts in my MikTex installation. For me the solution was to reinstall it with all packages to make sure that all fonts are generated. I know that is an ugly workaround, but it solved my problem completely. I've tried your script (only without seaborn, which does not affect fontstyles, I beleive) and generated pdf.</p> <p>There is also another workaround with XeTeX, you may have a look <a href="http://stackoverflow.com/questions/37533912/error-saving-matplotlib-figures-to-pdf-str-object-has-no-attribute-decode/37922573#37922573">here</a>.</p>
1
2016-08-25T20:33:17Z
[ "python", "pdf", "matplotlib", "latex" ]
Finding daily patterns in timestamps data with python
39,151,482
<p>So i want to analyze database data of smart house. This is how data i have look like: </p> <pre><code>ID NAME STATUS TIME 1 light 1 2016-06-25 08:00:00 2 light 1 2016-06-25 08:01:05 3 light 1 2016-06-25 08:00:21 4 light 1 2016-06-25 08:00:30 ... </code></pre> <p>Basically to calculate all i need is divide (number of light turns on at certain hour) by number of different dates at certain hour.</p>
0
2016-08-25T17:34:36Z
39,151,711
<p>This script takes lowest and maximum time from database and calculate time between these times.</p> <pre><code># db.txt 1 light 1 2016-06-25 08:00:00 1 light 1 2016-06-25 08:01:05 1 light 1 2016-06-25 08:00:21 1 light 1 2016-06-25 08:00:30 # python script import datetime def data(): with open('db.txt', 'r') as f: for line in f.readlines(): row = line.split() if row[2] == '1': yield row[4] data = sorted(data()) early = datetime.datetime.strptime(data[0], '%H:%M:%S') lately = datetime.datetime.strptime(data[1], '%H:%M:%S') sth_between = (lately - early)/2 print (early + sth_between).time() </code></pre>
1
2016-08-25T17:47:13Z
[ "python", "machine-learning", "statistics", "artificial-intelligence" ]
Initialize nested classes from JSON in Python?
39,151,488
<p>When writing APIs I often need to initialize classes from nested JSONs like this</p> <pre><code># When my API receives such a ... n_json = {"nested1": {"nested2" : { "nested3" : "..." }}} # .. I need to instantiate a proper object out of it ... nested1 = Nested1.from_json(json.loads(n_json)) # ... so I can later use the instance in OOP style. nested1.nested2.run_an_intance_method() </code></pre> <p>In my code this results in cascades of</p> <pre><code>class Nested1: @classmethod def from_json(json): self.nested2=Nested2.from_json(json.nested2) </code></pre> <p>With every layer of nesting this gets more repetetive and error prone. Any clever way to do this?</p>
1
2016-08-25T17:34:52Z
39,152,685
<p>This is how you can create a nested object from JSON (similarly to how PHP does that). To create object tree from JSON (rather, parsed JSON, which is just a Python structure), write the following class:</p> <pre><code>class Nested: def __new__(cls, structure): self = super(Nested, cls).__new__(cls) if type(structure) is dict: self.__dict__ = {key: Nested(structure[key]) for key in structure} elif type(structure) is list: self = [Nested(item) for item in structure] else: self = structure return self </code></pre> <p>and call it from your parsed JSON. For example:</p> <pre><code>import json s = json.dumps({'a': 1, 'b': {'c': [1, 2, {'d': 3}], 'e': {'f': 'g'}}}) result = Nested(json.loads(s)) print(result.a) # 1 print(result.b.c) # [1, 2, &lt;__main__.Nested object at 0x00000297A983D828&gt;] print(result.b.c[0]) # 1 print(result.b.c[2].d) # 3 </code></pre> <hr> <p>Here is what is how the class works:</p> <ol> <li><p><code>__new__</code> is invoked before anything else. Here we construct an instance of an object (empty)</p></li> <li><p>If new is list, we replace self with list of nested objects, so that <code>Nested({'a': [1, 2, 3]).a</code> is equal to <code>[Nested(1), Nested(2), Nested(3)]</code> (which also equals to just <code>[1, 2, 3]</code>, see number 4)</p></li> <li><p>If new is dict, for each key we create a property with the same name and assign <code>Nested(dict[key])</code> to it.</p></li> <li><p>If any other type, just assign value to self (replace <code>self</code> with value) so that <code>Nested({'a': ['b', 'c', 'd']}).a[0]</code> equals <code>'b'</code>, not <code>Nested(..)</code></p></li> </ol>
0
2016-08-25T18:47:56Z
[ "python", "json", "api", "web-applications" ]
Finding a sum of series in Python 2.7.x
39,151,536
<p>Here's the equation </p> <pre><code>x + x^2/2 + x^3/3 +.... x^n/n </code></pre> <p>How will I find the sum of this series? x is a constant term to be entered by user and n which is power is also based on user! </p> <p>I made this program but it's not working properly.. Have a look - </p> <pre><code>n=input("Enter power ") x=input("Enter value of x") i=0 while i&lt;n: c=n-1 res=(x**(n-c))/(n-(c)) print res i=i+1 </code></pre> <p>So how do we make it? Thanks a ton for your help!</p> <p>Update : The answers helped me and now the program is working as it should! This was my first time using Stackoverflow! Thanks to everyone for this.</p>
1
2016-08-25T17:37:37Z
39,151,609
<p>Something like this for your loop? Tried to keep it simple.</p> <pre><code>n = input("Enter power ") x = float(input("Enter value of x")) ans = 0 for i in range(1, n+1): ans += x**i/i print(ans) </code></pre> <p>See zev's answer regarding floats</p>
2
2016-08-25T17:42:02Z
[ "python" ]
Finding a sum of series in Python 2.7.x
39,151,536
<p>Here's the equation </p> <pre><code>x + x^2/2 + x^3/3 +.... x^n/n </code></pre> <p>How will I find the sum of this series? x is a constant term to be entered by user and n which is power is also based on user! </p> <p>I made this program but it's not working properly.. Have a look - </p> <pre><code>n=input("Enter power ") x=input("Enter value of x") i=0 while i&lt;n: c=n-1 res=(x**(n-c))/(n-(c)) print res i=i+1 </code></pre> <p>So how do we make it? Thanks a ton for your help!</p> <p>Update : The answers helped me and now the program is working as it should! This was my first time using Stackoverflow! Thanks to everyone for this.</p>
1
2016-08-25T17:37:37Z
39,151,666
<p>You're not adding the terms together. </p> <p><strong><em>Also</em></strong>, you need to be careful that you use float division when <code>x</code> is an integer. <a href="http://stackoverflow.com/q/1267869/1090302">See this thread</a>.</p> <p>Here's a working implementation:</p> <pre><code>n = input("Enter power: ") x = input("Enter value of x: ") result = 0 for i in range(1, n+1): result += (x**i) / float(i) print result </code></pre>
2
2016-08-25T17:44:52Z
[ "python" ]
Finding a sum of series in Python 2.7.x
39,151,536
<p>Here's the equation </p> <pre><code>x + x^2/2 + x^3/3 +.... x^n/n </code></pre> <p>How will I find the sum of this series? x is a constant term to be entered by user and n which is power is also based on user! </p> <p>I made this program but it's not working properly.. Have a look - </p> <pre><code>n=input("Enter power ") x=input("Enter value of x") i=0 while i&lt;n: c=n-1 res=(x**(n-c))/(n-(c)) print res i=i+1 </code></pre> <p>So how do we make it? Thanks a ton for your help!</p> <p>Update : The answers helped me and now the program is working as it should! This was my first time using Stackoverflow! Thanks to everyone for this.</p>
1
2016-08-25T17:37:37Z
39,151,921
<p>Issue with your program is that your are not adding the sum. See: <code>res=(x**(n-c))/(n-(c))</code>. Instead do:</p> <pre><code>res += (x**(n-c))/(n-(c)) </code></pre> <p>You may also achieve it by using in-built <code>sum</code>, <code>map</code> and <code>lambda</code> functions as:</p> <pre><code>y = 5 # or any of your number sum(map(lambda x: (y**x)/float(x), xrange(1, y))) </code></pre>
0
2016-08-25T17:59:17Z
[ "python" ]
Convert sparse pandas dataframe with `NaN` into integer values
39,151,545
<p>I have a binary pandas dataframe with values <code>0.0</code>, <code>1.0</code>, and <code>NaN</code>. </p> <pre><code>import pandas as pd df = pd.read_csv("file.csv") </code></pre> <p>I would like to turn the floats <code>1.0</code> and <code>0.0</code> into integers <code>1</code> and <code>0</code>. Unfortunately, because of <code>NaN</code> value, this command fails:</p> <pre><code>df.applymap(int) </code></pre> <p>The error is:</p> <pre><code>ValueError: ('cannot convert float NaN to integer', 'occurred at index 0') </code></pre> <p>Are there "pandas" alternatives? </p>
1
2016-08-25T17:38:00Z
39,152,098
<p><strong>UPDATE:</strong></p> <p>if you need nice looking <strong>string</strong> values you can do it:</p> <pre><code>In [84]: df.astype(object) Out[84]: a b c 0 0 1 0 1 0 0 1 2 1 1 1 3 0 1 1 4 1 1 NaN </code></pre> <p>but all values - are strings (<code>object</code> in pandas terms):</p> <pre><code>In [85]: df.astype(object).dtypes Out[85]: a object b object c object dtype: object </code></pre> <p>Timings against 500K rows DF:</p> <pre><code>In [86]: df = pd.concat([df] * 10**5, ignore_index=True) In [87]: df.shape Out[87]: (500000, 3) In [88]: %timeit df.astype(object) 10 loops, best of 3: 113 ms per loop In [89]: %timeit df.applymap(lambda x: int(x) if pd.notnull(x) else x).astype(object) 1 loop, best of 3: 7.86 s per loop </code></pre> <p><strong>OLD answer:</strong></p> <p>AFAIK you can't do it using modern pandas versions. </p> <p>Here is a demo:</p> <pre><code>In [52]: df Out[52]: a b c 0 1.0 NaN 0.0 1 NaN 1.0 1.0 2 0.0 0.0 NaN In [53]: df[pd.isnull(df)] = -1 In [54]: df Out[54]: a b c 0 1.0 -1.0 0.0 1 -1.0 1.0 1.0 2 0.0 0.0 -1.0 In [55]: df = df.astype(int) In [56]: df Out[56]: a b c 0 1 -1 0 1 -1 1 1 2 0 0 -1 </code></pre> <p>we are almost there, let's replace <code>-1</code> with <code>NaN</code>:</p> <pre><code>In [57]: df[df &lt; 0] = np.nan In [58]: df Out[58]: a b c 0 1.0 NaN 0.0 1 NaN 1.0 1.0 2 0.0 0.0 NaN </code></pre> <p>Another demo:</p> <pre><code>In [60]: df = pd.DataFrame(np.random.choice([0,1], (5,3)), columns=list('abc')) In [61]: df Out[61]: a b c 0 1 0 0 1 1 0 1 2 0 1 1 3 0 0 1 4 0 0 1 </code></pre> <p>look what happens with <code>c</code> column if we change a single cell in it to <code>NaN</code>:</p> <pre><code>In [62]: df.ix[4, 'c'] = np.nan In [63]: df Out[63]: a b c 0 1 0 0.0 1 1 0 1.0 2 0 1 1.0 3 0 0 1.0 4 0 0 NaN </code></pre>
1
2016-08-25T18:10:58Z
[ "python", "pandas", "binary", "int" ]
Where to put .theanorc file for Anaconda installation? (Windows)
39,151,628
<p>I recently installed Python 2.7 using Anaconda on my Windows 10 (x64)</p> <p>I am trying to install Theano, I am however not sure where I should put the '.theanorc' file (for setting Theano parameters). I have verified that theano works (trained small neural network).</p> <p>I have tried to put it in <code>C:\Anaconda</code> (where <code>python.exe</code> and <code>\Lib\os.py</code> are located), but it doesn't seem like theano registers it.</p> <p>My <code>.theanorc</code> file</p> <pre><code>[global] floatX=float32 </code></pre> <p>When I type</p> <pre><code>&gt;&gt;&gt; import theano; print(theano.config) </code></pre> <p>I get</p> <pre><code>... floatX (('float64', 'float32', 'float16')) Doc: Default floating-point precision for python casts. Note: float16 support is experimental, use at your own risk. Value: float64 ... </code></pre>
1
2016-08-25T17:42:48Z
39,152,622
<p>dotfiles are typically stored in the <code>%HOME%</code> directory, which on windows is <code>%USERPROFILE%</code>. This translates to <code>C:\Users\username</code></p>
3
2016-08-25T18:44:14Z
[ "python", "windows", "python-2.7", "anaconda", "theano" ]
Eloqua delete canvas dependencies using REST API
39,151,732
<p>I need to delete a big number of canvases and they have filters and segments as dependencies. </p> <p>I've done an application in Python which sends API calls to get the segments and filters by using a search key but I can't delete them because they are dependencies in canvases.</p> <p>Is there a way to delete the segments and filters using Eloqua REST API? The segments are also dependencies on some newer canvases that shouldn't be deleted.</p> <p>Thanks for the help!</p>
0
2016-08-25T17:48:50Z
39,824,955
<p>If the Campaign Canvas has dependencies, that means the Campaign Canvas is explicitly referenced. In example, the dependent Segment or Filter includes a "Clicked Emails from Campaigns" filer criteria that references the Campaign Canvas.</p> <p>In this example, in order to remove dependencies, you must edit the criteria to not include the Campaign Canvas you want to delete. </p>
0
2016-10-03T05:16:41Z
[ "python", "rest", "api", "eloqua" ]
parsing a dictionary from file in python using argparse?
39,151,817
<p>I have been using a file containing variables as input for a program, which is then imported into the main program at runtime. I am moving this system to using argparse reading the input values from a file. One of the current input variables is a list of dictionaries, with each dictionary providing settings for a given calculation. </p> <pre><code>CalculationVals=[{'startx':0,'starty':0,'endx':10, 'endy':10}, {'startx':1,'starty':1,'endx':12, 'endy':12}] </code></pre> <p>and then in the main part of the program, the individual CalculationVals are looped over. Is there a way to read this using argparse, or a better way to provide this input using an argparse method? Not relying on additional packages is advantageous here.</p>
0
2016-08-25T17:53:33Z
39,152,178
<p>That is not what argparse is for. It is for parsing command line arguments, not config files.</p> <p>It looks like your config is in JSON and unless you do something extremely weird and heavily abuse the library, argparse does not know how to parse JSON. So to understand the parameters you'd need to <code>import json</code> anyway. At which point the easiest (and most efficient) thing to do would be</p> <pre><code>import json with open('/your/config/file', 'r') as f: config = json.loads(f.read()) </code></pre>
1
2016-08-25T18:15:19Z
[ "python", "argparse" ]