title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to split a string by tabs but only once per occurrence
38,056,585
<p>I have a string structured like this:</p> <pre><code>"I\thave\ta\t\tstring" </code></pre> <p>And in order split by tabs I used this method:</p> <pre><code>text = [splits for splits in row.split("\t") if splits is not ""] </code></pre> <p>Now this method removes all tabs from the string but I want it to remove on...
1
2016-06-27T14:28:17Z
38,056,713
<p>Using <code>re.split</code> on a negative look behind assertion should do:</p> <pre><code>import re s = ''.join(re.split(r'(?&lt;!\t)\t', row)) print(s) # 'Ihavea\tstring' </code></pre> <p>The assertion <code>(?&lt;!\t)</code> prevents a split on a <code>\t</code> which was preceded by another <code>\t</code>. </...
2
2016-06-27T14:34:17Z
[ "python", "python-2.7" ]
How to split a string by tabs but only once per occurrence
38,056,585
<p>I have a string structured like this:</p> <pre><code>"I\thave\ta\t\tstring" </code></pre> <p>And in order split by tabs I used this method:</p> <pre><code>text = [splits for splits in row.split("\t") if splits is not ""] </code></pre> <p>Now this method removes all tabs from the string but I want it to remove on...
1
2016-06-27T14:28:17Z
38,056,778
<p>To keep it simple you can use <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split</code></a></p> <pre><code>from re import split text = "I\thave\ta\t\tstring" split_string = split(r'\t+', text) #Gives ['I', 'have', 'a', 'string'] </code></pre> <p>The regular expression <code...
1
2016-06-27T14:37:18Z
[ "python", "python-2.7" ]
How to split a string by tabs but only once per occurrence
38,056,585
<p>I have a string structured like this:</p> <pre><code>"I\thave\ta\t\tstring" </code></pre> <p>And in order split by tabs I used this method:</p> <pre><code>text = [splits for splits in row.split("\t") if splits is not ""] </code></pre> <p>Now this method removes all tabs from the string but I want it to remove on...
1
2016-06-27T14:28:17Z
38,058,119
<p>List comprehension is also a way to go if you want to avoid to import the re module:</p> <pre><code>row = "I\thave\ta\t\tstring" text = [splits if splits else "\t" for splits in row.split("\t")] "".join(text) #'Ihavea\tstring' </code></pre> <p>An empty string is in a boolean context false and empty list elements ...
1
2016-06-27T15:42:32Z
[ "python", "python-2.7" ]
How can I store binary values with trailing nulls in a numpy array?
38,056,642
<p>I'm trying to store fixed width binary data in a numpy array. However, if my data has trailing nulls, they get stripped. They do work if I use the void type, but I want to keep them as byte strings. Is there a way to do this?</p> <pre><code>&gt;&gt;&gt; import numpy as np # Works &gt;&gt;&gt; varr = np.array([(...
4
2016-06-27T14:30:48Z
38,058,660
<p>It dawned on me that I could side-step numpy's processing of the strings by specifying the type as an object.</p> <pre><code>&gt;&gt;&gt; np.array([(b'abc\x00\x00',), (b'de\x00\x00\x00',)], dtype='O') [[b'abc\x00\x00'] [b'de\x00\x00\x00']] </code></pre>
1
2016-06-27T16:12:20Z
[ "python", "arrays", "numpy" ]
Deploying a multiple window app in Kivy
38,056,678
<p><a href="http://stackoverflow.com/questions/31458331/running-multiple-kivy-apps-at-same-time-that-communicate-with-each-other">This</a> thread shows a way to open multiple windows in a Kivy app. It's necessary to create more than one app and then call the app that opens a new window when needed. I've never deployed ...
0
2016-06-27T14:32:27Z
38,057,150
<p>Yes this is possible. I did the same. I assume this counts for a windows application? If so I can provide you with a basic module framework which you could use. You need to make use of multiprocessing features where you instantiate separate kivy apps. Each app has it's own window definitions. Furthermore I make use ...
0
2016-06-27T14:54:26Z
[ "python", "kivy" ]
Deploying a multiple window app in Kivy
38,056,678
<p><a href="http://stackoverflow.com/questions/31458331/running-multiple-kivy-apps-at-same-time-that-communicate-with-each-other">This</a> thread shows a way to open multiple windows in a Kivy app. It's necessary to create more than one app and then call the app that opens a new window when needed. I've never deployed ...
0
2016-06-27T14:32:27Z
38,057,351
<p>First thing: Window != <a href="https://i.ytimg.com/vi/U14ZpnAmoXg/maxresdefault.jpg" rel="nofollow"><em>Form</em></a>. The question (and answer) only show a way how to communicate between multiple <em>apps</em>(multiple standalone things) and how to run multiple <em>apps</em> from the same interpreter. It may look ...
0
2016-06-27T15:04:17Z
[ "python", "kivy" ]
Adding bytes in python 2.7
38,056,711
<p>Hi I've been trying to iterate through a bytearray, add up all the bytes and then append the result back into the same bytearray. The bytearray looks like this: key = bytearray([0x12, 0x10, 0x32]) However, when I call sum(key) I get the decimal representation of 84. Any idea how I can change the decimal representat...
0
2016-06-27T14:34:13Z
38,056,839
<p>A <code>bytearray</code> is always a list of integers. How they are displayed is only their representation. The same applies to the way you entered them. Python understand the <code>0x??</code> (hexadicimal) and <code>0??</code> (octal) notation for integers but it will display the decimal notation.</p> <p>To conve...
1
2016-06-27T14:40:38Z
[ "python", "binary", "hex", "byte", "bytearray" ]
Transferring certain messages from a log to another
38,056,792
<p>I need to read a file, then take certain lines of the file, then write the lines I need to another file. I'm kinda stuck and can't seem to find a solution. The lines that need to be taken from <code>bi_server1-diagnostic.log</code> need to have the word <code>biserviceadministration</code> in them. Then they can be ...
0
2016-06-27T14:38:09Z
38,057,037
<p>You were really close. What was your problem? I would use the full paths for the files but it can also be done like that.</p> <pre><code>with open('bi_server1-diagnostic.log', 'r') as infile: with open ('SAC Report.log', 'w') as outfile: for line in infile: if 'biserviceadministration' in li...
1
2016-06-27T14:49:19Z
[ "python", "logfiles" ]
executing .py file in IPython
38,056,895
<p>Is there a way to run a <code>.py</code> file containing functions etc. from within the notebook such that the content of the <code>.py</code> file is treated as if it were directly in that cell?</p> <p>For instance, say I have the file <code>example.py</code> in which a function <code>test1</code> is defined that ...
2
2016-06-27T14:42:39Z
38,057,088
<p>In Python2 the <code>execfile</code> function would do what you want. In Python 3 you have to emulate that by reading the contents of the file, compiling it and then making sure that it executes in the right namespace.</p> <p>In a notebook cell I defined:</p> <pre><code>def f4(x): return x+x </code></pre> <p>...
3
2016-06-27T14:52:02Z
[ "python", "ipython" ]
PyQt - access data of another interface?
38,056,944
<p>I have a python script with 2 classes, each one is a different PyQt interface.</p> <p>The first one is the main interface, and the second one is a "pop-up interface" - it appears when you click a button in the main interface.</p> <p>Whenever that pop-up interface is launched via the main interface, i need it to di...
0
2016-06-27T14:44:43Z
38,094,905
<p>Just pass the data into the constructor for <code>PopUp</code></p> <pre><code>class PopUp(QtGui.QDialog): def __init__(self, data, parent=None): super(MyDialog, self).__init__(parent) self.data = data </code></pre> <p>If this is not feasible due to the design of your project, you can use <a hre...
1
2016-06-29T09:02:32Z
[ "python", "user-interface", "pyqt" ]
How do I handle database columns with reserved characters in SQLAlchemy ORM?
38,057,077
<p>I'm somewhat new to SQLAlchemy ORM, and I'm trying to select and then store data from a column within a view that has a forward slash in the name of the column.</p> <p>The databases are mapped using the following:</p> <pre><code>source_engine = create_engine("...") base = automap_base() base.prepare(source_engine,...
0
2016-06-27T14:51:15Z
38,057,737
<p>Thanks to @DeepSpace for helping me find the answer.</p> <p>Instead of </p> <pre><code>newrow.whatever = instance.whatever </code></pre> <p>I needed:</p> <pre><code>setattr(newrow, 'Slot/Port', getattr(instance, 'Slot/Port')) </code></pre>
0
2016-06-27T15:23:31Z
[ "python", "database", "python-2.7", "orm", "sqlalchemy" ]
Test os methods
38,057,117
<p>How would one test the <code>os</code> module methods provided in python. For example how would you test the use of <code>os.mkdir</code>?</p> <pre><code>def create_folder(self): os.mkdir("/parentFolder/newFolder") </code></pre> <p>What can be used to test this method?</p> <p>This method would have test cases...
1
2016-06-27T14:53:05Z
38,057,268
<p>To check if the directory was created you can use </p> <pre><code>os.path.isdir() </code></pre> <p>As for the permission: there is a python idiom which says</p> <blockquote> <p>It's easier to ask for forgiveness than for permission</p> </blockquote> <p>In that case i would try to create the folder and catch th...
0
2016-06-27T14:59:46Z
[ "python", "unit-testing" ]
Test os methods
38,057,117
<p>How would one test the <code>os</code> module methods provided in python. For example how would you test the use of <code>os.mkdir</code>?</p> <pre><code>def create_folder(self): os.mkdir("/parentFolder/newFolder") </code></pre> <p>What can be used to test this method?</p> <p>This method would have test cases...
1
2016-06-27T14:53:05Z
38,057,605
<p>When unit-testing <code>create_folder</code>, you <em>don't</em> test <code>os.mkdir</code>. This is for two reasons:</p> <ol> <li><p>It is part of an external library (in this case the standard library, but the same would be the case for third-party libraries), so should be covered by the test suites for that libr...
2
2016-06-27T15:17:07Z
[ "python", "unit-testing" ]
Gtk3+ Pygobject select columns in a TreeView
38,057,144
<p>Is there an efficient way/a way at all to retrieve the column of the selected cell in a ListModel when a user clicks on a cell in a TreeView? Or is there no such things as Cells and only Rows can be selected and return their treeiter/model when I call the get_selected() method?</p> <p>I would like to present the us...
0
2016-06-27T14:54:12Z
38,067,046
<p>Accessing 'columns' in GtkTreeView is a little more complicated than suspected at first sight. One of the reasons is that columns can actually contain several items, which are then shown as new column, even though they are 'packed'.</p> <p>One way to identify columns is to assign a sort_id to each, but that would m...
1
2016-06-28T04:24:33Z
[ "python", "gtk3", "pygobject" ]
Django Rest Framework - Serializing Many To Many fields attributes to POST operation
38,057,155
<p>I have the following model</p> <pre><code>class Metrics(models.Model): name = models.CharField( max_length=255, blank=True, verbose_name='Nombre' ) value = models.DecimalField( max_digits = 5, decimal_places = 3, verbose_name = 'Valor', null = True...
0
2016-06-27T14:54:42Z
38,062,553
<p>Well, as it says, lists are not supported in HTML input.</p> <p>As you can see here (<a href="http://www.django-rest-framework.org/topics/3.2-announcement/" rel="nofollow">http://www.django-rest-framework.org/topics/3.2-announcement/</a>), it was planned for 3.3 release but there's no mention of it in the release n...
1
2016-06-27T20:21:26Z
[ "python", "django", "serialization", "django-rest-framework" ]
Set ENV variables using Ansible command line
38,057,274
<p>I am trying to set an environment variable on my machine with Ansible. Then I would reference that in my python script. Is there a command line tag for Ansible that will set that environment variable such as:</p> <pre><code>ansible all -i inventory.py --env environment_name -m ping </code></pre> <p>I can't seem to...
0
2016-06-27T14:59:56Z
38,059,357
<p>We have a win_environment module for Windows, but that makes sense because Windows has a single dedicated place to store system and user envvars. It doesn't really make sense on a *nix system- how would Ansible know where to persist it (/etc/profile, .bashrc, .cshrc, .bash_profile, or any of a dozen other places)? <...
0
2016-06-27T16:57:02Z
[ "python", "command-line", "environment-variables", "ansible" ]
matplotlib display images from left to right to bottom (matlab montage)
38,057,300
<p>Is there a way I can display a list of images with one function ? In matlab there is montage. Currently if I for loop and imshow matplotlib displays the images from top to bottom. I would like it to be from left to right then to bottom when no space. My code is below but it is stupid code of course.</p> <pre><code>...
-1
2016-06-27T15:01:34Z
38,060,551
<p>You can do something like this with the <a href="http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html" rel="nofollow"><code>ImageGrid</code></a> class.</p> <p>This is adapted from the above documentation:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid impor...
0
2016-06-27T18:14:14Z
[ "python", "matlab", "numpy", "matplotlib", "montage" ]
Is it safe to remove all python *.pyc files to force usage of new code?
38,057,302
<p><strong>TL;DR</strong></p> <ul> <li>Is it safe to pick all <code>*.pyc</code> (that has a matching <code>*.py</code> file) files and remove them to force usage of new code?</li> <li>Is there a way to locate and re-compile all <code>.py</code> files found on disc while overwriting existing <code>.pyc</code> files?</...
1
2016-06-27T15:01:37Z
38,199,438
<h3>First approach,</h3> <p>Use the following python script which removes <code>*.pyc</code> files that has a matching <code>*.py</code> file </p> <p><strong>python-cache-flusher.py</strong> (your'e welcome to <strong><a href="https://github.com/jossef/python-cache-flusher/blob/master/src/python-cache-flusher.py" rel...
0
2016-07-05T09:10:32Z
[ "python", "pyc" ]
Reshaping a pandas correlation matrix
38,057,416
<p>I have the following correlation matrix which was created using pandas: <code>df.corr()</code></p> <pre><code>symbol aaa bbb ccc ddd eee symbol aaa 1.000000 0.346099 0.131874 -0.150910 0.177589 bbb 0.346099 1.000000 0.17730...
1
2016-06-27T15:07:41Z
38,057,451
<p>You need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>#reset columns and index names df = df.rename_axis(None).rename_axis(None, axis=1) #pandas bellow 0.18.0 #df.columns.name = None #df.index.name...
1
2016-06-27T15:09:08Z
[ "python", "pandas", "matrix", "dataframe", "reshape" ]
How to create a parameterized job with Jenkins api
38,057,468
<p>I am using Jenkins python api to create a parameterized job, I can create a job with one parameter using the following config.xml</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;project&gt; &lt;actions/&gt; &lt;description&gt;A build that explores the wonderous possibilities of parameterized bui...
0
2016-06-27T15:10:21Z
38,057,804
<p>Each parameter needs its own hudson.model.StringParameterDefinition section. It sounds like you're trying to put multiple names inside one StringParameterDefintion section, which won't work.</p> <p>If in doubt, create the job by hand, then go to the page for that job and append '/config.xml'. You will get back th...
4
2016-06-27T15:26:46Z
[ "python", "jenkins", "continuous-integration" ]
HyperVolume function not working in Python 3
38,057,598
<p>Based on a HyperVolume function found <a href="https://ls11-www.cs.uni-dortmund.de/rudolph/hypervolume/start" rel="nofollow"><strong>here</strong></a> (direct download <a href="https://ls11-www.cs.uni-dortmund.de/_media/rudolph/hypervolume/hv_python.zip" rel="nofollow">link</a>), I am trying to return hypervolume me...
1
2016-06-27T15:16:51Z
38,058,134
<p>Use 2to3 to convert hv.py to hv3.py:</p> <pre><code>$ 2to3 hv.py &gt; hv3.py.patch $ cp hv.py hv3.py $ patch &lt; hv3.py.patch </code></pre> <p>Then change your import line to</p> <pre><code>from hv3 import HyperVolume </code></pre> <p>If you want <code>2to3</code> to change the modify the original file, you nee...
1
2016-06-27T15:43:35Z
[ "python", "deap" ]
Python how to resize images?
38,057,604
<p>I am getting confused over all the different python datatypes. I wrote a face recognition algorithm in MATLAB, I want to redo it it Python. I am stuck trying to resize my images. How do I do that? Can someone link me to the things that i need to read to understand the difference in the functions between MATLAB in Py...
-2
2016-06-27T15:17:06Z
38,061,965
<p>using the jupyter qt-console interpreter, or jupyter notebook you can set the interpreter environment magic %pylab inline so that images will be displayed inline and the matplotlib.pylab namespace and numpy namespaces will be imported into the current namespace. All this means though is that you don't have to prefi...
0
2016-06-27T19:40:43Z
[ "python", "matlab", "matplotlib", "python-imaging-library" ]
Finding one or more strings of a certain kind in a list of tuples
38,057,632
<p>Let's say I have the following tuples:</p> <pre><code>tagged = [('They', 'PRP'), ('refuse', 'VBP'), ('to', 'TO'), ('permit', 'VB'), ('us', 'PRP'), ('to', 'TO'), ('obtain', 'VB'), ('the', 'DT'), ('refuse', 'NN'), ('permit', 'NN')] </code></pre> <p>I want to take all combinations of one or more nouns (that ...
1
2016-06-27T15:18:28Z
38,058,288
<p>This is a pretty simple <code>groupby</code> operation with a little processing. If we group by the tags and only look at the groups of nouns then we're almost there. The only thing to be done then is join the groups that have more than 1 item and put the stuff in the output in the proper order:</p> <pre><code>fr...
2
2016-06-27T15:51:26Z
[ "python", "nltk" ]
Finding specific tag using BeautifulSoup
38,057,756
<p>Here is the website that i'm parsing: <a href="http://uniapple.net/usaddress/address.php?address1=501+10th+ave&amp;address2=&amp;city=nyc&amp;state=ny&amp;zipcode=10036&amp;country=US" rel="nofollow">http://uniapple.net/usaddress/address.php?address1=501+10th+ave&amp;address2=&amp;city=nyc&amp;state=ny&amp;zipcode=1...
1
2016-06-27T15:24:23Z
38,057,953
<p>All you are missing is a bit of housekeeping:</p> <pre><code>ths = thesoup.find_all("th") for th in ths: if 'Residential or' in th.text: comres = th.find_next("td").text print(str(comres)) &gt;&gt; Commercial </code></pre>
1
2016-06-27T15:33:13Z
[ "python", "html", "beautifulsoup", "html-parsing" ]
Finding specific tag using BeautifulSoup
38,057,756
<p>Here is the website that i'm parsing: <a href="http://uniapple.net/usaddress/address.php?address1=501+10th+ave&amp;address2=&amp;city=nyc&amp;state=ny&amp;zipcode=10036&amp;country=US" rel="nofollow">http://uniapple.net/usaddress/address.php?address1=501+10th+ave&amp;address2=&amp;city=nyc&amp;state=ny&amp;zipcode=1...
1
2016-06-27T15:24:23Z
38,057,962
<p><code>text</code> argument would not work in this particular case. This is related to how the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string" rel="nofollow"><code>.string</code> property</a> of an element is calculated. Instead, I would use a <a href="https://www.crummy.com/software/Beautiful...
1
2016-06-27T15:33:44Z
[ "python", "html", "beautifulsoup", "html-parsing" ]
Finding specific tag using BeautifulSoup
38,057,756
<p>Here is the website that i'm parsing: <a href="http://uniapple.net/usaddress/address.php?address1=501+10th+ave&amp;address2=&amp;city=nyc&amp;state=ny&amp;zipcode=10036&amp;country=US" rel="nofollow">http://uniapple.net/usaddress/address.php?address1=501+10th+ave&amp;address2=&amp;city=nyc&amp;state=ny&amp;zipcode=1...
1
2016-06-27T15:24:23Z
38,058,181
<p>You'll need to use a regular expression as your text field, like <code>re.compile('Residential or')</code>, rather than a string.</p> <p>This was working for me. I had to iterate over the results provided, though if you only expect a single result per page you could swap <code>find</code> for <code>find_all</code>:...
-1
2016-06-27T15:45:50Z
[ "python", "html", "beautifulsoup", "html-parsing" ]
result of coupled ODE in python code is different from mathematica
38,057,790
<p>As per my language knowledge my code is written correct. But It is not giving me correct solution (plot). When I had solved same system of ODE's in mathematica, I have correct solution and both solutions are totally different. I am writing a research project so I need a proper code in python. could you please let m...
0
2016-06-27T15:25:41Z
38,119,566
<p>Both codes are correct, I just turned off my laptop and on it again, and it gives me the correct result (as mathematica)</p>
0
2016-06-30T09:50:02Z
[ "python", "wolfram-mathematica" ]
Django pre_save signal: how do I know if it is Insert or Update
38,057,951
<p>I'm working in a pre_save signal of a model and I don't know how to check if the record is a INSERT or UPDATE. Code below (doesn't work properly):</p> <pre><code>@receiver(pre_save, sender=Person) def pre_save_person(sender, instance, **kwargs): if not instance.pk: print 'INSERT !!!!!!' else: ...
0
2016-06-27T15:33:10Z
38,058,236
<p>Try with </p> <p><code>if instance.pk is None: print "inserting" else: print "updating"</code></p> <p>this wont work in all cases , I recommend using <a href="https://docs.djangoproject.com/en/dev/ref/signals/#post-save" rel="nofollow">post_save</a> where you have the flag created unless you specifica...
0
2016-06-27T15:48:39Z
[ "python", "django", "signals" ]
Django pre_save signal: how do I know if it is Insert or Update
38,057,951
<p>I'm working in a pre_save signal of a model and I don't know how to check if the record is a INSERT or UPDATE. Code below (doesn't work properly):</p> <pre><code>@receiver(pre_save, sender=Person) def pre_save_person(sender, instance, **kwargs): if not instance.pk: print 'INSERT !!!!!!' else: ...
0
2016-06-27T15:33:10Z
38,078,624
<p>Following @ knbk comment, the instance.pk will always exist at this point. You must check if this instance.pk exists in database:</p> <pre><code>@receiver(pre_save, sender=Person) def pre_save_person(sender, instance, **kwargs): num = Person.objects.filter(pk=instance.pk).count() if num == 0 : prin...
0
2016-06-28T14:12:50Z
[ "python", "django", "signals" ]
Excel row-column conversion using Java
38,057,993
<p>Folks,</p> <p>Am looking for some help to create a standalone utility to convert the input sheet below into an output format given below. Am interested to do this in Java, any pointers is appreciated</p> <h1>Input sheet</h1> <pre><code>DATE Item1 Item2 31-Mar-2000 8.6 3.8 03-Apr-2000 8.6 3.8 0...
0
2016-06-27T15:35:20Z
38,059,302
<p>You can use <a href="https://poi.apache.org/" rel="nofollow">Apache POI</a></p> <p>Here is an example of how to read and write <a href="http://howtodoinjava.com/apache-commons/readingwriting-excel-files-in-java-poi-tutorial/" rel="nofollow">Excel files</a></p>
0
2016-06-27T16:53:02Z
[ "java", "python", "apache-poi" ]
Excel row-column conversion using Java
38,057,993
<p>Folks,</p> <p>Am looking for some help to create a standalone utility to convert the input sheet below into an output format given below. Am interested to do this in Java, any pointers is appreciated</p> <h1>Input sheet</h1> <pre><code>DATE Item1 Item2 31-Mar-2000 8.6 3.8 03-Apr-2000 8.6 3.8 0...
0
2016-06-27T15:35:20Z
38,102,938
<p>I wrote a little awk script that did the trick , doing it in java involves lot of coding.</p> <h1>Awk script below.</h1> <pre><code>BEGIN { FS = "," OFS = "," } ...
0
2016-06-29T14:43:08Z
[ "java", "python", "apache-poi" ]
dynamically rename data frame in Python
38,058,008
<p>I'm trying to dynamically create datasets:</p> <pre><code>def CreateDF (indsn, outdsn): outdsn = pd.DataFrame(indsn) .... return outdsn CreateDF (phase_df, phase_df2) </code></pre> <p>But it does not work, I get the following error:</p> <blockquote> <p>NameError: name 'phase_df2' is not defined</p>...
-1
2016-06-27T15:35:51Z
38,058,321
<p>Initialise df:</p> <pre><code>df= pd.DataFrame(index=range(0,4),columns=['A','B','C','D'], dtype='object') </code></pre> <p>dynamically add:</p> <pre><code>for values in values_np df.set_value([iterator, 'A', values) iterator += 1 </code></pre> <p>This way you can dynamically add row wise</p>
0
2016-06-27T15:53:15Z
[ "python", "pandas", "dataframe", "dynamically-generated" ]
dynamically rename data frame in Python
38,058,008
<p>I'm trying to dynamically create datasets:</p> <pre><code>def CreateDF (indsn, outdsn): outdsn = pd.DataFrame(indsn) .... return outdsn CreateDF (phase_df, phase_df2) </code></pre> <p>But it does not work, I get the following error:</p> <blockquote> <p>NameError: name 'phase_df2' is not defined</p>...
-1
2016-06-27T15:35:51Z
38,058,360
<p>It's a little sparse because you didn't give us info on why this needs to happen, or what your source material looks like, but the general idea is:</p> <pre><code>def make_df(name): ... return df dict_of_dfs = dict() df_names = [] #a list of all the dataframes you want to create for name in df_name...
1
2016-06-27T15:55:16Z
[ "python", "pandas", "dataframe", "dynamically-generated" ]
cProfile command line how to reduce output
38,058,016
<p>I'm trying to run cProfile on my python script and all I care about is the total time it took to run. Is there a way to modify</p> <pre><code>python -m cProfile myscript.py </code></pre> <p>so the output is just the total time?</p>
0
2016-06-27T15:36:23Z
38,058,858
<p>This answers supposes that you are using a Unix terminal. The fastest thing I can think of would be to redirect the results into a file with the ">" operator and then read the file with head, something like:</p> <pre><code>python -m cProfile your_python_file.py &gt; temp_file &amp;&amp; head -n 3 temp_file </cod...
0
2016-06-27T16:24:50Z
[ "python", "command-line-arguments", "cprofile" ]
Game created with ovals, while loops, and for loops
38,058,189
<p>I am working on a program that fires a bullet from a cannon after having the user input a degree in order to hit the randomly generated target at its position. The program works fine if you are able to hit the target on the first try every time but it seems if I miss that it creates a new target, like it is supposed...
2
2016-06-27T15:46:14Z
38,061,180
<p>The only place I see <code>w.delete(Target)</code> is within the 'if hit' block. You need to add it somewhere else where it will be executed for missed. I presume that is after the <code>for</code> loop, before <code>if Win == True:</code>.</p>
0
2016-06-27T18:50:58Z
[ "python", "tkinter" ]
Game created with ovals, while loops, and for loops
38,058,189
<p>I am working on a program that fires a bullet from a cannon after having the user input a degree in order to hit the randomly generated target at its position. The program works fine if you are able to hit the target on the first try every time but it seems if I miss that it creates a new target, like it is supposed...
2
2016-06-27T15:46:14Z
38,062,085
<p>i believe ive fixed it for you, heres the code:</p> <pre><code>from tkinter import * import time import math import random master = Tk() w = Canvas(master, width=800,height=800, bg="white") w.pack() #Cannon Img1 = PhotoImage(file="cannon.gif") Pic1 = w.create_image(85,600, image=Img1) #Grass w.create_rectangle(...
0
2016-06-27T19:47:32Z
[ "python", "tkinter" ]
Why do some rows in csv file have an invalid format?
38,058,199
<p>I am currently fetching data from an API and I would like to store those data as csv.</p> <p>However, some lines are always invalid which means I cannot split them via Excel's text-in-columns functionality.</p> <p>I create the csv file as follows:</p> <pre><code>with open(directory_path + '/' + file_name + '-data...
0
2016-06-27T15:46:58Z
38,071,121
<p>The rows are not invalid, but what you do is.</p> <p>So first of all: You use pipes as delimeters. Its fine in some scenarios, but given the fact you want to load it into excel immediately it seems wiser to me to export the data in <a href="https://docs.python.org/2/library/csv.html#csv.writer" rel="nofollow">"exce...
1
2016-06-28T08:37:00Z
[ "python", "csv" ]
Why do some rows in csv file have an invalid format?
38,058,199
<p>I am currently fetching data from an API and I would like to store those data as csv.</p> <p>However, some lines are always invalid which means I cannot split them via Excel's text-in-columns functionality.</p> <p>I create the csv file as follows:</p> <pre><code>with open(directory_path + '/' + file_name + '-data...
0
2016-06-27T15:46:58Z
38,094,183
<p>I have finally found out that I had to strip the text and the tip because they sometimes contain whitespaces which would break the format.</p> <p>Additionally, I also followed the recommendation to use the <code>excel dialect</code> since I think this will make it easier to process the data later on.</p>
0
2016-06-29T08:27:25Z
[ "python", "csv" ]
Receive a message with RabbitMQ then process it then send back the results
38,058,257
<p>I would like to send a message (directly) from a script and than process it, and send back the results. So it's like a double publish-subscribe.</p> <p>I have 2 scripts:</p> <ul> <li>Processer</li> <li>Client</li> </ul> <p>The Client sends a message directly (simple string) to the Processer, and than the Processe...
0
2016-06-27T15:49:53Z
38,064,488
<p>Have you checked the tutorials for RPC in RabbitMQ w/ python and pika? <a href="http://www.rabbitmq.com/tutorials/tutorial-six-python.html" rel="nofollow">http://www.rabbitmq.com/tutorials/tutorial-six-python.html</a></p> <hr> <p>The gist of what you need to do in your client, is found in the RPC tutorial, but wit...
0
2016-06-27T22:56:41Z
[ "python", "rabbitmq" ]
Exclude Tags Based on Content in Beautifulsoup
38,058,262
<p>I'm scraping html data that is similar to the following:</p> <pre><code>&lt;div class="target-content"&gt; &lt;p id="random1"&gt; "the content of the p" &lt;/p&gt; &lt;p id="random2"&gt; "the content of the p" &lt;/p&gt; &lt;p&gt; &lt;q class="semi-predictable"&gt; "...
1
2016-06-27T15:50:08Z
38,058,337
<p>You can just skip <code>p</code> tags having the <code>q</code> tag inside:</p> <pre><code>for p in soup.select('div.target-content &gt; p'): if p.q: # if q is present - skip continue print(p) </code></pre> <p>where <code>p.q</code> is a shortcut to <code>p.find("q")</code>. <code>div.target-conte...
2
2016-06-27T15:54:11Z
[ "python", "web-scraping", "beautifulsoup" ]
Exclude Tags Based on Content in Beautifulsoup
38,058,262
<p>I'm scraping html data that is similar to the following:</p> <pre><code>&lt;div class="target-content"&gt; &lt;p id="random1"&gt; "the content of the p" &lt;/p&gt; &lt;p id="random2"&gt; "the content of the p" &lt;/p&gt; &lt;p&gt; &lt;q class="semi-predictable"&gt; "...
1
2016-06-27T15:50:08Z
38,058,401
<p>You can use <code>filter</code> to accomplish this:</p> <pre><code>filter(lambda e: e.find('q') == None, soup.find('div', class_='target-content').find_all('p')) </code></pre>
1
2016-06-27T15:57:10Z
[ "python", "web-scraping", "beautifulsoup" ]
.fit() error: Found arrays with inconsistent numbers of samples
38,058,486
<p>y1 is a numpy.ndarray with length 106 (representing heights measured in meters)</p> <p>x1 is a numpy.ndarray with length 106 (representing ages of the boys corresponding to the heights)</p> <p>I'm trying to predict heights given ages with linear regression using gradient descent, and then to plot it as a 3D surfac...
0
2016-06-27T16:01:31Z
38,074,736
<p>The expected array shapes are:</p> <ul> <li>(n_samples, 1) for x1, meaning a 2D array with one column (since you have one feature)</li> <li>(n_samples,) for y1, meaning a 1D array. </li> </ul> <p>If your first array is 1D, you should reshape it: </p> <pre><code>x1 = np.fromfile('ex2x.dat', float).reshape(-1, 1) <...
1
2016-06-28T11:17:01Z
[ "python", "numpy", "scikit-learn" ]
For Loop Iteration Inside of Javascript Variable (Django)
38,058,516
<p>I am trying to implement a dropdown menu with selectors inside of django. I have made good progress in finding a piece of software that looks great!</p> <p><a href="http://nelrohd.github.io/bootstrap-dropdown-checkbox/" rel="nofollow">http://nelrohd.github.io/bootstrap-dropdown-checkbox/</a></p> <p>However, i am g...
0
2016-06-27T16:03:41Z
38,058,598
<p>Have you tried:</p> <pre><code>var data = []; for (var i = 0; i &lt;= 10; i++) { data[data.length] = { id: (i + 1), label: 'Option ' + (i + 1), isChecked: true }; } </code></pre>
0
2016-06-27T16:07:58Z
[ "javascript", "python", "html", "django", "twitter-bootstrap" ]
For Loop Iteration Inside of Javascript Variable (Django)
38,058,516
<p>I am trying to implement a dropdown menu with selectors inside of django. I have made good progress in finding a piece of software that looks great!</p> <p><a href="http://nelrohd.github.io/bootstrap-dropdown-checkbox/" rel="nofollow">http://nelrohd.github.io/bootstrap-dropdown-checkbox/</a></p> <p>However, i am g...
0
2016-06-27T16:03:41Z
38,058,727
<p>If you generate the list in Django, you can do like:</p> <ol> <li>I will assume you have a list of arbitrary objects you want to serialize in Javascript. When you are ready to pass it to the response context, convert it with stuff like this: <code>mark_safe(json.dumps([{'id': element.id, 'label': element.label, 'is...
0
2016-06-27T16:16:42Z
[ "javascript", "python", "html", "django", "twitter-bootstrap" ]
For Loop Iteration Inside of Javascript Variable (Django)
38,058,516
<p>I am trying to implement a dropdown menu with selectors inside of django. I have made good progress in finding a piece of software that looks great!</p> <p><a href="http://nelrohd.github.io/bootstrap-dropdown-checkbox/" rel="nofollow">http://nelrohd.github.io/bootstrap-dropdown-checkbox/</a></p> <p>However, i am g...
0
2016-06-27T16:03:41Z
38,058,769
<p>I would double check to make sure you had the Django tags set up correctly. It should look like this by passing in the set of options as your context:</p> <pre><code>{% for opt in options %} {id: {{ forloop.counter }}, label: {{ opt }}, isChecked: true} {% endfor %} </code></pre>
0
2016-06-27T16:19:15Z
[ "javascript", "python", "html", "django", "twitter-bootstrap" ]
Why can the solve() function in matlab solve this equation while the nsolve() function in sympy requires a guess?
38,058,542
<p>I have a mode, a maximum and minimum value of X (<code>Xmin</code> and <code>Xmax</code>), and a percentage confidence (<code>percentage</code>).</p> <p>I want to use the following functions in order to find the μ and σ of a theoretical log normal distribution:</p> <p>The cumulative distribution function:</p> <...
2
2016-06-27T16:05:11Z
38,082,708
<p>Based on the <a href="https://www.mathworks.com/help/symbolic/solve.html?requestedDomain=www.mathworks.com#zmw57dd0e125966" rel="nofollow">documentation</a>, MATLAB's <code>solve</code> falls back to a numerical solution automatically. Assumedly it generates a guess value automatically (it doesn't mention how), but ...
1
2016-06-28T17:31:34Z
[ "python", "matlab", "math", "sympy" ]
Create "loading window" in PyQt4
38,058,643
<p>I have a program that graphs data using an embedded matplotlib plot and adds helpful visualizations. The problem is matplotlib can be very slow when these visualizations are heavy, to the point where the main window hangs. I can't add these graphics in a different thread or process because PyQt forbids updating the ...
0
2016-06-27T16:11:21Z
38,151,363
<p>I figured out my problem. It's not a total fix but I had to go back through to where the visualizations are being added and periodically call this function:</p> <pre><code>QtGui.QApplication.processEvents() </code></pre> <p>This let my UI update every once in a while so that the window at least didn't hang. I also...
0
2016-07-01T17:54:31Z
[ "python", "multithreading", "matplotlib", "pyqt", "pyqt4" ]
Python Tk() Button command not completely working
38,058,668
<p>I'm quite new to python programming and have quite a basic question which I can't seem to resolve myself - I hope someone might be able to shed some light on this!</p> <p>I created a .py file which runs a basic Rock, Paper, Scissors game between a user and the (random) computer. This uses a GUI via a tk() and works...
0
2016-06-27T16:12:40Z
38,060,829
<p>I presume you want the main window to remain when one selects a particular game. That means that the game should be in a separate frame, initially in a separate Toplevel. Modify your rps file something like the following,</p> <pre><code>from tkinter import * from tkinter.ttk import * import random class RPS(Topl...
0
2016-06-27T18:30:35Z
[ "python", "user-interface", "button", "tkinter" ]
Histogram rebinning with interpolation?
38,058,707
<p>I have histogram data in counts <code>a</code> and weights <code>b</code> format, such as:</p> <pre><code>a=[1,2,3,4,5] b=[2,3,6,7,1] </code></pre> <p>If I plot the histogram binning into 5 or less bins, it correctly plots, and rebins:</p> <pre><code>plt.hist(a,weights=b,bins=5)[0] </code></pre> <p><a href="http...
0
2016-06-27T16:14:50Z
38,094,656
<p>You have 6 bins for 5 values. And because histogram is merely a very simple (one can even say "stupid") counting of values, you logically have to have at least one empty bin. In this case, the bin edges are something like [1, 1.66, 2.33, 3.00, ...]. Left edges are inclusive, right (with the exception of the last one...
1
2016-06-29T08:50:54Z
[ "python", "numpy", "histogram" ]
How can I Configure linter-flake8 on Atom?
38,058,750
<p>I'm trying to configure linter-flake8 for python on Atom editor. I used pip install flake8 and it installed flake8 on </p> <pre><code>~/.local/bin/ </code></pre> <p>I put it on my PATH and add this line on my coffee.init file:</p> <pre><code>process.env.PATH = ['~/.local/bin', process.env.PATH].join(':') </code><...
1
2016-06-27T16:18:11Z
38,399,454
<p>I solved the same Error in Ubuntu using below command. </p> <p><strong>sudo pip install flake8</strong></p> <p>See below link to have more information. <a href="https://github.com/atom/atom/issues/4642" rel="nofollow">https://github.com/atom/atom/issues/4642</a></p> <p>If your getting <strong>pep8 error</strong> ...
1
2016-07-15T15:05:54Z
[ "python", "atom-editor", "flake8" ]
scikit-learn: how to scale back the 'y' predicted result
38,058,774
<p>I'm trying to learn scikit-learn and Machine Learning by using the Boston Housing Data Set.</p> <pre><code># I splitted the initial dataset ('housing_X' and 'housing_y') from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(housing_X, housing_y, test_size=0.25, ra...
1
2016-06-27T16:19:38Z
38,059,031
<p>You can use <code>inverse_transform</code> using your <code>scalery</code> object:</p> <pre><code>y_new_inverse = scalery.inverse_transform(y_new) </code></pre>
1
2016-06-27T16:35:21Z
[ "python", "machine-learning", "scikit-learn", "scale" ]
How can I read a CSV file line by line while keeping track of the column headers?
38,058,796
<p>When using this code:</p> <pre><code>with open(filepath, 'r') as f: reader = csv.reader(f) for i, line in enumerate(reader): print 'line[{}] = {}'.format(i, line) </code></pre> <p>It reads my CSV files line by line, but I can't select the line I want by its header. The index will probably change fr...
0
2016-06-27T16:22:01Z
38,058,980
<p>From the csv documentation, use DictReader instead of just reader. Updating your implementation to:</p> <pre><code>import csv with open(filename, 'r') as f: reader = csv.DictReader(f) for i, line in enumerate(reader): print 'line[{}] = {}'.format(i, line['header_name']) </code></pre> <p>Documentati...
0
2016-06-27T16:32:11Z
[ "python", "python-2.7", "csv" ]
I keep getting the following error django.db.utils.ProgrammingError: column "name" of relation "blog_post" already exists in my django app
38,058,834
<p>When I try to Migrate I get the following error</p> <pre><code>django.db.utils.ProgrammingError: column "name" of relation "blog_post" already exists </code></pre> <p>now I have assumed that the message means that I am trying to make a column named "name" and one with the same name already exists. So I looked at m...
0
2016-06-27T16:23:48Z
38,064,772
<p>I had a similar problem. This worked for me</p> <pre><code>./manage.py migrate --fake </code></pre> <p>and then:</p> <pre><code>./manage.py makemigrations </code></pre> <p>just to make sure and then ran</p> <pre><code>./manage.py migrate </code></pre>
1
2016-06-27T23:28:11Z
[ "python", "django-models", "traceback" ]
Syntax in the following Fibonacci number generator.
38,058,844
<p>I'm trying to understand what is happening in this block of code</p> <pre><code>def enum(seq): n = 0 for i in seq: yield n, i n += 1 def fibonacci(): i = j = 1 while True: r, i, j = i, j, i + j yield r </code></pre> <p>I have a general understanding of how generators...
0
2016-06-27T16:24:25Z
38,059,119
<p>It is called 'tuple assignment'.</p> <p>Often, you encounter multiple assignments like</p> <pre><code>a = 1 b = 2 c = 3 </code></pre> <p>This can be rewritten as:</p> <pre><code>(a, b, c) = (1, 2, 3) </code></pre> <p>Or even like this:</p> <pre><code>a, b, c = 1, 2, 3 </code></pre> <p>If you want to swap valu...
0
2016-06-27T16:41:43Z
[ "python" ]
Syntax in the following Fibonacci number generator.
38,058,844
<p>I'm trying to understand what is happening in this block of code</p> <pre><code>def enum(seq): n = 0 for i in seq: yield n, i n += 1 def fibonacci(): i = j = 1 while True: r, i, j = i, j, i + j yield r </code></pre> <p>I have a general understanding of how generators...
0
2016-06-27T16:24:25Z
38,059,172
<p>This is a standard "unpacking assignment" - the three values on the right hand side are computed, then the values are bound to the locations (in this case they are all simple names, but they could in theory be container elements) on the left hand side. This particular case is broadly equivalent to</p> <pre><code>r ...
0
2016-06-27T16:44:56Z
[ "python" ]
Syntax in the following Fibonacci number generator.
38,058,844
<p>I'm trying to understand what is happening in this block of code</p> <pre><code>def enum(seq): n = 0 for i in seq: yield n, i n += 1 def fibonacci(): i = j = 1 while True: r, i, j = i, j, i + j yield r </code></pre> <p>I have a general understanding of how generators...
0
2016-06-27T16:24:25Z
38,059,366
<p>The line</p> <pre><code>r, i, j = i, j, i+j </code></pre> <p>is a sequence unpacking statement.</p> <p>Let <code>i = j = 1</code>.</p> <ol> <li>First the right hand side <code>i, j, i+j</code> is evaluated and packed into a tuple <code>(1, 1, 2)</code>.</li> <li>Then the tuple is unpacked into the names <code>r<...
0
2016-06-27T16:57:19Z
[ "python" ]
Matlplotlib with Qt backend on OS X -> Incompatible library versions
38,058,957
<p>I'm having some problems with matplotlib's OS X native backend, namely that plot windows always pop up on the background. I wanted therefore to try matplotlib's Qt backend, but when I try it I get the following error message:</p> <blockquote> <p>ImportError: dlopen(/Users/x/anaconda/lib/python2.7/site-pack...
0
2016-06-27T16:30:43Z
38,154,073
<p>If anyone ever comes across this problem, my solution was to:</p> <pre><code>brew uninstall libpng brew cleanup &amp;&amp; brew prune brew install libpng </code></pre> <p>and</p> <pre><code>conda clean --all conda update --all </code></pre> <p>Now matplotlib works fine with Qt backend.</p>
0
2016-07-01T21:26:50Z
[ "python", "qt", "matplotlib" ]
Matlplotlib with Qt backend on OS X -> Incompatible library versions
38,058,957
<p>I'm having some problems with matplotlib's OS X native backend, namely that plot windows always pop up on the background. I wanted therefore to try matplotlib's Qt backend, but when I try it I get the following error message:</p> <blockquote> <p>ImportError: dlopen(/Users/x/anaconda/lib/python2.7/site-pack...
0
2016-06-27T16:30:43Z
39,859,600
<p>I fixed it by manualy removing <code>libpng16.16.dylib</code> and other versions of <code>libpng</code> from <code>~/anaconda/lib</code> and then installing latest version with brew</p> <pre><code>brew install libpng </code></pre>
1
2016-10-04T18:46:04Z
[ "python", "qt", "matplotlib" ]
Python: How to "NaN" a range of data when a given criteria is met for a given period of time
38,058,961
<p>I have a pd.dataframe which contains activity count data from a Philips Actiwatch. When there is no activity count for a period of more than 60 minutes, the user was probably not wearing the device, and this range should be removed. </p> <p>How do I detect periods of >60 min (each line is 1 minute) in my Dataframe ...
0
2016-06-27T16:31:06Z
38,059,371
<p>You were close, but you have an infinate loop in your code. as well as some of the logic in your if statement is a bit off. Here is a corrected solution.</p> <pre><code>streakCount = 0 # Counts the longest current streak streakIndex = 0 # Keeps track of where the streak started for n in range(len(data)): if da...
0
2016-06-27T16:57:38Z
[ "python", "if-statement", "for-loop", "while-loop" ]
Python 3.5.2 can be accessed through Terminal, but IDLE for 3.5.2 is missing
38,059,096
<p>I am just getting started with Python and computer programming in general, so hopefully someone can help me out. I am trying to use PyQt4 to start learning how to code GUI's, and eventually use py2app to bundle these GUI's into Mac Applications...</p> <p>The issue I am having is I just installed PyQt4 (or so I thou...
0
2016-06-27T16:40:09Z
38,159,326
<p>I also have IDLE programs which won't start. Not sure why.</p> <p>If you are willing to use PyCharm, I would recommend that to you anyway. You can change the pythonpath in the PyCharm Settings -> Build, Execution, Deployment -> Console -> Python Console -> Python interpreter. Select here the appropriate Python bina...
0
2016-07-02T10:54:27Z
[ "python", "osx", "python-3.x", "pyqt4", "python-3.5" ]
heroku twitter e_books: nothing added to commit but untracked files present
38,059,125
<p>I'm pretty new to using ruby and python and github and all that stuff - the only programming I've ever done has been in a game engine. But I want to make a randomized twitter e_books using python-twitter, heroku_ebooks, and of course heroku. Everything was going according to plan until one of the last steps. I try t...
0
2016-06-27T16:42:09Z
38,059,311
<p>Try with:</p> <pre><code>git push heroku HEAD:master </code></pre>
0
2016-06-27T16:53:37Z
[ "python", "ruby", "heroku", "twitter" ]
heroku twitter e_books: nothing added to commit but untracked files present
38,059,125
<p>I'm pretty new to using ruby and python and github and all that stuff - the only programming I've ever done has been in a game engine. But I want to make a randomized twitter e_books using python-twitter, heroku_ebooks, and of course heroku. Everything was going according to plan until one of the last steps. I try t...
0
2016-06-27T16:42:09Z
38,060,968
<p>I fixed my problem! For anyone with the same issue who finds this thread, I put the local file into the C:/ directory on my computer (don't know why it wasn't already there) and ran the following:</p> <pre><code>&gt;cd C:/xanderbot &gt;git init Initialized empty Git repository in C:/xanderbot/.git/ &gt;heroku git:r...
0
2016-06-27T18:38:07Z
[ "python", "ruby", "heroku", "twitter" ]
How to Copy the Matching Columns between CSV Files Using Pandas?
38,059,130
<p>I have two dataframes(f1_df and f2_df):</p> <p>f1_df looks like:</p> <pre><code>ID,Name,Gender 1,Smith,M 2,John,M </code></pre> <p>f2_df looks like:</p> <pre><code>name,gender,city,id </code></pre> <p><strong>Problem:</strong></p> <p>I want the code to compare the header of f1_df with f2_df by itself and copy ...
0
2016-06-27T16:42:40Z
38,059,183
<p>try this if you want to merge / join your DFs on common columns:</p> <p>first lets convert all columns to lower case:</p> <pre><code>df1.columns = df1.columns.str.lower() df2.columns = df2.columns.str.lower() </code></pre> <p>now we can join on common columns</p> <pre><code>common_cols = df2.columns.intersection...
2
2016-06-27T16:46:17Z
[ "python", "csv", "pandas", "inner-join" ]
Tkinter to display multiple randomly selected images in single window
38,059,145
<p>Code:</p> <pre><code>#!/usr/bin/env python import os import sys import random from Tkinter import Label,Tk from PIL import Image, ImageTk import tkFileDialog path = '/Users/InNov8/Desktop/broadcast/test' # All images in the directory get stored in this list images = [] for dirname, dirnames, filenames in os.w...
0
2016-06-27T16:43:44Z
38,161,115
<p>figured out that my original code actually works but the issue was an inability to scroll. </p> <p>Here's the final code with scrollbars added:</p> <pre><code>#!/usr/bin/env python import os import sys import random from Tkinter import * from PIL import Image, ImageTk import tkFileDialog path = '/Users/InNov8/...
0
2016-07-02T14:16:36Z
[ "python", "tkinter" ]
Python EVE aggregation not working
38,059,182
<p>I am using Eve to create a RESTful API for MongoDB. Maybe I am doing something wrong, but I cant figure out why Eve is not returning me aggregated results. Below is my DOMAIN:</p> <pre><code>DOMAIN = { 'heartbeats': { 'schema': { 'user': { 'type': 'objectid', ...
0
2016-06-27T16:46:13Z
38,069,166
<p>On which Eve version are you? MongoDB Aggregation Framework support is currently on the development branch. If you are using any of the stable versions (v0.6.4 being the latest), you won't get aggregation support. Try installing the development branch.</p>
0
2016-06-28T06:59:24Z
[ "python", "mongodb", "pymongo", "eve", "mongodb-aggregation" ]
Can't delete a row with SQLAlchemy / Flask-SQLAlchemy
38,059,242
<p>I can't seem to get this method to delete a row. It runs without error, but the row remains in the db (mysql). I have add and updates working using a similar approach.</p> <p>Basically, I'm creating a list of ids (ParentPage.id) and comparing those against a temp table (ParentPageTemp.id), with the intention of del...
0
2016-06-27T16:49:05Z
38,059,542
<p>You have two relationships on Page but nothing in ParentPage.</p> <p>Take a look: <a href="http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-many" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-many</a></p> <p>Add:</p> <pre><code>children = relations...
0
2016-06-27T17:08:54Z
[ "python", "mysql", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Can't delete a row with SQLAlchemy / Flask-SQLAlchemy
38,059,242
<p>I can't seem to get this method to delete a row. It runs without error, but the row remains in the db (mysql). I have add and updates working using a similar approach.</p> <p>Basically, I'm creating a list of ids (ParentPage.id) and comparing those against a temp table (ParentPageTemp.id), with the intention of del...
0
2016-06-27T16:49:05Z
38,061,007
<p>Probably, this is what you want:</p> <p>1 - Add a <code>relationship</code> attribute and mention the <code>backref</code> column in <code>ParentPage</code> table, basically this <code>backref</code> will be like an added attribute to the <code>Page</code> model, by which and from <code>Page</code> model, you can g...
0
2016-06-27T18:40:49Z
[ "python", "mysql", "flask", "sqlalchemy", "flask-sqlalchemy" ]
best way in python to extract specific info from columns of data in text file
38,059,252
<p>I currently have multiple txt files with two columns of data: wavenumber and intensity:</p> <pre><code>500.21506 0.00000 500.45613 0.00000 500.69720 0.00000 500.93826 0.00000 501.17933 0.00000 501.42040 0.00000 501.66147 0.00000 501.90253 0.00000 502.14360 0.00000 502.38467 0.00000 502.62574 0.00000 502.86680 0.000...
0
2016-06-27T16:50:07Z
38,059,309
<p>You are trying to <em>call <code>float()</code> on a list</em> of strings. Instead, call it on individual strings:</p> <pre><code>parts = [float(item) for item in line.split()] </code></pre>
2
2016-06-27T16:53:28Z
[ "python" ]
Implement a persistent stack data structure using Redis
38,059,255
<p>I am implementing a stack data structure using redis-py and Redis list data type. I am not clear on how to handle the case when the corresponding list data type is empty. Default Redis behaviour appears to be that once a list is empty the related key is deleted. The empty list case is hit on Redis for example, when ...
0
2016-06-27T16:50:19Z
38,068,894
<p>Your 2nd solution is the best Fit.</p> <p>Yes you have to maintain the naming conventions, this is very basic for any no sql databases or key value store. You must have the control over the keys you put in. If you don't have that control, then over the period of time you don't know which key is used for which purpo...
1
2016-06-28T06:45:17Z
[ "python", "redis", "stack", "persistence", "redis-py" ]
django.core.exceptions ImproperlyConfigured error when running selenium functional test in python
38,059,271
<p>I've had a similar problem to this one before where I received a nearly identical error message, i.e.</p> <pre><code>C:\Users\David J\optilab\optilab_project&gt;python functional_tests.py Traceback (most recent call last): File "functional_tests.py", line 4, in &lt;module&gt; from optilab.models import Design...
2
2016-06-27T16:51:00Z
38,064,596
<p>The start of your script should look something like this</p> <pre><code>import os, sys sys.path.append(os.getcwd()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "optilab.settings") # or whatever import django django.setup() from selenium import webdriver import unittest from selenium.webdriver.common.keys impo...
1
2016-06-27T23:08:31Z
[ "python", "django", "selenium", "data-migration" ]
PyCharm is not able find app.yaml when pushing to GAE
38,059,310
<p>I wrote a simple pymongo code insert a few values in MongoDB instance on GAE and My app got deployed properly from Pycharm but,</p> <p>I am getting the same error while running following command</p> <p><strong>appcfg.py -A login-services-1354 -V v1 update</strong> . on my cloud shell</p> <p>The following is the e...
0
2016-06-27T16:53:34Z
38,060,684
<p>The parameter to the <code>appcfg update</code> command is the yaml file or directory containing yaml file</p>
0
2016-06-27T18:22:06Z
[ "python", "google-app-engine" ]
spark using only one core on parallelism task
38,059,320
<p>So i have this code:</p> <pre><code>conf = SparkConf().setAll(( ("spark.python.profile", "true" if args.profile else "false"), ("spark.task.maxFailures", "20"), ("spark.driver.cores", "4"), ("spark.executor.cores", "4"), ("spark.shuffle.service.enabled", "true"), ("spark.dynamicAllocation.en...
-1
2016-06-27T16:54:17Z
38,072,942
<p>Problem was in the python itself not using all cores. I implemented multi-threading.</p> <p>Thanks for all who helped.</p>
0
2016-06-28T09:55:58Z
[ "python", "amazon-web-services", "apache-spark", "cpu" ]
python tkinter application same text on multiple rows
38,059,394
<p>I'm extremely new to python and I decided to try to make some things to test how things work. But I couldn't find a way to make a text on a tkinter button take the place of 2 rows. Here's the code:</p> <pre><code>import tkinter as tk hoho = 0 def lul(): global hoho hoho = hoho + 1 print(hoho) class App...
2
2016-06-27T16:59:11Z
38,060,220
<p>I hope I understood the question right but you can use <code>\n</code> in your string to print the text on a new line on the button.</p> <pre><code>import tkinter as tk hoho = 0 def lul(): global hoho hoho = hoho + 1 print(hoho) class Application(tk.Frame): def __init__(self, master=None): ...
2
2016-06-27T17:52:00Z
[ "python", "text", "tkinter" ]
Iterating through a file and replacing strings, leaving the number of characters intact
38,059,397
<p>I'm attempting to anonymize a file so that all the content except certain keywords are replaced with gibberish, but the format is kept the same (including punctuation, length of string and capitalization). For example:</p> <pre class="lang-none prettyprint-override"><code>I am testing this, check it out! This is ...
1
2016-06-27T16:59:23Z
38,059,536
<p>Initially let's disregard the fact that we have to preserve some keywords. We will fix that later.</p> <p>The easiest way to perform this kind of 1-to-1 mapping is to use the method <a href="https://docs.python.org/3.5/library/stdtypes.html?highlight=str.translate#str.translate" rel="nofollow"><code>str.translate</...
1
2016-06-27T17:08:22Z
[ "python", "replace" ]
Run iPython notebook with a specific version (2.7 instead of 3)
38,059,456
<p>I'm designing some software that is specifically going to be used by people running Python 2.7 instead of 3. Unfortunately, I'm using a computer that has 3, and apparently there are some dependency issues when some of my colleagues are using Python 2.7 to run code. I'm hoping to run with 2.7 in the ipython notebook ...
0
2016-06-27T17:02:58Z
38,059,614
<p>You can choose either using the Kernel tab --> change kernel and select python version, or when you open a new notebook under the file tab you can choose python version there. </p>
0
2016-06-27T17:12:48Z
[ "python", "ipython", "ipython-notebook", "jupyter", "jupyter-notebook" ]
How do I generate the following series of numbers in Python using List Comprehension?
38,059,506
<p>I am trying to learn List Comprehension, given two numbers as input, I want to generate a series of consecutive numbers.</p> <p>For example:</p> <pre><code>Input: 11,16 Output: [(11,12),(11,12,13),(11,12,13,14),(11,12,13,14,15),(11,12,13,14,15,16)] </code></pre> <p>So I am trying something like the following:</...
1
2016-06-27T17:06:41Z
38,059,583
<pre><code>[tuple(range(start, i+1)) for i in range(start+1, stop+1)] </code></pre>
5
2016-06-27T17:11:19Z
[ "python", "list-comprehension" ]
How do I generate the following series of numbers in Python using List Comprehension?
38,059,506
<p>I am trying to learn List Comprehension, given two numbers as input, I want to generate a series of consecutive numbers.</p> <p>For example:</p> <pre><code>Input: 11,16 Output: [(11,12),(11,12,13),(11,12,13,14),(11,12,13,14,15),(11,12,13,14,15,16)] </code></pre> <p>So I am trying something like the following:</...
1
2016-06-27T17:06:41Z
38,059,585
<p>You need an loop over the <code>stop</code> value; that way you can produces a <em>series</em> of ranges, from <code>range(11, 13)</code> through to <code>range(11, 17)</code>:</p> <pre><code>def genSeries(start, stop): return [tuple(range(start, endvalue)) for endvalue in range(start + 2, stop + 2)] </code></p...
2
2016-06-27T17:11:25Z
[ "python", "list-comprehension" ]
How do I generate the following series of numbers in Python using List Comprehension?
38,059,506
<p>I am trying to learn List Comprehension, given two numbers as input, I want to generate a series of consecutive numbers.</p> <p>For example:</p> <pre><code>Input: 11,16 Output: [(11,12),(11,12,13),(11,12,13,14),(11,12,13,14,15),(11,12,13,14,15,16)] </code></pre> <p>So I am trying something like the following:</...
1
2016-06-27T17:06:41Z
38,059,622
<p>Try this (wow so many people typing simultaneously :-) I suggest simply add 2 once ...:</p> <pre><code>#! /usr/bin/env python from __future__ import print_function def gen_series(start, stop): return [tuple(range(start, x + 2)) for x in range(start, stop)] print(gen_series(11, 16)) </code></pre> <p>yields:</...
1
2016-06-27T17:13:36Z
[ "python", "list-comprehension" ]
How to write the data of 3 dictionaries in a table separated by tab into a text file?
38,059,520
<p>Say I have the following 3 dictionaries:</p> <pre><code>d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}} d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'}, 'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}} d3 = {'Ben': {'Strength': '1.10', 'Int': '...
-2
2016-06-27T17:07:23Z
38,060,874
<p>I was not able to produce your exact desired output, but I got something that will work in Excel.</p> <p>Your three dictionaries each contain information about an object (or character) so I created a character class rather than use your dictionaries.</p> <pre><code>class Character(object): def __init__(self, n...
1
2016-06-27T18:32:57Z
[ "python", "python-2.7", "csv", "dictionary" ]
optionMenu is not returning value
38,059,624
<p>I have written up a simple UI that requires user to select something from a drop-down list, then using that selection, the code will executes the rest of the stuff</p> <p>Right now, I am having 2 issues.. 1. The 'value' is not exactly returning, as soon as a Format is selected and the OK button is hit... Am I missi...
0
2016-06-27T17:13:50Z
38,063,143
<p>Use python dictionnaries or class to pass data in your script. I really don't understand what the problem is.</p> <p>When you say : "The 'value' is not exactly returning", what do you mean ? Can you tell us what do you get and what do you expect ?</p> <pre><code>def mainCode(): ... ... showUI() cmd...
0
2016-06-27T20:59:53Z
[ "python", "selection", "maya", "optionmenu" ]
Python conventions with respect to if conditions
38,059,672
<p><strong>In python, is it frowned upon to use extra conditions within an if statement to avoid error, or should this be done separately from the if statement?</strong></p> <p>Example:</p> <p>I want to make sure that d, which will be either a empty string or a number string is not blank and not less than 1. If d is ...
2
2016-06-27T17:17:05Z
38,059,731
<p>You don't need the <code>if d</code> part if you include it in the try. Something like this would work, where either you'll get a <code>ValueError</code> if it's not a number, or it'll raise a <code>ValueError</code> if it is a number but under 1.</p> <pre><code>def check_d(d): try: if float(d) &gt;= 1:...
0
2016-06-27T17:21:04Z
[ "python" ]
Python conventions with respect to if conditions
38,059,672
<p><strong>In python, is it frowned upon to use extra conditions within an if statement to avoid error, or should this be done separately from the if statement?</strong></p> <p>Example:</p> <p>I want to make sure that d, which will be either a empty string or a number string is not blank and not less than 1. If d is ...
2
2016-06-27T17:17:05Z
38,059,967
<p>The first is fine assuming that <code>d</code> will always fit your criteria but the second example is more robust.</p> <p>For example when <code>d = "a"</code> the condition <code>if d and float(d) &gt;= 1:</code> will raise the <code>ValueError</code> where as the <code>try: except</code> will catch it and work p...
0
2016-06-27T17:36:13Z
[ "python" ]
error: command 'cl.exe' failed: No such file or directory
38,059,732
<p>I am currently trying to install PYODBC via pip but am getting an error. at this point, I am at a loss on what to do.<br> Here is what it looks like:</p> <pre><code> C:\Users\c.ginther&gt;pip install pyodbc Collecting pyodbc Using cached pyodbc-3.0.10.tar.gz Installing collected packages: pyodbc Running set...
0
2016-06-27T17:21:09Z
39,058,095
<p>As user590028 mentioned in the comments python requires a C compiler to install packages like pyodbc. On Windows the most common compiler is Visual Studio C++, so check the list below taken from <a href="http://stackoverflow.com/questions/29909330/microsoft-visual-c-compiler-for-python-3-4">here</a></p> <blockquote...
1
2016-08-20T19:47:49Z
[ "python", "pyodbc" ]
Pandas groupby with categorical and apply copies index to additional column
38,059,735
<p>Consider the following MWE with three alternative last lines:</p> <pre><code>df = pd.DataFrame({'a': np.arange(100)*3}) (df.assign(mybins = lambda df: pd.cut(df['a'],bins=np.linspace(0,300,6))) .groupby('mybins') .sum() #.apply(lambda x: x.sum()) #.apply(lambda x: x.count()/float(len(df))*100) ) </code>...
1
2016-06-27T17:21:13Z
38,059,832
<p>is that what you want - pay attention at <code>.groupby('mybins')['a']</code> (<strong>['a']</strong>):</p> <pre><code>In [270]: %paste (df.assign(mybins = lambda df: pd.cut(df['a'],bins=np.linspace(0,300,6))) .groupby('mybins')['a'] #.sum() #.apply(lambda x: x.sum()) .apply(lambda x: x.sum()/float(len(...
1
2016-06-27T17:26:31Z
[ "python", "pandas" ]
Can you use if-else statement inside braces for an array in Python?
38,059,796
<p>I'm wondering if there is a nice way to use an if-else statement inside braces of an array in Python to assign values. What I would like is something like:</p> <pre><code>A = #some 2D array of length m by n, already initialized A = np.float64(A) val = someValue #any number, pick a number A = [[val for j in range(n...
1
2016-06-27T17:24:55Z
38,059,963
<p>Python's one-line ternary operator syntax looks like this</p> <pre><code>variable = a if CONDITION else b </code></pre> <p>You can place this inside a list comprehension as well. It's not clear what <code>val</code> is in your example, but I'm assuming it's a value you specified beforehand.</p> <pre><code>val = ...
1
2016-06-27T17:35:58Z
[ "python", "arrays", "if-statement", "numpy" ]
Can you use if-else statement inside braces for an array in Python?
38,059,796
<p>I'm wondering if there is a nice way to use an if-else statement inside braces of an array in Python to assign values. What I would like is something like:</p> <pre><code>A = #some 2D array of length m by n, already initialized A = np.float64(A) val = someValue #any number, pick a number A = [[val for j in range(n...
1
2016-06-27T17:24:55Z
38,060,879
<p>With numpy arrays we try avoid iteration (list comprehension). Sometimes it is needed, but in this case it is not:</p> <pre><code>In [403]: A=np.arange(16).reshape(4,4) In [404]: A1=A.astype(np.float64) # better syntax for converting to float In [405]: A1 Out[405]: array([[ 0., 1., 2., 3.], [...
5
2016-06-27T18:33:14Z
[ "python", "arrays", "if-statement", "numpy" ]
Import external package into pycharm
38,059,799
<p>I'm using pycharm as python2.7 project editor, and I'm trying to import external packages (for example pytz for timezone issues) but for some reason, it doesn't recognize none of the packages I'm trying to import</p> <pre><code>from pytz import timezone </code></pre> <p>The Error I get is: <code>ImportError: No mo...
0
2016-06-27T17:25:01Z
38,059,880
<p>where it is underlined in red inside pycharm ... just click it so your cursor is on "pytz"(from <code>import pytz</code>) and hit alt+enter , and select <code>install package pytz</code> from the menu that pops up</p> <p>or go to pycharm file > settings > project > interpreter ... and add the package directly to th...
0
2016-06-27T17:29:32Z
[ "python", "osx", "python-2.7", "pip", "pycharm" ]
Encoding headaches with ' character in Python, Excel
38,059,812
<p>I am reading a txt file into Python, extract parts of it and then output the results as CSV. </p> <p>Problem is, I get encoding hiccups I don't know how to resolve. Here is what happens: </p> <ol> <li><p>The input file is an export from Adobe Acrobat, where I output a "plain text file" after changing the setting t...
3
2016-06-27T17:25:33Z
38,060,118
<p>Not a clean solution, but for a quick fix just use .replace('\0xe2', ' ').</p>
1
2016-06-27T17:46:13Z
[ "python", "csv", "pandas", "encoding", "utf-8" ]
Encoding headaches with ' character in Python, Excel
38,059,812
<p>I am reading a txt file into Python, extract parts of it and then output the results as CSV. </p> <p>Problem is, I get encoding hiccups I don't know how to resolve. Here is what happens: </p> <ol> <li><p>The input file is an export from Adobe Acrobat, where I output a "plain text file" after changing the setting t...
3
2016-06-27T17:25:33Z
38,060,751
<p>When writing the file from your pandas dataframe, do <strong>not</strong> use a <code>codecs</code> file object. <code>pandas.to_csv()</code> <em>already</em> encodes your data, and the <code>codecs</code> file object then has to try to decode (as ASCII) in order to be able to <em>re-encode</em> it.</p> <p>Just use...
1
2016-06-27T18:25:50Z
[ "python", "csv", "pandas", "encoding", "utf-8" ]
Encoding headaches with ' character in Python, Excel
38,059,812
<p>I am reading a txt file into Python, extract parts of it and then output the results as CSV. </p> <p>Problem is, I get encoding hiccups I don't know how to resolve. Here is what happens: </p> <ol> <li><p>The input file is an export from Adobe Acrobat, where I output a "plain text file" after changing the setting t...
3
2016-06-27T17:25:33Z
38,087,864
<p>So looks like this is an Excel (at least Mac Excel 2011) issue; appears that while it does offer an "Unicode UTF-8" setting, it actually can't deal with unicode characters. </p> <p>See e.g. this <a href="https://stackoverflow.com/questions/6588068/which-encoding-opens-csv-files-correctly-with-excel-on-both-mac-and-...
0
2016-06-28T23:25:30Z
[ "python", "csv", "pandas", "encoding", "utf-8" ]
Is there anyway to use a object's name after passing it arbitrarily?
38,059,996
<p>I need to pass a various amount of ships into the code but still be able to use their name when I am inside the hit_or_miss function. Is there a way to pass an arbitrary amount of parameters (as objects) but still access them specifically by name?</p> <pre><code>hit_or_miss(ship_1, ship_2, ship_3) def hit_or_miss(...
0
2016-06-27T17:37:59Z
38,060,140
<p>You could use kwargs. They basically translate your key-value arguments to a dictionary that you can access within your function:</p> <pre><code>def hit_or_miss(**kwargs): print kwargs hit_or_miss(ship1=ship1, ship2=ship2) &gt;&gt;&gt; {'ship2': *yourshipobject*, 'ship1': *yourshipobject*} </code></pre>
0
2016-06-27T17:47:16Z
[ "python", "parameters" ]
Is there anyway to use a object's name after passing it arbitrarily?
38,059,996
<p>I need to pass a various amount of ships into the code but still be able to use their name when I am inside the hit_or_miss function. Is there a way to pass an arbitrary amount of parameters (as objects) but still access them specifically by name?</p> <pre><code>hit_or_miss(ship_1, ship_2, ship_3) def hit_or_miss(...
0
2016-06-27T17:37:59Z
38,060,146
<p>There is no way of doing it without inspecting the upper stack frame, and inspecting the stack frame is generally a bad idea.</p> <p>A better approach would be to inject an attribute, perhaps ship._name, to the class, and later on map it:</p> <pre><code>ships = {ship._name: ship for ship in args} </code></pre> <p...
0
2016-06-27T17:47:26Z
[ "python", "parameters" ]
Is there anyway to use a object's name after passing it arbitrarily?
38,059,996
<p>I need to pass a various amount of ships into the code but still be able to use their name when I am inside the hit_or_miss function. Is there a way to pass an arbitrary amount of parameters (as objects) but still access them specifically by name?</p> <pre><code>hit_or_miss(ship_1, ship_2, ship_3) def hit_or_miss(...
0
2016-06-27T17:37:59Z
38,060,182
<p>You could try to replace your <code>if</code> statement with a loop over your args. </p> <pre><code>hit_or_miss(ship_1, ship_2, ship_3) def hit_or_miss(*args): ships_sunk = 0 for turn in range(4): print "Turn", turn + 1 guess_row = int(raw_input("Guess Row:")) guess_col = int...
1
2016-06-27T17:49:41Z
[ "python", "parameters" ]
Is there anyway to use a object's name after passing it arbitrarily?
38,059,996
<p>I need to pass a various amount of ships into the code but still be able to use their name when I am inside the hit_or_miss function. Is there a way to pass an arbitrary amount of parameters (as objects) but still access them specifically by name?</p> <pre><code>hit_or_miss(ship_1, ship_2, ship_3) def hit_or_miss(...
0
2016-06-27T17:37:59Z
38,060,330
<p>1) Why can't you use a list of ships? </p> <pre><code>def hit_or_miss(ships): for ship in ships: pass hit_or_miss([ship1, ship2, ship3]) </code></pre> <p>2) Or declare <code>hit_or_miss</code> with a variable number of arguments? </p> <pre><code>def hit_or_miss(*ships): for ship in ships: pass hit_or_mis...
0
2016-06-27T17:59:08Z
[ "python", "parameters" ]
Is there anyway to use a object's name after passing it arbitrarily?
38,059,996
<p>I need to pass a various amount of ships into the code but still be able to use their name when I am inside the hit_or_miss function. Is there a way to pass an arbitrary amount of parameters (as objects) but still access them specifically by name?</p> <pre><code>hit_or_miss(ship_1, ship_2, ship_3) def hit_or_miss(...
0
2016-06-27T17:37:59Z
38,060,597
<p>I think you misunderstand the word "arbitrarily". This means that there is a variable amount of ships passed to the function, not just 3.</p> <p>If your function should take exactly 3 ships that you refer to by name then the function should take 3 perameters:</p> <pre><code>def hit_or_miss(ship1, ship2, ship3): </...
0
2016-06-27T18:16:50Z
[ "python", "parameters" ]
Aggregate sets of Pandas DataFrames columns
38,060,113
<p>I have a pandas DataFrame with some independent columns, and I'm looking for an efficient way to unwind / aggregate them.</p> <p>So, let's say I have the table:</p> <pre><code>+-----+-----+-------+------+-------+ | One | Two | Three | Four | Count | +-----+-----+-------+------+-------+ | a | x | y | y |...
0
2016-06-27T17:46:07Z
38,060,331
<p>You can use <code>melt</code> function from <code>pandas</code> to reshape your data frame from wide to long format then groupby the <code>One</code> and <code>Other</code> columns and <code>sum</code> the <code>Count</code> column:</p> <pre><code>import pandas as pd pd.melt(df, id_vars = ['One', 'Count'], value_na...
0
2016-06-27T17:59:08Z
[ "python", "pandas", "dataframe" ]
Convert string date to a different format in pandas dataframe
38,060,172
<p>I have been looking for this answer in the community so far, could not have.</p> <p>I have a dataframe in python 3.5.1 that contains a column with dates in string imported from a CSV file.</p> <p>The dataframe looks like this</p> <pre><code> TimeStamp TBD TBD Value TBD 0 2016/06/08 1...
1
2016-06-27T17:49:01Z
38,060,464
<p>If you convert the column of strings to a time series, you could use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>dt.strftime</code> method</a>:</p> <pre><code>import numpy as np import pandas as pd nan = np.nan df = pd.DataFrame({'TBD': [na...
2
2016-06-27T18:08:28Z
[ "python", "pandas", "dataframe" ]
LLDB Python API type casting
38,060,174
<p>In GDB Macros, I can do something like this:</p> <pre><code>set $node = (node_t *) $arg0 </code></pre> <p>When the node_t is actually defined in a library file. How do I go about doing casting operations of the same nature in LLDB Python macros?</p>
0
2016-06-27T17:49:09Z
38,083,064
<p>There are a couple of ways to do this. The easiest is to use SBFrame.EvaluateExpression like:</p> <pre><code>options = lldb.SBExpressionOptions() val = frame.EvaluateExpression("(node_t *) $arg1", options) </code></pre> <p>where frame is the stack frame you in the context of which you are evaluating the expressio...
1
2016-06-28T17:52:47Z
[ "python", "lldb" ]
Django Left Outer Join
38,060,232
<p>I have a website where users can see a list of movies, and create reviews for them.</p> <p>The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score.</p> <p>...
13
2016-06-27T17:52:43Z
38,108,285
<p>First of all, there is not a way (atm Django 1.9.7) to have a representation <strong>with Django's ORM</strong> of the raw query you posted, <em><strong>exactly</strong> as you want</em>; although, you can get the same desired result with something like:</p> <pre><code>&gt;&gt;&gt; Topic.objects.annotate(f=Case(Whe...
12
2016-06-29T19:16:34Z
[ "python", "django", "django-models", "orm" ]
Django Left Outer Join
38,060,232
<p>I have a website where users can see a list of movies, and create reviews for them.</p> <p>The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score.</p> <p>...
13
2016-06-27T17:52:43Z
38,113,643
<h2>Raw Queries.</h2> <pre><code>topics = Topic.objects.raw(''' select * from bar_topic left join (select topic_id as tid, value from bar_record where user_id = 1) AS subq on tid = bar_topic.id ''') </code></pre> <p>You seem to know the answer yourself. There is nothing...
3
2016-06-30T03:46:46Z
[ "python", "django", "django-models", "orm" ]