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
simple matrix type rotation (without numpy or pandas)
39,004,701
<p>This must be something that is really simple, but I could not fix it.</p> <p>I want to do a matrix type transpose with native python list of list (i.e., without using <code>numpy</code> or <code>pandas</code>). Code is show following. I am having a hard time trying to figure out where it is wrong.</p> <pre><code>raw_matrix_list = [[1, 0, 1, 0, 1, 0], [1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 1]] def rotate_matrix_list(raw_matrix_list): rows = len(raw_matrix_list) cols = len(raw_matrix_list[0]) new_matrix_list = [[0] * rows] * cols for ii in xrange(cols): for jj in xrange(rows): # print str(ii) + ', ' + str(jj) + ', ' + str(rows) new_matrix_list[ii][jj] = raw_matrix_list[rows-jj - 1][ii] return(new_matrix_list) rotate_matrix_list(raw_matrix_list) </code></pre> <p>The result I get is</p> <pre><code>[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]] </code></pre> <p>What I want to get is:</p> <pre><code>[[1, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0], [1, 0, 1, 1], [1, 1, 0, 0]] </code></pre> <p>===</p> <pre><code>$ python --version </code></pre> <p>Python 2.7.12 :: Anaconda 2.3.0 (x86_64)</p> <p>===</p> <h1>update 2</h1> <p>Now I got the answer of how to do it in python with <code>zip</code> function. But I just failed to see why my code did not work. </p>
0
2016-08-17T19:23:24Z
39,004,924
<p>Using a nested list comprehension:</p> <pre><code>rows, cols = len(raw_matrix_list), len(raw_matrix_list[0]) &gt;&gt;&gt; [[raw_matrix_list[i][j] for i in range(rows)] for j in range(cols)] [[1, 1, 0, 1], [0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [1, 1, 0, 1], [0, 0, 1, 1]] </code></pre>
0
2016-08-17T19:36:46Z
[ "python" ]
simple matrix type rotation (without numpy or pandas)
39,004,701
<p>This must be something that is really simple, but I could not fix it.</p> <p>I want to do a matrix type transpose with native python list of list (i.e., without using <code>numpy</code> or <code>pandas</code>). Code is show following. I am having a hard time trying to figure out where it is wrong.</p> <pre><code>raw_matrix_list = [[1, 0, 1, 0, 1, 0], [1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 1]] def rotate_matrix_list(raw_matrix_list): rows = len(raw_matrix_list) cols = len(raw_matrix_list[0]) new_matrix_list = [[0] * rows] * cols for ii in xrange(cols): for jj in xrange(rows): # print str(ii) + ', ' + str(jj) + ', ' + str(rows) new_matrix_list[ii][jj] = raw_matrix_list[rows-jj - 1][ii] return(new_matrix_list) rotate_matrix_list(raw_matrix_list) </code></pre> <p>The result I get is</p> <pre><code>[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]] </code></pre> <p>What I want to get is:</p> <pre><code>[[1, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0], [1, 0, 1, 1], [1, 1, 0, 0]] </code></pre> <p>===</p> <pre><code>$ python --version </code></pre> <p>Python 2.7.12 :: Anaconda 2.3.0 (x86_64)</p> <p>===</p> <h1>update 2</h1> <p>Now I got the answer of how to do it in python with <code>zip</code> function. But I just failed to see why my code did not work. </p>
0
2016-08-17T19:23:24Z
39,005,228
<p>There are already answers that help solve your problem. As to why your code doesn't work, shouldn't it be this (by definition of matrix transpose):</p> <p><code>new_matrix_list[ii][jj] = raw_matrix_list[jj][ii]</code></p>
0
2016-08-17T19:57:00Z
[ "python" ]
Ascending/Resetting Integer Values from MultiIndex Pandas
39,004,736
<p>I have a dataframe:</p> <pre><code>import pandas as pd tuples = [('a', 1990),('a', 1994),('a',1996),('b',1992),('b',1997),('c',2001)] index = pd.MultiIndex.from_tuples(tuples, names = ['Type', 'Year']) vals = ['This','That','SomeName','This','SomeOtherName','SomeThirdName'] df = pd.DataFrame(vals, index=index, columns=['Whatev']) df Out[3]: Whatev Type Year a 1990 This 1994 That 1996 SomeName b 1992 This 1997 SomeOtherName c 2001 SomeThirdName </code></pre> <p>And I'd like to add a column of ascending integers corresponding to 'Year' that resets for each 'Type', like so:</p> <pre><code> Whatev IndexInt Type Year a 1990 This 1 1994 That 2 1996 SomeName 3 b 1992 This 1 1997 SomeOtherName 2 c 2001 SomeThirdName 1 </code></pre> <p>Here's my current method:</p> <pre><code>grouped = df.groupby(level=0) unique_loc = [] for name, group in grouped: unique_loc += range(1,len(group)+1) joined['IndexInt'] = unique_loc </code></pre> <p>But this seems ugly and convoluted to me, and I imagine it could get slow on the ~50 million row dataframe that I'm working with. Is there a simpler way?</p>
1
2016-08-17T19:25:32Z
39,004,767
<p>you can use <code>groupby(level=0)</code> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow">cumcount()</a>:</p> <pre><code>In [7]: df['IndexInt'] = df.groupby(level=0).cumcount()+1 In [8]: df Out[8]: Whatev IndexInt Type Year a 1990 This 1 1994 That 2 1996 SomeName 3 b 1992 This 1 1997 SomeOtherName 2 c 2001 SomeThirdName 1 </code></pre>
2
2016-08-17T19:27:23Z
[ "python", "pandas" ]
Can't use .update() function on Django context in views?
39,004,754
<p>I have a function that gets some base information in my <code>views.py</code> file, and I'm trying to update the context of each page using it by having it return a dictionary. However, using <code>.update()</code> on the context dictionary in the <code>render()</code> function doesn't seem to work.</p> <p>Here's what I'm doing:</p> <pre><code>def getBaseInfo(): allPages = list(Page.objects.all()) primaryPages = allPages[:5] secondaryPages = allPages[5:] return {'p':primaryPages, 'p2':secondaryPages} def index(request): return render(request, 'pages/index.html', {}.update(getBaseInfo())) </code></pre> <p>However, nothing is sent to my templates. Thanks in advance!</p> <p>Edit: I'm using Python 2.7.11</p>
-2
2016-08-17T19:26:23Z
39,005,157
<p>You should do something like this: </p> <pre><code>def index(request): allPages = list(Page.objects.all()) primaryPages = allPages[:5] secondaryPages = allPages[5:] return render(request, 'pages/index.html', {'p':primaryPages, 'p2':secondaryPages}) </code></pre> <p>Other option should be to make <code>getBaseInfo</code> a <code>@property</code> for reusability and DRY purposes, or make the view class based template view and define reusable code as mixin. I prefer the latter, but it's entirely matter of personal choice. </p>
1
2016-08-17T19:52:03Z
[ "python", "django" ]
Can't use .update() function on Django context in views?
39,004,754
<p>I have a function that gets some base information in my <code>views.py</code> file, and I'm trying to update the context of each page using it by having it return a dictionary. However, using <code>.update()</code> on the context dictionary in the <code>render()</code> function doesn't seem to work.</p> <p>Here's what I'm doing:</p> <pre><code>def getBaseInfo(): allPages = list(Page.objects.all()) primaryPages = allPages[:5] secondaryPages = allPages[5:] return {'p':primaryPages, 'p2':secondaryPages} def index(request): return render(request, 'pages/index.html', {}.update(getBaseInfo())) </code></pre> <p>However, nothing is sent to my templates. Thanks in advance!</p> <p>Edit: I'm using Python 2.7.11</p>
-2
2016-08-17T19:26:23Z
39,005,278
<p>Firstly, if you wanted to use a base dictionary and add objects to that you should do so explicitly:</p> <pre><code>def index(request): context = getBaseInfo() context.update({'otherkey': 'othervalue'}) # or context['otherkey'] = 'othervalue' return(...) </code></pre> <p>However, there is no need to do this at all. Django already provides you a way of automatically providing shared context, and that is a <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#subclassing-context-requestcontext" rel="nofollow">context processor</a>.</p> <p>In fact your <code>getBaseInfo()</code> function is <em>already</em> almost a context processor - it just needs to accept the <code>request</code> parameter - so you just need to add it to the <code>context_processors</code> list in your TEMPLATES setting. Then <em>all</em> your templates will automatically get the values from that function.</p>
2
2016-08-17T19:59:58Z
[ "python", "django" ]
Comparing list with dictionary to make new list in python
39,004,820
<p>I have one list and one dictionary. I want to compare the list values with the keys of the dictionary. If I have:</p> <pre><code>mydict = {'Hello':1,'Hi':2,'Hey':3} </code></pre> <p>and:</p> <pre><code>mylist = ['Hey','What\'s up','Hello'] </code></pre> <p>I want the output to be:</p> <pre><code>output = [3, None, 1] </code></pre> <p>Thanks!</p> <p>I tried <code>[mydict[i] for i in mylist]</code> and I get an error instead of None. I then tried using nested for loops (I deleted that bit) but I decided that was to inefficient.</p>
-1
2016-08-17T19:29:53Z
39,004,905
<p>Use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>: </p> <pre><code>output = [ mydict.get(key) for key in mylist ] </code></pre> <p>Note that <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dict.get</a> returns <code>None</code> if the key is not in the dict.</p>
3
2016-08-17T19:35:45Z
[ "python", "python-3.x", "python-3.5" ]
Comparing list with dictionary to make new list in python
39,004,820
<p>I have one list and one dictionary. I want to compare the list values with the keys of the dictionary. If I have:</p> <pre><code>mydict = {'Hello':1,'Hi':2,'Hey':3} </code></pre> <p>and:</p> <pre><code>mylist = ['Hey','What\'s up','Hello'] </code></pre> <p>I want the output to be:</p> <pre><code>output = [3, None, 1] </code></pre> <p>Thanks!</p> <p>I tried <code>[mydict[i] for i in mylist]</code> and I get an error instead of None. I then tried using nested for loops (I deleted that bit) but I decided that was to inefficient.</p>
-1
2016-08-17T19:29:53Z
39,004,914
<p>Use <code>dict.get()</code>, which defaults to <code>None</code> if key does not exist:</p> <pre><code>[mydict.get(k) for k in mylist] </code></pre> <hr> <pre><code>&gt;&gt;&gt; mydict = {'Hello':1,'Hi':2,'Hey':3} &gt;&gt;&gt; mylist = ['Hey','What\'s up','Hello'] &gt;&gt;&gt; out = [mydict.get(k) for k in mylist] &gt;&gt;&gt; out [3, None, 1] </code></pre>
2
2016-08-17T19:36:18Z
[ "python", "python-3.x", "python-3.5" ]
Passing Javascript variable to Django views.py with getJSON
39,004,837
<p>I currently have a javascript variable called myVariableToSend that contains a single string and I need to send to my views where I can make raw SQL queries to gather corresponding data from the database and bring it back to my javascript. Here is what I have:</p> <p><strong>Javascript:</strong></p> <pre><code>function scriptFunction(myVariableToSend){ $.getJSON("http://127.0.0.1:8000/getData/", myVariableToSend, function(serverdata){ window.alert(serverdata); }); </code></pre> <p><strong>Views.py:</strong></p> <pre><code>def getData(request): some_data = request.GET(myVariableToSend) cursor = connection.cursor() cursor.execute("SELECT Car_ID FROM cars WHERE Carname = %s ", [some_data]) row = cursor.fetchall() return JsonResponse(row, safe = False) </code></pre> <p><strong>Urls.py:</strong></p> <pre><code>url(r'^admin/', include(admin.site.urls)), url(r'^$', startpage), url(r'^getData/$', getData ), </code></pre> <p>I don't think my server side script(views.py) is working because when I run my server, I get a http500 error. Any help would be appreciated. Thank you.</p> <p><strong>UPDATE:</strong></p> <p>I have found that when I comment out my entire Views.py and only put </p> <pre><code>def getData(request): return JsonResponse({"hello":"World"}, safe = False) </code></pre> <p>I get no problems and the AJAX request works. But when I have my original getData, it doesn't work. When I add this line in my views.py:</p> <pre><code>some_data = request.GET(myVariableToSend) </code></pre> <p>, I get an error and the data isn't displayed</p>
0
2016-08-17T19:31:04Z
39,006,031
<p>If u want to send ur variables to function in view, u can capture it with url, like this: </p> <pre><code>$.getJSON('http://127.0.0.1:8000/getData/' + myVariableToSend +'/', function (serverdata) { //do ur work} </code></pre> <p>Then in urls.py you have: </p> <pre><code>url(r'getData/(?P&lt;my_var&gt;\w+)/$', views.get_data, name='get_data') </code></pre> <p>Then views.py:</p> <pre><code>def get_data(request, my_var): #do ur work here </code></pre>
0
2016-08-17T20:49:26Z
[ "javascript", "jquery", "python", "django" ]
Passing Javascript variable to Django views.py with getJSON
39,004,837
<p>I currently have a javascript variable called myVariableToSend that contains a single string and I need to send to my views where I can make raw SQL queries to gather corresponding data from the database and bring it back to my javascript. Here is what I have:</p> <p><strong>Javascript:</strong></p> <pre><code>function scriptFunction(myVariableToSend){ $.getJSON("http://127.0.0.1:8000/getData/", myVariableToSend, function(serverdata){ window.alert(serverdata); }); </code></pre> <p><strong>Views.py:</strong></p> <pre><code>def getData(request): some_data = request.GET(myVariableToSend) cursor = connection.cursor() cursor.execute("SELECT Car_ID FROM cars WHERE Carname = %s ", [some_data]) row = cursor.fetchall() return JsonResponse(row, safe = False) </code></pre> <p><strong>Urls.py:</strong></p> <pre><code>url(r'^admin/', include(admin.site.urls)), url(r'^$', startpage), url(r'^getData/$', getData ), </code></pre> <p>I don't think my server side script(views.py) is working because when I run my server, I get a http500 error. Any help would be appreciated. Thank you.</p> <p><strong>UPDATE:</strong></p> <p>I have found that when I comment out my entire Views.py and only put </p> <pre><code>def getData(request): return JsonResponse({"hello":"World"}, safe = False) </code></pre> <p>I get no problems and the AJAX request works. But when I have my original getData, it doesn't work. When I add this line in my views.py:</p> <pre><code>some_data = request.GET(myVariableToSend) </code></pre> <p>, I get an error and the data isn't displayed</p>
0
2016-08-17T19:31:04Z
39,006,737
<p><strong>Answering the original question:</strong></p> <p>Your server is failing probably because bad syntax in views.py</p> <pre><code>some_data = request.GET(myVariableToSend) </code></pre> <p><code>myVariableToSend</code> is undefined here. So you should get it like this:</p> <pre><code>some_data = request.GET['myVariableToSend'] </code></pre> <p><strong>Besides the original question:</strong></p> <p>You'll get a lot of headaches if you try to set up your django app like this.You can query your database way easier if you use django's ORM. Read about it <a href="https://docs.djangoproject.com/es/1.10/topics/db/queries/" rel="nofollow">here</a>. </p> <p>Also, if you want to send the data in your models to your javascript code, you can save yourself lots of time by using a framework like <a href="http://www.django-rest-framework.org/" rel="nofollow">Django REST Framework</a>.</p>
0
2016-08-17T21:43:20Z
[ "javascript", "jquery", "python", "django" ]
How open python2.7 in spyder, jupyter, qtconsole. from Anaconda Navigator installed with python3? (OS X)
39,004,849
<p>Under OS X (10.11.6) I installed the current Python 3.5 version of Anaconda. Anaconda Navigator then works just fine to launch sypder, jupyter,or qtconsole with python 3.5.2 running.</p> <p>At the command line I also created a python 2.7 environment (conda create --name python2 python=2.7 anaconda). But now when I open Anaconda Navigator, go to Environments in the left pane, and select my python2 environment, still if I go back to Home and launch sypder, jupyter, qtconsole, the python version shown is still 3.5.2.</p> <p>I tried closing Anaconda Navigator, executing "source activate python2" at the command line, and reopening Anaconda Navigator, and again selecting python2 from Environments there. But still sypder, jupyter, qtconsole open with python 3.5.2.</p> <p>How do I launch with python 2.7?</p>
0
2016-08-17T19:31:26Z
39,654,422
<p>Type the following commands in the terminal:</p> <ol> <li><p>source activate python2</p></li> <li><p>spyder</p></li> </ol> <p>Spyder will be launched with the python2 environment. With this method you do not use the anaconda navigator, but at least you can use spyder with your python2 environment.</p>
1
2016-09-23T06:53:51Z
[ "python", "anaconda" ]
AWS IoT device is not getting message published by iOS app
39,004,902
<p>So I am building an iOS app that can communicate with a device via AWS IoT. both the device and the app are subscribed to the update/accepted, get/accepted and update/delta. I can publish updates from either side, and the update is reflected on AWS IoT thing shadow, but somehow the update was never relayed from one device to another. So if I press send on the app the update will be shown on AWS IoT, but the device that is supposedly subscribed to the topics never seem to receive such update, and vice versa. <strong>Below is the cod snippet on the device side.</strong></p> <pre><code># For certificate based connection myShadowClient = AWSIoTMQTTShadowClient("myDevice") myShadowClient.configureEndpoint("xxxxxxxxx.iot.us-east-1.amazonaws.com", 8883) myShadowClient.configureCredentials("certs/root-CA.crt", "certs/private.pem.key", "certs/certificate.pem.crt") myShadowClient.configureConnectDisconnectTimeout(10) # 10 sec myShadowClient.configureMQTTOperationTimeout(5) # 5 sec # Custom MQTT message callback def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") # Custom Shadow callback def customShadowCallback_Update(payload, responseStatus, token): # payload is a JSON string ready to be parsed using json.loads(...) # in both Py2.x and Py3.x if responseStatus == "timeout": print("Update request " + token + " time out!") if responseStatus == "accepted": payloadDict = json.loads(payload) print("~~~~~~~~~~~~~~~~~~~~~~~") print("Update request with token: " + token + " accepted!") print("property: " + str(payloadDict["state"]["desired"]["property"])) print("~~~~~~~~~~~~~~~~~~~~~~~\n\n") if responseStatus == "rejected": print("Update request " + token + " rejected!") def customShadowCallback_Delete(payload, responseStatus, token): if responseStatus == "timeout": print("Delete request " + token + " time out!") if responseStatus == "accepted": print("~~~~~~~~~~~~~~~~~~~~~~~") print("Delete request with token: " + token + " accepted!") print("~~~~~~~~~~~~~~~~~~~~~~~\n\n") if responseStatus == "rejected": print("Delete request " + token + " rejected!") #MQTT Operations JSONPayload = '{"state":{"reported":{"property": "published from Device"}}}' myShadowClient.connect() myMQTTClient = myShadowClient.getMQTTConnection() # AWSIoTMQTTClient connection configuration myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.publish("$aws/things/myDevice/shadow/update", JSONPayload, 1) myMQTTClient.publish("$aws/things/myDevice/shadow/get", "", 1) myMQTTClient.subscribe("$aws/things/myDevice/shadow/update/accepted", 1, customCallback) myMQTTClient.subscribe("$aws/things/myDevice/shadow/update/rejected", 1, customCallback) myMQTTClient.subscribe("$aws/things/myDevice/shadow/get/accepted", 1, customCallback) myMQTTClient.subscribe("$aws/things/myDevice/shadow/get/rejected", 1, customCallback) myMQTTClient.subscribe("$aws/things/myDevice/shadow/update/delta", 1, customCallback) # Create a device shadow instance using persistent subscription myDeviceShadow = myShadowClient.createShadowHandlerWithName("Bot", True) while True: time.sleep(10) </code></pre>
0
2016-08-17T19:35:33Z
39,085,092
<p>This is intended behavior. The explanation can be found <a href="http://%20http://docs.aws.amazon.com/iot/latest/developerguide/using-thing-shadows.html#delta-state" rel="nofollow">here</a></p> <blockquote> <p>Delta state is a virtual type of state that contains the difference between the desired and reported states. Fields in the desired section that are not in the reported section are included in the delta. Fields that are in the reported section and not in the desired section are <strong>not</strong> included in the delta. </p> </blockquote>
1
2016-08-22T17:08:16Z
[ "python", "ios", "swift", "amazon-web-services", "aws-iot" ]
Does timeit clear the local memory after each iteration
39,004,937
<p>I have a moderately sized sorted ascii text file that I am attempting to work with in Python. I am trying to decide at what number of searches it becomes faster to read the entire file into memory and use numpy logical indexing to do searches instead of using a simple binary search function that I wrote using the timeit function. To do this I have the following setup</p> <pre><code>import os import timeit import numpy as np def binsearch(file, label, col=0, start=0, stop=None, linelength=None): if linelength is None: file.seek(0, os.SEEK_SET) file.readline() linelength = file.tell() if stop is None: file.seek(0, os.SEEK_END) stop = file.tell() stopline = stop // linelength startline = start // linelength midline = (stopline-startline) // 2 + startline mid = midline*linelength file.seek(mid, os.SEEK_SET) line = file.readline() if not line: return None linelab = int(line.split()[col]) if linelab == label: return line elif midline == startline or midline == stopline: return None elif linelab &lt; label: start = mid return binsearch(file, label, col=col, start=start, stop=stop, linelength=linelength) elif linelab &gt; label: stop = mid return binsearch(file, label, col=col, start=start, stop=stop, linelength=linelength) filepath = '/Users/aliounis/UCAC4/u4i/u4xtycho' data0 = np.genfromtxt(filepath, dtype=np.int, names=['tycid', 'ucacid', 'rnm']) numsearch = 10000 checks = data0['ucacid'][np.random.randint(0, 259788-1, numsearch)] del data0 allin = """ data = np.genfromtxt(filepath, dtype=np.int, names=['tycid', 'ucacid', 'rnm']) locate = checks.reshape(1, -1) == data['ucacid'].reshape(-1, 1) print(data[np.any(locate, axis=1)].shape) """ bins = """ file = open(filepath, 'r') recs = [] dtypes = np.dtype([('tycid', np.int), ('ucacid', np.int), ('rnm', np.int)]) for val in checks: line = binsearch(file, val, col=1) if line is not None: recs.append(np.array([tuple(np.fromstring(line, dtype=np.int, sep=' '))], dtype=dtypes)) print(np.concatenate(recs, axis=0).shape) file.close() """ numattempts = 10 print(timeit.timeit(allin, number=numattempts, globals=globals())/numattempts) print(timeit.timeit(bins, number=numattempts, globals=globals())/numattempts) </code></pre> <p>where I am using <code>timeit</code> to compare the average amount of time it takes to complete each task. I want to know if this is a fair test, particularly to the numpy implementation. Does timeit clear the local memory between each run (i.e. will it <code>del data</code> and <code>del locate</code> between each run number for the <code>allin</code> <code>timeit</code> call)? I just want to be sure that I'm not accidentally forcing the numpy method to work in swap thus really slowing things down.</p> <p>(note that the numpy array take up about 60MB when it is loaded so it being loaded a single time will not push into swap but if it is loaded many times things may start pushing into swap).</p>
0
2016-08-17T19:37:23Z
39,005,118
<p>Since timeit is implemented in regular Python it's quite easy to see what it does: <a href="https://hg.python.org/cpython/file/2.7/Lib/timeit.py" rel="nofollow">https://hg.python.org/cpython/file/2.7/Lib/timeit.py</a></p> <p>To answer the question though, no, it will not execute a <code>del data</code> since that's not part of the statement or the setup method you are passing along to timeit. If you want that behaviour you should add it as a <code>setup</code> method.</p> <p>In this specific case you reassign to the same value which results in a new memory block each time since timeit disabled the garbage collector by default.</p>
0
2016-08-17T19:49:17Z
[ "python", "numpy", "timeit" ]
making an animation from a data file with matplotlib
39,004,963
<p>I have some c++ code which generates trajectories of particles. i. e. x and y coordinates of particles in different steps of simulations, in which the output file looks like this (for 4 particles):</p> <pre><code>#step0 1 2 3 4 5 6 7 8 #step1 1.2 2.2 3.2 4.3 5.2 6.4 7.2 8.5 ... </code></pre> <p>I want to make an animation with <strong>matplotlib</strong> by reading data from this file. For doing this I changed a python code, but it just produces blank image.</p> <pre><code>#!/usr/bin/python """ Animation of Elastic collisions with Gravity author: Jake Vanderplas email: vanderplas@astro.washington.edu website: http://jakevdp.github.com license: BSD Please feel free to use and modify this, but keep the above information. Thanks! """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation N_step = 2 N_particle = 4 class ParticleBox: """Orbits class init_state is an [N x 4] array, where N is the number of particles: [[x1, y1, vx1, vy1], [x2, y2, vx2, vy2], ... ] bounds is the size of the box: [xmin, xmax, ymin, ymax] """ def __init__(self, init_state = [[1, 0, 0, -1], [-0.5, 0.5, 0.5, 0.5], [-0.5, -0.5, -0.5, 0.5]], bounds = [-2, 2, -2, 2], size = 0.04): self.init_state = np.asarray(init_state, dtype=float) self.size = size self.state = self.init_state.copy() self.time_elapsed = 0 self.bounds = bounds def step(self, dt): """step once by dt seconds""" self.time_elapsed += dt **x,y = [], [] with open("traj.xyz") as f: lines = f.readlines() Data = lines[(N_particle + 1)*self.time_elapsed:N_particle+(N_particle + 1)*self.time_elapsed] for line in Data: row = line.split() x.append(row[0]) y.append(row[1]) # update positions self.state[:, 0] = x self.state[:, 1] = y #------------------------------------------------------------ # set up initial state np.random.seed(0) init_state = -0.5 + np.random.random((4, 4)) box = ParticleBox(init_state, size=0.04) dt = 1. #------------------------------------------------------------ # set up figure and animation fig = plt.figure() fig.subplots_adjust(left=0, right=1, bottom=0, top=1) axes = fig.add_subplot(111, aspect='equal') particles, = axes.plot([], [], 'bo') rect = plt.Rectangle(box.bounds[::2], box.bounds[1] - box.bounds[0], box.bounds[3] - box.bounds[2], ec='none', lw=2, fc='none') axes.add_patch(rect) axes.grid() axes.relim() axes.autoscale_view(True,True,True) #print x,y def init(): """initialize animation""" global box, rect particles.set_data([], []) rect.set_edgecolor('none') return particles, rect def animate(i): """perform animation step""" global box, rect, dt, axes, fig box.step(dt) # update pieces of the animation rect.set_edgecolor('k') particles.set_data(box.state[:, 0], box.state[:, 1]) particles.set_markersize(10) return particles, rect #plt.draw()????? ani = animation.FuncAnimation(fig, animate, frames=3, interval=10, blit=True, init_func=init) #ani.save('particle_box.mp4', fps=30, extra_args=['-vcodec', 'libx264']) plt.show() </code></pre>
0
2016-08-17T19:39:08Z
39,108,146
<p>you are using the default bounds of the box, that's why (assuming your data is similar to the first two data points you posted) nothing shows in the box.</p> <p>to fix this, change line 62 to something like this:</p> <p><code>box = ParticleBox(init_state,bounds = [-1, 10, -1, 10], size=0.04)</code></p>
0
2016-08-23T18:17:51Z
[ "python", "matplotlib", "visualization" ]
Flask server with MongoDB (flask-pymongo)
39,004,969
<p>I'm trying to set up a flask server which adds data/users to a mongoDB database. I set up the DB (using mongo shell) like so:</p> <pre><code>&gt;use dbname switched to dbname &gt;db.users.save( {username:"user", password:"pass"} ) WriteResult({ "nInserted" : 1 }) </code></pre> <p>And confirm the data is written with db.users.find().</p> <p>I added a mongo user like so:</p> <pre><code>&gt;use admin switched to db admin &gt;var w = { user:"user", roles:["readWriteAnyDatabase"], pwd:"password"} &gt;db.createUser(w) </code></pre> <p>My config.py looks like:</p> <pre><code>... MONGO_URI = 'mongodb://user:password@localhost:27017/dbname' </code></pre> <p>and my python looks like this:</p> <pre><code>from flask import render_template, flash, redirect, Flask from app import app from flask_pymongo import PyMongo from .forms import LoginForm appp = Flask(__name__) mongo = PyMongo(appp) @app.route('/login', methods=['GET', 'POST']) def login: form = LoginForm() if form.validate_on_submit(): user = {"username": form.username.data, "password": form.password.data} post_id = mongo.db.users.insert_one(user) flash('Login req: u=%s, p=%s' % (form.username.data, str(form.remember_me.data))) return redirect('/index') </code></pre> <p>I thought all was well but I got this when I tried it out:</p> <p><a href="http://i.stack.imgur.com/raRwp.png" rel="nofollow"><img src="http://i.stack.imgur.com/raRwp.png" alt="enter image description here"></a></p> <p>It appears to say something about the config_prefix? The docs say config_prefix is set to 'MONGO' by default and in my config the prefix is mongo. I must be missing something SOS</p>
0
2016-08-17T19:39:52Z
39,005,160
<p>You have a typo in</p> <pre><code>@app.route('/login', methods=['GET', 'POST']) </code></pre> <p>PyMongo uses current_app variable from flask which refers to the application instance handling the request. In this case <strong>app</strong> handles the request but <strong>appp</strong> has the configuration. So this line should become</p> <pre><code>@appp.route('/login', methods=['GET', 'POST']) </code></pre>
0
2016-08-17T19:52:28Z
[ "python", "mongodb" ]
Flask server with MongoDB (flask-pymongo)
39,004,969
<p>I'm trying to set up a flask server which adds data/users to a mongoDB database. I set up the DB (using mongo shell) like so:</p> <pre><code>&gt;use dbname switched to dbname &gt;db.users.save( {username:"user", password:"pass"} ) WriteResult({ "nInserted" : 1 }) </code></pre> <p>And confirm the data is written with db.users.find().</p> <p>I added a mongo user like so:</p> <pre><code>&gt;use admin switched to db admin &gt;var w = { user:"user", roles:["readWriteAnyDatabase"], pwd:"password"} &gt;db.createUser(w) </code></pre> <p>My config.py looks like:</p> <pre><code>... MONGO_URI = 'mongodb://user:password@localhost:27017/dbname' </code></pre> <p>and my python looks like this:</p> <pre><code>from flask import render_template, flash, redirect, Flask from app import app from flask_pymongo import PyMongo from .forms import LoginForm appp = Flask(__name__) mongo = PyMongo(appp) @app.route('/login', methods=['GET', 'POST']) def login: form = LoginForm() if form.validate_on_submit(): user = {"username": form.username.data, "password": form.password.data} post_id = mongo.db.users.insert_one(user) flash('Login req: u=%s, p=%s' % (form.username.data, str(form.remember_me.data))) return redirect('/index') </code></pre> <p>I thought all was well but I got this when I tried it out:</p> <p><a href="http://i.stack.imgur.com/raRwp.png" rel="nofollow"><img src="http://i.stack.imgur.com/raRwp.png" alt="enter image description here"></a></p> <p>It appears to say something about the config_prefix? The docs say config_prefix is set to 'MONGO' by default and in my config the prefix is mongo. I must be missing something SOS</p>
0
2016-08-17T19:39:52Z
39,005,488
<p>Kostas was correct. </p> <p>I changed:</p> <pre><code>appp = Flask(__name__) mongo = PyMongo(appp) </code></pre> <p>to simply</p> <pre><code>mongo = PyMongo(app) </code></pre>
1
2016-08-17T20:13:47Z
[ "python", "mongodb" ]
Inverting tridiagonal matrix
39,005,026
<p>I am having an equation</p> <p>Ax=By</p> <p>Where A and B are tridiagonal matrices. I want to calculate a matrix </p> <p>C=inv (A).B</p> <p>there are different x,s which will give different y,s hence calculation of C is handy. </p> <p>Can someone please tell me a faster method to compute the inverse. I am using Python 3.5 and prefer if we use any method from numpy. If not possible I can use scipy or cython as second and third choice. </p> <p>I have seen other similar questions but they do not fully match with my problem. </p> <p>Thank you </p>
-1
2016-08-17T19:43:29Z
39,015,683
<p>There are many method to do it, anyway one of the simplest is the Tridiagonal matrix algorithm see the <a href="https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm" rel="nofollow">Wiki page</a>. This algorithm work in O(n) time, there is a simple implementation in Numpy at the following <a href="https://gist.github.com/ofan666/1875903" rel="nofollow">Github link</a>. However, you may think to implement by yourself one of the known algorithm, for example something like a <a href="http://ekilic.etu.edu.tr/list/13Expinv.pdf" rel="nofollow">LU factorization </a> </p>
1
2016-08-18T10:21:04Z
[ "python", "performance", "sparse-matrix", "matrix-inverse" ]
What unit does scipy's kdtree function return distance in?
39,005,104
<p>I'm new to KD trees and I'm using them to find the nearest neighbour for each point in one array (search_array), compared with all the points in a second array (vec_array).</p> <p>Both arrays are formatted like so:</p> <pre><code>array([[ 51.54094696, 0.09767043], [ 51.53620148, 0.0798 ], [ 51.53620148, 0.0798 ], ..., [ 51.54118347, -0.08202313], [ 48.84996033, 2.32329845], [ 40.42570496, -3.70100427]]) </code></pre> <p>Here is my code:</p> <pre><code>def kdtree(search_points, vec_points): mytree = scipy.spatial.cKDTree(search_points) dist, indexes = mytree.query(vec_points) return indexes, dist result = kdtree(vec_array,search_array) </code></pre> <p>And the output:</p> <pre><code>(array([1361, 1339, 1339, ..., 1139, 1766, 1711]), array([ 0.01365104, 0.00059667, 0.00059667, ..., 0.00151025, 0.00754338, 0.00203098])) </code></pre> <p>The second array is clearly the distances but I can't work out what unit it is in, I'd be very grateful if somebody could enlighten me!</p>
0
2016-08-17T19:48:12Z
39,012,091
<p>As kindly indicated by Warren in the comment above, the units are the same as in the input array.</p>
0
2016-08-18T07:17:37Z
[ "python", "scipy", "spatial", "kdtree" ]
How to install packages with pip to python 2 when python 3 is the "defult"
39,005,114
<p>So I am using python 3 but, for a course I am taking I need to use python 2. So I installed it. Now I need to install a package called zmq. Before I just installed it by doing <code>pip install zmq</code> but how do I install this package to python 2? </p>
0
2016-08-17T19:49:05Z
39,005,313
<p>Generally pip installs not only the <code>pip</code> command but also the <code>pip2</code> and <code>pip2.7</code> command in your Path.</p> <p>So, to install within the Python 2 context use:</p> <pre><code>pip2 install &lt;package&gt; </code></pre> <p>And to install within the Python 3 context use:</p> <pre><code>pip3 install &lt;package&gt; </code></pre>
1
2016-08-17T20:02:19Z
[ "python", "python-2.7", "pip" ]
When should I store the result of a function as a variable in python?
39,005,133
<p>Suppose a function <code>my_list(obj)</code> returns a list. I want to write a function that returns the single element of <code>my_list(obj)</code> if this list has length one and <code>False</code> otherwise. My code is</p> <pre><code>def my_test(obj): if len(my_list(obj)) == 1: return my_list(obj)[0] return False </code></pre> <p>It just dawned on me that the code</p> <pre><code>def my_test(obj): L = my_list(obj) if len(L) == 1: return L[0] return False </code></pre> <p>might be more efficient since it only calls <code>my_list()</code> once. Is this true?</p> <p>The function <code>my_list()</code> could possibly be computationally intensive so I'm curious if there is a difference between these two blocks of code. I'd happily run a test myself but I'm not quite sure how to do so. I'm also curious if it is better practice in general to store the result of a function as a variable if the function is going to be called more than once.</p>
1
2016-08-17T19:50:00Z
39,005,356
<p>To answer your question on whether it is generally better to store the result of a function as a variable if it is going to be called more than once: it depends. In terms of readability, it's really up to you as a programmer. In terms of speed, storing the result in a variable is generally faster than running the function twice.</p> <p>Storing the result can, however, uses memory, and if you're storing an unusually large variable, the memory usage can actually lead to longer running time than simply calling the function. Further, as noted above, running a function can do more than just storing the result in a variable, so running a function a different number of times can give a different result. </p>
2
2016-08-17T20:05:10Z
[ "python" ]
When should I store the result of a function as a variable in python?
39,005,133
<p>Suppose a function <code>my_list(obj)</code> returns a list. I want to write a function that returns the single element of <code>my_list(obj)</code> if this list has length one and <code>False</code> otherwise. My code is</p> <pre><code>def my_test(obj): if len(my_list(obj)) == 1: return my_list(obj)[0] return False </code></pre> <p>It just dawned on me that the code</p> <pre><code>def my_test(obj): L = my_list(obj) if len(L) == 1: return L[0] return False </code></pre> <p>might be more efficient since it only calls <code>my_list()</code> once. Is this true?</p> <p>The function <code>my_list()</code> could possibly be computationally intensive so I'm curious if there is a difference between these two blocks of code. I'd happily run a test myself but I'm not quite sure how to do so. I'm also curious if it is better practice in general to store the result of a function as a variable if the function is going to be called more than once.</p>
1
2016-08-17T19:50:00Z
39,005,402
<p>You are correct. The second block would be more efficient since it only calls <code>my_list()</code> once. If <code>my_list()</code> isn't particularly computationally expensive, it's unlikely you will notice a difference at all. If you know it will be expensive, on the other hand, it is a good idea to save the result where you can if it does not hamper readability (however, note the caveat in <a href="http://stackoverflow.com/a/39005356/919057">@Checkmate's answer</a> about memory for a possible exception).</p> <p>However, if <code>my_list()</code> has <a href="http://programmers.stackexchange.com/questions/40297/what-is-a-side-effect">side effects</a>, or if it's return value may change between those two invocations, you may not want to save it (depends on if you want to trigger the side effects twice or need to receive the changed return value). </p> <p>If you wanted to test this yourself, you could use <code>time.time</code> like <a href="http://stackoverflow.com/a/2866456/919057">this</a>:</p> <pre><code>import time t0 = time.time() my_test() t1 = time.time() total = t1-t0 </code></pre> <p>to get the time for <code>my_test()</code>. Just run both functions and compare their time.</p>
3
2016-08-17T20:08:13Z
[ "python" ]
Inline User Data Input Manipulation for Query Selection | Python
39,005,165
<p>I am in the process of developing a troubleshooting application in Python that will allow a user to input a query. This query would contain the brand of the device and the issue or symptom of their problem. I am in the process of writing a script which essentially dissects the query to find an appropriate solution following keywords and brands of the device.</p> <p>Current Code: #Import Modules import warnings</p> <pre><code>#Define Globals brands = ["apple", "android", "windows"] brand = '' def Main(): init() print("--Welcome to Troubleshooting Applet--") print("In your query please include the brand of your device and the problem / symptom of your current issue. \n") query = input("Enter your query: ").lower() brand = set(brands).intersection(query.split()) if brand != '': print(brand) else: print("Brand in existance not defined") def init(): #warnings.filterwarnings("ignore") #Disable while debugging if __name__ == '__main__': Main() </code></pre> <p>Currently, the script will identify a brand, but I am not certain on how to check for a wide number of keywords in order to follow a solution route. I would expect the solution to follow the pattern of having selected a brand a secondary array specific for the brand which would contain a number of potential errors. Each of these errors could have a solution defined.</p> <p>I would appreciate any insight,</p> <p>Thanks,</p> <p>Sam</p>
1
2016-08-17T19:52:49Z
39,048,423
<p><strong>Run this</strong> I hope this gives you some ideas. You need to fix your indentation for the <code>main():</code> function.</p> <pre><code>#Define Globals brands = ["apple", "android", "windows"] brand = '' import random def Main(): init() print("--Welcome to Troubleshooting Applet--") print("In your query please include the brand of your device and the problem / symptom of your current issue. \n") query = input("Enter your query: ").lower() brand = set(brands).intersection(query.split()) keywords = ['custom security keywords collection', 'item2', 'key3'] index = 0 for i in range(len(query)): if query.__contains__(keywords[index]): # __iter__() # could use 'in' keyword here #switch/decide text = 'run decision' print(keywords[index]) else: if len(keywords) &lt; 3: index = index + 1 text1 = 'continue' # OR # Test keyword idea... tKeyword = random.choice(keywords) # You need a lot of work to come up with error decisions right? # You may need to start pulling from a Database and checking against large documents? # just trying to come up with something to get you going print ('RANDOM keyword for TESTING:' + tKeyword) if brand != '': print(brand) else: print("Brand in existance not defined") def init(): ftp = 0 #warnings.filterwarnings("ignore") #Disable while debugging if __name__ == '__main__': Main() print('ask yourself about escape sequences and encoding for the query? \+' ' I believe utf-8 is the default encoding for python 3') def dbconnect(): url = "http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python" url1 = "https://docs.python.org/3/reference/datamodel.html#object.__contains__" url2 = "مرحبا I think python is very unicode friendly.." </code></pre>
0
2016-08-19T22:19:55Z
[ "python", "user-interface", "user-input", "conditional-operator" ]
Set value for particular cell in pandas DataFrame
39,005,183
<p>This question is similar to <a href="http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe">this question</a> posted earlier. The difference is that I want to change value in a cell that index column is not unique. For example:</p> <pre><code> x y A 1 5 B 4 6 C 0 3 C 5 9 </code></pre> <p>I want to replace 9 with 100 and get:</p> <pre><code> x y A 1 5 B 4 6 C 0 3 C 5 100 </code></pre> <p>Any suggestions?</p>
0
2016-08-17T19:53:35Z
39,005,334
<p>You could go for the ordinal indexes (they are always unique) like so:</p> <pre><code>In [13]: df.iloc[3, 1] = 100 In [14]: df Out[14]: x y A 1 5 B 4 6 C 0 3 C 5 100 </code></pre>
1
2016-08-17T20:03:45Z
[ "python", "pandas" ]
Slicing a list of dictionaries and removing one key
39,005,241
<p>I have a list of dictionaries, like the one below:</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] </code></pre> <p>Now, I want to slice it and have a list only with dictionaries where the key <code>a</code> has value <code>10</code>, but removing the key <code>a</code> from the dictionary. Like the list below:</p> <pre><code>nl = [ { "b": 4, "c": 6 }, { "b": 6, "c": 8 } ] </code></pre> <p>I can do this by processing <code>l</code> twice:</p> <pre><code>l[:] = [d for d in l if d.get("a") == 10] nl = [] for c in l: del c["a"] nl.append(c) </code></pre> <p>Is there a more straightforward way to accomplish this?</p>
0
2016-08-17T19:57:53Z
39,005,337
<p>There may be a better way, but you can do a nested dict comprehension:</p> <pre><code>[{k:d[k] for k in d if k!="a"} for d in l if d.get("a") == 10] </code></pre>
6
2016-08-17T20:04:02Z
[ "python", "list", "dictionary", "slice" ]
Slicing a list of dictionaries and removing one key
39,005,241
<p>I have a list of dictionaries, like the one below:</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] </code></pre> <p>Now, I want to slice it and have a list only with dictionaries where the key <code>a</code> has value <code>10</code>, but removing the key <code>a</code> from the dictionary. Like the list below:</p> <pre><code>nl = [ { "b": 4, "c": 6 }, { "b": 6, "c": 8 } ] </code></pre> <p>I can do this by processing <code>l</code> twice:</p> <pre><code>l[:] = [d for d in l if d.get("a") == 10] nl = [] for c in l: del c["a"] nl.append(c) </code></pre> <p>Is there a more straightforward way to accomplish this?</p>
0
2016-08-17T19:57:53Z
39,005,366
<p>Maybe you can use the functions filter and map for readability and immutability.</p> <p>Example (I didn't test it):</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] l_filtered = filter(lambda x: x.get('a') == 10, l) l_filtered_without_a = map(lambda x: {'b': x.get('b'), 'c': x.get('c')}, l_filtered) </code></pre>
1
2016-08-17T20:05:39Z
[ "python", "list", "dictionary", "slice" ]
Slicing a list of dictionaries and removing one key
39,005,241
<p>I have a list of dictionaries, like the one below:</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] </code></pre> <p>Now, I want to slice it and have a list only with dictionaries where the key <code>a</code> has value <code>10</code>, but removing the key <code>a</code> from the dictionary. Like the list below:</p> <pre><code>nl = [ { "b": 4, "c": 6 }, { "b": 6, "c": 8 } ] </code></pre> <p>I can do this by processing <code>l</code> twice:</p> <pre><code>l[:] = [d for d in l if d.get("a") == 10] nl = [] for c in l: del c["a"] nl.append(c) </code></pre> <p>Is there a more straightforward way to accomplish this?</p>
0
2016-08-17T19:57:53Z
39,005,376
<p>Similar to <a href="http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary">This question</a> on SO for element removal from dictionary. The rest is straightforward.</p> <pre><code>[ {i:elem[i] for i in elem if i!="a"} for elem in l if elem["a"] == 10] </code></pre> <p>Returns</p> <blockquote> <p>[{'b': 4, 'c': 6}, {'b': 6, 'c': 8}]</p> </blockquote>
1
2016-08-17T20:06:09Z
[ "python", "list", "dictionary", "slice" ]
Slicing a list of dictionaries and removing one key
39,005,241
<p>I have a list of dictionaries, like the one below:</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] </code></pre> <p>Now, I want to slice it and have a list only with dictionaries where the key <code>a</code> has value <code>10</code>, but removing the key <code>a</code> from the dictionary. Like the list below:</p> <pre><code>nl = [ { "b": 4, "c": 6 }, { "b": 6, "c": 8 } ] </code></pre> <p>I can do this by processing <code>l</code> twice:</p> <pre><code>l[:] = [d for d in l if d.get("a") == 10] nl = [] for c in l: del c["a"] nl.append(c) </code></pre> <p>Is there a more straightforward way to accomplish this?</p>
0
2016-08-17T19:57:53Z
39,005,382
<p>Seems to me that you're working too hard to make this a one-liner. Create two empty lists and append each dict to one or the other depending on the value of the <code>a</code> key.</p> <pre><code>&gt;&gt;&gt; l = [ { "a": 10, "b": 4, "c": 6 }, ... { "a": 10, "b": 6, "c": 8 }, ... { "a": 13, "b": 3, "c": 9 }, ... { "a": 12, "b": 5, "c": 3 }, ... { "a": 11, "b": 7, "c": 1 } ] &gt;&gt;&gt; l1 = [] &gt;&gt;&gt; nl = [] &gt;&gt;&gt; for d in l: ... targetList = l1 if d.get('a') == 10 else nl ... targetList.append(d) &gt;&gt;&gt; l1 [{'a': 10, 'c': 6, 'b': 4}, {'a': 10, 'c': 8, 'b': 6}] &gt;&gt;&gt; nl [{'a': 13, 'c': 9, 'b': 3}, {'a': 12, 'c': 3, 'b': 5}, {'a': 11, 'c': 1, 'b': 7}] &gt;&gt;&gt; </code></pre>
0
2016-08-17T20:06:37Z
[ "python", "list", "dictionary", "slice" ]
Slicing a list of dictionaries and removing one key
39,005,241
<p>I have a list of dictionaries, like the one below:</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] </code></pre> <p>Now, I want to slice it and have a list only with dictionaries where the key <code>a</code> has value <code>10</code>, but removing the key <code>a</code> from the dictionary. Like the list below:</p> <pre><code>nl = [ { "b": 4, "c": 6 }, { "b": 6, "c": 8 } ] </code></pre> <p>I can do this by processing <code>l</code> twice:</p> <pre><code>l[:] = [d for d in l if d.get("a") == 10] nl = [] for c in l: del c["a"] nl.append(c) </code></pre> <p>Is there a more straightforward way to accomplish this?</p>
0
2016-08-17T19:57:53Z
39,005,489
<p>I think I've got a pretty cool one-liner that should be very fast and works whether or not <code>a</code> is in the dictionary. It relies on the fact that popping from a dictionary returns the value of the key (or none if key is not present) as well as removes the entry. Note that it does mutate <code>l</code> though.</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "q": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] ret = [d for d in l if "a" in d.keys() and d.pop("a") == 10] print ret &gt;&gt;[{'c': 6, 'b': 4}, {'c': 8, 'b': 6}] </code></pre>
2
2016-08-17T20:13:51Z
[ "python", "list", "dictionary", "slice" ]
Slicing a list of dictionaries and removing one key
39,005,241
<p>I have a list of dictionaries, like the one below:</p> <pre><code>l = [ { "a": 10, "b": 4, "c": 6 }, { "a": 10, "b": 6, "c": 8 }, { "a": 13, "b": 3, "c": 9 }, { "a": 12, "b": 5, "c": 3 }, { "a": 11, "b": 7, "c": 1 } ] </code></pre> <p>Now, I want to slice it and have a list only with dictionaries where the key <code>a</code> has value <code>10</code>, but removing the key <code>a</code> from the dictionary. Like the list below:</p> <pre><code>nl = [ { "b": 4, "c": 6 }, { "b": 6, "c": 8 } ] </code></pre> <p>I can do this by processing <code>l</code> twice:</p> <pre><code>l[:] = [d for d in l if d.get("a") == 10] nl = [] for c in l: del c["a"] nl.append(c) </code></pre> <p>Is there a more straightforward way to accomplish this?</p>
0
2016-08-17T19:57:53Z
39,005,606
<p>It can be done in a one-liner with map/filter</p> <pre><code>res = [elem for elem in map(lambda x:{k:v for k,v in x.items() if k != 'a'}, [e for e in filter(lambda y:y.get('a') != 10,a)])] </code></pre>
0
2016-08-17T20:21:14Z
[ "python", "list", "dictionary", "slice" ]
Install rpy2 inside virtualenv (can't find library)
39,005,256
<p>I have a Python virtualenv set up with <a href="https://github.com/yyuu/pyenv-virtualenv" rel="nofollow">pyenv-virtualenv</a>. I installed the <a href="https://www.r-project.org/" rel="nofollow">R statistical software</a>, and now I need to install the <a href="https://rpy2.readthedocs.io" rel="nofollow">rpy2</a> package to allow communication between Python and R.</p> <p>Both Python v2.7.12 and R version 3.3.1 (2016-06-21) are installed.</p> <p>Attempting to install <code>rpy2</code> with <code>pip install rpy2</code> fails with:</p> <pre><code> /usr/bin/ld: no se puede encontrar -llzma collect2: error: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/home/gabriel/.pyenv/versions/2.7.12/envs/test-env/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-b7O2v3/rpy2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-4SXyxe-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/gabriel/.pyenv/versions/2.7.12/envs/asteca-env/include/site/python2.7/rpy2" failed with error code 1 in /tmp/pip-build-b7O2v3/rpy2/ </code></pre> <p><code>no se puede encontrar -llzma</code> means <code>can't find -llzma</code>.</p> <p><code>python-dev</code> is already installed in my system.</p> <p>How can I bypass this issue?</p>
0
2016-08-17T19:58:50Z
39,229,335
<p>I finally could install the package successfully.</p> <p>The issue was that I had installed the <code>python-dev</code> library <em>after</em> the <code>virtualenv</code> was created. This caused the installation of the <code>rpy2</code> package to fail.</p> <p>The solution was to uninstall the <code>virtualenv</code> and create again from scratch.</p>
0
2016-08-30T13:49:06Z
[ "python", "rpy2" ]
Are all functionalities of ggplot2 available in Python?
39,005,267
<p>the title is actually my question. I googled quite a bit, checked Quora and searched through Stackoverflow. Since I couldn't find an answer to my question I think the question is warranted.</p> <p>So basically my question is twofold:</p> <p>1) are all the ggplot2 functionalities available in python (especially jupyter notebook)?</p> <p>2) If yes, can the R tutorials applied directly?</p> <p>Kind regards Fabian</p>
-1
2016-08-17T19:59:28Z
39,005,568
<p>According to my knowledge, the answer is no. In Jupyter Notebook, however, you can interface with R. In brief, do your calculations in Python and then plot using R in the same notebook. For details, check out this <a href="https://github.com/cliburn/sta-663-2016/blob/master/lectures/18B_Foreing_Language_Interface.ipynb" rel="nofollow">notebook</a>.</p> <p>However, if you are going to use python, you might as well learn matplotlib - the canonical python library for graphing. In my opinion, it's a bit more flexible and it is quite similar to Matplot's plotting functionalities. </p>
1
2016-08-17T20:19:08Z
[ "python", "ggplot2", "jupyter-notebook" ]
Subset rows by partially matching two columns for words greater than n characters
39,005,274
<p>I would be open to doing this in python pandas, but in R I have the following df:</p> <pre><code> result&lt;-structure(list(traffic_Count_Street = c("San Angelo", "W Commerce St", "W Commerce St", "S Gevers St", "Austin Hwy", "W Evergreen St" ), unit_Street = c("San Pedro Ave", "W Commerce", "W Commerce", "S New Braunfels", "Austin Highway", "W Cypress")), .Names = c("traffic_Count_Street", "unit_Street"), row.names = c(1L, 17L, 18L, 34L, 260L, 273L), class = "data.frame") 1 San Angelo San Pedro Ave 17 W Commerce St W Commerce 18 W Commerce St W Commerce 34 S Gevers St S New Braunfels 260 Austin Hwy Austin Highway 273 W Evergreen St W Cypress </code></pre> <p>For each row I want to partially match column 1 to 2 if one of the words, greater than 3 characters, matches another.</p> <p>I would remove:</p> <pre><code>1 San Angelo San Pedro Ave 34 S Gevers St S New Braunfels 273 W Evergreen St W Cypress </code></pre> <p>and keep:</p> <pre><code>17 W Commerce St W Commerce 18 W Commerce St W Commerce 260 Austin Hwy Austin Highway </code></pre> <p>I tried using <code>stringR</code> in the following way but it did not work:</p> <p><code>result$unit_Street[str_detect(result$traffic_Count_Street, "\\w{3}")]</code></p>
2
2016-08-17T19:59:47Z
39,005,538
<p>Create a distance filter that has a threshold adjustment. Then you can adjust until you are getting the results you want. A Levenshtein distance of 5 worked well in this case:</p> <pre><code>distanceFilter &lt;- function(df, thresh=5) { ind &lt;- apply(df, 1, function(x) adist(x[1], x[2]) &lt; thresh ) df[ind,] } distanceFilter(result, 5) # traffic_Count_Street unit_Street # 17 W Commerce St W Commerce # 18 W Commerce St W Commerce # 260 Austin Hwy Austin Highway </code></pre> <p>To learn more, see <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">the wiki page</a> and the <a href="https://stat.ethz.ch/R-manual/R-devel/library/utils/html/adist.html" rel="nofollow">R doc help page</a></p>
1
2016-08-17T20:17:03Z
[ "python", "regex", "pandas", "stringr" ]
Longest Common Subsequence Python 2 function
39,005,328
<p>When I run LCS( 'human', 'chimp' ), I'm getting "h" instead of "hm". When I run LCS( 'gattaca', 'tacgaacta' ), I'm getting "g" instead of "gaaca". When I run LCS( 'wow', 'whew' ), I'm getting "ww" which is correct. When I run LCS( '', 'whew' ), I'm getting "" which is correct. When I run LCS( 'abcdefgh', 'efghabcd' ), I'm getting "a" instead of "abcd". What am I doing incorrectly?</p> <p>Here is my code:</p> <pre><code>def LCS(S, T): array = '' i = 0 j = 0 while i &lt; len(S): while j &lt; len(T): if S[i] == T[j]: array += S[i] j += 1 i += 1 return array </code></pre>
0
2016-08-17T20:03:15Z
39,005,562
<p>That is not how you write LCS. This is how you write very weird function that calculates the number of letters in the second string that are equal to the first letter of the first string.</p> <p>I believe what you meant to write is wrong, so that does not matter, but if I correctly guessed what you meant to write, you forgot to assign 0 to j inside the outer while loop.</p>
0
2016-08-17T20:18:57Z
[ "python", "python-2.7", "lcs" ]
Longest Common Subsequence Python 2 function
39,005,328
<p>When I run LCS( 'human', 'chimp' ), I'm getting "h" instead of "hm". When I run LCS( 'gattaca', 'tacgaacta' ), I'm getting "g" instead of "gaaca". When I run LCS( 'wow', 'whew' ), I'm getting "ww" which is correct. When I run LCS( '', 'whew' ), I'm getting "" which is correct. When I run LCS( 'abcdefgh', 'efghabcd' ), I'm getting "a" instead of "abcd". What am I doing incorrectly?</p> <p>Here is my code:</p> <pre><code>def LCS(S, T): array = '' i = 0 j = 0 while i &lt; len(S): while j &lt; len(T): if S[i] == T[j]: array += S[i] j += 1 i += 1 return array </code></pre>
0
2016-08-17T20:03:15Z
39,054,886
<p>Figured it out thanks to the people next to me in the lab! It would also be nice to not run into snooty people on Stack Overflow every now and then.</p> <pre><code>def LCS(S, T): # If either string is empty, stop if len(S) == 0 or len(T) == 0: return "" # First property if S[-1] == T[-1]: return LCS(S[:-1], T[:-1]) + S[-1] # Second proprerty # Last of S not needed: result1 = LCS(S[:-1], T) # Last of T not needed result2 = LCS(S, T[:-1]) if len(result1) &gt; len(result2): return result1 else: return result2 </code></pre>
0
2016-08-20T13:53:15Z
[ "python", "python-2.7", "lcs" ]
What is the best user-friendly way to package up a python script into an executable?
39,005,363
<p>I'm new to python and am writing a web scraping script for some coworkers that will scrape data off of a given webpage and package up into a .csv for them. What is the best way to package up this script so that they can just click on it and maybe enter some search terms then let it run and produce a .csv?</p> <p>Thanks! Let me know if any clarification is needed, this is my first question!</p>
2
2016-08-17T20:05:36Z
39,005,527
<p>For Windows: </p> <p>If your coworkers have Python itself installed, you could simply write a simple batch script which executes</p> <pre><code>python myscript.py </code></pre> <p>You can then provide them the *.py and *.bat file.</p> <p>If you want to build an *.exe from your Python script, take a look at <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a>. I found it fairly easy to use and it has a good documentation. It also offers the ability to package your application into a single file, and your coworkers don't have to install Python itself.</p> <p>For Linux:</p> <p>Add a shebang in the first line of your script to make it executable, see <a href="http://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take">this StackOverflow question</a>.</p>
0
2016-08-17T20:16:21Z
[ "python", "user-interface", "scripting" ]
What is the best user-friendly way to package up a python script into an executable?
39,005,363
<p>I'm new to python and am writing a web scraping script for some coworkers that will scrape data off of a given webpage and package up into a .csv for them. What is the best way to package up this script so that they can just click on it and maybe enter some search terms then let it run and produce a .csv?</p> <p>Thanks! Let me know if any clarification is needed, this is my first question!</p>
2
2016-08-17T20:05:36Z
39,012,774
<p>A better solution would be taking arguments while running your python script. The only parameter would be the url of the target webpage. Check this SO <a href="http://stackoverflow.com/questions/4033723/how-do-i-access-command-line-arguments-in-python">answer</a> for getting parameters.</p> <p>My approach would be creating a simple HTML page that has a textbox takes target url, when user hits scrape button, it would trigger .py script, return csv file in the same directory. Check <a href="http://stackoverflow.com/questions/26792899/run-python-script-with-html-button">this</a> out. You can archive it and email coworkers. Make sure that owner of the script is current user that is running OS.</p>
1
2016-08-18T07:59:19Z
[ "python", "user-interface", "scripting" ]
When using Docker Containers, where are shared Python libraries stored?
39,005,380
<p>In an environment where Docker Containers are used for each application, where are Python's shared libraries stored? Are they stored separately within each Docker Container, or shared by the host O/S?</p> <p>Additionally I'm wondering if it would be best practice to use a virtual environment regardless?</p>
2
2016-08-17T20:06:30Z
39,005,477
<p>Just like everything else in a Docker Container, your libraries are inside the container. Unless you mount a host volume, or a volume from another container of course. On the plus side, though, they're copy-on-write, so if you're not making changes to the libraries in your container (why would you do that anyway?) then you can have 100 running containers from the same image and they don't require any extra disk space.</p> <p><em>Some</em> people advocate for using a virtualenv within the container - there are pros and cons to the approach, and I don't think there's a one-sized-fits-all answer, though I would lean for not having a virtualenv.</p>
3
2016-08-17T20:13:15Z
[ "python", "docker", "virtualenv" ]
FMU Variable Values Do Not Match Input
39,005,445
<p>I'm getting some strange behavior in a simple co-simulation that I'm trying to configure. I setup a building energy model in EnergyPlus to test out an FMU generated from JModelica. However, the building energy model would get hung up at the co-simulation step. I then ran the FMU in JModelica and got some very strange results.</p> <p>The Modelica code is:</p> <pre><code>model CallAdd input Real FirstInput(start=0); input Real SecondInput(start=0); output Real FMUOutput(start=0); function CAdd input Real x(start=0); input Real y(start=0); output Real z(start=0); external "C" annotation(Library = "CAdd", LibraryDirectory = "modelica://CallAdd"); end CAdd; equation FMUOutput = CAdd(FirstInput,SecondInput); annotation(uses(Modelica(version = "3.2.1"))); end CallAdd; </code></pre> <p>The above code references "CAdd" which is library file for the c code "CAdd.c":</p> <pre><code>double CAdd(double x, double y){ double answer; answer = x + y; return answer; } </code></pre> <p>which is compiled into a library file with the below two commands in CMD:</p> <pre><code>gcc -c CAdd.c -o CAdd.o ar rcs libCAdd.a CAdd.o </code></pre> <p>I can run the above example in OpenModelica with a wrapper and it works great.</p> <p>I then used JModelica to compile the above as an FMU for co-simulation. The JModelica compile code is:</p> <pre><code># Import the compiler function from pymodelica import compile_fmu # Specify Modelica model and model file (.mo or .mop) model_name = "CallAdd" mo_file = "CallAdd.mo" # Compile the model and save the return argument, for use later if wanted my_fmu = compile_fmu(model_name, mo_file, target="cs") </code></pre> <p>I then simulated the FMU and got the strange results with the JModelica Python code:</p> <pre><code>from pyfmi import load_fmu import numpy as np import matplotlib.pyplot as plt modelName = 'CallAdd' numSteps = 100 timeStop = 20 # Load FMU created with the last script myModel = load_fmu(modelName+'.fmu') # Load options opts = myModel.simulate_options() # Set number of timesteps opts['ncp'] = numSteps # Set up input, needs more than one value to interpolate the input over time. t = np.linspace(0.0,timeStop,numSteps) u1 = np.sin(t) u2 = np.empty(len(t)); u2.fill(5.0) u_traj = np.transpose(np.vstack((t,u1,u2))) input_object = (['FirstInput','SecondInput'],u_traj) # Internalize results res = myModel.simulate(final_time=timeStop, input = input_object, options=opts) # print 'res: ', res # Internalize individual results FMUTime = res['time'] FMUIn1 = res['FirstInput'] FMUIn2 = res['SecondInput'] FMUOut = res['FMUOutput'] plt.figure(2) FMUIn1Plot = plt.plot(t,FMUTime[1:],label='FMUTime') # FMUIn1Plot = plt.plot(t,FMUIn1[1:],label='FMUIn1') # FMUIn2Plot = plt.plot(t,FMUIn2[1:],label='FMUIn2') # FMUOutPlot = plt.plot(t,FMUOut[1:],label='FMUOut') plt.grid(True) plt.legend() plt.ylabel('FMU time [s]') plt.xlabel('time [s]') plt.show() </code></pre> <p>which resulted in the plot for result "FMUTime" vs python "t": <a href="http://i.stack.imgur.com/mev2P.png" rel="nofollow"><img src="http://i.stack.imgur.com/mev2P.png" alt="FMU Time does not match simulation time"></a></p> <p>In addition to seeing this strange behavior the input "FirstInput" and "SecondInput" in the FMU results do not match the u1 and u2 specified in the python code. I'm hoping that someone can help me better understand what is going on.</p> <p>Best, </p> <p>Justin </p>
1
2016-08-17T20:11:27Z
39,134,843
<p>Following @ChristianAndersson's suggestion to update my JModelica installation the problem described in my question above was solved. </p> <p>JModelica 1.17.0 was release in December, 2015. </p> <p>JModelica-SDK-1.12.0 was released in February, 2016 and is built from the source code, which fixed the problem and provided me with the expected results. </p>
0
2016-08-25T00:15:08Z
[ "python", "c", "modelica", "fmi", "jmodelica" ]
can't call an existing function from python shell
39,005,456
<p>I have a python/django project, with a django app called <code>"testApp"</code>. under <code>"testApp"</code> I have a python file: <code>"hello.py"</code>. The file reads:</p> <pre><code>class Hello(): def sayHello(): print ("hello") </code></pre> <p>How can I activate the <code>sayHello</code> function from <code>python manage.py shell</code></p> <p>importing <code>"testApp"</code> doesn't help as calling <code>"Hello.sayHello()"</code> gives out an <code>undefined</code> error.</p> <p>What am I doing wrong?</p>
0
2016-08-17T20:12:06Z
39,005,733
<p>You need to import the actual name you want to use. Just importing testApp won't do anything; you would need to do <code>from testApp.hello import Hello</code>.</p> <p>Note also that since for some reason you have a class, <code>sayHello</code> is an instance method and therefore needs to accept the <code>self</code> parameter; also, you would need to instantiate the class before calling the method. However, Python is not Java, and there is absolutely no need for the Hello class to exist.</p>
1
2016-08-17T20:29:36Z
[ "python", "django" ]
render two seaborn figure objects in same ipython cell
39,005,461
<p>I have two matplotlib (seaborn) figure objects both made in different ipython cells.</p> <pre><code>#One Cell fig_1_object = sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_d_fam) fig_1 = fig_1_object.fig #Two Cell fig_2_object = sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_c_fam) fig_2 = fig_2_object.fig </code></pre> <p>How can I "show" them one after another in the same cell. I have matplotlib inline turned on.</p> <pre><code>#third cell fig_1 fig_2 &gt;&gt;Only shows fig_2 </code></pre>
0
2016-08-17T20:12:24Z
39,027,892
<p>You just need to import the <code>display</code> function from the <code>IPython.display</code> module:</p> <pre><code>from IPython.display import display import seaborn %matplotlib inline g1 = seaborn.factorplot(**options1) g2 = seaborn.factorplot(**options2) display(g1) display(g2) </code></pre>
2
2016-08-18T21:36:27Z
[ "python", "matplotlib", "ipython", "jupyter-notebook", "seaborn" ]
Python: How to modify values in nested dictionary and have the whole dict returned
39,005,474
<p>Imagine that I have got a file named 'test_dict.txt' containing the following dictionary-like text:</p> <pre><code>{ "subdic1" : { "a_string" : "something1", "a_integer" : 16, "a_list" : [ "str_1", "str_2" ] }, "subdic2" : { "a_string" : "something2", "a_integer" : 32, "a_list" : [ "str_3", "str_4" ] } } </code></pre> <p>As you can see that there are nested dictionaries. What I want to do is to convert all deepest values ("something1", 16, ["str_1", "str_2"], etc) to unicode type objects, for some comparison purposes. Here is my attempt:</p> <pre><code>import json from copy import deepcopy def to_unicode(d): dc = deepcopy(d) for k,v in dc.iteritems(): if isinstance(v, dict): to_unicode(v) else: dc[k] = unicode(v) return dc dict_fname = 'test_dict.txt' with open(dict_fname) as dict_fd: dic = json.load(dict_fd) print dic print to_unicode(dic) </code></pre> <p>I used recursion in my function 'to_unicode' in order to traverse to the deepest values. The first 'print' gives the result of 'json.load' operation like the following:</p> <pre><code>{u'subdic1': {u'a_list': [u'str_1', u'str_2'], u'a_integer': 16, u'a_string': u'something1'}, u'subdic2': {u'a_list': [u'str_3', u'str_4'], u'a_integer': 32, u'a_string': u'something2'}} </code></pre> <p>So what I should really convert to unicode type is the two integers 16 and 32. But I still want the function to convert each value inside each level of dictionary for the purpose of simplicity. The two numbers are supposed to be converted to u'16' and u'32', so the dictionary object returned by the function should be printed like this:</p> <pre><code>{u'subdic1': {u'a_list': [u'str_1', u'str_2'], u'a_integer': u'16', u'a_string': u'something1'}, u'subdic2': {u'a_list': [u'str_3', u'str_4'], u'a_integer': u'32', u'a_string': u'something2'}} </code></pre> <p>But in fact my second 'print' gives the exactly same result as the first one. I guess the issue occurs either in deepcopy or in the way of return of the function, or even both. I really want the whole dictionary to be returned back after the conversion, rather than yielding one item a time. Could somebody help correcting my code please?</p>
0
2016-08-17T20:13:01Z
39,006,115
<p>As @jonrsharpe mentioned you just need to assign things back to the master or original copy. Here's some spaghetti that iterates on the code you've provided : </p> <pre><code>def to_unicode(d, target_dict={}): for k,v in d.iteritems(): if isinstance(v, dict): target_dict = to_unicode(v, target_dict) else: target_dict[k] = unicode(v) return target_dict </code></pre>
0
2016-08-17T20:55:08Z
[ "python", "dictionary", "unicode" ]
Sending HTTP requests concurrently
39,005,564
<p>I'm looking to send 100K-300K POST requests to an API Endpoint - these requests are originating from a list of JSON objects that I'm iterating over. Unfortunately, the maximum chunk size I'm able to use is 10 events at a time which is greatly decreasing the speed of sending off all the events I want. After I have my list of JSON objects defined:</p> <pre><code>chunkSize= 10 for i in xrange(0, len(list_of_JSON), chunkSize): chunk = list_of_JSON[i:i+chunkSize] #10 endpoint = "" d_profile = "[" + ",".join(json.dumps(x) for x in chunk) + "]" str_event = d_profile try: url = base_api + endpoint + "?api_key=" + api_key + "&amp;event=" + str_event r = requests.post(url) print r.content print i except: print 'failed' </code></pre> <p>This process works extremely slowly to send off the events. I've looked up the possibility of multithreading/concurrency/and parallel processing although I'm completely new to the topic. After some research, I've come up with this ugly snippit: </p> <pre><code>import logging import threading import time logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-10s) %(message)s', ) def worker(): logging.debug('Starting') import time chunkSize= 10 for i in xrange(0, (len(list_of_JSON)/2), chunkSize): chunk = list_of_JSON[i:i+chunkSize] #10 endpoint = "" d = "[" + ",".join(json.dumps(x) for x in chunk) + "]" str_event = d try: url = base_api + endpoint + "?api_key=" + api_key + "&amp;event=" + str_event r = requests.post(url) print r.content print i except: print 'failed' time.sleep(2) logging.debug('Exiting') def my_service(): logging.debug('Starting') import time chunkSize= 10 for i in xrange(((len(list_of_JSON)/2)+1), len(list_of_JSON), chunkSize): chunk = list_of_JSON[i:i+chunkSize] #10 endpoint = "" d = "[" + ",".join(json.dumps(x) for x in chunk) + "]" str_event = d try: url = base_api + endpoint + "?api_key=" + api_key + "&amp;event=" + str_event r = requests.post(url) print r.content print i except: print 'failed' time.sleep(3) logging.debug('Exiting') t = threading.Thread(target=my_service) w = threading.Thread(target=worker) w.start() t.start() </code></pre> <p>Would appreciate any suggestions or refactoring.</p> <p>Edit: I believe my implementation accomplishes what I want. I've looked over <a href="http://stackoverflow.com/questions/2632520/what-is-the-fastest-way-to-send-100-000-http-requests-in-python">What is the fastest way to send 100,000 HTTP requests in Python?</a> but am still unsure of how pythonic or efficient this solution is. </p>
1
2016-08-17T20:18:59Z
39,007,115
<p>You could use scrapy, which uses twisted (as suggested in the comments). Scrapy is a framework intended for scraping web pages, but you can use it to send <code>post</code> requests too. A spider that achieves the same as your code would look more or less like this:</p> <pre><code>class EventUploader(scrapy.Spider): BASE_URL = 'http://stackoverflow.com/' # Example url def start_requests(self): for chunk in list_of_JSON: get_parameters = { 'api_key': api_key, 'event': json.dumps(chunk), # json.dumps can encode lists too } url = "{}/endpoint?{}".format( self.BASE_URL, urlencode(get_parameters)) yield scrapy.FormRequest(url, formdata={}, callback=self.next) def next(self, response): # here you can assert everything went ok pass </code></pre> <p>Once your spider is in place, you can use scrapy middlewares to limit your requests. You'd run your uploader like this:</p> <pre><code>scrapy runspider my_spider.py </code></pre>
-1
2016-08-17T22:17:06Z
[ "python", "python-requests", "python-multithreading" ]
Python Flask Server Not Working With Twilio
39,005,768
<p>I have been trying to create a personnel log using Raspberry Pi to record who is in the house and to respond to a Twilio text message and reply who is home. I'm using flask to form the server to Twilio however I am getting no response at all when I text the 'whoshome' query. It should reply who is home, although only with one person assigned currently! Also Twilio should be sending a POST request to the predefined client in the dashboard to then ask for instructions upon receiving an SMS.</p> <pre><code>#!/usr/bin/python import time import thread from twilio import twiml import Adafruit_CharLCD as LCD import os import logging import twilio.twiml from twilio.rest import TwilioRestClient from flask import Flask, request, redirect lcd_rs = 21 #lcd setup lcd_en = 22 lcd_d4 = 25 lcd_d5 = 24 lcd_d6 = 23 lcd_d7 = 18 lcd_backlight = 4 lcd_columns = 16 lcd_rows = 4 lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight) logging.basicConfig(filename='wifilog.log', level=logging.INFO) #logging setup ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" #Twilio credentials setup AUTH_TOKEN = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) user1status = 0 #variables def wifiping(): #check who is present while True: ret = os.system("ping -c 1 -s 1 192.168.1.118") lcd.clear() if ret != 0: lcd.message('Sam is not home') print "Sam is not home" logging.info('Sam not home at' + time.strftime("%H:%M:%S", time.gmtime())) user1status = 0 time.sleep(5) else: lcd.message('Sam is home') print "Sam is home" logging.info('Sam home at' + time.strftime("%H:%M:%S", time.gmtime())) user1status = 1 time.sleep(5) thread.start_new_thread(wifiping, ()) #new thread r = twiml.Response() #Flask server setup app = Flask(__name__) app.config.from_object(__name__) @app.route("/", methods={'GET', 'POST'}) def whos_home(): #Twilio message detection body = request.values.get('Body', None) if body == 'Whos home': if user1status == 0: r.message("Sam is not home.") elif user1status == 1: r.message("Sam is home.") else: pass return ' ' app.run(debug=True, host='0.0.0.0', port=80) #Flask app start </code></pre>
-1
2016-08-17T20:31:58Z
39,006,500
<p>Twilio evangelist here.</p> <p>It looks like you are returning an empty trying from your route:</p> <pre><code>return ' ' </code></pre> <p>Since you've marked the route as accepting GET requests you can check this is what's happening by opening the public URL for this route in a browser and seeing what's returned. You could also run a cURL request against the route to verify its returning what you expect.</p> <p>I think you probably need to return the TwiML Response from the route instead of the empty string:</p> <pre><code>return str(r) </code></pre> <p>Hope that helps.</p>
2
2016-08-17T21:22:33Z
[ "python", "flask", "twilio" ]
Menu floats above menu button
39,005,823
<p>So to begin with here is my code:</p> <pre><code>from Tkinter import * def hello(): print "Hello" root = Tk() root.attributes('-fullscreen', 1) icons = [] icons.append(PhotoImage(file="Icons\start.gif")) icons.append(PhotoImage(file="Icons\quit.gif")) icons.append(PhotoImage(file="Icons\save.gif")) icons.append(PhotoImage(file="Icons\load.gif")) icons.append(PhotoImage(file="Icons\Next.gif")) screensizex = root.winfo_screenwidth() screensizey = root.winfo_screenheight() mainframe = Frame(root, height=(screensizey-(screensizey/20)), width=screensizex, bg="#50a9ad") mainframe.grid(row=0) menuframe = Frame(root, height=(screensizey/20), width=screensizex) menuframe.grid(row=1, sticky="w") startmenu = Menubutton ( menuframe, text="Start", image=icons[0], compound = LEFT, relief=RAISED, direction="above") startmenu.grid(row=0, column=0) startmenu.place(relx=0.03, rely=0.5, anchor=CENTER) startmenu.menu = Menu(startmenu, tearoff=0) startmenu["menu"] = startmenu.menu startmenu.configure(font=("Arial", 8, "bold")) startmenu.menu.add_command(label="Next Day", image = icons[4], compound = LEFT, command=hello) startmenu.menu.add_separator() startmenu.menu.add_command(label="Save", image = icons[2], compound = LEFT, command=hello) startmenu.menu.add_command(label="Load", image = icons[3], compound = LEFT, command=hello) startmenu.menu.add_separator() startmenu.menu.add_command(label="Quit", image = icons[1], compound = LEFT, command=root.quit) startmenu.menu.configure(font=("Arial", 8)) root.mainloop() </code></pre> <p>And here is what I get: <a href="http://i.stack.imgur.com/H4NJf.jpg" rel="nofollow">GUI</a></p> <p>As you can see the menu "Floats" above the menu button instead of just being above it. I am not sure of what causes that but I can't figure out how to fix it. I am sure it's something pretty simple but I am a beginner with Python.... Thanks in advance for your help.</p>
0
2016-08-17T20:35:14Z
39,008,266
<p>The problem seems to be with putting the menu button on the absolute bottom. Here is near minimal code, with menu button one 'line' up from bottom, that works with 3.6 (tk 8.6) on Win10</p> <pre><code>import tkinter as tk root = tk.Tk() root.attributes('-fullscreen', 1) tk.Button(root, text='Close', command=root.destroy).pack() mb = tk.Menubutton(root, text='Menu', direction='above') #mb.pack(side='bottom') tk.Label(root, text='Filler2').pack(side='bottom') mb.pack(side='bottom') tk.Label(root, text='Filler1').pack(side='bottom') menu = tk.Menu(mb, tearoff=0) menu.add_command(label='Popup', command=lambda:print('hello')) mb['menu'] = menu </code></pre> <p>Popup is on top of Filler1. Move the bottom down to the bottom (by commenting and uncommenting pack lines) and popup is in same place, leaving a gap. I tried using a ttk Menubutton instead and got the same behavior. I then went to the <a href="http://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm" rel="nofollow">official Tk docs</a> and discovered the 'flush' direction which puts the box 'over' the button. For tk, this means means 'on top of so as to cover the button'. For ttk, it means 'flush against the top, leaving the button exposed', which is what you want. So the solution, as least on Windows with tk 8.6 is to create the button with</p> <pre><code>mb = ttk.Menubutton(root, text='Menu', direction='flush') </code></pre>
0
2016-08-18T00:39:44Z
[ "python", "tkinter" ]
sorting list of decimals in python
39,005,831
<p>I have the following list that I'd like to sort:</p> <p><code>['104.900209904', '238.501860857', '9.59893298149', '362.470027924', '419.737339973']</code></p> <p>I used the "sorted" function to do it:</p> <pre><code>Block1_Video1 = sorted(Block1_Video1) </code></pre> <p>However, this is what I get:</p> <pre><code>['104.900209904', '238.501860857', '362.470027924', '419.737339973', '9.59893298149'] </code></pre> <p>Whereas this is what I want (a list sorted numerically, taking decimal points into account):</p> <pre><code>[''9.59893298149', 104.900209904', '238.501860857', '362.470027924', '419.737339973'] </code></pre> <p>How can I accomplish this?</p>
0
2016-08-17T20:35:31Z
39,005,864
<p>The sorting needs to be based on the float values of the corresponding strings in the list.</p> <pre><code>Block1_Video1 = ['104.900209904', '238.501860857', '9.59893298149', '362.470027924', '419.737339973'] sorted(Block1_Video1,key=lambda x:float(x)) </code></pre> <p>Or simply use </p> <pre><code>sorted(Block1_Video1, key=float) </code></pre>
7
2016-08-17T20:37:24Z
[ "python", "list", "sorting", "floating-point" ]
sorting list of decimals in python
39,005,831
<p>I have the following list that I'd like to sort:</p> <p><code>['104.900209904', '238.501860857', '9.59893298149', '362.470027924', '419.737339973']</code></p> <p>I used the "sorted" function to do it:</p> <pre><code>Block1_Video1 = sorted(Block1_Video1) </code></pre> <p>However, this is what I get:</p> <pre><code>['104.900209904', '238.501860857', '362.470027924', '419.737339973', '9.59893298149'] </code></pre> <p>Whereas this is what I want (a list sorted numerically, taking decimal points into account):</p> <pre><code>[''9.59893298149', 104.900209904', '238.501860857', '362.470027924', '419.737339973'] </code></pre> <p>How can I accomplish this?</p>
0
2016-08-17T20:35:31Z
39,005,888
<p>You have to convert your strings in numbers first, this is possible with the key-Argument of the <code>sorted</code> function:</p> <pre><code>Block1_Video1 = sorted(Block1_Video1, key=float) </code></pre> <p>or as you assign the new list to the same variable, you can also sort in-place:</p> <pre><code>Block1_Video1.sort(key=float) </code></pre>
1
2016-08-17T20:38:47Z
[ "python", "list", "sorting", "floating-point" ]
How "generate " multiple TCP clients using Threads instead of opening multiple instances of the terminal and run the script several times?
39,005,901
<p>I wrote the code for a simple TCP client:</p> <pre><code>from socket import * # Configurações de conexão do servidor # O nome do servidor pode ser o endereço de # IP ou o domínio (ola.python.net) serverHost = 'localhost'#ip do servidor serverPort = 50008 # Mensagem a ser mandada codificada em bytes menssagem = [b'Ola mundo da internet!'] # Criamos o socket e o conectamos ao servidor sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) # Mandamos a menssagem linha por linha for linha in menssagem: sockobj.send(linha) # Depois de mandar uma linha esperamos uma resposta # do servidor data = sockobj.recv(1024) print('Cliente recebeu:', data) # Fechamos a conexão sockobj.close() </code></pre> <p>I would like to know, how " generate " multiple clients TCP using Threads instead of opening multiple instances of the terminal and run the script several times.</p>
10
2016-08-17T20:39:55Z
39,207,374
<p>Try this: The worker method will be set as target for the thread. So every thread will use the code of the method. After starting all thread, the for loop at the bottom will wait for all threads to finish. </p> <p>In the worker method you can use arrays or lists of data from outside the method. So you can iterate for example over a list of Urls or append the fetched data to a new output array. </p> <pre><code>import threading threads = [] maxNrOfThreads = 5 def worker(): do_stuff() for _ in range(maxNrOfThreads): thr = threading.Thread(target=worker) threads.append(thr) thr.setDaemon(True) thr.start() for thread in threads: thread.join() </code></pre>
2
2016-08-29T13:21:17Z
[ "python", "multithreading", "python-3.x" ]
How "generate " multiple TCP clients using Threads instead of opening multiple instances of the terminal and run the script several times?
39,005,901
<p>I wrote the code for a simple TCP client:</p> <pre><code>from socket import * # Configurações de conexão do servidor # O nome do servidor pode ser o endereço de # IP ou o domínio (ola.python.net) serverHost = 'localhost'#ip do servidor serverPort = 50008 # Mensagem a ser mandada codificada em bytes menssagem = [b'Ola mundo da internet!'] # Criamos o socket e o conectamos ao servidor sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) # Mandamos a menssagem linha por linha for linha in menssagem: sockobj.send(linha) # Depois de mandar uma linha esperamos uma resposta # do servidor data = sockobj.recv(1024) print('Cliente recebeu:', data) # Fechamos a conexão sockobj.close() </code></pre> <p>I would like to know, how " generate " multiple clients TCP using Threads instead of opening multiple instances of the terminal and run the script several times.</p>
10
2016-08-17T20:39:55Z
39,224,893
<p>I have just wrapped your code/what you want to do, into a function i.e. <code>worker()</code>. Next, I have added extra code for <code>thread</code> spawning and set the <code>worker()</code> function as the <code>target</code> (the function/work/code each spawned thread will execute - this is why it's a convention to name it <code>worker</code>).</p> <pre><code>th = threading.Thread(target=worker) </code></pre> <hr> <p>The multithreaded version of you above example can be as follows:</p> <pre><code>import threading from socket import * serverHost = 'localhost'#ip do servidor serverPort = 50008 threads = [] input = input("Enter the number of threads:") num_of_threads = int(input) def worker(): # Criamos o socket e o conectamos ao servidor sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) # Mandamos a menssagem linha por linha for linha in menssagem: sockobj.send(linha) # Depois de mandar uma linha esperamos uma resposta # do servidor data = sockobj.recv(1024) print('Cliente recebeu:', data) sockobj.close() # thread generation block for t in range(num_of_threads): th = threading.Thread(target=worker) threads.append(th) th.setDaemon(True) th.start() for thread in threads: thread.join() </code></pre>
0
2016-08-30T10:23:32Z
[ "python", "multithreading", "python-3.x" ]
How "generate " multiple TCP clients using Threads instead of opening multiple instances of the terminal and run the script several times?
39,005,901
<p>I wrote the code for a simple TCP client:</p> <pre><code>from socket import * # Configurações de conexão do servidor # O nome do servidor pode ser o endereço de # IP ou o domínio (ola.python.net) serverHost = 'localhost'#ip do servidor serverPort = 50008 # Mensagem a ser mandada codificada em bytes menssagem = [b'Ola mundo da internet!'] # Criamos o socket e o conectamos ao servidor sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) # Mandamos a menssagem linha por linha for linha in menssagem: sockobj.send(linha) # Depois de mandar uma linha esperamos uma resposta # do servidor data = sockobj.recv(1024) print('Cliente recebeu:', data) # Fechamos a conexão sockobj.close() </code></pre> <p>I would like to know, how " generate " multiple clients TCP using Threads instead of opening multiple instances of the terminal and run the script several times.</p>
10
2016-08-17T20:39:55Z
39,322,922
<p>Here is one solution with queues to send distinct messages.</p> <pre><code>#!/usr/bin/python import Queue import threading import time from socket import * DEF_HOST = 'localhost' DEF_PORT = 50008 queueLock = threading.Lock() class myThreadTCP (threading.Thread): def __init__(self, host=DEF_HOST, port=DEF_PORT, q=None): threading.Thread.__init__(self) self.host = host self.port = port self.q = q def run(self): global queueLock print("Starting Thread") # Criamos o socket e o conectamos ao servidor sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((self.host, self.port)) while not workQueue.empty(): with queueLock: data = q.get() if data: print("sending %s" % data) sockobj.send(data) # Depois de mandar uma linha esperamos uma resposta # do servidor data = sockobj.recv(1024) print('Cliente recebeu:', data) # Fechamos a conexão sockobj.close() print("Exiting Thread") workQueue = Queue.Queue() # Mensagem a ser mandada codificada em bytes menssagem = [b'Ola mundo da internet!', b'Ola mundo da internet #2!'] for msg in menssagem: workQueue.put(msg) threads = [] # Create 10 new threads for i in range(0, 10): thread = myThreadTCP(host=DEF_HOST, port=DEF_PORT, q=workQueue) thread.daemon = True thread.start() threads.append(thread) # Wait for all threads to complete for t in threads: t.join() print("Exiting Main Thread") </code></pre>
0
2016-09-05T01:34:45Z
[ "python", "multithreading", "python-3.x" ]
How "generate " multiple TCP clients using Threads instead of opening multiple instances of the terminal and run the script several times?
39,005,901
<p>I wrote the code for a simple TCP client:</p> <pre><code>from socket import * # Configurações de conexão do servidor # O nome do servidor pode ser o endereço de # IP ou o domínio (ola.python.net) serverHost = 'localhost'#ip do servidor serverPort = 50008 # Mensagem a ser mandada codificada em bytes menssagem = [b'Ola mundo da internet!'] # Criamos o socket e o conectamos ao servidor sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) # Mandamos a menssagem linha por linha for linha in menssagem: sockobj.send(linha) # Depois de mandar uma linha esperamos uma resposta # do servidor data = sockobj.recv(1024) print('Cliente recebeu:', data) # Fechamos a conexão sockobj.close() </code></pre> <p>I would like to know, how " generate " multiple clients TCP using Threads instead of opening multiple instances of the terminal and run the script several times.</p>
10
2016-08-17T20:39:55Z
39,330,655
<p>The simplest and most pythonic way is to use <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.dummy" rel="nofollow">multiprocessing thread pool implementation</a>, and then call <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map" rel="nofollow"><code>pool.map</code></a>. The former will allow you effortlessly swap from threads to processes when needed. The latter will provide you a clean interface hiding synchronisation chores behind the scenes.</p> <pre><code>#!/usr/bin/env python3 import socket from pprint import pprint from contextlib import closing from multiprocessing.dummy import Pool as ThreadPool serverHost = 'localhost' serverPort = 80 messageGroups = [ [b'GET / HTTP/1.0\n\n'], [b'GET /some-path HTTP/1.0\n\n'], ] def send(messages): result = [] options = socket.AF_INET, socket.SOCK_STREAM with closing(socket.socket(*options)) as sockobj: sockobj.connect((serverHost, serverPort)) for message in messages: sockobj.send(message) response = sockobj.recv(1014) result.append((message, response)) return result if __name__ == '__main__': size = 10 pool = ThreadPool(size) result = pool.map(send, messageGroups) pool.close() pool.join() pprint(result) </code></pre>
0
2016-09-05T12:29:52Z
[ "python", "multithreading", "python-3.x" ]
Losе links at multiprocessing parsing on Python (selenium/phantomJS/ProcessPoolExecutor)
39,005,906
<p>(Sorry for my English) I want to make parser for some website with include a lot of JS scripts, for this I use selenium+phantomjs+lxml. Needs that this parser works fast, at least 1000 links per 1 hour. For this purpose I use multiprocessing (not Threading!! because GIL) and module Future, and ProcessExecutorPool. </p> <p>The problem in next, when I give to input list from 10 links and 5 workers, after executions lose some links. It can be 1 links or greater(till 6! - the max value but rare). This of course bad result. There is some dependence, for increasing amount of process, increase amount of lost links. First of all I trace where program breaking. (asserts doesn't works correctly because multiprocessing) I find that, the program breaking after string "browser.get(l)". Then I put time.sleep(x) - give some time for downloading page. Give no result. Then I try research .get() from selenium.webdriver....remote.webdriver.py but it's reload .execute() - and this function takes so many parameters - and discovers it - too long and difficult for me... and the same time I try to run program for 1 process - and I lost 1 links. I thought, may be problem not in selenium and PhantomJS, than I replace concurrent.futures.Future.ProcessExecutorPool on multiprocessing.Pool - problem solves, links don't lose, but if amount of process - &lt;= 4, works almost good, but some time appeares new mistakes(this mistakes appears when set 4 &lt;= amount of process): </p> <pre><code> """ multiprocessing.pool.RemoteTraceback: Traceback (most recent call last): File "/usr/lib/python3.4/multiprocessing/pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "/usr/lib/python3.4/multiprocessing/pool.py", line 44, in mapstar return list(map(*args)) File "interface.py", line 34, in hotline_to_mysql w = Parse_hotline().browser_manipulation(link) File "/home/water/work/parsing/class_parser/parsing_classes.py", line 352, in browser_manipulation browser.get(l) File "/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webdriver.py", line 247, in get self.execute(Command.GET, {'url': url}) File "/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webdriver.py", line 233, in execute response = self.command_executor.execute(driver_command, params) File "/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/remote_connection.py", line 401, in execute return self._request(command_info[0], url, body=data) File "/usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/remote_connection.py", line 471, in _request resp = opener.open(request, timeout=self._timeout) File "/usr/lib/python3.4/urllib/request.py", line 463, in open response = self._open(req, data) File "/usr/lib/python3.4/urllib/request.py", line 481, in _open '_open', req) File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain result = func(*args) File "/usr/lib/python3.4/urllib/request.py", line 1210, in http_open return self.do_open(http.client.HTTPConnection, req) File "/usr/lib/python3.4/urllib/request.py", line 1185, in do_open r = h.getresponse() File "/usr/lib/python3.4/http/client.py", line 1171, in getresponse response.begin() File "/usr/lib/python3.4/http/client.py", line 351, in begin version, status, reason = self._read_status() File "/usr/lib/python3.4/http/client.py", line 321, in _read_status raise BadStatusLine(line) http.client.BadStatusLine: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "interface.py", line 69, in &lt;module&gt; main() File "interface.py", line 63, in main executor.map(hotline_to_mysql, link_list) File "/usr/lib/python3.4/multiprocessing/pool.py", line 260, in map return self._map_async(func, iterable, mapstar, chunksize).get() File "/usr/lib/python3.4/multiprocessing/pool.py", line 599, in get raise self._value http.client.BadStatusLine: '' """ import random import time import lxml.html as lh from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from multiprocessing import Pool from selenium.webdriver.common.keys import Keys from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor AMOUNT_PROCESS = 5 def parse(h)-&gt;list: # h - str, html of page lxml_ = lh.document_fromstring(h) name = lxml_.xpath('/html/body/div[2]/div[7]/div[6]/ul/li[1]/a/@title') prices_ = (price.text_content().strip().replace('\xa0', ' ') for price in lxml_.xpath('//*[@id="gotoshop-price"]')) markets_ =(market.text_content().strip() for market in lxml_.find_class('cell shop-title')) wares = [[name[0], market, price] for (market, price) in zip(markets_, prices_)] return wares def browser_manipulation(l): #options = [] #options.append('--load-images=false') #options.append('--proxy={}:{}'.format(host, port)) #options.append('--proxy-type=http') #options.append('--user-agent={}'.format(user_agent)) #тут хедеры рандомно dcap = dict(DesiredCapabilities.PHANTOMJS) #user agent takes from my config.py dcap["phantomjs.page.settings.userAgent"] = (random.choice(USER_AGENT)) browser = webdriver.PhantomJS(desired_capabilities=dcap) #print(browser) #print('~~~~~~', l) #browser.implicitly_wait(20) #browser.set_page_load_timeout(80) #time.sleep(2) browser.get(l) time.sleep(20) result = parse(browser.page_source) #print('++++++', result[0][0]) browser.quit() return result def main(): #open some file with links with open(sys.argv[1], 'r') as f: link_list = [i.replace('\n', '') for i in f] with Pool(AMOUNT_PROCESS) as executor: executor.map(browser_manipulation, link_list) if __name__ == '__main__': main() </code></pre> <p>Where is the problem(selenium+phantomJS, ThreadPoolExecutor, my code)? Why links lost? How to increase speed of parsing? Finally, may be there are alternative way for parse dynamic website without selenium+phantomjs, on python? Of course, important is speed of parsing. Thank's for answers.</p>
0
2016-08-17T20:40:14Z
39,103,553
<p>I try, instead ProcessPoolExecutor - ThreadPoolExecutor, losing links stop. In Thread... case, speed approximately equal to Process. </p> <p>The question is actual, if you have some information about this, please write. Thanks.</p>
0
2016-08-23T14:08:58Z
[ "python", "parsing", "selenium-webdriver", "phantomjs", "multiprocessing" ]
How to get items in a list before and after a specified index
39,005,928
<p>Suppose I have the list <code>f=[1,2,3]</code> and index <code>i</code> -- I want to iterate over <code>f</code>, excluding <code>i</code>. Is there a way I can use <code>i</code> to split the list, something like <code>f[:i:]</code>, where I would be given a new list of <code>[1,3]</code> when ran with <code>i=1</code>?</p> <p>Code I'm trying to fit this into:</p> <pre><code># permutations, excluding self addition # &lt;something here&gt; would be f excluding f[x] f = [1,2,3] r = [x + y for x in f for y in &lt;something here&gt;] # Expected Output (notice absence of any f[i]+f[i]) [3, 4, 3, 5, 4, 5] </code></pre>
0
2016-08-17T20:42:04Z
39,006,006
<p>iterate y over the index:</p> <pre><code>f = [10,20,30,40,50,60] r = [x + f[y] for x in f for y in range(len(f)) if f[y] != x] </code></pre>
0
2016-08-17T20:47:53Z
[ "python", "python-2.7", "list-comprehension" ]
How to get items in a list before and after a specified index
39,005,928
<p>Suppose I have the list <code>f=[1,2,3]</code> and index <code>i</code> -- I want to iterate over <code>f</code>, excluding <code>i</code>. Is there a way I can use <code>i</code> to split the list, something like <code>f[:i:]</code>, where I would be given a new list of <code>[1,3]</code> when ran with <code>i=1</code>?</p> <p>Code I'm trying to fit this into:</p> <pre><code># permutations, excluding self addition # &lt;something here&gt; would be f excluding f[x] f = [1,2,3] r = [x + y for x in f for y in &lt;something here&gt;] # Expected Output (notice absence of any f[i]+f[i]) [3, 4, 3, 5, 4, 5] </code></pre>
0
2016-08-17T20:42:04Z
39,006,016
<p>Use <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> in order to have access to index at iteration time.</p> <pre><code>[item for i, item in enumerate(f) if i != 3] </code></pre> <p>In this case you can escape the intended index or if you have a set of indices you can check the membership with <code>in</code>:</p> <pre><code>[item for i, item in enumerate(f) if i not in {3, 4, 5}] </code></pre> <p>If you want to remove an item in a certain index you can use <code>del</code> statement:</p> <pre><code>&gt;&gt;&gt; l = ['a', 'b', 'c', 'd', 'e'] &gt;&gt;&gt; &gt;&gt;&gt; del l[3] &gt;&gt;&gt; l ['a', 'b', 'c', 'e'] &gt;&gt;&gt; </code></pre> <p>If you want to create a new list by removing that item and preserve teh main list you can use a simple slicing:</p> <pre><code>&gt;&gt;&gt; new = l[:3] + l[4:] &gt;&gt;&gt; new ['a', 'b', 'c', 'e'] </code></pre>
3
2016-08-17T20:48:39Z
[ "python", "python-2.7", "list-comprehension" ]
How to get items in a list before and after a specified index
39,005,928
<p>Suppose I have the list <code>f=[1,2,3]</code> and index <code>i</code> -- I want to iterate over <code>f</code>, excluding <code>i</code>. Is there a way I can use <code>i</code> to split the list, something like <code>f[:i:]</code>, where I would be given a new list of <code>[1,3]</code> when ran with <code>i=1</code>?</p> <p>Code I'm trying to fit this into:</p> <pre><code># permutations, excluding self addition # &lt;something here&gt; would be f excluding f[x] f = [1,2,3] r = [x + y for x in f for y in &lt;something here&gt;] # Expected Output (notice absence of any f[i]+f[i]) [3, 4, 3, 5, 4, 5] </code></pre>
0
2016-08-17T20:42:04Z
39,006,424
<p>Probably not the most elegant solution, but this might work:</p> <pre><code>f = [1,2,3,4,5] for i, x in enumerate(f): if i == 0: new_list = f[1:] elif i == len(f) -1: new_list = f[:-1] else: new_list = f[:i]+f[i+1:] print i, new_list </code></pre> <p>prints:</p> <pre><code>0 [2, 3, 4, 5] 1 [1, 3, 4, 5] 2 [1, 2, 4, 5] 3 [1, 2, 3, 5] 4 [1, 2, 3, 4] </code></pre>
0
2016-08-17T21:17:26Z
[ "python", "python-2.7", "list-comprehension" ]
How to get items in a list before and after a specified index
39,005,928
<p>Suppose I have the list <code>f=[1,2,3]</code> and index <code>i</code> -- I want to iterate over <code>f</code>, excluding <code>i</code>. Is there a way I can use <code>i</code> to split the list, something like <code>f[:i:]</code>, where I would be given a new list of <code>[1,3]</code> when ran with <code>i=1</code>?</p> <p>Code I'm trying to fit this into:</p> <pre><code># permutations, excluding self addition # &lt;something here&gt; would be f excluding f[x] f = [1,2,3] r = [x + y for x in f for y in &lt;something here&gt;] # Expected Output (notice absence of any f[i]+f[i]) [3, 4, 3, 5, 4, 5] </code></pre>
0
2016-08-17T20:42:04Z
39,006,848
<p>Well, it may seem scary but that's a one-liner that does the work:</p> <pre><code>&gt;&gt;&gt; from numpy import array &gt;&gt;&gt; import itertools &gt;&gt;&gt; list(itertools.chain(*(i+array(l) for i,l in zip(reversed(f), itertools.combinations(f, len(f)-1))))) [3, 4, 3, 5, 4, 5] </code></pre> <p>If you look at it slowly, it's not so complicated:</p> <ol> <li><p>The <code>itertools.combination</code> give all the possible options to the <code>len(f)-1</code> combination:</p> <pre><code>&gt;&gt;&gt; list(itertools.combinations(f, len(f)-1)) [(1, 2), (1, 3), (2, 3)] </code></pre></li> <li><p>You wrap it with <code>zip</code> and <code>reversed(f)</code> so you can get each combination together with the missing value:</p> <pre><code>&gt;&gt;&gt; [(i,l) for i,l in zip(reversed(f), itertools.combinations(f, len(f)-1))] [(3, (1, 2)), (2, (1, 3)), (1, (2, 3))] </code></pre></li> <li><p>Then you convert <code>l</code> to a <code>numpy.array</code> so you can add the missing value:</p> <pre><code>&gt;&gt;&gt; list((i+array(l) for i,l in zip(reversed(f), itertools.combinations(f, len(f)-1)))) [array([4, 5]), array([3, 5]), array([3, 4])] </code></pre></li> <li><p>And finaly you use <code>itertools.chain</code> to get the desired result.</p></li> </ol>
0
2016-08-17T21:54:23Z
[ "python", "python-2.7", "list-comprehension" ]
WSGI flask problems 500 error
39,006,019
<p>I am trying to launch a flask program to an apache server and it works... kinda. I can access a test route that yields just a "hello" so I know that everything is configured correctly. However when I try to access any other part I get a 500 error. my first instinct was that there was a flaw in the program and it was crashing. So I ran it on Flask independent server and it works perfectly. So my question is why do some urls work but not others even though there are no problems in the other URL. please let me know if you need any more information. </p> <p>This is my conf file</p> <p> ServerName localhost</p> <pre><code>WSGIDaemonProcess Ellucian user=www-data group=www-data threads=5 home=/var/www/Ellucian/ WSGIScriptAlias /api/matching-gift-policies /var/www/Ellucian/app.wsgi &lt;directory /var/www/Ellucian&gt; WSGIProcessGroup Ellucian WSGIApplicationGroup %{GLOBAL} WSGIScriptReloading On Order deny,allow Allow from all &lt;/directory&gt; </code></pre> <p></p> <p>The error log is a classic </p> <blockquote> <p>caught SIGTERM, shutting down </p> <p>Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.19 mod_wsgi/3.4 Python/2.7.6 configured -- resuming normal operations</p> <p>Command line: '/usr/sbin/apache2'</p> </blockquote>
-2
2016-08-17T20:48:43Z
39,006,179
<p>My guess is Apache is blocking the requests or doesn't forward them to your application. Since I am an Nginx user I don't know much about Apache configuration but here's what I found on the internet.</p> <pre><code>NameVirtualHost * &lt;VirtualHost *&gt; ServerName yourdomain.com ProxyRequests Off &lt;Proxy *&gt; Order deny,allow Allow from all &lt;/Proxy&gt; ProxyPass / http://localhost:(WSGI port)/ ProxyPassReverse / http://localhost:(WSGI port)/ &lt;Location /&gt; Order allow,deny Allow from all &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre> <p>Where WSGI port is the port your flask application is running</p> <p>This a simple configuration that will (hopefully) forward all requests from Apache to your flask application. If it doesn't please provide your current Apache configuration file</p>
-1
2016-08-17T20:58:53Z
[ "python", "apache", "flask", "wsgi" ]
WSGI flask problems 500 error
39,006,019
<p>I am trying to launch a flask program to an apache server and it works... kinda. I can access a test route that yields just a "hello" so I know that everything is configured correctly. However when I try to access any other part I get a 500 error. my first instinct was that there was a flaw in the program and it was crashing. So I ran it on Flask independent server and it works perfectly. So my question is why do some urls work but not others even though there are no problems in the other URL. please let me know if you need any more information. </p> <p>This is my conf file</p> <p> ServerName localhost</p> <pre><code>WSGIDaemonProcess Ellucian user=www-data group=www-data threads=5 home=/var/www/Ellucian/ WSGIScriptAlias /api/matching-gift-policies /var/www/Ellucian/app.wsgi &lt;directory /var/www/Ellucian&gt; WSGIProcessGroup Ellucian WSGIApplicationGroup %{GLOBAL} WSGIScriptReloading On Order deny,allow Allow from all &lt;/directory&gt; </code></pre> <p></p> <p>The error log is a classic </p> <blockquote> <p>caught SIGTERM, shutting down </p> <p>Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.19 mod_wsgi/3.4 Python/2.7.6 configured -- resuming normal operations</p> <p>Command line: '/usr/sbin/apache2'</p> </blockquote>
-2
2016-08-17T20:48:43Z
39,009,338
<p>The problem was that wgsi was eating my authentication. Not sure how I missed it but it happens I guess. Thanks for the help everyone. I had to include a tag to allow authentication to pass through.</p>
0
2016-08-18T03:03:12Z
[ "python", "apache", "flask", "wsgi" ]
How do I take 31 columns for days in pandas and group them into a single column?
39,006,055
<p>I have a very large file that I'm trying to reformat to run QC checks. The format is very strange how do I make it into a single column with a record for each date?</p> <p>current code is:</p> <pre><code>group = df.groupby(['ID','MONTH'], as_index = True).sum() </code></pre> <p>The dataframe looks like this before any grouping:</p> <p><code>ID TASK MONTH 1 2 3 4 5 6 P502867 5.34545 201601 4.664981 4.6699 4.557714 P502867 5.34545 201602 4.736791 4.664536 4.751841 4.744383</code></p> <p>The top numbers are the days of the month, and in the month column we have each corresponding month until 201608 (August). Essentially I want to group this by the ID, Month, and then the have each column of the days within each month. So this would enable me to run down the list and compare it with another file with daily records. The output dataframe would look something like:</p> <p><code>ID TASK MONTH DAY VALUE P502867 5.34545 201601 1<br> P502867 5.34545 201601 2<br> P502867 5.34545 201601 3 4.664981 P502867 5.34545 201601 4 4.6699</code> </p> <p>Also it might even be helpful to append the month and day together? like 20160101, 20160102. Whichever is easiest. </p>
1
2016-08-17T20:50:56Z
39,006,376
<p>You can <code>melt</code> the days.</p> <pre><code>df2 = pd.melt(df, id_vars=df.columns[:3].tolist(), var_name='day', value_vars=df.columns[3:].tolist()) df2['timestamp'] = pd.to_datetime(df2.MONTH.astype(str) + df2.day.astype(str), format='%Y%m%d') &gt;&gt;&gt; df2.sort_values(['ID', 'timestamp']) ID TASK MONTH day value timestamp 0 P502867 5.34545 201601 1 4.664981 2016-01-01 2 P502867 5.34545 201601 2 4.669900 2016-01-02 4 P502867 5.34545 201601 3 4.557714 2016-01-03 6 P502867 5.34545 201601 4 NaN 2016-01-04 8 P502867 5.34545 201601 5 NaN 2016-01-05 10 P502867 5.34545 201601 6 NaN 2016-01-06 1 P502867 5.34545 201602 1 4.736791 2016-02-01 3 P502867 5.34545 201602 2 4.664536 2016-02-02 5 P502867 5.34545 201602 3 4.751841 2016-02-03 7 P502867 5.34545 201602 4 4.744383 2016-02-04 9 P502867 5.34545 201602 5 NaN 2016-02-05 11 P502867 5.34545 201602 6 NaN 2016-02-06 </code></pre> <p>Optionally, you can drop those with no values:</p> <pre><code>&gt;&gt;&gt; df2.dropna(subset=['value']) ID TASK MONTH day value timestamp 0 P502867 5.34545 201601 1 4.664981 2016-01-01 1 P502867 5.34545 201602 1 4.736791 2016-02-01 2 P502867 5.34545 201601 2 4.669900 2016-01-02 3 P502867 5.34545 201602 2 4.664536 2016-02-02 4 P502867 5.34545 201601 3 4.557714 2016-01-03 5 P502867 5.34545 201602 3 4.751841 2016-02-03 7 P502867 5.34545 201602 4 4.744383 2016-02-04 </code></pre>
0
2016-08-17T21:13:38Z
[ "python", "python-2.7", "pandas" ]
Store compiled model in Keras?
39,006,100
<p>I'd like to use a Keras model in production but don't want to have to re-compile the model everytime I need to run it. Should I just pickle it, etc.?</p>
1
2016-08-17T20:54:14Z
39,260,993
<p>If all you want to do is predict (and not train in production) it is not necessary to compile the model.</p> <p>Source: <a href="https://github.com/fchollet/keras/issues/2621" rel="nofollow">https://github.com/fchollet/keras/issues/2621</a></p>
2
2016-09-01T00:28:12Z
[ "python", "neural-network", "keras" ]
Python: Pandas: Groupby & Pivot Tables are missing rows
39,006,133
<p>I have a dataframe composed of individuals (their ID's in), activities, and corresponding scores. I'm trying to get the sum of the scores when grouping by the student and an activity type. I can do this with the following:</p> <pre><code>data_detail.pivot_table(["total_scored","total_scored_omitted"], index = ["id","activity"], aggfunc="sum") data_detail.groupby(["id","activity"]).sum() </code></pre> <p>However, when I check the results by looking at a typical student:</p> <pre><code>data_detail[data_detail["id"]== 41824840].sort_values("activity") </code></pre> <p>I see that there are some activities listed for that given student which are missing from the groupby/pivot table. How can I ensure the final groupby/pivot table is complete and isn't missing any values?</p>
0
2016-08-17T20:56:36Z
39,006,134
<p>The problem is that the <strong><em>data type</em> for the scores wasn't consistent (and a float at that!).</strong> </p> <p>Some of them were strings. After I converted all of the scores into floats, the missing activities showed up.</p> <p>As an added benefit, having the datatypes be uniform, made the calculation much faster! </p>
1
2016-08-17T20:56:36Z
[ "python", "debugging", "pandas", "dataframe", "pivot-table" ]
Converting a string of length 20 into a float of length 20
39,006,155
<p>I have some strings with numbers inside like '0.9999965341102361' and '3.465889763814134E-6'. I know how to convert them to a float value; however, when I do, they become 9.99996534e-01 and 3.46588976e-06. How can I preserve the full length of the number while still converting to a float? In other words, I don't want to have to round off the original number. Is there a way to do this - can I set the float length equal to 20 or something?</p> <p>It's been a while since I actually took python in school, so I may be forgetting something rather obvious.</p> <p>Thank you.</p>
0
2016-08-17T20:57:41Z
39,006,268
<p>You can't get better than your machine float, which is 64 bit or 32 bit. My linux laptop has 64 bit words, and the number is preserved:</p> <pre><code> In [6]: f = float('0.9999965341102361') In [7]: f Out[7]: 0.9999965341102361 In [8]: f2 = float('3.465889763814134E-6') In [9]: f2 Out[9]: 3.465889763814134e-06 </code></pre>
1
2016-08-17T21:05:17Z
[ "python", "python-3.x" ]
Converting a string of length 20 into a float of length 20
39,006,155
<p>I have some strings with numbers inside like '0.9999965341102361' and '3.465889763814134E-6'. I know how to convert them to a float value; however, when I do, they become 9.99996534e-01 and 3.46588976e-06. How can I preserve the full length of the number while still converting to a float? In other words, I don't want to have to round off the original number. Is there a way to do this - can I set the float length equal to 20 or something?</p> <p>It's been a while since I actually took python in school, so I may be forgetting something rather obvious.</p> <p>Thank you.</p>
0
2016-08-17T20:57:41Z
39,006,542
<p>Use the decimal module:</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; &gt;&gt;&gt; a = decimal.Decimal('0.9999965341102361') &gt;&gt;&gt; b = decimal.Decimal('3.465889763814134E-6') &gt;&gt;&gt; a Decimal('0.9999965341102361') &gt;&gt;&gt; b Decimal('0.000003465889763814134') &gt;&gt;&gt; a*10 Decimal('9.9999653411023610') &gt;&gt;&gt; b*10 Decimal('0.000034658897638141340') &gt;&gt;&gt; print(a) 0.9999965341102361 &gt;&gt;&gt; print(b) 0.000003465889763814134 &gt;&gt;&gt; print('{:1.20e}'.format(b)) 3.46588976381413400000e-6 &gt;&gt;&gt; </code></pre> <hr> <p>decimal.Decimal objects in a numpy array</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = decimal.Decimal('0.9999965341102361') &gt;&gt;&gt; y = decimal.Decimal('3.465889763814134E-6') &gt;&gt;&gt; z = decimal.Decimal('1.23456789012345678901e-2') &gt;&gt;&gt; &gt;&gt;&gt; a = np.array((x, y, z)) &gt;&gt;&gt; a array([Decimal('0.9999965341102361'), Decimal('0.000003465889763814134'), Decimal('0.0123456789012345678901')], dtype=object) &gt;&gt;&gt; &gt;&gt;&gt; b = np.float64((x,y,z)) &gt;&gt;&gt; b array([ 9.99996534e-01, 3.46588976e-06, 1.23456789e-02]) &gt;&gt;&gt; b[2], a[2] &gt;&gt;&gt; (0.012345678901234568, Decimal('0.0123456789012345678901')) &gt;&gt;&gt; &gt;&gt;&gt; a*2 array([Decimal('1.9999930682204722'), Decimal('0.000006931779527628268'), Decimal('0.0246913578024691357802')], dtype=object) &gt;&gt;&gt; b*2 array([ 1.99999307e+00, 6.93177953e-06, 2.46913578e-02]) &gt;&gt;&gt; &gt;&gt;&gt; a*b Traceback (most recent call last): File "&lt;pyshell#50&gt;", line 1, in &lt;module&gt; a*b TypeError: unsupported operand type(s) for *: 'Decimal' and 'float' &gt;&gt;&gt; </code></pre> <p>Looks like a numpy array of type object will hold decimal.Decimal objects. Depending on what you want to do they might work.</p>
2
2016-08-17T21:26:09Z
[ "python", "python-3.x" ]
Matplotlib - imshow subsplots overlapping
39,006,248
<p>So I'm trying to display a collection of imshow (heatmap) subplots on a single figure, side by side and row by row. As a prelim I am testing just displaying 2 fine, and experiencing issues. </p> <p>See code below:</p> <pre><code>axes = [] fig = plt.figure()#figsize=(10,5)) idx = 0 for symbol in ['EURUSD','GBPUSD']: df = get_data_period_symbol('1h', symbol) ranges_df = ranges(df) # Define x and y as the length of columns and indices for use in setting # x and y ticks x, y = len(ranges_df.columns.values), len(ranges_df.index.values) axes.append(fig.add_subplot(1, idx+1, 1)) # Get axes from imshow axes[idx].imshow(ranges_df, interpolation='nearest', cmap='Oranges', aspect='auto') # Set values for x/y ticks/labels axes[idx].set_xticks(np.linspace(0, x-1, x)) axes[idx].set_xticklabels(ranges_df.columns) axes[idx].set_yticks(np.linspace(0, y-1, y)) axes[idx].set_yticklabels(ranges_df.index) # Hide grid lines axes[idx].grid('off') # Push x axis to top instead of bottom axes[idx].xaxis.tick_top() axes[idx].autoscale(False) for i, j in product(range(y), range(x)): _ = axes[idx].text(j, i, '{0:.0f}'.format(ranges_df.iloc[i, j]), size='small', ha='center', va='center') idx += 1 plt.show() </code></pre> <p>It is worth noting that I get the following error when using plt.tight_layout() just before plt.show()</p> <pre><code>UserWarning: tight_layout : falling back to Agg renderer </code></pre> <p>The code above produces the following image:</p> <p><a href="http://i.stack.imgur.com/9ZuOT.png" rel="nofollow"><img src="http://i.stack.imgur.com/9ZuOT.png" alt="enter image description here"></a></p> <p>The plot ranges from 1-12 (months, on the x-axis) and 2001-2015 on the y-axis. You should notice that the plot on the right seems to start at the same place as the one on the left, and is then stretched all the way to the right. I just want them sitting comfortably!</p> <p>The overall intention as discussed is to have many of these in one figure, which I will be able to do dynamically with rows/cols once I get this cracked. </p>
1
2016-08-17T21:03:43Z
39,006,389
<p>I believe it should be <code>add_subplot(1, 2, idx+1)</code>. That is the subplot is defined by number of rows, then number of cols, and then the region ordinal.</p> <p>Aside from this problem, you might want to "pythonize" your code a bit by auto indexing like this:</p> <pre><code>for idx, symbol in enumerate(['EURUSD','GBPUSD']): </code></pre>
1
2016-08-17T21:14:01Z
[ "python", "matplotlib" ]
How to convert a set of features to a count matrix in pandas
39,006,270
<p>Given a matrix </p> <p>----<code>d1 d2 d3 a: v1 0 v2 b: v1 v3 0</code></p> <p>I want </p> <p>----<code>v1 v2 v3 a: 1 1 0 b: 1 0 1</code></p> <p>I remember vaguely that this can be done with <code>Gensim</code>...but there must also be some module in pandas? I have tried to do <code>for v in v: for el in [a,b]</code>(happy to post the code, but I think that the example is clear enough) but it is very slow, and I imagine this must have been solved before.</p>
1
2016-08-17T21:05:21Z
39,006,865
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>pandas.get_dummies</code></a>, e.g.</p> <pre><code>import pandas as pd # create your dataframe df = pd.DataFrame(index=['a', 'b'], data={'d1': ['v1', 'v1'], 'd2': [None, 'v3'], 'd3': ['v2', None]}) # perform one-hot encoding df = pd.get_dummies(df, prefix_sep='=') # rename if you so wish df.rename(columns={c: c.split('=')[1] for c in df.columns}, inplace=True) # sort columns by name (not really necessary) df.sort_index(axis=1, inplace=True) # have a look print df </code></pre> <p>which yields</p> <pre><code> v1 v2 v3 a 1 1 0 b 1 0 1 </code></pre>
3
2016-08-17T21:56:07Z
[ "python", "pandas", "gensim" ]
How to convert a set of features to a count matrix in pandas
39,006,270
<p>Given a matrix </p> <p>----<code>d1 d2 d3 a: v1 0 v2 b: v1 v3 0</code></p> <p>I want </p> <p>----<code>v1 v2 v3 a: 1 1 0 b: 1 0 1</code></p> <p>I remember vaguely that this can be done with <code>Gensim</code>...but there must also be some module in pandas? I have tried to do <code>for v in v: for el in [a,b]</code>(happy to post the code, but I think that the example is clear enough) but it is very slow, and I imagine this must have been solved before.</p>
1
2016-08-17T21:05:21Z
39,007,052
<p>Start with your DataFrame <code>DF</code>, with <code>0</code> replaced with <code>NaN</code></p> <pre><code>DF=ps.DataFrame({'d1':['v1','v1'],'d2':[NaN,'v3'],'d3':['v2',NaN]},index=['a','b']) </code></pre> <p>Get the unique values you want to count:</p> <pre><code>Vals=DF.stack().unique() </code></pre> <p>use some list comprehension for counts:</p> <pre><code>ps.DataFrame([[(DF.ix[ind,:]==Vi).sum() for Vi in Vals] for ind in DF.index] , columns=Vals, index=DF.index) </code></pre>
1
2016-08-17T22:12:33Z
[ "python", "pandas", "gensim" ]
Infinite loop in python - why?
39,006,344
<p>I'm using the code</p> <pre><code>fibList=[1] def fib(n1, n2): n3 = n1+n2 n1=n2 n2=n3 num1=1 num2=2 while(num2&lt;4000000): fib(num1,num2) if (num2%2==0): fibList.append(num2) total = sum(fibList) print total </code></pre> <p>in an online compiler, repl.it. It was going and going and not giving a solution, so I typed the line <code>print n3</code> right below the <code>n3=</code> line in the definition of the <code>fib</code> function. It gave 3, over and over again, and it crashed before I could stop the program. So obviously there's some kind of infinite loop somewhere (at least, obviously in my mind; it could not be an infinite loop, I suppose, but I'm pretty sure it is). The question is where. I don't really understand why there'd be an infinite loop.</p> <p>This is not, by the way, a homework question, but a problem I'm doing for fun. The <code>fib</code> function is supposed to calculate Fibonacci numbers, and the second part isolate the even ones less than four million, and then at the end calculate the sum. </p> <p>What I want to know is where the infinite loop is coming in and what I can do to fix it. Thanks!</p>
0
2016-08-17T21:10:57Z
39,006,390
<p><code>n1</code>, <code>n2</code> and <code>n3</code> are local variables and have nothing in common with <code>num1</code> and <code>num2</code> in the outer scope, despite their initial value. You have to <code>return</code> the value and assign these results to <code>num1</code> and <code>num2</code> again.</p> <pre><code>def fib(n1, n2): n3 = n1+n2 n1=n2 n2=n3 return n1, n2 num1=1 num2=2 fibList=[1] while num2&lt;4000000: num1, num2 = fib(num1,num2) if num2%2==0: fibList.append(num2) total = sum(fibList) print total </code></pre>
6
2016-08-17T21:14:02Z
[ "python" ]
How I can make my db add codes for users to register with one of the codes ? (Python-Django)
39,006,439
<p>I want to put a number of codes in my database so that when a user wants to register my application need to enter a code of those who are in the database, so that the system registry access.</p> <p>All this in django, but honestly I have no idea how to do it, if you can help me, I would appreciate it very much.</p> <p>Thanks for your time.</p>
0
2016-08-17T21:18:30Z
39,006,758
<p>There are a couple of steps that you will need to do, but essentially you are just seeding the DB with valid registration codes. To generate a number of registration codes you can use the following, I limit the number to 1000 but this can be changed</p> <pre><code>import uuid codes = set() num_codes = 1000 while (num_codes &gt; 0): code = str(uuid.uuid4()) # make sure the randomly gen code isn't a duplicated while code in codes: code = str(uuid.uuid4()) # add the newly generated code to the set and dec the counter codes.add(code) num_codes -= 1 </code></pre> <p>Next what you will want to do is add the codes to a new table. It would probably make sense to have a table structure like:</p> <pre><code>{ table_name: registration code, columns: { id: int, code: string, valid: bool, } } </code></pre> <p>where valid limits the code to a one time registration.</p> <p>Then when a user tries to register select where the key used = code column and valid = true, if it returns something it is valid otherwise the key is invalid or already used.</p>
0
2016-08-17T21:44:47Z
[ "python", "django" ]
Saving averages in text file
39,006,474
<p>I am making an average calculator in python, i have to save the averages in a text file and have done it like this:</p> <pre><code>Mean = statistics.mean(aver) Mode = statistics.mode(aver) Medi = statistics.median(aver) file = open("Averages.txt", "a") file.write("\n\nYour numbers are" + aver + "\nMean : " + Mean + "\nMode : " + Mode + "\nMedian : " + Medi) </code></pre> <p>(aver is a list of numbers i am finding the average of)</p> <p>when i try to run this part of the code, i recieve the error message:</p> <pre><code>TypeError: Can't convert 'list' object to str implicitly </code></pre> <p>I tried basic stuff like adding 'str' on but it doesnt help.</p>
1
2016-08-17T21:21:18Z
39,006,548
<pre><code>file.write("\n\nYour numbers are" + **aver** + </code></pre> <p>this would be better as something like this:</p> <pre><code>aver = " " + ", ".join(aver) + " " </code></pre> <p>which converts your list to a comma separated string.</p>
1
2016-08-17T21:26:48Z
[ "python", "list", "average" ]
How to use localtime (HH:MM) in if statement - python
39,006,475
<p>I made some code to turn on a light depending on movement and the time of the day in an if statement. If the (local)time is between sunrise and a preset time or sunset and a preset time the if statement is true and the motion detection statements will follow. </p> <p>At the moment the time is only presented in hours as an integer. How can i make my if statement to work with hours and minutes (think this will need to be a string). So the statement will work with 6:45 instead of 7 for example. </p> <p>Here is my code. </p> <pre><code>import RPi.GPIO as GPIO import time import urllib2 from datetime import datetime from business_calendar import Calendar, MO, TU, WE, TH, FR from pytz import timezone #uur fmh = "%H" fmt = "$H:%M" #Def. var. x=0 now_utc = 0 now_amsterdam = 0 print "Here we go! Press CTRL+C to exit" try: while x &lt; 1: count = 0 date = datetime.today() #werkdag def. cal = Calendar(workdays=[MO,TU,WE,TH,FR]) busday = cal.isbusday(date) # dT AMS-UTC now_utc = datetime.now(timezone('UTC')) now_amsterdam = now_utc.astimezone(timezone('Europe/Amsterdam')) UTC = int(now_utc.strftime(fmh)) AMS = int(now_amsterdam.strftime(fmh)) dT = AMS - UTC # Zonsopgang/Ondegang request = 'http://api.sunrise-sunset.org/json?lat=51.9913XXX&amp;lng=4.4733XXX&amp;formatted=0' response = urllib2.urlopen(request) timestring = response.read() utcsunrise = timestring[35:39] #Will be 35:39 for HH:MM and cant be a string then utcsunset = timestring[71:73] #Will be 71:79 for HH:MM amssunrise = int(utcsunrise) + dT #Wont work with a string amssunset = int(utcsunset) + dT if amssunrise &lt; 8 #Will be 7:30 amssunrise = 8 #Will be 7:30 if amssunset &lt; 21 #Will be 21:30 amssunset = 21 #Will be 21:30 #uur uur = date.hour #Must be HH:MM instead of only hours if busday == True and ((uur &gt;= 7 and uur &lt;= amssunrise) or (uur &gt;= amssunset and uur &lt;= 23)): # rest of the statements # end statement except KeyboardInterrupt: GPIO.cleanup() </code></pre> <p>I would like to hear your thoughts. Little note I'm new to python but not to coding. </p> <p>Greetings, Thijs</p>
0
2016-08-17T21:21:19Z
39,006,851
<p>Do all calculations with <code>datetime</code>-objects:</p> <pre><code>import RPi.GPIO as GPIO import time import urllib2 import json from datetime import datetime from business_calendar import Calendar, MO, TU, WE, TH, FR from pytz import timezone, utc local_timezone = timezone('Europe/Amsterdam') print "Here we go! Press CTRL+C to exit" try: while True: #werkdag def. cal = Calendar(workdays=[MO,TU,WE,TH,FR]) busday = cal.isbusday(date) now = datetime.now(local_timezone) work_start = now.replace(hour=7, minute=0, second=0, microsecond=0) work_end = now.replace(hour=23, minute=0, second=0, microsecond=0) # Zonsopgang/Ondegang request = 'http://api.sunrise-sunset.org/json?lat=51.9913XXX&amp;lng=4.4733XXX&amp;formatted=0' response = urllib2.urlopen(request) timestring = json.loads(response.read()) sunset = datetime.strptime(timestring['results']['sunset'],'%Y-%m-%dT%H:%M:%S+00:00') sunset = utc.localize(sunset).astimezone(local_timezone) sunrise = datetime.strptime(timestring['results']['sunrise'],'%Y-%m-%dT%H:%M:%S+00:00') sunrise = utc.localize(sunset).astimezone(local_timezone) if busday and (work_start &lt;= now &lt;= sunrise or sunset &lt;= now &lt;= work_end): # rest of the statements # end statement except KeyboardInterrupt: GPIO.cleanup() </code></pre>
1
2016-08-17T21:54:33Z
[ "python", "python-2.7", "if-statement", "localtime" ]
How to use localtime (HH:MM) in if statement - python
39,006,475
<p>I made some code to turn on a light depending on movement and the time of the day in an if statement. If the (local)time is between sunrise and a preset time or sunset and a preset time the if statement is true and the motion detection statements will follow. </p> <p>At the moment the time is only presented in hours as an integer. How can i make my if statement to work with hours and minutes (think this will need to be a string). So the statement will work with 6:45 instead of 7 for example. </p> <p>Here is my code. </p> <pre><code>import RPi.GPIO as GPIO import time import urllib2 from datetime import datetime from business_calendar import Calendar, MO, TU, WE, TH, FR from pytz import timezone #uur fmh = "%H" fmt = "$H:%M" #Def. var. x=0 now_utc = 0 now_amsterdam = 0 print "Here we go! Press CTRL+C to exit" try: while x &lt; 1: count = 0 date = datetime.today() #werkdag def. cal = Calendar(workdays=[MO,TU,WE,TH,FR]) busday = cal.isbusday(date) # dT AMS-UTC now_utc = datetime.now(timezone('UTC')) now_amsterdam = now_utc.astimezone(timezone('Europe/Amsterdam')) UTC = int(now_utc.strftime(fmh)) AMS = int(now_amsterdam.strftime(fmh)) dT = AMS - UTC # Zonsopgang/Ondegang request = 'http://api.sunrise-sunset.org/json?lat=51.9913XXX&amp;lng=4.4733XXX&amp;formatted=0' response = urllib2.urlopen(request) timestring = response.read() utcsunrise = timestring[35:39] #Will be 35:39 for HH:MM and cant be a string then utcsunset = timestring[71:73] #Will be 71:79 for HH:MM amssunrise = int(utcsunrise) + dT #Wont work with a string amssunset = int(utcsunset) + dT if amssunrise &lt; 8 #Will be 7:30 amssunrise = 8 #Will be 7:30 if amssunset &lt; 21 #Will be 21:30 amssunset = 21 #Will be 21:30 #uur uur = date.hour #Must be HH:MM instead of only hours if busday == True and ((uur &gt;= 7 and uur &lt;= amssunrise) or (uur &gt;= amssunset and uur &lt;= 23)): # rest of the statements # end statement except KeyboardInterrupt: GPIO.cleanup() </code></pre> <p>I would like to hear your thoughts. Little note I'm new to python but not to coding. </p> <p>Greetings, Thijs</p>
0
2016-08-17T21:21:19Z
39,006,860
<p>I no longer use the builtin <code>datetime</code> lib it sucks. Look into <code>arrow</code> <a href="http://crsmithdev.com/arrow/" rel="nofollow">http://crsmithdev.com/arrow/</a></p> <p>just one tip.</p> <p>Also look into using <code>requests</code> its the defacto way of doing http stuff in python.</p> <p>I have rewritten you app as much as I could and provided the link below. I wasn't quite sure where you were headed with it put tried to replicate it as much as possible but. I hope this helps.</p> <p><a href="http://hastebin.com/elomonacod.py" rel="nofollow">http://hastebin.com/elomonacod.py</a></p> <pre><code>import arrow import requests import sys from business_calendar import Calendar, MO, TU, WE, TH, FR #uur fmh = "%H" fmt = "$H:%M" #Def. var. now_utc = 0 now_amsterdam = 0 some_condition = False def main(): print "Here we go! Press CTRL+C to exit" global now_amsterdam global now_utc global some_condition while True: count = 0 date = arrow.now() # werkdag def. cal = Calendar(workdays=[MO, TU, WE, TH, FR]) busday = cal.isbusday(date) # dT AMS-UTC now_utc = arrow.utcnow() now_amsterdam = now_utc.to('Europe/Amsterdam') print now_utc, now_amsterdam time_diff = now_amsterdam - now_utc r = requests.get('http://api.sunrise-sunset.org/json?lat=51.9913XXX&amp;lng=4.4733XXX&amp;formatted=0') if r.status_code != 200: print('Server could not be reached: {}'.format(r.status_code)) sys.exit() ''' Data structure { "results": { "sunrise": "2016-08-17T04:31:10+00:00", "sunset": "2016-08-17T19:00:46+00:00", "solar_noon": "2016-08-17T11:45:58+00:00", "day_length": 52176, "civil_twilight_begin": "2016-08-17T03:53:46+00:00", "civil_twilight_end": "2016-08-17T19:38:10+00:00", "nautical_twilight_begin": "2016-08-17T03:06:02+00:00", "nautical_twilight_end": "2016-08-17T20:25:54+00:00", "astronomical_twilight_begin": "2016-08-17T02:09:10+00:00", "astronomical_twilight_end": "2016-08-17T21:22:46+00:00" }, "status": "OK" } ''' data = r.json()['results'] utc_sunrise = arrow.get(data['sunrise']) utc_sunset = arrow.get(data['sunset']) ams_sunrise = utc_sunrise + time_diff ams_sunset = utc_sunset + time_diff # Zonsopgang/Ondegang if ams_sunrise &lt; arrow.get('{} 07:30:00'.format(now_amsterdam.format('YYYY-MM-DD'))): pass if ams_sunset &lt; arrow.get('{} 21:30:00'.format(now_amsterdam.format('YYYY-MM-DD'))): pass if busday: pass if some_condition: break # # if amssunrise &lt; 8: # Will be 7:30 # amssunrise = 8 # Will be 7:30 # # if amssunset &lt; 21: # Will be 21:30 # amssunset = 21 # Will be 21:30 # # # uur # uur = date.hour # Must be HH:MM instead of only hours # # if busday == True and ((uur &gt;= 7 and uur &lt;= amssunrise) or (uur &gt;= amssunset and uur &lt;= 23)): # # rest of the statements # # end statement # pass if __name__ == '__main__': main() </code></pre>
0
2016-08-17T21:55:27Z
[ "python", "python-2.7", "if-statement", "localtime" ]
Unicode error in `str.format()`
39,006,484
<p>I am trying to run the following script, which scans for <code>*.csproj</code> files and checks for project dependencies in Visual Studio solutions, but I am getting the following error. I have already tried all sorts of <code>codec</code> and <code>encode/decode</code> and <code>u''</code> combination, to no avail...</p> <p>(the diacritics <em>are</em> intended and I plan to keep them).</p> <blockquote> <pre><code>Traceback (most recent call last): File "E:\00 GIT\SolutionDependencies.py", line 44, in &lt;module&gt; references = GetProjectReferences("MiotecGit") File "E:\00 GIT\SolutionDependencies.py", line 40, in GetProjectReferences outputline = u'"{}" -&gt; "{}"'.format(projectName, referenceName) UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 19: ordinal not in range(128) </code></pre> </blockquote> <pre><code>import glob import os import fnmatch import re import subprocess import codecs gvtemplate = """ digraph g { rankdir = "LR" ##### } """.strip() def GetProjectFiles(rootFolder): result = [] for root, dirnames, filenames in os.walk(rootFolder): for filename in fnmatch.filter(filenames, "*.csproj"): result.append(os.path.join(root, filename)) return result def GetProjectName(path): result = os.path.splitext(os.path.basename(path))[0] return result def GetProjectReferences(rootFolder): result = [] projectFiles = GetProjectFiles(rootFolder) for projectFile in projectFiles: projectName = GetProjectName(projectFile) with codecs.open(projectFile, 'r', "utf-8") as pfile: content = pfile.read() references = re.findall("&lt;ProjectReference.*?&lt;/ProjectReference&gt;", content, re.DOTALL) for reference in references: referenceProject = re.search('"([^"]*?)"', reference).group(1) referenceName = GetProjectName(referenceProject) outputline = u'"{}" -&gt; "{}"'.format(projectName, referenceName) result.append(outputline) return result references = GetProjectReferences("MiotecGit") output = u"\n".join(*references) with codecs.open("output.gv", "w", 'utf-8') as outputfile: outputfile.write(gvtemplate.replace("#####", output)) graphvizpath = glob.glob(r"C:\Program Files*\Graphviz*\bin\dot.*")[0] command = '{} -Gcharset=latin1 -T pdf -o "output.pdf" "output.gv"'.format(graphvizpath) subprocess.call(command) </code></pre>
0
2016-08-17T21:21:45Z
39,006,764
<p>When Python 2.x tries to use a byte string in a Unicode context, it automatically tries to <code>decode</code> the byte string to a Unicode string using the <code>ascii</code> codec. While the <code>ascii</code> codec is a safe choice, it often doesn't work.</p> <p>For Windows environments the <code>mbcs</code> codec will select the code page that Windows uses for 8-bit characters. You can decode the string yourself explicitly.</p> <pre><code>outputline = u'"{}" -&gt; "{}"'.format(projectName.decode('mbcs'), referenceName.decode('mbcs')) </code></pre>
1
2016-08-17T21:45:25Z
[ "python", "unicode", "encoding", "python-unicode" ]
Remove documents from a collection based on value located in another collection
39,006,486
<p>I started working with mongodb yesterday. I have two collections in the same database with 100 million and 300 million documents. I want to remove documents in one collection if a value in the document is not found in any document of the second collection. To maybe make this more clear I have provided python/mongodb pseudocode code below. I realize this is not proper syntax, its just to show the logic I am after. I am looking for the most efficient way as there are a lot of records and its on my laptop :)</p> <pre><code>for doc_ONE in db.collection_ONE: if doc_ONE["arbitrary"] not in [doc_TWO["arbitrary"] for doc_TWO in db.collection_TWO]: db.collection_ONE.remove({"arbitrary": doc_ONE["arbitrary"]}) </code></pre> <p>I am fine with this being done from the mongo cli if faster. Thanks for reading this and please don't flame me to hard lol.</p>
0
2016-08-17T21:21:53Z
39,006,667
<p>If <code>document["arbitrary"]</code> is a immuable value, you can store all the values (without duplicates) in a <code>set</code>:</p> <p>values = {document["arbitrary"] for document in db.collection_TWO}</p> <p>The process like you suggest:</p> <pre><code>for doc_one in db.collection_ONE: if doc_one["arbitrary"] not in values: db.collection_ONE.remove({"arbitrary": doc_one["arbitrary"]}) </code></pre>
0
2016-08-17T21:36:21Z
[ "python", "mongodb" ]
On linux, how can I allow any user to write to a file, but only by running my (python) script?
39,006,562
<p>I'm working on a GUI for managing the contents of a specific network folder. The files are created/deleted and moved by a script.</p> <p>I have a json index file that has information about the files in this folder.</p> <p>Is there a way to give all users write permission to these files, but only if they use my script?</p> <p>I'm not worried about security, just don't want people to edit files without the index file being updated.</p>
1
2016-08-17T21:28:04Z
39,007,077
<p>You can specify this type of thing using visudo.</p> <p>From: <a href="http://www.atrixnet.com/allow-an-unprivileged-user-to-run-a-certain-command-with-sudo/" rel="nofollow">http://www.atrixnet.com/allow-an-unprivileged-user-to-run-a-certain-command-with-sudo/</a></p> <p>First, you’ll need to use the visudo utility…</p> <pre><code> sudo visudo </code></pre> <p>This command safely opens up the /etc/sudoers file for you in your default editor. Let’s say you want to allow a user named “joe” to run a given command. You just need to add a line like this below (customize for your needs)</p> <pre><code> joe ALL=(ALL) NOPASSWD: /full/path/to/command </code></pre> <p>Now what if you want to restrict joe to only use that command within a given set of parameters or with only certain arguments? Well, just toss them in there too! Check this out:</p> <pre><code> joe ALL=(ALL) NOPASSWD: /full/path/to/command ARG1 ARG2 </code></pre>
1
2016-08-17T22:13:55Z
[ "python", "linux" ]
On linux, how can I allow any user to write to a file, but only by running my (python) script?
39,006,562
<p>I'm working on a GUI for managing the contents of a specific network folder. The files are created/deleted and moved by a script.</p> <p>I have a json index file that has information about the files in this folder.</p> <p>Is there a way to give all users write permission to these files, but only if they use my script?</p> <p>I'm not worried about security, just don't want people to edit files without the index file being updated.</p>
1
2016-08-17T21:28:04Z
39,007,109
<p>You're program needs the the SUID bit set <a href="https://en.wikipedia.org/wiki/Setuid" rel="nofollow">https://en.wikipedia.org/wiki/Setuid</a>. I'm not sure if this can be done with a python script.</p>
0
2016-08-17T22:16:50Z
[ "python", "linux" ]
search for variable from list write line to file
39,006,599
<p>When going through a list with <code>for x in list</code>, I am having a problem with:</p> <pre><code>if x in Invalid_names_file: ISP_names_file.write(str(x)) </code></pre> <p>If I replace <code>if</code> with <code>for</code> then I get the entire contents of <code>Invalid_names_file</code> written into <code>ISP_names_file</code>.</p> <p>Here is my code:</p> <pre><code>def isp_email_names(): with open('Invalid_names_file', 'r') as Invalid_names_file: with open('ISP_names_file', 'w') as ISP_names_file: for x in one_ip_each(): if x in Invalid_names_file: ISP_names_file.write(str(x)) ISP_names_file.flush() ISP_names_file.closed Invalid_names_file.closed </code></pre> <p>The <code>one_ip_each</code> variable is my list, that come from a module that I have imported.</p> <p>I can print this list at the end of the script to make sure that it's working, yet can't get any input into the write file.</p> <p>I will be putting more <code>for</code> statements behind this, so I don't mind that it's just the last <code>x</code> in my list that shows up in the file when I cut it out to see that it's working.</p> <p>The file does get written to disk, nothing in it with the <code>if ...</code>, whole file-1 with the <code>for ...</code></p> <p>i should have been clearer in my original post.</p> <p>my list-></p> <pre><code>['192.168.122.21', '192.168.122.22', '192.168.122.25'] </code></pre> <p>and some of the file that i'm trying to go through-></p> <pre><code>Jul 25 11:29:02 testing sshd[1345]: Invalid user JoseMartinez from 192.168.122.25 Jul 25 11:29:03 testing sshd[1347]: Invalid user BillyCarter from 192.168.122.25 Jul 25 11:24:26 testing sshd[1094]: Invalid user DavidFlores from 192.168.122.21 Jul 25 11:25:05 testing sshd[1108]: Invalid user Nicole from 192.168.122.22 </code></pre> <p>trying to do 'for x in list' find lines with x in it and print the whole line to a file.</p>
0
2016-08-17T21:31:38Z
39,006,694
<p><code>Invalid_names_file</code> is an iterator. So after first <code>if x in ...</code> this iterator is empty and all following tests results in <code>False</code>. Read your file into a list first and then test each line with the <code>in</code> operator and not only the list elements.</p> <pre><code>def isp_email_names(): with open('Invalid_names_file', 'r') as Invalid_names_file: Invalid_names_file = list(Invalid_names_file) with open('ISP_names_file', 'w') as ISP_names_file: for ip in one_ip_each(): for line in Invalid_names_file: if ip in line: ISP_names_file.write(line) </code></pre>
0
2016-08-17T21:39:35Z
[ "python" ]
search for variable from list write line to file
39,006,599
<p>When going through a list with <code>for x in list</code>, I am having a problem with:</p> <pre><code>if x in Invalid_names_file: ISP_names_file.write(str(x)) </code></pre> <p>If I replace <code>if</code> with <code>for</code> then I get the entire contents of <code>Invalid_names_file</code> written into <code>ISP_names_file</code>.</p> <p>Here is my code:</p> <pre><code>def isp_email_names(): with open('Invalid_names_file', 'r') as Invalid_names_file: with open('ISP_names_file', 'w') as ISP_names_file: for x in one_ip_each(): if x in Invalid_names_file: ISP_names_file.write(str(x)) ISP_names_file.flush() ISP_names_file.closed Invalid_names_file.closed </code></pre> <p>The <code>one_ip_each</code> variable is my list, that come from a module that I have imported.</p> <p>I can print this list at the end of the script to make sure that it's working, yet can't get any input into the write file.</p> <p>I will be putting more <code>for</code> statements behind this, so I don't mind that it's just the last <code>x</code> in my list that shows up in the file when I cut it out to see that it's working.</p> <p>The file does get written to disk, nothing in it with the <code>if ...</code>, whole file-1 with the <code>for ...</code></p> <p>i should have been clearer in my original post.</p> <p>my list-></p> <pre><code>['192.168.122.21', '192.168.122.22', '192.168.122.25'] </code></pre> <p>and some of the file that i'm trying to go through-></p> <pre><code>Jul 25 11:29:02 testing sshd[1345]: Invalid user JoseMartinez from 192.168.122.25 Jul 25 11:29:03 testing sshd[1347]: Invalid user BillyCarter from 192.168.122.25 Jul 25 11:24:26 testing sshd[1094]: Invalid user DavidFlores from 192.168.122.21 Jul 25 11:25:05 testing sshd[1108]: Invalid user Nicole from 192.168.122.22 </code></pre> <p>trying to do 'for x in list' find lines with x in it and print the whole line to a file.</p>
0
2016-08-17T21:31:38Z
39,006,750
<p>A not so elegant solution, running in O(N) run time, but having it check in regards to if x is contained in a readline. Sorry in advance for the not so elegant solution and hope it works.</p> <pre><code>def isp_email_names(): with open('Invalid_names_file', 'r') as Invalid_names_file: with open('ISP_names_file', 'w') as ISP_names_file: for x in one_ip_each(): if str(x) in Invalid_names_file.readline(): ISP_names_file.write(str(x)) ISP_names_file.flush() </code></pre>
0
2016-08-17T21:44:15Z
[ "python" ]
search for variable from list write line to file
39,006,599
<p>When going through a list with <code>for x in list</code>, I am having a problem with:</p> <pre><code>if x in Invalid_names_file: ISP_names_file.write(str(x)) </code></pre> <p>If I replace <code>if</code> with <code>for</code> then I get the entire contents of <code>Invalid_names_file</code> written into <code>ISP_names_file</code>.</p> <p>Here is my code:</p> <pre><code>def isp_email_names(): with open('Invalid_names_file', 'r') as Invalid_names_file: with open('ISP_names_file', 'w') as ISP_names_file: for x in one_ip_each(): if x in Invalid_names_file: ISP_names_file.write(str(x)) ISP_names_file.flush() ISP_names_file.closed Invalid_names_file.closed </code></pre> <p>The <code>one_ip_each</code> variable is my list, that come from a module that I have imported.</p> <p>I can print this list at the end of the script to make sure that it's working, yet can't get any input into the write file.</p> <p>I will be putting more <code>for</code> statements behind this, so I don't mind that it's just the last <code>x</code> in my list that shows up in the file when I cut it out to see that it's working.</p> <p>The file does get written to disk, nothing in it with the <code>if ...</code>, whole file-1 with the <code>for ...</code></p> <p>i should have been clearer in my original post.</p> <p>my list-></p> <pre><code>['192.168.122.21', '192.168.122.22', '192.168.122.25'] </code></pre> <p>and some of the file that i'm trying to go through-></p> <pre><code>Jul 25 11:29:02 testing sshd[1345]: Invalid user JoseMartinez from 192.168.122.25 Jul 25 11:29:03 testing sshd[1347]: Invalid user BillyCarter from 192.168.122.25 Jul 25 11:24:26 testing sshd[1094]: Invalid user DavidFlores from 192.168.122.21 Jul 25 11:25:05 testing sshd[1108]: Invalid user Nicole from 192.168.122.22 </code></pre> <p>trying to do 'for x in list' find lines with x in it and print the whole line to a file.</p>
0
2016-08-17T21:31:38Z
39,023,805
<p>final code that works-></p> <pre><code>def isp_email_names(): with open('Invalid_names_file', 'r') as Invalid_names_file: with open('ISP_names_file', 'w') as ISP_names_file: for x in one_ip_each(): for line in Invalid_names_file: if x in line: ISP_names_file.writelines(str(line)) ISP_names_file.flush() ISP_names_file.closed Invalid_names_file.closed isp_email_names() </code></pre> <p>don't know why i have to call the function to have it write to disk though. will try to figure that out later.</p> <p>thank you everyone for your patience.</p>
0
2016-08-18T17:03:43Z
[ "python" ]
Automatic Legend Placement in Bokeh
39,006,611
<p>Does Bokeh have the functionality to automatically position a legend in a plot, <a href="http://matplotlib.org/1.3.0/examples/pylab_examples/legend_auto.html" rel="nofollow">similar to Matplotlib</a>?</p>
0
2016-08-17T21:32:17Z
39,006,816
<p>Yes. Just set the legend.location attribute as one of the enumerable locations (i.e. 'top_left' or 'bottom_right'):</p> <p><a href="http://bokeh.pydata.org/en/latest/docs/reference/models/annotations.html#bokeh.models.annotations.Legend.location" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/reference/models/annotations.html#bokeh.models.annotations.Legend.location</a></p>
0
2016-08-17T21:51:14Z
[ "python", "bokeh" ]
Splitting a list of file names in a predefined ratio
39,006,647
<p>I am trying to form an optimized approach to splitting a list of file names(examples shortly) in a x:y ratio based on the file names. This file list was procured using os.scandir (better performance vs os.listdir, src: <a href="https://docs.python.org/3.5/library/os.html#os.scandir" rel="nofollow">Python Docs scandir</a>).</p> <p><strong>Example -</strong> </p> <p>Files (extension disregarded)-</p> <p>A_1,A_2,...A_10 (here A is filename and 1 is the sample number of the file)</p> <p>B_1,B_2,...B_10</p> <p>and so on</p> <p>Let's say the x:y ratio is 7:3 So I would like 70% of file names (A_1..A7,B_1..B_7) and 30%(A_8--A_10,B_8..B_10) in different lists, it does not matter that the first list should be in that order meaning the files could be A_1,A_9,A_5 etc as long as they are split 7 files in list 1 to 3 files in list 2. </p> <p>Now it must be noted that this directory is huge (~150k files) and the samples of each type of files vary, i.e. it maybe that files with filename A have 1000 files or it may have only 5. Also there are about 400 unique filenames.</p> <p>This current solution should not be called a solution at all as it defies the purpose of an accurate ratio for each filename. It is currently splitting the list of fileObjects(basically- name like A, number like 1, data within file A_1 and so on) as a whole in x:y ratio and taking advantage of the fact that entries are yielded in arbitrary order when using <strong>os.scandir</strong>.</p> <pre><code>ratio_number = int(len(list_of_fileObjects) *.7) list_70 = list_of_fileObjects[:ratio_number] list_30 = list_of_fileObjects[ratio_number:] </code></pre> <p>My second approach which would at least be a valid solution was to create a list separately for each filename(involves sorting the whole list of files), split it in the ratio and do this for each filename. I am looking for a more pythonic/elegant solution to this problem. Any suggestions or help would be appreciated especially considering the size of data being dealt with.</p>
-2
2016-08-17T21:34:57Z
39,007,920
<p>If I understand the situation correctly, your trying to partition the same proportion of each filename prefix's files. Your current method selects the correct proportion from the whole set of files, but it doesn't consider the different filename prefixes, so it may not get them in the correct proportion (though it will probably be somewhat close, most of the time).</p> <p>Your second approach avoids that issue by first separating the filenames by prefix, then partitioning each sublist. But if you want a combined list with all the prefixes together, this approach may end up wasting time copying data around, since you have to separate out and then recombine the separate lists by prefix.</p> <p>I think you can do what you want with a single loop over the filenames. You'll need to keep track of two data points for each filename prefix: The number of files with that prefix you've selected for the first sample and the total number of files with that prefix that you've seen.</p> <pre><code>ratio = 0.7 prefix_dict = {} # values are lists: [number_selected_for_first_list, total_number_seen] first_sample = [] # gets a proportion of the files equal to ratio (for each prefix) second_sample = [] # gets the rest of the files for filename in list_of_files: prefix = filename.split("_", 1)[0] selected_seen = prefix_dict.setdefault(prefix, [0, 0]) selected_seen[1] += 1 if selected_seen[0] &lt; round(ratio * selected_seen[1]): first_sample.append(filename) selected_seen[0] += 1 else: second_sample.append(filename) </code></pre> <p>The only tricky part to this code is the use of <code>dict.setdefault</code> to fetch the <code>selected_seen</code> list. It if the requested <code>prefix</code> didn't yet exist in the dictionary, a new value (<code>[0, 0]</code>) will be added to the dictionary under that key (and returned). The later code modifies the list in place.</p> <p>Depending on how exactly you want to handle inexact proportions, you can change the <code>if</code> condition a bit. I put in a <code>round</code> call (which I think will partition most accurately), but the code would work OK without it (biasing the selection towards the second sample) or with <code>selected_seen[0] &lt;= int(ratio * selected_seen[1])</code> (biasing towards the first sample).</p> <p>Note that whichever way you choose to round when partitioning each prefix, there's the possibility that the separate prefixes will all end up unbalanced in the same direction, making the overall samples unbalanced by more than you'd normally expect. For instance, if you had ten prefixes with ten files (for 100 files total), a ratio of 7.5 would result in final sample lists of 80 and 20 files rather than 75 and 25. That happens since each of the prefixes gets partitioned 8 and 2 (7.5 rounds up). If every file had a unique prefix, you'd end up with everything in the first sample! If it's very important that the overall samples be the right sizes, you might need to fudge the sampling of the items a bit, based on the overall sample sizes.</p>
0
2016-08-17T23:49:26Z
[ "python", "list" ]
Splitting a list of file names in a predefined ratio
39,006,647
<p>I am trying to form an optimized approach to splitting a list of file names(examples shortly) in a x:y ratio based on the file names. This file list was procured using os.scandir (better performance vs os.listdir, src: <a href="https://docs.python.org/3.5/library/os.html#os.scandir" rel="nofollow">Python Docs scandir</a>).</p> <p><strong>Example -</strong> </p> <p>Files (extension disregarded)-</p> <p>A_1,A_2,...A_10 (here A is filename and 1 is the sample number of the file)</p> <p>B_1,B_2,...B_10</p> <p>and so on</p> <p>Let's say the x:y ratio is 7:3 So I would like 70% of file names (A_1..A7,B_1..B_7) and 30%(A_8--A_10,B_8..B_10) in different lists, it does not matter that the first list should be in that order meaning the files could be A_1,A_9,A_5 etc as long as they are split 7 files in list 1 to 3 files in list 2. </p> <p>Now it must be noted that this directory is huge (~150k files) and the samples of each type of files vary, i.e. it maybe that files with filename A have 1000 files or it may have only 5. Also there are about 400 unique filenames.</p> <p>This current solution should not be called a solution at all as it defies the purpose of an accurate ratio for each filename. It is currently splitting the list of fileObjects(basically- name like A, number like 1, data within file A_1 and so on) as a whole in x:y ratio and taking advantage of the fact that entries are yielded in arbitrary order when using <strong>os.scandir</strong>.</p> <pre><code>ratio_number = int(len(list_of_fileObjects) *.7) list_70 = list_of_fileObjects[:ratio_number] list_30 = list_of_fileObjects[ratio_number:] </code></pre> <p>My second approach which would at least be a valid solution was to create a list separately for each filename(involves sorting the whole list of files), split it in the ratio and do this for each filename. I am looking for a more pythonic/elegant solution to this problem. Any suggestions or help would be appreciated especially considering the size of data being dealt with.</p>
-2
2016-08-17T21:34:57Z
39,237,188
<p>I figured out a good solution to this problem.</p> <pre><code>all_file_names = {} # ObjList is a list of objects but we only need # file_name from that object for our solution for x in ObjList: if x.file_name not in all_file_names: all_file_names[x.file_name] = 1 else: all_file_names[x.file_name] += 1 trainingData = [] testData = [] temp_dict = {} for x in ObjList: ratio = int(0.7*all_file_names[x.file_name])+1 if x.file_name not in temp_dict: temp_dict[x.file_name] = 1 trainingData.append(x) else: temp_dict[x.file_name] += 1 if(temp_dict[x.file_name] &lt; ratio): trainingData.append(x) else: testData.append(x) </code></pre>
0
2016-08-30T21:14:00Z
[ "python", "list" ]
If statement always True Jinja2 Template
39,006,653
<p>I'm not sure what exactly the problem is but the concept is when my function execute it should fetch a query list from database and if It doesnt contain any object it should return False and the else part should execute</p> <p>The first part works but even when my database is empty it passes True,</p> <pre><code>{% if new_bookmarks %} &lt;div id='newBookmarks'&gt; {% for bm in new_bookmarks %} &lt;a href='{{ bm.url }}'&gt;&lt;span&gt;{{ bm.user.username }}&lt;/span&gt; Added: {{ bm.url }} &lt;span&gt;{{ bm.description }}&lt;/span&gt;&lt;/a&gt; {% endfor %} &lt;/div&gt; {% else %} &lt;div&gt; Something else &lt;/div&gt; {% endif %} </code></pre> <hr> <pre><code>@app.route('/') @app.route('/index') def index(): return render_template('index.html', new_bookmarks=Bookmark.newest(5)) </code></pre> <hr> <pre><code>class Bookmark(db.Model): id = db.Column(db.Integer, primary_key=True) url = db.Column(db.Text, nullable=False) date = db.Column(db.DateTime, default=datetime.utcnow) description = db.Column(db.String(300)) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) @staticmethod def newest(num): return Bookmark.query.order_by(desc(Bookmark.date)).limit(num) </code></pre>
0
2016-08-17T21:35:27Z
39,006,974
<p>The problem is that a query is lazy, i.e., it doesn't execute until you begin iterating over it. Therefore it has no idea how many records are in it at the point you're testing its truthiness. By default most objects in Python are truthy, and this applies to queries as well.</p> <p>To work around this, use:</p> <pre><code>return Bookmark.query.order_by(desc(Bookmark.date)).limit(num).all() </code></pre> <p>The <code>.all()</code> executes the query and puts the results into a list. Lists are falsy when they are empty. Since this is a small query, the drawbacks to having the results in memory all at once are minor.</p>
1
2016-08-17T22:04:58Z
[ "python", "model-view-controller", "flask", "jinja2", "backend" ]
How to get all of the "ids" within a python array
39,006,669
<p>So I am pulling some json data using an API and it initially looks like this:</p> <pre><code>{ "result": { "elements": [ { "id": "SV_3s0FmbrNancSmsB", "name": "Test Survey", "ownerId": "sdfsdfasdf", "lastModified": "2016-08-09T21:33:27Z", "isActive": false }, { "id": "SV_dgJOVyJvwZR0593", "name": "Test Survey", "ownerId": "sdfdsfsdfs", "lastModified": "2016-08-04T17:53:37Z", "isActive": true } ], "nextPage": null }, "meta": { "httpStatus": "200 - OK" } } </code></pre> <p>So I want to pull all of the ids within this JSON using Python, and here is my code:</p> <pre><code>url = "random.com" headers = { 'x-api-token': "dsfsdagdfa" } response = requests.get(url, headers=headers) data = json.loads(response.text) id_0 = data['result']['elements'][0]['id'] print(id_0) </code></pre> <p>This will basically just print the first Id within the created array. What would I do to get all of the ids?</p>
0
2016-08-17T21:36:54Z
39,006,696
<p>This should work. Im sure there is a more elegant way with map or list comprehension.</p> <pre><code>ids = [] for elem in data['result']['elements']: ids.append(elem['id']) </code></pre> <p>If you want to evaluate this lazily, make a generator comprehension!</p> <p><code>ids = (element['id'] for element in data['result']['elements'])</code></p>
1
2016-08-17T21:39:52Z
[ "python", "arrays", "json" ]
How to get all of the "ids" within a python array
39,006,669
<p>So I am pulling some json data using an API and it initially looks like this:</p> <pre><code>{ "result": { "elements": [ { "id": "SV_3s0FmbrNancSmsB", "name": "Test Survey", "ownerId": "sdfsdfasdf", "lastModified": "2016-08-09T21:33:27Z", "isActive": false }, { "id": "SV_dgJOVyJvwZR0593", "name": "Test Survey", "ownerId": "sdfdsfsdfs", "lastModified": "2016-08-04T17:53:37Z", "isActive": true } ], "nextPage": null }, "meta": { "httpStatus": "200 - OK" } } </code></pre> <p>So I want to pull all of the ids within this JSON using Python, and here is my code:</p> <pre><code>url = "random.com" headers = { 'x-api-token': "dsfsdagdfa" } response = requests.get(url, headers=headers) data = json.loads(response.text) id_0 = data['result']['elements'][0]['id'] print(id_0) </code></pre> <p>This will basically just print the first Id within the created array. What would I do to get all of the ids?</p>
0
2016-08-17T21:36:54Z
39,006,699
<p>You can use this oneliner:</p> <pre><code>ids = [element['id'] for element in data['result']['elements']] </code></pre>
2
2016-08-17T21:40:01Z
[ "python", "arrays", "json" ]
How to get all of the "ids" within a python array
39,006,669
<p>So I am pulling some json data using an API and it initially looks like this:</p> <pre><code>{ "result": { "elements": [ { "id": "SV_3s0FmbrNancSmsB", "name": "Test Survey", "ownerId": "sdfsdfasdf", "lastModified": "2016-08-09T21:33:27Z", "isActive": false }, { "id": "SV_dgJOVyJvwZR0593", "name": "Test Survey", "ownerId": "sdfdsfsdfs", "lastModified": "2016-08-04T17:53:37Z", "isActive": true } ], "nextPage": null }, "meta": { "httpStatus": "200 - OK" } } </code></pre> <p>So I want to pull all of the ids within this JSON using Python, and here is my code:</p> <pre><code>url = "random.com" headers = { 'x-api-token': "dsfsdagdfa" } response = requests.get(url, headers=headers) data = json.loads(response.text) id_0 = data['result']['elements'][0]['id'] print(id_0) </code></pre> <p>This will basically just print the first Id within the created array. What would I do to get all of the ids?</p>
0
2016-08-17T21:36:54Z
39,006,714
<p>How about:</p> <pre><code>ids = [element['id'] for element in data['result']['elements']] </code></pre>
2
2016-08-17T21:40:55Z
[ "python", "arrays", "json" ]
deploying kik bot to heroku not working
39,006,692
<p>I've been trying to deploy my kik api to heroku, but it just isn't working. I've set up my procfile, my requirements.txt file, my runtime.txt file, and it shows up on my machine as running fine. However, when I open the kik app on my phone and try to message the bot, the messages aren't sent and it is not echoing my message. By Using ngrok as a webhook, I was able to get the bot to work and echo the messages just fine. However, when I tried deploying to heroku, it didn't work at all. For reference, the kik bot is written using flask and the kik api, here is my code </p> <pre><code>from flask import Flask, request, Response import os from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage app = Flask(__name__) BOT_USERNAME = os.environ['BOT_USERNAME'] BOT_API_KEY= os.environ['BOT_API_KEY'] kik = KikApi(BOT_USERNAME, BOT_API_KEY) config = Configuration(webhook=os.environ['WEBHOOK']) kik.set_configuration(config) @app.route('/', methods=['POST']) def incoming(): if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()): return Response(status=403) messages = messages_from_json(request.json['messages']) for message in messages: if isinstance(message, TextMessage): kik.send_messages([ TextMessage( to=message.from_user, chat_id=message.chat_id, body=message.body ) ]) return Response(status=200) if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. print('HI') port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) </code></pre> <p>Here is my requirements.txt </p> <pre><code>Flask==0.11.1 kik==1.1.0 gunicorn==19.6.0 </code></pre> <p>Here is my runtime.txt </p> <pre><code>python-2.7.12 </code></pre> <p>Here is my procfile </p> <pre><code>web: python bot.py </code></pre> <p>I set up the webhook variable to be the heroku URL. When I run the app locally, it seems to be running just fine. </p> <p><a href="http://i.stack.imgur.com/5aFXh.png" rel="nofollow">Heroku local app</a></p> <p>Any help is greatly appreciated. </p>
0
2016-08-17T21:39:28Z
39,021,935
<p>I figured out the issue. I had set the wrong environmental variables for my heroku deployment, so it threw a keyerror because it couldn't find the key and stopped the process. </p>
0
2016-08-18T15:20:15Z
[ "python", "heroku", "flask", "bots", "kik" ]
Return multiple instances from an object in python
39,006,706
<p>This question has no doubt been asked before, but I am not entirely sure how to search for it (since I do not know what it is called). So apologies in advance.</p> <p>Alas, my problem is that I have a huge amount of objects </p> <pre><code>for i in range(1000): M = subParts[0].get(parts['thing'][i]) </code></pre> <p>Each <code>M</code> is an object that contains a lot of info about this model, now my job is to call four separate functions on this object, so that those functions can return four simple numbers as so:</p> <pre><code>for i in range(1000): M = subParts[0].get(parts['thing'][i]) M.getItem1() M.getItem2() M.getItem3() M.getItem4() </code></pre> <p>each of which returns a number, e.g.</p> <pre><code>4.5 5.7 3.7 2.9 </code></pre> <p>My question is thus, what is an efficient way to do this? The above is very ugly but works, but there must be more efficient methods. Upon which I would just like to store the whole lot in a dictionary as so </p> <pre><code>myDict = { 0 : [4.5,5.7,3.7,2.9], ... , 999 : [2.5,3.7,5.7,2.9] } </code></pre> <p>Thanks.</p>
2
2016-08-17T21:40:32Z
39,006,790
<pre><code>def getdata(m): return [m.getItem1(), m.getItem2(), m.getItem3(), m.getItem4()] myDict = {i: getdata(subParts[0].get(parts['thing'][i])) for i in range(1000)} </code></pre>
3
2016-08-17T21:48:03Z
[ "python", "dictionary", "optimization" ]
Return multiple instances from an object in python
39,006,706
<p>This question has no doubt been asked before, but I am not entirely sure how to search for it (since I do not know what it is called). So apologies in advance.</p> <p>Alas, my problem is that I have a huge amount of objects </p> <pre><code>for i in range(1000): M = subParts[0].get(parts['thing'][i]) </code></pre> <p>Each <code>M</code> is an object that contains a lot of info about this model, now my job is to call four separate functions on this object, so that those functions can return four simple numbers as so:</p> <pre><code>for i in range(1000): M = subParts[0].get(parts['thing'][i]) M.getItem1() M.getItem2() M.getItem3() M.getItem4() </code></pre> <p>each of which returns a number, e.g.</p> <pre><code>4.5 5.7 3.7 2.9 </code></pre> <p>My question is thus, what is an efficient way to do this? The above is very ugly but works, but there must be more efficient methods. Upon which I would just like to store the whole lot in a dictionary as so </p> <pre><code>myDict = { 0 : [4.5,5.7,3.7,2.9], ... , 999 : [2.5,3.7,5.7,2.9] } </code></pre> <p>Thanks.</p>
2
2016-08-17T21:40:32Z
39,006,958
<p>Assuming that <code>parts['thing']</code> is an ordered sequence that can be iterated over, you can use <code>map</code> to call <code>subParts[0].get</code> on each element of <code>parts['thing']</code> so iterating over each <code>M</code> object could be done like this:</p> <pre><code>for M in map(subParts[0].get, parts['thing']): ... </code></pre> <p>Note that this will return a list in python 2 so using <code>itertools.imap</code> would be preferable.</p> <p>To put it into dict comprehension you would just do:</p> <pre><code>stuff = {i:[M.getItem1(), M.getItem2(), M.getItem3(), M.getItem4()] for i,M in enumerate(map(subParts[0].get, parts['thing']))} </code></pre>
1
2016-08-17T22:03:13Z
[ "python", "dictionary", "optimization" ]
Implement dragMoveEvent on QWidget in pyqt5?
39,006,733
<p>does anyone know how I can implement the dragMove event on my QWidget? So basically what I want is to move my mouse over the Widget hold down my mouse button and drag it. While dragging, the widget should not be moved it should only capture the mouse coordinates while the mouse is pressed.</p> <p>I have already googled and just find some drag and drop tutorials where they have dragged something into a widget etc. like text. This wasn't really helpful.</p>
1
2016-08-17T21:42:50Z
39,012,849
<p>I think you are looking for <a href="http://doc.qt.io/qt-5/qwidget.html#mousePressEvent" rel="nofollow">mousePressEvent</a> rather than <a href="http://doc.qt.io/qt-5/qwidget.html#dragMoveEvent" rel="nofollow">dragMoveEvent</a>. You would need to subclass <code>QWidget</code> and implement the <code>mousePressEvent</code> method providing your implementation:</p> <pre><code>from PyQt5.QtWidgets import QWidget class MyWidget(QWidget): def mousePressEvent(self, event): print(event.pos()) </code></pre>
0
2016-08-18T08:02:45Z
[ "python", "user-interface", "pyqt", "pyqt5" ]
Implement dragMoveEvent on QWidget in pyqt5?
39,006,733
<p>does anyone know how I can implement the dragMove event on my QWidget? So basically what I want is to move my mouse over the Widget hold down my mouse button and drag it. While dragging, the widget should not be moved it should only capture the mouse coordinates while the mouse is pressed.</p> <p>I have already googled and just find some drag and drop tutorials where they have dragged something into a widget etc. like text. This wasn't really helpful.</p>
1
2016-08-17T21:42:50Z
39,030,627
<p>This has got nothing to do with dragging. What you actually need to do is enable mouse-tracking and then monitor mouse-move events.</p> <p>Here's a simple demo:</p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() self.setMouseTracking(True) def mouseMoveEvent(self, event): if event.buttons() &amp; QtCore.Qt.LeftButton: print(event.globalPos().x(), event.globalPos().y()) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) window = Window() window.setGeometry(500, 150, 100, 100) window.show() sys.exit(app.exec_()) </code></pre>
0
2016-08-19T03:23:56Z
[ "python", "user-interface", "pyqt", "pyqt5" ]
How can I access the data in an XML node when using ElementTree
39,006,735
<p>i am parsing the XML located at this link:</p> <p><a href="http://python-data.dr-chuck.net/comments_42.xml" rel="nofollow">XML File to Parse</a></p> <p>I need to access the data inside the node and it seems like the program I have written is telling me that there is nothing inside the node. Here is my code:</p> <pre><code>import urllib import xml.etree.ElementTree as ET #prompt for link where xml data resides #Use this link for testing: http://python-data.dr-chuck.net/comments_42.xml url = raw_input('Enter URL Link: ') #open url and prep for parsing data = urllib.urlopen(url).read() #read url data and convert to XML Node Tree for parsing comments = ET.fromstring(data) #the comment below is part of another approach to the solution #both approaches are leading me into the same direction #it appears as if the data inside the node is not being parsed/extracted #counts = comments.findall('comments/comment/count') for count in comments.findall('count'): print comments.find('count').text </code></pre> <p>When i print out the 'data' variable alone, i get the complete XML tree. However, when I try to access the data inside a particular node, the node comes back empty.</p> <p>I also tried printing the following code to see what data I would get back:</p> <pre><code>for child in comments: print child.tag, child.attrib </code></pre> <p>the output i got was:</p> <blockquote> <p>note {} comments {}</p> </blockquote> <p>What am i doing wrong, and what am i missing?</p> <p>one of the errors i get when trying a different looping strategy of accessing the node is this:</p> <pre><code>Traceback (most recent call last): File "xmlextractor.py", line 16, in &lt;module&gt; print comments.find('count').text AttributeError: 'NoneType' object has no attribute 'text' </code></pre> <p>Please help and thanks!!!</p> <p>UPDATE:</p> <p>Ive realized in looking through the etree docs for python that my approach has been trying to 'get' the node attributes instead of the contents of the nodes. I still havent found an answer but i am definitely closer!!!</p> <p>2nd UPDATE:</p> <p>so i tried out this code:</p> <pre><code>import urllib import xml.etree.ElementTree as ET #prompt for link where xml data resides #Use this link for testing: http://python-data.dr-chuck.net/comments_42.xml url = raw_input('Enter URL Link: ') #open url and prep for parsing data = urllib.urlopen(url).read() #read url data and convert to XML Node Tree for parsing comments = ET.fromstring(data) counts = comments.findall('comments/comment/count') print len(counts) for count in counts: print 'count', count.find('count').text </code></pre> <p>from above, when i run this code my:</p> <pre><code>print len(counts) </code></pre> <p>outputs that i have 50 nodes in my counts list, but i still get the same error:</p> <pre><code>Traceback (most recent call last): File "xmlextractor.py", line 18, in &lt;module&gt; print 'count', count.find('count').text AttributeError: 'NoneType' object has no attribute 'text' </code></pre> <p>i dont understand why it says that there is no 'text' attribute when i am trying to access the contents of the node.</p> <p>What am I doing wrong??</p>
0
2016-08-17T21:42:58Z
39,011,824
<p>A few comments on your approaches:</p> <blockquote> <pre><code>for count in comments.findall('count'): print comments.find('count').text </code></pre> </blockquote> <p><code>comments.findall('count')</code> returns an empty list because <code>comments</code> does not have any immediate child elements with the name <code>count</code>.</p> <blockquote> <pre><code>for child in comments: print child.tag, child.attrib </code></pre> </blockquote> <p>Iterates over the immediate child elements of your root node, which are called <code>note</code>.</p> <blockquote> <pre><code># From update #2 for count in comments.findall('comments/comment/count'): print 'count', count.find('count').text </code></pre> </blockquote> <p>Here, <code>count</code> is an <code>Element</code> object representing a <code>count</code> node which itself does not contain any <code>count</code> nodes. Thus, <code>count.find('count')</code> returns a <code>NoneType</code> object.</p> <p>If I understand correctly, your goal is to retrieve the text values of the <code>count</code> nodes. Here are two ways this can be achieved:</p> <pre><code>for count in comments.findall('comments/comment/count'): print count.text for comment in comments.iter('comment'): print comment.find('count').text </code></pre>
1
2016-08-18T07:01:56Z
[ "python", "xml", "xml-parsing", "string-parsing" ]
Matching a Pattern in a Region in Sikuli is very slow
39,006,769
<p>I am automating a computer game using Sikuli as a hobby project and to hopefully get good enough to make scripts to help me at my job. In a certain small region, (20x20 pixels) one of 15 characters will appear. Right now I have these 15 images defined as variables, and then using an <code>if</code>, <code>elif</code> loop I am doing <code>Region.exists()</code>. If one of my images is present in the region, I assign a variable the appropriate value. </p> <p>I am doing this for two areas on the screen and then based on the combination of characters the script clicks appropriately.</p> <p>The problem right now is that to run the 15 if statements is taking approximately 10 seconds. I was hoping to do this recognition in closer to 1 second. </p> <p>These are just text characters but the OCR feature was not reading them reliably and I wanted close to 100% accuracy.</p> <p>Is this an appropriate way to do OCR? Is there a better way you guys can recommend? I haven't done much coding in the last 3 years so I am wondering if OCR has improved and if Sikuli is still even a relevant program. Seeing as this is just a hobby project I am hoping to stick to free solutions.</p>
1
2016-08-17T21:45:52Z
39,008,510
<p>Sikuli operates by scanning a Screen or a part of a screen and attempting to match a set pattern. Naturally, the smaller the pattern is, the more time it will consume to match it. There few ways to improve the detection time:</p> <ol> <li>Region and Pattern manipulation (bound region size)</li> <li>Functions settings (reduce minimum wait time)</li> <li>Configuration (amend scan rate)</li> </ol> <p>I have described the issue in some more detail <a href="http://eugenesautomation.blogspot.com.au/2015/01/speeding-up-pattern-match-time.html" rel="nofollow">here</a>.</p> <p>OCR is still quite unreliable. There are ways to improve that but if you only have a limited set of characters, I reckon you will be better off using them as patterns. It will be quicker and more reliable.</p> <p>As of Sikuli itself, the tool is under active development and is still relevant if it helps you to solve your problem.</p>
1
2016-08-18T01:16:01Z
[ "python", "automation", "ocr", "sikuli", "sikuli-ide" ]
XGBoost installation via Anaconda 1.5.1 fails on OS X
39,006,804
<p>I have GCC installed via Homebrew using <code>brew install gcc --without-multilib</code>. When I tried to use <code>pip install xgboost</code> in Anaconda 1.5.1 on OS X El Capitan 10.11.6 and Conda 4.1.11 running Python 3.5.2, I get the following output and error:</p> <pre><code>Collecting xgboost Using cached xgboost-0.6a2.tar.gz Complete output from command python setup.py egg_info: rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost clang-omp++ -std=c++0x -Wall -O3 -msse2 -Wno-unknown-pragmas -funroll-loops -Iinclude -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc &gt;build/learner.d /bin/sh: clang-omp++: command not found clang-omp++ -std=c++0x -Wall -O3 -msse2 -Wno-unknown-pragmas -funroll-loops -Iinclude -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc &gt;build/logging.d make: *** [build/learner.o] Error 127 make: *** Waiting for unfinished jobs.... /bin/sh: clang-omp++: command not found make: *** [build/logging.o] Error 127 ----------------------------- Building multi-thread xgboost failed Start to build single-thread xgboost rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost clang-omp++ -std=c++0x -Wall -O3 -msse2 -Wno-unknown-pragmas -funroll-loops -Iinclude -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc &gt;build/learner.d /bin/sh: clang-omp++: command not found make: *** [build/learner.o] Error 127 make: *** Waiting for unfinished jobs.... clang-omp++ -std=c++0x -Wall -O3 -msse2 -Wno-unknown-pragmas -funroll-loops -Iinclude -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc &gt;build/logging.d /bin/sh: clang-omp++: command not found make: *** [build/logging.o] Error 127 Successfully build single-thread xgboost If you want multi-threaded version See additional instructions in doc/build.md Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/94/yw1tx2t95lb31nlww2nwpk114lvh7b/T/pip-build-k_1ed1r6/xgboost/setup.py", line 29, in &lt;module&gt; LIB_PATH = libpath['find_lib_path']() File "/private/var/folders/94/yw1tx2t95lb31nlww2nwpk114lvh7b/T/pip-build-k_1ed1r6/xgboost/xgboost/libpath.py", line 45, in find_lib_path 'List of candidates:\n' + ('\n'.join(dll_path))) XGBoostLibraryNotFound: Cannot find XGBoost Libarary in the candicate path, did you install compilers and run build.sh in root path? List of candidates: /private/var/folders/94/yw1tx2t95lb31nlww2nwpk114lvh7b/T/pip-build-k_1ed1r6/xgboost/xgboost/libxgboost.so /private/var/folders/94/yw1tx2t95lb31nlww2nwpk114lvh7b/T/pip-build-k_1ed1r6/xgboost/xgboost/../../lib/libxgboost.so /private/var/folders/94/yw1tx2t95lb31nlww2nwpk114lvh7b/T/pip-build-k_1ed1r6/xgboost/xgboost/./lib/libxgboost.so ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/94/yw1tx2t95lb31nlww2nwpk114lvh7b/T/pip-build-k_1ed1r6/xgboost/ </code></pre>
0
2016-08-17T21:50:32Z
39,007,799
<p>I solved this by following the <a href="https://github.com/dmlc/xgboost/blob/master/doc/build.md" rel="nofollow">Python Package Installation instructions.</a> I now have the package without a pip installation.</p>
0
2016-08-17T23:34:31Z
[ "python", "anaconda" ]
Why does this code not work for all inputs
39,006,826
<p>I am trying to write python code that takes two strings as input and checks if all the characters of the second string are present in the first string. If so, then the output is the second string. If not, the output is the string "This does not work". I have tested this procedure for a variety of inputs, and it typically works, but not always. For example, if my two inputs are "helo" and "olhe", respectively, the output is "This does not work," whereas it should be "olhe" since all the characters in "olhe" are present in "helo."</p> <p>Here is my code</p> <pre><code>def fix_machine(debris,product): n = 1 while True: first_element = product[0:n] find_first_element = debris.find(first_element) if first_element == product: return product break n = n + 1 if find_first_element == -1: return "This does not work" break </code></pre> <p>So why does this not work?</p>
0
2016-08-17T21:52:18Z
39,006,981
<p>You could do this as a more elegant solution, assuming that you strictly want all of the second string characters to be present in first.</p> <pre><code>def fix_machine(first, second): for character in second: if character not in first: return False return second </code></pre> <p>This returns correct input for your code. Not entirely sure what is wrong with your code as I have not stepped through.</p> <p>EDIT: Albert has a much more elegant solution, reference his</p>
0
2016-08-17T22:05:30Z
[ "python" ]
Why does this code not work for all inputs
39,006,826
<p>I am trying to write python code that takes two strings as input and checks if all the characters of the second string are present in the first string. If so, then the output is the second string. If not, the output is the string "This does not work". I have tested this procedure for a variety of inputs, and it typically works, but not always. For example, if my two inputs are "helo" and "olhe", respectively, the output is "This does not work," whereas it should be "olhe" since all the characters in "olhe" are present in "helo."</p> <p>Here is my code</p> <pre><code>def fix_machine(debris,product): n = 1 while True: first_element = product[0:n] find_first_element = debris.find(first_element) if first_element == product: return product break n = n + 1 if find_first_element == -1: return "This does not work" break </code></pre> <p>So why does this not work?</p>
0
2016-08-17T21:52:18Z
39,006,986
<p>As far as I understood you just want to compare two strings containing different characters.</p> <p>For doing so, I would suggest converting both strings to a <code>set</code> which then provides (in contrast to a <code>list</code>) order-less comparison of its elements.</p> <pre><code>def check_string(first_str, second_str): # convert strings to sets in order to compare characters if set(first_string) == set(second_string): return second_str else: return 'This does not work.' first_string = 'helo' second_string = 'olhe' print(check_string(first_string, second_string)) # prints True first_string = 'helo' second_string = 'hello' print(check_string(first_string, second_string)) # prints True first_string = 'helo' second_string = 'helofoo' print(check_string(first_string, second_string)) # prints 'This does not work.' </code></pre>
0
2016-08-17T22:05:41Z
[ "python" ]
Why does this code not work for all inputs
39,006,826
<p>I am trying to write python code that takes two strings as input and checks if all the characters of the second string are present in the first string. If so, then the output is the second string. If not, the output is the string "This does not work". I have tested this procedure for a variety of inputs, and it typically works, but not always. For example, if my two inputs are "helo" and "olhe", respectively, the output is "This does not work," whereas it should be "olhe" since all the characters in "olhe" are present in "helo."</p> <p>Here is my code</p> <pre><code>def fix_machine(debris,product): n = 1 while True: first_element = product[0:n] find_first_element = debris.find(first_element) if first_element == product: return product break n = n + 1 if find_first_element == -1: return "This does not work" break </code></pre> <p>So why does this not work?</p>
0
2016-08-17T21:52:18Z
39,007,038
<p>I agree that you should step through that code with a debugger (maybe try PyCharm if you don't have an IDE set up yet) to see what went wrong. Would be hard to explain whats going wrong but I think it has something to do with <code>first_element = product[0:n]</code>. This will return increasingly larger segments of the string. i.e. 'ol' on the second run through.</p> <p>Here's an alternative way of writing it</p> <pre><code>def fix_machine(debris, product): all_present = all(letter in debris for letter in product) return product if all_present else 'This does not work' </code></pre>
0
2016-08-17T22:11:09Z
[ "python" ]
python-docx add horizontal line
39,006,878
<p>Is it possible to add a single horizontal line spanning the entire page width after a paragraph?</p> <p>By using the <code>add_header</code> such a line is created after the header:</p> <pre><code> document.add_heading('Test', 0) </code></pre> <p>I'd need such a line between two paragraphs in the document, so is it possible to just add the line by itself?</p>
0
2016-08-17T21:57:11Z
39,009,362
<p>This is not supported directly yet by the <code>python-docx</code> API.</p> <p>However, you can achieve this effect by creating a paragraph style that has this border setting in the "template" document you open to create a new document, e.g.</p> <pre><code>document = Document('template-with-style.docx') </code></pre> <p>Then you can apply that style to a new paragraph in that document using python-docx.</p>
1
2016-08-18T03:05:49Z
[ "python", "python-docx" ]
Display python data on node.js when python is still running
39,006,939
<p>I have a long running python script, and I want to use a node.js to display the data python prints(becasue I will make it a server and send data to somewhere else), I used python-shell, it doesn't display anything until the whole python finished, it there any way to display 'partial' output?</p> <pre><code>var pshell = require('python-shell'); var prompt = require('prompt'); var command = 'start'; prompt.start(); function receivecommand() { prompt.get(['input'], function(err, result) { if(result.input == command) { run(); console.log('run') } else {console.log('type start') receivecommand(); } }) } receivecommand(); function run() { var ps = new pshell('hello.py'); ps.on('message', function(message) { console.log(message); }); ps.end(function(err) { if (err) throw err; console.log('finished') }); } </code></pre> <p>for now hello.py is just running a time-delay loop and print something out. </p>
0
2016-08-17T22:01:45Z
39,007,825
<p>The easiest way is to setup a server with node js and just send requests with the data that is suppose to be printed. I am giving this solution of course in the prior knowledge that you have control of what is printed. ( You didn't mention if the output is coming from a script that you wrote or it is coming from another library or script of python.)</p>
0
2016-08-17T23:37:13Z
[ "javascript", "python", "node.js" ]
Django url not found upon submitting form
39,006,956
<p>My apologies if the question is stupid, I am a newbie to this. I am creating a django web application. I have created a form inside it. When I submit the form, it says 'url' not found even though the same URL loads fine for the first time when opening the form. This is whats confusing me. Here is my code:</p> <pre><code>#forms.py class Recipe_ruleForm(forms.ModelForm): class Meta: model = Recipe_rule fields = ('content',) #urls.py url(r"^create_recipe_rule/(?P&lt;recipe_pk&gt;[0-9]+)/$",views.create_recipe_rule, name="create_recipe_rule"), #views.py def create_recipe_rule(request, recipe_pk): form = Knowledgebase_ruleForm selected_recipe = Recipe.objects.get(pk = recipe_pk) if request.method == 'POST': form = Recipe_ruleForm(request.POST) if form.is_valid(): #current_user = request.user data = form.cleaned_data recipe_rule_data=Recipe_rule.objects.create(recipe=selected_recipe, content=data['content']) recipe_rule_data.save() recipe_rule = Recipe_rule.objects.get(pk = recipe_rule_data.pk) recipe=selected_recipe recipe = Recipe.objects.get(pk = recipe.pk) return redirect('recipe_detail', pk=recipe.pk) else: messages.error(request, "Error") return render(request, 'create_recipe_rule.html' , {'form': form}) </code></pre> <p>Here is the error when I submit the form:</p> <blockquote> <p>Page not found (404) Request Method: POST Request URL: <a href="http://[ip_adress]:[port]/create_recipe_rule/" rel="nofollow">http://[ip_adress]:[port]/create_recipe_rule/</a></p> </blockquote> <p><strong>UPDATE:</strong></p> <p>Here is my template:</p> <pre><code>{% extends "account/base.html" %} {% load i18n %} {% load bootstrap %} {% block body_class %}applications{% endblock %} {% block head_title %}{% trans "Create recipe" %}{% endblock %} {% block body %} &lt;form action="/create_recipe_rule/" method="post"&gt; {% csrf_token %} &lt;div class="form-group"&gt; &lt;label for="{{ form.content.label }}"&gt;{{ form.content.label }}:&lt;/label&gt; &lt;textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="{{ form.content.id }}"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;input class="btn btn-default" type="submit" value="submit"&gt; &lt;/form&gt; {% endblock %} </code></pre>
0
2016-08-17T22:03:10Z
39,007,250
<p>You have <code>action="/create_recipe_rule/"</code>, which is missing the recipe id.</p> <p>One option is to simply remove the action from the form, then your browser will submit the request to the current url.</p> <pre><code>&lt;form method="post"&gt; </code></pre> <p>If you do want to include the form action, then first you need to update your view so that it includes the recipe id in the template context.</p> <pre><code>return render(request, 'create_recipe_rule.html' , {'form': form, recipe_id: recipe_id }) </code></pre> <p>Then you can update the form action to include the recipe id.</p> <pre><code>action="/create_recipe_rule/{{ recipe_id }}" </code></pre> <p>It's good practice to use the <code>{% url %}</code> tag, so that you are not hardcoding urls in the template:</p> <pre><code>action="{% url 'create_recipe_rule' recipe_id %}" </code></pre>
1
2016-08-17T22:31:53Z
[ "python", "django", "forms" ]
error of no log results dumped to file by running an executable file from Python subprosess
39,006,982
<p>This question is related to my previous question.</p> <p><a href="http://stackoverflow.com/questions/38928330/error-of-running-an-executable-file-from-python-subprosess">Error of running an executable file from Python subprosess</a></p> <p>I am trying to run an executable file (a linear programming solver CLP.exe) from Python 3.5. </p> <pre><code> Import subprocess exeFile = "C:\\MyPath\\CLP.exe" arg1 = "C:\\Temp\\LpModel.mps" arg2 = "-max" arg3 = "-dualSimplex" arg4 = "-printi" arg4a = "all" arg5 = "-solution" arg6 = "solutionFile.txt" arg7 = "-log" arg8 = "6" arg9 = "&gt;" arg10 = "log.txt" subprocess.check_output([exeFile, arg1, arg2, arg3, arg4a, arg5,arg6, arg7, arg8, arg9, arg10], stderr=subprocess.STDOUT, shell=False) </code></pre> <p>When I run the python file in Eclipse PyDev, I can see the results in Eclipse console and the solution results are also saved in "solution.txt".</p> <p>But, no log results are saved at the file of "log.txt".</p> <p>In the Eclipse console, I got: </p> <pre><code> b'Coin LP version 1.16, build Dec 25 2015 command line - C:\\MyPath\\clp.exe C:\\Temp\\LpModel.mps -max -dualSimplex -printi all -solution C:\\Temp\\solutionFile.txt &gt; log.txt Optimal - objective value 118816.5 Optimal objective 110 - 40 iterations time 0.022 logLevel was changed from 1 to 6 No match for &gt; - ? for list of commands No match for log.txt - ? for list of commands </code></pre> <p>When I run the command in MS windows shell from command line: </p> <pre><code> C:\\MyPath\\clp.exe C:\\Temp\\LpModel.mps -max -dualSimplex -printi all -solution C:\\Temp\\solution.txt &gt; log.txt </code></pre> <p>I can get log results in log.txt.</p> <p>Why the log.txt file was not created and no log results were saved to it if I run the command from Python subprocess ? </p>
0
2016-08-17T22:05:37Z
39,007,186
<p>You can replace your default stdout descriptor with your log file descriptor. Try this</p> <pre><code>with open('log.txt', 'w+') s fid: subprocess.check_call([arg1,...,arg8],stdout = fid, stderr=subprocess.STDOUT, shell = False) </code></pre>
0
2016-08-17T22:25:30Z
[ "python", "python-3.x", "subprocess", "pydev" ]
Python flask: how to avoid users from browsing static directory
39,006,985
<p>I followed digital ocean <a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps" rel="nofollow">tutorial</a> to deploy my Flask application using Apache server. Now the problem is when a user visits <code>mywebsite.com/static</code>, all the files in the static directory is available to that user. How to avoid users from browsing static directory? </p> <p>My apache virtual host file looks this:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName mywebsite.com ServerAdmin admin@mywebsite.com WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi &lt;Directory /var/www/FlaskApp/FlaskApp/&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/FlaskApp/FlaskApp/static &lt;Directory /var/www/FlaskApp/FlaskApp/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre>
0
2016-08-17T22:05:40Z
39,007,113
<p>You can prevent generation of directory indexes with the <code>Option -Indexes</code> directive:</p> <pre><code> &lt;Directory /var/www/FlaskApp/FlaskApp/static/&gt; Order allow,deny Allow from all Options -Indexes &lt;/Directory&gt; </code></pre> <p>Alternatively, you can place the directive in an <code>.htaccess</code> file in the appropriate directory. </p>
0
2016-08-17T22:16:58Z
[ "python", "apache" ]
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"username"}
39,007,011
<p>Here's the method I wrote with selenium to login to my webpage:</p> <pre><code>def login(self, username, password): driver.switch_to.default_content() driver.switch_to.frame("iframe") driver.find_element_by_id("username").send_keys(username) driver.find_element_by_id("password").send_keys(password) driver.find_element_by_id("loginButton").click() </code></pre> <p>Here's the code I have in Robot Framework:</p> <pre><code>*** Settings *** Library CustomSelenium2Plus.py *** Test Cases *** SR Create New Service Open Browser https://partner.sdg.msg.lab.t-mobile.com/tpim/ Chrome ${webdriver}= Get webdriver instance Set Driver ${webdriver} Login usrnm pwd ... Delete Service Close Browser </code></pre> <p><code>CustomSelenium2Plus.py</code> is a custom library I wrote that subclasses RobotFramework's Selenium2Library and is where the login method is located. The method is totally functional when I call it the first time with the <code>Login</code> Keyword. However, it throws a <code>NoSuchElementException</code> when it's called a second time within <code>Delete Service</code> Keyword's function which looks like this:</p> <pre><code>def delete_service(self): self.logout() self.login("usrnm", "pwd") ... </code></pre> <p>I've already checked that the frame is correct. I've also already tried having my <code>WebDriver</code> wait for the visibility of both the iframe and the username textarea, an implicit <code>WebDriverWait</code>, and a <code>time.sleep(30)</code>.</p> <p>EDIT: The HTML code isn't mine and pretty ugly but here's a screencap</p> <p><a href="http://i.stack.imgur.com/dKeOo.png" rel="nofollow"><img src="http://i.stack.imgur.com/dKeOo.png" alt="enter image description here"></a></p> <p>There are technically four iframes nested within each other but calling <code>driver.switch_to.frame("iframe")</code> any more than once throws a <code>NoSuchFrameException</code></p>
-2
2016-08-17T22:08:29Z
39,009,429
<p>I would have guessed that repeating the line <code>driver.switch_to.frame("iframe")</code> a few times would have worked. Technically that id is not unique on the page so I would try using an index instead. From the HTML you provided, it looks like the <code>IFRAME</code> you want is the first one each time. The below will hopefully work.</p> <pre><code>driver.switch_to.default_content() driver.switch_to.frame(0) driver.switch_to.frame(0) driver.switch_to.frame(0) driver.find_element_by_id("username").send_keys(username) driver.find_element_by_id("password").send_keys(password) driver.find_element_by_id("loginButton").click() </code></pre> <p>The first line technically isn't necessary unless you are executing code before this that dives into an <code>IFRAME</code> but I included it because you had it above.</p>
0
2016-08-18T03:14:02Z
[ "python", "selenium", "robotframework" ]