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
List Comprehension doesn't work as expected
38,000,337
<p>In trying to use list comprehension more often I tried to code golf an assignment. So this works:</p> <pre><code>if fraction[0] % i == 0 and fraction[1] % i == 0: fraction = [fraction[x]/i for x in range(2)] </code></pre> <p>But this doesn't work:</p> <pre><code>fraction = [fraction[x]/i for x in ran...
0
2016-06-23T19:35:06Z
38,000,510
<p>The issue is that in the second case, <code>fraction</code> always gets overridden.</p> <p>So for example, if <code>fraction = [2, 4]</code> and <code>i = 3</code>, your list comprehension will result in <code>fraction == []</code>, while the loop will just do nothing.</p> <p><strong>UPDATE</strong></p> <p>Here's...
1
2016-06-23T19:45:17Z
[ "python", "list-comprehension" ]
PyCharm Code Folding Collapse
38,000,353
<p>In PyCharm, I have it selected in my settings so that when I collapse the code within a method or I collapse my import statements, I get the box on the left hand size by the line numbers with the "+" inside it to expand when I want to investigate.</p> <p>Is there any way to adjust the color settings in PyCharm rega...
1
2016-06-23T19:35:58Z
38,000,487
<p>I personally prefer to use the <strong>keyboard shortcuts</strong> for (un-)folding. They are very helpful and maybe you can have a look. I also sometimes click "in the code" to fold or unfold code. </p> <p>If that does not solve your problem, intelliJ comes with 3 different default <strong>UI themes</strong> (Darc...
1
2016-06-23T19:44:00Z
[ "python", "colors", "ide", "pycharm", "setting" ]
How to deploy a web.py webservice on Windows 2012 rs server with IIS?
38,000,377
<p>I have a Windows 2012 server with IIS on it and i have my web.py script on it . This script is working fine on localhost of the server but i want to deploy it to be used on internet. As i cannot find any good documentation or sources , any help is appreciated.</p> <p>Thanx in advance.</p>
1
2016-06-23T19:37:38Z
38,289,335
<p>Please check: </p> <p><a href="http://netdot.co/2015/03/09/flask-on-iis/" rel="nofollow">http://netdot.co/2015/03/09/flask-on-iis/</a> or <a href="http://www.golden-orb.ltd.uk/running-a-python-website-using-microsoft-iis/" rel="nofollow">http://www.golden-orb.ltd.uk/running-a-python-website-using-microsoft-iis/</a>...
0
2016-07-10T06:41:10Z
[ "python", "web-services", "iis", "web.py" ]
How to calculate the volume of a vtk file
38,000,412
<p>I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume.</p> <p>This is the code I'm using:</p> <pre><code>import vtk reader = vtk.vtkPolyDataReader...
1
2016-06-23T19:39:35Z
38,000,772
<p>You have assigned <code>reader.GetOutput()</code> in <code>polydata</code>. From <code>polydata</code>, I believe you need to do, <code>polydata.GetOutputPort()</code></p>
0
2016-06-23T20:00:17Z
[ "python", "3d", "vtk" ]
How to calculate the volume of a vtk file
38,000,412
<p>I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume.</p> <p>This is the code I'm using:</p> <pre><code>import vtk reader = vtk.vtkPolyDataReader...
1
2016-06-23T19:39:35Z
38,058,473
<p>Depending on your version of <code>vtk</code> package you may want to test the following syntax if your version &lt;= <code>5</code>:</p> <pre><code> Mass.SetInput(polydata.GetOutput()); </code></pre> <p>Otherwise, the actual syntax is:</p> <pre><code> Mass.SetInputData(polydata.GetOutputPort()); </code></pre> ...
1
2016-06-27T16:01:04Z
[ "python", "3d", "vtk" ]
How to calculate the volume of a vtk file
38,000,412
<p>I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume.</p> <p>This is the code I'm using:</p> <pre><code>import vtk reader = vtk.vtkPolyDataReader...
1
2016-06-23T19:39:35Z
38,076,802
<p>I guess you have VTK 6 , you can provide as input to a filter either the output port of a filter or a vtkDataObject :</p> <pre><code>Mass.SetInputConnection(reader.GetOutputPort()) Mass.SetInputData(polydata) #that is Mass.SetInputData(reader.GetOutput()) </code></pre> <p>For understanding why these method are no...
0
2016-06-28T12:53:09Z
[ "python", "3d", "vtk" ]
How to get source packages from dir in /usr/lib/python2.7/dist-packages/
38,000,416
<p>What is the way to get the name of the package which creates specific dir under /usr/lib/python2.7/dist-packages/ on Ubuntu </p> <p>For example I am trying to get the package name which installs <code>/usr/lib/python2.7/dist-packages/hdinsight_common/</code> or <code>/usr/lib/python2.7/dist-packages/hdinsight_commo...
0
2016-06-23T19:39:46Z
38,004,576
<p>Use <code>dpkg -S &lt;path...&gt;</code> for installed packages, or <code>apt-file search &lt;paths...&gt;</code> for packages that might not be installed.</p>
1
2016-06-24T02:03:43Z
[ "python", "python-2.7", "ubuntu", "pip" ]
Move still-buffered stdin line down by one when there is output
38,000,588
<p>I have written a simple chat program in python. You just have a simple input() prompt (using readline) which should always be on the bottom.</p> <pre><code>partner: hey you &gt; (stdin) </code></pre> <p>Now, I am trying this without using curses and I have had success by defining these two constants</p> <pre clas...
2
2016-06-23T19:49:47Z
38,004,548
<p>If you put the terminal in raw mode (using module <code>termios</code>), and handle every keystroke as it's typed, then you will <em>know</em> whether or not there is any buffered input before you print the partner's message.</p> <p>(Also, how are receiving the messages from the partner (socket?) and how are you mu...
0
2016-06-24T01:59:09Z
[ "python", "tty", "ansi-escape" ]
Move still-buffered stdin line down by one when there is output
38,000,588
<p>I have written a simple chat program in python. You just have a simple input() prompt (using readline) which should always be on the bottom.</p> <pre><code>partner: hey you &gt; (stdin) </code></pre> <p>Now, I am trying this without using curses and I have had success by defining these two constants</p> <pre clas...
2
2016-06-23T19:49:47Z
38,015,932
<p>Ok, I solved my problem. I discovered the module <code>rl</code>. I use it this way:</p> <pre class="lang-py prettyprint-override"><code>import rl.readline as readline # code print(ERASE_LINE + CURSOR_UP_ONE) print('partner &gt; ' + msg) readline.redisplay(True) </code></pre> <p>This just redisplays the prompt ...
0
2016-06-24T14:34:09Z
[ "python", "tty", "ansi-escape" ]
multiplication of large arrays in python
38,000,663
<p>I have big arrays to multiply in large number of iterations also. </p> <p>I am training a model with array long around 1500 and I will perform 3 multiplications for about 1000000 times which takes a long time almost week. </p> <p>I found Dask I tried to compare it with the normal numpy way but I found numpy faster...
1
2016-06-23T19:54:27Z
38,000,861
<p>Performance for <code>.dot</code> strongly depends on the <a href="https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms" rel="nofollow">BLAS library</a> to which your NumPy implementation is linked. </p> <p>If you have a modern implementation like OpenBLAS or MKL then NumPy is already running at full spe...
2
2016-06-23T20:05:53Z
[ "python", "parallel-processing", "dask" ]
How to extract h2 and h3 titles from news articles
38,000,666
<p>I'm trying to create this web scrapper that can extract the main title from news articles. </p> <pre><code># -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup url= input('enter the url \n') r = requests.get(url) content = r.content soup = BeautifulSoup(content, "html.parser") heading = soup.fin...
-3
2016-06-23T19:54:42Z
38,000,741
<p><code>BeautifulSoup</code> is quite flexible, just pass in a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list" rel="nofollow">list of tag names</a> you want to find:</p> <pre><code>soup.find_all(['h1', 'h2', 'h3']) </code></pre> <p>You can even do:</p> <pre><code>import re soup.find_all(re....
2
2016-06-23T19:58:58Z
[ "python", "beautifulsoup" ]
Django - aggregate queryset by week of year
38,000,670
<p>I have model looking like this:</p> <pre><code>class TestData(models.Model): name = models.CharField(max_length=255) one_value = models.IntegerField() second_value = models.IntegerField() create_at = models.DateTimeField() </code></pre> <p>Is any way to easy generate queryset of summed values for e...
0
2016-06-23T19:54:47Z
38,001,646
<pre><code>from django.db.models import Func, F, Sum class Week(Func): def as_mysql(self, compiler, connection): self.function = 'WEEK' return super().as_sql(compiler, connection) data = (TestData.objects .filter(create_at__year=year) .annotate(week=Week('create_at')) .valu...
1
2016-06-23T20:52:38Z
[ "python", "django", "orm" ]
Python (pygame) using the sprites and classes to make clones of images
38,000,690
<pre><code>import pygame import time import random #Loads pygame and clock and random function pygame.init() #Intiates pygame display_width = 1440 display_height = 900 gameDisplay = pygame.display.set_mode((display_width,display_height)) clock = pygame.time.Clock() #Starts auto clock updater AstImg = pygame.image.l...
1
2016-06-23T19:55:56Z
38,014,701
<p>It looks like you're going to want to use classes to make your code more compact. Essentially, a class is a collection of variables and functions that may be used to define an object, such as an asteroid. Here is an example of a very simple asteroid class:</p> <pre><code>class Asteroid(pygame.sprite.Sprite): d...
0
2016-06-24T13:32:47Z
[ "python", "class", "pygame", "sprite", "clone" ]
writing arrays to csv
38,000,716
<p>I am looping through 2d array (data) then populate fields using different segments of the arrays that I am looping over. Below is the sample code:</p> <pre><code>with open('output.csv' , 'wb') as outcsv: headers = ['Field1', 'Field2', 'LongField'] writer = csv.DictWriter(outcsv, headers) writer.writehea...
-1
2016-06-23T19:57:00Z
38,001,112
<p>I suspect OP wants all those 0's to print, no matter how many there are. No <code>array(</code> nor <code>)</code> and no ellipsis <code>...</code></p> <p><strong>Guess:</strong></p> <p>Try <code>','.join([str(_) for _ in data[i][5:]])</code></p> <p><strong>In full:</strong></p> <pre><code>row = [{'Field1': data...
1
2016-06-23T20:21:31Z
[ "python", "arrays", "csv" ]
How to iterate over keys in array of arrays?
38,000,743
<p>I have an array, say:</p> <pre><code>products = [['product_1','description 1'],['product_2','description 2']] </code></pre> <p>And I want to check input against the keys, e.g.,:</p> <pre><code>product = raw_input('Enter product: ') if product not in products.keys(): log.fatal('Invalid product: {}'.format(pro...
1
2016-06-23T19:59:03Z
38,000,780
<p>lists dont have keys ... you just want the first element of each sublist</p> <pre><code>dict(products).keys() #ONLY if there is exactly 2 items per sublist </code></pre> <p>or </p> <pre><code>zip(*products)[0] #any number of items per sublist is ok </code></pre> <p>or </p> <pre><code>[k for k,val in products] #...
2
2016-06-23T20:00:56Z
[ "python", "arrays", "python-2.7" ]
How to iterate over keys in array of arrays?
38,000,743
<p>I have an array, say:</p> <pre><code>products = [['product_1','description 1'],['product_2','description 2']] </code></pre> <p>And I want to check input against the keys, e.g.,:</p> <pre><code>product = raw_input('Enter product: ') if product not in products.keys(): log.fatal('Invalid product: {}'.format(pro...
1
2016-06-23T19:59:03Z
38,000,802
<p><code>keys</code> is not a method of a <code>list</code>. You must be thinking of a <code>dict</code>. Just do:</p> <pre><code>products = {k: v for k, v in [['product_1','description 1'],['product_2','description 2']]} </code></pre>
2
2016-06-23T20:02:07Z
[ "python", "arrays", "python-2.7" ]
Efficient way of finding a specific directory based on input parameters?
38,000,763
<p>Given two parameters, <code>123</code> and <code>abc</code>, I can uniquely identify a directory of the form:</p> <pre><code>\path\to\unique_123\directory_abc </code></pre> <p><strong>However</strong>, "unique" and "directory" will vary from folder to folder. I would like to create a function such that <code>func(...
0
2016-06-23T19:59:47Z
38,000,904
<p>If you want to see what directories are in folder, use:</p> <pre><code>os.listdir("/path/to/folder") </code></pre> <p>Using this, you can get the names of the subfolders. </p> <p>If you see a folder like <code>unique_123</code> already in there, you can strip the digits off the end of the folder name using `rstr...
-1
2016-06-23T20:09:15Z
[ "python", "directory", "os.walk", "pathname" ]
Efficient way of finding a specific directory based on input parameters?
38,000,763
<p>Given two parameters, <code>123</code> and <code>abc</code>, I can uniquely identify a directory of the form:</p> <pre><code>\path\to\unique_123\directory_abc </code></pre> <p><strong>However</strong>, "unique" and "directory" will vary from folder to folder. I would like to create a function such that <code>func(...
0
2016-06-23T19:59:47Z
38,004,492
<p>Possibly you want:</p> <pre><code>import glob matches = glob.glob('**/*_%s/*_%s' % ('123', 'abc'), recursive=True) assert len(matches) == 1 print(matches[0]) </code></pre> <p>But avoid <code>recursive</code> if you don't really need it, it will often be very slow! If you really <em>do</em> need it, I would probab...
2
2016-06-24T01:51:38Z
[ "python", "directory", "os.walk", "pathname" ]
Creating conda environment using only symbolic links
38,000,773
<p>I want to create an environment which is an exact copy of my <code>root</code> environment, but not making any hard copies of packages (later I will add a few packages not in Anaconda). I though I could do this with one of the following:</p> <pre><code>conda create -n newroot --clone root conda create -n newroot --...
0
2016-06-23T20:00:19Z
38,378,345
<p><code>conda</code> uses hardlinks internally when it can (nearly always) so the cost of new environments is minimal, so my recommendation is to use:</p> <p><code> conda create -n newroot --clone root </code></p> <p>Do not use <code>--copy</code> since that explicitly avoids using hardlinks.</p>
1
2016-07-14T15:29:51Z
[ "python", "anaconda", "conda" ]
pylab: different behavior in shell and script
38,000,793
<p>I'm running into a weird problem with matplotlib. Here is my code:</p> <pre><code>f,a=subplots(3,1,sharex='col') f.set_figheight(3.) f.set_figwidth(3.) ## Make plots, set labels for a[0], a[1], a[2] a[2].set_xlim(-4.40,6) [plt.setp(i.get_xticklabels(),fontsize=9) for i in a] [plt.setp(i.get_yticklabels(),fontsize=...
1
2016-06-23T20:01:42Z
38,000,884
<p>Actually, the for-loop is more "pythonic" than your misuse of list comprehension. See also <a href="http://stackoverflow.com/questions/21428602/how-inefficient-is-a-list-comprehension-if-you-dont-assign-it">here</a>.</p> <p>I think you should move all those into the for-loop... That way you have a single outer loop...
3
2016-06-23T20:07:21Z
[ "python", "matplotlib", "ipython" ]
Reordering columns in CSV
38,000,868
<p>Question has been posted before but the requirements were not properly conveyed. I have a csv file with more than 1000 columns:</p> <pre><code>A B C D .... X Y Z 1 0 0.5 5 .... 1 7 6 2 0 0.6 4 .... 0 7 6 3 0 0.7 3 .... 1 7 6 4 0 0.8 2 .... 0 7 6 </code></pre> <p>Here ...
-2
2016-06-23T20:06:16Z
38,001,459
<p>So the question is how to reorder your columns in a custom way.</p> <p>For example you have the following DF and you want to reorder your columns in the following way (indices):</p> <p>5, 3, rest...</p> <p>DF</p> <pre><code>In [82]: df Out[82]: A B C D E F G 0 1 0 0.5 5 1 7 6 1 2 0 0.6 4 0...
1
2016-06-23T20:41:30Z
[ "python", "python-2.7", "csv", "numpy", "pandas" ]
Reordering columns in CSV
38,000,868
<p>Question has been posted before but the requirements were not properly conveyed. I have a csv file with more than 1000 columns:</p> <pre><code>A B C D .... X Y Z 1 0 0.5 5 .... 1 7 6 2 0 0.6 4 .... 0 7 6 3 0 0.7 3 .... 1 7 6 4 0 0.8 2 .... 0 7 6 </code></pre> <p>Here ...
-2
2016-06-23T20:06:16Z
38,002,825
<pre><code>In [4]: df Out[4]: A B C D X Y Z 0 1 0 0.5 5 1 7 6 1 2 0 0.6 4 0 7 6 2 3 0 0.7 3 1 7 6 3 4 0 0.8 2 0 7 6 In [5]: df.reindex(columns=['D','Y','Z','A','B','C','X']) Out[5]: D Y Z A B C X 0 5 7 6 1 0 0.5 1 1 4 7 6 2 0 0.6 0 2 3 7 6 3 0 0.7 ...
0
2016-06-23T22:20:08Z
[ "python", "python-2.7", "csv", "numpy", "pandas" ]
String operations not working with special characters
38,000,912
<p>I opened a text file using utf-8 encoding. I am trying to do operations on the strings like <code>line[0]</code>, but it is not working correctly because of special characters in the text file. Most of the time, it does not return anything.</p> <pre><code>import codecs with codecs.open('test_2014.txt', mode='r', en...
-4
2016-06-23T20:09:53Z
38,001,143
<p>Your code reads a full string into the variable <code>line</code> which is encoded into <code>conv</code> Since that is a string, <code>conv[i]</code> gives you one of the characters in the string. If you have more than one word in the line, then use `split()1</p> <pre><code>for line in document: conv = line.en...
0
2016-06-23T20:23:08Z
[ "python", "utf-8", "character-encoding", "python-2.x" ]
Do tornado AsyncHTTPClient fetch callbacks get called in order of request or response?
38,000,992
<p>I'm using Tornado's AsyncHTTPClient to fetch a URL multiple times. I pass in a different callback with each request.</p> <p>If I send requests A, B (with associated callbacks Callback_A and Callback_B) to a URL, but the responses come back in the opposite order B, A. Should I expect the callbacks to be called in th...
0
2016-06-23T20:15:19Z
38,003,009
<p>Callbacks are executed as soon as possible after the event for which they're waiting is complete. So, they are called in response order.</p>
0
2016-06-23T22:35:31Z
[ "python", "python-3.x", "http", "tornado" ]
How can I get my assertions in pytest to stop being abbreviated with ellipsis?
38,000,993
<p>How can I get my assertions in pytest to stop being abbreviated with ellipsis ?</p> <p>Every time i have an assertion that reports error it truncates all my strings with "..." why is that? how can i sto pthat? </p>
1
2016-06-23T20:15:19Z
38,009,364
<p>Could you show an example? This is how the output looks for me:</p> <pre><code> def test_foo(): &gt; assert "a"*100 == "a"*100 + "b" E assert 'aaaaaaaaaaaa...aaaaaaaaaaaaa' == 'aaaaaaaaaaaaa...aaaaaaaaaaaab' E Skipping 89 identical leading characters in diff, use -v to show E - aaaaaa...
2
2016-06-24T08:57:37Z
[ "python", "py.test" ]
Python: Print only one time inside a loop
38,001,105
<p>I have a code where I want capture a video from a camera. I want to use Logging library of Python to get messages on the shell or export them to a text file.</p> <p>Here is a part of my code where inside the while loop I want to print <em>Camera Opened Successfully</em> </p> <pre><code>import numpy as np import cv...
0
2016-06-23T20:21:00Z
38,001,145
<p>You must break out of the loop</p> <pre><code>import numpy as np import cv2 import logging as log cap = cv2.VideoCapture('5.mpg') while True: ret, image = cap.read() if ret == True: log.warning('Camera Opened Successfully') break </code></pre>
0
2016-06-23T20:23:19Z
[ "python", "loops", "opencv3.0" ]
Python: Print only one time inside a loop
38,001,105
<p>I have a code where I want capture a video from a camera. I want to use Logging library of Python to get messages on the shell or export them to a text file.</p> <p>Here is a part of my code where inside the while loop I want to print <em>Camera Opened Successfully</em> </p> <pre><code>import numpy as np import cv...
0
2016-06-23T20:21:00Z
38,001,196
<pre><code>import numpy as np import cv2 import logging as log cap = cv2.VideoCapture('5.mpg') hasOpened = False while True: ret, image = cap.read() if ret and not hasOpened: log.warning('Camera Opened Successfully') hasOpened = True </code></pre> <p>If you want to break out of the loop aft...
3
2016-06-23T20:26:05Z
[ "python", "loops", "opencv3.0" ]
Python: Print only one time inside a loop
38,001,105
<p>I have a code where I want capture a video from a camera. I want to use Logging library of Python to get messages on the shell or export them to a text file.</p> <p>Here is a part of my code where inside the while loop I want to print <em>Camera Opened Successfully</em> </p> <pre><code>import numpy as np import cv...
0
2016-06-23T20:21:00Z
38,001,213
<p>Add an extra boolean to track whether you have printed it out before: </p> <pre><code>import numpy as np import cv2 import logging as log cap = cv2.VideoCapture('5.mpg') printed = False while True: ret, image = cap.read() if ret == True and not printed: log.warning('Camera Opened Successfully') ...
0
2016-06-23T20:27:20Z
[ "python", "loops", "opencv3.0" ]
Python: Print only one time inside a loop
38,001,105
<p>I have a code where I want capture a video from a camera. I want to use Logging library of Python to get messages on the shell or export them to a text file.</p> <p>Here is a part of my code where inside the while loop I want to print <em>Camera Opened Successfully</em> </p> <pre><code>import numpy as np import cv...
0
2016-06-23T20:21:00Z
38,001,231
<p>Assuming you want to use your main loop to handle your application logic, and it doesn't make sense to have one loop for detecting if it is opened and another for working with it then I think what you want is to set a variable to determine if the state has changed.</p> <pre><code>import numpy as np import cv2 impor...
-1
2016-06-23T20:27:59Z
[ "python", "loops", "opencv3.0" ]
Python: Print only one time inside a loop
38,001,105
<p>I have a code where I want capture a video from a camera. I want to use Logging library of Python to get messages on the shell or export them to a text file.</p> <p>Here is a part of my code where inside the while loop I want to print <em>Camera Opened Successfully</em> </p> <pre><code>import numpy as np import cv...
0
2016-06-23T20:21:00Z
38,001,270
<p>You need to break the while loop, also since you would like to break out of the loop as soon as you get <code>ret</code> True you can use:</p> <pre><code>ret = False while not ret: ret, image = cap.read() if ret: log.warning('Camera Opened Successfully') # any other code </code></pre>
0
2016-06-23T20:30:45Z
[ "python", "loops", "opencv3.0" ]
Python: Print only one time inside a loop
38,001,105
<p>I have a code where I want capture a video from a camera. I want to use Logging library of Python to get messages on the shell or export them to a text file.</p> <p>Here is a part of my code where inside the while loop I want to print <em>Camera Opened Successfully</em> </p> <pre><code>import numpy as np import cv...
0
2016-06-23T20:21:00Z
38,001,303
<p>Set a flag to trigger the log and then make it false. ret is to be made False when you are ready to exit the loop so that it will exit </p> <pre><code>import numpy as np import cv2 import logging as log cap = cv2.VideoCapture('5.mpg') ret = True logit = True while ret: ret, image = cap.read() if logit ==...
0
2016-06-23T20:32:51Z
[ "python", "loops", "opencv3.0" ]
How to take random sample of a cvs file in Python?
38,001,157
<p>I am new to Python and want to learn Data Wrangling process using it. I am using jupyter for this.</p> <p>I have a file named fle with 81,000 rows and 89 columns. I want to randomly select about 100 rows from it. How do I do that? I keep on getting following error.</p> <pre><code>fle=pd.read_csv("C:\Users\Mine\Doc...
0
2016-06-23T20:23:58Z
38,002,595
<p>use <code>random.choice</code> instead of sample. you can use <code>csv.DictReader</code> to handle the csv as a list of dicts</p> <pre><code>import csv import random random_rows = set() with open("C:\Users\Mine\Documents\ssample.csv", "r") as csvfile: reader = csv.DictReader(csvfile) rows = [r for r in read...
1
2016-06-23T21:58:49Z
[ "python", "ipython", "sampling" ]
SQL insert multiple data in a specific column (python)
38,001,158
<p>Hi have the following code:</p> <pre><code>def create_table(): c.execute('CREATE TABLE IF NOT EXISTS TEST(Tournament TEXT, MATCH_TIME TEXT, TEAM_1 TEXT, TEAM_2 TEXT)') create_table() def data_entry_tournament(): c.executemany("INSERT INTO TEST(TOURNAMENT) VALUES (?)", (Tournament.text.strip())) ...
0
2016-06-23T20:24:02Z
38,001,385
<p><code>executemany()</code> executes the SQL statement once for each element in the list.</p> <p>You did not give it a list but a string, so it executed the SQL statement once for each element in the string, i.e., once for each character.</p> <p>Just use <code>execute()</code> for a single execution, and don't forg...
0
2016-06-23T20:37:33Z
[ "python", "mysql", "sql", "sqlite" ]
Why can't I see all stats for object from Facebook Graph API
38,001,160
<p>I'm using the <a href="https://github.com/mobolic/facebook-sdk" rel="nofollow">Python SDK for Facebook's Graph API</a> to fetch how many times a Facebook page has been liked. I went to the <a href="https://developers.facebook.com/tools/explorer/" rel="nofollow">API Explorer</a> to obtain an access token. The first...
0
2016-06-23T20:24:20Z
38,003,597
<p>There are two things to look here. </p> <ol> <li><p>Version of facebook API. In your first example when you got lots of result, you are using <strong>version 2.2</strong> (that is the default version of facebook python sdk). When you went and created new app in facebook, it has most likely used <strong>version 2.6...
2
2016-06-23T23:45:48Z
[ "python", "facebook", "facebook-graph-api" ]
File upload at web2py
38,001,245
<p>I am using the web2py framework. I have uploaded txt a file via SQLFORM and the file is stored in the "upload folder", now I need to read this txt file from the controller, what is the file path I should use in the function defined in the default.py ? </p> <pre><code>def readthefile(uploaded_file): file = open...
0
2016-06-23T20:28:44Z
38,005,543
<p>You can do join of application directory and upload folder to build path to file. Do something like this:</p> <pre><code>import os filepath = os.path.join(request.folder, 'uploads', uploaded_file_name) file = open(filepath, "rb") </code></pre> <blockquote> <p><strong>request.folder</strong>: the application dir...
0
2016-06-24T04:19:43Z
[ "python", "web2py" ]
File upload at web2py
38,001,245
<p>I am using the web2py framework. I have uploaded txt a file via SQLFORM and the file is stored in the "upload folder", now I need to read this txt file from the controller, what is the file path I should use in the function defined in the default.py ? </p> <pre><code>def readthefile(uploaded_file): file = open...
0
2016-06-23T20:28:44Z
38,012,530
<p>The transformed name of the uploaded file is stored in the upload field of your database table, so you need a way to query the specific record that was inserted via the <code>SQLFORM</code> submission in order to get the name of the stored file. Here is how it would look assuming you know the record ID:</p> <pre><c...
0
2016-06-24T11:37:24Z
[ "python", "web2py" ]
Try to call a function within itself
38,001,247
<p>I am new to the python. Recently, I follow the online python course to learn the python. Here is a simple question from the course: </p> <p>Write a function called <strong>item_order</strong> that takes as input a string named <strong>order</strong>. The string contains only words for the items the customer can ord...
0
2016-06-23T20:28:46Z
38,001,363
<pre><code>if flag == 1: print('There is something wrong on the order you insert, please re-enter.') fix_order = raw_input('') item_order(fix_order) </code></pre> <p>This <code>item_order</code> call has no effect. You're not using the return value.</p> <p>Remember that calling a function doesn't just jum...
1
2016-06-23T20:36:26Z
[ "python", "function", "recursion" ]
Try to call a function within itself
38,001,247
<p>I am new to the python. Recently, I follow the online python course to learn the python. Here is a simple question from the course: </p> <p>Write a function called <strong>item_order</strong> that takes as input a string named <strong>order</strong>. The string contains only words for the items the customer can ord...
0
2016-06-23T20:28:46Z
38,001,375
<p>The bug is that your function, item_order, is returning a string, but you are not capturing it anywhere. So when you call item_order in the if statement, you need to have a variable to catch the string it is returning. For example:</p> <pre><code>if flag == 1: print('There is something wrong on the order you ...
1
2016-06-23T20:36:59Z
[ "python", "function", "recursion" ]
How to use dictionaries with variables
38,001,285
<p>I'm trying to create a python program to automatically sort jobs that I'm working on. So far I have managed to create a dictionary. For example:</p> <pre><code>monday = ('1' : 'clean the counters') </code></pre> <p>and assign everyone a number:</p> <pre><code>joe = random.randint(1,3) </code></pre> <p>but when I...
-1
2016-06-23T20:31:27Z
38,001,387
<p>There are a few errors in your code. Firstly, you should be using <code>{}</code> to define a dictionary, not <code>()</code>, like:</p> <pre><code>monday = {1 : 'clean the counters'} </code></pre> <p>Also, you'll notice that I took the quotations off of the <code>1</code>, because you cannot search a dictionary u...
1
2016-06-23T20:37:36Z
[ "python" ]
How to use dictionaries with variables
38,001,285
<p>I'm trying to create a python program to automatically sort jobs that I'm working on. So far I have managed to create a dictionary. For example:</p> <pre><code>monday = ('1' : 'clean the counters') </code></pre> <p>and assign everyone a number:</p> <pre><code>joe = random.randint(1,3) </code></pre> <p>but when I...
-1
2016-06-23T20:31:27Z
38,001,416
<p>You have an extra quotation mark that would cause an error. You also need to convert the integer you assign to joe to be a <code>char</code>/<code>string</code>, since that is how it's stored in dictionary key.</p> <p>A better way would be to just make the dictionary a list. Using <code>1</code>, <code>2</code>, ...
3
2016-06-23T20:39:04Z
[ "python" ]
How to use dictionaries with variables
38,001,285
<p>I'm trying to create a python program to automatically sort jobs that I'm working on. So far I have managed to create a dictionary. For example:</p> <pre><code>monday = ('1' : 'clean the counters') </code></pre> <p>and assign everyone a number:</p> <pre><code>joe = random.randint(1,3) </code></pre> <p>but when I...
-1
2016-06-23T20:31:27Z
38,001,444
<p>Try the following modifications to your code and it should work:</p> <pre><code>monday = {'1' : 'clean the counters', '2' : 'upload the files', '3' : 'pick up the garbage'} joe = str(random.randint(1, 3)) print("Today joe has to do : " + monday[joe]) </code></pre>
0
2016-06-23T20:40:41Z
[ "python" ]
How to use Python to create a single dataset from hundreds of JSON files?
38,001,321
<p>I am brand new to Python and REST (but a long time SAS programmer). I'm trying to download about 10 years of court files from the Wisconsin court REST API. Each case must be queried individually by case number to get the full information, and I've written a loop that gets me the full list of URL's that I need and op...
0
2016-06-23T20:34:15Z
38,002,044
<p>I haven't seen this data, but have you looked at using Pandas? If you're new to Python, it's the module that creates R-like dataframe objects. It also includes a json parser:</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html" rel="nofollow">http://pandas.pydata.org/pandas...
0
2016-06-23T21:19:20Z
[ "python", "json", "rest", "csv" ]
How to use Python to create a single dataset from hundreds of JSON files?
38,001,321
<p>I am brand new to Python and REST (but a long time SAS programmer). I'm trying to download about 10 years of court files from the Wisconsin court REST API. Each case must be queried individually by case number to get the full information, and I've written a loop that gets me the full list of URL's that I need and op...
0
2016-06-23T20:34:15Z
38,002,075
<p>Why not just write a custom flattener function that grabs the data you want from the json into a plain old python dict? I the data you are interested in is on the first level - the conversion will probably look like this:</p> <pre><code>function flattener(s): nested = json.loads(s) return { k:nested[k] for ...
0
2016-06-23T21:22:02Z
[ "python", "json", "rest", "csv" ]
Is there a python equivilent to NDhist in matlab?
38,001,336
<p><a href="http://www.mathworks.com/matlabcentral/fileexchange/45325-efficient-2d-histogram--no-toolboxes-needed/content/ndhist.m" rel="nofollow">Here</a> is the link to the Matlab function, I was wondering if anyone had come across something similar in python. I want to input X and Y arrays of the same length and gen...
0
2016-06-23T20:34:50Z
38,094,838
<p>To put it simply...</p> <p>If you can use numpy, there is a function for that - <code>numpy.histogram2d</code> ( <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.histogram2d.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.histogram2d.html</a> ) to get d...
0
2016-06-29T08:59:46Z
[ "python", "matlab", "histogram", "heatmap", "frequency-distribution" ]
How make a diamond text pattern in python 3.5 using loops
38,001,410
<p>As stated in the title, I am looking to make a diamond text pattern using python 3.5, but I am a little stuck on how to get the shape working correctly. </p> <p>Desired output:</p> <pre><code> S SAS SAMAS SAMPMAS SAMPLPMAS ...
0
2016-06-23T20:38:49Z
38,001,570
<p>You have to print out the whitespace. Think of it like a rectangle rather than a diamond.</p> <p>To get you started:</p> <pre><code>for i in range (0, length): for x in range(0, length-i): print(" ", end="") for j in range(0, i+1): print(word[j], end="") ... </code></pre>
0
2016-06-23T20:47:39Z
[ "python", "python-3.x", "ascii-art" ]
How make a diamond text pattern in python 3.5 using loops
38,001,410
<p>As stated in the title, I am looking to make a diamond text pattern using python 3.5, but I am a little stuck on how to get the shape working correctly. </p> <p>Desired output:</p> <pre><code> S SAS SAMAS SAMPMAS SAMPLPMAS ...
0
2016-06-23T20:38:49Z
38,001,575
<p>You almost have solved it yourself, the only thing missing are <strong>spaces in front of each line</strong>. Now the first line has <em>n-1</em> spaces in front, with <em>n</em> the length of the string, the second line has <em>n-2</em> spaces in front and so on until we reach the middle. The middle line should con...
2
2016-06-23T20:47:52Z
[ "python", "python-3.x", "ascii-art" ]
How make a diamond text pattern in python 3.5 using loops
38,001,410
<p>As stated in the title, I am looking to make a diamond text pattern using python 3.5, but I am a little stuck on how to get the shape working correctly. </p> <p>Desired output:</p> <pre><code> S SAS SAMAS SAMPMAS SAMPLPMAS ...
0
2016-06-23T20:38:49Z
38,001,579
<p>Looks like you're missing padding at the beginning of each line equal to <code>length - i - 1</code> or <code>length - l - 1</code> spaces.</p> <pre><code>def print_row(i, l): print(" " * (l - i - 1), end="") for j in range(0, i+1): print(word[j], end="") for k in range(i-1, -1, -1): pri...
2
2016-06-23T20:48:02Z
[ "python", "python-3.x", "ascii-art" ]
How make a diamond text pattern in python 3.5 using loops
38,001,410
<p>As stated in the title, I am looking to make a diamond text pattern using python 3.5, but I am a little stuck on how to get the shape working correctly. </p> <p>Desired output:</p> <pre><code> S SAS SAMAS SAMPMAS SAMPLPMAS ...
0
2016-06-23T20:38:49Z
38,001,746
<p>How about</p> <pre><code>import itertools l = len(word) for j in itertools.chain(range(l), reversed(range(l-1))): print(word[0:j].rjust(l) + word[j::-1]) </code></pre> <p>which gives the output you are looking for. This uses the <code>rjust</code> string method to properly pad the space before the shortened w...
2
2016-06-23T20:58:54Z
[ "python", "python-3.x", "ascii-art" ]
How make a diamond text pattern in python 3.5 using loops
38,001,410
<p>As stated in the title, I am looking to make a diamond text pattern using python 3.5, but I am a little stuck on how to get the shape working correctly. </p> <p>Desired output:</p> <pre><code> S SAS SAMAS SAMPMAS SAMPLPMAS ...
0
2016-06-23T20:38:49Z
38,002,067
<p>This code works for this problem and is pretty simple:</p> <pre><code>def diamond(): word = input("Enter characters : ") space_length = len(word) for i in range(len(word)): space_length -= 1 for k in range(space_length, 0, -1): print(" ", end="") sliced = word[0:i+1] ...
0
2016-06-23T21:21:36Z
[ "python", "python-3.x", "ascii-art" ]
How make a diamond text pattern in python 3.5 using loops
38,001,410
<p>As stated in the title, I am looking to make a diamond text pattern using python 3.5, but I am a little stuck on how to get the shape working correctly. </p> <p>Desired output:</p> <pre><code> S SAS SAMAS SAMPMAS SAMPLPMAS ...
0
2016-06-23T20:38:49Z
38,002,578
<p>You could use list comprehension and centered string padding, looping though the generated list and slicing the string to create the diamond as follows:</p> <pre><code># concatenated list comprehensions # form 0 to 11 to 0 in steps of 2 diamondlist = [i for i in range(1,12,2)] + [i for i in range(9,0,-2)] # string...
0
2016-06-23T21:57:54Z
[ "python", "python-3.x", "ascii-art" ]
how to call function from python script from different directory in shell
38,001,414
<p>i am trying to run function from python from different directory with </p> <p><code>python -c 'import /advg/users/ibrahims/test-coverage-files/coverage.py; coverage.InitliazeResultHtml' </code> i get the following output :</p> <pre><code> File "&lt;string&gt;", line 1 import $location; $location.InitliazeResult...
-1
2016-06-23T20:39:01Z
38,003,179
<p>This error means what you type was not correct, python don't understand what you type. I think you should simply type python to enter interactive mode, and then do what you want.</p> <pre><code>import sys sys.append(your path to this file) </code></pre> <p>You can google python module to see how to import.</p> <p...
0
2016-06-23T22:52:01Z
[ "python", "linux", "bash", "python-2.7" ]
Django upload many images and save to model
38,001,439
<p>I have seen similar questions, but they are old. I wonder if there is a new better approach to this process.</p> <p>I have a form that uploads many images at once. ¿How do I process them with django and create one model object per uploaded image?</p> <p>I have a model with an Image field:</p> <pre><code>class XM...
1
2016-06-23T20:40:27Z
38,002,885
<p>Ok, this is how I did it. Maybe there is a better way but anyway:</p> <pre><code> if request.method == "POST": files = request.FILES.getlist('images') for x in files: XModel.objects.create(image=x) return HttpResponse('Yeii') </code></pre>
1
2016-06-23T22:25:31Z
[ "python", "django" ]
Python and XML Append for Feed RSS
38,001,485
<p>I'm developing a simple Python script that generates an Feed RSS (XML).</p> <p>But I can't append a new feed before the old, so as to have first rss always the latest news.</p> <p>This is the code that I use to generate the initial XML file:</p> <pre><code>#!/usr/bin/env python from lxml import etree as ET root ...
1
2016-06-23T20:43:22Z
38,001,767
<p>You want to add it after the <em>description</em> node, which you can do with <a href="http://lxml.de/api/lxml.etree._Element-class.html#addnext" rel="nofollow">addnext</a>:</p> <pre><code>channel.find(".//description").addnext(item) print ET.tostring(channel, pretty_print=True, xml_declaration=True) </code></pre>...
0
2016-06-23T20:59:49Z
[ "python", "xml", "rss" ]
Pandas: create new column from old, add values
38,001,588
<p>I have the following pandas DataFrame:</p> <pre><code>import pandas as pd import numpy as np data = 'filename.csv' df = pd.DataFrame(data) df one two three four five a 0.469112 -0.282863 -1.509059 bar True b NaN 1.224234 7.823421 bar False c -1.135632 1.212112 -0.173215 bar Fa...
1
2016-06-23T20:48:38Z
38,001,607
<p>try this:</p> <pre><code>df['oneplus20'] = df['one'] + 20.0 </code></pre> <p>demo:</p> <pre><code>In [36]: df['oneplus20'] = df['one'] + 20.0 In [37]: df Out[37]: one two three four five oneplus20 a 0.469112 -0.282863 -1.509059 bar True 20.469112 b NaN 1.224234 7.823421 bar Fa...
1
2016-06-23T20:49:51Z
[ "python", "pandas" ]
An efficient way to get dictionary from dataframe
38,001,612
<p>I have a dataframe as follwos:</p> <pre><code> City Name 0 Seattle Alice 1 Seattle Bob 2 Portland Mallory 3 Portland Bob </code></pre> <p>What is an efficient way to get a dictionary for which the keys are cities and the values are names, i.e.:</p> <pre><co...
1
2016-06-23T20:50:08Z
38,001,714
<p><code>df.groupby('City')</code> is an iterator. You can use it in a dict comprehension to generate the desired dict:</p> <pre><code>In [84]: {city:set(grp['Name'].tolist()) for city, grp in df.groupby('City')} Out[84]: {'Portland': {'Bob', 'Mallory'}, 'Seattle': {'Alice', 'Bob'}} </code></pre> <hr> <p>To create a...
2
2016-06-23T20:56:40Z
[ "python", "pandas" ]
An efficient way to get dictionary from dataframe
38,001,612
<p>I have a dataframe as follwos:</p> <pre><code> City Name 0 Seattle Alice 1 Seattle Bob 2 Portland Mallory 3 Portland Bob </code></pre> <p>What is an efficient way to get a dictionary for which the keys are cities and the values are names, i.e.:</p> <pre><co...
1
2016-06-23T20:50:08Z
38,001,789
<p>You can use <code>GroupBy.apply</code> and <code>to_dict</code>:</p> <pre><code>df.groupby('City')['Name'].apply(set).to_dict() </code></pre>
4
2016-06-23T21:00:42Z
[ "python", "pandas" ]
An efficient way to get dictionary from dataframe
38,001,612
<p>I have a dataframe as follwos:</p> <pre><code> City Name 0 Seattle Alice 1 Seattle Bob 2 Portland Mallory 3 Portland Bob </code></pre> <p>What is an efficient way to get a dictionary for which the keys are cities and the values are names, i.e.:</p> <pre><co...
1
2016-06-23T20:50:08Z
38,001,828
<p>You could do</p> <pre><code>dict(df.groupby('City')['Name'].apply(list)) </code></pre>
1
2016-06-23T21:03:12Z
[ "python", "pandas" ]
How do I make python open a window?
38,001,684
<p>I'm trying to learn kivy and I have been running programs in terminal The problem is that whenever I run a python script, it will never open a window unless I run it from the terminal, and the terminal often does not run things that will run on other people's machines. I tried this tkinter code from another question...
0
2016-06-23T20:54:42Z
38,002,685
<p>on line 1: change the first letter of tkinter to capital T. from Tkinter import Tk, Frame, Both</p> <p>It will work fine. I tried the code on python 2.7</p>
-1
2016-06-23T22:06:32Z
[ "python", "tkinter", "terminal", "window", "kivy" ]
wsadmin - Jython script picking up PWD when its not specified
38,001,723
<p>TL;DR, Some how the Present Working Directory is being prepended to the EAR location.</p> <p>I am trying to run a Jython script for IBM WebSphere ND to do a batch install of some applications in a directory. The script takes two arguments, the path to the EARs, and then the Module Mappings. Going through this scri...
0
2016-06-23T20:57:21Z
38,002,678
<p>The signature is:</p> <pre><code>AdminApp.install(earFile,options) </code></pre> <p>So it's probably easier to try breaking it apart into two separate args like:</p> <pre><code>for app_name in dirs : install_app_loc = "%s/%s" % ( ear_location, app_name) install_app_opts = "'[ -MapModulesToServers [[ %s ]]...
1
2016-06-23T22:06:04Z
[ "python", "websphere", "ibm", "jython", "wsadmin" ]
Pandas: Replace column values to empty if not present in pre-defined list
38,001,754
<p>I have a list, <code>X</code>, that contains a set of legal values for a column. Say, I have column <code>A</code>. I want to replace (set to empty string) elements in <code>df['A']</code> if their value is not in X. How can I do that efficiently in Pandas?</p> <p>I know there is <code>isin()</code>, but that just ...
1
2016-06-23T20:59:20Z
38,001,809
<p>try this:</p> <pre><code>df.ix[~df.A.isin(X), 'A'] = '' </code></pre>
0
2016-06-23T21:02:19Z
[ "python", "pandas" ]
Pandas: Replace column values to empty if not present in pre-defined list
38,001,754
<p>I have a list, <code>X</code>, that contains a set of legal values for a column. Say, I have column <code>A</code>. I want to replace (set to empty string) elements in <code>df['A']</code> if their value is not in X. How can I do that efficiently in Pandas?</p> <p>I know there is <code>isin()</code>, but that just ...
1
2016-06-23T20:59:20Z
38,001,952
<p>You can do it with apply:</p> <pre><code>import pandas as pd x = ['a', 'b', 'c'] data = {'foo':['a', 'a', 'q', 'p']} df = pd.DataFrame.from_dict(data) df_new = df['foo'].apply(lambda i: i if i in x else '') </code></pre>
1
2016-06-23T21:12:02Z
[ "python", "pandas" ]
Python 3.5.1, How to ask for input 3 times in a function
38,001,895
<p>I have a basic main() function that starts by asking for input (miles information). I have to leave the input statement in the main function (required) and then proceed on to the milesToKM() function.<br> The goal is:</p> <p>1) If input is >=0, then print results and move to the next conversion (gallons)</p> <p>2...
-3
2016-06-23T21:08:02Z
38,002,048
<p>Could be simpler. Check for a ValueError for safer input.</p> <pre><code>_continue = True _nTries = 0 while _continue: miles = int(input("How many miles would you like converted to kilometers?\n ")) if miles &gt;= 0: # 1) If input is &gt;=0, then print results and move to the next conversion (gal...
0
2016-06-23T21:19:40Z
[ "python", "function", "if-statement", "python-3.5" ]
Python 3.5.1, How to ask for input 3 times in a function
38,001,895
<p>I have a basic main() function that starts by asking for input (miles information). I have to leave the input statement in the main function (required) and then proceed on to the milesToKM() function.<br> The goal is:</p> <p>1) If input is >=0, then print results and move to the next conversion (gallons)</p> <p>2...
-3
2016-06-23T21:08:02Z
38,002,103
<p>Change main() to this:</p> <pre><code>def main(): #Get miles to be converted to kilometers miles = miles = float(input('How many miles would you like converted to kilometers?\n')) # Number of tries numTries = 1 # Checks if miles is less than 0 and if less than 3 tries while numTries &lt; 3...
0
2016-06-23T21:23:27Z
[ "python", "function", "if-statement", "python-3.5" ]
PyQT5 QComboBox - get value of combobox
38,001,976
<p>I am still very new to Qt but I am developing a type of calculator and want to use a combobox to select a coefficient. I have had success creating a combobox with a liststore in pyGT but it appears pyQT is quite different. </p> <p>I am having a hard time wrapping my head around the data models and list models. Esse...
0
2016-06-23T21:13:39Z
38,002,980
<p>You can use <a href="http://doc.qt.io/qt-5/qcombobox.html#addItem" rel="nofollow">addItem</a> to add a name (text) with an associated value (data):</p> <pre><code> self.combo.addItem('Foo', 23) self.combo.addItem('Bar', 42) </code></pre> <p>A slot can be connected to the <a href="http://doc.qt.io/qt-5/qcomb...
1
2016-06-23T22:33:44Z
[ "python", "pyqt5", "qcombobox" ]
click detection using python (for maya 3D)
38,002,010
<p>I'm interesting about making a python tool for maya, and I need to detect a click input from user, basicaly to create a cube each time the user click with his left mouse button. But the problem is that I don't know how to do it.. I have good knowleges about python but not with that...</p> <p>If someone could help m...
0
2016-06-23T21:16:59Z
38,002,442
<p>You can rely on draggerContext and if you search enough there are result every where about that :) .. But here is minimal working example..</p> <pre><code>def createCubesForFun(): x, y, z = tuple(cmds.draggerContext( 'cubeFunCtx', query=1, dragPoint=1)) newBox = cmds.polyCube() cmds.setAttr("%s.t" % new...
1
2016-06-23T21:47:47Z
[ "python", "click", "detection", "maya", "autodesk" ]
click detection using python (for maya 3D)
38,002,010
<p>I'm interesting about making a python tool for maya, and I need to detect a click input from user, basicaly to create a cube each time the user click with his left mouse button. But the problem is that I don't know how to do it.. I have good knowleges about python but not with that...</p> <p>If someone could help m...
0
2016-06-23T21:16:59Z
38,009,341
<p>I think you can go with PyQt. Detecting some focus widget. And then on click, find whatever is selected</p> <pre><code>import sip import maya.cmds as cmds import maya.OpenMayaUI as apiUI from PyQt4 import QtGui, QtCore def getMayaWindow(): """Get the maya main window as a QMainWindow instance""" ptr = api...
0
2016-06-24T08:56:02Z
[ "python", "click", "detection", "maya", "autodesk" ]
Python read append more that one line to a list from a text file
38,002,047
<p>I have a text file of a network device configuration and I have my scrip loops through the lines of the file and here is what I'm looking for:</p> <p>I would like to have my script append to a list if it finds a specific word in the line. so far I'm only able to append one single line to my list...here is an exampl...
0
2016-06-23T21:19:35Z
38,002,224
<pre><code>my_file = open('configs.txt', 'r') license = [] for line in my_file: if line.startswith ("show license verbose"): license.append(line) for (i, line) in zip( range(1, 6), my_file ): license.append( line ) print( license ) </code></pre> <p>It's python3 code for python 2 you p...
2
2016-06-23T21:31:51Z
[ "python" ]
Python read append more that one line to a list from a text file
38,002,047
<p>I have a text file of a network device configuration and I have my scrip loops through the lines of the file and here is what I'm looking for:</p> <p>I would like to have my script append to a list if it finds a specific word in the line. so far I'm only able to append one single line to my list...here is an exampl...
0
2016-06-23T21:19:35Z
38,002,276
<p>You can use <a href="https://docs.python.org/2.7/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a> to fetch succeeding lines from the file object:</p> <pre><code>from itertools import islice my_file = open('configs.txt', 'r') license = [] for line in my_file: if line...
2
2016-06-23T21:36:01Z
[ "python" ]
Python read append more that one line to a list from a text file
38,002,047
<p>I have a text file of a network device configuration and I have my scrip loops through the lines of the file and here is what I'm looking for:</p> <p>I would like to have my script append to a list if it finds a specific word in the line. so far I'm only able to append one single line to my list...here is an exampl...
0
2016-06-23T21:19:35Z
38,002,466
<p>open returns a generator therefore you might be able to use next method:</p> <pre><code># you don't need this input as you already has generator source = ['a','b','c','d','e','f','g','h','i','j'] # turn it to generator g = (i for i in source) # create empty list lines = [] # put what you want inside for item in g: ...
1
2016-06-23T21:49:42Z
[ "python" ]
How to create list of matrices from three lists in python 2.7?
38,002,069
<p>I need to read a txt file in python 2.7 and create list of quadruples from the readings. The elements in the txt file are blocks of 4 lines. Thus every fourth line is a new element. Here is a sample element of the file:</p> <pre><code>0 3 53 -0.999909 -0.0135226 851.576 0.0135226 -0.999909 901.481 0 0 1 ... </co...
1
2016-06-23T21:21:37Z
38,002,135
<p>try this:</p> <p>file <code>a.data</code>:</p> <pre><code>0 3 53 -0.999909 -0.0135226 851.576 0.0135226 -0.999909 901.481 0 0 1 0 4 54 -0.999909 -0.0135226 851.576 0.0135226 -0.999909 901.481 1 1 2 </code></pre> <p>Code:</p> <pre><code>In [47]: fn = 'a.data' In [49]: np.loadtxt(fn) Out[49]: array([[ 0.0000...
1
2016-06-23T21:25:24Z
[ "python", "list", "matrix" ]
How to create list of matrices from three lists in python 2.7?
38,002,069
<p>I need to read a txt file in python 2.7 and create list of quadruples from the readings. The elements in the txt file are blocks of 4 lines. Thus every fourth line is a new element. Here is a sample element of the file:</p> <pre><code>0 3 53 -0.999909 -0.0135226 851.576 0.0135226 -0.999909 901.481 0 0 1 ... </co...
1
2016-06-23T21:21:37Z
38,002,137
<p>Your code seems very complicated. Why don't you some something like: </p> <pre><code>import numpy as np import re import operator # reading lines fil...
1
2016-06-23T21:25:35Z
[ "python", "list", "matrix" ]
How to create list of matrices from three lists in python 2.7?
38,002,069
<p>I need to read a txt file in python 2.7 and create list of quadruples from the readings. The elements in the txt file are blocks of 4 lines. Thus every fourth line is a new element. Here is a sample element of the file:</p> <pre><code>0 3 53 -0.999909 -0.0135226 851.576 0.0135226 -0.999909 901.481 0 0 1 ... </co...
1
2016-06-23T21:21:37Z
38,002,332
<p>Building off of @MaxU , I usually use <code>pandas</code> <code>DataFrames</code> if the columns and rows are labeled</p> <pre><code>import pandas as pd import numpy as np DF = pd.read_table("a.data", sep=" ") DF 0 1 2 0 0.000000 3.000000 53.000 1 -0.999909 -0.013523 851.576 2 0.01...
1
2016-06-23T21:40:17Z
[ "python", "list", "matrix" ]
How to create list of matrices from three lists in python 2.7?
38,002,069
<p>I need to read a txt file in python 2.7 and create list of quadruples from the readings. The elements in the txt file are blocks of 4 lines. Thus every fourth line is a new element. Here is a sample element of the file:</p> <pre><code>0 3 53 -0.999909 -0.0135226 851.576 0.0135226 -0.999909 901.481 0 0 1 ... </co...
1
2016-06-23T21:21:37Z
38,002,369
<p>I suppose this is what you are looking for.</p> <pre><code>import numpy as np import re import operator final_list = [] with open('data.txt','r') as f...
1
2016-06-23T21:42:45Z
[ "python", "list", "matrix" ]
Numpy: Conditional sum rows using an mask array
38,002,108
<p>Suppose I have array a and array mask,</p> <pre><code>Array a: [[1,1,2] [2,2,3] [3,5,2] [2,3,4]] Array mask: [[0,1] [1,1] [1,0] [0,0]] </code></pre> <p>How can I generate a array c with shape(2,3) in a numpy way like below:</p> <pre><code>Array c: [[5, 3], [7, 3], [5, 5]]) </code></pre> <p>where the 1st...
3
2016-06-23T21:23:36Z
38,002,265
<p>You can use the <code>numpy</code> dot product, which is essentially a matrix product, as documented <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html">here</a>:</p> <blockquote> <p>For 2-D arrays it is the matrix product</p> </blockquote> <pre><code>import numpy as np np.dot(a.transpos...
5
2016-06-23T21:34:53Z
[ "python", "arrays", "numpy" ]
Test python package installation from local files
38,002,125
<p>I would like to start testing the installation of individual python packages (tar.gz, egg, wheel) before uploading to pypi. That is, I'd like something like the following flow:</p> <p>Build like this:</p> <pre><code>cd /path/to/mypkg python setup.py sdist bdist_egg bdist_wheel </code></pre> <p>Then perhaps in an...
0
2016-06-23T21:24:22Z
38,016,958
<p>Downloading files from PyPI locally and installing them from "downloads" folder into a venv: <code> pip download -d downloads -r requirements-dev.txt virtualenv --clear -q -p python2.7 venv ./venv/bin/pip install -r requirements-dev.txt -f downloads --no-index -U </code></p> <p>If you can put all the packages you'd...
0
2016-06-24T15:27:03Z
[ "python", "pip", "setuptools", "easy-install", "pypi" ]
How do I vectorize the following loop in Numpy?
38,002,264
<pre><code>"""Some simulations to predict the future portfolio value based on past distribution. x is a numpy array that contains past returns.The interpolated_returns are the returns generated from the cdf of the past returns to simulate future returns. The portfolio starts with a value of 100. portfolio_v...
0
2016-06-23T21:34:52Z
38,003,488
<p>Forget about <code>np.nditer</code>. It does not improve the speed of iterations. Only use if you intend to go one and use the <code>C</code> version (via <code>cython</code>).</p> <p>I'm puzzled about that inner loop. What is it supposed to be doing special? Why the loop?</p> <p>In tests with simulated values ...
0
2016-06-23T23:32:35Z
[ "python", "loops", "numpy", "vectorization", "montecarlo" ]
How do I vectorize the following loop in Numpy?
38,002,264
<pre><code>"""Some simulations to predict the future portfolio value based on past distribution. x is a numpy array that contains past returns.The interpolated_returns are the returns generated from the cdf of the past returns to simulate future returns. The portfolio starts with a value of 100. portfolio_v...
0
2016-06-23T21:34:52Z
38,018,313
<p>I guess the easiest way to figure out how you can vectorize your stuff would be to look at the equations that govern your evolution and see how your portfolio actually iterates, finding patterns that could be vectorized instead of trying to vectorize the code you already have. You would have noticed that the cumprod...
0
2016-06-24T16:40:46Z
[ "python", "loops", "numpy", "vectorization", "montecarlo" ]
Why XORing two hex strings produce an output in the following format: '\x02\x07\x01P\x00\x07
38,002,285
<p>The ultimate purpose of this program is to get the words Eve and Bob back in plain text from XORed hex strings. So first I got Eve and bob in hex, then XORed them together, was hoping to then see the result in hex.The problem is when I XOR the hex strings for Bob and Eve I get this notation, '\x02\x07\x01P\x00\x07 ...
0
2016-06-23T21:36:25Z
38,002,561
<p>this is basic xor_encryption... in effect b works like an encryption/decryption key</p> <pre><code>import itertools name1 = "eve online" name2 = "bob" xor_encrypted = "".join(chr(ord(a)^ord(b)) for a,b in zip(name1,itertools.cycle(name2))) print repr(xor_encrypted) # 3 characters will look something like '\x07\x1...
1
2016-06-23T21:56:36Z
[ "python", "xor" ]
Converting a string with list of dicts to pandas df
38,002,329
<p>I am reading a string from a file which looks like:</p> <p><code>"[{key1:val1,key2:val2},{key1:val1,key2:val2}.....}]" </code></p> <p>How do I convert this string into a pandas dataframe with key1 and key2 as two columns? </p> <p>I can think of string manipulations like first removing '[' and ']' characters and t...
1
2016-06-23T21:40:03Z
38,002,356
<p>try this:</p> <pre><code>In [73]: pd.DataFrame.from_dict([{'key1':'val1','key2':'val2'},{'key1':'val1','key2':'val2'}]) Out[73]: key1 key2 0 val1 val2 1 val1 val2 </code></pre> <p>or from the JSON string:</p> <pre><code>import json In [81]: s Out[81]: '[{"key1":"val1","key2":"val2"},{"key1":"val1","key2"...
1
2016-06-23T21:42:04Z
[ "python", "pandas" ]
Iterate over a badly formed set with python
38,002,367
<p>I've got a batch of PDF documents with the following metadata property: Language: <code>set([NL,DE,FR,EN])</code></p> <p>I want to iterate these values but it outputs each char like:</p> <pre><code>s e t ( [ ... E N , ] ) </code></pre> <p>My guess is that the set is missing quotes. <code>set(["NL","FR","DE","EN"]...
0
2016-06-23T21:42:38Z
38,002,419
<pre><code>for lang in re.findall("[A-Z]{2}",metadata_text): print lang </code></pre> <p>I guess maybe?</p> <p>alternatively</p> <pre><code>for lang in metadata_text[5:-2].split(","): print lang </code></pre>
1
2016-06-23T21:46:26Z
[ "python", "set", "iteration" ]
How to distribute data in 2D map grid and take average
38,002,377
<p>I am trying to do a map in 2D coordinates with color defined by a third variable. I already defined the grids by the following command:</p> <pre><code>b_step = np.linspace(-75,90,12) l_step = np.linspace(0,360,25) grid = [(x,y) for x in b_step for y in l_step] </code></pre> <p>There are three variables in my data ...
0
2016-06-23T21:43:01Z
38,259,174
<p>ROOT TH2F is the best way to handle it efficiently. If you create two TH2F histogram, one tracks the data, the other one tracks total number contributed, then you can calculate the mean value in each grid point. The python code for this is below:</p> <pre><code>from ROOT import TH2F, gStyle, TCanvas ##### if you w...
0
2016-07-08T05:00:39Z
[ "python", "dictionary", "grid", "coordinates" ]
Align DataFrames in pandas so that data matches in rows
38,002,423
<p>I want to align my data</p> <p>I currently have it like this:</p> <pre><code>Yan TNSeq Kato Eco-GeneOrth Essential accA accA accA accA accA accB accB accB accB accB accC accC accC accC accC accD accD accD accD ...
-1
2016-06-23T21:46:38Z
38,002,491
<p><strong>UPDATE:</strong></p> <pre><code>In [120]: df[df.apply(lambda x: x['Essential'] == x, axis=1)] Out[120]: Yan TNSeq Kato Eco-GeneOrth Essential 0 accA accA accA accA accA 1 accB accB accB accB accB 2 accC accC accC accC accC 3 accD accD accD accD...
1
2016-06-23T21:51:53Z
[ "python", "pandas", "alignment" ]
Align DataFrames in pandas so that data matches in rows
38,002,423
<p>I want to align my data</p> <p>I currently have it like this:</p> <pre><code>Yan TNSeq Kato Eco-GeneOrth Essential accA accA accA accA accA accB accB accB accB accB accC accC accC accC accC accD accD accD accD ...
-1
2016-06-23T21:46:38Z
38,002,953
<p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow"><code>eq</code></a> and pass your column with arg <code>axis=0</code> to create a boolean mask of your entire df against that column:</p> <pre><code>In [49]: df[df.eq(df['Essential'],axis=0)] Out[49]: ...
0
2016-06-23T22:30:28Z
[ "python", "pandas", "alignment" ]
Python: If header exists, use as variable
38,002,657
<p>I am working with a HDUList with many columns (over 1000). The columns are related to characteristics of galaxies in clusters fit by an external code. The columns should end in 'ser' or 'dev'. However, some columns are too long and the names get cut off (eg: LOGRE_F3mF2_F850LPse or eLOGRE_F3mF2_F850LPs)</p> <p>I am...
0
2016-06-23T22:04:06Z
38,002,715
<p>Try using <code>hasattr(object,property)</code> to detect if the key actually exists. Otherwise try restructuring your dictionaries so that you don't have weird names like that.</p>
0
2016-06-23T22:09:12Z
[ "python" ]
Python: If header exists, use as variable
38,002,657
<p>I am working with a HDUList with many columns (over 1000). The columns are related to characteristics of galaxies in clusters fit by an external code. The columns should end in 'ser' or 'dev'. However, some columns are too long and the names get cut off (eg: LOGRE_F3mF2_F850LPse or eLOGRE_F3mF2_F850LPs)</p> <p>I am...
0
2016-06-23T22:04:06Z
38,003,265
<p>It looks like names are cutoff at 20 characters. If that's the case, you can try something along the lines of:</p> <pre><code>key = root + '_avg_f850lpser' key = key[:20] </code></pre> <p>That ensures your <code>key</code> is always 20 characters or less, and trimmed at the right end of the string (since that whe...
0
2016-06-23T23:03:35Z
[ "python" ]
viewing nested JSON data into a pandas dataframe
38,002,663
<p>I have now added the current problem onto GitHib. Please find the URL for the repo. I have included a Jupyter notebook that also explains the problem. Thanks guys.</p> <p><a href="https://github.com/simongraham/dataExplore.git" rel="nofollow">https://github.com/simongraham/dataExplore.git</a></p> <hr> <p>I am cur...
5
2016-06-23T22:04:35Z
38,002,810
<p><strong>UPDATE:</strong> this should work for your <code>kaidoData.json</code> file: </p> <pre><code>df = (pd.io .json .json_normalize(data[0]['ionPortions'], 'nutritionNutrients', ['vcNutritionId','vcUserId','vcPortionId','vcPortionName','vcPortionSize', 'dtCreatedDate','dt...
4
2016-06-23T22:18:49Z
[ "python", "json", "pandas", "dataframe" ]
Parsing multiple child elements in python
38,002,686
<p>I'm attempting to parse XML and store the element values into an object. The issue I'm running into is that the child elements are repeated so I'm not quite sure the best practice to iterate over it and store the value.</p> <p>What I was considering doing is looking at a child element and adding a counter. The coun...
0
2016-06-23T22:06:34Z
38,004,409
<p>There are to main ways to parse XML data:</p> <ol> <li><p>DOM parsers. </p> <p>They load full xml file into memory and build DOM (Document Object Model). It's allow programmer to use many nice technologys to navigate in document or retrieve data from it (i.e. <a href="http://www.w3schools.com/xml/xml_xpath.asp" re...
0
2016-06-24T01:37:51Z
[ "python", "xml", "python-3.x" ]
How to calculate taylor series and Lewis Carrol divisbilty test in python 3.5 without using the math module
38,002,712
<p>Like the title says, I need to find Taylor series as well as program the divisibility test without using the math module in Python 3.5. I'd do the math on a piece of paper but I was actually never taught either one of these things in school so I honestly have absolutely no clue how to the hell do them on paper. I ha...
0
2016-06-23T22:09:04Z
38,004,852
<p>The calculation in the <code>for</code> loop in your <code>question3()</code> function has a number of errors.</p> <ul> <li>In <code>(-1**n)</code>, the <code>**</code> has higher precedence than <code>-</code>. The correct expression is <code>((-1)**n)</code></li> <li>In the divisor, <code>(x*(2*n)+1)</code> uses ...
0
2016-06-24T02:43:18Z
[ "python", "python-3.x", "math", "taylor-series" ]
How do I set a function parameter as a string in python?
38,002,719
<pre><code>def count(string,letter): count=0 for each in string: if each==letter: count=count+1 print count </code></pre> <p>is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?</p>
-2
2016-06-23T22:09:47Z
38,002,755
<pre><code>def count(string,letter): if not isinstance(string,str): string = str(string) count=0 for each in string: if each==letter: count=count+1 print count </code></pre>
-1
2016-06-23T22:13:22Z
[ "python", "string", "parameters" ]
How do I set a function parameter as a string in python?
38,002,719
<pre><code>def count(string,letter): count=0 for each in string: if each==letter: count=count+1 print count </code></pre> <p>is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?</p>
-2
2016-06-23T22:09:47Z
38,002,762
<p>I think you're asking if you can call the function like this:</p> <pre><code>count(this is my string, i) # 3 </code></pre> <p>instead of like this:</p> <pre><code>count('this is my string', 'i') # 3 </code></pre> <p>And the answer is that <strong>there is no way to do this</strong>. The arguments are parsed w...
2
2016-06-23T22:13:58Z
[ "python", "string", "parameters" ]
How do I set a function parameter as a string in python?
38,002,719
<pre><code>def count(string,letter): count=0 for each in string: if each==letter: count=count+1 print count </code></pre> <p>is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?</p>
-2
2016-06-23T22:09:47Z
38,002,796
<p>Another option: You can use <code>input()</code></p> <pre><code> def count(letter): string=input() #&lt;- user can type string into command line w/o quote do_stuff return bacon </code></pre> <p>But as far as passing a string as arguments w/o quotes, you can't do that. They'll be interpreted...
1
2016-06-23T22:17:35Z
[ "python", "string", "parameters" ]
How do I set a function parameter as a string in python?
38,002,719
<pre><code>def count(string,letter): count=0 for each in string: if each==letter: count=count+1 print count </code></pre> <p>is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?</p>
-2
2016-06-23T22:09:47Z
38,002,823
<blockquote> <p>is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?</p> </blockquote> <p>You must add the quotations so that the interpreter knows the variable is of type String so that the internal code of the method knows how to handl...
0
2016-06-23T22:19:45Z
[ "python", "string", "parameters" ]
How do I set a function parameter as a string in python?
38,002,719
<pre><code>def count(string,letter): count=0 for each in string: if each==letter: count=count+1 print count </code></pre> <p>is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?</p>
-2
2016-06-23T22:09:47Z
38,003,692
<p>This is a complete version to use <strong><em>input()</em></strong></p> <pre><code>def count(letter): string = input() # &lt;- user can type string into command line and end by 'Enter' count = 0 for each in string: if each == letter: count += 1 print (count) </code></pre> <h3>Te...
0
2016-06-23T23:56:07Z
[ "python", "string", "parameters" ]
Writing Latex onto Axis
38,002,752
<pre><code>plt.xlabel(r'$\rm log \: M_*$') plt.ylabel(r’$\rm log \: M_{\bullet}$') </code></pre> <p>The x axis is able to be printed correctly. However, the y axis has an error. What's the cause for that error?</p>
0
2016-06-23T22:12:59Z
38,007,552
<p>If I take the Arial's answer in order to give a general solution, you have a wrong typo in the y line.</p> <p>You write : </p> <pre><code>plt.ylabel(r’$\rm log \: M_{\bullet}$') </code></pre> <p>But, after the r, you made <code>’</code> instead of <code>'</code></p> <p>So, you just have to write : </p> <pre...
2
2016-06-24T07:08:51Z
[ "python", "matplotlib", "latex" ]
double/float type precision in Python
38,002,875
<p>Using Python 2.7 on OSX, the output is different from <code>x</code>, wondering if there is a way to control Python double/float more precision?</p> <pre><code>x=0.123456789123456789 print x # output 0.123456789123 </code></pre> <p><strong>Update 1,</strong></p> <p>Weird output when using Decimal,</p> <pre><cod...
0
2016-06-23T22:24:52Z
38,003,005
<p>You can do it with Decimal - once you have the number you can play with precision</p> <pre><code>import decimal initial_x='0.123456789123456789' x=decimal.Decimal(initial_x) </code></pre>
2
2016-06-23T22:35:14Z
[ "python", "osx", "python-2.7" ]
Adding rows with duplicate indexes in pandas
38,002,962
<p>I have a set of "unidirectional" airline data, somewhat like below (numbers are not sequential or the same for every row in actual data):</p> <pre><code>origin dest a b c d e f BOS JFK 1 2 3 4 5 6 DCA 1 2 3 4 5 6 JFK BOS 1 2 3 4 5 6 DCA 1 2 3 4 5 6 DCA...
1
2016-06-23T22:31:28Z
38,003,013
<p>is that what you want?</p> <pre><code>In [133]: df.groupby('dest').sum().reset_index() Out[133]: dest a b c d e f 0 BOS 2 4 6 8 10 12 1 DCA 2 4 6 8 10 12 2 JFK 2 4 6 8 10 12 </code></pre>
1
2016-06-23T22:35:42Z
[ "python", "pandas", "pivot-table" ]
Adding rows with duplicate indexes in pandas
38,002,962
<p>I have a set of "unidirectional" airline data, somewhat like below (numbers are not sequential or the same for every row in actual data):</p> <pre><code>origin dest a b c d e f BOS JFK 1 2 3 4 5 6 DCA 1 2 3 4 5 6 JFK BOS 1 2 3 4 5 6 DCA 1 2 3 4 5 6 DCA...
1
2016-06-23T22:31:28Z
38,003,428
<p>You can sort your <code>origin</code> and <code>dest</code> columns by row firstly and then do a <code>groupby</code>, <code>sum</code> since it looks like that your result doesn't care about the order of the <code>origin</code> and <code>dest</code>:</p> <pre><code>import pandas as pd df.reset_index(["origin", "d...
0
2016-06-23T23:24:56Z
[ "python", "pandas", "pivot-table" ]
python - how to write empty tree node as empty string to xml file
38,003,030
<p>I want to remove elements of a certain tag value and then write out the <code>.xml</code> file WITHOUT any tags for those deleted elements; is my only option to create a new tree?</p> <p>There are two options to remove/delete an element:</p> <blockquote> <p><a href="https://docs.python.org/3/library/xml.etree.el...
0
2016-06-23T22:37:43Z
38,003,299
<pre><code>import lxml.etree as et xml = et.parse("test.xml") for node in xml.xpath("//neighbor"): node.getparent().remove(node) xml.write("out.xml",encoding="utf-8",xml_declaration=True) </code></pre> <p>Using elementTree, we need to find the <em><code>parents of the neighbor nodes</code></em> then find the...
2
2016-06-23T23:08:37Z
[ "python", "xml" ]
python - how to write empty tree node as empty string to xml file
38,003,030
<p>I want to remove elements of a certain tag value and then write out the <code>.xml</code> file WITHOUT any tags for those deleted elements; is my only option to create a new tree?</p> <p>There are two options to remove/delete an element:</p> <blockquote> <p><a href="https://docs.python.org/3/library/xml.etree.el...
0
2016-06-23T22:37:43Z
38,004,715
<p>Whenever modifying XML documents is needed, consider also <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the special-purpose language part of the XSL family which includes XPath. XSLT is designed specifically to transform XML files. Pythoners are not quick to recommend it but it avoids the need of ...
0
2016-06-24T02:24:06Z
[ "python", "xml" ]
python - how to write empty tree node as empty string to xml file
38,003,030
<p>I want to remove elements of a certain tag value and then write out the <code>.xml</code> file WITHOUT any tags for those deleted elements; is my only option to create a new tree?</p> <p>There are two options to remove/delete an element:</p> <blockquote> <p><a href="https://docs.python.org/3/library/xml.etree.el...
0
2016-06-23T22:37:43Z
38,005,505
<p>The trick here is to find the parent (the country node), and delete the neighbor from there. In this example, I am using ElementTree because I am somewhat familiar with it:</p> <pre><code>import xml.etree.ElementTree as ET if __name__ == '__main__': with open('debug.log') as f: doc = ET.parse(f) ...
0
2016-06-24T04:15:42Z
[ "python", "xml" ]