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
parameters substitution from one .py file to another .py file
37,821,733
<p>I have a parameter file with all param values . I want to pass these values to another .py (raw sql file) and generate an executable sql file Here is what I have so far</p> <p>params.py file</p> <pre><code>var1 = '1,2,3' var2 = '('abc', 'cde', 'xyz')' </code></pre> <p>rawsql.py</p> <pre><code>import params ...
0
2016-06-14T20:42:54Z
37,821,961
<p>The following snippet will give you and idea of what you need to do:</p> <pre><code>import params # filter non built-in variable names variables = [k for k in params.__dict__ if '__' not in k] with open('rawsql.sql', 'r') as f: content = f.read() for v in variables: content = content.replace(v, getattr(pa...
0
2016-06-14T20:58:07Z
[ "python", "input", "substitution", "parameterization" ]
parameters substitution from one .py file to another .py file
37,821,733
<p>I have a parameter file with all param values . I want to pass these values to another .py (raw sql file) and generate an executable sql file Here is what I have so far</p> <p>params.py file</p> <pre><code>var1 = '1,2,3' var2 = '('abc', 'cde', 'xyz')' </code></pre> <p>rawsql.py</p> <pre><code>import params ...
0
2016-06-14T20:42:54Z
37,822,326
<p>Maybe try something like this? Instead return sql write to file. </p> <p>params.py file</p> <pre><code>def var1(): return = '1,2,3' def var2(): return '('abc', 'cde', 'xyz')' </code></pre> <p>rawsql.py</p> <pre><code>import params def sqlCont(): return "select * from emp.ids where ids in '%s' and na...
0
2016-06-14T21:20:19Z
[ "python", "input", "substitution", "parameterization" ]
image scaling in loop using python OpenCV
37,821,769
<p>I am new to Python and I am having a really hard time figuring out how to transform what I got here into a loop. As you can see here I am doing a basic image scaling to 3 different images (from mask_0001.png to mask_0003.png), but I will have more than 100 to go later on, so I will have to do it in a loop I guess. (...
1
2016-06-14T20:45:21Z
37,821,934
<p>This loops <code>i</code> from 1 to 150, setting the mask to <code>i</code>.</p> <p>Python 2 </p> <pre><code>for i in range(1,151): img = cv2.imread("C://Users//user//Desktop//research//images//Mask//set1//set1_mask_" + str(i).zfill(4) +".png") res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = c...
0
2016-06-14T20:56:26Z
[ "python", "loops", "opencv", "io", "path" ]
Is it possible to import a function as a class method?
37,821,852
<p>I'm wondering if this is even possible. </p> <p>Let's say, there are two files. </p> <p>in a.py:</p> <pre><code>class A() </code></pre> <p>in b.py:</p> <pre><code>def x(): def y(): </code></pre> <p>I'd like to import a function x() from b.py to a.py's class A so that the class A has a method x.</p> <p>so th...
0
2016-06-14T20:51:32Z
37,821,999
<p>If the functions signature doesn't allow for an instance of <code>A</code> to be passed as the first argument the best you can do is make them <code>staticmethod</code>s:</p> <pre><code>import b class A: x = staticmethod(b.x) y = staticmethod(b.y) test = A() test.x() </code></pre> <p>However if you had fu...
2
2016-06-14T21:00:20Z
[ "python" ]
Is it possible to import a function as a class method?
37,821,852
<p>I'm wondering if this is even possible. </p> <p>Let's say, there are two files. </p> <p>in a.py:</p> <pre><code>class A() </code></pre> <p>in b.py:</p> <pre><code>def x(): def y(): </code></pre> <p>I'd like to import a function x() from b.py to a.py's class A so that the class A has a method x.</p> <p>so th...
0
2016-06-14T20:51:32Z
37,822,129
<p>Why not try it?</p> <p><strong>a.py</strong></p> <pre><code>class A(): from b import x, y a = A() a.x() </code></pre> <p><strong>b.py</strong></p> <pre><code>def x(): print "Hi, I'm x!" def y(): print "Hi, I'm y!" </code></pre> <p>Yikes, that didn't work!</p> <pre><code>Traceback (most recent ca...
1
2016-06-14T21:09:15Z
[ "python" ]
Adding new rows to dataframe subsets using Pandas
37,821,903
<p>I have the following dataframe:</p> <pre><code>Customer ProductID Count John 1 25 John 6 50 Mary 2 15 Mary 3 35 </code></pre> <p>I want my output to look like this:</p> <pre><code>Customer ProductID Count John 1 25 John 2 0 John 3 ...
1
2016-06-14T20:54:45Z
37,821,953
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> - you get <code>NaN</code> values which are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</c...
1
2016-06-14T20:57:38Z
[ "python", "pandas", "dataframe" ]
Python: pull fields from formatted string
37,821,977
<p>I have a list of strings that are formatted as key/value pairs, separated by spaces. For example, a message may be:</p> <pre><code>"time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 user=Username subject=subject goes here message=This is a message" </code></pre> <p>The key/value pairs will always be in that ord...
2
2016-06-14T20:59:24Z
37,822,412
<p>ok, quickly threw something together</p> <pre><code>inputString = "time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 user=Username subject=subject goes here message=This is a message" keys = [] #key is always the element before the '=' sign for segment in inputString.split('='): keys.append(segment.split(" "...
0
2016-06-14T21:26:29Z
[ "python", "regex", "parsing", "dictionary" ]
Python: pull fields from formatted string
37,821,977
<p>I have a list of strings that are formatted as key/value pairs, separated by spaces. For example, a message may be:</p> <pre><code>"time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 user=Username subject=subject goes here message=This is a message" </code></pre> <p>The key/value pairs will always be in that ord...
2
2016-06-14T20:59:24Z
37,822,449
<p>A little lateral thinking: split on the '=', which leaves each label at the end of the previous row. For instance:</p> <pre><code>in_stuff = "time=2016/06/14 16:44:00.000 level=1 sequenceNum=35" +" user=Username message=This is a message" skew = in_stuff.split('=') table = [entry.split() for entry in sk...
0
2016-06-14T21:29:02Z
[ "python", "regex", "parsing", "dictionary" ]
Python: pull fields from formatted string
37,821,977
<p>I have a list of strings that are formatted as key/value pairs, separated by spaces. For example, a message may be:</p> <pre><code>"time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 user=Username subject=subject goes here message=This is a message" </code></pre> <p>The key/value pairs will always be in that ord...
2
2016-06-14T20:59:24Z
37,822,463
<p>For this I would go with regular expressions. That might not be the fastest (performance-wise) or the easiest (to understand) solution but it will certainly work. (And is probably the closest you will get to a "reverse-format")</p> <pre><code>import re pattern = re.compile( "time=(?P&lt;time&gt;.+)\s" "lev...
2
2016-06-14T21:29:57Z
[ "python", "regex", "parsing", "dictionary" ]
Python: pull fields from formatted string
37,821,977
<p>I have a list of strings that are formatted as key/value pairs, separated by spaces. For example, a message may be:</p> <pre><code>"time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 user=Username subject=subject goes here message=This is a message" </code></pre> <p>The key/value pairs will always be in that ord...
2
2016-06-14T20:59:24Z
37,822,622
<p>You can use a regular expression and <code>re.findall()</code> to find each key-value-pair. The advantage of this method is that it should work with any string of <code>key=value</code> pairs.</p> <pre><code>import re data = ("time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 " "user=Username subject=subj...
2
2016-06-14T21:43:28Z
[ "python", "regex", "parsing", "dictionary" ]
Python: pull fields from formatted string
37,821,977
<p>I have a list of strings that are formatted as key/value pairs, separated by spaces. For example, a message may be:</p> <pre><code>"time=2016/06/14 16:44:00.000 level=1 sequenceNum=35 user=Username subject=subject goes here message=This is a message" </code></pre> <p>The key/value pairs will always be in that ord...
2
2016-06-14T20:59:24Z
37,823,246
<p>I came up with something to allows you use custom converters.</p> <pre><code>class Convert(object): def __init__(self, *args): self.content = ' '.join(args) def sequenceNum(self): return int(self.content) def level(self): return int(self.content) def __getattr__(self, name...
0
2016-06-14T22:36:43Z
[ "python", "regex", "parsing", "dictionary" ]
Text Adventure - Inventory Drop
37,821,996
<p>I am making a rogue-like game and was wondering if there was a way to allow a player to drop an item by entering: <code>Drop [Item Name]</code></p> <p><code>Drop</code> being the command and the item name being one located in your inventory, e.g. if I had a rock that I wanted to get rid of I would input: <code>Drop...
0
2016-06-14T21:00:08Z
37,822,049
<p>you might want to take a look at <a href="https://docs.python.org/3/library/cmd.html" rel="nofollow">cmd</a>, which makes command handling much easier</p> <p>you can create functions for each command, that are then being called</p>
0
2016-06-14T21:03:31Z
[ "python", "python-3.x" ]
Text Adventure - Inventory Drop
37,821,996
<p>I am making a rogue-like game and was wondering if there was a way to allow a player to drop an item by entering: <code>Drop [Item Name]</code></p> <p><code>Drop</code> being the command and the item name being one located in your inventory, e.g. if I had a rock that I wanted to get rid of I would input: <code>Drop...
0
2016-06-14T21:00:08Z
37,822,072
<p>Since you're using numbered slots (rather than e.g. "bag", "pocket") a simpler approach would be to use a list for your inventory. You can index into a list, and find items in a list by value, easily.</p> <p>I would also suggest you use <code>None</code> or at least an empty string <code>""</code> to represent the ...
1
2016-06-14T21:05:06Z
[ "python", "python-3.x" ]
Text Adventure - Inventory Drop
37,821,996
<p>I am making a rogue-like game and was wondering if there was a way to allow a player to drop an item by entering: <code>Drop [Item Name]</code></p> <p><code>Drop</code> being the command and the item name being one located in your inventory, e.g. if I had a rock that I wanted to get rid of I would input: <code>Drop...
0
2016-06-14T21:00:08Z
37,828,157
<p>I took it one step further than @mfitzp and made it all one line of code so that <em>Drop Stick</em> will drop a stick. Here is the code I used:</p> <pre><code>def DROP(CHOICE): global NV NV = CHOICE[5:] str(NV) CHOICE = input("\nWhat do you want to do (type Help for list of commands): ") if CHOICE....
0
2016-06-15T06:58:40Z
[ "python", "python-3.x" ]
Efficiently measuring how long a process has been running
37,822,109
<p>I am trying to count the elapsed time of a process(tracking time in a game). The following code works but keeps the CPU busy constantly. I'd imagine it's something to do with the while loop constantly polling to check if the process is still running. Could there be a more efficent way of implementing this?</p> <pre...
1
2016-06-14T21:07:22Z
37,822,812
<p>You ought use <a href="https://pythonhosted.org/psutil/" rel="nofollow">psutil</a> (python system and process utilities) to search for a running process.</p> <p>Please note that the <code>pidof</code> command only works on Linux based system, Unix user either try <code>ps</code> command or <code>pgrep</code> comman...
0
2016-06-14T21:59:13Z
[ "python", "optimization", "subprocess" ]
Invalid file error when trying to open file in PyQT5
37,822,131
<p>I am trying to make a basic text editor and I am using PYQT5 to do so however when I try to open or save a file I get errors, for open I get:</p> <pre><code>File "D:\NicKLz\Documents\GitHub\MiscProjects\TextEditor\txtEditor.py", line 81, in open with open(self.filename, "r") as file: TypeError: invalid file: ('...
0
2016-06-14T21:09:25Z
37,822,182
<p><code>self.filename</code> is a tuple so obviously you cannot treat it as a string, there are two elements returned from the method, you want the first so unpack:</p> <pre><code>self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)") </code></pre> <p>Or index:</p> <pre><cod...
1
2016-06-14T21:12:17Z
[ "python", "python-3.x", "pyqt", "qt5", "pyqt5" ]
Why does Python support both tuple and dict formatting using the percent operator in a specific case?
37,822,180
<p>This input:</p> <pre><code>'%s %(?)s' % {'?': 'a'} </code></pre> <p>results in this output:</p> <pre><code>"{'?': 'a'} a" </code></pre> <p>which replaces both the tuple-based and dict-based placeholders in the source string with the value you would expect if you used either of them alone.</p> <p>However, if you...
4
2016-06-14T21:12:14Z
37,822,574
<p>Each %s consumes one of the variable after the standalone % symbol. In the first case there are two variables, the while expression and the dictionary mapping.</p> <p>In the second case, the first %s takes the dictionary mapping and consumes the whole expression, has evaluated it. That leaves the second %s without...
0
2016-06-14T21:39:41Z
[ "python", "dictionary", "tuples", "string-formatting" ]
How to add a new line with print when another variable is in place (Python 3.x)
37,822,217
<p>I am new to learning Python 3.0 and I am trying to solve an issue I have with making a list and printing at the end of it a new line to separate printing between two strings. </p> <p>I.E.</p> <pre><code>list_1 = ['Autumn', 'Mary', 'Ditto', 'Gamma'] print(list_1) print(list_1[2]) Output: ['Autumn', 'Mary', 'Ditto'...
0
2016-06-14T21:14:43Z
37,822,251
<p>Yes, set <code>end="\n\n"</code> to add an extra newline or as many as you want:</p> <pre><code>print(list_1, end="\n\n") print(list_1[2]) </code></pre> <p>Or a single print using <em>sep</em>:</p> <pre><code>print(list_1, list_1[2], sep="\n\n") </code></pre>
0
2016-06-14T21:16:07Z
[ "python", "python-3.x" ]
Pandas read_pickle slowness
37,822,220
<p>I have Python 3.4 with Pandas 0.17. I noticed that my program takes ~30 seconds to read a pickle file. </p> <pre><code>df= pd.read_csv(a, skiprows=[1]) df.to_pickle(b) df2 = pd.read_pickle(b) --- This line takes almost 30 seconds. </code></pre> <p>The original csv file is ~185 MB (2967000 lines) and the pickle fi...
0
2016-06-14T21:14:44Z
37,842,845
<p>I found a way to resolve the issue. My pickle file was being created by a cronjob from root user. Python program was developed in virtual environment. Global environment does not have pandas. So when the root user ran the cronjob, it created pickle file successfully but something was wrong with this file. I modified...
0
2016-06-15T18:13:54Z
[ "python", "performance", "pandas", "pickle" ]
How to share multiple dictionaries between processes
37,822,270
<p>I use the multiprocessing package for a multi-layered application and I want to share multiple dicts within a few processes.</p> <p>I found the multiprocessing.Manager class already but it seems like it provides only one dict (Manager.dict()) per application. For me it looks like something like a <a href="https://e...
1
2016-06-14T21:17:16Z
37,822,569
<p>As far as I can tell, a single <code>Manager</code> instance can manage multiple independent <code>dict</code>. Here's a simple example:</p> <pre><code>from multiprocessing import Process, Manager def f(x, d1, d2): if x == 1: d1['foo'] = 'bar' if x == 2: d2['bar'] = 'foo' print x, d1, ...
1
2016-06-14T21:39:01Z
[ "python", "python-3.x", "multiprocessing" ]
Flask-Restful basic setup
37,822,362
<p>When I try to go to <code>/api</code> I get to convert my database to an api.</p> <pre><code>from flask import Flask , render_template from flask_restful import Resource, Api,marshal_with, fields from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') api = Api(app) db = S...
-1
2016-06-14T21:22:45Z
37,822,614
<p>This annotation is expecting a dictionary <code>@marshal_with</code>. </p> <p>You ended up giving it your <code>songbook</code> class, which, while you could maybe <code>def __dict__(self)</code> (not sure, haven't tried) on it and have it return a schema, it looks like you meant to do <code>@marshal_with(resouce_f...
0
2016-06-14T21:42:38Z
[ "python", "flask", "flask-restful" ]
I require assistance in understanding what's wrong with my code (if statements)
37,822,369
<p>I'm not sure what I did wrong in this code, but for some reason, Eclipse keeps on telling me that the if statement is just bad. I'm not sure why, when I look at the examples, it looked fine to me.</p> <pre><code>penny = .01 nickel = .05 dime = .1 quarter = .25 print("Enter how many coins you want to use to make a ...
0
2016-06-14T21:23:27Z
37,822,405
<p>If statements require a colon and proper indentation, see:</p> <pre><code>if doll &gt; 1: print("blah") else: Print ("Try again") </code></pre> <p>Note, the indentation is 4 spaces.</p>
1
2016-06-14T21:26:02Z
[ "python", "eclipse", "if-statement" ]
Python, OpenCV: Increasing image brightness without overflowing UINT8 array
37,822,375
<p>I am trying to increase brightness of a grayscale image. <code>cv2.imread()</code> returns a numpy array. I am adding integer value to every element of the array. Theoretically, this would increase each of them. After that I would be able to put upper threshold of 255 and get the image with the higher brightness.</p...
2
2016-06-14T21:23:43Z
37,822,699
<p>One idea would be to check before adding <code>value</code> whether the addition would result in an overflow by checking the difference between <code>255</code> and the current pixel value and checking if it's within <code>value</code>. If it does, we won't add <code>value</code>, we would directly set those at <cod...
3
2016-06-14T21:50:24Z
[ "python", "arrays", "opencv", "numpy", "image-processing" ]
Python, OpenCV: Increasing image brightness without overflowing UINT8 array
37,822,375
<p>I am trying to increase brightness of a grayscale image. <code>cv2.imread()</code> returns a numpy array. I am adding integer value to every element of the array. Theoretically, this would increase each of them. After that I would be able to put upper threshold of 255 and get the image with the higher brightness.</p...
2
2016-06-14T21:23:43Z
37,823,528
<p>Briefly, you should add 50 to each value, find <code>maxBrightness</code>, then <code>thisPixel = int(255 * thisPixel / maxBrightness)</code></p> <p>You have to run a check for an overflow for each pixel. The method suggested by Divakar is straightforward and fast. You actually might want to increment (by 50 in you...
2
2016-06-14T23:04:54Z
[ "python", "arrays", "opencv", "numpy", "image-processing" ]
Python, OpenCV: Increasing image brightness without overflowing UINT8 array
37,822,375
<p>I am trying to increase brightness of a grayscale image. <code>cv2.imread()</code> returns a numpy array. I am adding integer value to every element of the array. Theoretically, this would increase each of them. After that I would be able to put upper threshold of 255 and get the image with the higher brightness.</p...
2
2016-06-14T21:23:43Z
38,519,098
<p>An alternate approach that worked efficiently for me is to "blend in" a white image to the original image using the blend function in the PIL>Image library.</p> <pre><code>from PIL import Image correctionVal = 0.05 # fraction of white to add to the main image img_file = Image.open(location_filename) img_file_white ...
0
2016-07-22T05:51:48Z
[ "python", "arrays", "opencv", "numpy", "image-processing" ]
TemplateNotFound when using Airflow's PostgresOperator with Jinja templating and SQL
37,822,380
<p>When trying to use Airflow's templating capabilities (via Jinja2) with the PostgresOperator, I've been unable to get things to render. It's quite possible I'm doing something wrong, but I'm pretty lost as to what the issue might be. Here's an example to reproduce the TemplateNotFound error I've been getting:</p> <p...
2
2016-06-14T21:24:04Z
37,823,033
<p>Standard <a href="https://en.wikipedia.org/wiki/User_error" rel="nofollow">PEBCAK error</a>.</p> <p>There was an issue specifying the path to the SQL template within the given Airflow task, which needed to be relative.</p> <pre><code>copy_s3_to_redshift = PostgresOperator( task_id='load_table', sql='/copy_...
0
2016-06-14T22:17:40Z
[ "python", "jinja2", "airflow" ]
Plotting based on groupby
37,822,419
<p>I have a df like so:</p> <pre><code>Year Grass Crop Forest Ecoregion CRP 1993 30.41268857 68.45446692 0.255632102 46e 0508common 2001 47.29988968 47.68577796 0.509939614 46e 0508common 2006 71.37357063 20.40485399 0.908684114 46e 0508common 1993 27.17246635...
1
2016-06-14T21:26:56Z
37,823,711
<p>You had a mistake in plot. You have to plot inner group (<code>igr</code>) not outer. I had slightly changed your code to be more smoothly:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import os lu_colors=(['g','y','b','r','k']) df = pd.re...
1
2016-06-14T23:22:15Z
[ "python", "pandas", "matplotlib" ]
Scrape and login to angular webabb using Python
37,822,455
<p>I'm trying to login to an angular webapp. </p> <p>I tried using multiple packages like requests, urllib, mechanize etc., but can't figure out what I'm missing/ is going wrong. Here's the code:</p> <pre><code>import requests from requests.utils import quote session = requests.Session() session.cookies.get_dict() u...
0
2016-06-14T21:29:30Z
37,822,631
<p>Maybe i am mistaken, but AngularJS is a JS-Framework. That means that the Login-Form is rendered by the browser on runtime and not present in the pure HTML code. The Packages you mentined do not render JS. They only download the sourcecode. Maybe have a look here on how to work with JS-based websites: <a href="http:...
0
2016-06-14T21:44:03Z
[ "javascript", "python", "angularjs", "login", "web-scraping" ]
Import CSV and create one list for each column in Python
37,822,459
<p>I am trying to import a CSV file into python delimited by a comma (,).</p> <p>Each column is a sampled parameter, for instance column 0 is time, sampled at once a second, column 1 is altitude sampled at 4 times a second, etc. </p> <p>So columns will look like as below:</p> <pre><code>Column 0 -&gt; ["Time", 0, " ...
0
2016-06-14T21:29:40Z
37,822,871
<p>Pandas will probably work best for you. If you use csv_read from pandas, it will create a DataFrame based on the column. It's roughly a dictionary of lists.</p> <p>You can also use the .tolist() functionality of pandas to convert it to a list if you want a list specifically.</p> <pre><code>import pandas as pd data...
1
2016-06-14T22:03:57Z
[ "python", "csv", "variables", "dynamic" ]
Import CSV and create one list for each column in Python
37,822,459
<p>I am trying to import a CSV file into python delimited by a comma (,).</p> <p>Each column is a sampled parameter, for instance column 0 is time, sampled at once a second, column 1 is altitude sampled at 4 times a second, etc. </p> <p>So columns will look like as below:</p> <pre><code>Column 0 -&gt; ["Time", 0, " ...
0
2016-06-14T21:29:40Z
37,823,610
<p>I think I made my problem more simpler and just focused on one column. </p> <p>What I ultimately wanted to do was to interpolate to the highest sampling rate. So here is what I came up with... Please let me know if I can do anything more efficient. I used A LOT of searching on this site to help build this. Again I ...
0
2016-06-14T23:13:11Z
[ "python", "csv", "variables", "dynamic" ]
python: adding any number of days to date
37,822,478
<p>I am hoping someone can point me in the right direction in working with dates and timedelta.</p> <p>my understanding is that to add any number (ex: 10 days) to a date, you need to convert it to a timedelta. if that is correct, how can I add any number to a date when it is an integer?</p> <p>any documentation or li...
-2
2016-06-14T21:31:35Z
37,822,575
<pre><code>x=20100103 x2 = int((datetime.datetime.strptime(str(x),"%Y%m%d") + datetime.timedelta(days=10)).strftime("%Y%m%d")) </code></pre> <p>to break it down</p> <pre><code>x=20100103 x_as_datetime = datetime.datetime.strptime(str(x),"%Y%m%d") new_datetime = x_as_datetime + datetime.timedelta(days=10) #add your t...
3
2016-06-14T21:39:42Z
[ "python", "date", "timedelta" ]
python: adding any number of days to date
37,822,478
<p>I am hoping someone can point me in the right direction in working with dates and timedelta.</p> <p>my understanding is that to add any number (ex: 10 days) to a date, you need to convert it to a timedelta. if that is correct, how can I add any number to a date when it is an integer?</p> <p>any documentation or li...
-2
2016-06-14T21:31:35Z
37,822,617
<pre><code>from datetime import datetime from datetime import timedelta StartDate = "20100103" Date = datetime.strptime(StartDate, "%Y%m%d") EndDate = Date + timedelta(days=10) </code></pre>
1
2016-06-14T21:43:08Z
[ "python", "date", "timedelta" ]
python: adding any number of days to date
37,822,478
<p>I am hoping someone can point me in the right direction in working with dates and timedelta.</p> <p>my understanding is that to add any number (ex: 10 days) to a date, you need to convert it to a timedelta. if that is correct, how can I add any number to a date when it is an integer?</p> <p>any documentation or li...
-2
2016-06-14T21:31:35Z
37,822,655
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; today = datetime.datetime.now().date() &gt;&gt;&gt; today datetime.date(2016, 6, 14) &gt;&gt;&gt; today + datetime.timedelta(days=10) datetime.date(2016, 6, 24) </code></pre> <p>There's no need to convert it to a timedelta. Just use the timedelta function, if you wa...
1
2016-06-14T21:46:39Z
[ "python", "date", "timedelta" ]
Show "still loading" in django
37,822,560
<p>I have two things I want to address, and I'm new to <code>django</code> and styling: First, I have this algorithm I'm running on the upload file and it takes time to load, so I want to show loading message or so until the <code>output.csv</code> is generated and ready to download (after home function is executed). I...
0
2016-06-14T21:38:20Z
37,830,585
<p>Not the final solution - but to give an idea: As Rajesh did mention in the comment this can be addressed client side (with JavaScript/jQuery). So you could add the desired message when submitting the form.</p> <h3>Question 1</h3> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta cha...
0
2016-06-15T08:53:28Z
[ "javascript", "python", "html", "django", "django-templates" ]
How to initialize static member based on constructor args?
37,822,573
<p>I need to have static or external list, that will be used by every object of <code>A</code> class. The values of the list need to be initialized only once and should be taken from constructor parameters, e.g:</p> <pre><code>def initialize(x, y): for i in range(0, x): static_to_return.append([]) ...
2
2016-06-14T21:39:40Z
37,822,774
<p>It seems like you actually want to provide <code>x</code> and <code>y</code> when the <em>class</em> is created, not when an <em>instance</em> is created. If all instances will share the same values, you do not need to provide them as parameters to <code>__init__</code>.</p> <p>Depending on how complex your class i...
-1
2016-06-14T21:56:32Z
[ "python", "static" ]
How to initialize static member based on constructor args?
37,822,573
<p>I need to have static or external list, that will be used by every object of <code>A</code> class. The values of the list need to be initialized only once and should be taken from constructor parameters, e.g:</p> <pre><code>def initialize(x, y): for i in range(0, x): static_to_return.append([]) ...
2
2016-06-14T21:39:40Z
37,822,960
<p>If you want the static member to be initialized from the <strong>first</strong> object of the class, you could initialize it to <code>None</code> in class definition, and test its value in instance constructor:</p> <pre><code>class A: static_member = None def __init__(self, x, y): self.x = x ...
3
2016-06-14T22:10:28Z
[ "python", "static" ]
Sending email with optional attachment in django
37,822,586
<p>I am working on a form to send email where have optional attachment.</p> <p>When I try to send the email without attach a file. I got this error</p> <p><strong>Key 'file' not found in MultiValueDict: {}</strong></p> <p>Any idea what I am doing wrong? I would like to send it directly to the email address without u...
0
2016-06-14T21:40:31Z
37,825,282
<p>If you don't send a file, request.FILE will be a blank dictionary-like object. <a href="https://docs.djangoproject.com/ja/1.9/ref/request-response/#django.http.HttpRequest.FILES" rel="nofollow">Documentation</a></p> <p>Based on this, you need to check if key is present at this dict. examples:</p> <pre><code> if 'f...
0
2016-06-15T02:47:29Z
[ "python", "django", "django-forms" ]
Python: Creating a plot inside of a for loop with two different variables
37,822,616
<p>I am trying to plot a function with two parameters. In this case I'd like the function to plot with respect to "yy" in order for it to be in polar coordinates. When I run the program I get 10 figures rather than 1 single plot. Is there a reason this happens? Also, I'm not getting a plot at all. </p> <pre><code>impo...
-1
2016-06-14T21:42:50Z
37,822,681
<p>You need a little restructure:</p> <pre><code>import scipy.optimize as opt import matplotlib.pyplot as plt import pylab as pyl import numpy as np freq = 9.75e9 lmda = 299792458./freq k = 2*np.pi/lmda h1 = 0.25*lmda def theta(x,y): th = np.arctan(y,x) return th def F(x,y): f=2*np.abs(np.sin(k*h1*...
0
2016-06-14T21:49:33Z
[ "python", "loops", "variables", "for-loop", "plot" ]
Avoid global variable in a python util file
37,822,675
<p>I have a <em><code>utilities.py</code></em> file for my python project. It contains only util functions, for example <code>is_float(string)</code>, <code>is_empty(file)</code>, etc. </p> <p>Now I want to have a function <code>is_valid(number)</code>, which has to:</p> <ol> <li>read from a file, <em><code>valid.tx...
4
2016-06-14T21:49:10Z
37,822,915
<p>The following is a simple example of a <em>closure</em>. The dictionary, <code>cache</code>, is encapsulated within the outer function (<code>load_func</code>), but remains in scope of the inner, even when it is returned. Notice that <code>load_func</code> returns the inner function as an object, it does not call ...
4
2016-06-14T22:06:56Z
[ "python" ]
Avoid global variable in a python util file
37,822,675
<p>I have a <em><code>utilities.py</code></em> file for my python project. It contains only util functions, for example <code>is_float(string)</code>, <code>is_empty(file)</code>, etc. </p> <p>Now I want to have a function <code>is_valid(number)</code>, which has to:</p> <ol> <li>read from a file, <em><code>valid.tx...
4
2016-06-14T21:49:10Z
37,823,003
<p>The variable <code>valid_dict</code> would not be global but local to <code>utilities.py</code>. It would only become global if you did something like <code>from utilities import *</code>. Now that <em>is</em> considered bad practice when you're developing a package.</p> <p>However, I have used a trick in cases li...
3
2016-06-14T22:14:24Z
[ "python" ]
Given a MxN grid in the x,y plane, compute f(x,y) and store it into matrix (python)
37,822,722
<p>I'm looking for something similar to ARRAYFUN in MATLAB, but for Python. What I need to do is to compute a matrix whose components are exp(j*dot([kx,ky], [x,y])), where [kx,ky] is a fixed known vector, and [x,y] is an element from a meshgrid.</p> <p>What I was trying to do is to define </p> <pre><code>RX, RY = np....
1
2016-06-14T21:52:53Z
37,822,862
<p>You could do what we used to do in MATLAB before they added <code>ARRAYFUN</code> - change the calculation so it works with arrays. That could be tricky in the days when everything in MATLAB was 2d; allowing more dimensions made it easier. <code>numpy</code> allows more than 2 dimensions.</p> <p>Anyways, here a q...
4
2016-06-14T22:03:29Z
[ "python", "numpy", "matrix" ]
Python Regex checking for repeated combination
37,822,745
<p>I am working with a file that has asterisks (*) and pipes (|).</p> <p>I would like a regex to match a combination where there are at least 4 pipes with any number of asterisks between them. Any number of pipes need to be matched as long as there are at least 4.</p> <p>I need to be able to remove these from the fil...
-3
2016-06-14T21:54:15Z
37,825,915
<h1>Description</h1> <pre class="lang-regex prettyprint-override"><code>(?:[*]*[|]){4,} </code></pre> <p><img src="https://www.debuggex.com/i/ijFE9gq1xuJsdY-X.png" alt="Regular expression visualization"></p> <p>This regular expression will do the following:</p> <ul> <li>Find substrings that are made up <code>*</cod...
0
2016-06-15T04:04:23Z
[ "python", "regex" ]
Searching and replacing specific string using Python
37,822,791
<p>I'm trying to write a python script that will search and replace specific string in text file</p> <p>As an example foo.txt is like that:</p> <pre><code>[section1] option1=xyz option2=abc [section2] option1=aaa option2=bbb </code></pre> <p>My objective is to replace only option1 and option2 values under section2 ...
0
2016-06-14T21:57:40Z
37,822,867
<p>You may find it easier to use <a href="https://docs.python.org/2/library/configparser.html" rel="nofollow">ConfigParser</a> instead of searching and replacing:</p> <pre><code>#!/usr/bin/python import ConfigParser ...
1
2016-06-14T22:03:49Z
[ "python", "scripting" ]
Python/Django on IIS with Windows Authentication - "The connection sessions doesn't exist"
37,822,800
<p>I am running a Python/Django API on Windows IIS and have windows authentication active. The actual authentication part is working fine. However whenever I try and visit any web page or endpoint on the server, I get this error:</p> <pre><code>Environment: Request Method: GET Request URL: ** My URL ** Django Versi...
0
2016-06-14T21:58:17Z
37,823,507
<p>This was actually an issue with using routing over multiple databases. In my development server no authentication is taking place - so the database is not interacted with. </p> <p>What I found was that Django was trying to communicate with the 'auth' and 'sessions' database alias'. I was not handling these names pr...
0
2016-06-14T23:03:29Z
[ "python", "django", "iis" ]
Determining time since process's last output - with subprocess.Popen
37,822,838
<p>I am writing a watchdog, of sorts, for processes in a test suite. I need to determine if a test hangs.</p> <p>I could simply start the process with <code>subprocess.Popen(...)</code>, and use <code>Popen.wait(timeout=to)</code> or <code>Popen.poll()</code> and keep my own timer. However, the tests differ greatly in...
0
2016-06-14T22:01:29Z
37,823,168
<p>This is kind of covered <a href="http://stackoverflow.com/questions/337863/python-popen-and-select-waiting-for-a-process-to-terminate-or-a-timeout">here</a>..</p> <p>Essentially you need to use <code>select()</code> to poll the fd's to see if they have input:</p> <pre><code>#!/usr/bin/python import fcntl import o...
2
2016-06-14T22:28:39Z
[ "python", "linux", "subprocess" ]
Determining time since process's last output - with subprocess.Popen
37,822,838
<p>I am writing a watchdog, of sorts, for processes in a test suite. I need to determine if a test hangs.</p> <p>I could simply start the process with <code>subprocess.Popen(...)</code>, and use <code>Popen.wait(timeout=to)</code> or <code>Popen.poll()</code> and keep my own timer. However, the tests differ greatly in...
0
2016-06-14T22:01:29Z
37,849,017
<p>Here's how to implement "timeout since the subprocess' last output" on Unix in Python 3:</p> <pre><code>#!/usr/bin/env python3 import os import selectors import sys from subprocess import Popen, PIPE, _PopenSelector as Selector timeout = 1 # seconds with Popen([sys.executable, '-c', '''import time for i in range...
0
2016-06-16T02:41:45Z
[ "python", "linux", "subprocess" ]
how to make substring in Python but for my example?
37,822,848
<p>I have a string like this:</p> <pre><code>&lt;node&gt; user = "bob" password ="123" &lt;/node&gt; &lt;node&gt; user = "john" password ="123" &lt;/node&gt; &lt;node&gt; user = "will" password ="1234" &lt;/node&gt; &lt;node&gt; user = "andrew" password ="12345" &lt;/node&gt; &lt;node&gt; user = "mike" password ="1234...
-1
2016-06-14T22:02:21Z
37,822,888
<p>This can be done with a simple regular expression:</p> <pre><code>&gt;&gt;&gt; s = '&lt;node&gt; user = "bob" password ="123" &lt;/node&gt; &lt;node&gt; user = "john" password ="123" &lt;/node&gt; &lt;node&gt; user = "will" password ="1234" &lt;/node&gt; &lt;node&gt; user = "andrew" password ="12345" &lt;/node&gt; ...
1
2016-06-14T22:05:04Z
[ "python", "eclipse" ]
how to make substring in Python but for my example?
37,822,848
<p>I have a string like this:</p> <pre><code>&lt;node&gt; user = "bob" password ="123" &lt;/node&gt; &lt;node&gt; user = "john" password ="123" &lt;/node&gt; &lt;node&gt; user = "will" password ="1234" &lt;/node&gt; &lt;node&gt; user = "andrew" password ="12345" &lt;/node&gt; &lt;node&gt; user = "mike" password ="1234...
-1
2016-06-14T22:02:21Z
37,823,092
<p>This is a great way to learn about Python strings and lists. Given that you initially have a string, strings have a split method that allows you to break a string based on the value passed to split</p> <pre><code>my_list = string.split('=') </code></pre> <p>So this splits your string on the = sign the sections sp...
0
2016-06-14T22:21:23Z
[ "python", "eclipse" ]
Convert a for loop to a list comprehension
37,822,872
<p>I have a <code>for</code> loop that compares a substring of each element in a list of strings to the elements in another list of strings.</p> <pre><code>mylist = [] for x in list1: mat = False for y in list2: if x[:-14] in y: mat = True if not mat: mylist.append(x) </code></p...
-4
2016-06-14T22:03:58Z
37,823,166
<p>Are you looking for something like this?:</p> <pre><code>mylist = [x for x in list1 if x[:-14] not in list2] </code></pre>
-1
2016-06-14T22:28:21Z
[ "python", "list", "list-comprehension" ]
Convert a for loop to a list comprehension
37,822,872
<p>I have a <code>for</code> loop that compares a substring of each element in a list of strings to the elements in another list of strings.</p> <pre><code>mylist = [] for x in list1: mat = False for y in list2: if x[:-14] in y: mat = True if not mat: mylist.append(x) </code></p...
-4
2016-06-14T22:03:58Z
37,823,480
<p>As it is written, no you cannot directly write it as list comprehension.</p> <p>however if you rewrite the computation of <code>mat</code> to be a single expression. (in this case you would use <code>any</code>)</p> <pre><code>mylist = [] for x in list1: mat = any((x[:-14] in y) for y in list2) if not mat:...
1
2016-06-14T23:01:17Z
[ "python", "list", "list-comprehension" ]
Unicode error PyPdf
37,822,887
<p>I try to download several pdfs using the <code>requests</code> library and merge them together using pypdf. In general, this is working fine but for some pdfs I just get an error.</p> <p>MWE.py</p> <pre><code>import requests from pyPdf import PdfFileWriter, PdfFileReader from StringIO import StringIO input = Pdf...
0
2016-06-14T22:05:03Z
37,823,261
<p>Ok, I found out that this seems to be a bug inside pyPdf (1.13) <a href="https://github.com/mstamy2/PyPDF2/issues/51" rel="nofollow">https://github.com/mstamy2/PyPDF2/issues/51</a></p> <p>Using PyPDF2 (1.26.0) instead works as expected so far.</p>
0
2016-06-14T22:38:07Z
[ "python", "python-requests", "pypdf" ]
Iterate over specifified sheets in a workbook with python
37,822,905
<p>I would like to iterate over sheets 3 to 9. So a total of 7 sheets will be looped over. How to I specify they sheets to loop over? </p> <pre><code>import openpyxl wb = openpyxl.load_workbook('DemoFile.xlsx') for sheets 3 to 9 in wb.worksheets: print(Sheets) </code></pre>
1
2016-06-14T22:06:13Z
37,823,022
<p>Just use <code>range</code> to specify which sheets to iterate based on the index of the sheet. <code>openpyxl</code> uses 0-based indexes, so sheet 3 has an index of 2.</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('DemoFile.xlsx') for n in range(2,9): print(wb.worksheets[n]) </code></pre> <p>O...
1
2016-06-14T22:16:07Z
[ "python", "openpyxl" ]
Create filter queries by hand using elasticsearch_dsl
37,822,916
<p>I am trying to build arbitrary nested queries stored in a some data structures (possibly a tree). <a href="http://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#filters" rel="nofollow">From the manual</a> I gather that <code>filter</code> type of queries are special types of <code>Bool</code> queries, s...
0
2016-06-14T22:07:13Z
37,825,695
<p>If you're using ES 1.x, then you cannot use the second way, i.e. the one that yields a <code>bool/filter</code> query.</p> <p>If you get that query, that means you're using elasticsearch-dsl 2.x or later, <a href="http://elasticsearch-dsl.readthedocs.io/en/latest/index.html#compatibility" rel="nofollow">which is no...
0
2016-06-15T03:39:30Z
[ "python", "elasticsearch", "elasticsearch-dsl" ]
How to smooth by interpolation when using pcolormesh?
37,822,925
<p>I have a basemap of the world, and it's filled with data (lintrends_mean) using pcolormesh. Because the data has relatively large grid boxes, I'd like to smooth the plot. However, I can't figure out how to do this. Setting shading='gouraud' in the plotting function blurs the edges of the grid boxes, but I'd like som...
1
2016-06-14T22:07:42Z
37,823,297
<p>You have some variants:</p> <ol> <li>Use special shading for <code>pcolormesh</code>.</li> <li>Use <code>imshow</code> which allows to interpolated data.</li> <li>Interpolate data with <code>scipy.interpolate</code> and plot with <code>pcolormesh</code>.</li> </ol> <p>Look at the example:</p> <pre><code>import ma...
0
2016-06-14T22:42:18Z
[ "python", "matplotlib", "interpolation" ]
How to implement hlda transformation to find correlation of topics in gensim?
37,823,014
<p>I am trying to categorize the blog content using Topic Modeling. Using LDA transformation, I couldn't find the correlation b/w topics. Say, cricket is a sub topic of Sports topic. However, I come to know that it could be achieved using HLDA. Could some one help me how to implement the HLDA transformation in python g...
1
2016-06-14T22:15:14Z
38,597,616
<p>I could not find a python implementation of hLDA, and gensim currently does not have hLDA as one of its models. You might want to look at C <a href="https://github.com/blei-lab/hlda" rel="nofollow">implementation</a> from Blei Lab and Java <a href="http://mallet.cs.umass.edu/api/cc/mallet/topics/HierarchicalLDA.html...
0
2016-07-26T18:43:49Z
[ "python", "gensim", "topic-modeling" ]
Search for a string in a line and replace the entire line with another string
37,823,041
<p>I have a file called <code>testing</code> present in <code>/home/hiperbolt</code> that has a line which says:</p> <pre><code>nameserver 127.89.87.3 </code></pre> <p>I want a piece of code to look for a line that starts with <code>nameserver</code> and replace the entire line with </p> <pre><code>nameserver 8.8.8....
1
2016-06-14T22:18:38Z
37,823,111
<p>You can just use <code>re.sub()</code> on the text content of the file, and then write the replaced text back to the file.</p> <pre><code>In [30]: filedata Out[30]: 'nameserver 127.89.87.3\nsearch example.com\n' In [31]: re.sub(r'nameserver\s+.*', 'nameserver 8.8.8.8', filedata) Out[31]: 'nameserver 8.8.8.8\nsearc...
2
2016-06-14T22:23:39Z
[ "python" ]
Search for a string in a line and replace the entire line with another string
37,823,041
<p>I have a file called <code>testing</code> present in <code>/home/hiperbolt</code> that has a line which says:</p> <pre><code>nameserver 127.89.87.3 </code></pre> <p>I want a piece of code to look for a line that starts with <code>nameserver</code> and replace the entire line with </p> <pre><code>nameserver 8.8.8....
1
2016-06-14T22:18:38Z
37,823,113
<p>You could do this without regex if you wanted. </p> <pre><code>with open('/home/hiperbolt', 'r') as f: lines = [] for line in f: if line.startswith('nameserver'): lines.append('nameserver 8.8.8.8') else: lines.append(line) with open('/home/hiperbolt', 'w') as f: ...
3
2016-06-14T22:23:56Z
[ "python" ]
kivy python clock schedule update
37,823,060
<p>'main_loop' function while loop does not increment self.i value every 5 seconds and 'run' function does not decrement self.mycounter value every 1 second. </p> <p>Why?</p> <p>What am I doing wrong?</p> <p>I do not want to use time.sleep.</p> <pre><code>class MyThread(BoxLayout): stop = [] timer = [] ...
0
2016-06-14T22:19:48Z
37,823,554
<p>I suggest you to throw away whole <code>while</code> styling if it's not necessary - <em>especially</em> that one in <code>main_loop</code>, which is just checking values. It's not good in kivy if you really don't need that functionality e.g.:</p> <pre><code>while &lt;some list&gt;: value = &lt;some list&gt;.po...
1
2016-06-14T23:07:33Z
[ "python", "kivy", "clock" ]
input_shape issue in Neural networks with Keras in Python
37,823,109
<p>I am trying to replicate exactly <a href="http://nbviewer.jupyter.org/github/julienr/ipynb_playground/blob/master/keras/convmnist/keras_cnn_mnist.ipynb" rel="nofollow">this tutorial</a> on neural networks using the MNIST data set. When I just copy-paste it into my Python editor, I get the following exception:</p> <...
1
2016-06-14T22:23:25Z
37,823,605
<p>It says so right there</p> <blockquote> <p>Exception: The first layer in a Sequential model must get an <code>input_shape</code> or <code>batch_input_shape</code> argument.</p> </blockquote> <p>I will now try to break this error message up for you. Next time you try it yourself.</p> <blockquote> <p>The first ...
0
2016-06-14T23:12:52Z
[ "python", "conv-neural-network", "keras" ]
input_shape issue in Neural networks with Keras in Python
37,823,109
<p>I am trying to replicate exactly <a href="http://nbviewer.jupyter.org/github/julienr/ipynb_playground/blob/master/keras/convmnist/keras_cnn_mnist.ipynb" rel="nofollow">this tutorial</a> on neural networks using the MNIST data set. When I just copy-paste it into my Python editor, I get the following exception:</p> <...
1
2016-06-14T22:23:25Z
38,638,540
<p>Typo</p> <pre><code>model.add(Convolution2D(32, 1, 3, 3, border_mode='same', input_sheme=(1,28,28))) ^ </code></pre> <p>should be</p> <pre><code>model.add(Convolution2D(32, 1, 3, 3, border_mode='same', input_shape=(1,28,28))) </code></pre>
1
2016-07-28T13:53:48Z
[ "python", "conv-neural-network", "keras" ]
Python Using Fileinput to Replace Words
37,823,126
<p>I am using Python 2.7 with MAC OS X and wrote a program to replace a word in a file with another word. Any time that word shows up in that file I want it replaced with another word that the user specifies. It seems to be working but it seems to be outputting a couple extra lines on the bottom that are copied from th...
0
2016-06-14T22:24:49Z
37,823,469
<p>Ok, after thinking about this for a long time, here is my answer:</p> <p><strike>change the open type from "r+" to "w" (or maybe "w+", haven't tried)</strike></p> <p><strong>Edit 2:</strong> These don't seem to work. Try something like copying the contents of the file before re-writing it, then rewrite the file fr...
0
2016-06-14T23:00:09Z
[ "python", "linux", "osx", "fileinputstream" ]
Python Using Fileinput to Replace Words
37,823,126
<p>I am using Python 2.7 with MAC OS X and wrote a program to replace a word in a file with another word. Any time that word shows up in that file I want it replaced with another word that the user specifies. It seems to be working but it seems to be outputting a couple extra lines on the bottom that are copied from th...
0
2016-06-14T22:24:49Z
37,838,852
<p>Use the <code>fileinput.input(filePath, inplace=True)</code> method instead of the <code>open(..) method</code></p> <p>Here's the script:</p> <pre><code>import fileinput textToSearch = "hostname" print ("Please type in the TSM Hostname:") textToReplace = raw_input( "Hostname/Nodename: " ) print ("***Updating dsm...
0
2016-06-15T14:51:42Z
[ "python", "linux", "osx", "fileinputstream" ]
How to handle a post request in Flask that contains a list
37,823,149
<p>What i want is to handle an order placed to a server from an android app.</p> <p>To test things i am using POSTMAN.</p> <p>I tested it </p> <p>with the following code.</p> <pre><code>class newOrder(Resource): ''' this class receives credentials from a post request and returns the full menu of the est...
0
2016-06-14T22:26:50Z
37,823,319
<p>You need to come up with a format in which to send the list. I believe the most common format is just a comma seperated string like so</p> <pre><code>thing1,thing2,thing3,etc </code></pre> <p>Pass this in the url like</p> <pre><code>https://127.0.0.1:3000/postendpoint?arrayParameter=thing1,thing2,thing3,etc </cod...
0
2016-06-14T22:44:24Z
[ "python", "post", "flask", "request", "flask-restful" ]
Put 2 separate .csv files on one graph using Python
37,823,156
<p>I have created a multi-line graph, of water temperatures throughout the year, with python using pandas:</p> <pre><code>import pandas as pd filepath = "C:\\Users\\technician\\Desktop\\LowerBD2014.csv" data = pd.read_csv(filepath, header = 0, index_col = 0) data.plot(kind = 'line', use_index = True, title="timeser...
0
2016-06-14T22:27:12Z
37,823,877
<p>As someone <a href="http://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe">here</a> said, if your columns are the same for both csv files, you can follow <a href="http://stackoverflow.com/a/21232849/4907651">their</a> code.</p> <p><strong>or</strong></p...
0
2016-06-14T23:38:51Z
[ "python", "csv", "pandas" ]
Put 2 separate .csv files on one graph using Python
37,823,156
<p>I have created a multi-line graph, of water temperatures throughout the year, with python using pandas:</p> <pre><code>import pandas as pd filepath = "C:\\Users\\technician\\Desktop\\LowerBD2014.csv" data = pd.read_csv(filepath, header = 0, index_col = 0) data.plot(kind = 'line', use_index = True, title="timeser...
0
2016-06-14T22:27:12Z
37,840,078
<p>Once your two csv's are imported as two dataframes, just plot the first assigned to a named matplotlib axes object (ax in the block below) then pass that axes to the second plot call.</p> <pre><code>import pandas as pd import numpy as np # two made-up timeseries with different periods, for demonstration plot below...
0
2016-06-15T15:45:22Z
[ "python", "csv", "pandas" ]
Interpreter thinks 2 declarations of the same class are different
37,823,198
<p>Basically I have a project set up like so:</p> <pre><code>&lt;container-folder&gt; |- &lt;folder_1&gt; |- &lt;extra_folder&gt; | |- source.py | |- main.py </code></pre> <p>And in <code>main.py</code> I declare a class like so:</p> <pre><co...
1
2016-06-14T22:30:52Z
37,823,759
<p>They are not the same class. This is due to a quirk in that when you run a python module (ie. <code>python main.py</code>) it gets run as <code>__main__</code>. Thus you have <code>__main__.SomeClass</code> (from the root module of the program) and <code>main.SomeClass</code> (from the module imported by <code>sour...
0
2016-06-14T23:26:36Z
[ "python", "python-2.7", "class" ]
Writing a python c extension that modifies argument
37,823,232
<p>I want to write a c extension with a function that modifies its argument. Is that possible?</p> <p>helloworld.c</p> <pre><code>#include &lt;Python.h&gt; // adapted from http://www.tutorialspoint.com/python/python_further_extensions.htm /***************\ * Argument Test * \***************/ // Documentation string...
1
2016-06-14T22:35:11Z
37,823,272
<blockquote> <p>I want to write a c extension with a function that modifies its argument. Is that possible?</p> </blockquote> <p>Only to the extent that it's possible with an ordinary function. You can mutate the objects passed to you, if they're mutable, but you can't reassign any variables used to pass you those o...
2
2016-06-14T22:39:26Z
[ "python", "c", "python-c-extension" ]
Confluent Python API for Kafka
37,823,244
<p>I'm getting an error with basic usage of the official Confluent Kafka Python API:</p> <p>I subscribe:</p> <pre><code>kafka_consumer.subscribe(topics=["my-avro-topic"], on_assign=on_assign_callback, on_revoke=on_revoke_callback) </code></pre> <p>Using callback:</p> <pre><code>def on_assign_callback(consumer, topi...
0
2016-06-14T22:36:43Z
37,831,179
<p>This is a bug in the underlying C library librdkafka. See the upstream issue here: <a href="https://github.com/edenhill/librdkafka/issues/692" rel="nofollow">https://github.com/edenhill/librdkafka/issues/692</a></p> <p>If you want to start consuming from the stored offsets you dont actually need to call position() ...
3
2016-06-15T09:17:39Z
[ "python", "apache-kafka", "kafka-consumer-api", "confluent" ]
How to share a variable (not for modification) in python using multithread?
37,823,289
<p>I'm trying to parallelize a function I wrote for sequential program. Below is the input and output</p> <p>Input 1, list of string : <code>["foo bar los angles", "foo bar new york", ...]</code></p> <p>Input 2, list of string as dictionary: <code>["los angles", "new york"..]</code></p> <p>I want to remove all strin...
2
2016-06-14T22:41:11Z
37,823,606
<p>It's generally recommended to avoid multithreading when wanting performance because of the <a href="http://stackoverflow.com/questions/1294382/what-is-a-global-interpreter-lock-gil">GIL</a>. Luckily we have <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a>!</p> <pr...
2
2016-06-14T23:12:56Z
[ "python", "multithreading" ]
python selenium proxys in chrome/phantomjs
37,823,305
<p>I've tried to use proxy s in chrome but, I get this error.</p> <pre><code> driver = webdriver.Chrome(proxy=proxy) TypeError: __init__() got an unexpected keyword argument 'proxy' </code></pre> <p>This is the code I am trying to use but it only works with FireFox, so I was wondering if it is possible to do this...
0
2016-06-14T22:43:01Z
37,823,378
<p>Try doing it like this</p> <pre><code>from selenium import webdriver PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=http://%s' % PROXY) chrome = webdriver.Chrome(chrome_options=chrome_options) chrome.get("http://whatismyipa...
0
2016-06-14T22:50:20Z
[ "python", "python-2.7", "google-chrome", "python-3.x", "selenium" ]
python selenium proxys in chrome/phantomjs
37,823,305
<p>I've tried to use proxy s in chrome but, I get this error.</p> <pre><code> driver = webdriver.Chrome(proxy=proxy) TypeError: __init__() got an unexpected keyword argument 'proxy' </code></pre> <p>This is the code I am trying to use but it only works with FireFox, so I was wondering if it is possible to do this...
0
2016-06-14T22:43:01Z
37,823,811
<pre><code>from selenium import webdriver PROXY = "31.28.244.230:41905" webdriver.DesiredCapabilities.CHROME['proxy']={ "httpProxy":PROXY, "ftpProxy":PROXY, "sslProxy":PROXY, "noProxy":None, "proxyType":"MANUAL", "autodetect":False } driver = webdriver.Chrome() driver.get('http://www.whatsmyip.org/') </code></pr...
0
2016-06-14T23:32:22Z
[ "python", "python-2.7", "google-chrome", "python-3.x", "selenium" ]
Python Socket Connection Always Times Out
37,823,342
<p>When trying to create a very simple python program to create a socket and then download data the socket always times out regardless of the website. I turned off my computers firewall but after that have no clue. Thoughts?</p> <p><a href="http://i.stack.imgur.com/v3v8d.jpg" rel="nofollow"><img src="http://i.stack....
1
2016-06-14T22:46:26Z
37,824,828
<p>Okay nevermind. Turns out the network I was on was locked down in a funky way. Browsing to the page using Chrome worked fine. And using a socket request on my home network is smooth. So chalk that one up to a network configuration issue.</p>
0
2016-06-15T01:51:35Z
[ "python", "network-programming" ]
Python API design for existing Java API
37,823,533
<p>I am new to python and I have to design a Python API(version - 2.7) similar to an existing Java API</p> <p><strong>Python version - 2.7</strong></p> <p>The Java API is as follows</p> <pre><code>public interface Process&lt;T&gt; { Future&lt;T&gt; create(Client&lt;T&gt; client) //Other methods } public inter...
1
2016-06-14T23:05:17Z
37,843,895
<p>In general I would use closure to create function templates , like the case where i want to generate many functions of the same template with different variables </p> <p>example</p> <pre><code>def add(x): def addto(y): return x+y return addto addto5 = add(5) print addto5(1) #will print 6 </code></...
1
2016-06-15T19:11:08Z
[ "java", "python", "python-2.7", "closures" ]
Pandas: Import feature vectors from list of dictionaries into dataframe
37,823,571
<p>I have a list of dictionaries, and each dictionary consists of two key-value tuples. The first key-value is the name of a person and the second one is a feature vector consisting of the grades each person achieved in different courses. For example:</p> <pre><code>ListOfGrades=[{'Name':"Mike", 'grades':[98,86,90,72]...
0
2016-06-14T23:09:01Z
37,823,683
<p>This reason you are getting an error is that <code>i</code> is already an item (in this case a dictionary) from the list and is not an index. To have this work better you could change your loop as follows</p> <pre><code>for i in range(len(ListOfGrades)): </code></pre> <p>This will have the effect of making <code>i...
1
2016-06-14T23:19:27Z
[ "python", "dictionary", "pandas" ]
Pandas: Import feature vectors from list of dictionaries into dataframe
37,823,571
<p>I have a list of dictionaries, and each dictionary consists of two key-value tuples. The first key-value is the name of a person and the second one is a feature vector consisting of the grades each person achieved in different courses. For example:</p> <pre><code>ListOfGrades=[{'Name':"Mike", 'grades':[98,86,90,72]...
0
2016-06-14T23:09:01Z
37,823,968
<p>Ok, this approach is a bit of a hack, and it will quickly run into problems if each student doesn't have the same number of grades, but essentially, you need to build a new list and create the dictionary from that list. For python 3.5:</p> <pre><code>new_list = [] for student in ListOfGrades: new_list.append({'...
1
2016-06-14T23:50:28Z
[ "python", "dictionary", "pandas" ]
Pandas: Import feature vectors from list of dictionaries into dataframe
37,823,571
<p>I have a list of dictionaries, and each dictionary consists of two key-value tuples. The first key-value is the name of a person and the second one is a feature vector consisting of the grades each person achieved in different courses. For example:</p> <pre><code>ListOfGrades=[{'Name':"Mike", 'grades':[98,86,90,72]...
0
2016-06-14T23:09:01Z
37,824,842
<p>Try this.. </p> <pre><code>df = pd.DataFrame.from_records(ListOfGrades, index='Name')['grades'].apply(pd.Series) df # 0 1 2 3 # Name # Mike 98 86 90 72 # Sasha 92 79 85 94 # Beth 89 89 76 90 </code></pre> <p>Adding data to list:</p> <pre><code>ListOfGrades=[{'Name':"...
3
2016-06-15T01:53:27Z
[ "python", "dictionary", "pandas" ]
Strange Code Indenting Issue
37,823,623
<p>I'm probably missing something obvious, but I've been trying to solve this problem for about an hour, without any success. Probably going to feel really stupid when the solution is found. Here's the error I'm getting:</p> <pre><code> File "xpc_connection.py", line 77 def remoteObjectProxy(): ^ IndentationE...
1
2016-06-14T23:14:16Z
37,823,667
<p>You're using multi-line strings to substitute for multi-line comments. They are not comments, however, and when they're dedented all the way out like that, then it terminates the class scope and you can't get back into it.</p> <p>Quick fix, indent the opening <code>'''</code> to match the class scope.</p>
5
2016-06-14T23:18:26Z
[ "python" ]
Running dict.clear but the dictionary still prints with items
37,823,688
<p>I'm trying to run option 11, to clear my dictionary, but when I run the clear option (11), and then the view all items option (4), it prints the same dictionary as above without clearing it.</p> <p>Any ideas on how I can get this to work as I am stuck?</p> <pre><code>basketball_scores = {'Luke' : 18, 'Nick' : 7, '...
0
2016-06-14T23:19:58Z
37,823,722
<p><code>range(1, 11)</code> doesn't include 11, so you're just skipping that input. I recommend using a chained comparison:</p> <pre><code>1 &lt;= option &lt;= 11 </code></pre> <p>rather than <code>in range(...)</code>. It makes the behavior on the bounds more explicit (and allows you to specify the behavior), it wo...
1
2016-06-14T23:23:14Z
[ "python", "python-3.x", "dictionary" ]
How can I use nuitka with virtualenv
37,823,697
<p>I am using nuitka for my project. It have dependencies some 3th part modules and I am using virtualenv.</p> <p>How can I use nuitka with virtualenv?</p> <p><em>ps: sory my english</em></p>
2
2016-06-14T23:20:47Z
38,776,469
<p>While compilation worked perfect, I had import error at execution time on all packages that were installed in virtualenv folder, even is virtualenv was activated by <code>workon</code>.</p> <p>Extending <code>PYTHONPATH</code> before running the resulted <code>.exe</code> has solved the issue though:</p> <pre><cod...
0
2016-08-04T20:03:05Z
[ "python", "python-3.x", "nuitka" ]
Django foreign key new model instance used as default
37,823,717
<p>I'm wondering whether it's possible to do something like the following</p> <pre><code>class ModelA(models.Model): my_field = models.ForeignKey('UniqueKey', to_field='key' default=UniqueKey.create(key=KeyGen())) # KeyGen() returns a new random key </code></pre> <p>In essence, I have a number of models that ...
0
2016-06-14T23:22:33Z
37,826,035
<p>I think your best approach will be to use the post_save signal when an instance of your model is created. <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#post-save" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/signals/#post-save</a></p> <p>i.e. </p> <pre><code>class ModelA(models.Model): ...
0
2016-06-15T04:15:23Z
[ "python", "django" ]
Directly calling associated script with arguments
37,823,822
<p>In Windows console if I execute this script (<code>test.py</code>):</p> <pre><code>import sys print(sys.argv) </code></pre> <p>like:</p> <pre><code>&gt;python test.py my args </code></pre> <p>I get expected output:</p> <pre><code>['test.py', 'my', 'args'] </code></pre> <p>but if I call it directly, like this:<...
1
2016-06-14T23:33:25Z
37,825,221
<p>Similar to the discussion <a href="http://stackoverflow.com/questions/2640971/windows-is-not-passing-command-line-arguments-to-python-programs-executed-from-t">here</a>, you want to make sure the <code>command</code> key is set properly. On my copies of Windows 10, I found I had the <code>command</code> reg set to <...
0
2016-06-15T02:41:01Z
[ "python", "windows" ]
Python - Why is my Tkinter window not closing on self.destroy?
37,823,884
<p>I am currently creating a little program which inserts Tkinter Entry boxes into Google Calendar (after all different kind of checks ofcourse). That part is not the problem. Since I am running a terminal at the same time that I don't want to 'hold' during the Tkinter window is open.</p> <p>When I close the window us...
1
2016-06-14T23:40:23Z
37,832,942
<p>instead of <code>self.destroy()</code> do this <code>self.parent.destroy()</code>.</p> <p>As far as my understanding we are passing <code>tk</code> object to the class <code>window</code> and it used as <code>parent</code> in the class.So instead of using <code>root</code> to create widgets we are using <code>paren...
0
2016-06-15T10:33:45Z
[ "python", "multithreading", "tkinter" ]
json.dump throwing “TypeError: {…} is not JSON serializable” on wtf form validation errors
37,823,934
<p>I would like to handle wtf form via Ajax post request in flask. </p> <pre><code>form = LoginForm(request.form) if form.validate(): ..... .... do something ..... form.errors['iserror'] = True return json.dumps(form.errors) </code></pre> <p>But I get this error</p> <p>File "/usr/lib/python3.4/json/enc...
0
2016-06-14T23:46:22Z
37,824,257
<p>Problem was my validation message. Not sure why I had _ before the message and that was causing the issue.</p> <pre><code>password = PasswordField(_("Password"), validators=[ DataRequired(message=_("A Password is required."))]) </code></pre> <p>Works fine having after changing the form validation to <br>...
0
2016-06-15T00:30:14Z
[ "python", "json", "flask" ]
Looking for specific arguments in text
37,823,962
<p>I'm looping through a number of .PHP files, treating them as plain text, and I'm attempting to locate text arguments of certain functions.</p> <p>The functions in the PHP files are all called by using <code>\L10n::</code> and then take string arguments.</p> <p>Examples of the text that I'm trying to find are below...
0
2016-06-14T23:49:38Z
37,824,852
<p>Let me try my hand at this one:</p> <pre><code>import re input = """bar\L10n::__('Double _')baz bar\L10n::esc_attr__('Escape Attributes __')baz bar\L10n::_n( 'Text 1', 'Text 2', $variable )""" input = input.replace('\n', '') reg = re.compile('\'(.*?)\'') foo = reg.findall(input) </code></pre> <p>gives ...
0
2016-06-15T01:54:47Z
[ "python", "regex", "python-3.x" ]
IDLE won't open
37,823,965
<p>I am very new to programming and I am trying to use Python on my computer. I downloaded and installed the program, but when I try to open IDLE, the Windows blue loading circle pops up and then disappears and nothing else happens. I'm using Windows 10 and Python version 3.4.3. I've tried downloading it from different...
0
2016-06-14T23:50:01Z
37,823,985
<p>While this won't help you get IDLE open, I would strongly suggest looking into using another IDE, such as Pycharm's free edition.</p>
0
2016-06-14T23:51:52Z
[ "python", "windows-10", "python-idle" ]
Condensing a list of lists in python by duplicates in a certain column
37,823,991
<p>So, I have a list of lists in python like so:</p> <pre><code>[[a, foo, bar], [a, dog, cat], [b, foo, bar], [c, foo, bar]] </code></pre> <p>And I want to condense it in to the following:</p> <pre><code>[[a, bar, cat], [b, bar], [c, bar]] </code></pre> <p>Where the last two indexes of the 'a' object are the 3rd co...
0
2016-06-14T23:52:42Z
37,824,065
<p>You can use a dict to group, using the first element as the key and appending the third elements:</p> <pre><code>l = [["a", "foo", "bar"], ["a", "dog", "cat"], ["b", "foo", "bar"], ["c", "foo", "bar"]] from collections import defaultdict d = defaultdict(list) for a, b, c in l: d[a].append(c) print([[k] + v fo...
2
2016-06-15T00:01:21Z
[ "python" ]
Equivalent of pyspark.mllib.tree.DecisionTreeModel.toDebugString() in pyspark.ml.classification.DecisionTreeClassificationModel - IN PYTHON
37,823,992
<p>This is essentially the same question as:</p> <ul> <li><a href="http://stackoverflow.com/questions/37678365/equivalent-of-mllib-decisiontreemodel-todebugstring-in-ml-decisiontreeclassifi">Equivalent of mllib.DecisionTreeModel.toDebugString() in ml.DecisionTreeClassificationModel</a></li> </ul> <p><strong>BUT for p...
3
2016-06-14T23:52:46Z
37,932,340
<p>I found a solution. It is not elegant and it violates encapsulation and everything you ever learned about object oriented programming, but it works:</p> <pre><code>print model._call_java("toDebugString") DecisionTreeClassificationModel (uid=DecisionTreeClassifier_4c3bb548827f07c590e6) of depth 5 with 49 nodes I...
1
2016-06-20T21:48:48Z
[ "python", "apache-spark", "apache-spark-mllib", "apache-spark-ml" ]
Find numpy array values bounding an input value
37,824,040
<p>I have a value, say 2016 and a sorted numpy array: <code>[2005, 2010, 2015, 2020, 2025, 2030]</code>. What is the pythonic way to find the 2 values in the array that bound 2016. In this case, the answer will be an array [2015, 2020].</p> <p>Not sure how to do it other than loop, but hoping for a more numpy based so...
3
2016-06-14T23:58:22Z
37,824,223
<p>You could do something like this:</p> <pre><code>In[1]: import numpy as np In[2]: x = np.array([2005, 2010, 2015, 2020, 2025, 2030]) In[3]: x Out[3]: array([2005, 2010, 2015, 2020, 2025, 2030]) In[4]: x[x &gt; 2016].min() Out[4]: 2020 In[5]: x[x &lt; 2016].max() Out[5]: 2015 In[6]: def bound(value, arr): ...
3
2016-06-15T00:23:38Z
[ "python", "numpy" ]
Find numpy array values bounding an input value
37,824,040
<p>I have a value, say 2016 and a sorted numpy array: <code>[2005, 2010, 2015, 2020, 2025, 2030]</code>. What is the pythonic way to find the 2 values in the array that bound 2016. In this case, the answer will be an array [2015, 2020].</p> <p>Not sure how to do it other than loop, but hoping for a more numpy based so...
3
2016-06-14T23:58:22Z
37,826,723
<p>A straight-forward approach would be with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> -</p> <pre><code>idx = np.searchsorted(A,B,'left') out = A[idx],A[idx+1] </code></pre> <p><strong>Explanation</strong></p> <p>The inputs a...
3
2016-06-15T05:20:43Z
[ "python", "numpy" ]
Fast floating point modpow
37,824,084
<p>I am looking to compute a^b mod m where a &amp; b are <strong>floating point</strong> numbers and m is an non-negative integer. The trivial solution is to do b multiplications which takes O(n) time, however my numbers a &amp; b can be largish (~10 digits before the decimal point) and I would like to do this efficien...
0
2016-06-15T00:03:26Z
37,826,126
<p>I don't think there is an easy way to do this in general, if <code>a</code> and <code>b</code> can be 10 digits (assuming before the decimal point). The problem is that for floats <code>x</code> and <code>y</code>, you don't necessarily have the property</p> <pre><code>((x % m) * (y % m)) % m == (x * y) % m </code>...
1
2016-06-15T04:24:42Z
[ "python", "math", "floating-point", "exponentiation", "mod" ]
How do I check whether or not I'm logged in or not?
37,824,114
<p>I want to test whether or not this request worked or not. is there a way to check the html or do something like geturl() while using session on requests?</p> <pre><code>#!/usr/bin/env python 2.7.11 # import requests headers = {'User-Agent': 'Mozilla/5.0'} cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918...
2
2016-06-15T00:07:33Z
37,824,178
<p>The thing that keeps people logged in on every site when they navigate through pages is something called cookies. <a href="https://en.wikipedia.org/wiki/HTTP_cookie" rel="nofollow">HTTP cookies</a> are data that hold login information. After clicking from one page, you would be logged out without cookies. To make su...
0
2016-06-15T00:17:40Z
[ "python", "python-2.7", "python-requests" ]
How do I check whether or not I'm logged in or not?
37,824,114
<p>I want to test whether or not this request worked or not. is there a way to check the html or do something like geturl() while using session on requests?</p> <pre><code>#!/usr/bin/env python 2.7.11 # import requests headers = {'User-Agent': 'Mozilla/5.0'} cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918...
2
2016-06-15T00:07:33Z
37,824,577
<p>Please take your time to read the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests documentation</a> not only does it provide examples, but you can easily identify a successful request by verifying the status code returned by the server after doing one:</p> <p>For Ex.</p> <pre><code>r ...
-1
2016-06-15T01:12:09Z
[ "python", "python-2.7", "python-requests" ]
Xcode 8 don't Start
37,824,143
<p>I have a big problem with Xcode 8, can not get it to start ^ _ ^, I always get the following error:</p> <blockquote> <p>Loading a plug-in failed.</p> <p>The plug-in or one of its prerequisite plug-ins may be missing or damaged and may need to be reinstalled.</p> </blockquote> <p>I am looking at the logs I...
1
2016-06-15T00:12:11Z
37,832,853
<p>just for the record, Apple says the problem is related to the fact that I updated Python (although I downloaded from the official website python.org) and indicates that 8 of Xcode is more control for the XcodeGhost problem.</p> <p>I have to try to reinsert the 2.7.10 version and see if this works for me.</p> <p><s...
2
2016-06-15T10:29:57Z
[ "python", "ios", "xcode", "xcode8" ]
Xcode 8 don't Start
37,824,143
<p>I have a big problem with Xcode 8, can not get it to start ^ _ ^, I always get the following error:</p> <blockquote> <p>Loading a plug-in failed.</p> <p>The plug-in or one of its prerequisite plug-ins may be missing or damaged and may need to be reinstalled.</p> </blockquote> <p>I am looking at the logs I...
1
2016-06-15T00:12:11Z
39,593,701
<p>I also have the problem, and I copy an official version of Python 2.7 to <code>/System/Library/Frameworks/Python.framework/Versions/2.7/</code>, the problem is gone.</p>
0
2016-09-20T12:08:28Z
[ "python", "ios", "xcode", "xcode8" ]
Xcode 8 don't Start
37,824,143
<p>I have a big problem with Xcode 8, can not get it to start ^ _ ^, I always get the following error:</p> <blockquote> <p>Loading a plug-in failed.</p> <p>The plug-in or one of its prerequisite plug-ins may be missing or damaged and may need to be reinstalled.</p> </blockquote> <p>I am looking at the logs I...
1
2016-06-15T00:12:11Z
39,593,757
<p>Try to delete(copy them on other folder for backup) everything in this folder:</p> <p><code>~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/</code></p>
0
2016-09-20T12:11:26Z
[ "python", "ios", "xcode", "xcode8" ]
how not to throw an error even for 'None' type?
37,824,150
<p>I am trying to create HTML format (for sending automatic emails)from JSON data I get from an internal database, I am getting the following error for 'None' type,I want to capture 'None' type aswell?how to not throw an error even for 'None' type?</p> <p>INPUT:-</p> <pre><code>{'total': 0, 'Resolution': None, 'key':...
0
2016-06-15T00:13:00Z
37,824,177
<p>It might sound like too broad of an answer, but I would suggest to switch to a <em>template engine</em>, like <a href="http://www.makotemplates.org/" rel="nofollow"><code>mako</code></a> or <a href="http://jinja.pocoo.org/docs/dev/" rel="nofollow"><code>jinja2</code></a>, instead of trying to manually construct HTML...
4
2016-06-15T00:17:26Z
[ "python" ]
how not to throw an error even for 'None' type?
37,824,150
<p>I am trying to create HTML format (for sending automatic emails)from JSON data I get from an internal database, I am getting the following error for 'None' type,I want to capture 'None' type aswell?how to not throw an error even for 'None' type?</p> <p>INPUT:-</p> <pre><code>{'total': 0, 'Resolution': None, 'key':...
0
2016-06-15T00:13:00Z
37,824,182
<p>Extract each field from the dict using <code>dict.get(key,default)</code> to avoid missing fields, and then use <code>or</code> to cover the <code>None</code> case</p> <p>For example</p> <pre><code>item['Resolution'].rstrip('\n!') </code></pre> <p>becomes</p> <pre><code>(item.get('Resolution', None) or '').rstri...
2
2016-06-15T00:18:08Z
[ "python" ]
Returning a Selenium Webdriver from a Thread
37,824,151
<p>Trying to deal with the creation of a webdriver timing out (which happens once in a while covered <a href="http://stackoverflow.com/questions/37587942/python-selenium-failing-when-some-threads-create-webdriver/37593609#37593609">here</a>). I can't use a signal based timeout because my server is running on Windows so...
0
2016-06-15T00:13:05Z
37,833,054
<p>Thread pooling.</p> <pre><code>from multiprocessing.pool import ThreadPool pool = ThreadPool(processes=1) async_result = pool.apply_async(SpawnPhantomJS, (dcap, service_args)) newDriver = async_result.get(10) </code></pre>
0
2016-06-15T10:38:09Z
[ "python", "multithreading", "selenium" ]
Count the number of occurrences of certain choices in models
37,824,209
<p>I have the following models:</p> <pre><code>class Team(models.Model): # stuff class Event(models.Model): # stuff class Award(models.Model): award_type_choices = ( (1, "some string"), # a lot of these (2, "some other str"), ) award_type = models.CharField(choices=award_type_choice...
0
2016-06-15T00:21:22Z
37,824,253
<pre><code>choices = Award.specific_choices.all() c = Team.objects.filter(award__award_type__in=choices).count() </code></pre>
1
2016-06-15T00:29:44Z
[ "python", "django", "python-3.x", "django-queryset" ]
Count the number of occurrences of certain choices in models
37,824,209
<p>I have the following models:</p> <pre><code>class Team(models.Model): # stuff class Event(models.Model): # stuff class Award(models.Model): award_type_choices = ( (1, "some string"), # a lot of these (2, "some other str"), ) award_type = models.CharField(choices=award_type_choice...
0
2016-06-15T00:21:22Z
37,824,784
<p>I was able to find some Django docs about <a href="https://docs.djangoproject.com/en/1.9/ref/models/conditional-expressions/#conditional-aggregation" rel="nofollow">Conditional Aggregation</a> that helped me solve this.</p> <pre><code>def most_specifics(): reverse_specs = dict((v, k) for k, v in Award.specific_...
0
2016-06-15T01:44:58Z
[ "python", "django", "python-3.x", "django-queryset" ]