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 auto wrap function call in try / catch?
39,905,390
<p>I have a lot of getter functions like this:</p> <pre><code>get_property_a(default=None): try: self.data.get("field_1")[0].get("a") except Exception as e: return default get_property_b(default=None): try: self.data.get("field_2")[0].get("b") except Exception as e: return default ... </c...
2
2016-10-06T20:50:21Z
39,905,474
<p>You <em>can</em> do this by writing your own decorator:</p> <pre><code>import functools def silent_exec(default=None): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs): except Exception: ...
5
2016-10-06T20:55:32Z
[ "python" ]
Applying lambda function to datetime
39,905,432
<p>I am using the following code to find clusters with difference &lt;=1 in a list </p> <pre><code>from itertools import groupby from operator import itemgetter data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] for k, g in groupby(enumerate(data), lambda (i, x): (i-x)): print map(itemgetter(1), g) </code></pre>...
2
2016-10-06T20:53:15Z
39,906,009
<p>If you want to get all subsequences of items such that each item is an hour later than the previous one (not clusters of items that each are within an hour from eachother), you need to iterate over pairs <code>(data[i-1], data[i])</code>. Currently, you are just iterating over <code>(i, data[i])</code> which raises ...
1
2016-10-06T21:37:50Z
[ "python", "lambda" ]
No Pages getting crawled - scrapy
39,905,469
<p>The following spider code in Scrapy was developed to be used to crawl pages from americanas website:</p> <pre><code> # -*- coding: utf-8 -*- import scrapy import urllib import re import webscrap.items import time from urlparse import urljoin from HTMLParser import HTMLParser clas...
0
2016-10-06T20:55:21Z
39,906,320
<p>Your <em>xpath</em> is not correct and there is only one <code>item-menu</code> per page, i have removed the items logic as I don't know what they are. This will get you all the links from the <em>item-menu</em> ul, you can add back in whatever logic you like:</p> <pre><code> def parse(self, response): for url ...
0
2016-10-06T22:04:12Z
[ "python", "web-scraping", "scrapy", "web-crawler" ]
Python: How to piggyback on existing tests when developing third party packages
39,905,532
<p>My <a href="https://github.com/tomchristie/django-rest-framework/pull/4540" rel="nofollow">PR</a> on django-rest-framework to add in a "hybrid pagination" got rejected reason being better to be in a 3rd party package. </p> <p>So I went ahead and created the package structure but got stuck in creating the test, if y...
0
2016-10-06T20:59:36Z
39,913,118
<p>Correct that you won't be able to include the tests from the <code>pip install</code> package. You'll need to clone whichever bits of test case you want to replicate locally.</p> <blockquote> <p>I tried copying the particular test_pagination.py file but getting a lot of errors.</p> </blockquote> <p>I'd suggest s...
0
2016-10-07T08:45:44Z
[ "python", "django" ]
How do I handle form data in aiohttp responses
39,905,588
<p>I'm looking to get the multipart form data and turn it into a dictionary. Easy enough for json, but this seems to be a bit different. </p> <p>Current code:</p> <pre><code>app = web.Application() async def deploy(request): # retrieve multipart form data or # x-www-form-urlencoded data # convert to a di...
1
2016-10-06T21:03:38Z
39,906,151
<p>You can use the <code>request.post()</code> method.</p> <pre><code>app = web.Application() async def deploy(request): # retrieve multipart form data or # x-www-form-urlencoded data data = await request.post() print(data) text = "Hello" return web.Response(text=text) app.router.add_post('/'...
2
2016-10-06T21:50:21Z
[ "python", "multipartform-data", "python-3.5", "aiohttp" ]
I can't get QueryAABB to work in PyBox2D. What am I doing wrong?
39,905,657
<p>I'm trying to detect if the mouse pointer is over a body so i can drag it but i'm getting the error below. I don't know if it's me or a bug in pybox2d but i've been at it for hours and the docs are ancient. </p> <pre><code>&gt;&gt;&gt; from Box2D.b2 import * &gt;&gt;&gt; w = world() &gt;&gt;&gt; my_body = w.CreateD...
0
2016-10-06T21:08:22Z
39,906,397
<p>silly me i figured it out. right there in the 'ancient' docs.</p> <p><a href="https://github.com/pybox2d/pybox2d/wiki/manual#aabb-queries" rel="nofollow">https://github.com/pybox2d/pybox2d/wiki/manual#aabb-queries</a></p>
0
2016-10-06T22:11:12Z
[ "python", "python-3.x", "box2d" ]
Appending output of a for loop for Python to a csv file
39,905,678
<p>I have a folder with .txt files in it. My code will find the line count and character count in each of these files and save the output for each file in a single csv file in a different directory. The csv file is <em>Linecount.csv</em>. For some reason the output to csv file is repeating for character and linecount f...
0
2016-10-06T21:10:01Z
39,906,978
<p>Please check your indentation.</p> <p>You are looping through each file using <code>for file in glob.glob("*.txt"):</code> </p> <p>This stores the last result in <code>a</code>,<code>b</code>, and <code>c</code>. It doesn't appear to write it anywhere.</p> <p>You then loop through each item using <code>for a in ...
0
2016-10-06T23:08:51Z
[ "python", "csv" ]
Closed lines in matplotlib contour plots
39,905,702
<p>When looking closely at contour plots made with matplotlib, I noticed that smaller contours have inaccurate endpoints which do not close perfectly in PDF figures. Consider the minimal example:</p> <pre><code>plt.gca().set_aspect('equal') x,y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100)) r = x*x + y*y...
3
2016-10-06T21:12:00Z
39,906,056
<p>So I just did the same thing, but got closed contours (see images). Did you check for any updates on the package?</p> <pre><code>import matplotlib.pyplot as plt import numpy as np plt.gca().set_aspect('equal') x,y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100)) r = x*x + y*y plt.contour(np.log(r)) plt....
0
2016-10-06T21:43:49Z
[ "python", "pdf", "matplotlib", "contour" ]
Closed lines in matplotlib contour plots
39,905,702
<p>When looking closely at contour plots made with matplotlib, I noticed that smaller contours have inaccurate endpoints which do not close perfectly in PDF figures. Consider the minimal example:</p> <pre><code>plt.gca().set_aspect('equal') x,y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100)) r = x*x + y*y...
3
2016-10-06T21:12:00Z
39,912,344
<p>Disclaimer: this is more an <strong>explanation + hack</strong> than a real answer.</p> <p>I believe that there is a fundamental problem the way matplotlib makes contour plots. Essentially, all contours are collections of lines (<code>LineCollection</code>), while they should be collection of possibly closed lines...
3
2016-10-07T08:01:22Z
[ "python", "pdf", "matplotlib", "contour" ]
How to execute code on save in Django User model?
39,905,713
<p>I would like to run some code specifically when the is_active field is changed for a Django User, similar to how the save method works for other models:</p> <pre><code>class Foo(models.Model): ... def save(self, *args, **kwargs): if self.pk is not None: orig = Foo.objects.get(pk=self.pk)...
1
2016-10-06T21:13:02Z
39,905,768
<p>You're looking for this <a href="https://docs.djangoproject.com/en/1.10/ref/signals/#django.db.models.signals.pre_save" rel="nofollow">Signal</a></p> <pre><code>from django.db.models.signals import pre_save from django.contrib.auth.models import User def do_your_thing(sender, instance, **kwargs): # Do somethin...
2
2016-10-06T21:17:21Z
[ "python", "django" ]
Out of bounds nanosecond timestamp
39,905,822
<p>I have a variable ['date_hiring'] in Googlespeedsheet in format like</p> <pre><code>16.01.2016 </code></pre> <p>I import it in Python, the variable has an object type. I try to convert to datetime </p> <pre><code>from datetime import datetime data['date_hiring'] = pd.to_datetime(data['date_hiring']) </code></pre>...
2
2016-10-06T21:22:15Z
39,905,987
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">documentation</a>, the <em>dayfirst</em> field defaults to false:</p> <blockquote> <p>dayfirst : boolean, default False</p> </blockquote> <p>So it must have decided that there was a malformed d...
2
2016-10-06T21:36:01Z
[ "python", "datetime", "pandas" ]
Python Program Expecting a Return
39,905,916
<p>I'm having trouble getting this program I'm writing to execute correctly. I'm trying to build a table, within a separate class. The method within the class seems to require a return, in order for the table to show and I'm trying to figure out why. If I use "return" or "return None" the table will not show when I run...
1
2016-10-06T21:29:46Z
39,906,819
<p><code>__init__</code> as constructor can't return value. </p> <hr> <p>Every <code>Widget</code> needs a parent - so <code>QTableWidget</code> needs too.</p> <pre><code> table = QTableWidget(parent) </code></pre> <p>Because you send <code>MainWindow</code> to your class as parent so now <code>MainWindow</code>...
0
2016-10-06T22:51:41Z
[ "python", "python-3.x", "pyqt4" ]
Python Program Expecting a Return
39,905,916
<p>I'm having trouble getting this program I'm writing to execute correctly. I'm trying to build a table, within a separate class. The method within the class seems to require a return, in order for the table to show and I'm trying to figure out why. If I use "return" or "return None" the table will not show when I run...
1
2016-10-06T21:29:46Z
39,907,189
<p>You're not keeping a reference to the table, so it gets garbage-collected when <code>__init__</code> returns. You can fix this by putting the table in a layout, like this:</p> <pre><code>class TableWidget(QWidget): def __init__(self, parent): super(TableWidget, self).__init__(parent) table = Q...
0
2016-10-06T23:33:07Z
[ "python", "python-3.x", "pyqt4" ]
How to sort a list of dictionaries by the value of a key and by the value of a value of a key?
39,905,925
<pre><code>{ "states": [ { "timestamp": { "double": 968628281.0 }, "sensorSerialNumber": 13020235 }, { "timestamp": { "double": 964069109.0 }, "sensorSerialNumber": 13020203 }, ...
1
2016-10-06T21:30:38Z
39,905,948
<p><code>key</code> can be any callable, it is passed each element in the <code>list_to_be_sorted</code> in turn. So a <code>lambda</code> would fit here:</p> <pre><code>newlist = sorted( data['states'], key=lambda i: (i['sensorSerialNumber'], i['timestamp']['double'])) </code></pre> <p>So the lambda returns ...
1
2016-10-06T21:32:52Z
[ "python", "list", "sorting", "dictionary" ]
Dataframe head not shown in PyCharm
39,905,931
<p>I have the following code in PyCharm</p> <pre><code>import pandas as pd import numpy as np import matplotlib as plt df = pd.read_csv("c:/temp/datafile.txt", sep='\t') df.head(10) </code></pre> <p>I get the following output:</p> <pre><code>Process finished with exit code 0 </code></pre> <p>I am supposed to ge...
0
2016-10-06T21:31:28Z
39,906,582
<p><code>PyCharm</code> is not <code>Python Shell</code> which automatically prints all results. You have to use <code>print()</code> to display anything.</p> <pre><code>print(df.head(10)) </code></pre>
6
2016-10-06T22:28:07Z
[ "python", "pandas", "dataframe", "pycharm" ]
A query that works in MySQL terminal fails when executed via PyMySQL
39,905,956
<p>I've provided three sample SQL queries below. Each of these works fine, returning the expected table output when executed directly from terminal in the <code>MySQL [db] &gt;</code> environment. </p> <p>Each other these queries is saved in a python doc called <code>queries.py</code>. The second two queries work fine...
-1
2016-10-06T21:33:24Z
39,906,259
<p>I think you need <em>four</em> backslashes in the Python string literal to represent <em>two</em> backslash characters needed by MySQL, to represent a backslash character.</p> <p>MySQL needs <em>two</em> backslashes in a string literal to represent a backslash character. The SQL text you have works in MySQL because...
1
2016-10-06T21:59:46Z
[ "python", "mysql", "python-3.x", "pymysql" ]
XML attribute parsing with python and ElementTree
39,905,988
<p>folks! I'm trying to parse some weird formed XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;analytics&gt; &lt;standard1&gt; ... &lt;attributes&gt; &lt;attribute name="agentname" value="userx userx" /&gt; &lt;attribute name="agentpk" value="5" /&gt; &lt;attribute nam...
0
2016-10-06T21:36:08Z
39,906,156
<p>You can use a simple <em>XPath expression</em> to filter <code>attribute</code> element by the value of <code>name</code> attribute. Sample working code:</p> <pre><code>import xml.etree.ElementTree as ET data = """&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;analytics&gt; &lt;standard&gt; &lt;attribute...
1
2016-10-06T21:50:59Z
[ "python", "xml", "elementtree" ]
Python help displaying strings
39,906,046
<pre><code>def main(): name = input("Enter your name, eg Zelle: ") name = name.lower() output = [] for character in name: number = ord(character) - 96 output.append(number) print(output) main() </code></pre> <p>This is what I have so far but I need to make this program run each o...
0
2016-10-06T21:42:42Z
39,906,171
<p>here you go:</p> <pre><code>def main(): name = input("Enter your name, eg Zelle: ") name = name.lower() output = [] name_value = 0 for character in name: number = ord(character) - 96 output.append((character,number)) print("Letter {} value is {}".format(character, number)...
0
2016-10-06T21:51:57Z
[ "python" ]
Python help displaying strings
39,906,046
<pre><code>def main(): name = input("Enter your name, eg Zelle: ") name = name.lower() output = [] for character in name: number = ord(character) - 96 output.append(number) print(output) main() </code></pre> <p>This is what I have so far but I need to make this program run each o...
0
2016-10-06T21:42:42Z
39,906,292
<pre><code>def main(): name = input("Enter your name, eg Zelle: ") name = name.lower() output = [] total = 0 for character in name: number = ord(character) - 96 total += number print("Letter {0} value is {1}".format(character, number)) print("The numeric value of the name {0} is {1}".format(name, total)) ...
0
2016-10-06T22:02:00Z
[ "python" ]
Python help displaying strings
39,906,046
<pre><code>def main(): name = input("Enter your name, eg Zelle: ") name = name.lower() output = [] for character in name: number = ord(character) - 96 output.append(number) print(output) main() </code></pre> <p>This is what I have so far but I need to make this program run each o...
0
2016-10-06T21:42:42Z
39,906,352
<pre><code>def main(): name = input("Enter your name, eg Zelle:").lower() char_values = [ord(char) for char in name] total = sum(char_values) for value in char_values: print("Letter {} value is {}".format(chr(value), value)) print("The numeric value of the name {} is {}".format(name, total))...
0
2016-10-06T22:06:50Z
[ "python" ]
Pattern matching python - return multiple items from input in one go
39,906,048
<p>Input: </p> <pre><code>A-&gt;(B, 1), (C, 2), (AKSDFSDF, 1231231) ... </code></pre> <p>Expected output:</p> <pre><code>[('A', 1, 2, 1231231)] </code></pre> <p>Cannot seem to get it to work. My code:</p> <pre><code>import re pattern = r"([a-zA-z]+)-&gt;(.*)" r = re.compile(pattern) print r.findall("A-&gt;(B, 1)...
0
2016-10-06T21:42:59Z
39,906,102
<p>You can use a <em>positive lookahead assertion</em> to pick words starting with a word boundary <code>\b</code> and followed by <code>-</code> or <code>)</code>:</p> <pre><code>import re s = 'A-&gt;(B, 1), (C, 2), (AKSDFSDF, 1231231)' pattern = re.compile(r'\b\w+(?=-|\))') print pattern.findall(s) #['A', '1', '2',...
2
2016-10-06T21:47:21Z
[ "python", "regex", "pattern-matching" ]
tweepy.Cursor returns the same users over and over
39,906,052
<p>I am trying to get all the search results in a list.</p> <p>Here is the code:</p> <pre><code>cursor = tweepy.Cursor(api.search_users,"foo") count = 0 for u in cursor.items(30): count += 1 print count, u.id_str print count </code></pre> <p>Alas, item 1 is the same as 21, 2 is the same as 22 &amp;c:</p> <p...
1
2016-10-06T21:43:26Z
40,032,109
<p>As per the <a href="http://docs.tweepy.org/en/v3.5.0/api.html#API.search_users" rel="nofollow">tweepy documentation</a>, you should not pass a number greater than 20. You're passing 30, that's why you get repeated ids after 20 id entries.</p> <p>I hacked up a bit and came up with the below code which will get all t...
1
2016-10-13T22:32:45Z
[ "python", "twitter", "tweepy" ]
list of list but specific representations in python
39,906,109
<p>I don't have much experience about lists in Python. So basically, I want to create N list inside one huge list. Reading from a file that looks like this:</p> <pre><code>Fail = h yes Sucess = h no </code></pre> <p>This is an example of 2 lines in the file, and the file contains N line, thus I want to create a list ...
0
2016-10-06T21:47:30Z
39,906,229
<p>You can't use string functions to create tuple - <code>("h", "yes")</code></p> <p>You need</p> <pre><code>m = ( l_rule[2], ) m = ( l_rule[2], l_rule[3] ) </code></pre> <hr> <p><strong>EDIT:</strong> I found you have to clear <code>G_list</code> before you add new elements</p> <pre><code> G_list = [] G_list...
1
2016-10-06T21:57:27Z
[ "python", "list" ]
list of list but specific representations in python
39,906,109
<p>I don't have much experience about lists in Python. So basically, I want to create N list inside one huge list. Reading from a file that looks like this:</p> <pre><code>Fail = h yes Sucess = h no </code></pre> <p>This is an example of 2 lines in the file, and the file contains N line, thus I want to create a list ...
0
2016-10-06T21:47:30Z
39,906,232
<p>Split each line and unpack it. Then you can check whether the necessary last element was found, and create the appropriate tuple. Append the result to your list of results.</p> <pre><code>with open('file.txt') as f: result = [] for line in f: a,b,c,*d = line.split() if d: tup = c...
2
2016-10-06T21:57:40Z
[ "python", "list" ]
list of list but specific representations in python
39,906,109
<p>I don't have much experience about lists in Python. So basically, I want to create N list inside one huge list. Reading from a file that looks like this:</p> <pre><code>Fail = h yes Sucess = h no </code></pre> <p>This is an example of 2 lines in the file, and the file contains N line, thus I want to create a list ...
0
2016-10-06T21:47:30Z
39,906,244
<p>Try this:</p> <pre><code>def format_data(line): lst = line.split() return lst[0], tuple(lst[2:]) with open('file.txt') as f: for l in f: G_list.append(format_data(l)) listoflist.append(G_list) </code></pre> <p>or you can do a one_liner inside your <code>with</code> statement.</p> <pre><code>w...
0
2016-10-06T21:58:33Z
[ "python", "list" ]
list of list but specific representations in python
39,906,109
<p>I don't have much experience about lists in Python. So basically, I want to create N list inside one huge list. Reading from a file that looks like this:</p> <pre><code>Fail = h yes Sucess = h no </code></pre> <p>This is an example of 2 lines in the file, and the file contains N line, thus I want to create a list ...
0
2016-10-06T21:47:30Z
39,906,299
<p>One straightforward way is to do two passes of splitting, first by <code>=</code> and then by whitespace (default for <code>split</code>). Use <code>strip</code> as necessary:</p> <pre><code>&gt;&gt;&gt; import io &gt;&gt;&gt; s = """Fail = h yes ... Sucess = h no ... Fail = h """ &gt;&gt;&gt; &gt;&gt;&gt; L = [li...
0
2016-10-06T22:02:24Z
[ "python", "list" ]
why does my openpyxl load only pull one cell in worksheet
39,906,162
<p>I have this openpyxl intent on reading rows in an XLSX document.</p> <p>But for some reason It is only reading the value in CELL A1, then finishing. What am I missing?</p> <p>Thanks</p> <p>from openpyxl import load_workbook</p> <pre><code>Dutch = load_workbook(filename='languages/READY-Language Translation-- Aug...
2
2016-10-06T21:51:29Z
39,911,974
<p>Read-only mode depends to a large extent on the metadata provided by the file you're reading, particularly the "dimensions". You can check this by seeing what <code>ws.max_row</code> and <code>ws.max_col</code> are. If these are different to what you expect then the metadata in the file is incorrect. You can force o...
0
2016-10-07T07:40:49Z
[ "python", "excel", "openpyxl" ]
Inputs on how to achieve REST based interaction between Java and Python?
39,906,167
<p>I have a <strong>Java</strong> process which interacts with its REST API called from my program's UI. When I receive the API call, I end up calling the (non-REST based) <strong>Python script(s)</strong> which do a bunch of work and return me back the results which are returned back as API response. - I wanted to con...
0
2016-10-06T21:51:44Z
39,906,371
<p>Furthermore, in the future you might want to separate them from the same machine and use network to communicate.</p> <p>You can use <strong>http</strong> requests.</p> <p>Make a contract in java of which output you will provide to your python script (or any other language you will use) send the output as a json to...
0
2016-10-06T22:08:42Z
[ "java", "python", "rest", "api" ]
Inputs on how to achieve REST based interaction between Java and Python?
39,906,167
<p>I have a <strong>Java</strong> process which interacts with its REST API called from my program's UI. When I receive the API call, I end up calling the (non-REST based) <strong>Python script(s)</strong> which do a bunch of work and return me back the results which are returned back as API response. - I wanted to con...
0
2016-10-06T21:51:44Z
39,907,522
<p>You can use Flask as a wrapper for converting your Python scripts into microservices. Then, call your Python scripts from Java by passing them a JSON string in a REST call.</p> <p>For each python script, listen on a port between 50,000-65,000 and then send your Java-->Python REST calls to <code>http://127.0.0.1:500...
0
2016-10-07T00:18:01Z
[ "java", "python", "rest", "api" ]
How to run django application in background
39,906,305
<p>I have a Django application that send emails to customers. I want this application to be run in background every certain time, is like a job/quote process. What could be best way to do this with python/Django?</p>
0
2016-10-06T22:03:00Z
39,906,403
<blockquote> <p>How to run django application in background?</p> </blockquote> <p>This question makes no sense. Django is a web based framework. What do you mean by running a web application in background?</p> <p>I think you want to ask: <em>How to run periodic background tasks in <code>Django</code> application?</...
1
2016-10-06T22:11:39Z
[ "python", "django" ]
Multithreaded file read python
39,906,375
<pre><code>import threading def read_file(): f = open('text.txt') for line in f: print line.strip() ,' : ', threading.current_thread().getName() if __name__ == '__main__': threads = [] for i in range(15): t = threading.Thread(target=read_file) threads.append(t) t.start() </code></pre> <p>...
0
2016-10-06T22:09:17Z
39,943,677
<p>Each thread runs your function independently; each copy of the function opens the file as a local, which is not shared. Each Python file object tracks reading state completely independently; each has their own OS-level file handle here.</p> <p>So no, if <em>nothing else is altering the file contents</em>, each thre...
7
2016-10-09T12:34:03Z
[ "python", "multithreading", "python-multithreading" ]
Python function not running, interpreter not giving any errors
39,906,388
<p>I'm very new to Python and having a problem with a program I'm doing for a class. main() and create_file work, but when it gets to read_file, the interpreter just sits there. The program is running but nothing is happening.</p> <p>The answer is probably something very simple, but I just can't see it. Thanks in a...
2
2016-10-06T22:10:37Z
39,906,453
<p>You have an infinite <code>while</code> loop in the function, since <code>entry</code> never changes during the loop.</p> <p>The Pythonic way to process all the lines in a file is like this:</p> <pre><code>for entry in randomInput: num = int(entry) total += num count += 1 </code></pre>
6
2016-10-06T22:16:17Z
[ "python", "function" ]
How to put an argument of a function inside a raw string
39,906,492
<p>I want to create a function that will delete a character in a string of text. I'll pass the string of text and the character as arguments of the function. The function works fine but I don't know how to do this correctly if I want to threat it as a raw string.</p> <p>For example:</p> <pre><code>import re def my_f...
0
2016-10-06T22:20:32Z
39,906,518
<p>How about changing:</p> <pre><code>Regex=re.compile(r'(ch)') print(Regex.sub('',r'text')) </code></pre> <p>to:</p> <pre><code>Regex=re.compile(r'({})'.format(ch)) print(Regex.sub('',r'{}'.format(text))) </code></pre> <p>However, simpler way to achieve this is using <code>str.replace()</code> as:</p> <pre><code>...
2
2016-10-06T22:22:16Z
[ "python", "regex", "string", "variables" ]
How to put an argument of a function inside a raw string
39,906,492
<p>I want to create a function that will delete a character in a string of text. I'll pass the string of text and the character as arguments of the function. The function works fine but I don't know how to do this correctly if I want to threat it as a raw string.</p> <p>For example:</p> <pre><code>import re def my_f...
0
2016-10-06T22:20:32Z
39,906,534
<pre><code>def my_function(text, ch): text.replace(ch, "") </code></pre> <p>This will replace all occurrences of <strong>ch</strong> with an empty string. No need to invoke the overhead of regular expressions in this.</p>
2
2016-10-06T22:23:49Z
[ "python", "regex", "string", "variables" ]
how do I insert data to an arbitrary location in a binary file without overwriting existing file data?
39,906,620
<p>I've tried to do this using the 'r+b', 'w+b', and 'a+b' modes for <code>open()</code>. I'm using with <code>seek()</code> and <code>write()</code> to move to and write to an arbitrary location in the file, but all I can get it to do is either 1) write new info at the end of the file or 2) overwrite existing data in...
0
2016-10-06T22:31:47Z
39,906,690
<p>What you're doing wrong is assuming that it can be done. :-)</p> <p>You don't get to insert and shove the existing data over; it's already in that position on disk, and overwrite is all you get.</p> <p>What you need to do is to mark the insert position, read the remainder of the file, write your insertion, and th...
1
2016-10-06T22:38:00Z
[ "python", "file", "binaryfiles", "file-writing" ]
How to avoid .pyc files using selenium webdriver/python while running test suites?
39,906,630
<p>There's no relevant answer to this question. When I run my test cases inside a test suite using selenium webdriver with python the directory gets trashed with .pyc files. They do not appear if I run test cases separately, only when I run them inside one test suite.How to avoid them?</p> <pre><code>import unittest f...
0
2016-10-06T22:32:20Z
39,906,839
<p><code>pyc</code> files are created any time you <code>import</code> a module, but not when you run a module directly as a script. That's why you're seeing them when you import the modules with the test code but don't see them created when you run the modules separately.</p> <p>If you're invoking Python from the com...
1
2016-10-06T22:53:56Z
[ "python", "selenium" ]
How to avoid .pyc files using selenium webdriver/python while running test suites?
39,906,630
<p>There's no relevant answer to this question. When I run my test cases inside a test suite using selenium webdriver with python the directory gets trashed with .pyc files. They do not appear if I run test cases separately, only when I run them inside one test suite.How to avoid them?</p> <pre><code>import unittest f...
0
2016-10-06T22:32:20Z
39,906,859
<p>You can supply the -B option to the interpreter stop the files from being generated. See: <a href="http://stackoverflow.com/questions/154443/how-to-avoid-pyc-files">How to avoid pyc files</a></p> <p>If you really wanted to, you could also add to your test script a cleanup after running the test. Not that I'm recomm...
1
2016-10-06T22:56:36Z
[ "python", "selenium" ]
Faster way to perform bulk insert, while avoiding duplicates, with SQLAlchemy
39,906,704
<p>I'm using the following method to perform a bulk insert, and to optionally avoid inserting duplicates, with SQLAlchemy:</p> <pre><code>def bulk_insert_users(self, users, allow_duplicates = False): if not allow_duplicates: users_new = [] for user in users: if not self.SQL_IO.db.query...
0
2016-10-06T22:39:58Z
39,906,732
<p>You can load all user ids first, put them into a set and then use <code>user.user_id in existing_user_ids</code> to determine whether to add a new user or not instead of sending a SELECT query every time. Even with ten thousands of users this will be quite fast, especially compared to contacting the database for eac...
1
2016-10-06T22:42:22Z
[ "python", "sqlalchemy" ]
Faster way to perform bulk insert, while avoiding duplicates, with SQLAlchemy
39,906,704
<p>I'm using the following method to perform a bulk insert, and to optionally avoid inserting duplicates, with SQLAlchemy:</p> <pre><code>def bulk_insert_users(self, users, allow_duplicates = False): if not allow_duplicates: users_new = [] for user in users: if not self.SQL_IO.db.query...
0
2016-10-06T22:39:58Z
39,906,752
<p>How many users do you have? You're querying for the users one at a time, every single iteration of that loop. You might have more luck querying for ALL user Ids, put them in a list, then check against that list.</p> <pre><code>existing_users = #query for all user IDs for user in new_users: if user not in existi...
1
2016-10-06T22:43:59Z
[ "python", "sqlalchemy" ]
zerorpc: how to convert string data from python to node
39,906,825
<p>I need to call a python script from <a href="https://nodejs.org/en/" rel="nofollow">nodejs</a> and getting back the result. I found the <a href="http://www.zerorpc.io" rel="nofollow">zerorpc</a> library which seems a good fit. The python script returns an array of strings but in node i got objects of binary data.</p...
0
2016-10-06T22:52:24Z
39,906,976
<p>Node JS Buffer class has the toString method</p> <pre><code>strings[i] = response[i].toString("utf8") </code></pre> <p>See the method: <a href="https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end" rel="nofollow">https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end</a></p>...
0
2016-10-06T23:08:42Z
[ "python", "node.js", "string", "binary", "zerorpc" ]
How to debug cython in and IDE
39,906,830
<p>I am trying to debug a Cython code, that wraps a c++ class, and the error I am hunting is somewhere in the C++ code.</p> <p>It would be awfully convenient if I could somehow debug as if it were written in one language, i.e. if there's an error in the C++ part, it show me the source code line there, if the error is ...
1
2016-10-06T22:53:05Z
39,906,972
<p>It's been a while for me and I forgot how I exactly did it, but when I was writing my own C/C++ library and interfaced it with swig into python, I was able to debug the C code with <a href="https://www.gnu.org/software/ddd/" rel="nofollow">DDD</a>. It was important to compile with debug options. It wasn't great, but...
2
2016-10-06T23:08:35Z
[ "python", "c++", "debugging", "cython" ]
Problems Reversing a Doubly Linked List
39,906,837
<p>I have to reverse a doubly linked list(DLL) between two nodes. I've done this with singly linked lists(SLL), but I find it harder to do with DLL's? It might be the having to do it between two particular nodes. Here is the code for my DLLNode &amp; DLL. When I test this code it seems to do nothing to my DLL. Any tips...
0
2016-10-06T22:53:32Z
39,907,078
<p>I don't see how this executes at all. You've apparently set up a DLL, and then called <strong>DLL.twist('b', 'e')</strong>. Thus, endpt1 = 'b' and endpt2 = 'e'. You then compare endpt1 to current.data, but then you access endpt2.next. <em>endpt2 is a single-character string</em>.</p> <p>You never reference the ...
0
2016-10-06T23:19:48Z
[ "python", "linked-list", "doubly-linked-list" ]
Efficient Way to Permutate a Symmetric Square Matrix in Numpy
39,906,919
<p>What's the best way to do the following in Numpy when dealing with <strong>symmetric square matrices</strong> (<code>NxN</code>) where <code>N &gt; 20000</code>? </p> <pre><code>&gt;&gt;&gt; a = np.arange(9).reshape([3,3]) &gt;&gt;&gt; a = np.maximum(a, a.T) &gt;&gt;&gt; a array([[0, 3, 6], [3, 4, 7], ...
1
2016-10-06T23:02:50Z
39,908,235
<pre><code>In [703]: N=10000 In [704]: a=np.arange(N*N).reshape(N,N);a=np.maximum(a, a.T) In [705]: perm=np.random.permutation(N) </code></pre> <p>One indexing step is quite a bit faster:</p> <pre><code>In [706]: timeit a[perm[:,None],perm] # same as `np.ix_...` 1 loop, best of 3: 1.88 s per loop In [707]: timeit ...
2
2016-10-07T02:02:05Z
[ "python", "matlab", "numpy" ]
PATCH and PUT don't work as expected when pytest is interacting with REST framework
39,906,956
<p>I am building an API using the django REST framework.</p> <p>To test this API I am using pytest and the test client like so:</p> <pre><code>def test_doesnt_find(self, client): resp = client.post(self.url, data={'name': '123'}) assert resp.status_code == 404 </code></pre> <p>or</p> <pre><code>def test_doe...
0
2016-10-06T23:06:56Z
39,923,402
<p>As for the request with JSON data you are receiving this error due to <a href="http://www.json.org/" rel="nofollow">JSON syntax</a> it needs <strong>double quotes</strong> over a string. </p>
-1
2016-10-07T18:06:08Z
[ "python", "django-rest-framework", "put", "pytest-django" ]
PATCH and PUT don't work as expected when pytest is interacting with REST framework
39,906,956
<p>I am building an API using the django REST framework.</p> <p>To test this API I am using pytest and the test client like so:</p> <pre><code>def test_doesnt_find(self, client): resp = client.post(self.url, data={'name': '123'}) assert resp.status_code == 404 </code></pre> <p>or</p> <pre><code>def test_doe...
0
2016-10-06T23:06:56Z
39,953,904
<blockquote> <p>rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`</p> </blockquote> <p>This is usually sign that you send a string inside a string in json. For example:</p> <pre><code>resp = client.patch(self.url, data=json.dumps("n...
0
2016-10-10T08:11:17Z
[ "python", "django-rest-framework", "put", "pytest-django" ]
python read in a txt file and assign strings to combined variable (concatenation)
39,906,991
<p>I have a text file (Grades) where I'm given last name, first name, and grades. I need to read them in, assign them to variables, and write them to a different text file (Graded). I'm a beginner and this is my first hw assignment. There are errors I know, but the biggest thing I want to know is how to read in and the...
-1
2016-10-06T23:10:32Z
39,907,047
<p>Have you read through the Python tutorial? <a href="https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files</a></p>
1
2016-10-06T23:16:06Z
[ "python", "file", "read-write" ]
concatenating variables into one large variable with python
39,907,006
<p>I have the below program in python which is supposed to print values from an array.</p> <pre><code>import sys from datetime import * import pprint txtfile=sys.argv[1] f = open(txtfile,'r') lines=f.readlines() f.close for line in lines: col = line.split(',') wrow=[] grid=[] lon=int(round(float(col[...
0
2016-10-06T23:11:42Z
39,907,072
<p>You'll have to do some kind of loop or join to put them all on the same line, but it's not that bad. I'd do something like this:</p> <pre><code>tuples = [(1, .51), (2, 0.69), (3, 0.83)] joined = " ".join([repr(x[1]) for x in tuples]) print (joined) '0.51 0.69 0.83' </code></pre>
2
2016-10-06T23:19:16Z
[ "python", "string", "loops", "variables", "concatenation" ]
PySp-Pyomo error: 'dict' has no attribute 'f'
39,907,057
<p>i am new to promo and PySP. I am trying to replicate the solutions for the Stochastic Programming tutorial under Vehicle Routing Problems from <code>https://projects.coin-or.org/Coopr/browser/pyomo.data/trunk/pyomo/data/pysp/vehicle_routing/3-7f?rev=9398&amp;order=name</code> But with the excerption of PS3-7b, all ...
0
2016-10-06T23:16:46Z
39,907,309
<p>Try adding -c at the end of the command. It will provide you with a full stack trace showing the source of the error.</p> <p>You should also note that the Coopr project has been renamed to Pyomo, and we are now hosted on Github. The most up to date documentation can be found at pyomo.org</p> <p>Edit:</p> <p>I too...
0
2016-10-06T23:47:25Z
[ "python", "python-2.7", "pyomo" ]
How to pass dictionary as an argument of function and how to access them in the function
39,907,174
<p>I tried doing this:</p> <pre><code>def func(dict): if dict[a] == dict[b]: dict[c] = dict[a] return dict num = { "a": 1, "b": 2, "c": 2} print(func(**num)) </code></pre> <p>But it gives in TypeError. Func got an unexpected argument a</p>
-2
2016-10-06T23:31:24Z
39,907,227
<p>Two main problems:</p> <ul> <li>passing the ** argument is incorrect. Just pass the dictionary; Python will handle the referencing.</li> <li>you tried to reference locations with uninitialized variable names. Letters a/b/c are literal strings in your dictionary.</li> </ul> <p>Code:</p> <pre><code>def func(table...
1
2016-10-06T23:37:38Z
[ "python", "python-3.x" ]
How to pass dictionary as an argument of function and how to access them in the function
39,907,174
<p>I tried doing this:</p> <pre><code>def func(dict): if dict[a] == dict[b]: dict[c] = dict[a] return dict num = { "a": 1, "b": 2, "c": 2} print(func(**num)) </code></pre> <p>But it gives in TypeError. Func got an unexpected argument a</p>
-2
2016-10-06T23:31:24Z
39,907,260
<p>Using ** will unpack the dictionary, in your case you should just pass a reference to <code>num</code> to func, i.e.</p> <p><code>print(num(func))</code></p> <p>(Unpacking <code>**</code> is the equivalent of <code>func(a=1,b=2,c=3)</code>), e.g.</p> <pre><code>def func(arg1,arg2): return arg1 + arg2 args = ...
1
2016-10-06T23:40:51Z
[ "python", "python-3.x" ]
Python not identifying a white space character
39,907,195
<p>I am near my wit's end with this problem: Basically, I need to remove a double space gap between words. My program happens to be in Hebrew, but this is the basic idea:</p> <pre><code>TITLE: הלכות ‏ ‏השכמת‏ ‏הבוקר‏ </code></pre> <p>Notice there is an extra space between the first two words ...
-1
2016-10-06T23:33:33Z
39,907,279
<p>There was a hiding \xe2\x80\x8e, LEFT-TO-RIGHT MARK. Found it using repr(word). Thanks @mgilson!</p>
0
2016-10-06T23:44:24Z
[ "python", "regex" ]
Python attach list of dict to another dict as new key
39,907,209
<p>I have two lists. First one (list a) contain lists of dicts and every list represent comments from the specific post. They all have the same 'id' value. Second list (list b) contain dicts only and these dicts are posts.</p> <p>Now I need to create new key named 'comments' for every dict in b_list and assign appropr...
0
2016-10-06T23:35:20Z
39,907,286
<p>Build a dictionary of IDs and then go through them:</p> <pre><code>&gt;&gt;&gt; a_list=[ ... [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ], ... [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'},], ... ] &gt;&gt;&gt; b_list=[{'post':'123','text': 'Something'}, {'post':'456'...
0
2016-10-06T23:45:00Z
[ "python", "django", "list", "python-3.x", "dictionary" ]
Python attach list of dict to another dict as new key
39,907,209
<p>I have two lists. First one (list a) contain lists of dicts and every list represent comments from the specific post. They all have the same 'id' value. Second list (list b) contain dicts only and these dicts are posts.</p> <p>Now I need to create new key named 'comments' for every dict in b_list and assign appropr...
0
2016-10-06T23:35:20Z
39,907,313
<p><em>I am assuming that in the <code>a_list</code>, one nested <code>list</code> will have same <code>'id'</code> and there will be only one list per id.</em></p> <p>For achieving this, iterate over b_list and check for match in <code>a_list</code>. In case of match, add value to the dict object of <code>a_list</cod...
0
2016-10-06T23:49:18Z
[ "python", "django", "list", "python-3.x", "dictionary" ]
How to put swig wrappers in a reachable location to be tested by python tests?
39,907,237
<p>I got a simple test example like this one:</p> <p><a href="http://i.stack.imgur.com/4GHE0.png" rel="nofollow"><img src="http://i.stack.imgur.com/4GHE0.png" alt="enter image description here"></a></p> <p>And my CMakeLists.txt looks like this:</p> <pre><code>cmake_minimum_required(VERSION 3.7) FIND_PACKAGE(SWIG RE...
0
2016-10-06T23:38:46Z
39,907,318
<p>I am assuming that you want to import the libraries into your runme.py. In order to import python files in a sub-directory, that sub-directory needs an __init__.py file in it. You can place an empty one into your build folder. This should allow your program to import the files.</p> <p>You could then use:</p> <pre>...
0
2016-10-06T23:50:03Z
[ "python", "cmake", "swig" ]
How to put swig wrappers in a reachable location to be tested by python tests?
39,907,237
<p>I got a simple test example like this one:</p> <p><a href="http://i.stack.imgur.com/4GHE0.png" rel="nofollow"><img src="http://i.stack.imgur.com/4GHE0.png" alt="enter image description here"></a></p> <p>And my CMakeLists.txt looks like this:</p> <pre><code>cmake_minimum_required(VERSION 3.7) FIND_PACKAGE(SWIG RE...
0
2016-10-06T23:38:46Z
39,967,741
<p>I use C++ for unit testing and Python for testing against reference implementations or integration testing. </p> <p>The approach I use is to add a custom target, which copies the libraries as well as any extra generated files to my source directory, where the python test files are located. I have configured my <cod...
0
2016-10-10T22:31:34Z
[ "python", "cmake", "swig" ]
How do I apply a regex substitution in a string column
39,907,239
<p>I have a data frame with a column like below</p> <pre><code>Years in current job &lt; 1 year 10+ years 9 years 1 year </code></pre> <p>I want to use regex or any other technique in python to get the result as</p> <pre><code>Years in current job 1 10 9 1 </code></pre> <p>I got something like this but, i guess it ...
-3
2016-10-06T23:39:04Z
39,907,379
<pre><code>df['Years in current job'] = df['Years in current job'].str.replace('\D+', '').astype('int') </code></pre> <p>Regex <code>\D+</code> search non-digits (and replace with empty string)</p> <hr> <p>I found this on SO: <a href="http://stackoverflow.com/a/22591024/1832058">http://stackoverflow.com/a/22591024/1...
1
2016-10-06T23:57:26Z
[ "python", "regex", "pandas" ]
How do I apply a regex substitution in a string column
39,907,239
<p>I have a data frame with a column like below</p> <pre><code>Years in current job &lt; 1 year 10+ years 9 years 1 year </code></pre> <p>I want to use regex or any other technique in python to get the result as</p> <pre><code>Years in current job 1 10 9 1 </code></pre> <p>I got something like this but, i guess it ...
-3
2016-10-06T23:39:04Z
39,907,487
<pre><code>import re def extract_nums(txt): try: return int(re.search('([0-9]+)', txt).group(1)) except: return -1 df['Years in current job'] = df['Years in current job'].apply(extract_nums) </code></pre> <p>EDIT - adding context per suggestion below</p> <p>this could be done easily enough with string m...
0
2016-10-07T00:12:48Z
[ "python", "regex", "pandas" ]
Pandas df.isnull().all() count across multiple files
39,907,249
<p>I have 2000 csv files in a data set with 88 columns each: </p> <pre><code> filenames = glob.glob('path\*.csv') for f in filenames: df = pd.read_csv(f, error_bad_lines = False) df = df.isnull().all() </code></pre> <p>This returns a series with the column title, and True ...
1
2016-10-06T23:40:03Z
39,907,334
<p>The way you've phrased it, you're getting the number of missing columns per dataset. </p> <p>However, you can get the number of missing rows per column, you can modify that code and call this:</p> <pre><code>df.isnull().sum() </code></pre> <p>which will yield a count of missing rows per column. Something like: </...
1
2016-10-06T23:51:25Z
[ "python", "pandas" ]
PIL OverflowError on loading PIL.Image.fromArray
39,907,275
<p>I am trying to store large images using pillow 3.3.1 on python 3.4. These images tend to be in the range from 1 to 4 GB, as uint8 RGB pixels. Linux and OSX give me the same result.</p> <pre><code>from PIL import Image import numpy as np imgArray = np.random.randint(255, size=(39000, 35000, 3)).astype(np.uint8) pri...
0
2016-10-06T23:43:54Z
39,915,609
<p>I realize you asked about PIL, but you could try <a href="http://www.vips.ecs.soton.ac.uk/index.php?title=VIPS" rel="nofollow">libvips</a>. It specializes in large images (images larger than your available RAM) and should have no problems with your 4gb files. There are some <a href="http://www.vips.ecs.soton.ac.uk/i...
0
2016-10-07T10:59:21Z
[ "python", "pillow" ]
Django, uwsgi static files not being served even after collectstatic
39,907,281
<p>I'm having trouble with the deployment of a Django application on a Debian 8 VPS. Python version 2.7, Django 1.10.2.</p> <p>My problem is that it will not serve static files in production mode (DEBUG = False) even after having run 'collectstatic' and assigning a STATIC_ROOT directory.</p> <p>I've followed every in...
0
2016-10-06T23:44:30Z
39,907,426
<p>You need to make sure, <code>urls.py</code> file of your project is updated to serve the static file from production.</p> <p>Update the urls.py file of your project with the following code as shown below.</p> <pre><code>from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ...
0
2016-10-07T00:03:52Z
[ "python", "django", "django-staticfiles" ]
Replace duplicate values across columns in Pandas
39,907,315
<p>I have a simple dataframe as such: </p> <pre><code>df = [ {'col1' : 'A', 'col2': 'B', 'col3': 'C', 'col4':'0'}, {'col1' : 'M', 'col2': '0', 'col3': 'M', 'col4':'0'}, {'col1' : 'B', 'col2': 'B', 'col3': '0', 'col4':'B'}, {'col1' : 'X', 'col2': '0', 'col3': 'Y', 'col4':'0'} ...
3
2016-10-06T23:49:43Z
39,907,637
<p>You can use the <code>duplicated</code> method to return a boolean indexer of whether elements are duplicates or not:</p> <pre><code>In [214]: pd.Series(['M', '0', 'M', '0']).duplicated() Out[214]: 0 False 1 False 2 True 3 True dtype: bool </code></pre> <p>Then you could create a mask by mapping this...
4
2016-10-07T00:32:49Z
[ "python", "pandas" ]
Plot a CSV file where the delimiter is '; ' (semicolon + space)
39,907,407
<p>I'm learning how to plot things (CSV files) in Python, using <code>import matplotlib.pyplot as plt</code>. </p> <pre><code>Column1;Column2;Column3; 1;4;6; 2;2;6; 3;3;8; 4;1;1; 5;4;2; </code></pre> <p>I can plot the one above with <code>plt.plotfile('test0.csv', (0, 1), delimiter=';')</code>, getting the figure bel...
2
2016-10-07T00:01:13Z
39,918,711
<p>So the error matplotlib is throwing you is</p> <pre><code> TypeError: "delimiter" must be a 1-character string </code></pre> <p>Which makes it seem very unlikely you can use <code>'; '</code>. I also had errors thrown when I tried <code>delimiter=';'</code> although you may wish to check that that is reproducible....
0
2016-10-07T13:41:04Z
[ "python", "python-2.7", "matplotlib" ]
Django python trying to use forms with token does not work for me
39,907,411
<p>I'm learning django, in this moment I'm trying to implement web forms, actually some of them works fine with the data base model but I'm trying to make a new one without use the models. The problem is that django show me the token and not the value typed in the form.</p> <p>I hope you can help me, to understand mo...
0
2016-10-07T00:01:45Z
39,907,550
<p>To protect from <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" rel="nofollow">Cross-Site_Request_Forgery</a> attack, for each post request we need to send a csrf token, from the form, which is missing in your form, you can get rid of this error by modifying your form as follows.</p> <pr...
0
2016-10-07T00:20:26Z
[ "python", "django", "forms", "token" ]
Computing the sum of the numbers with a define statement-python
39,907,438
<pre><code>data = [92.5, 87.7, 74.8, 93., 91.7, 90.0, 90.3, 92.5, 100.0, 100.0, 35.7, 37.4, 21.0] def data_sum(data): total=0.0 for element in data: total+=element return total </code></pre> <p>My task is to find the sum of the list above and that is what I came up with so far, however when I g...
-1
2016-10-07T00:06:16Z
39,907,451
<p>Your code is fine. You are not making any call to this function, that is why your code is not executing. You can call your function as:</p> <pre><code>data_sum(data) </code></pre> <p>However, there is <code>sum()</code> function in Python that returns the sum of the <code>list</code> if the list is of numeric type...
0
2016-10-07T00:08:15Z
[ "python", "python-2.7" ]
Computing the sum of the numbers with a define statement-python
39,907,438
<pre><code>data = [92.5, 87.7, 74.8, 93., 91.7, 90.0, 90.3, 92.5, 100.0, 100.0, 35.7, 37.4, 21.0] def data_sum(data): total=0.0 for element in data: total+=element return total </code></pre> <p>My task is to find the sum of the list above and that is what I came up with so far, however when I g...
-1
2016-10-07T00:06:16Z
39,907,561
<p>You need to call your function like the below example:</p> <pre><code>data = [92.5, 87.7, 74.8, 93., 91.7, 90.0, 90.3, 92.5, 100.0, 100.0, 35.7, 37.4, 21.0] def data_sum(data): total = 0.0 for element in data: total += element return total print data_sum(data) </code></pre> <p>Anothe...
0
2016-10-07T00:22:48Z
[ "python", "python-2.7" ]
Assist with re Module
39,907,452
<p>I need to extract all those strings between the patterns nr: or /nr:. Can anyone please help me?</p> <p>The string is </p> <pre><code>nr:Organization/nr:Customer/nr:Agreement/nr:date/nr:coverage/nr:Premium/nr:Option/nr:OptionID </code></pre> <p>Output I am expecting is</p> <pre><code>Organization, Customer, Agre...
-1
2016-10-07T00:08:15Z
39,907,532
<p>Use the <code>re</code> module, <code>split</code> the string and filter out matches whose lengths are 0:</p> <pre><code>import re test_string = "nr:Organization/nr:Customer/nr:Agreement/nr:date/nr:coverage/nr:Premium/nr:Option/nr:OptionID" columns = [x for x in re.split("/{0,1}nr:",test_string) if len(x) &gt; 0]...
0
2016-10-07T00:18:54Z
[ "python" ]
Assist with re Module
39,907,452
<p>I need to extract all those strings between the patterns nr: or /nr:. Can anyone please help me?</p> <p>The string is </p> <pre><code>nr:Organization/nr:Customer/nr:Agreement/nr:date/nr:coverage/nr:Premium/nr:Option/nr:OptionID </code></pre> <p>Output I am expecting is</p> <pre><code>Organization, Customer, Agre...
-1
2016-10-07T00:08:15Z
39,907,542
<p>Here is a way with regular expression and split:</p> <pre><code>import re string = 'nr:Organization/nr:Customer/nr:Agreement/nr:date/nr:coverage/nr:Premium/nr:Option/nr:OptionID' x = filter(None, re.split('/*nr:', string)) print x </code></pre> <p>The regular expression looks for <code>nr:</code> preceded (or no...
0
2016-10-07T00:19:55Z
[ "python" ]
Assist with re Module
39,907,452
<p>I need to extract all those strings between the patterns nr: or /nr:. Can anyone please help me?</p> <p>The string is </p> <pre><code>nr:Organization/nr:Customer/nr:Agreement/nr:date/nr:coverage/nr:Premium/nr:Option/nr:OptionID </code></pre> <p>Output I am expecting is</p> <pre><code>Organization, Customer, Agre...
-1
2016-10-07T00:08:15Z
39,907,570
<p>If you want to do it without using the "re" module, it looks like this would work:</p> <pre><code>test_string = 'nr:Organization/nr:Customer/nr:Agreement/nr:date/nr:coverage/nr:Premium/nr:Option/nr:OptionID' columns = [f[3:] for f in test_string.split('/')] print(columns) </code></pre>
1
2016-10-07T00:23:44Z
[ "python" ]
Cannot import sqlite3 in Python3
39,907,475
<p>I am unable to import the sqlite3 module in Python, version 3.5.0. Here's what I get:</p> <p><code>&gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/sqlite3/__init__.py", line 23, in &lt;module&gt; from sqlite3.dbapi...
1
2016-10-07T00:10:56Z
39,907,500
<p>Install <a href="http://centos-packages.com/7/package/sqlite-devel/" rel="nofollow"><code>sqlite-devel</code></a> package which includes header, library that is required to build <code>sqlite3</code> extension.</p> <pre><code>yum install sqlite-devel </code></pre> <p><strong>NOTE</strong>: Python does not include ...
-1
2016-10-07T00:14:19Z
[ "python", "linux", "python-3.x", "sqlite3", "python-import" ]
Calculating cube root: OverflowError: ('Result too large')
39,907,504
<p>So I'm supposed to create a code that calculates the cube root of an inputted number with the approximation of up to 2 decimal places. This code above calculates the square root of a number with up to 2 decimal places:</p> <pre><code>epsilon = 0.01 guess = num/2.0 while abs(guess**2 - num) &gt;= epsilon: guess ...
0
2016-10-07T00:15:30Z
39,907,815
<p>The method you are using is called <a href="https://en.wikipedia.org/wiki/Newton%27s_method" rel="nofollow">Newton-Raphson approximation</a>, and you should use the first derivative of the function you are trying to solve as the denominator. Because the first derivative of <code>x^3</code> is <code>3*x^2</code>, th...
4
2016-10-07T00:57:36Z
[ "python", "python-3.x" ]
How to perform a root command with Pexpect?
39,907,546
<p>I'm working on a python program to assist with the apt-get tool. I want to use pexpect to download the chosen package. I believe I'm getting stuck at the child.expect line. It seems to timeout when it comes to that line.</p> <pre><code>butt = "vlc" child = pexpect.spawn('sudo apt-get install ' + butt) child.logfile...
2
2016-10-07T00:20:14Z
39,907,632
<p>Try <code>child.expect_exact()</code>.</p> <p>From the docs:</p> <blockquote> <p>The expect() method waits for the child application to return a given string. The string you specify is a regular expression, so you can match complicated patterns.</p> </blockquote> <p>It is good practice to use <code>expect()</co...
1
2016-10-07T00:32:34Z
[ "python", "linux", "ubuntu", "pexpect" ]
How to perform a root command with Pexpect?
39,907,546
<p>I'm working on a python program to assist with the apt-get tool. I want to use pexpect to download the chosen package. I believe I'm getting stuck at the child.expect line. It seems to timeout when it comes to that line.</p> <pre><code>butt = "vlc" child = pexpect.spawn('sudo apt-get install ' + butt) child.logfile...
2
2016-10-07T00:20:14Z
39,907,724
<p>The immediate problem is that this:</p> <pre><code>child.expect('[sudo] password for user1: ') </code></pre> <p>uses a regular expression. The <code>[...]</code> construct has special meaning in regular expressions, so what you're actually waiting for there is one of the letters "d", "o", "s", or "u" followed by t...
1
2016-10-07T00:45:57Z
[ "python", "linux", "ubuntu", "pexpect" ]
pandas groupby a list of strings
39,907,589
<p>Imagine if you have a list of strings and a pandas dataframe with a column <code>Foo</code> that has words which may contain those strings:</p> <p><code> my_list = ['A', 'B', 'C'] </code> </p> <p>df['Foo'] has words that contain 'A' or 'B' or 'C',</p> <p>you can extract the ones that contain by <code>df.Foo.str.c...
0
2016-10-07T00:26:08Z
39,908,159
<p>Yes, you can do this by passing a function to groupby()</p> <pre><code>data = {'Foo': {0: 'apple', 1: 'body', 2: 'animal', 3: 'cot', 4: 'cord', 5: 'bed', 6: 'ant'}} df = pd.DataFrame(data) print (df) Foo 0 apple 1 body 2 animal 3 cot 4 cord 5 bed 6 ant </code></pre> <p>get_...
0
2016-10-07T01:50:43Z
[ "python", "pandas", "data-analysis" ]
How do I create a list of true and false values when comparing two numpy arrays?
39,907,614
<p>I'm creating a list of true and false values out of the following array using list comprehension:</p> <pre><code>array([[ True, True, False, ..., False, True, False], [ True, True, False, ..., False, True, True], [ True, False, True, ..., False, True, False], ..., [ True, True, False, ..., Tru...
0
2016-10-07T00:29:55Z
39,907,905
<p>Assuming my understanding is correct you just need to:</p> <pre><code>numpy.logical_and.reduce(features[index] == features) </code></pre> <p>Here we first produce the matches between all rows and <code>feature[index]</code> with:</p> <pre><code>features[index] == features </code></pre> <p>Then, we reduce the mat...
0
2016-10-07T01:11:59Z
[ "python", "arrays", "numpy" ]
How do I create a list of true and false values when comparing two numpy arrays?
39,907,614
<p>I'm creating a list of true and false values out of the following array using list comprehension:</p> <pre><code>array([[ True, True, False, ..., False, True, False], [ True, True, False, ..., False, True, True], [ True, False, True, ..., False, True, False], ..., [ True, True, False, ..., Tru...
0
2016-10-07T00:29:55Z
39,922,058
<p>With your array excerpt I get the same sort of error with just the indexing:</p> <pre><code>In [726]: features Out[726]: array([[ True, True, False, True, False, True, False], [ True, True, False, True, False, True, True], [ True, False, True, True, False, True, False], [ True, True...
0
2016-10-07T16:34:33Z
[ "python", "arrays", "numpy" ]
Plot specifying column by name, upper case issue
39,907,708
<p>I'm learning how to plot things (CSV files) in Python, using <code>import matplotlib.pyplot as plt</code>. </p> <pre><code>Column1;Column2;Column3; 1;4;6; 2;2;6; 3;3;8; 4;1;1; 5;4;2; </code></pre> <p>I can plot the one above with <code>plt.plotfile('test0.csv', (0, 1), delimiter=';')</code>, which gives me the fig...
0
2016-10-07T00:44:14Z
39,912,122
<p>You are mixing up two things here.<br> Matplotlib is designed for plotting data. It is not designed for managing data.<br> Pandas is designed for data analysis. Even if you were using pandas, you would still need to plot the data. How? Well, probably using matplotlib! Independently of what you're doing, think of it ...
1
2016-10-07T07:49:14Z
[ "python", "python-2.7", "matplotlib" ]
Pandas: How to do analysis on array-like field?
39,907,720
<p>I'm doing analysis on movies, and each movie have a <code>genre</code> attribute, it might be several specific genre, like <code>drama</code>, <code>comedy</code>, the data looks like this:</p> <pre><code>movie_list = [ {'name': 'Movie 1', 'genre' :'Action, Fantasy, Horror'}, {'name': 'Movie 2', 'ge...
0
2016-10-07T00:45:22Z
39,908,150
<p>If your data isn't too huge, I would do some pre-processing and get 1 record per genre. That is, I would structure your data frame like this:</p> <pre><code> Name Genre Movie 1 Action Movie 1 Fantasy Movie 1 Horor ... </code></pre> <p>Note the names should be repeated. While this may make your data set much...
0
2016-10-07T01:49:37Z
[ "python", "pandas", "statistics" ]
Creating a time range in python from a set of custom dates
39,907,791
<p>Let's say I have a set of dates in a DateTimeIndex. There are no times just dates and for each date in the set I would like to have multiple DateTimes. For example for each day I would like index variables every hour from 10am-2pm? I have been using pd.date_range which works well for 1 datetime but not sure how t...
0
2016-10-07T00:54:54Z
39,908,209
<p>Consider a cross join with <code>date</code> + <code>time</code> operation.</p> <pre><code># Example data: # NumData1 NumData2 NumData3 NumData4 NumData5 # DateExample # 2016-10-01 0.299950 0.740431 0.275306 0.168967 0.902464 # 2016-10-02 0....
1
2016-10-07T01:58:24Z
[ "python", "pandas" ]
subprocess.Popen execution of a script stuck
39,907,800
<p>I am trying to execute a command as follows but it is STUCK in <code>try</code> block as below until the timeout kicks in,the python script executes fine by itself independently,can anyone suggest why is it so and how to debug this?</p> <pre><code>cmd = "python complete.py" proc = subprocess.Popen(cmd.split(' '),st...
0
2016-10-07T00:56:02Z
39,907,869
<p><code>proc.stdout</code> isn't available to be read <em>after the process exits</em>. Instead, you need to read it <em>while the process is running</em>. <code>communicate()</code> will do that for you, but since you're not using it, you get to do it yourself.</p> <p>Right now, your process is almost certainly hang...
1
2016-10-07T01:06:51Z
[ "python" ]
Word guessing game -- Can this be written any better?
39,907,806
<p>This is just a portion of the game, a function that takes in the secret word and the letters guessed as arguments and tells you if they guessed the word correctly.</p> <p>I'll be completely honest, this is from an assignment on an edX course, <strong>however</strong> I have already passed this assignment, this code...
3
2016-10-07T00:56:47Z
39,907,887
<p>Something like this is pretty short:</p> <pre><code>def isWordGuessed(secretWord, lettersGuessed): return all([c in lettersGuessed for c in secretWord]) </code></pre> <p>For every character in the <code>secretWord</code> ensure it's in the <code>lettersGuessed</code>. This basically creates a list of booleans an...
6
2016-10-07T01:09:25Z
[ "python", "python-3.x" ]
How to modify deprecated imports for a reusable app?
39,907,808
<p>My project depends on an OSS reusable app, and that app includes a Django import which is deprecated in Django 1.10:</p> <p><code>from django.db.models.sql.aggregates import Aggregate</code></p> <p>is changing to:</p> <p><code>from django.db.models.aggregates import Aggregate</code></p> <p>We get a warning on Dj...
1
2016-10-07T00:57:13Z
39,910,769
<p>Django has a strict backwards compatibility policy. If it's raising a deprecation warning, then the new version <em>works already</em> in 1.9. You should just switch to it before you upgrade.</p>
1
2016-10-07T06:27:31Z
[ "python", "django" ]
Python Scripting in TIBCO Spotfire to show custom Messages
39,907,870
<p>I am loading a data table on demand and have linked it to markings in a previous tab. The Data table look like:</p> <pre><code> ID Values 1 365 2 65 3 32 3 125 4 74 5 98 6 107 </code></pre> <p>I want to limit the data that is brought int...
0
2016-10-07T01:06:57Z
39,979,462
<p>One work-around would be use of a small Text Area on the page (perhaps as a header). You can <code>Insert Dynamic Item</code> -> Calculated Value or Icon and have it perform a count or unique count based on marking (selection). For example, once the Count(ID) is > 1000, the text can change to red, or the icon can ...
1
2016-10-11T14:21:51Z
[ "python", "visualization", "data-visualization", "ironpython", "spotfire" ]
Merging files bases on partially matching file names
39,907,927
<p>I am measuring the dependent variable vs independent variable (let's say current vs voltage from a device measurement) and the measurement set up will give me a separate file for positive measurement and negative measurement values. Each file is an excel file and has 2 columns, one for voltage and current each. I ca...
0
2016-10-07T01:15:34Z
39,966,762
<p>Here is how I went about doing this</p> <pre><code>groups= defaultdict(list) group_sweep=defaultdict(list) for filename in os.listdir('C:\\Users\\TLP_IV'): basename, extension = os.path.splitext(filename) mod, name, pin1, pin2, sweep, dev, meas, date, time, hour=basename.split('_') groups[mod, name, pin...
0
2016-10-10T21:06:46Z
[ "python", "shell" ]
How to merge two dataframes with different column names but same number of rows?
39,907,958
<p>I have two different data frames in pandas. Example:</p> <pre><code>df1=a b df2= c 0 1 1 1 2 2 2 3 3 </code></pre> <p>I want to merge them so </p> <pre><code>df1= a b c 0 1 1 1 2 2 2 3 3 </code></pre> <p>I tried using <code>df1['c'] = df2['c']</code> but i got a...
1
2016-10-07T01:19:55Z
39,908,187
<p>In order to merge two dataframes you can use this two examples. Both returns the same goal.</p> <p>Using <code>merge</code> plus additional arguments instructing it to use the indexes</p> <p>Try this:</p> <pre><code>response = pandas.merge(df1, df2, left_index=True, right_index=True) In [2]: response Out[2]: ...
1
2016-10-07T01:55:32Z
[ "python", "pandas", "dataframe" ]
Restructuring Pandas DataFrame
39,907,981
<p>I have been suggested to move from the class structure, defining my own class, to the pandas DataFrame realm as I envision to have many operations with my data.</p> <p>At this point I have a dataframe that looks like this:</p> <pre><code> ID Name Recording Direction Duration Distance Path Raw ...
1
2016-10-07T01:23:09Z
39,908,393
<p>I think I have a partial answer! I got a little confused about what you wanted with regard to the FFT (fast fourier transform?) and where the data were coming from. </p> <p>HOWEVER, I got everything else. </p> <p>First, I'm gonna make some sample data. </p> <pre><code>import pandas as pd df = pd.DataFrame({"ID":...
1
2016-10-07T02:22:20Z
[ "python", "pandas", "dataframe" ]
Restructuring Pandas DataFrame
39,907,981
<p>I have been suggested to move from the class structure, defining my own class, to the pandas DataFrame realm as I envision to have many operations with my data.</p> <p>At this point I have a dataframe that looks like this:</p> <pre><code> ID Name Recording Direction Duration Distance Path Raw ...
1
2016-10-07T01:23:09Z
39,909,040
<p>Consider concatenating a list of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pandas.pivot_tables</a>. However, prior to concatenating, the dataframe must be sliced by the <em>Raw</em> value common stems --<em>HW.txt</em>, <em>HD.txt</em>, <em>CD.txt</em>-- g...
1
2016-10-07T03:47:00Z
[ "python", "pandas", "dataframe" ]
Output list of files from slideshow
39,908,060
<p>I have adapted a python script to display a slideshow of images. The original script can be found at <a href="https://github.com/cgoldberg/py-slideshow" rel="nofollow">https://github.com/cgoldberg/py-slideshow</a></p> <p>I want to be able to record the filename of each of the images that is displayed so that I may...
0
2016-10-07T01:37:19Z
39,908,247
<p>System don't have to write to file at once but it can keep text in buffer and saves when you close file. So probably you have to close file.</p> <p>Or you can use <code>thefile.flush()</code> after every <code>thefile.write()</code> to send new text from buffer to file at once.</p>
1
2016-10-07T02:04:12Z
[ "python", "for-loop", "pyglet" ]
Output list of files from slideshow
39,908,060
<p>I have adapted a python script to display a slideshow of images. The original script can be found at <a href="https://github.com/cgoldberg/py-slideshow" rel="nofollow">https://github.com/cgoldberg/py-slideshow</a></p> <p>I want to be able to record the filename of each of the images that is displayed so that I may...
0
2016-10-07T01:37:19Z
39,917,033
<p>I ended up declaring the random image chosen to a variable that I, then, wrote to a txt file. Relevant code with changes appears below:</p> <pre><code>thefile=open('test.txt','w') def update_image(dt): pic = random.choice(image_paths) img = pyglet.image.load(pic) thefile.write(pic+'\n') thefile.flush() sprite.ima...
0
2016-10-07T12:13:41Z
[ "python", "for-loop", "pyglet" ]
Regex find ALL patterns betwen string
39,908,061
<p>I want to match digits betwen "000" or betwen \b and "000" or "000" and \b from a string like this: </p> <pre><code>11101110001011101000000011101010111 </code></pre> <p>I have tried with expressions like this:</p> <pre><code>(?&lt;=000)\d+(?=000) </code></pre> <p>but I only get the largest occurrence </p> <p>I ...
0
2016-10-07T01:37:36Z
39,908,125
<p>You can use the <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code> package</a> and the <code>.findall()</code> method:</p> <pre><code>In [1]: s = "11101110001011101000000011101010111" In [2]: import regex In [3]: regex.findall(r"(?&lt;=000|^)\d+?(?=000|$)", s) Out[3]: ['1110111', '1011...
1
2016-10-07T01:44:47Z
[ "python", "regex", "string", "digits" ]
Regex find ALL patterns betwen string
39,908,061
<p>I want to match digits betwen "000" or betwen \b and "000" or "000" and \b from a string like this: </p> <pre><code>11101110001011101000000011101010111 </code></pre> <p>I have tried with expressions like this:</p> <pre><code>(?&lt;=000)\d+(?=000) </code></pre> <p>but I only get the largest occurrence </p> <p>I ...
0
2016-10-07T01:37:36Z
39,915,616
<p>you can do it with the re module like this:</p> <pre><code>re.findall(r'(?:\b|(?&lt;=000))(\d+?)(?:000|\b)', s) </code></pre>
1
2016-10-07T10:59:41Z
[ "python", "regex", "string", "digits" ]
Extract the year and the month from a line in a file and use a map to print every time its found to add 1 to the value
39,908,080
<pre><code>def Stats(): file = open('mbox.txt') d = dict() for line in file: if line.startswith('From'): words = line.split() for words in file: key = words[3] + " " + words[6] if key: d[key] +=1 return d </code></pre> ...
-1
2016-10-07T01:39:45Z
39,908,172
<p>Not the direct answer to the question, but a possible alternative solution - use the <a href="https://labix.org/python-dateutil" rel="nofollow"><code>dateutil</code></a> datetime parser in a "fuzzy" mode and simply format the extracted <code>datetime</code> object via <a href="https://docs.python.org/2/library/datet...
0
2016-10-07T01:52:29Z
[ "python", "python-2.7", "python-3.x" ]
Extract the year and the month from a line in a file and use a map to print every time its found to add 1 to the value
39,908,080
<pre><code>def Stats(): file = open('mbox.txt') d = dict() for line in file: if line.startswith('From'): words = line.split() for words in file: key = words[3] + " " + words[6] if key: d[key] +=1 return d </code></pre> ...
-1
2016-10-07T01:39:45Z
39,908,413
<p>You need something more like this</p> <pre><code>def Stats(): with open('mbox.txt') as f: d = {} for line in f: if line.startswith('From'): words = line.split() key = words[3] + " " + words[6] if key in d: d[key] +=...
0
2016-10-07T02:25:22Z
[ "python", "python-2.7", "python-3.x" ]
Problems cropping entire white lines from .png file
39,908,104
<p>What I want to do is to crop out the white lines above a given instagram print screen. I tried doing that by finding the center of the image and going up, line by line, until I found the first line entirely white. Any idea why my code is not working? </p> <pre><code>from PIL import Image image_file = "test.png" im...
0
2016-10-07T01:41:58Z
39,911,102
<p>Your <code>getpixel()</code> call is actually searching with the coordinates the wrong way around, so in effect you were scanning for the left edge. You could use the following approach. This creates a row of data containing only white pixels. If the length of the row equals your width, then you know they are all wh...
0
2016-10-07T06:51:07Z
[ "python", "set", "python-imaging-library", "crop" ]
cx_Freeze error: no commands supplied
39,908,111
<p>I'm trying to create a executable from my .py file.</p> <p>I did this:</p> <pre><code>import cx_Freeze executables = [cx_Freeze.Executable("Cobra.py")] cx_Freeze.setup(name="Snake Python", options={"build_exe":{"packages":["pygame","time","sys","os","random"]}}, executables = executables) </code></pre> <p>And r...
0
2016-10-07T01:42:59Z
39,908,178
<p>You need to actually pass a command to <code>setup.py</code> to tell it to build the executable</p> <pre><code>python setup.py build </code></pre> <blockquote> <p>This command will create a subdirectory called <code>build</code> with a further subdirectory starting with the letters <code>exe.</code> and ending w...
0
2016-10-07T01:53:45Z
[ "python", "cx-freeze" ]
control of user input
39,908,116
<p>I'm wondering why my input control here doesn't work. I tried it with only <code>userOption != "1"</code> and it worked fine (Side note: Ignore the other functions.)</p> <pre><code>userOption = str(input("Chose option 1, 2 or \"E/e to exit\": ")) print(userOption) while(userOption != "1" or userOption != "2" or use...
0
2016-10-07T01:43:30Z
39,908,157
<p>You have to use <code>and</code> instead of <code>or</code></p> <pre><code>while userOption != "1" and userOption != "2" and userOption != "e" and userOption != "E": </code></pre> <p>or <code>not</code> with <code>==</code></p> <pre><code>while not(userOption == "1" or userOption == "2" or userOption == "e" or us...
1
2016-10-07T01:50:24Z
[ "python" ]
control of user input
39,908,116
<p>I'm wondering why my input control here doesn't work. I tried it with only <code>userOption != "1"</code> and it worked fine (Side note: Ignore the other functions.)</p> <pre><code>userOption = str(input("Chose option 1, 2 or \"E/e to exit\": ")) print(userOption) while(userOption != "1" or userOption != "2" or use...
0
2016-10-07T01:43:30Z
39,908,747
<pre><code>while(userOption != "1" or userOption != "2" or userOption != "e" or userOption != "E"): </code></pre> <p>That logic will produce a true result <em>no matter what the user types</em>. As others have said, you need to use <code>and</code> here instead of <code>or</code>.</p>
0
2016-10-07T03:07:47Z
[ "python" ]
Check parallelism of files using their suffixes
39,908,156
<p>Given a directory of files, e.g.:</p> <pre><code>mydir/ test1.abc set123.abc jaja98.abc test1.xyz set123.xyz jaja98.xyz </code></pre> <p>I need to check that for every <code>.abc</code> file there is an equivalent <code>.xyz</code> file. I could do it like this:</p> <pre><code>&gt;&gt;&gt; filenames =...
0
2016-10-07T01:50:09Z
39,908,318
<p>You could define helper function that would return <code>set</code> of filenames without extension that match to the given suffix. Then you could easily check is files with suffix <code>.abc</code> is subset of files with suffix <code>.xyz</code>:</p> <pre><code>filenames = ['test1.abc', 'set123.abc', 'jaja98.abc',...
2
2016-10-07T02:13:34Z
[ "python", "operating-system", "filepath", "file-extension", "suffix" ]
drop datetimeindex where df shows nan
39,908,183
<p>I have a pandas dataframe with datetime index which has nan values on some rows. How do I remove the datetimeindex along with the nan rows? </p> <pre><code>2016-10-06 13:15:00 2.923383 0.007970 -0.001883 2016-10-06 13:30:00 2.809612 0.007389 0.001466 2016-10-06 13:45:00 3.022803 0.028234 -0.005162 2016-10-06...
0
2016-10-07T01:54:15Z
39,908,682
<p>If you just want to find the indices where there is <em>no</em> NaN in a row, you can do this:</p> <pre><code># get a single column of T/F values that # where at least one value in the row is null msk = df.isnull().any(axis=1) # now drop all of the index values where msk = True new_index = df.index.drop(msk[msk =...
0
2016-10-07T02:58:59Z
[ "python", "pandas", "dataframe" ]
Printing Parallel Tuples in python
39,908,251
<p>I'm trying to make a word guessing program and I'm having trouble printing parallel tuples. I need to print the <code>"secret word"</code> with the corresponding hint, but the code that I wrote doesn't work. I can't figure out where I'm going wrong.</p> <p>Any help would be appreciated :)</p> <p>This is my code so...
0
2016-10-07T02:04:41Z
39,919,414
<p>The issue here is that <code>random_int</code> is, as defined, random. As a result you'll randomly get the right result sometimes.</p> <p>A quick fix is by using the <code>tuple.index</code> method, get the index of the element inside the tuple <code>Words</code> and then use that index on <code>Hints</code> to get...
0
2016-10-07T14:16:02Z
[ "python", "python-3.x", "tuples" ]
pass data result from python to Java variable by processbuilder
39,908,283
<p>I used process builder to run a python script from java. and i can sent the data from Java to python variable ( import sys to get data from Java) . and print out the python result in java. for example: </p> <pre><code>public static void main(String a[]){ try{ int number1 = 100; int number2 = 200; String searchTerm...
0
2016-10-07T02:09:42Z
39,955,186
<p>As far as I am aware, you can't do that with ProcessBuilder. You can print your variable to the output and let Java interpret it. Or you can use some API that is connecting Java and Python stronger (for example <a href="http://www.jython.org/" rel="nofollow">Jython</a>).</p>
0
2016-10-10T09:27:09Z
[ "java", "python", "json", "processbuilder", "sys" ]