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
Regex replacing pairs of dollar signs
38,645,212
<p>I have a string like: <code>The old man $went$ to the $barn$.</code> How would I convert this to <code>The old man ~!went! to the ~!barn!.</code></p> <p>If I didn't need to add the <code>~</code> in front of the first occurrence, I could simply do <code>text.replace('$', '!')</code> in Python.</p>
1
2016-07-28T19:30:58Z
38,645,784
<p>Probably regex capturing group is the way to go here, but here a simple way to do it without regex:</p> <pre><code>&gt;&gt;&gt; s 'The old man $went$ to the $barn$' &gt;&gt;&gt; r '' &gt;&gt;&gt; seen = False &gt;&gt;&gt; &gt;&gt;&gt; for c in s: if c=='$': if seen: r +='!' ...
1
2016-07-28T20:06:05Z
[ "python", "regex" ]
How to avoid memory error when computing huge covariance and identity matrices with numpy
38,645,218
<p>I have two matrices as numpy arrays:</p> <pre><code>A.shape (800, 1200) B.shape (800, 101343) </code></pre> <p>I need to compute the covariance matrix of A, and B, and the identity matrix of A and B:</p> <pre><code>import numpy as np a_row, a_col = A.shape b_row, b_col = B.shape C_ab = np.cov(A,B, rowvar=False)[:...
0
2016-07-28T19:31:17Z
38,646,198
<p>GraphLab create has their own implementation of Numpy that you can install, that does all the computation on disk, see: <a href="https://turi.com/learn/gallery/notebooks/linear_regression_benchmark.html" rel="nofollow">https://turi.com/learn/gallery/notebooks/linear_regression_benchmark.html</a>. Specifically they h...
0
2016-07-28T20:32:19Z
[ "python", "numpy", "matrix" ]
Python pygame error : Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found
38,645,391
<p>I installed the FlapPyBird repo from <a href="https://github.com/sourabhv/FlapPyBird">https://github.com/sourabhv/FlapPyBird</a>. I have libpng installed but when i try to run the program with python flappy.py i get </p> <pre><code>Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found </code></pre> ...
7
2016-07-28T19:42:29Z
38,907,345
<p>Maybe you must install <code>libpng</code>?</p> <p>You can do it with homebrew:</p> <pre><code>brew install libpng </code></pre>
0
2016-08-11T22:59:45Z
[ "python", "osx", "libpng" ]
Python pygame error : Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found
38,645,391
<p>I installed the FlapPyBird repo from <a href="https://github.com/sourabhv/FlapPyBird">https://github.com/sourabhv/FlapPyBird</a>. I have libpng installed but when i try to run the program with python flappy.py i get </p> <pre><code>Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found </code></pre> ...
7
2016-07-28T19:42:29Z
39,425,923
<p>Use python3 interpreter and it will work</p>
0
2016-09-10T12:07:45Z
[ "python", "osx", "libpng" ]
Python pygame error : Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found
38,645,391
<p>I installed the FlapPyBird repo from <a href="https://github.com/sourabhv/FlapPyBird">https://github.com/sourabhv/FlapPyBird</a>. I have libpng installed but when i try to run the program with python flappy.py i get </p> <pre><code>Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found </code></pre> ...
7
2016-07-28T19:42:29Z
39,614,409
<p>Try:</p> <pre><code>brew unlink libpng &amp;&amp; brew link libpng </code></pre> <p>With me it was some problems with the linking.</p>
0
2016-09-21T10:47:07Z
[ "python", "osx", "libpng" ]
Creating a model from a form in django
38,645,398
<p>I have a django project with a front end created using bootstrap which has about 20 fields :</p> <pre><code>&lt;form id="form" class="form-vertical" action="/contact/" method="post"&gt; {% csrf_token %} &lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-md-6 col-sm-6 col-xs-...
0
2016-07-28T19:43:19Z
38,646,442
<p>The simplest approach is probably to switch it to a ModelForm - and it's definitely the best approach to take.</p> <p>Using a ModelForm with bootstrap can be a little tricky at first, but take a look at <a href="http://django-crispy-forms.readthedocs.io/en/latest/" rel="nofollow">django crispy forms</a>, it makes i...
2
2016-07-28T20:47:48Z
[ "python", "django", "twitter-bootstrap" ]
Catkin build corruption after interruption
38,645,427
<p>I interrupted (Ctrl+C) a <code>catkin build</code> execution when it hadn't started to actually build files. Now, I can't run it again because some file seems to be corrupted. I get this error when I execute <code>catkin build</code> on the workspace:</p> <pre><code>$ catkin build Traceback (most recent call last):...
0
2016-07-28T19:45:36Z
38,655,571
<p>I solved it by removing the file <code>&lt;workspace&gt;/build/.catkin_tools.yaml</code>.</p>
0
2016-07-29T09:44:07Z
[ "python", "ros", "catkin" ]
Cannot pull only visible text from table using BS4
38,645,464
<p>I am trying to scrape data such as the position and player name from <a href="https://en.wikipedia.org/wiki/2012_NFL_Draft" rel="nofollow">this</a> webpage. My code is below.</p> <pre><code>#create url for the wikipedia data we are going to scrape wikiURL = "https://en.wikipedia.org/wiki/2012_NFL_Draft" #create ar...
1
2016-07-28T19:47:47Z
38,646,030
<p>If you just want the name and the position, you can simplify the code to look for each <em>span</em> inside each <em>td</em> of the table with the <em>class fn</em>, get the text from that then look for the next <em>td</em> and extract the text from the <em>td's anchor</em>.</p> <pre><code>from bs4 import Beautifu...
2
2016-07-28T20:21:38Z
[ "python", "html", "web-scraping", "beautifulsoup", "wikipedia" ]
Python Pandas: Creating seasonal DateOffset object?
38,645,472
<p>I have a datetime indexed dataframe with an hourly frequency. I would like to produce a groupby object - grouping by the season. By season I mean spring is months 3, 4, 5, summer is 6, 7, 8, and so on. I would like to have a unique group for each year-season combination. Is there a way to do this with a custom D...
0
2016-07-28T19:47:58Z
38,646,603
<p>For the kind of grouping you want to do, use <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offsets" rel="nofollow">anchored quarterly offsets</a>.</p> <pre><code>import numpy as np import pandas as pd dates = pd.date_range('2016-01', freq='MS', periods=12) df = pd.DataFrame({'num': ...
1
2016-07-28T20:56:58Z
[ "python", "pandas" ]
Python Relative Import cannot find package
38,645,486
<p>I'm sure that this is a pretty simple problem and that I am just missing something incredibly obvious, but the answer to this predicament has eluded me for several hours now.</p> <p>My project directory structure looks like this:</p> <pre><code>-PhysicsMaterial -Macros __init__.py Macros.py -Modu...
2
2016-07-28T19:48:38Z
38,645,828
<p><a href="http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py">Attempted relative import in non-package even with __init__.py</a></p> <p>Well, guess it's on to using sys.path.append now. Clap and a half to @BrenBarn, @fireant, and @Ignacio Vazquez-Abrams </p>
0
2016-07-28T20:09:04Z
[ "python", "package", "directory-structure", "relative-import" ]
Python Relative Import cannot find package
38,645,486
<p>I'm sure that this is a pretty simple problem and that I am just missing something incredibly obvious, but the answer to this predicament has eluded me for several hours now.</p> <p>My project directory structure looks like this:</p> <pre><code>-PhysicsMaterial -Macros __init__.py Macros.py -Modu...
2
2016-07-28T19:48:38Z
38,645,976
<p>This occurs because you're running the script as <code>__main__</code>. When you run a script like this:</p> <pre><code>python /path/to/package/module.py </code></pre> <p>That file is loaded as <code>__main__</code>, not as <code>package.module</code>, so it can't do relative imports because it isn't part of a pa...
2
2016-07-28T20:17:00Z
[ "python", "package", "directory-structure", "relative-import" ]
Need to Kill Batch File
38,645,496
<p>Ok, I've searched many sites for an answer for a few days now. If there is an answer somewhere, if you point me there is fine. I am trying to get batch file "A" to read text file "B" and take some information and replace code in batch file "C". On first run it will do this and then run batch file "C". While batch fi...
-1
2016-07-28T19:49:18Z
38,645,846
<p>On windows I use that and it works fine. Can also be done by directly calling win32 api.</p> <pre><code> os.system ("taskkill /F /PID "+str (p.pid)) </code></pre> <p>P being your subprocess popen object.</p> <p>Edit: that is not working probably because of <code>start</code> prefix. You need to create a python th...
0
2016-07-28T20:09:59Z
[ "python", "windows", "batch-file", "cmd" ]
Issue With Checking If Number Contained in Index Pandas
38,645,562
<p>So I have a dataframe, lets call it df1, that looks like the following.</p> <pre><code> Index ID 1 90 2 508 3 692 4 944 5 1172 6 1998 7 2022 </code></pre> <p>Now if I call (508 == df['ID']).any() it returns true as it should. But if I have ...
2
2016-07-28T19:52:32Z
38,645,711
<p>Try turning it around.</p> <pre><code>(df1['ID'] == df2.iloc[1][0]).any() True </code></pre> <p>This is happening as a result of how the <code>==</code> is being handled for the objects being passed to it.</p> <p>In this case you have the first object of type</p> <pre><code>type(df2.iloc[1][0]) numpy.int64 </c...
3
2016-07-28T20:01:38Z
[ "python", "pandas" ]
Issue With Checking If Number Contained in Index Pandas
38,645,562
<p>So I have a dataframe, lets call it df1, that looks like the following.</p> <pre><code> Index ID 1 90 2 508 3 692 4 944 5 1172 6 1998 7 2022 </code></pre> <p>Now if I call (508 == df['ID']).any() it returns true as it should. But if I have ...
2
2016-07-28T19:52:32Z
38,645,723
<p>Something like this to check if the <code>ID</code> column is in the <code>Num</code> column of <code>df2</code>:</p> <pre><code>&gt;&gt;&gt; df1.ID.isin(df2.Num) Index 1 False 2 True 3 False 4 False 5 False 6 False 7 False Name: ID, dtype: bool </code></pre> <p>or:</p> <pre><code>&gt;&gt;&g...
0
2016-07-28T20:02:27Z
[ "python", "pandas" ]
Issue With Checking If Number Contained in Index Pandas
38,645,562
<p>So I have a dataframe, lets call it df1, that looks like the following.</p> <pre><code> Index ID 1 90 2 508 3 692 4 944 5 1172 6 1998 7 2022 </code></pre> <p>Now if I call (508 == df['ID']).any() it returns true as it should. But if I have ...
2
2016-07-28T19:52:32Z
38,645,762
<p>This works </p> <pre><code> (df['ID']==df2.iloc[1][0]).any() </code></pre>
1
2016-07-28T20:04:52Z
[ "python", "pandas" ]
building json data from sql database cursor
38,645,607
<p>Without knowing the structure of the json, how can I return a json object from the database query? All of the the information is there, I just can't figure out how to build the object.</p> <pre><code>import MySQLdb import json db = MySQLdb.connect( host, user, password, db) cursor = db.cursor() cursor.execute( quer...
0
2016-07-28T19:55:32Z
38,645,873
<p>1- You can use <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">pymsql</a> <code>DictCursor</code>:</p> <pre><code>import pymysql connection = pymysql.connect(db="test") cursor = connection.cursor(pymysql.cursors.DictCursor) cursor.execute("SELECT ...") row = cursor.fetchone() print row["key"] </code></p...
1
2016-07-28T20:11:08Z
[ "python", "sql", "json" ]
building json data from sql database cursor
38,645,607
<p>Without knowing the structure of the json, how can I return a json object from the database query? All of the the information is there, I just can't figure out how to build the object.</p> <pre><code>import MySQLdb import json db = MySQLdb.connect( host, user, password, db) cursor = db.cursor() cursor.execute( quer...
0
2016-07-28T19:55:32Z
38,646,113
<p>The problem you are encountering happens because you only turn the fetched items into dicts, without their description.</p> <p><code>dict</code> in python expects either another dict, or an iterable returning two-item tuples, where for each tuple the first item will be the key, and the second the value. </p> <p>Si...
1
2016-07-28T20:26:04Z
[ "python", "sql", "json" ]
building json data from sql database cursor
38,645,607
<p>Without knowing the structure of the json, how can I return a json object from the database query? All of the the information is there, I just can't figure out how to build the object.</p> <pre><code>import MySQLdb import json db = MySQLdb.connect( host, user, password, db) cursor = db.cursor() cursor.execute( quer...
0
2016-07-28T19:55:32Z
38,646,138
<p>I got this to work using Collections library, although the code is confusing: </p> <pre><code>import MySQLdb import json import collections db = MySQLdb.connect(host, user, passwd, db) cursor = db.cursor() cursor.execute( query ) rows = cursor.fetchall() field_names = [i[0] for i in cursor.description] objects_lis...
0
2016-07-28T20:28:03Z
[ "python", "sql", "json" ]
python: read in text file in numpy.loadtxt format splitting integers by digits
38,645,616
<p>My program reads a text file formatted like this with spaces between each digit:</p> <pre><code>0 1 1 1 0 0 1 0 0 </code></pre> <p>My current code to read the text file is </p> <pre><code>G = numpy.loadtxt(filename, int) </code></pre> <p>If I print(G), the output looks like this:</p> <pre><code>[[0 1 1] [1 0 0...
1
2016-07-28T19:55:55Z
38,645,726
<p>What you have already is almost working. Just add one more line at the bottom of your code, like this:</p> <pre><code>G = numpy.array(G) </code></pre>
1
2016-07-28T20:02:31Z
[ "python" ]
Issues with PyQt5's OpenGL module and versioning (calls for incorrect _QOpenGLFunctions_(ver))
38,645,674
<p>I have been trying to get <a href="https://github.com/baoboa/pyqt5/blob/master/examples/opengl/hellogl.py" rel="nofollow">the PyQt5 helloGL example code</a> to compile. When I try to build the solution, I get:</p> <pre><code>Traceback (most recent call last): File "C:\Users\\-PATH-\trunk\view\test.py", line 142,...
0
2016-07-28T19:59:45Z
38,766,800
<p>That's the problem of using these 2 lines:</p> <pre><code> self.gl = self.context().versionFunctions() self.gl.initializeOpenGLFunctions() </code></pre> <p>Instead, you should be creating a custom QSurfaceFormat with the proper major/minor version and using QContext's setFormat to make it work with a suitab...
0
2016-08-04T12:02:11Z
[ "python", "opengl", "pyqt", "pyopengl" ]
The fastest way to parse dates in Python when reading .csv file?
38,645,733
<p>I have a .csv file that has 2 separate columns for <code>'Date'</code> and <code>' Time'</code>. I read the file like this:</p> <pre><code>data1 = pd.read_csv('filename.csv', parse_dates=['Date', 'Time']) </code></pre> <p>But it seems that only the <code>' Date'</code> column is in time format while the <code>'Tim...
2
2016-07-28T20:02:50Z
38,646,821
<p>Here, In your case '<strong>Time</strong>' is in <strong>AM/PM</strong> format which take more time to parse.</p> <p>You can add <strong>format</strong> to increase speed of to_datetime() method.</p> <pre><code>data0=pd.read_csv('filename.csv') # %Y - year including the century # %m - month (01 to 12) # %d - day ...
2
2016-07-28T21:11:32Z
[ "python", "date", "csv", "pandas" ]
OpenCV Hough Circle Transform Not Working
38,645,772
<p>I have followed OpenCV's tutorial <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html#additional-resources" rel="nofollow">here</a> for circle detection on my Raspberry Pi. This is the code that I am using which is the same as the tutorial except a different imag...
0
2016-07-28T20:05:43Z
38,646,350
<p>The large amount of circles generated by <em>Hough Circle Transform</em> is caused by the low value of the threshold for center detection, which is <code>param2</code> in <code>cv2.HoughCircles</code> in your case.</p> <p>So try to increase the value of <code>param2</code> to avoid false detections.</p> <p>Also yo...
1
2016-07-28T20:41:56Z
[ "python", "opencv", "geometry", "shape", "detection" ]
Python: class with double underscore
38,645,871
<p>I'm following this <a href="http://stackoverflow.com/a/6798042/820410">link</a> and trying to make a singleton class using Metaclass. But, I want to make some internal tweaks to this singleton class and want the users to use another class (let's call it <code>MySingleton(__Singleton)</code>). So I decided to make it...
2
2016-07-28T20:11:03Z
38,645,934
<p>Every name inside a class definition with two leading underscores is mangled, so <code>__Singleton</code> becomes <code>_Singleton__Singleton</code>. To make clear, that some class is not supposed to be used publicly use <strong>one</strong> underscore.</p>
1
2016-07-28T20:14:33Z
[ "python", "python-2.7", "class", "private" ]
Python: class with double underscore
38,645,871
<p>I'm following this <a href="http://stackoverflow.com/a/6798042/820410">link</a> and trying to make a singleton class using Metaclass. But, I want to make some internal tweaks to this singleton class and want the users to use another class (let's call it <code>MySingleton(__Singleton)</code>). So I decided to make it...
2
2016-07-28T20:11:03Z
38,646,003
<p>Inside the class, the identifier <code>__Singleton</code> is getting <a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="nofollow">mangled</a>. You end up having problems because name mangling only happens inside classes (not outside). So <code>__Singleton</code> as a class name means ...
3
2016-07-28T20:18:57Z
[ "python", "python-2.7", "class", "private" ]
Python: class with double underscore
38,645,871
<p>I'm following this <a href="http://stackoverflow.com/a/6798042/820410">link</a> and trying to make a singleton class using Metaclass. But, I want to make some internal tweaks to this singleton class and want the users to use another class (let's call it <code>MySingleton(__Singleton)</code>). So I decided to make it...
2
2016-07-28T20:11:03Z
38,646,051
<p>Python does not have <a href="https://docs.python.org/2/tutorial/classes.html#tut-private" rel="nofollow">private variables</a>; they are all accessible externally.</p> <blockquote> <p>“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is ...
1
2016-07-28T20:22:47Z
[ "python", "python-2.7", "class", "private" ]
How can I pass an image to a template in Django?
38,645,938
<p>Suppose that the corresponding function in views.py looks like</p> <pre><code>from PIL import Image def get_img(request, img_source) base_image = Image.open(os.getcwd() + '/deskprod/media/img/'+ img_source + ".png") #Some editing of base_image done with PIL that prevents image from being directly loaded in ...
0
2016-07-28T20:14:50Z
38,646,112
<p>I think you must save image (write it to temp file) in static directory of project and in template use static command and image file name to display it.</p>
0
2016-07-28T20:26:03Z
[ "python", "django", "image", "python-imaging-library" ]
How can I pass an image to a template in Django?
38,645,938
<p>Suppose that the corresponding function in views.py looks like</p> <pre><code>from PIL import Image def get_img(request, img_source) base_image = Image.open(os.getcwd() + '/deskprod/media/img/'+ img_source + ".png") #Some editing of base_image done with PIL that prevents image from being directly loaded in ...
0
2016-07-28T20:14:50Z
38,646,192
<p>You should process the image, save it on local disk and then send a path to it or more like the media url which will correspond to that image as context to html template. You need to configure your django server to serve static and media files to do that and configure serving those files in production environment as...
3
2016-07-28T20:32:02Z
[ "python", "django", "image", "python-imaging-library" ]
Creating ORM mappings over subqueries of a table
38,645,982
<p>I'm trying to use SQLAlchemy in a situation where I have a one to many table construct and but I essentially want to create a one to one mapping between tables using a subquery.</p> <p>For example </p> <pre><code>class User: __tablename__='user' userid = Column(Integer) username = Column(String) class...
0
2016-07-28T20:17:22Z
38,646,805
<p>You don't need to use a subquery. The join condition is not limited to foreign key against primary key:</p> <pre><code>home_address = aliased(Address, "home_address") work_address = aliased(Address, "work_address") session.query(User) \ .join(home_address, and_(User.userid == home_address.userid, ...
1
2016-07-28T21:10:28Z
[ "python", "orm", "sqlalchemy" ]
Change title of automatically generated form view in Odoo
38,645,998
<p>I want to change the heading of form view in the grey area. This should have to be change from SHIP00001 to some other name or field. Is that possible? <a href="http://i.stack.imgur.com/LdsfI.png" rel="nofollow">You can see in this image</a></p>
1
2016-07-28T20:18:46Z
38,647,548
<p>The name in the form view is gotten in two ways</p> <ol> <li>From a field which you specified <code>name</code> of the field (i.e <code>name = fields.Char('Field name')</code>)</li> <li>and when you set <code>_rec_name</code> to some other field or you override <code>_name_get</code> to set a custom name</li> </ol>...
3
2016-07-28T22:09:12Z
[ "python", "xml", "openerp", "odoo-8" ]
MemoryError while reading and writing a 40GB CSV... where is my leak?
38,646,009
<p>I have a 40GB CSV file which I have to output with different column subsets as CSVs once again, with a check that there are no <code>NaN</code>s in the data. I opted to use Pandas, and a minimal example of my implementation looks like this (inside a function <code>output_different_formats</code>):</p> <pre><code># ...
2
2016-07-28T20:19:15Z
38,655,202
<p>The solution for now has been to manually call the garbage collector with <code>gc.collect()</code></p> <pre><code>while scen_cnt &lt; 10000: scenario = scen_iter.get_chunk(CHUNKSIZE) if scenario.isnull().values.any(): # some error handling (has yet to ever occur) for item in output_names: ...
1
2016-07-29T09:26:14Z
[ "python", "python-3.x", "pandas", "memory" ]
AttributeError: LinearRegression object has no attribute 'coef_'
38,646,040
<p>I've been attempting to fit this data by a Linear Regression, following a tutorial on bigdataexaminer. Everything was working fine up until this point. I imported LinearRegression from sklearn, and printed the number of coefficients just fine. This was the code before I attempted to grab the coefficients from the co...
2
2016-07-28T20:22:22Z
38,646,285
<p>The <code>coef_</code> attribute is created when the <code>fit()</code> method is called. Before that, it will be undefined:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; from sklearn.datasets import load_boston &gt;&gt;&gt; from sklearn.linear_model import LinearRegre...
1
2016-07-28T20:37:59Z
[ "python", "python-3.x", "scikit-learn", "linear-regression", "attributeerror" ]
Having troubles changing value of global variable
38,646,056
<p>I am trying to create a battleships game to practice my coding, however I am having trouble changing the value of a global variable.</p> <hr> <pre><code>turnsover = 0 diff = 0 ship_row = 0 ship_col = 0 def difficulty(): global diff global turnsover diff = input("Please select a difficulty\n 1=Easy \n...
-3
2016-07-28T20:23:05Z
38,646,184
<p>As @MorganThrapp says, you are checking <code>turnsover</code> equality with code such as <code>turnsover == 10</code> and not assigning a value to it like so: <code>turnsover = 0</code>. <code>=</code> means <em>assignment</em> and <code>==</code> means <em>equality</em>. This should be obvious as you're <em>assign...
0
2016-07-28T20:31:40Z
[ "python", "python-3.x" ]
How can I authenticate with the Twitter API from Zapier?
38,646,057
<p>I'm trying to call the Twitter API from Zapier using "Webhooks by Zapier", but do not manage to authenticate correctly via OAuth 1.0.</p> <p>Using a REST client like Postman, it is a piece of cake. You just pass the consumer key, consumer secret, token and token secret, and set the signature method to HMAC-SHA1. Pl...
0
2016-07-28T20:23:08Z
38,646,157
<p>Similar to <a href="http://stackoverflow.com/questions/38624607">How do I make a Tweet in Zapier code</a>.</p> <p>Get that access token and then use your own token and set a header! </p>
0
2016-07-28T20:29:30Z
[ "javascript", "python", "twitter", "oauth", "zapier" ]
Tensorflow creating new variables even when graph is resued
38,646,076
<p>I'm using TFLearn and Tensorflow to run a CNN. My current approach is rebuilding the model with each run because my batch size changes between training and testing. I noticed some memory issues and then when I investigated further I found that on each run I was recreating my entire model on the Graph even though I'm...
0
2016-07-28T20:24:19Z
38,646,776
<p>Looks like I had a misunderstanding of what is meant by the default graph. I thought if I created the graph like I did above it would be used every time I ran that model, but that didn't appear to be the case. I've changed my code to build the model inside a block like so:</p> <pre><code>tf.reset_default_graph() g ...
0
2016-07-28T21:08:04Z
[ "python", "tensorflow", "tensorboard" ]
Tensorflow creating new variables even when graph is resued
38,646,076
<p>I'm using TFLearn and Tensorflow to run a CNN. My current approach is rebuilding the model with each run because my batch size changes between training and testing. I noticed some memory issues and then when I investigated further I found that on each run I was recreating my entire model on the Graph even though I'm...
0
2016-07-28T20:24:19Z
39,556,108
<p>You can also write it as follows:<br> <code>with tf.Graph().as_default(), tf.Session() as session: </code></p>
0
2016-09-18T09:29:06Z
[ "python", "tensorflow", "tensorboard" ]
Django Reverse relation in template renders sporadically
38,646,145
<p>I'm getting different results from a template when I render it using Selenium in a functional test. Visiting the page normally, I see objects being rendered. During a functional test, the page is blank (it doesn't even render the text in the empty clause.) I wrote a small Django app to test it and make sure I'm n...
1
2016-07-28T20:28:36Z
38,646,426
<pre><code>self.browser.get(self.live_server_url) text = ... </code></pre>
0
2016-07-28T20:46:45Z
[ "python", "django", "selenium" ]
Flatten columns by grouping by and adding values in pandas
38,646,160
<p>I have a dataframe like</p> <pre><code> id, index, name, count1, count2 1, 1, foo, 12, 10 1, 2, foo, 11, 12 1, 3, foo, 23, 12 1, 1, bar, 11, 21 ... 2, 1, foo, ... </code></pre> <p>I want to get a dataframe as follows</p> <pre><code>id, name, count1, count2 1, foo, 46,34 1, bar, .. </code></...
1
2016-07-28T20:29:57Z
38,646,211
<p>is that what you want?</p> <pre><code>In [24]: df.groupby(['id','name']).sum().reset_index() Out[24]: id name index count1 count2 0 1 bar 1 11 21 1 1 foo 6 46 34 </code></pre> <p>if you want to drop <code>index</code> column:</p> <pre><code>In [26]: df.groupby(['id','name...
1
2016-07-28T20:32:41Z
[ "python", "pandas" ]
Python: Including only the last 7 values in each key
38,646,190
<p>I have a dictionary where each key has multiple values. Would it be possible to include only the last 7 values for each key, and then do basic arithmetic with it (ex: addition, subtraction, multiplication, division)?</p> <p>The end objective is to be able to upload date-specific data and be able to include only the...
-3
2016-07-28T20:31:51Z
38,646,262
<p>How do you store multiple values of each key? If you use a list, then all you need to do is reference the last X elements of that list. </p> <p>Assuming that you need to retain the entire dictionary and only reference the last X elements: </p> <pre><code>my_dict = {key1:[e_a1, e_a2, ... e_a9], key2:[e_b1, e_b2, .....
0
2016-07-28T20:36:11Z
[ "python", "dictionary", "value" ]
Python: Including only the last 7 values in each key
38,646,190
<p>I have a dictionary where each key has multiple values. Would it be possible to include only the last 7 values for each key, and then do basic arithmetic with it (ex: addition, subtraction, multiplication, division)?</p> <p>The end objective is to be able to upload date-specific data and be able to include only the...
-3
2016-07-28T20:31:51Z
38,646,339
<p>Depending on how the incoming data is organized (already sorted vs. random order), I'd take a look at <a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow"><code>collections.deque</code></a> (which can set a maximum length so newly added items seamlessly push out older items o...
2
2016-07-28T20:41:19Z
[ "python", "dictionary", "value" ]
Pandas read_sql query with multiple selects
38,646,214
<p>Can read_sql query handle a sql script with multiple select statements?</p> <p>I have a MSSQL query that is performing different tasks, but I don't want to have to write an individual query for each case. I would like to write just the one query and pull in the multiple tables.</p> <p>I want the multiple queries i...
5
2016-07-28T20:32:53Z
38,647,343
<p>You could do the following:</p> <pre><code>queries = """ SELECT ColumnX_1, ColumnX_2, ColumnX_3 FROM Table_X INNER JOIN (Etc etc...) --- SELECT ColumnY_1, ColumnY_2, ColumnY_3 FROM Table_Y INNER JOIN (Etc etc...) """.split("---") </code></pre> <p>Now you can query each table and concat the result:</p> <pre><cod...
2
2016-07-28T21:51:37Z
[ "python", "sql", "sql-server", "python-3.x", "pandas" ]
How to remove b and \n from variable/text file in Python3? (TypeError)
38,646,251
<p>This gives me a massive headache. My code:</p> <pre><code>import subprocess proc = subprocess.Popen("php /var/scripts/data.php", shell=True, stdout=subprocess.PIPE) scriptresponse = proc.stdout.read() print (scriptresponse) </code></pre> <p>Output:</p> <blockquote> <p>b'January\n'</p> </blockquote> <p>I tried ...
1
2016-07-28T20:35:24Z
38,648,265
<p>Try adding <code>universal_newlines=True</code> as an argument to the <code>Popen</code> call.</p> <p>As mentioned in the <a href="https://docs.python.org/3.5/library/subprocess.html#subprocess.Popen" rel="nofollow">docs</a>:</p> <blockquote> <p>If <em>universal_newlines</em> is <code>True</code>, the file objec...
0
2016-07-28T23:23:01Z
[ "python", "python-3.x" ]
Irregular region masking in python
38,646,270
<p>I want to mask the region inside a contour. My piece of code is as follows:</p> <pre><code>cnt = np.array(list((y, x) for x in X for y in Y)) mask = np.zeros(np.shape(b_contour_map),np.uint8) cv2.drawContours(mask,[cnt],0,1) </code></pre> <p>I create cnt based on two vectors of points coordinates, and when printed...
1
2016-07-28T20:36:51Z
38,693,319
<p>It turns out that the order of the points was the issue. I got correct results by implementing: <p> cnt = zip(Y, X) cnt.sort(key=lambda x: (-x[0], x[<a href="http://i.stack.imgur.com/p4JQS.png" rel="nofollow">1</a>])) <p> maskIm = Image.new('L', (b_contour_map.shape[<a href="http://i.stack.imgur.com/p4JQS.png" rel="...
0
2016-08-01T07:37:15Z
[ "python", "opencv" ]
Authenticating a Controller with a Tor subprocess using Stem
38,646,320
<p>I am trying to launch a new tor process (no tor processes currently running on the system) using a 'custom' config by using stems <code>launch_tor_with_config</code>.</p> <p>I wrote a function that will successfully generate and capture a new hashed password. I then use that new password in the config, launch tor a...
1
2016-07-28T20:40:00Z
38,663,392
<p>The trouble is that you're authenticating with the password hash rather than the password itself. Try...</p> <pre><code>password = raw_input('password: ') password_hash = genTorPassHash(password) ... then use the password_hash in the config and password for authentication </code></pre>
2
2016-07-29T16:21:14Z
[ "python", "tor", "stem" ]
insert data in mongodb with python
38,646,338
<p>this is my first shot at using dbs and I'm having some trouble with the basics. Tried to look online but couldnt find answers to simple questions. When I try to add some info to my db, I get a whole bunch of errors.</p> <pre><code>import pymongo def get_db(): from pymongo import MongoClient client = Mongo...
1
2016-07-28T20:41:07Z
38,651,091
<ol> <li><p>Check twice if your <code>xxxxxxx</code> from <code>ds029735.mlab.com:29735/xxxxxxx</code> is equal to <code>myDB</code> from <code>db = client.myDB</code>. I mean if your connection string is <code>mongodb://username:password@ds029735.mlab.com:29735/xyz</code> then your code should be <code>db = client.xyz...
1
2016-07-29T05:28:14Z
[ "python", "mongodb", "python-2.7", "pymongo" ]
Python list comprehension for identifying and modifying a sequence
38,646,362
<p>I have a method which iterates over a list of numbers, and identifies for sequences of 0, non-zero, 0 and then 'normalizes' the value inbetween to 0.</p> <p>Here is my code:</p> <pre><code>for index in range(len(array)-2): if array[index] == 0 and array[index + 1] != 0 and array[index + 2] == 0: array[...
0
2016-07-28T20:42:39Z
38,646,564
<p>You might try something like</p> <pre><code>new_array = [ 0 if (array[i-1] == array[i+1] == 0) else array[i] for i in range(1,len(array)-1) ] # More readable, but far less efficient array = array[0] + new_array + array[-1] # More efficient, but less readable # array[1:-1] = new_arr...
2
2016-07-28T20:54:30Z
[ "python", "list-comprehension" ]
Python list comprehension for identifying and modifying a sequence
38,646,362
<p>I have a method which iterates over a list of numbers, and identifies for sequences of 0, non-zero, 0 and then 'normalizes' the value inbetween to 0.</p> <p>Here is my code:</p> <pre><code>for index in range(len(array)-2): if array[index] == 0 and array[index + 1] != 0 and array[index + 2] == 0: array[...
0
2016-07-28T20:42:39Z
38,647,033
<p>From the comments and advice given, it seems that my original code is the most simplest and perhaps most efficient way of performing the process. No further answers are necessary.</p>
1
2016-07-28T21:27:19Z
[ "python", "list-comprehension" ]
Python list comprehension for identifying and modifying a sequence
38,646,362
<p>I have a method which iterates over a list of numbers, and identifies for sequences of 0, non-zero, 0 and then 'normalizes' the value inbetween to 0.</p> <p>Here is my code:</p> <pre><code>for index in range(len(array)-2): if array[index] == 0 and array[index + 1] != 0 and array[index + 2] == 0: array[...
0
2016-07-28T20:42:39Z
38,649,360
<p>Not everything should be a comprehension. If you wish to be torturous though:</p> <pre><code>def f(a): [a.__setitem__(i + 1, 0) for i, (x, y, z) in enumerate(zip(a, a[1:], a[2:])) if x == z == 0 and y != 0] </code></pre> <p>Then</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 0, 1, 0, 4] &gt;&gt;&gt; f(a) &gt;&...
-2
2016-07-29T01:58:16Z
[ "python", "list-comprehension" ]
How do I unit test a filter?
38,646,380
<p>I'm using a filter to <a href="http://stackoverflow.com/questions/3845423/remove-empty-strings-from-a-list-of-strings#3845453">remove empty values from a list</a>:</p> <pre><code>def clean_list(inp): return filter(None, inp) </code></pre> <p>How do I unit-test this piece of code?</p> <p>All of the following fai...
1
2016-07-28T20:43:57Z
38,646,649
<p>Based on the comments and confirmation from <a href="http://stackoverflow.com/a/12319034/1316981">this question</a>, it seems the best solution is to "consume" the filter. Because I'm using parameterized testing, the best option is to do this in the function itself and return a plain list.</p> <p>So my <code>clean_...
0
2016-07-28T21:00:04Z
[ "python", "unit-testing", "python-3.x", "filter", "py.test" ]
tarfile compressionerror bz2 module is not available
38,646,400
<p>I'm trying to install twisted pip install <a href="https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd9a97f1e900dfcb/Twisted-16.2.0.tar.bz2#md5=8b35a88d5f1a4bfd762a008968fddabf" rel="nofollow">https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd...
1
2016-07-28T20:45:11Z
38,650,101
<p>I don't seem to have any problem with <code>import bz2</code> on my python 3.4 installation. So I did </p> <pre><code>import bz2 print (bz2.__file__) </code></pre> <p>And found that it's located at <code>/usr/lib/python3.4/bz2.py</code> then I did</p> <pre><code>dpkg -S /usr/lib/python3.4/bz2.py </code></pre> <p...
1
2016-07-29T03:33:50Z
[ "python", "linux", "django", "python-3.x", "bz2" ]
How to change values in a list by using dict definitions python?
38,646,432
<p>I have a list <code>l = [1, 1, 2, 1, 3, 3, 1, 1, 1, 3]</code> and I want to use my dict <code>d = {1:'r', 2:'b', 3:'g'}</code> to get the result <code>l = [r, r, b, r, g, g, r, r, r, g]</code>? What is the most pythonic way to achieve this?</p>
-2
2016-07-28T20:47:13Z
38,646,488
<p>Most Pythonic is probably a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>l = [d[x] for x in l] </code></pre> <p>For larger inputs, the following <em>might</em> be faster, but less Pythonic, as it pays a slightly higher se...
2
2016-07-28T20:50:19Z
[ "python", "list", "dictionary" ]
How to change values in a list by using dict definitions python?
38,646,432
<p>I have a list <code>l = [1, 1, 2, 1, 3, 3, 1, 1, 1, 3]</code> and I want to use my dict <code>d = {1:'r', 2:'b', 3:'g'}</code> to get the result <code>l = [r, r, b, r, g, g, r, r, r, g]</code>? What is the most pythonic way to achieve this?</p>
-2
2016-07-28T20:47:13Z
38,646,517
<p>The following list comprehension will do:</p> <pre><code>mapped = [d[item] for item in l] </code></pre>
0
2016-07-28T20:52:01Z
[ "python", "list", "dictionary" ]
How to decode character to utf-8 at specific position
38,646,459
<p>I have a python script, in which there is a dictionary. For some reason, I need to convert dictionary to json. But, whenever script executed, It gives below error</p> <p><strong>UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 604: invalid continuation byte</strong></p> <p>for line <strong>json....
1
2016-07-28T16:18:38Z
38,646,460
<p>You're attempting to decode an invalid UTF-8 codepoint. Non-UTF-8 characters cannot be decoded. Try passing <code>'ignore</code>' to <code>.decode</code> if you absolutely must handle invalid codepoints, or try the <a href="http://chardet.readthedocs.io/en/latest/usage.html" rel="nofollow">chardet library</a> to det...
2
2016-07-28T17:55:08Z
[ "centos", "python", "character-encoding" ]
Implement Cost Function of Neural Network (Week #5 Coursera) using Python
38,646,500
<p>Based on the Coursera Course for Machine Learning, I'm trying to implement the cost function for a neural network in python. There is a <a href="http://stackoverflow.com/questions/21441457/neural-network-cost-function-in-matlab">question</a> similar to this one -- with an accepted answer -- but the code in that answ...
4
2016-07-28T20:51:04Z
38,648,739
<p>The problem is that you are using the <strong>wrong class labels</strong>. When computing the cost function, you need to use the <strong>ground truth</strong>, or the true class labels.</p> <p>I'm not sure what your Ynew array, was, but it wasn't the training outputs. So, I changed your code to use Y for the class ...
2
2016-07-29T00:28:45Z
[ "python", "numpy", "machine-learning" ]
Pulling hostnames from single line of text with regex
38,646,681
<p>I'm attempting to write a Python script pull all the Google Cloud Compute subnets from their DNS. More info about this here:</p> <p><a href="https://cloud.google.com/compute/docs/faq#where_can_i_find_short_product_name_ip_ranges" rel="nofollow">https://cloud.google.com/compute/docs/faq#where_can_i_find_short_produc...
2
2016-07-28T21:01:38Z
38,646,804
<p>You do not need to use a regex for this, use <code>split</code> twice and comprehension:</p> <pre><code>s = "v=spf1 include:_cloud-netblocks1.googleusercontent.com include:_cloud-netblocks2.googleusercontent.com include:_cloud-netblocks3.googleusercontent.com include:_cloud-netblocks4.googleusercontent.com include:...
1
2016-07-28T21:10:27Z
[ "python", "regex" ]
Minimum and Maximum query not working properly (Python 3.5)
38,646,688
<p>I wonder if you can help because I've been looking at this for a good half hour and I'm completely baffled, I think I must be missing something so I hope you can shed some light on this.</p> <p>In this area of my program I am coding a query which will search a list of tuples for the salary of the person. Each tuple...
1
2016-07-28T21:01:59Z
38,646,731
<p>When you read in from standard input in Python, no matter what input you get, you receive the input as a string. That means that your comparison function is resulting to:</p> <pre><code>if tuplist[x][2] &gt; "0" and tuplist[x][2] &lt; "999999" : </code></pre> <p>Can you see what the problem is now? Because it's a ...
1
2016-07-28T21:05:34Z
[ "python", "python-3.x" ]
Minimum and Maximum query not working properly (Python 3.5)
38,646,688
<p>I wonder if you can help because I've been looking at this for a good half hour and I'm completely baffled, I think I must be missing something so I hope you can shed some light on this.</p> <p>In this area of my program I am coding a query which will search a list of tuples for the salary of the person. Each tuple...
1
2016-07-28T21:01:59Z
38,646,760
<p>Given your use of the <code>print</code> function (instead of the Python 2 <code>print</code> statement), it looks like you're writing Python 3 code. In Python 3, <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow"><code>input</code></a> returns a <code>str</code>. I'm guessing your data ...
1
2016-07-28T21:07:16Z
[ "python", "python-3.x" ]
Using vimrc function to pass python arguments
38,646,736
<p>I am attempting to create a vimrc function that will be used in an <code>autocmd</code>. The function must simply call a python script and pass the file name as an argument.</p> <p><em>.vimrc</em></p> <pre><code>fu! Test(filename) let filename = expand("%:t") "echom filename !test.py filename </code></...
0
2016-07-28T21:05:44Z
38,646,861
<p>Sure, you can use the <code>execute</code> command to execute a string, which is built from the command you want and the variable concatenated together:</p> <pre><code>fu! Test() let filename = expand("%:t") execute "!test.py " . l:filename endfunction </code></pre> <p>I've omitted the filename argument in...
1
2016-07-28T21:13:37Z
[ "python", "vim" ]
Using vimrc function to pass python arguments
38,646,736
<p>I am attempting to create a vimrc function that will be used in an <code>autocmd</code>. The function must simply call a python script and pass the file name as an argument.</p> <p><em>.vimrc</em></p> <pre><code>fu! Test(filename) let filename = expand("%:t") "echom filename !test.py filename </code></...
0
2016-07-28T21:05:44Z
38,646,875
<p>You have two options either you pass the filename directly as an argument or pass it as a local variable:</p> <pre><code>fu! Test(filename) "echom a:filename execute "!test.py ".a:filename </code></pre> <p>or </p> <pre><code>fu! Test() let l:filename = expand("%:t") "echom filename execute "!t...
1
2016-07-28T21:14:35Z
[ "python", "vim" ]
How to generate JSON data with python 2.7+
38,646,742
<p>I have to following bit of JSON data which is a snippet from a large file of JSON. I'm basically just looking to expand this data. I'll worry about adding it to the existing JSON file later.</p> <p>The JSON data snippet is:</p> <pre><code> "Roles": [ { "Role": "STACiWS_B", "Settings": { "HostTyp...
1
2016-07-28T21:06:04Z
38,646,787
<p>Right here:</p> <pre><code>RoleData['Role']=SingleRole </code></pre> <p>You set RoleData to be the string 'STACiTS'. So then the next command evaluates to:</p> <pre><code>'STACiTS'['Settings']['HostType']=ASFHostType </code></pre> <p>Which of course is trying to index into a string with another string, which is ...
1
2016-07-28T21:08:50Z
[ "python", "json", "dictionary" ]
How do I order by an integer column divided the time difference in sqlalchemy?
38,646,803
<p>I'm trying to write and algorithm that orders links by: Link # of points / time difference in seconds / # of rows</p> <p>The only part that I'm having trouble with is the time difference part.</p> <pre><code>(Link.query .join(Point, (Point.link == Link.id)) .group_by(Link.id) .filter(Link.visibility...
1
2016-07-28T21:10:25Z
38,661,486
<p><em>Note: Well, you didn't provide any sample of your ORM, so I guessed one.</em> </p> <p>I think you need to not mix up python date types with sql date types. You need to use functions from your database. </p> <p>If using SQLite, you could use this order:</p> <pre><code># only valid for sqlite my_order = func.co...
1
2016-07-29T14:35:38Z
[ "python", "sqlalchemy" ]
Transmute list of dictionaries
38,646,853
<p>Attempting to track rank over time for various apps:</p> <pre><code># I need to convert this list of dicts: [{"Date" : "7/1/16", "Foo": 32, "Bar" : 49, 'Spam': 55}, {"Date" : "7/2/16", "Foo": 43, "Bar" : 44, 'Spam': 77}, {"Date" : "7/3/16", "Foo": 23, "Bar" : 47, 'Spam': 63}] # Into this list of dicts: [{"AppTi...
2
2016-07-28T21:13:16Z
38,646,990
<pre><code>import pandas as pd df = pd.DataFrame([{"Date" : "7/1/16", "Foo": 32, "Bar" : 49, 'Spam': 55}, {"Date" : "7/2/16", "Foo": 43, "Bar" : 44, 'Spam': 77}, {"Date" : "7/3/16", "Foo": 23, "Bar" : 47, 'Spam': 63}]) </code></pre> <p>From this DataFrame, you can get your result ...
2
2016-07-28T21:23:03Z
[ "python", "pandas" ]
Import CSV without primary key to existing table
38,646,873
<p>I have an existing table in Postgresql that has an id column (serial) for row identification and is the primary key. I have a script to import the CSV's, which do not contain the id column. Here is the code I'm using:</p> <pre><code>file_list = glob.glob(path) for f in file_list: if os.stat(f).st_size != 0: ...
1
2016-07-28T21:14:28Z
38,650,714
<p>COPY command contains the columns you want to insert. You must skip PK in the columns list: COPY table(col1, col2,...) </p> <p><a href="https://www.postgresql.org/docs/9.2/static/sql-copy.html" rel="nofollow">COPY documentation</a></p>
1
2016-07-29T04:50:07Z
[ "python", "postgresql", "csv", "import" ]
Embedding thumbnail to mp3 with Youtube-dl raise exception
38,646,886
<p>I am trying to use youtube-dl to download some youtube video sound as mp3 and embed the thumbnail as well. But i get the following error every time i try:</p> <pre><code>thumbnail_filename = info['thumbnails'][-1]['filename'] KeyError: 'filename' </code></pre> <p>Here is my youtube-dl options</p> <pre><code> y...
0
2016-07-28T21:15:20Z
38,667,103
<p>So I figured it out on on my own although its not documented on youtube-dl api. You need to add <code>'writethumbnail':True</code> to options, and change the order on the post processors so <code>'key': 'FFmpegExtractAudio'</code> is before <code>'key': 'EmbedThumbnail'</code></p> <pre><code> ydl_opts = { ...
0
2016-07-29T20:37:22Z
[ "python", "youtube-dl" ]
pyaiml does not respond on <that> tag
38,646,903
<p>I am trying the PyAiml package to write a chatbot. I wrote a very basic program with all those default aiml files from A.L.I.C.E. Everything works fine so far except the &lt;that&gt; tag. I thought it was the session problem. Then I fixed the session. But still no luck with &lt;that&gt; tag for contextual conversati...
2
2016-07-28T21:16:27Z
38,728,989
<p>Regarding your <code>&lt;that&gt;</code> tag issue, all I can tell you is that it's fine on the AIML part, what I came to offer is an alternative to using that tag (if that's how you were planning to use it):</p> <pre><code>&lt;category&gt; &lt;pattern&gt;TEST1&lt;/pattern&gt; &lt;template&gt;testing on...
0
2016-08-02T19:30:53Z
[ "python", "aiml" ]
How to find nearby points given a gps origin?
38,646,917
<p>How does one find a nearby point given a gps coordinate? The new point can be randomly chosen, but must be within 100 meters of the origin. Collisions are fine as well.</p> <p>ie, </p> <pre><code>origin = (latitude, longitude) # prints one nearby point in (lat, lon) print "%s, %s" % get_nearby_point(origin) # pr...
2
2016-07-28T21:17:25Z
38,647,176
<pre><code>import geopy.distance from random import random def get_nearby_point(origin): dist = geopy.distance.VincentyDistance(kilometers = .1) pt = dist.destination(point=geopy.Point(origin), bearing=random()*360) return pt[0],pt[1] origin = (34.2234, 14.252) # I picked some mostly random numbers # pri...
0
2016-07-28T21:39:12Z
[ "python", "python-2.7", "gps", "coordinates", "geopy" ]
How to install python packages for use in a jupyter notebook kernel?
38,647,078
<p>I installed Python 3 kernel using the following commands</p> <pre><code>conda create -n py35 python=3.5 ipykernel source activate py35 python -m ipykernel install –user –name py35 –display-name “Python 3” </code></pre> <p>When I import numpy in a python 3 notebook, I get <code>ImportError: No module name...
1
2016-07-28T21:32:01Z
38,647,099
<pre><code>conda create -n py35 python=3.5 ipykernel source activate py35 pip install numpy </code></pre>
-1
2016-07-28T21:33:27Z
[ "python", "jupyter-notebook" ]
Read CSV with Spark
38,647,132
<p>I am reading csv file through Spark using the following. </p> <pre><code>rdd=sc.textFile("emails.csv").map(lambda line: line.split(",")) </code></pre> <p>I need to create a Spark DataFrame. </p> <p>I have converted this rdd to spark df by using the following:</p> <pre><code>dataframe=rdd.toDF() </code></pre> <p...
1
2016-07-28T21:35:41Z
38,647,352
<p>If the RDD will fit in memory, then:</p> <pre><code>rdd.toPandas().to_csv('emails.csv') </code></pre> <p>If not, use <a href="https://github.com/databricks/spark-csv" rel="nofollow">spark-csv</a> for your version of spark:</p> <pre><code>rdd.write.format('com.databricks.spark.csv').save('emails.csv') </code></pre...
0
2016-07-28T21:52:51Z
[ "python", "csv", "apache-spark", "dataframe", "rdd" ]
Read CSV with Spark
38,647,132
<p>I am reading csv file through Spark using the following. </p> <pre><code>rdd=sc.textFile("emails.csv").map(lambda line: line.split(",")) </code></pre> <p>I need to create a Spark DataFrame. </p> <p>I have converted this rdd to spark df by using the following:</p> <pre><code>dataframe=rdd.toDF() </code></pre> <p...
1
2016-07-28T21:35:41Z
38,694,864
<p>If you have a huge file, why not use a pandas dataframe in chunks rather than loading all of it at once, something like :</p> <pre><code>import pandas as pd df_pd = pd.read_csv('myfilename.csv',chunksize = 10000) for i,chunk in enumerate(df1): if i==0: df_spark = sqlContext.createDataFrame(chunk) e...
0
2016-08-01T09:06:09Z
[ "python", "csv", "apache-spark", "dataframe", "rdd" ]
Adding functions to Selenium WebDriver WebElements using Python
38,647,151
<p>While using Selenium WebDriver to test a website, I would like to have the ability to double click on a WebElement object without having to having to use class inheritance or mess with ActionChains. Ideally, it should be accessible in the webelement.double_click() form, just as click() is. This can be done by editin...
2
2016-07-28T21:37:02Z
38,647,609
<p>To monkey patch the double click method on the <code>WebElement</code> class:</p> <pre><code>def WebElement_double_click(self): self._parent.execute(Command.MOVE_TO, {'element': self._id}) self._parent.execute(Command.DOUBLE_CLICK) return self WebElement.double_click = WebElement_double_click </code></...
0
2016-07-28T22:15:11Z
[ "python", "selenium", "webdriver" ]
Shapely not able to precisely find points inside polygon
38,647,168
<p>I have several points and I would like to check if they are contained on a polygon. The polygon and the points are represented by latitudes and longitudes.</p> <p>Following is the code of to reproduce my scenario and the Google Maps print screen of what it looks like the polygon, the points inside/outside the polyg...
0
2016-07-28T21:38:20Z
38,649,572
<p>Your polygon doesn't look anything like the picture you drew (best I can tell). </p> <p><a href="http://jsfiddle.net/geocodezip/sbcd0m22/" rel="nofollow">fiddle</a></p> <p><a href="http://i.stack.imgur.com/W8emI.png" rel="nofollow"><img src="http://i.stack.imgur.com/W8emI.png" alt="enter image description here"></...
1
2016-07-29T02:21:27Z
[ "python", "google-maps", "map-projections", "shapely" ]
Can create one figure but not another in matplotlib/pyplot
38,647,225
<p>I am trying to use PyPlot to display multiple graphs in a single window. I can do that no problem with the following code:</p> <pre><code>def create_figure_one(self): plt.figure(1) plt.subplot(311) plt.plot_date(self.dates, self.PREC, '-', color='b') plt.title('Precipitation', fontsize=20) plt.y...
0
2016-07-28T21:43:18Z
38,647,585
<p>I am not a smart man... I had "self.title" in my second figure where I should of have "plt.title". That fixed it.</p>
1
2016-07-28T22:12:13Z
[ "python", "numpy", "matplotlib" ]
Comparing number cast to string in str list
38,647,232
<p>I have a list of string numbers and a counter inside a for loop. If the counter is in the list I do something, like this:</p> <pre><code>codes = ['123','1245','564','8920','57498'] f = open('path_to_file','r') for lineno, line in enumerate(f, start=1): if str(lineno) in codes: print str(lineno) + ' is i...
-3
2016-07-28T21:43:51Z
38,650,420
<p>I code bellow:</p> <pre><code>In [8]: codes = ['1', '3', '4'] In [9]: f = open("test.py", "r") In [10]: for lineno, line in enumerate(f, start=1): ....: if str(lineno) in codes: ....: print str(lineno) + ' is in the list' ....: 1 is in the list 3 is in the list 4 is in the list </code></pre> ...
0
2016-07-29T04:15:50Z
[ "python", "python-2.7", "python-2.x" ]
Does flask_json extension support top-level array JSON responses?
38,647,237
<p>I've been using flask_json's as_json decorators in my Flask API for a project. This has worked fine for json responses that are dicts/hashes at the top-level (<code>{name: ... }</code>) but I'd like to do a JSON response that is a list/array at the top-level:</p> <pre><code>[ { "created_at": "02/07/2016 00:01...
1
2016-07-28T21:44:16Z
38,647,542
<p>Prior to 0.11, Flask's <code>jsonify</code> function only accepted dicts at the top level. This was due to a security issue with very old versions of Internet Explorer that was open to attacks by overriding the <code>Array</code> prototype.</p> <p>As of Flask 0.11, <code>jsonify</code> accepts any valid JSON value...
1
2016-07-28T22:08:35Z
[ "python", "json", "flask" ]
Python - Determining when subprocess has completed with parent process Tkinter GUI still interactable
38,647,245
<p>I have a Tkinter GUI that I want to spawn a subprocess and find out when the subprocess ends without waiting for the subprocess to terminate, which means that my GUI is still completely interactable / isn't frozen.</p> <p>I have tried many methods such as the ones found in the following (mostly stackoverflow) links...
0
2016-07-28T21:44:52Z
38,651,474
<p>On Linux you are signaled the death of a child process. Catch that signal in a Signal handler.</p> <p>If you need cross-platform code (including Windows) you should create a new thread that communicates with <code>self.process</code>.</p>
0
2016-07-29T05:58:23Z
[ "python", "multithreading", "tkinter", "subprocess", "python-3.5" ]
csv file compression without using existing libraries in Python
38,647,250
<p>I'm trying to compress a .csv file without using any 3rd party or framework provided compression libraries.</p> <p>I have tried, what I wish to think, everything. I looked at Huffman, but since I'm not allowed to use that solution I tried to do my own.</p> <p>An example:</p> <pre><code>6NH8,F,A,0,60541567,6054156...
0
2016-07-28T21:45:00Z
38,647,885
<p>Try running your algorithm on the contents of each cell instead of individual characters and then creating a new CSV file with the compressed cell values.</p> <p>If the data you have provided is an example of the larger file you may want to run the compression algorithm on each column separately. For example it may...
0
2016-07-28T22:40:31Z
[ "python", "csv", "compression", "decompression" ]
csv file compression without using existing libraries in Python
38,647,250
<p>I'm trying to compress a .csv file without using any 3rd party or framework provided compression libraries.</p> <p>I have tried, what I wish to think, everything. I looked at Huffman, but since I'm not allowed to use that solution I tried to do my own.</p> <p>An example:</p> <pre><code>6NH8,F,A,0,60541567,6054156...
0
2016-07-28T21:45:00Z
38,649,366
<p>For each line, search for matching substrings in the previous line or lines. For each matching substring (e.g. <code>6NH8,F,A,0,6054156</code> or <code>,78.78,2</code>), send the length of the match and distance back to copy from instead. This is called LZ77 compression.</p>
0
2016-07-29T01:59:01Z
[ "python", "csv", "compression", "decompression" ]
csv file compression without using existing libraries in Python
38,647,250
<p>I'm trying to compress a .csv file without using any 3rd party or framework provided compression libraries.</p> <p>I have tried, what I wish to think, everything. I looked at Huffman, but since I'm not allowed to use that solution I tried to do my own.</p> <p>An example:</p> <pre><code>6NH8,F,A,0,60541567,6054156...
0
2016-07-28T21:45:00Z
38,662,750
<p>It is unclear whether you need to create a generic compression algorithm or a custom one that works reasonably well for this kind of data.</p> <p>It is also unclear whether the output should be another CSV, a string made of printable ASCII characters or plain binary data.</p> <p>I'm going to assume that we're talk...
0
2016-07-29T15:44:41Z
[ "python", "csv", "compression", "decompression" ]
pyqt4 already has a layout. How to 'detect' it or change?
38,647,300
<p>I'm trying to set a layout manager. But getting the message:</p> <pre><code>QLayout: Attempting to add QLayout "" to Window "", which already has a layout </code></pre> <p>How can I change or detect which type the layout is? I'd like to use the boxlayout as it seems to be prefered.</p> <pre><code>import sys from ...
0
2016-07-28T21:48:23Z
38,648,159
<p>The <a href="http://doc.qt.io/qt-4.8/qmainwindow.html#qt-main-window-framework" rel="nofollow">QMainWindow</a> class has built-in support for toolbars and dock-widgets, and a menubar and statusbar - so it has to have a fixed layout. Therefore, rather than adding child widgets to the main window itself, you must set ...
2
2016-07-28T23:09:09Z
[ "python", "pyqt" ]
BLOSUM62 (or 45) Scoring in JavaScript
38,647,306
<p>I'm working with multiple sequence alignments while interfacing with several web-based APIs, so I have been doing most of my lightweight analysis in JavaScript. I'm currently trying to figure out how to calculate a BLOSUM62 score in JavaScript. There are lots of Python functions, like the following from Github:</p...
0
2016-07-28T21:49:03Z
38,648,570
<p>This is not a full answer, but I made the blossum62 matrix into something javascript friendly so that hopefully you can write the scoring yourself (I don't understand how the scoring is done in the example code above)</p> <pre><code>var blossum62 = {'*': {'*': 1, 'A': -4, 'C': -4, 'B': -4, 'E': -4, 'D': -4, 'G': -4...
2
2016-07-29T00:04:50Z
[ "javascript", "python", "alignment", "bioinformatics" ]
Using global variable in multiple python files
38,647,344
<p>I have a main file and hundreds of sub files which are imported into the main file.Also, i have a global dictionary defined in main.py file.</p> <pre><code># ../myproject/main.py import sub1.py import sub2.py global dict_test={} dict_test["fruit"]="apple" </code></pre> <p>How can i get to use this dict_test dict...
0
2016-07-28T21:51:42Z
38,647,454
<p>You cannot do it directly, as it will result in a circular input where <code>main</code> imports <code>sub1</code> and <code>sub1</code> imports the dict from <code>main</code>.</p> <p>The way forward is to break the dependency by introducing a third module containing shared resources.</p> <pre><code>`constanst.py...
0
2016-07-28T22:00:52Z
[ "python" ]
Tensorflow: Convert Tensor to numpy array WITHOUT .eval() or sess.run()
38,647,353
<p>How can you convert a tensor into a Numpy ndarray, without using eval or sess.run()?</p> <p>I need to pass a tensor into a feed dictionary and I already have a session running.</p>
2
2016-07-28T21:52:55Z
38,660,000
<p>The fact that you say "already have a session running" implies a misunderstanding of what sess.run() actually does.</p> <p>If you have a tf.Session() initiated, you should be able to use it to retrieve any tensor using sess.run(). If you need to retrieve a variable or constant tensor this is very straight forward.<...
1
2016-07-29T13:20:57Z
[ "python", "numpy", "tensorflow" ]
Python Regex, fix number spacing
38,647,357
<p>I have some paragraphs with malformed text. I need to replace spaces between numbers. For example:</p> <pre><code>6. 7 should be 6.7 </code></pre> <p>I have tried the following expression to get at the offending space but it selects <code>6.</code>:</p> <pre><code>(?:\d\.)\s(?=\d+) </code></pre> <p>Any pointers ...
1
2016-07-28T21:53:05Z
38,647,383
<p>You can either use a lookbehind:</p> <pre><code>(?&lt;=\d\.)\s+(?=\d+) ^^^ </code></pre> <p>See the <a href="https://regex101.com/r/qA5cP4/1" rel="nofollow">regex demo here</a>. Or, use a capturing group but replace with a <code>\1</code> backreference later:</p> <pre><code>(\d\.)\s+(?=\d+) </code></pre> <p>See...
1
2016-07-28T21:55:38Z
[ "python", "regex" ]
Python Regex, fix number spacing
38,647,357
<p>I have some paragraphs with malformed text. I need to replace spaces between numbers. For example:</p> <pre><code>6. 7 should be 6.7 </code></pre> <p>I have tried the following expression to get at the offending space but it selects <code>6.</code>:</p> <pre><code>(?:\d\.)\s(?=\d+) </code></pre> <p>Any pointers ...
1
2016-07-28T21:53:05Z
38,647,401
<pre><code>&gt;&gt;&gt; re.sub(r'(\d+\.)\s+(\d+)',r'\1\2','62. 7; 8.5; 6. 912') '62.7; 8.5; 6.912' </code></pre>
2
2016-07-28T21:57:01Z
[ "python", "regex" ]
Table legend with header in matplotlib
38,647,370
<p>I would like to make a complex legend in matplotlib. I made the following code</p> <pre><code>import matplotlib.pylab as plt import numpy as np N = 25 y = np.random.randn(N) x = np.arange(N) y2 = np.random.randn(25) # serie A p1a, = plt.plot(x, y, "ro", ms=10, mfc="r", mew=2, mec="r") p1b, = plt.plot(x[:5]...
8
2016-07-28T21:54:39Z
38,680,964
<p>It seems there is no standard approach for this rather than some few tricks available over here.</p> <p>It is worth mentioning that you should check the size bbox factor that fits you the most.</p> <p>The best I could find so far, an perhaps can lead you to a better solution:</p> <pre><code>N = 25 y = np.random.r...
2
2016-07-31T05:11:03Z
[ "python", "matplotlib", "legend" ]
Table legend with header in matplotlib
38,647,370
<p>I would like to make a complex legend in matplotlib. I made the following code</p> <pre><code>import matplotlib.pylab as plt import numpy as np N = 25 y = np.random.randn(N) x = np.arange(N) y2 = np.random.randn(25) # serie A p1a, = plt.plot(x, y, "ro", ms=10, mfc="r", mew=2, mec="r") p1b, = plt.plot(x[:5]...
8
2016-07-28T21:54:39Z
38,815,854
<p>Is this solution close enough to your liking? It is slighty inspired by Ricardo's answer, but I only used one legend-object for each column, and then utilised the <code>title</code>-keyword to set the title of each individual column. To put the markers in the center of each column I used <code>handletextpad</code>...
1
2016-08-07T15:50:26Z
[ "python", "matplotlib", "legend" ]
Convert CharField to Choice Field (PositiveSmallIntegerField) in Django
38,647,440
<p>My current model is set up as follows:</p> <pre><code>Class MyClass(models.Model): my_field = models.CharField(max_length=100,...) </code></pre> <p>All of the values are either, for sake of argument, <code>"foo"</code> or <code>"bar"</code>.</p> <p>I want to convert this to be a PositiveSmallIntegerField inst...
3
2016-07-28T22:00:11Z
38,649,210
<p>There are no Django model ChoiceField? </p> <p>I think you can add ‘choices’ to your CharField without losing any data. See <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices</a></p> <p>However if you want t...
1
2016-07-29T01:38:00Z
[ "python", "django" ]
Why does Pygame Movie Rewind Only on Event Input
38,647,525
<p>I'm working on a small script in Python 2.7.9 and Pygame that would be a small display for our IT department. The idea is that there are several toggle switches that indicate our current status (in, out, etc) , some information about our program at the school, and play a short video that repeats with images of the ...
1
2016-07-28T22:07:22Z
38,648,663
<p>You need to take the code for replaying the movie out of the for loop that gets current events. Do this for that code and any other code you want to happen continuously without waiting for an event by moving the code 4 spaces to the left.</p> <p>Like so:</p> <pre><code>while not done: for event in pygame.event...
0
2016-07-29T00:17:58Z
[ "python", "pygame" ]
Output is not what I think it should be
38,647,526
<p>This is my first question on the site, I highly appreciate any feedback. The book I'm working on by Guttag from MIT says that the program would print the following:</p> <pre><code>x=4 z=4 x = abc x=4 x=3 z = &lt;function g at 0x15b43b0&gt; x = abc </code></pre> <p>My question is, why does the first x displayed ha...
1
2016-07-28T22:07:25Z
38,647,715
<p>Here is my explanation:</p> <ol> <li>x is set to 3</li> <li>f is called with the input x = 3</li> <li>Then, <code>x=x+1</code> sets x (the local variable) to 4.</li> <li>The first print prints x=4</li> </ol> <p>To answer your concerns:</p> <ol> <li>x <strong>is</strong> a local variable to f, because f takes x as...
0
2016-07-28T22:23:36Z
[ "python" ]
How can i work with separate elements in a list of objects?
38,647,562
<p>So, i have a huge list of objects which contains: Level Of Difficulty, Math Expression, Result. I'm trying to build a game and want to print the expression and check the result, but i don't know how to print a separate element. What my list looks like: 3, s, 520 + 370, 890 I want to print only the expression: Someth...
0
2016-07-28T22:10:04Z
38,647,776
<p>Given the list <code>expressoes</code>, you can get the attributes of the contained class instances using <code>map</code> or a <em>list comprehension</em>:</p> <pre><code>list_of_nivels = map(lambda x: x.nivel, expressoes) </code></pre> <p>In Python 3.x, you'll need to call <code>list</code> on <code>map</code> t...
0
2016-07-28T22:30:04Z
[ "python", "list", "object" ]
Concatenating files with matching string in middle of filename
38,647,567
<p>My goal is to concatenate files in a folder based on a string in the middle of the filename, ideally using python or bash. To simplify the question, here is an example: </p> <ul> <li>P16C-X128-22MB-LL_merged_trimmed.fastq </li> <li>P16C-X128-27MB-LR_merged_trimmed.fastq </li> <li>P16C-X1324-14DL-UL_merged_trimme...
-1
2016-07-28T22:10:23Z
38,648,153
<p>You can use <code>open</code> to read and write (create) files, <code>os.listdir</code> to get all files (and directories) in a certain directory and <code>re</code> to match file name as needed.</p> <p>Use a dictionary to store contents by filename prefix (the file's name up until 3rd hyphen <code>-</code>) and co...
0
2016-07-28T23:07:43Z
[ "python", "python-2.7" ]
Concatenating files with matching string in middle of filename
38,647,567
<p>My goal is to concatenate files in a folder based on a string in the middle of the filename, ideally using python or bash. To simplify the question, here is an example: </p> <ul> <li>P16C-X128-22MB-LL_merged_trimmed.fastq </li> <li>P16C-X128-27MB-LR_merged_trimmed.fastq </li> <li>P16C-X1324-14DL-UL_merged_trimme...
-1
2016-07-28T22:10:23Z
38,665,686
<p>For simple string manipulations, I prefer to avoid the use of regular expressions. I think that <code>str.split()</code> is enough in this case. Besides, for simple file name matching, the library <code>fnmatch</code> provides enough functionality. </p> <pre><code>import fnmatch import os from itertools import grou...
0
2016-07-29T18:49:08Z
[ "python", "python-2.7" ]
How to create a proxy that can decode SSL traffic?
38,647,601
<p>I was writing a proxy that can capture the requests made in my selenium tests. In selenium I used this </p> <pre><code>host = '10.203.9.156' profile = webdriver.FirefoxProfile() myProxy = "localhost:8899" proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy': myProxy, 'ftpProxy': myProxy, 'sslProxy': myProxy...
1
2016-07-28T22:14:16Z
38,647,840
<p><strong>BoilerPlate</strong></p> <p>SSL is a protocol providing an end-to-end encrypted communication between two parties each having one of the keys in private/public key pair. Typically a browser and a web server.</p> <p>In normal circumstances any device between the two endpoints cannot decrypt the communicatio...
2
2016-07-28T22:37:05Z
[ "python", "selenium", "ssl", "encryption", "proxy" ]
Error in reading html to data frame in Python "'module' object has no attribute '_base'"
38,647,716
<p>I encounter this error when trying to read a table from url (link <a href="http://www.checkee.info/main.php?dispdate=" rel="nofollow">here</a>). </p> <p>Here is the code:</p> <pre><code>import pandas as pd link = "http://www.checkee.info/main.php?dispdate=" c=pd.read_html(link) </code></pre> <p>The error returned...
0
2016-07-28T22:23:36Z
38,651,437
<p>Not sure why you're running into that problem, but I would try using BeautifulSoup to select the table you're interested in, and pass that to <code>read_html()</code> as a string. For example:</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup url = "http://www.checkee.info/main.php?d...
0
2016-07-29T05:55:01Z
[ "python", "pandas", "dataframe" ]
Error in reading html to data frame in Python "'module' object has no attribute '_base'"
38,647,716
<p>I encounter this error when trying to read a table from url (link <a href="http://www.checkee.info/main.php?dispdate=" rel="nofollow">here</a>). </p> <p>Here is the code:</p> <pre><code>import pandas as pd link = "http://www.checkee.info/main.php?dispdate=" c=pd.read_html(link) </code></pre> <p>The error returned...
0
2016-07-28T22:23:36Z
38,755,203
<p>I've just had the same problem, and came across a solution <a href="https://github.com/coursera-dl/coursera-dl/issues/554" rel="nofollow">on this page on github</a>. For completeness, the comment/answer there was:</p> <p>This is an issue with upstream package html5lib ... To fix, force downgrade to an older version...
2
2016-08-03T23:27:36Z
[ "python", "pandas", "dataframe" ]
Django REST Framework ManyToMany Field Error
38,647,833
<p>I am working with an existing database and wish to create a ManyToMany relationship between two tables. The abbreviated code is:</p> <pre><code>class AddressSummary(models.Model): class Meta: managed = False db_table = 'addresses' app_label = 'myapp' address_id = models.IntegerFiel...
0
2016-07-28T22:36:39Z
38,648,913
<p>You should show us how your serializer looks like.</p> <p>Missing informations make answerers to guess harder what's going on, and your chance of getting answer goes down..</p> <p>With the limited info,</p> <blockquote> <p>Cannot resolve keyword 'addresssummary' into field. Choices are: family_name, id, parti...
0
2016-07-29T00:53:10Z
[ "python", "django-rest-framework", "manytomanyfield" ]
Is there a way to make buffer() writable without copying when the size argument is set?
38,647,848
<p>If an object is mutable then it’s possible to get a modifiable buffer by not the specifying the second argument of <code>buffer()</code> <em>(which is a built‑in function)</em> like this :</p> <pre><code>&gt;&gt;&gt; s = bytearray(1000000) # a million zeroed bytes &gt;&gt;&gt; t = buffer(s, 1) # slic...
-1
2016-07-28T22:37:38Z
38,647,884
<p>The copy is necessary. The bytearray's internal buffer simply isn't 2 GiB long; if you want a 2 GiB buffer, you will need to copy the bytearray's data into a new buffer.</p> <p>If you were to somehow force Python to treat the buffer as the size you want it to be without making a copy, writing to it would corrupt yo...
0
2016-07-28T22:40:30Z
[ "python", "linux", "security", "python-2.x", "32-bit" ]
Ansible - grab a key from a dictionary (but not in a loop)
38,647,864
<p>Another question regarding dictionaries in Ansible!</p> <p>For convenience, I have certain values for mysql databases held in dictionaries, which works fine to loop over using <code>with_dict</code> to create the DBs and DB users.</p> <pre><code>mysql_dbs: db1: user: db1user pass: "jdhfksjdf" accessi...
0
2016-07-28T22:38:54Z
38,649,020
<p>Given a nested dictionary...</p> <pre><code>mysql_dbs: db1: user: db1user pass: "jdhfksjdf" accessible_from: localhost db2: user: db2user pass: "npoaivrpon" accessible_from: localhost </code></pre> <p>You can either use dotted notation:</p> <pre><code>- debug: var: mysql_dbs.db1 </...
1
2016-07-29T01:08:46Z
[ "python", "yaml", "ansible", "ansible-playbook" ]
How to deliver custom HTML on a bottle 404 Handler?
38,647,874
<p>I'm trying to use the jinja2_view plugin to render a template from a custom error handler like this:</p> <pre><code>from bottle import Bottle, abort, jinja2_view app = Bottle() @jinja2_view('index.html') @app.get('/') def index(): abort(404) @jinja_view('404.html') @app.error(404) def handle404(error): r...
0
2016-07-28T22:39:30Z
38,647,875
<p>You can always instantiate your own Jinja Environment like this:</p> <pre><code>from bottle import Bottle, abort, jinja2_view from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('yourapplication', 'templates')) app = Bottle() @jinja2_view('index.html') @app.get('/') def index(): ...
0
2016-07-28T22:39:30Z
[ "python", "error-handling", "http-status-code-404", "jinja2", "bottle" ]
How to deliver custom HTML on a bottle 404 Handler?
38,647,874
<p>I'm trying to use the jinja2_view plugin to render a template from a custom error handler like this:</p> <pre><code>from bottle import Bottle, abort, jinja2_view app = Bottle() @jinja2_view('index.html') @app.get('/') def index(): abort(404) @jinja_view('404.html') @app.error(404) def handle404(error): r...
0
2016-07-28T22:39:30Z
38,977,635
<p>Decorators are applied in reverse order. In your code example, you apply the view decorators <em>after</em> the route decorators, meaning that the undecorated handler functions are bound to the app and no templates are rendered. Your get-route won't work either. Simply switch the order of the decorators:</p> <pre c...
0
2016-08-16T14:30:56Z
[ "python", "error-handling", "http-status-code-404", "jinja2", "bottle" ]
Python error: Cannot import name KafkaConsumer
38,647,922
<p>I installed the kafka-python package for Python. I have a kafka producer and consumer running. I want the python code to read the kafka topic and print out the messages. </p> <p>My python code is below:</p> <pre><code>import sys from kafka import KafkaConsumer def kafkatest(): print "Step 1 complete" cons...
2
2016-07-28T22:44:35Z
38,648,350
<p>You have named your file <code>kafka.py</code>. Now when you run it, python encounters the following statement inside it:</p> <pre><code>from kafka import KafkaConsumer </code></pre> <p>So it must find a module called <code>kafka</code>. How does it known where to look? Well it looks in the directories on <code...
1
2016-07-28T23:34:28Z
[ "python", "apache-kafka" ]