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
listlengths
1
5
php exec function doesn't work correct
38,523,675
<p>I'm using Python beside Laravel on my PC , I Have Installed Python . when I try to run a python code which is in a file via command line ( Windows ) , there is no problem , but when I attempt to run that file via :<br></p> <pre><code>exec("python ".__DIR__.'\new.py'); </code></pre> <p>from my routes.php document , it returns 1<br> here is my document tree :</p> <pre><code> C:. │ Kernel.php │ new.py │ routes.php │&lt;br&gt; ├───Controllers │ │ clientController.php │ │ Controller.php │ │ HomeController.php │ │ requestHandler.php │ │ │ └───Auth │ AuthController.php │ PasswordController.php │ ├───Middleware │ Authenticate.php │ EncryptCookies.php │ RedirectIfAuthenticated.php │ VerifyCsrfToken.php │ └───Requests Request.php </code></pre> <p>in addition this is .py file :</p> <pre><code>print("Hello World") </code></pre>
0
2016-07-22T10:05:42Z
38,523,845
<p>It look like the <code>__DIR__</code> constant doesn't add the final slash. Try using something like this:</p> <pre><code>exec("python ".__DIR__.DIRECTORY_SEPARATOR."new.py"); </code></pre> <p>(Sorry for my english!)</p>
0
2016-07-22T10:13:53Z
[ "php", "python", "laravel", "laravel-5", "exec" ]
Trying to get ironpython to create a text file that I can store info in
38,523,771
<p>I'm writing a gui for ironpython and I'm trying create a text file that the user can name in a textbox. The textfile is being used to give me a python script from a vector file. Any suggestions</p>
0
2016-07-22T10:10:03Z
38,528,335
<p>With the following I was able to create a file with IronPython</p> <pre><code>ScriptEngine m_engine = Python.CreateEngine(); ScriptScope m_scope = m_engine.CreateScope(); String code = @"file = open('myfile.txt', 'w+')"; ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement); source.Execute(m_scope); </code></pre> <p>Here's the <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow">Python documentation</a> about the <code>w+</code>. It opens the file for writing, truncating the file first.</p> <p>So I guess you just need to insert the name of the file in the script...</p>
0
2016-07-22T13:57:55Z
[ "c#", "python", "visual-studio-2013", "ironpython" ]
Trying to get ironpython to create a text file that I can store info in
38,523,771
<p>I'm writing a gui for ironpython and I'm trying create a text file that the user can name in a textbox. The textfile is being used to give me a python script from a vector file. Any suggestions</p>
0
2016-07-22T10:10:03Z
38,566,514
<p>I am putting up the code that worked for me when I was writing in python. Hope it helps.</p> <pre><code>def on_save_as(self, sender, e): dlg = SaveFileDialog() dlg.Filter = "Text File (*.txt)|*.txt" dlg.Title = "SaveFile" if dlg.ShowDialog(): self.save_file(dlg.FileName) def save_file(self, filename): sw = StreamWriter(filename) try: buf = self.textbox.Text sw.Write(buf) self.statusbar_item.Content = Path.GetFileName(filename) self.openfile = filename except Exception, ex: MessageBox.Show(ex.Message) finally: sw.Close() </code></pre>
0
2016-07-25T11:26:31Z
[ "c#", "python", "visual-studio-2013", "ironpython" ]
Variable shift in Pandas
38,523,920
<p>having two columns A and B in a dataframe: </p> <pre><code> A B 0 1 6 1 2 7 2 1 8 3 2 9 4 1 10 </code></pre> <p>I would like to create a column C. C must have values of B shifted by value of A:</p> <pre><code> A B C 0 1 6 NaN 1 2 7 NaN 2 1 8 7 3 2 9 7 4 1 10 9 </code></pre> <p>The command:</p> <pre><code>df['C'] = df['B'].shift(df['A']) </code></pre> <p>does not work. Do you have any other ideas?</p>
2
2016-07-22T10:17:50Z
38,524,134
<p>This is tricky due to index alignment, you can define a user func and <code>apply</code> row-wise on your df, here the function will perform a shift on the B column and return the index value (using <code>.name</code> attribute to return the index) of the shifted column:</p> <pre><code>In [134]: def func(x): return df['B'].shift(x['A'])[x.name] df['C'] = df.apply(lambda x: func(x), axis=1) df Out[134]: A B C 0 1 6 NaN 1 2 7 NaN 2 1 8 7.0 3 2 9 7.0 4 1 10 9.0 </code></pre>
0
2016-07-22T10:27:45Z
[ "python", "pandas", "shift" ]
Change Cython's naming rules for .so files
38,523,941
<p>I'm using Cython to generate a shared object out of Python module. The compilation output is written to <code>build/lib.linux-x86_64-3.5/&lt;Package&gt;/&lt;module&gt;.cpython-35m-x86_64-linux-gnu.so</code>. Is there any option to change the naming rule? I want the file to be named <code>&lt;module&gt;.so</code> without the interpreter version or arch appendix.</p>
1
2016-07-22T10:18:51Z
38,525,461
<p>Seems like <code>setuptools</code> provides no option to change or get rid of the suffix completely. The magic happens in <code>distutils/command/build_ext.py</code>: </p> <pre><code>def get_ext_filename(self, ext_name): from distutils.sysconfig import get_config_var ext_path = ext_name.split('.') ext_suffix = get_config_var('EXT_SUFFIX') return os.path.join(*ext_path) + ext_suffix </code></pre> <p>Seems like I will need to add a post-build renaming action.</p> <hr> <p><strong>Update from 08/12/2016:</strong></p> <p>Ok, I forgot to actually post the solution. Actually, I implemented a renaming action by overloading the built-in <code>install_lib</code> command. Here's the logic:</p> <pre class="lang-py prettyprint-override"><code>from distutils.command.install_lib import install_lib as _install_lib def batch_rename(src, dst, src_dir_fd=None, dst_dir_fd=None): '''Same as os.rename, but returns the renaming result.''' os.rename(src, dst, src_dir_fd=src_dir_fd, dst_dir_fd=dst_dir_fd) return dst class _CommandInstallCythonized(_install_lib): def __init__(self, *args, **kwargs): _install_lib.__init__(self, *args, **kwargs) def install(self): # let the distutils' install_lib do the hard work outfiles = _install_lib.install(self) # batch rename the outfiles: # for each file, match string between # second last and last dot and trim it matcher = re.compile('\.([^.]+)\.so$') return [batch_rename(file, re.sub(matcher, '.so', file)) for file in outfiles] </code></pre> <p>Now all you have to do is to overload the command in the <code>setup</code> function:</p> <pre class="lang-py prettyprint-override"><code>setup( ... cmdclass={ 'install_lib': _CommandInstallCythonized, }, ... ) </code></pre> <p>Still, I'm not happy with overloading standard commands; if you find a better solution, post it and I will accept your answer.</p>
1
2016-07-22T11:35:47Z
[ "python", "cython" ]
Python Pandas, create empty DataFrame specifying column dtypes
38,523,965
<p>There is one thing that I find myself having to do quite often, and it surprises me how difficult it is to achieve this in Pandas. Suppose I need to create an empty <code>DataFrame</code> with specified index type and name, and column types and names. (I might want to fill it later, in a loop for example.) The easiest way to do this, that I have found, is to create an empty <code>pandas.Series</code> object for each column, specifying their <code>dtype</code>s, put them into a dictionary which specifies their names, and pass the dictionary into the <code>DataFrame</code> constructor. Something like the following.</p> <pre><code>def create_empty_dataframe(): index = pandas.Index([], name="id", dtype=int) column_names = ["name", "score", "height", "weight"] series = [pandas.Series(dtype=str), pandas.Series(dtype=int), pandas.Series(dtype=float), pandas.Series(dtype=float)] columns = dict(zip(column_names, series)) return pandas.DataFrame(columns, index=index, columns=column_names) # The columns=column_names is required because the dictionary will in general put the columns in arbitrary order. </code></pre> <p>First question. Is the above really the simplest way of doing this? There are so many things that are convoluted about this. What I really want to do, and what I'm pretty sure a lot of people really want to do, is something like the following.</p> <pre><code>df = pandas.DataFrame(columns=["id", "name", "score", "height", "weight"], dtypes=[int, str, int, float, float], index_column="id") </code></pre> <p>Second question. Is this sort of syntax at all possible in Pandas? If not, are the devs considering supporting something like this at all? It feels to me that it really ought to be as simple as this (the above syntax).</p>
1
2016-07-22T10:19:52Z
38,524,255
<p>Unfortunately the <code>DateFrame</code> ctor accepts a single <code>dtype</code> descriptor, however you can cheat a little by using <code>read_csv</code>:</p> <pre><code>In [143]: import pandas as pd import io cols=["id", "name", "score", "height", "weight"] df = pd.read_csv(io.StringIO(""), names=cols, dtype=dict(zip(cols,[int, str, int, float, float])), index_col=['id']) df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 0 entries Data columns (total 4 columns): name 0 non-null object score 0 non-null int32 height 0 non-null float64 weight 0 non-null float64 dtypes: float64(2), int32(1), object(1) memory usage: 0.0+ bytes </code></pre> <p>So you can see that the dtypes are as desired and that the index is set as desired:</p> <pre><code>In [145]: df.index Out[145]: Int64Index([], dtype='int64', name='id') </code></pre>
2
2016-07-22T10:33:41Z
[ "python", "pandas", "dataframe" ]
Python Pandas, create empty DataFrame specifying column dtypes
38,523,965
<p>There is one thing that I find myself having to do quite often, and it surprises me how difficult it is to achieve this in Pandas. Suppose I need to create an empty <code>DataFrame</code> with specified index type and name, and column types and names. (I might want to fill it later, in a loop for example.) The easiest way to do this, that I have found, is to create an empty <code>pandas.Series</code> object for each column, specifying their <code>dtype</code>s, put them into a dictionary which specifies their names, and pass the dictionary into the <code>DataFrame</code> constructor. Something like the following.</p> <pre><code>def create_empty_dataframe(): index = pandas.Index([], name="id", dtype=int) column_names = ["name", "score", "height", "weight"] series = [pandas.Series(dtype=str), pandas.Series(dtype=int), pandas.Series(dtype=float), pandas.Series(dtype=float)] columns = dict(zip(column_names, series)) return pandas.DataFrame(columns, index=index, columns=column_names) # The columns=column_names is required because the dictionary will in general put the columns in arbitrary order. </code></pre> <p>First question. Is the above really the simplest way of doing this? There are so many things that are convoluted about this. What I really want to do, and what I'm pretty sure a lot of people really want to do, is something like the following.</p> <pre><code>df = pandas.DataFrame(columns=["id", "name", "score", "height", "weight"], dtypes=[int, str, int, float, float], index_column="id") </code></pre> <p>Second question. Is this sort of syntax at all possible in Pandas? If not, are the devs considering supporting something like this at all? It feels to me that it really ought to be as simple as this (the above syntax).</p>
1
2016-07-22T10:19:52Z
39,509,517
<p>You can set the dtype of a DataFrame's column also by replacing it:</p> <pre><code>df['column_name'] = df['column_name'].astype(float) </code></pre>
0
2016-09-15T11:05:44Z
[ "python", "pandas", "dataframe" ]
Python Pandas, create empty DataFrame specifying column dtypes
38,523,965
<p>There is one thing that I find myself having to do quite often, and it surprises me how difficult it is to achieve this in Pandas. Suppose I need to create an empty <code>DataFrame</code> with specified index type and name, and column types and names. (I might want to fill it later, in a loop for example.) The easiest way to do this, that I have found, is to create an empty <code>pandas.Series</code> object for each column, specifying their <code>dtype</code>s, put them into a dictionary which specifies their names, and pass the dictionary into the <code>DataFrame</code> constructor. Something like the following.</p> <pre><code>def create_empty_dataframe(): index = pandas.Index([], name="id", dtype=int) column_names = ["name", "score", "height", "weight"] series = [pandas.Series(dtype=str), pandas.Series(dtype=int), pandas.Series(dtype=float), pandas.Series(dtype=float)] columns = dict(zip(column_names, series)) return pandas.DataFrame(columns, index=index, columns=column_names) # The columns=column_names is required because the dictionary will in general put the columns in arbitrary order. </code></pre> <p>First question. Is the above really the simplest way of doing this? There are so many things that are convoluted about this. What I really want to do, and what I'm pretty sure a lot of people really want to do, is something like the following.</p> <pre><code>df = pandas.DataFrame(columns=["id", "name", "score", "height", "weight"], dtypes=[int, str, int, float, float], index_column="id") </code></pre> <p>Second question. Is this sort of syntax at all possible in Pandas? If not, are the devs considering supporting something like this at all? It feels to me that it really ought to be as simple as this (the above syntax).</p>
1
2016-07-22T10:19:52Z
39,510,423
<p>You simplify things a little by using a list comprehension</p> <pre><code>def create_empty_dataframe(): index = pandas.Index([], name="id", dtype=int) # specify column name and data type columns = [('name', str), ('score', int), ('height', float), ('weight', float)] # create the dataframe from a dict return pandas.DataFrame({k: pandas.Series(dtype=t) for k, t in columns}) </code></pre> <p>This isn't drastically different in effect to what you've already done, but it should be easier to make an arbitrary dataframe without having to modify multiple locations in the code.</p>
0
2016-09-15T11:55:53Z
[ "python", "pandas", "dataframe" ]
switching rows and columns in dataframe
38,524,060
<p>I have a dataframe that looks like the following:</p> <pre><code>import pandas as pd datelisttemp = pd.date_range('1/1/2014', periods=3, freq='D') s = list(datelisttemp)*3 s.sort() df = pd.DataFrame({'day':s,'stats':['mean','var','std','mean','var','std','mean','var','std'], 's1':[21 ,25 ,27 ,42 ,4 ,74 ,63 ,67, 6],'s2':[34 ,32 ,3, 53 ,75 ,5, 32, 75, 7], 's3':[8 ,82 ,8, 12 ,43 ,12, 99, 99, 95]}) </code></pre> <p>I would like to get a dataframe like this:</p> <pre><code>df = pd.DataFrame({'sensors': ['s1','s2','s3','s1','s2','s3','s1','s2','s3'],'day':s,'mean':[21,34,8,42,53,12, 63,32,99],'var':[25,32,82,4,75,43,67,75,99],'std':[27,3,8,74,5,12,74,5,12]}) </code></pre> <p>Basically, I need the dataframe to have sensors in rows and stats in columns. Can please someone help me?</p>
3
2016-07-22T10:24:11Z
38,524,543
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>. Last <code>reset_index</code>, rename columns and remove column names by <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p> <pre><code>print (df.pivot_table(index='day', columns='stats') .stack(0) .reset_index() .rename(columns={'level_1':'sensors'}) .rename_axis(None, axis=1)) day sensors mean std var 0 2014-01-01 s1 21 27 25 1 2014-01-01 s2 34 3 32 2 2014-01-01 s3 8 8 82 3 2014-01-02 s1 42 74 4 4 2014-01-02 s2 53 5 75 5 2014-01-02 s3 12 12 43 6 2014-01-03 s1 63 6 67 7 2014-01-03 s2 32 7 75 8 2014-01-03 s3 99 95 99 </code></pre>
2
2016-07-22T10:47:51Z
[ "python", "pandas", "dataframe" ]
Parse User name for extracting user location Twitter
38,524,071
<p>I am trying to scrape user location with respect to user names from twitter. </p> <p>Input: The user list has more than 50K User names </p> <pre><code>AkkiPritam,6.77E+17,12/15/2015,#chennaifloods AkkiPritam,6.77E+17,12/15/2015,#bhoomikatrust AkkiPritam,6.77E+17,12/15/2015,#akshaykumar gischethans,6.77E+17,12/15/2015,#chennaifloods mid_day,6.77E+17,12/15/2015,#bollywood mid_day,6.77E+17,12/15/2015,#chennaifloods Nanthivarman16,6.77E+17,12/15/2015,#admkfails Nanthivarman16,6.77E+17,12/15/2015,#jayafails Nanthivarman16,6.77E+17,12/15/2015,#stickergovt Nanthivarman16,6.77E+17,12/15/2015,#chennaifloods AdilaMatra,6.77E+17,12/15/2015,#chennaifloods AdilaMatra,6.77E+17,12/15/2015,#climatechange AdilaMatra,6.77E+17,12/15/2015,#delhichokes AdilaMatra,6.77E+17,12/15/2015,#smog HDFCERGOGIC,6.77E+17,12/15/2015,#chennaifloods HDFCERGOGIC,6.77E+17,12/15/2015,#tnfloods ImSoorej,6.77E+17,12/15/2015,#chennaifloods ImSoorej,6.77E+17,12/15/2015,#chennaimicr </code></pre> <p>Code: I want to find geo location possibly geo coordinates. </p> <pre><code>from __future__ import print_function import tweepy from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener import pandas as pd import csv consumer_key = 'xyz' consumer_secret = 'xyz' access_token = 'xyz' access_token_secret = 'xyz' data = pd.read_csv('user_keyword.csv') df = ['user_name', 'user_id', 'date', 'keyword'] def get_user_details(username): userobj = api.get_user(username) return userobj if __name__ == '__main__': #authenticating the app (https://apps.twitter.com/) auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) username = df['user_name'] userOBJ = get_user_details(username) print(userOBJ.location) </code></pre> <p>Error: Trouble parsing the usernames into program. </p> <pre><code>Traceback (most recent call last): File "user_profile_location.py", line 38, in &lt;module&gt; username = df['user_name'] TypeError: list indices must be integers, not str </code></pre>
-3
2016-07-22T10:24:48Z
38,525,522
<p>You are using 'data' to define your DataFrame and 'df' for what I think should be the columns of the DataFrame</p> <pre><code>data = pd.read_csv('user_keyword.csv') df = ['user_name', 'user_id', 'date', 'keyword'] </code></pre> <p>I assume that the user_keyword.csv file has no header, try adding:</p> <pre><code>data.columns = df </code></pre> <p>It will change the column names to the values stored in df. Then later instead of:</p> <pre><code>username = df['user_name'] </code></pre> <p>Try:</p> <pre><code>username = data['user_name'] </code></pre> <p>Keep in mind that now username is a whole column so <code>get_user_details(username)</code> should not be expecting a single string.</p>
1
2016-07-22T11:39:02Z
[ "python", "pandas", "twitter", "geolocation", "latitude-longitude" ]
Scrapy Change Items Order
38,524,090
<p>I'm scraping some data and exporting it to a json file, but i cant seem to set the order of the items. After doing some reading i found scrapy Items are wrappers of python dict and will return the item fields in an unpredicted order. </p> <p>i have tried adding: </p> <pre><code> def keys(self): return ['item1', 'item2', 'item3'] </code></pre> <p>now the output only consists of these 3 items but the order still remains unpredictable is there anyways i could set the order of these items ?</p>
0
2016-07-22T10:25:34Z
38,551,719
<p>In JSON, an object is defined thus:</p> <pre><code>An object is an unordered set of name/value pairs. </code></pre> <p>See <a href="http://json.org" rel="nofollow">http://json.org</a>.</p> <p>Most implementations of JSON make no effort to preserve the order of an object's name/value pairs, since it is (by definition) not significant.</p> <p>So in the end i switched the data format.</p>
0
2016-07-24T11:55:06Z
[ "python", "python-2.7", "scrapy", "scrapy-spider" ]
python script for creating maproxy OGC WMS service using Mapnik and PostGIS
38,524,212
<p>Would that be possible to create programatically a new OGC WMS (1.1/1/3) service using:</p> <ol> <li>Python</li> <li>MapProxy</li> <li>Mapnik</li> <li>PostGIS/Postgres</li> </ol> <p>any script/gist or sample would be more then appreciated.</p> <p>Cheers, M</p>
0
2016-07-22T10:32:20Z
39,139,392
<p>In general everything is about configuration files. I create automatically new WMS endpoints for my Mapserver/Mapproxy setup with a python script, which also process my images.</p> <p>MapServer config-pattern:</p> <pre><code>MAP NAME "WMS Server" #IMAGECOLOR 255 255 255 IMAGETYPE custom TRANSPARENT OFF CONFIG "MS_ERRORFILE" [error.txt] EXTENT [Extent] SIZE 800 600 WEB METADATA "wms_title" [title] "wms_srs" [epsg] "wms_enable_request" "*" END END PROJECTION "init=[epsg]" END INCLUDE [layer list] OUTPUTFORMAT NAME "custom" DRIVER "GDAL/GTiff" MIMETYPE "image/tiff" IMAGEMODE RGBA TRANSPARENT ON EXTENSION "tif" FORMATOPTION "GAMMA=1.0" END END </code></pre> <p>Mapproxy config-pattern:</p> <pre><code>caches: [cache folder]: cache: directory_layout: tms type: file grids: - webmercator image: format: image/png mode: RGBA resampling_method: bilinear encoding_options: jpeg_quality: 100 transparent: true meta_size: - 2 - 2 sources: - [source] globals: cache: base_dir: [base dir] lock_dir: [lock dir] tile_lock_dir: [tile lock dir] image: paletted: false grids: webmercator: base: GLOBAL_WEBMERCATOR num_levels: 22 layers: - name: [layer name] sources: - [cache] title: [title] services: demo: null wms: md: abstract: This is a minimal MapProxy example. title: MapProxy WMS Proxy srs: - [epsg] sources: 45_source: coverage: datasource: [coverage datasource] srs: [epsg] mapserver: binary: [mapserver binary] working_dir: / req: layers: [mapserver layer name] map: [mapserver mapfile] transparent: true supported_formats: - image/tiff supported_srs: - [epsg] type: mapserver </code></pre> <p>Everything you have to do is to split up the config into different parts, which you then can edit with a python script. </p>
0
2016-08-25T07:41:09Z
[ "python", "postgis", "mapnik" ]
python script for creating maproxy OGC WMS service using Mapnik and PostGIS
38,524,212
<p>Would that be possible to create programatically a new OGC WMS (1.1/1/3) service using:</p> <ol> <li>Python</li> <li>MapProxy</li> <li>Mapnik</li> <li>PostGIS/Postgres</li> </ol> <p>any script/gist or sample would be more then appreciated.</p> <p>Cheers, M</p>
0
2016-07-22T10:32:20Z
39,417,434
<p>If we are looking for publish data in postgres to WMS, enable tilecache, and use more advanced rendering engine like mapnik, then I would say there could be one component missing is the GIS server.</p> <p>So if I am guessing your requirement correctly as I mentioned earlier then here is what the system design could be:</p> <ol> <li>Use postgres/postgis as database connection.</li> <li>Write your own server side program using python to create the service definition file for the dynamic WMS (mapfile if you are going to use MapServer).</li> <li>Then your program handling tilecache/tile seeding by change the configuration file (.yaml) in mapproxy.</li> <li>Then escalate WMS to mapnik for rendering and expose the output. Like someone else mentioned, it would be easy to have a template configuration file for each step and do parameter substitution.</li> </ol>
0
2016-09-09T18:10:04Z
[ "python", "postgis", "mapnik" ]
What file does the python symlink point to
38,524,275
<p>I bought my mac about a year ago and somehow changed my python symlink so that when I run <code>python some_file.py</code>, python 3.4 is used to run the file instead of python 2.7. I now need to change it back, but I can't figure out what I did to change it in the first place! When I run:</p> <pre><code>import os os.path.realpath("/usr/local/bin/python") </code></pre> <p>in the python terminal, the output is:</p> <pre><code>'/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7' </code></pre> <p>Does this not mean that my python symlink is pointing to my python 2.7 version, and not my 3.4 version? If not, how do I find out which file is run when I use the python symlink?</p>
0
2016-07-22T10:34:39Z
38,524,389
<p>You probably installed that specific Python version using the official Python installer for OS X; see the <a href="https://docs.python.org/2/using/mac.html" rel="nofollow"><em>Using Python on a Macintosh</em> documentation</a>. The installer creates the <code>/usr/local/bin</code> symlink for you.</p> <p>If you also, at some point, had 3.4 installed then that installation is still there too. Check for a <code>/usr/local/bin/python3</code> command; it'll link to the existing Python 3 binary. Use that instead to run Python 3 code.</p> <p>If you do have a <code>/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4</code> command, you <em>could</em> re-create the <code>/usr/local/bin/python</code> symlink to point there instead, but I'd personally only use the <code>python3</code> name for Python 3 scripts.</p> <p>Last, you could also have used the homebrew tool to install Python; it can manage symlinks for you. However, homebrew installs Python binaries into the <code>/usr/local/Cellar</code> tree structure instead.</p>
1
2016-07-22T10:40:44Z
[ "python", "python-2.7", "python-3.x" ]
Declaring decorator inside a class
38,524,332
<p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p> <hr> <p>Here is what I'd like to do (NB: this code doesn't work, I explain what happens below)</p> <pre><code>class TestWrapper(): def __init__(self, a, b): self.a = a self.b = b self.c = 0 def enter_exit_info(self, func): def wrapper(*arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(*arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper @enter_exit_info def add_in_c(self): self.c = self.a + self.b print self.c @enter_exit_info def mult_in_c(self): self.c = self.a * self.b print self.c if __name__ == '__main__': t = TestWrapper(2, 3) t.add_in_c() t.mult_in_c() </code></pre> <p>The expected output is :</p> <pre><code>-- entering add_in_c -- {'a': 2, 'b': 3, 'c': 0} 5 -- exiting add_in_c -- {'a': 2, 'b': 3, 'c': 5} -- entering mult_in_c -- {'a': 2, 'b': 3, 'c': 5} 6 -- exiting mult_in_c -- {'a': 2, 'b': 3, 'c': 6} </code></pre> <p>But I this code gives </p> <pre><code>Traceback (most recent call last): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 2, in &lt;module&gt; class TestWrapper(): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 18, in TestWrapper @enter_exit_info TypeError: enter_exit_info() takes exactly 2 arguments (1 given) </code></pre> <p>And if I try <code>@enter_exit_info(self)</code> or <code>@self.enter_exit_info</code>, I get a <code>NameError</code>. What could I do?</p> <hr> <p><strong>EDIT:</strong></p> <p>I do not need above all to have the decorator <em>physically</em> declared inside the class, as long as it is able to access attributes from an instance of this class. I thought it could only be made by declaring it inside the class, <a href="http://stackoverflow.com/a/38524581/5018771">Rawing's answer</a> proved me wrong.</p>
2
2016-07-22T10:37:23Z
38,524,579
<p>You will need to handle <code>self</code> explicitly.</p> <pre><code>class TestWrapper(): def __init__(self, a, b): self.a = a self.b = b self.c = 0 def enter_exit_info(func): def wrapper(self, *arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(self, *arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper @enter_exit_info def add_in_c(self): self.c = self.a + self.b print self.c @enter_exit_info def mult_in_c(self): self.c = self.a * self.b print self.c if __name__ == '__main__': t = TestWrapper(2, 3) t.add_in_c() t.mult_in_c() </code></pre> <p>This is valid python, but it's somewhat weird to have a function at the class level which is not really a method. Unless you have a good reason to do it this way, it would be more idiomatic to move the decorator to module level scope. </p>
7
2016-07-22T10:49:36Z
[ "python", "python-2.7", "wrapper", "decorator", "python-decorators" ]
Declaring decorator inside a class
38,524,332
<p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p> <hr> <p>Here is what I'd like to do (NB: this code doesn't work, I explain what happens below)</p> <pre><code>class TestWrapper(): def __init__(self, a, b): self.a = a self.b = b self.c = 0 def enter_exit_info(self, func): def wrapper(*arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(*arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper @enter_exit_info def add_in_c(self): self.c = self.a + self.b print self.c @enter_exit_info def mult_in_c(self): self.c = self.a * self.b print self.c if __name__ == '__main__': t = TestWrapper(2, 3) t.add_in_c() t.mult_in_c() </code></pre> <p>The expected output is :</p> <pre><code>-- entering add_in_c -- {'a': 2, 'b': 3, 'c': 0} 5 -- exiting add_in_c -- {'a': 2, 'b': 3, 'c': 5} -- entering mult_in_c -- {'a': 2, 'b': 3, 'c': 5} 6 -- exiting mult_in_c -- {'a': 2, 'b': 3, 'c': 6} </code></pre> <p>But I this code gives </p> <pre><code>Traceback (most recent call last): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 2, in &lt;module&gt; class TestWrapper(): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 18, in TestWrapper @enter_exit_info TypeError: enter_exit_info() takes exactly 2 arguments (1 given) </code></pre> <p>And if I try <code>@enter_exit_info(self)</code> or <code>@self.enter_exit_info</code>, I get a <code>NameError</code>. What could I do?</p> <hr> <p><strong>EDIT:</strong></p> <p>I do not need above all to have the decorator <em>physically</em> declared inside the class, as long as it is able to access attributes from an instance of this class. I thought it could only be made by declaring it inside the class, <a href="http://stackoverflow.com/a/38524581/5018771">Rawing's answer</a> proved me wrong.</p>
2
2016-07-22T10:37:23Z
38,524,581
<p>Instead of defining the decorator inside the class you can just intercept the <code>self</code> parameter:</p> <pre><code>def enter_exit_info(func): def wrapper(self, *arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(self, *arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper class TestWrapper(): def __init__(self, a, b): self.a = a self.b = b self.c = 0 @enter_exit_info def add_in_c(self): self.c = self.a + self.b print self.c @enter_exit_info def mult_in_c(self): self.c = self.a * self.b print self.c if __name__ == '__main__': t = TestWrapper(2, 3) t.add_in_c() t.mult_in_c() </code></pre>
0
2016-07-22T10:49:46Z
[ "python", "python-2.7", "wrapper", "decorator", "python-decorators" ]
Declaring decorator inside a class
38,524,332
<p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p> <hr> <p>Here is what I'd like to do (NB: this code doesn't work, I explain what happens below)</p> <pre><code>class TestWrapper(): def __init__(self, a, b): self.a = a self.b = b self.c = 0 def enter_exit_info(self, func): def wrapper(*arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(*arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper @enter_exit_info def add_in_c(self): self.c = self.a + self.b print self.c @enter_exit_info def mult_in_c(self): self.c = self.a * self.b print self.c if __name__ == '__main__': t = TestWrapper(2, 3) t.add_in_c() t.mult_in_c() </code></pre> <p>The expected output is :</p> <pre><code>-- entering add_in_c -- {'a': 2, 'b': 3, 'c': 0} 5 -- exiting add_in_c -- {'a': 2, 'b': 3, 'c': 5} -- entering mult_in_c -- {'a': 2, 'b': 3, 'c': 5} 6 -- exiting mult_in_c -- {'a': 2, 'b': 3, 'c': 6} </code></pre> <p>But I this code gives </p> <pre><code>Traceback (most recent call last): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 2, in &lt;module&gt; class TestWrapper(): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 18, in TestWrapper @enter_exit_info TypeError: enter_exit_info() takes exactly 2 arguments (1 given) </code></pre> <p>And if I try <code>@enter_exit_info(self)</code> or <code>@self.enter_exit_info</code>, I get a <code>NameError</code>. What could I do?</p> <hr> <p><strong>EDIT:</strong></p> <p>I do not need above all to have the decorator <em>physically</em> declared inside the class, as long as it is able to access attributes from an instance of this class. I thought it could only be made by declaring it inside the class, <a href="http://stackoverflow.com/a/38524581/5018771">Rawing's answer</a> proved me wrong.</p>
2
2016-07-22T10:37:23Z
38,524,704
<p>TL;DR : what you want is</p> <pre><code>def enter_exit_info(func): def wrapper(self, *arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(*arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper </code></pre> <p>Remember that </p> <pre><code>@decorate def myfunc(): pass </code></pre> <p>is really just syntactic sugar for</p> <pre><code>def myfunc(): pass my_func = decorate(my_func) </code></pre> <p>So since in your case, decorated functions are replaced by the decorator's <code>wrapper</code> function, it's this <code>wrapper</code> function that will receive the current instance as first argument.</p> <p>EDIT : I positively agree with other answers on the point that it makes no sense defining this decorator within the class. You don't need it to access the current instance since it's provided as the function's first argument. FWIW the <code>def</code> statement doesn't work any differently from being used within a <code>class</code> statement, it always yields a plain old <code>function</code> object. What makes the function a "method" (and 'automagically' pass the current instance as first argument) is the attribute resolution mechanism, cf <a href="https://wiki.python.org/moin/FromFunctionToMethod" rel="nofollow">https://wiki.python.org/moin/FromFunctionToMethod</a></p>
2
2016-07-22T10:55:49Z
[ "python", "python-2.7", "wrapper", "decorator", "python-decorators" ]
Declaring decorator inside a class
38,524,332
<p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p> <hr> <p>Here is what I'd like to do (NB: this code doesn't work, I explain what happens below)</p> <pre><code>class TestWrapper(): def __init__(self, a, b): self.a = a self.b = b self.c = 0 def enter_exit_info(self, func): def wrapper(*arg, **kw): print '-- entering', func.__name__ print '-- ', self.__dict__ res = func(*arg, **kw) print '-- exiting', func.__name__ print '-- ', self.__dict__ return res return wrapper @enter_exit_info def add_in_c(self): self.c = self.a + self.b print self.c @enter_exit_info def mult_in_c(self): self.c = self.a * self.b print self.c if __name__ == '__main__': t = TestWrapper(2, 3) t.add_in_c() t.mult_in_c() </code></pre> <p>The expected output is :</p> <pre><code>-- entering add_in_c -- {'a': 2, 'b': 3, 'c': 0} 5 -- exiting add_in_c -- {'a': 2, 'b': 3, 'c': 5} -- entering mult_in_c -- {'a': 2, 'b': 3, 'c': 5} 6 -- exiting mult_in_c -- {'a': 2, 'b': 3, 'c': 6} </code></pre> <p>But I this code gives </p> <pre><code>Traceback (most recent call last): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 2, in &lt;module&gt; class TestWrapper(): File "C:\Users\cccvag\workspace\Test\src\module2.py", line 18, in TestWrapper @enter_exit_info TypeError: enter_exit_info() takes exactly 2 arguments (1 given) </code></pre> <p>And if I try <code>@enter_exit_info(self)</code> or <code>@self.enter_exit_info</code>, I get a <code>NameError</code>. What could I do?</p> <hr> <p><strong>EDIT:</strong></p> <p>I do not need above all to have the decorator <em>physically</em> declared inside the class, as long as it is able to access attributes from an instance of this class. I thought it could only be made by declaring it inside the class, <a href="http://stackoverflow.com/a/38524581/5018771">Rawing's answer</a> proved me wrong.</p>
2
2016-07-22T10:37:23Z
38,525,351
<p>Hi do you want the output should be in dictionary format? If you don't want the output in dictionary format u can try this....</p> <p>def enter_exit_info(func): def wrapper(*arg, **kw): print '-- entering', func.<strong>name</strong><br> res = func(*arg, **kw) print '-- exiting', func.<strong>name</strong> return res return wrapper</p> <p>then your output will be</p> <p>-- entering add_in_c</p> <p>5 -- exiting add_in_c</p> <p>-- entering mult_in_c</p> <p>6 -- exiting mult_in_c</p>
-1
2016-07-22T11:29:55Z
[ "python", "python-2.7", "wrapper", "decorator", "python-decorators" ]
Python Pandas v0.18+: is there a way to resample a dataframe without filling NAs?
38,524,400
<p>I wonder if there is a way to up resample a <code>DataFrame</code> without having to decide how NAs should be filled immediately.</p> <p>I tried the following but got the Future Warning:</p> <blockquote> <p>FutureWarning: .resample() is now a deferred operation use .resample(...).mean() instead of .resample(...)</p> </blockquote> <p>Code:</p> <pre><code>import pandas as pd dates = pd.date_range('2015-01-01', '2016-01-01', freq='BM') dummy = [i for i in range(len(dates))] df = pd.DataFrame({'A': dummy}) df.index = dates df.resample('B') </code></pre> <p><strong>Is there a better way to do this, that doesn't show warnings?</strong></p> <p>Thanks.</p>
3
2016-07-22T10:41:23Z
38,524,422
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.asfreq.html" rel="nofollow"><code>Resampler.asfreq</code></a>:</p> <pre><code>print (df.resample('B').asfreq()) A 2015-01-30 0.0 2015-02-02 NaN 2015-02-03 NaN 2015-02-04 NaN 2015-02-05 NaN 2015-02-06 NaN 2015-02-09 NaN 2015-02-10 NaN 2015-02-11 NaN 2015-02-12 NaN 2015-02-13 NaN 2015-02-16 NaN 2015-02-17 NaN 2015-02-18 NaN 2015-02-19 NaN 2015-02-20 NaN 2015-02-23 NaN 2015-02-24 NaN 2015-02-25 NaN 2015-02-26 NaN 2015-02-27 1.0 2015-03-02 NaN 2015-03-03 NaN 2015-03-04 NaN ... ... </code></pre>
1
2016-07-22T10:42:31Z
[ "python", "pandas", "dataframe", null, "resampling" ]
Extracting tables from website
38,524,459
<p>I am trying to get the table from Morningstar into pandas</p> <p>Website link - <a href="http://financials.morningstar.com/cash-flow/cf.html?t=3IINFOTECH&amp;region=ind&amp;culture=en-US" rel="nofollow">http://financials.morningstar.com/cash-flow/cf.html?t=3IINFOTECH&amp;region=ind&amp;culture=en-US</a></p> <p>Since the website is Javascript, I am first rendering the website in my local browser using selenium and then reading the rendered HTML file from browser and trying to read the table. </p> <p>The problem is the table is stored in a div style as below: this means that I cannot read the table using either pandas read HTML, or beautiful soup's read table functions. Both give the error <code>no tables found</code>. Can somebody help me with an easy way to extract the data from the div nodes as I am new to Python. Below is a portion of the HTML script for the table</p> <pre><code>"" style="overflow:hidden;white-space: nowrap;"&gt; 25,875 &lt;/div&gt; &lt;div class="pos column6Width109px" id="Y_2" rawvalue="16810200000" style="overflow:hidden;white-space: nowrap;"&gt; 16,810 &lt;/div&gt; &lt;div class="pos column6Width109px" id="Y_3" rawvalue="13113600000" style="overflow:hidden;white-space: nowrap;"&gt; 13,114" </code></pre>
-1
2016-07-22T10:44:00Z
38,532,560
<p>You can get the data using just <em>requests</em> and <em>Beautifulsoup</em>, the html is retrieved with an ajax call:</p> <pre><code>from bs4 import BeautifulSoup from json import loads import requests from time import time params = {'columnYear': '5', 'region': 'ind', 'rounding': '3', 'period': '12', 'curYearPart': '1st5year', 'culture': 'en-US', 'reportType': 'cf', 't': 'XNSE:3IINFOTECH', 'callback': 'jsonp{}'.format(str(int(time()))), 'order': 'asc', '_': str(int(time()))} r = requests.get('http://financials.morningstar.com/ajax/ReportProcess4HtmlAjax.html', params=params) cont = r.content jsn = loads(cont[cont.find("{"):cont.rfind("}") + 1]) soup = BeautifulSoup(jsn["result"]) table = soup.select_one("div.r_xcmenu.rf_table") headers = [d.text for d in table.select("div.rf_header [id^=Y_]")] print headers for row in table.find_all("div","rf_crow", style=False): print([d.text for d in row.select("[id^=Y_]")]) </code></pre> <p>Which gives you:</p> <pre><code>[u'2011-03', u'2012-03', u'2013-03', u'2014-03', u'2015-03', u'TTM'] [u'3,511', u'(1,545)', u'495', u'498', u'(513)', u'(513)'] [u'975', u'1,092', u'2,308', u'2,564', u'2,291', u'2,291'] [u'\u2014', u'(80)', u'\u2014', u'\u2014', u'\u2014', u'\u2014'] [u'(10)', u'6', u'5', u'2', u'(1)', u'(1)'] [u'(1,277)', u'(3,556)', u'(401)', u'(409)', u'(2,080)', u'(2,080)'] [u'3,823', u'995', u'(1,417)', u'(1,661)', u'(724)', u'(724)'] [u'(1,168)', u'4,953', u'(398)', u'(190)', u'3,137', u'3,137'] [u'(4,713)', u'(617)', u'(426)', u'(229)', u'\u2014', u'\u2014'] [u'232', u'\u2014', u'\u2014', u'\u2014', u'89', u'89'] [u'\u2014', u'5,513', u'\u2014', u'\u2014', u'3,037', u'3,037'] [u'\u2014', u'\u2014', u'(1)', u'\u2014', u'\u2014', u'\u2014'] [u'3,251', u'\u2014', u'\u2014', u'0', u'\u2014', u'\u2014'] [u'63', u'57', u'29', u'39', u'12', u'12'] [u'(2,207)', u'(3,843)', u'(604)', u'(168)', u'(3,026)', u'(3,026)'] [u'(1,482)', u'\u2014', u'\u2014', u'\u2014', u'\u2014', u'\u2014'] [u'1,816', u'\u2014', u'\u2014', u'\u2014', u'\u2014', u'\u2014'] [u'(151)', u'\u2014', u'\u2014', u'\u2014', u'\u2014', u'\u2014'] [u'(410)', u'(341)', u'\u2014', u'\u2014', u'\u2014', u'\u2014'] [u'(1,980)', u'(3,502)', u'(604)', u'(168)', u'(3,026)', u'(3,026)'] [u'136', u'(435)', u'(506)', u'140', u'(403)', u'(403)'] [u'1,806', u'1,318', u'884', u'377', u'518', u'518'] [u'1,941', u'884', u'377', u'518', u'115', u'115'] [u'\xa0', u'\xa0', u'\xa0', u'\xa0', u'\xa0', u'\xa0'] [u'3,511', u'(1,545)', u'495', u'498', u'(513)', u'(513)'] [u'(4,713)', u'(617)', u'(426)', u'(229)', u'\u2014', u'\u2014'] [u'(1,203)', u'(2,162)', u'69', u'269', u'(513)', u'(513)'] </code></pre> <p><code>u'\u2014'</code> is a unicode <code>_</code> which you see on the page for missing values.</p>
0
2016-07-22T17:50:01Z
[ "python", "pandas", "beautifulsoup" ]
Session cookies and http headers
38,524,532
<p>I'm did a login system to experiment a login script in python, the login system has a form token which i extract from the page with regex (so i can post it along with username/password after), that's what i'm trying to avoid. So i did this example code to show you, and maybe you can anser me. Is there anyway besides this one to extract the <code>session</code> vars.</p> <p>My php code:</p> <pre><code>&lt;?php session_start(); $_SESION['token'] = md5(time()); ?&gt; &lt;input type="hidden" name="token" value="&lt;?= $_SESION['token']; ?&gt;"&gt; </code></pre> <p>My 'login script' (just the part relevant about the token extracion):</p> <pre><code>import requests import re s = requests.Session() headers = { "User-agent" : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1', "Referer": 'https://www.google.com' } req = s.get('http://migueldvl.com/heya/login/tests.php', headers=headers) token = re.compile('&lt;input type="hidden" name="token" value="(.*?)"&gt;').search(req.text).group(1) print('page: ', req.text) print('token: ', token) print('\nheaders we sent: ', req.request.headers) print('\nheaders server sent back: ', req.headers) # (nothing about the token session here) </code></pre> <p>You guys are welcome to test the code (python3) in this <a href="http://migueldvl.com/heya/login/tests.php" rel="nofollow">url</a>, it's not blank if you view source</p>
0
2016-07-22T10:47:25Z
38,525,008
<p>You can't retrieve session variables defined in PHP this way:</p> <blockquote> <p>A session is a way to store information (in variables) to be used across multiple pages.</p> <p>Unlike a cookie, the information is not stored on the users computer.</p> </blockquote> <p><em>Source: <a href="http://www.w3schools.com/php/php_sessions.asp" rel="nofollow">http://www.w3schools.com/php/php_sessions.asp</a></em></p> <p><strong>Regex alternative</strong></p> <p>Alternatively to using regex, you could use <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> (<a href="http://beautiful-soup-4.readthedocs.io/en/latest/#" rel="nofollow">docs</a>) to extract the token value:</p> <pre><code>from bs4 import BeautifulSoup r = s.get('http://migueldvl.com/heya/login/tests.php', headers=headers) r.raise_for_status() soup = BeautifulSoup(r.content, 'lxml') # Simple reference token = soup.html.body.input['value'] # With more attributes specified token = soup.html.body.find('input', attrs={'name':'token', 'type':'hidden'})['value'] </code></pre>
1
2016-07-22T11:11:53Z
[ "python", "http", "session", "request" ]
Set default value of field depends on other field in odoo
38,524,745
<p>I am setting up default value of <code>analytics_id</code> in <code>account.move.line</code> by below code</p> <pre class="lang-py prettyprint-override"><code>class account_move_line(models.Model): _inherit = 'account.move.line' _name = "account.move.line" def _get_default_account(self, cr, uid, context=None): obj = self.pool.get('account.move') value = obj.browse(cr, uid, uid) if value.move_id.debit&gt;0 or value.move_id.credit&lt;0: res = self.pool.get('account.analytic.plan.instance').search(cr, uid, [('code','=','LAL')], context=context) return res and res[0] or False _defaults = { 'analytics_id': _get_default_account, } </code></pre> <p>it is working well for me but now i want to set this default value if <code>debit field value is greater then zero</code> <strong><em>OR</em></strong> <code>credit field value less then zero</code> otherwise <code>analytics_id</code> field remain empty.</p>
0
2016-07-22T10:58:08Z
38,538,520
<p>Try to use this type of code</p> <pre class="lang-py prettyprint-override"><code>res = self.pool.get('account.analytic.plan.instance').search(cr, uid, [('code','=','LAL')], context=context) if res: br_analytic_plan=self.pool.get('account.analytic.plan.instance').browse(cr,uid,res[0],context=context) if ---your Condition---- # You can access For example. br_analytic_plan.amount &gt; 0 return res[0] </code></pre> <p>This same logic you can apply to both groups condition (it means under if and else on your current code).</p> <p>Hope this helps.</p>
0
2016-07-23T05:32:46Z
[ "python", "openerp", "odoo-8", "openerp-8", "odoo-9" ]
In tensorflow, how to iterate over a sequence of inputs stored in a tensor?
38,524,776
<p>I am trying RNN on a variable length multivariate sequence classification problem.</p> <p>I have defined following function to get the output of the sequence (i.e. the output of RNN cell after the final input from sequence is fed)</p> <pre><code>def get_sequence_output(x_sequence, initial_hidden_state): previous_hidden_state = initial_hidden_state for x_single in x_sequence: hidden_state = gru_unit(previous_hidden_state, x_single) previous_hidden_state = hidden_state final_hidden_state = hidden_state return final_hidden_state </code></pre> <p>Here <code>x_sequence</code> is tensor of shape <code>(?, ?, 10)</code> where first ? is for batch size and second ? is for sequence length and each input element is of length 10. <code>gru</code> function takes a previous hidden state and current input and spits out next hidden state (a standard gated recurrent unit).</p> <p>I am getting an error: <code>'Tensor' object is not iterable.</code> How do I iterate over a Tensor in sequence manner (reading single element at a time)?</p> <p>My objective is to apply <code>gru</code> function for every input from the sequence and get the final hidden state.</p>
0
2016-07-22T10:59:52Z
38,531,914
<p>You can convert a tensor into a list using the unpack function which converts the first dimension into a list. There is also a split function which does something similar. I use unpack in an RNN model I am working on.</p> <pre><code>y = tf.unpack(tf.transpose(y, (1, 0, 2))) </code></pre> <p>In this case y starts out with shape (BATCH_SIZE, TIME_STEPS, 128) I transpose it to make the time steps the outer dimension and then unpack it into a list of tensors, one per time step. Now every element in the y list if of shape (BATCH_SIZE, 128) and I can feed it into my RNN.</p>
1
2016-07-22T17:06:42Z
[ "python", "tensorflow", "recurrent-neural-network", "gated-recurrent-unit" ]
How to assign dataframe to dynamic variable to python?
38,524,821
<p>As a part of code,I need to assign a dataframe to a dynamic variable created during the process.</p> <p>I did research on assigning value as below:</p> <pre><code>I = 1 x = 'varName'+str(I) exec("%s = %d" % (x,2)) varName1 </code></pre> <p>But how to do it for dataframe?</p> <p>Thanks</p>
0
2016-07-22T11:01:52Z
38,524,988
<p>"dynamic variables" are an antipattern. What you want is either a <code>dict</code>: </p> <pre><code>vars = {} key = "something_%s" % another_string vars[key] = something() </code></pre> <p>or (more probably since you seem to be using some numeric index):</p> <pre><code>vars = [] for whatever in (some_sequence): val = something(whatever) vars.append(val) </code></pre> <p>which FWIW can be rewritten more simply as :</p> <pre><code>vars = [something(whatever) for whatever in some_sequence] </code></pre>
0
2016-07-22T11:11:04Z
[ "python", "pandas" ]
How to convolve array of arrays with a mask in Python?
38,524,847
<p>Given a t1xt2xn array and a m1xm2 mask, how to obtain the t1xt2xn array where the n-dim arrays are convolved with the mask?</p> <p>The function scipy.signal.convolve is not able to handle this because it only accept inputs with same number of dimensions.</p> <p>Example with the "same" logic:</p> <pre><code>in1 = [[[0,1,2],[3,4,5],[6,7,8]], [[9,10,11],[12,13,14],[15,16,17]], [[18,19,20],[21,22,23],[24,25,26]]] in2 = [[0,1,0], [0,1,0], [0,1,0]] output = [[[0,0,0],[15,17,19],[0,0,0]], [[0,0,0],[36,39,42],[0,0,0]], [[0,0,0],[33,35,37],[0,0,0]]] </code></pre>
1
2016-07-22T11:03:36Z
38,527,060
<p>I'm very sorry but I haven't strong math background, so my answer could be wrong. Anyway, if you need to use mask for selecting you should convert it to bool type. For example:</p> <pre><code>in1 = np.array([[[0,1,2], [3,4,5], [6,7,8]], [[9,10,11], [12,13,14], [15,16,17]], [[18,19,20], [21,22,23], [24,25,26]]]) in2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]]) mask = in2.astype(bool) print(in1[mask]) # [[ 3 4 5] # [12 13 14] # [21 22 23]] in3 = np.zeros(in1.shape) in3[mask] = np.convolve(in1[mask].ravel(), in2.ravel(), 'same').reshape(mask.shape) print(in3) # [[[ 0. 0. 0.] # [ 15. 17. 19.] # [ 0. 0. 0.]] # # [[ 0. 0. 0.] # [ 36. 39. 42.] # [ 0. 0. 0.]] # # [[ 0. 0. 0.] # [ 33. 35. 37.] # [ 0. 0. 0.]]] </code></pre> <p>I'm not very sure about last part, especially about reshaping but I hope you get an idea.</p>
0
2016-07-22T12:56:34Z
[ "python", "mask", "convolution" ]
Anaconda 3 for Linux Has No ensurepip?
38,524,856
<p>This is my environment:</p> <ul> <li><p>CentOS 64-bit 7.2.1511</p></li> <li><p>Anaconda 3 4.1.1 64-bit (Python 3.5.2)</p></li> </ul> <p>I want to create venv virtual environment by <code>pyvenv</code>. Unfortunately, I got this error message:</p> <p><code>$ pyvenv test Error: Command '['/root/test/bin/python', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1</code></p> <p>After searching the Internet, people said the module <code>ensurepip</code> is missing. I checked my Anaconda installation path <code>/opt/anaconda3/lib/python3.5</code>. There is no ensurepip folder.</p> <p>Then, on my Windows 10 64-bit, I checked my Anaconda installation path <code>D:\win10\Anaconda3\Lib\</code>. There is an ensurepip folder! And I can successfully run <code>python -m venv test</code> to create a venv.</p> <p>Then, I checked the download Anaconda python archives: <code>D:\win10\Anaconda3\pkgs\python-3.5.2-0.tar.bz2</code> on Windows 10 and <code>/opt/anaconda3/pkgs/python-3.5.2-0.tar.bz2</code> on CentOS 7.</p> <p>The one archive on Windows 10 does has a ensurepip subfolder. But the one on CentOS 7 doesn't!</p> <p>Does anyone know this difference? Is it a bug of Anaconda?</p>
2
2016-07-22T11:04:30Z
39,114,277
<p>Yes, Anaconda3/2 for Linux and Mac OS do not have <code>ensurepip</code> installed. </p> <p>According to <a href="https://github.com/ContinuumIO/anaconda-issues/issues/952" rel="nofollow">this issue record</a>, it is NOT a bug, this is done <em>intentionally</em> when the Python in Anaconda being compiled without the <code>--with-ensurepip=install</code> flag.</p> <p>I think the rationale (of Continuum Analytics) is that, <em>in Anaconda Distribution</em>, <code>conda</code> is the boss to manage the packages and virtual environments, and </p> <blockquote> <p>pip (and it's setuptools dependency) are installed independent of Python <strong>as conda packages</strong>.</p> </blockquote> <p>So instead of running <code>pyvenv test</code>, you can first run <code>pyvenv test --without-pip</code>, then download the <code>get-pip.py</code> from <a href="https://pip.pypa.io/en/stable/installing/#installing-with-get-pip-py" rel="nofollow">pip's homepage</a>, and install the pip in <strong>activated</strong> <code>test</code> venv.</p> <p>Just like the following:</p> <pre><code>$ #===== First create the venv without pip, and **activate** it. $ pyvenv test --without-pip $ cd test/ $ ls bin/ activate activate.csh activate.fish python@ python3@ $ echo $PATH Whatever/Else:In/Your/System $ source bin/activate (test) $ echo $PATH /Users/YaOzI/test/bin:Whatever/Else:In/Your/System (test) $ (test) $ #===== Then install the pip independently. (test) $ python ~/Downloads/get-pip.py Collecting pip Using cached pip-8.1.2-py2.py3-none-any.whl Collecting setuptools Downloading setuptools-26.0.0-py2.py3-none-any.whl (459kB) 100% |████████████████████████████████| 460kB 1.3MB/s Collecting wheel Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB) 100% |████████████████████████████████| 71kB 5.7MB/s Installing collected packages: pip, setuptools, wheel Successfully installed pip-8.1.2 setuptools-26.0.0 wheel-0.29.0 (test) $ ls bin/ activate activate.fish easy_install-3.5* pip3* python@ wheel* activate.csh easy_install* pip* pip3.5* python3@ (test) $ (test) $ #===== Now you can play around with pip (test) $ pip list (test) $ </code></pre>
2
2016-08-24T04:09:57Z
[ "python", "anaconda", "python-venv" ]
pip install mysql-connector==2.1.3 fails
38,524,946
<pre><code>(ENV)$ pip install mysql-connector==2.1.3 Collecting mysql-connector==2.1.3 Using cached mysql-connector-2.1.3.zip Installing collected packages: mysql-connector Running setup.py install for mysql-connector usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: option --single-version-externally-managed not recognized Complete output from command /&lt;DIR&gt;/ENV/bin/python2 -c "import setuptools, tokenize;__file__='/tmp/pip-build-ImtJft/mysql-connector/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-FN9lfq-record/install-record.txt --single-version-externally-managed --compile --install-headers /&lt;DIR&gt;/ENV/include/site/python2.7: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: option --single-version-externally-managed not recognized ---------------------------------------- Command "/&lt;DIR&gt;/ENV/bin/python2 -c "import setuptools, tokenize;__file__='/tmp/pip-build-ImtJft/mysql-connector/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-FN9lfq-record/install-record.txt --single-version-externally-managed --compile --install-headers /&lt;DIR&gt;/ENV/include/site/python2.7" failed with error code 1 in /tmp/pip-build-ImtJft/mysql-connector </code></pre> <p>This is the error. I have been trying to figure out the error is. I did some searching around, but of no use. I am running fedora 22. I checked to see if it could be if mysql is installed. But mysql-devel and mysql-libs are installed. Please help. </p> <p>EDIT: I tried: </p> <pre><code>easy_install mysql-connector==2.1.3 </code></pre> <p>And it works. But why is pip failing?</p>
0
2016-07-22T11:09:12Z
38,525,912
<p>Your setuptools version might be outdated. try upgrading pip:</p> <pre><code>pip install --upgrade setuptools </code></pre> <p>You can find information about this error in this thread:</p> <p><a href="http://stackoverflow.com/questions/14296531/what-does-error-option-single-version-externally-managed-not-recognized-ind">What does &quot;error: option --single-version-externally-managed not recognized&quot; indicate?</a></p>
0
2016-07-22T12:00:28Z
[ "python", "mysql", "pip" ]
Python: Recursive Structs
38,524,949
<p>I have problem with <a href="https://thrift.apache.org/" rel="nofollow">thrift</a> code generator or python.</p> <p>Code sample (generated by thrift):</p> <pre><code>class SomeClass: spec = ( (1, (SomeClass, SomeClass.spec)), ) </code></pre> <p>Error message:</p> <pre><code>NameError: name 'SomeClass' is not defined </code></pre> <p>So I found <a href="https://issues.apache.org/jira/browse/THRIFT-2642" rel="nofollow">bug</a> in thrift jira (still opened since 2014). Suggested solution pretty bad.</p> <p>Can I avoid this problem somehow?</p> <p>In best case solution in *.thrift or *.py files, that can be changed before or after generation manually. </p>
0
2016-07-22T11:09:18Z
38,525,700
<p>Try to replace the code with the following code snippet, Note: it is using lists instead of tuples since tuples are immutable.</p> <pre><code>class SomeClass: spec = None @classmethod def init(cls): cls.spec = [] cls.spec.append( [ 1 , (cls, cls.spec) ] ) SomeClass.init() print( SomeClass.spec ) # [[1, (&lt;class SomeClass&gt;, [...])]] </code></pre> <p>Another solution without class methods</p> <pre><code>class SomeClass: spec = None SomeClass.spec = [] SomeClass.spec.append( [ 1 , (SomeClass, SomeClass.spec) ] ) print( SomeClass.spec ) # [[1, (&lt;class SomeClass&gt;, [...])]] </code></pre>
1
2016-07-22T11:48:20Z
[ "python", "recursion", "structure", "thrift" ]
Python: Recursive Structs
38,524,949
<p>I have problem with <a href="https://thrift.apache.org/" rel="nofollow">thrift</a> code generator or python.</p> <p>Code sample (generated by thrift):</p> <pre><code>class SomeClass: spec = ( (1, (SomeClass, SomeClass.spec)), ) </code></pre> <p>Error message:</p> <pre><code>NameError: name 'SomeClass' is not defined </code></pre> <p>So I found <a href="https://issues.apache.org/jira/browse/THRIFT-2642" rel="nofollow">bug</a> in thrift jira (still opened since 2014). Suggested solution pretty bad.</p> <p>Can I avoid this problem somehow?</p> <p>In best case solution in *.thrift or *.py files, that can be changed before or after generation manually. </p>
0
2016-07-22T11:09:18Z
38,527,916
<p>Seems, thats python's genered code contains useless field </p> <pre><code>SomeClass.spec </code></pre> <p>So i just delete it.</p> <p>I compared this with java generated code.</p> <p><strong>If someone will use my solution dont forget to change generated methods, thats check, when your spec!=None</strong> </p>
0
2016-07-22T13:37:56Z
[ "python", "recursion", "structure", "thrift" ]
Max tablename length with registerTempTable in Python
38,524,981
<p>I am a absolute novice in python and this is a very basic question to which I could not find an answer while searching.</p> <p>I am using <strong>registerTempTable</strong> function to register a dataframe as table, I wanted to check what is the max length there can be for the tablename? To test I used up to 70 characters and it did register the table, but for my own knowledge I wanted to know if there is any restriction on the length of the tablename.</p> <p>Thanks!!</p>
0
2016-07-22T11:10:48Z
38,537,603
<p>If you are working with a HiveContext, then the max length of a table name should be the max length allowed by Hive/Metastore (last time I checked, were 128 characters), probably the same thing happen with SqlContext.</p>
0
2016-07-23T02:36:45Z
[ "python", "pyspark" ]
Generate list of dictionaries without adjacent dictionary key/values equal
38,525,024
<p>I have a sorted list based on the value for key <code>name</code> as below:</p> <pre><code>s = [{'name': 'Bart', 'age': 12}, {'name': 'Bart', 'age': 19}, {'name': 'Bart', 'age': 1},{'name': 'Homer', 'age': 30}, {'name': 'Homer', 'age': 12},{'name': 'Simpson', 'age': 19}] </code></pre> <p>I want to arrange the elements of the list such that dictionaries with the same value for key <code>name</code> <strong>do not</strong> occur one after the other.</p> <p>Required output:</p> <pre><code>[{'name': 'Bart', 'age': 12}, {'name': 'Homer', 'age': 30}, {'name': 'Simpson', 'age': 19}, {'name': 'Bart', 'age': 19}, {'name': 'Homer', 'age': 12}, {'name': 'Bart', 'age': 1}] </code></pre> <p><strong>OR</strong></p> <pre><code>[{'name': 'Bart', 'age': 12}, {'name': 'Homer', 'age': 30}, {'name': 'Bart', 'age': 19}, {'name': 'Homer', 'age': 12}, {'name': 'Bart', 'age': 1},{'name': 'Simpson', 'age': 19}] </code></pre> <p>To get either one of the required outputs I tried using <code>map</code> and <code>lambda</code> The idea was to compare every <code>name</code> element with the next elements <code>name</code> and if they don't match, swap the values and return the resulting list.</p> <p>Below is the code which I was trying:</p> <pre><code>map(lambda x: x if x['name']!=next(iter(x))['name'] else None, s) </code></pre> <p>One thing that did not work is that <code>next(iter(x)</code> did not return the next element. I also want to know why and if the solution can be achieved using <code>map</code> and <code>lambda</code> ?</p>
0
2016-07-22T11:12:28Z
38,525,492
<p>I wrote this according to your requirements, though it is not as condensed:</p> <pre><code>s = [{'name': 'Bart', 'age': 12}, {'name': 'Bart', 'age': 19}, {'name': 'Bart', 'age': 1}, {'name': 'Homer', 'age': 30}, {'name': 'Homer', 'age': 12},{'name': 'Simpson', 'age': 19}] res=[] for m,n in zip(s, reversed(s)): if m!=n: res.append(m) res.append(n) else: res.append(m) if len(res)==len(s): break print res </code></pre> <p>It makes use of the fact that you already have the sorted list.</p>
1
2016-07-22T11:37:10Z
[ "python", "lambda" ]
Python Data Scraping
38,525,038
<p>Data Scraping in Pyhton. Code is working fine but it is showing the error which I mentioned below. What could be the reason?</p> <pre><code>import urllib2 from bs4 import BeautifulSoup from xlwt import workbook wb = Workbook() sheet1 = wb.add_sheet('Sheet1') soup = BeautifulSoup(urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_Indian_satellites").read()) for row in soup('table', {'class': 'wikitable sortable jquery-tablesorter’})[0].tbody('tr'): tds = row('td') sheet1.write(row, 0, tds[0].string) sheet2.write(row, 1, tds[1].string) wb.save('Performance Project.xls') </code></pre> <blockquote> <p>Error: File "ProcessingProject.py", line 12 SyntaxError: Non-ASCII character '\xe2' in file ProcessingProject.py on line 12</p> </blockquote> <p>but no encoding declared; see <a href="http://python.org/dev/peps/pep-0263/" rel="nofollow">http://python.org/dev/peps/pep-0263/</a> for details</p>
-1
2016-07-22T11:13:09Z
38,525,097
<pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- </code></pre> <p>Add this to top of your file</p>
0
2016-07-22T11:16:38Z
[ "python", "excel" ]
Python Data Scraping
38,525,038
<p>Data Scraping in Pyhton. Code is working fine but it is showing the error which I mentioned below. What could be the reason?</p> <pre><code>import urllib2 from bs4 import BeautifulSoup from xlwt import workbook wb = Workbook() sheet1 = wb.add_sheet('Sheet1') soup = BeautifulSoup(urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_Indian_satellites").read()) for row in soup('table', {'class': 'wikitable sortable jquery-tablesorter’})[0].tbody('tr'): tds = row('td') sheet1.write(row, 0, tds[0].string) sheet2.write(row, 1, tds[1].string) wb.save('Performance Project.xls') </code></pre> <blockquote> <p>Error: File "ProcessingProject.py", line 12 SyntaxError: Non-ASCII character '\xe2' in file ProcessingProject.py on line 12</p> </blockquote> <p>but no encoding declared; see <a href="http://python.org/dev/peps/pep-0263/" rel="nofollow">http://python.org/dev/peps/pep-0263/</a> for details</p>
-1
2016-07-22T11:13:09Z
38,525,127
<p>for row in soup('table', {'class': 'wikitable sortable jquery-tablesorter’})[0].tbody('tr'):</p> <p>You used a wrong character as single quote delimiter sign after jquery-tablesorter</p>
0
2016-07-22T11:18:31Z
[ "python", "excel" ]
Finding the maximum element with a recursive function
38,525,085
<p>I wrote a function that tries to find out what has the maximum value in a list:</p> <pre><code>def maxElement(L): length=len(L) if L[length-1]&gt;L[length-2]: del L[length-2] print L elif L[length-1]&lt;L[length-2]: del L[length-1] return L print maxElement([1,2,95754754745,3,1,8,444,2,42425]) </code></pre> <p>My output is wrong:</p> <pre><code>&gt;&gt;&gt; [1, 2, 95754754745L, 3, 1, 8, 444, 42425] [1, 2, 95754754745L, 3, 1, 8, 444, 42425] &gt;&gt;&gt; </code></pre> <p>It doesn't even delete for me what I've ask for. What did I do wrong? I can't get it!</p>
2
2016-07-22T11:16:08Z
38,525,222
<p>You are not calling your function again, which makes recursion impossible. Furthermore you have no base case which would stop recursion, which in this case would be:</p> <pre><code>if length == 1: return L </code></pre> <p>Here is the fixed code:</p> <pre><code>def maxElement(L): length=len(L) if length == 1: return L elif L[length-1]&gt;=L[length-2]: del L[length-2] elif L[length-1]&lt;=L[length-2]: del L[length-1] return maxElement(L) print maxElement([1,2,95754754745,3,1,8,444,2,42425]) </code></pre> <p>This outputs:</p> <pre><code>python recursive.py &gt; [95754754745L] </code></pre> <p>I also added <code>&lt;=</code> and <code>&gt;=</code> on the conditionals to avoid infinite recursion if there are two elements that share the maximum value.</p>
6
2016-07-22T11:24:13Z
[ "python", "list", "function" ]
Finding the maximum element with a recursive function
38,525,085
<p>I wrote a function that tries to find out what has the maximum value in a list:</p> <pre><code>def maxElement(L): length=len(L) if L[length-1]&gt;L[length-2]: del L[length-2] print L elif L[length-1]&lt;L[length-2]: del L[length-1] return L print maxElement([1,2,95754754745,3,1,8,444,2,42425]) </code></pre> <p>My output is wrong:</p> <pre><code>&gt;&gt;&gt; [1, 2, 95754754745L, 3, 1, 8, 444, 42425] [1, 2, 95754754745L, 3, 1, 8, 444, 42425] &gt;&gt;&gt; </code></pre> <p>It doesn't even delete for me what I've ask for. What did I do wrong? I can't get it!</p>
2
2016-07-22T11:16:08Z
38,525,233
<p>It did exactly what you asked it to do. </p> <p>Your function is not recursive as you forgot calling it again towards the end.</p> <p>Something like this is what you are looking for:</p> <pre><code>def maxElement(L): length=len(L) if L[length-1]&gt;L[length-2]: del L[length-2] print L elif L[length-1]&lt;L[length-2]: del L[length-1] if len(L) == 1: return L return maxElement(L) print maxElement([1,2,95754754745,3,1,8,444,2,42425]) </code></pre> <p>This would return:</p> <pre><code>[1, 2, 95754754745L, 3, 1, 8, 444, 42425] [1, 2, 95754754745L, 3, 1, 8, 42425] [1, 2, 95754754745L, 3, 1, 42425] [1, 2, 95754754745L, 3, 42425] [1, 2, 95754754745L, 42425] [1, 95754754745L] [95754754745L] [95754754745L] </code></pre> <p>I would make it a bit more better as follows:</p> <pre><code>def maxElement(L): length=len(L) if length == 1: # Have this condition on the top because you are using length - 2 later # Just return the only element return L if L[length-1] &gt; L[length-2]: # If the last element is greater than the last but one, delete the last but one del L[length - 2] else: # Simple else would suffice because you are just checking for the opposite # Also this condition saves you from: # infinite looping when the last two elements are equal del L[length - 1] print L # Time to call it recursively. # But if you just don't want to unnecessarily increase the recursion # tree depth, check for length and return it if length == 1: return L return maxElement(L) </code></pre>
6
2016-07-22T11:24:38Z
[ "python", "list", "function" ]
Finding the maximum element with a recursive function
38,525,085
<p>I wrote a function that tries to find out what has the maximum value in a list:</p> <pre><code>def maxElement(L): length=len(L) if L[length-1]&gt;L[length-2]: del L[length-2] print L elif L[length-1]&lt;L[length-2]: del L[length-1] return L print maxElement([1,2,95754754745,3,1,8,444,2,42425]) </code></pre> <p>My output is wrong:</p> <pre><code>&gt;&gt;&gt; [1, 2, 95754754745L, 3, 1, 8, 444, 42425] [1, 2, 95754754745L, 3, 1, 8, 444, 42425] &gt;&gt;&gt; </code></pre> <p>It doesn't even delete for me what I've ask for. What did I do wrong? I can't get it!</p>
2
2016-07-22T11:16:08Z
38,525,409
<p>Why are you not simply using max()?</p> <blockquote> <p>max([1,2,95754754745,3,1,8,444,2,42425])</p> <p>95754754745L</p> </blockquote>
2
2016-07-22T11:33:31Z
[ "python", "list", "function" ]
How to run background processes on Bluemix?
38,525,257
<p>I'm trying to get a really simple python program to run as a background process on IBM Bluemix as a CloudFoundry app.</p> <p>I've put it in a <a href="https://github.com/Zapaan/bluemix-bg-proc-test" rel="nofollow">Github repo</a>. There's a one-line req file because I find it easier than a setup.py and the python buildpack needs it to run.</p> <p>My complete use-case is that I have an API written with Django and I need an MQTT client that will run besides it to collect data from a broker (something with Watson IOT I think).</p> <p>I've tried to run both in the same CF app with a 2-lines Procfile looking like this :</p> <pre><code>web: gunicorn -e DJANGO_SETTINGS_MODULE=conf.dev conf.wsgi --workers 2 worker: python time.py </code></pre> <p>but the second process was just ignored.</p> <p>I've also tried in the current configuration, but with a Procfile containing only the second line and it was telling me that it couldn't find the start command.</p> <p>Now, with start command in the Manifest and <code>no-route</code> at <code>true</code>, either it doesn't pass the health check, or it just wait at the starting step until I get this error :</p> <pre><code>2016-07-22T13:10:36.671+0200 [LGR/null] err WebsocketListener.Start: Error connecting to a doppler server 2016-07-22T13:10:36.677+0200 [LGR/null] err proxy: error connecting to 159.8.128.238:8081: dial tcp 159.8.128.238:8081: getsockopt: connection refused </code></pre> <p>So, is there a way to run background tasks in Bluemix, if possible as standalone app (to scale and update more easily) ?</p> <p>EDIT : now it works, though I haven't changed anything besides a typo to format a string in my Python script, though the app crash just about every minute </p> <pre><code>Removing crash for app with id 3978a475-4dc6-495f-9662-a6fd562dc28a </code></pre>
0
2016-07-22T11:25:41Z
38,527,239
<p>Short answer to the question : a separate app with the <code>no-route</code> argument set to <code>true</code></p> <p>Ok, so I've apparently got it to work fully.</p> <p>I'm not sure what I've done but the problem might have come from the fact that I was asking for a 32M instance and the minimum seems to be 64M so Bluemix/CF wasn't so happy with my demand and crashed.</p> <p>I was using 128M in my older tries but I think I didn't put <code>no-route: true</code> at the time</p>
0
2016-07-22T13:06:15Z
[ "python", "ibm-bluemix", "cloudfoundry" ]
create_or_get with data from user input
38,525,530
<p>Trying to implement a user registration form on a website I can't make user input to be added as a new user to the database. I'm using Flask with Peewee, and have:</p> <pre><code>nUser ={ 'email': request.form['e_mail'], 'uname': request.form['username'], 'pword': request.form['password'], 'time': strftime('%Y-%m-%d %H:%M:%S') } nUser = User.create_or_get() </code></pre> <p>where nUser is temporary dict for new user. I should mention, that with <a href="http://peewee.readthedocs.io/en/latest/peewee/api.html#Model.create_or_get" rel="nofollow">the official peewee docs</a> I tried <code>nUser, created = User.create_or_get(nUser)</code> what returned an error of too many arguments. </p> <p>A code about <code>User</code> class is below (stored in separate .py, but there is <code>from models import *</code> up there):</p> <pre><code>class User(Model): email=TextField() uname=TextField(unique=True) pword=TextField() time=TextField() class Meta: database = db </code></pre> <p>Although it looks like it "works" from a webuser side, no record is added to the database. Previously I did it with <code>User.select().where(User.uname......</code> and it worked, but now I would like to switch to <code>create_or_get()</code> method since it would shorten my code and looks more efficient. Logging in for old users works, so the connection and access to the DB is fine. I would appreciate any hints.</p>
0
2016-07-22T11:39:29Z
38,525,732
<p>The official documentation that you link to show that <code>create_or_get</code> takes keyword arguments only. To pass a dict, you need to use the <code>**</code> syntax:</p> <pre><code>User.create_or_get(**nuser) </code></pre>
1
2016-07-22T11:49:38Z
[ "python", "flask", "peewee", "flask-peewee" ]
How to import java class, to Robot Framework like library
38,525,558
<p>I can't understand how to import .jar file, in Robot Framework.</p> <p>Here is the code:</p> <pre><code>*** Settings *** Library MyLibrary *** Test Cases *** My Test Do Nothing Hello world </code></pre> <p>and Java:</p> <pre><code>public class MyLibrary { public void hello(String name) { System.out.println("Hello, " + name + "!"); } public void doNothing() { } } </code></pre> <p>After Extracting in .jar, I put in C:\Python27\Lib\site-packages\MyLibrary and I created empty <code>__init__.py</code> file. After I execute my Robot file with: <code>pybot TestJavaLibrary.robot</code> I get this WARN:</p> <pre><code>[ WARN ] Imported library 'MyLibrary' contains no keywords. ============================================================================== TestJavaLibrary ============================================================================== My Test | FAIL | No keyword with name 'Do Nothing' found. </code></pre> <p>How to use this jar, like external library?</p>
0
2016-07-22T11:41:01Z
38,535,672
<p>You have to use jython (jybot). There are other settings like JYTHONPATH.</p>
0
2016-07-22T21:43:23Z
[ "java", "python", "robotframework" ]
generate a qr code in pyramid view, return it without writing to disk
38,525,722
<p>I have a pyramid view that needs to generate a qr code and return it as an image to the user. I want to avoid storing the image, I want to just generate it, send it and forget about it.</p> <p>The first thing I tried was something like this:</p> <pre><code>oRet = StringIO.StringIO() oQR = pyqrcode.create('yo mamma') oQR.svg(oRet, scale=8) return Response(body = oRet.read(), content_type="image/svg") </code></pre> <p>But this generates an svg file that can't be opened.</p> <p>Looking a little closer:</p> <pre><code>oRet = StringIO.StringIO() oQR = pyqrcode.create('yo mamma') oQR.eps(oRet, scale=8) with open('test.eps','w') as f: # cant display image in file f.write(oRet.read()) with open('test2.eps','w') as f: # image file works fine oQR.eps(f, scale=8) oQR.svg(oRet, scale=8) with open('test.svg','w') as f: # cant display image in file f.write(oRet.read()) with open('test2.svg','w') as f: # image file works fine oQR.svg(f, scale=8) oQR.png(oRet) with open('test.png','w') as f: # cant display image f.write(oRet.read()) with open('test2.png','w') as f: #works oQR.png(f) # works with open('test3.png','w') as f: f.write(oQR.png_as_base64_str()) #doesn't work </code></pre> <p>So my question is: How do I return a newly generated qr code as a pyramid response without storing it on disk? I don't mind too much what format the image is in</p>
0
2016-07-22T11:49:13Z
38,529,362
<p>we have a winner:</p> <pre><code>oRet = StringIO.StringIO() oQR = pyqrcode.create('yo mamma') oQR.png(oRet, scale=8) oResp = Response(body = oRet.getvalue(), content_type="image/png",content_disposition='attachment; filename="yummy.png"') return oResp </code></pre> <p>The trick was to use <code>oRet.getvalue()</code> instead or <code>oRet.read()</code></p>
0
2016-07-22T14:46:53Z
[ "python", "response", "qr-code", "pyramid" ]
Variable scope in Python higher-order functions
38,525,774
<p>I am looking at some learning material here: <a href="http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators" rel="nofollow">http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators</a></p> <p>Particularly the <code>Memoize</code> section, in which the following code is used as an example for higher-order functions:</p> <pre><code>def memoize(f): cache = {} def g(x): if x not in cache: cache[x] = f(x) return cache[x] return g </code></pre> <p>It was my understanding that the function returned by memoize would not have access to the "cache" variable since it is out of scope of the definition of "g".</p> <p>Eg. if I do <code>result_function = memoize(some_function)</code> that <code>result_function</code> would have no knowledge of any <code>cache</code> variable since it is declared outside the <code>g</code> function and the <code>g</code> function alone is returned. Why does it work, and not throw an error?</p>
0
2016-07-22T11:52:11Z
38,526,343
<p>the cache object and g(x) object both have the same scope as they are both objects in the memoize function. This means that g(x) will have access to cache because they are both objects scoped in the memoize function.</p>
0
2016-07-22T12:23:28Z
[ "python", "higher-order-functions" ]
Variable scope in Python higher-order functions
38,525,774
<p>I am looking at some learning material here: <a href="http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators" rel="nofollow">http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators</a></p> <p>Particularly the <code>Memoize</code> section, in which the following code is used as an example for higher-order functions:</p> <pre><code>def memoize(f): cache = {} def g(x): if x not in cache: cache[x] = f(x) return cache[x] return g </code></pre> <p>It was my understanding that the function returned by memoize would not have access to the "cache" variable since it is out of scope of the definition of "g".</p> <p>Eg. if I do <code>result_function = memoize(some_function)</code> that <code>result_function</code> would have no knowledge of any <code>cache</code> variable since it is declared outside the <code>g</code> function and the <code>g</code> function alone is returned. Why does it work, and not throw an error?</p>
0
2016-07-22T11:52:11Z
38,526,815
<p>the <code>def memoize():</code> line introduces a new scope. the <code>g</code> function code 'sees' the scope of its enclosing function. Sure do look into this question's answers: <a href="http://stackoverflow.com/q/291978/6610">Short Description of Python Scoping Rules</a>.</p> <p>So no: that's not an error! It's a very nice feature.</p>
1
2016-07-22T12:44:41Z
[ "python", "higher-order-functions" ]
Return response during multi if in python
38,525,779
<p>I'm doing a <a href="http://flask.pocoo.org/docs/0.11/testing/" rel="nofollow">unit testing</a>, I'm checking fields in two databases collections so during it I have to do a multi if conditions like this:</p> <pre><code>for doc1,doc2 in itertools.izip(docs1, docs2): if ... : if ... : response = 'Error' else: response = 'OK' else... : if ... : response = 'Error' else: response = 'OK' if ... : if ... : response = 'Error' else ... : response = 'OK' else ... : if ... : response = 'Error' else ... : response = 'OK' </code></pre> <p>so I want to assert a response if the error happened in one of this ifs, to give an answer like this: <code>self.assert400(response, message="Bad request, empty body.")</code> </p> <p>and when the whole process is okay to give an Ok response.</p> <p>All I want is to avoid writing this:</p> <pre><code> if ... : if ... : self.assert400(response, message="Bad request, empty body.") else: self.assert200(response, message="OK.") else... : if ... : self.assert400(response, message="Bad request, empty body.") else: self.assert200(response, message="OK.") </code></pre> <p>So what to achieve this?</p> <p>I thought to create an if condition in the end of it but that wouldn't stop the for loop?Please help me?</p>
-3
2016-07-22T11:52:34Z
38,526,694
<p>In this case you should consider using a default value and only checking for the error case:</p> <pre><code>response = "OK" # default value for doc1,doc2 in itertools.izip(docs1, docs2): if ... : if ... : response = "Error" else... : if ... : response = "Error" if response == "Error": break # If no errors were found, then the result must be OK if response == "Error": self.assert400(response, message="Bad request, empty body.") else: self.assert200(response, message="OK.") </code></pre> <p>This achieves that only one error is enough to make the whole thing fail. I am a bit unclear on what you actually want to do, so do comment if this is not what you expected.</p>
0
2016-07-22T12:39:43Z
[ "python", "unit-testing", "flask" ]
Return response during multi if in python
38,525,779
<p>I'm doing a <a href="http://flask.pocoo.org/docs/0.11/testing/" rel="nofollow">unit testing</a>, I'm checking fields in two databases collections so during it I have to do a multi if conditions like this:</p> <pre><code>for doc1,doc2 in itertools.izip(docs1, docs2): if ... : if ... : response = 'Error' else: response = 'OK' else... : if ... : response = 'Error' else: response = 'OK' if ... : if ... : response = 'Error' else ... : response = 'OK' else ... : if ... : response = 'Error' else ... : response = 'OK' </code></pre> <p>so I want to assert a response if the error happened in one of this ifs, to give an answer like this: <code>self.assert400(response, message="Bad request, empty body.")</code> </p> <p>and when the whole process is okay to give an Ok response.</p> <p>All I want is to avoid writing this:</p> <pre><code> if ... : if ... : self.assert400(response, message="Bad request, empty body.") else: self.assert200(response, message="OK.") else... : if ... : self.assert400(response, message="Bad request, empty body.") else: self.assert200(response, message="OK.") </code></pre> <p>So what to achieve this?</p> <p>I thought to create an if condition in the end of it but that wouldn't stop the for loop?Please help me?</p>
-3
2016-07-22T11:52:34Z
38,527,076
<p>It seems to me that you're not really unit-testing. The structure in your function and unit test are exactly the same. So if your code change the test will have to change too. I don't think that testing the "=" operator is worth your time. </p> <p>I could be wrong but I think you should have a function taking doc1 and doc2 and returning a response. Then you unit test the return value for specific imput value. Something like this :</p> <pre><code>result = foo(doc1,doc2) self.assert_equal(result.message, "Bad request, empty body.") result = foo(doc3,doc4) self.assert_equal(result.message, "OK.") </code></pre> <p>In general, making your code "unit-testable" makes it better.</p>
0
2016-07-22T12:57:27Z
[ "python", "unit-testing", "flask" ]
PyQt QWidget destructor error `AttributeError: 'NoneType' object has no attribute 'path'`
38,525,796
<p>I use a custom widget inheriting from <code>QWidget</code>. This widget may use an online resource: a picture I download from the internet and store in a local file before displaying it in a <code>QLabel</code> instance.</p> <p>When the user closes the window I want the local file to be deleted so I changed the destructor to:</p> <pre><code>def __del__(self): if os.path.isfile( self.pictureFilename): os.remove( self.pictureFilename) </code></pre> <p>I have:</p> <pre><code>import os </code></pre> <p>at the beginning of my script. Strangely, when the main application closes I get the error:</p> <blockquote> <p>Traceback (most recent call last):</p> <p>File "/home/XXX/XXX/XXX.py", line 103, in <strong>del</strong></p> <p>AttributeError: 'NoneType' object has no attribute 'path'</p> </blockquote> <p>It looks like the library gets garbage collected before the destructor gets called. I do not see how to fix that.</p>
0
2016-07-22T11:53:39Z
38,531,458
<p>Looking at the github code, the problem seems to be that when the widget is closed, the Qt application terminate and sys.exit() is called, so probably the module is garbage collected before<code>__del__</code> call.</p> <p>there:</p> <pre><code>if __name__ == '__main__': app = QApplication( sys.argv) url = "http://www.transfermarkt.co.uk/cristiano-ronaldo/profil/spieler/8198" ex = PlayerWindow( url) sys.exit( app.exec_()) </code></pre> <p>To avoid the problem I suggest to use the <code>closeEvent(event)</code> form QWidget <a href="http://doc.qt.io/qt-5/qwidget.html#closeEvent" rel="nofollow">http://doc.qt.io/qt-5/qwidget.html#closeEvent</a></p> <p>replace yours <code>__del__</code> function with this:</p> <pre><code>def closeEvent(self, event): if os.path.isfile( self.pictureFilename): os.remove( self.pictureFilename) del self.profile del self.pictureLabel </code></pre> <p>As a general rule you should try to avoid using <code>__del__</code> to automatically finalize object with garbage-collection without <code>del object</code> begin called explicitly in your code.</p>
2
2016-07-22T16:36:22Z
[ "python", "python-3.x", "debugging", "pyqt" ]
Use the same browser session for multiple tests with Selenium Pytest
38,525,925
<p>I want to be able to use the same browser session for multiple tests within the same test file.</p> <p>I have a class set up for the login:</p> <pre><code>class Loginpage (): url="http://appsv01:8084/#/" def __init__(self, workbook): self.workbook=workbook def login(self,value_Name,worksheet): #Open a new mymobile suite window in Chrome and maximize driver = webdriver.Chrome('C:/temp/chromedriver.exe') driver.get("http://appsv01:8084") driver.maximize_window() </code></pre> <p>I've been closing the browser session and then opening a new one per test, but I tried changing it so that the structure looks like (in the file called test_mytests.py):</p> <pre><code> #open the browser and log in mylogin=Loginpage('C:\Automation\Common_Objects.xlsx') driver=mylogin.login("AutoSMS", "Users") #perform the first test def test_one(): task1 task2 #perform the second test def test_two(): task3 task4 </code></pre> <p>This fails with the error:</p> <pre><code>E ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it </code></pre> <p>If I put the code for #open the browser under each test individually, then everything works fine. Is it possible to only open the browser once and have all the tests in the file work on that same browser session?</p>
0
2016-07-22T12:01:14Z
38,526,945
<p>You could pass the driver object to the function calls:</p> <pre><code> #open the browser driver = webdriver.Chrome('C:/temp/chromedriver.exe') driver.get("http://appsv01:8084") driver.maximize_window() #perform the first test def test_one(driver): #do something with driver here, e.g. driver.find_element_by_id('test').click() #perform the second test def test_two(driver): task3 task4 #function calls test_one(driver) test_two(driver) #close driver driver.close() </code></pre>
0
2016-07-22T12:50:56Z
[ "python", "selenium" ]
Accessing user home directory from django
38,525,997
<p>I'm creating a Django app who can access to the user home directory. For this purpose I want to create a directory using something like <code>os.mkdir('/home/user/new_directory')</code> or a <em>subprocess</em> command.</p> <p>Because Django is started by an apache server, python act as the apache user and can't access to my users home directories.</p> <p>Currently, I know the login of my users because they have to be logged on the website. Is there a solution to <strong>perform unix commands from Django/Python in the name of the user</strong> ?</p>
3
2016-07-22T12:04:54Z
38,527,243
<p>You can set the home directories via <code>MEDIA_URL</code> /or symlink itself. I think of a combined aproach of symlink and os.system calls.</p> <p><a href="http://unix.stackexchange.com/questions/68368/what-is-symlinking-and-how-can-learn-i-how-to-to-do-this">what-is-symlinking-and-how-can-learn-i-how-to-to-do-this</a></p> <p>To change the apache user, use <code>os.system(su &lt;command&gt;)</code> <a href="http://stackoverflow.com/questions/8025294/changing-user-in-python">changing-user-in-python</a></p>
0
2016-07-22T13:06:30Z
[ "python", "django", "unix", "authentication", "subprocess" ]
How to post to Google+?
38,526,066
<p>I want to make some application (Google App Engine) which will be fetching some data from other websites and post them in one of my "collections" in Google+.</p> <p>For now I have this code: main.py</p> <pre><code># -*- coding: utf-8 -*- import webapp2 import httplib2 from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials class UpdateChannelTask(webapp2.RequestHandler): def get(self): self.add_news() def add_news(self): credentials = ServiceAccountCredentials.from_json_keyfile_name( 'my_project.json', ( 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.stream.write' ) ) delegate_credentials = credentials.create_delegated('my_email@gmail.com') http = httplib2.Http() http = delegate_credentials.authorize(http) service = build( 'plusDomains', 'v1', http=http) service.activities().insert( userId='me', preview=True, body={ 'object': { 'originalContent': 'Test, my first post in Google+!' }, 'access': { 'items': [{ 'type': 'domain' }], 'domainRestricted': True } }).execute() app = webapp2.WSGIApplication( routes=[ (r'/update', UpdateChannelTask), ], debug=True ) </code></pre> <p>but this does not work, I get error</p> <pre><code>HttpError: &lt;HttpError 403 when requesting https://www.googleapis.com/plusDomains/v1/people/me/activities?alt=json&amp;preview=true returned "Forbidden"&gt; </code></pre> <p>How can my app gain right to post to my Google+ collection?</p> <p>//edit Am I understand this <a href="https://developers.google.com/+/domains/authentication/delegation" rel="nofollow">document</a> correctly? I need to have paid account "Google for Work" to solve my problem?</p> <p>Everything I do I do according to <a href="https://developers.google.com/+/domains/quickstart/python" rel="nofollow">link</a>. In section Delegate domain-wide authority to your service account I have to go to URL <a href="https://www.google.com/a/cpanel/my_app.appspot.com" rel="nofollow">https://www.google.com/a/cpanel/my_app.appspot.com</a> and setup something. Attempt to go there gives me screen with "You need a Google for Work account for my_app.appspot.com to login. Learn more". So I need "Google for Work"?</p>
3
2016-07-22T12:08:47Z
38,526,485
<p>You have to add the scope `<a href="https://www.googleapis.com/auth/plus.stream.write" rel="nofollow">https://www.googleapis.com/auth/plus.stream.write</a> <a href="https://www.googleapis.com/auth/plus.me" rel="nofollow">https://www.googleapis.com/auth/plus.me</a> for writing the post to google+ account.By authorizing google+ using this scope, you are get the authorization token to post in google+ .</p>
0
2016-07-22T12:30:30Z
[ "python", "google-app-engine", "google-api", "google-plus", "google-plus-domains" ]
How to post to Google+?
38,526,066
<p>I want to make some application (Google App Engine) which will be fetching some data from other websites and post them in one of my "collections" in Google+.</p> <p>For now I have this code: main.py</p> <pre><code># -*- coding: utf-8 -*- import webapp2 import httplib2 from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials class UpdateChannelTask(webapp2.RequestHandler): def get(self): self.add_news() def add_news(self): credentials = ServiceAccountCredentials.from_json_keyfile_name( 'my_project.json', ( 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.stream.write' ) ) delegate_credentials = credentials.create_delegated('my_email@gmail.com') http = httplib2.Http() http = delegate_credentials.authorize(http) service = build( 'plusDomains', 'v1', http=http) service.activities().insert( userId='me', preview=True, body={ 'object': { 'originalContent': 'Test, my first post in Google+!' }, 'access': { 'items': [{ 'type': 'domain' }], 'domainRestricted': True } }).execute() app = webapp2.WSGIApplication( routes=[ (r'/update', UpdateChannelTask), ], debug=True ) </code></pre> <p>but this does not work, I get error</p> <pre><code>HttpError: &lt;HttpError 403 when requesting https://www.googleapis.com/plusDomains/v1/people/me/activities?alt=json&amp;preview=true returned "Forbidden"&gt; </code></pre> <p>How can my app gain right to post to my Google+ collection?</p> <p>//edit Am I understand this <a href="https://developers.google.com/+/domains/authentication/delegation" rel="nofollow">document</a> correctly? I need to have paid account "Google for Work" to solve my problem?</p> <p>Everything I do I do according to <a href="https://developers.google.com/+/domains/quickstart/python" rel="nofollow">link</a>. In section Delegate domain-wide authority to your service account I have to go to URL <a href="https://www.google.com/a/cpanel/my_app.appspot.com" rel="nofollow">https://www.google.com/a/cpanel/my_app.appspot.com</a> and setup something. Attempt to go there gives me screen with "You need a Google for Work account for my_app.appspot.com to login. Learn more". So I need "Google for Work"?</p>
3
2016-07-22T12:08:47Z
39,765,266
<p>Yes, you need to have a Work Account. Unfortunately the Google Plus Pages API is not open to the public. You can send a request to sign up <a href="https://developers.google.com/+/api/pages-signup" rel="nofollow">here</a>. </p> <p>That's why you get the <strong>HTTP 403 Forbidden</strong> error, which means that server got your request, but refused to take the action you requiered.</p> <p>So you can't automatically post to Google+ without a Work account. When you have one, you can either use <a href="https://developers.google.com/+/api/latest/moments/insert" rel="nofollow">moments.insert</a> (to be inserted programmatically), or with the <a href="https://developers.google.com/+/web/share/" rel="nofollow">embeddable share button</a>.</p>
3
2016-09-29T08:32:16Z
[ "python", "google-app-engine", "google-api", "google-plus", "google-plus-domains" ]
how to shift single value of a pandas dataframe column
38,526,122
<p>Using pandas <code>first_valid_index()</code> to get index of first non-null value of a column, how can I shifta single value of column rather than the whole column. i.e.</p> <pre><code>data = {'year': [2010, 2011, 2012, 2013, 2014, 2015, 2016,2017, 2018, 2019], 'columnA': [10, 21, 20, 10, 39, 30, 31,45, 23, 56], 'columnB': [None, None, None, 10, 39, 30, 31,45, 23, 56], 'total': [100, 200, 300, 400, 500, 600, 700,800, 900, 1000]} df = pd.DataFrame(data) df = df.set_index('year') print df columnA columnB total year 2010 10 NaN 100 2011 21 NaN 200 2012 20 NaN 300 2013 10 10 400 2014 39 39 500 2015 30 30 600 2016 31 31 700 2017 45 45 800 2018 23 23 900 2019 56 56 1000 for col in df.columns: if col not in ['total']: idx = df[col].first_valid_index() df.loc[idx, col] = df.loc[idx, col] + df.loc[idx, 'total'].shift(1) print df AttributeError: 'numpy.float64' object has no attribute 'shift' </code></pre> <p>desired result:</p> <pre><code>print df columnA columnB total year 2010 10 NaN 100 2011 21 NaN 200 2012 20 NaN 300 2013 10 310 400 2014 39 39 500 2015 30 30 600 2016 31 31 700 2017 45 45 800 2018 23 23 900 2019 56 56 1000 </code></pre>
3
2016-07-22T12:11:21Z
38,526,268
<p>is that what you want?</p> <pre><code>In [63]: idx = df.columnB.first_valid_index() In [64]: df.ix[idx, 'columnB'] += df.total.shift().ix[idx] In [65]: df Out[65]: columnA columnB total year 2010 10 NaN 100 2011 21 NaN 200 2012 20 NaN 300 2013 10 310.0 400 2014 39 39.0 500 2015 30 30.0 600 2016 31 31.0 700 2017 45 45.0 800 2018 23 23.0 900 2019 56 56.0 1000 </code></pre>
2
2016-07-22T12:19:37Z
[ "python", "pandas", "dataframe" ]
how to shift single value of a pandas dataframe column
38,526,122
<p>Using pandas <code>first_valid_index()</code> to get index of first non-null value of a column, how can I shifta single value of column rather than the whole column. i.e.</p> <pre><code>data = {'year': [2010, 2011, 2012, 2013, 2014, 2015, 2016,2017, 2018, 2019], 'columnA': [10, 21, 20, 10, 39, 30, 31,45, 23, 56], 'columnB': [None, None, None, 10, 39, 30, 31,45, 23, 56], 'total': [100, 200, 300, 400, 500, 600, 700,800, 900, 1000]} df = pd.DataFrame(data) df = df.set_index('year') print df columnA columnB total year 2010 10 NaN 100 2011 21 NaN 200 2012 20 NaN 300 2013 10 10 400 2014 39 39 500 2015 30 30 600 2016 31 31 700 2017 45 45 800 2018 23 23 900 2019 56 56 1000 for col in df.columns: if col not in ['total']: idx = df[col].first_valid_index() df.loc[idx, col] = df.loc[idx, col] + df.loc[idx, 'total'].shift(1) print df AttributeError: 'numpy.float64' object has no attribute 'shift' </code></pre> <p>desired result:</p> <pre><code>print df columnA columnB total year 2010 10 NaN 100 2011 21 NaN 200 2012 20 NaN 300 2013 10 310 400 2014 39 39 500 2015 30 30 600 2016 31 31 700 2017 45 45 800 2018 23 23 900 2019 56 56 1000 </code></pre>
3
2016-07-22T12:11:21Z
38,526,494
<p>You can filter all column names, where is least one <code>NaN</code> value and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.union.html" rel="nofollow"><code>union</code></a> with column <code>total</code>:</p> <pre><code>for col in df.columns: if col not in pd.Index(['total']).union(df.columns[~df.isnull().any()]): idx = df[col].first_valid_index() df.loc[idx, col] += df.total.shift().loc[idx] print (df) columnA columnB total year 2010 10 NaN 100 2011 21 NaN 200 2012 20 NaN 300 2013 10 310.0 400 2014 39 39.0 500 2015 30 30.0 600 2016 31 31.0 700 2017 45 45.0 800 2018 23 23.0 900 2019 56 56.0 1000 </code></pre>
1
2016-07-22T12:31:12Z
[ "python", "pandas", "dataframe" ]
How to draw a coordinate system on top of an image using tkinter?
38,526,285
<p>I want to show an image and draw a coordinate system(x-axe, y-axe) on top of it. I can show the image</p> <pre><code>img = ImageTk.PhotoImage(Image.open(path).resize((400,400),Image.ANTIALIAS)) panel = tk.Label(root,image = img, width = 400, height = 400s) panel.pack(size= "bottom", fill = "both", expand = "yes") panel.place(rely = 073, rely = 0.5s) </code></pre> <p>I can also draw a line for the x-axe/y-axe(it would be even better if you know a way to draw a flash instead of a line)</p> <pre><code>canvas = Canvas(root) canvas.create_line(x0,y0,x1,y1) canvas.pack() </code></pre> <p>What I cannot do is <strong>place this line on top of the image</strong>. I tried using canvas.place(), but when I put it on top of the image I cannot see the image anymore. Is there a way to make the canvas transparent ? Or is there something else I can do ? I'm new to Tkinter.</p> <p>Thanks.</p> <p>EDIT: apparently it is not possible to make a canvas transparent <a href="http://stackoverflow.com/questions/17392365/transparent-canvas-in-tkinter-python">Transparent canvas in tkinter python</a></p> <p>But can I add a background image in the canvas and then draw the line, so that I can see both ? </p>
1
2016-07-22T12:20:42Z
38,527,334
<p>You have to place the image on the canvas and then put the axis lines on top of it:</p> <pre><code>import Tkinter as tk from PIL import Image, ImageTk root = tk.Tk() img_path = 'water-drop-splash.png' img = ImageTk.PhotoImage(Image.open(img_path).resize((400,400), Image.ANTIALIAS)) canvas = tk.Canvas(root, height=400, width=400) canvas.create_image(200, 200, image=img) canvas.create_line(0, 200, 399, 200, dash=(2,2)) # x-axis canvas.create_line(200, 0, 200, 399, dash=(2,2)) # y-axis canvas.pack() root.mainloop() </code></pre> <p>Ta-da!</p> <p><a href="http://i.stack.imgur.com/rESbg.png" rel="nofollow"><img src="http://i.stack.imgur.com/rESbg.png" alt="screenshot of tkinter window displaying image and axes"></a></p>
3
2016-07-22T13:10:29Z
[ "python", "canvas", "tkinter" ]
How to find frequency of a square wave using FFT
38,526,289
<p>In the FFT (second) plot, I am expecting a bigger peak at frequency = 1.0, compared to other frequencies, since it is a 1 Hz Square Wave signal sampled at 5Hz. </p> <p><em>I am a beginner at this, possibly missing something silly here</em> Here's what I have done:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from scipy import signal t500 = np.linspace(0,5,500,endpoint=False) s1t500 = signal.square(2*np.pi*1.0*t500) </code></pre> <p>First plot shows 1 Hz Square Wave sampled at 5Hz for 5 seconds:</p> <pre><code>t5 = np.linspace(0,5,25,endpoint=False) t5 = t5 + 1e-14 s1t5 = signal.square(2.0*np.pi*1.0*t5) plt.ylim(-2,2); plt.plot(t500,s1t500,'k',t5,s1t5,'b',t5,s1t5,'bo'); plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/tlbqc.png" rel="nofollow"><img src="http://i.stack.imgur.com/tlbqc.png" alt="1 Hz Square Wave sampled at 5Hz"></a></p> <p>Here in the Second plot, I am expecting the magnitude at f=1 Hz to be more than at f=2. Am I missing something ?</p> <pre><code>y1t5 = np.fft.fft(s1t5) ff1t5 = np.fft.fftfreq(25,d=0.2) plt.plot(ff1t5,y1t5); plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/cjO6l.png" rel="nofollow"><img src="http://i.stack.imgur.com/cjO6l.png" alt="FFT for 1 Hz Square Wave sampled at 5Hz"></a></p>
2
2016-07-22T12:20:54Z
38,527,464
<p>It seems you missed the fact that Fourier transform produces functions (or sequences of numbers in case of DFT/FFT) in complex space:</p> <pre><code>&gt;&gt;&gt; np.fft.fft(s1t5) [ 5. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 5.-15.38841769j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 5. +3.63271264j 0. +0.j 0. +0.j 0. +0.j 0. +0.j # and so on </code></pre> <p>In order to see the amplitude spectrum on your plot, apply <code>np.absolute</code> or <code>abs</code>:</p> <pre><code>&gt;&gt;&gt; np.absolute(np.fft.fft(s1t5)) [ 5. 0. 0. 0. 0. 16.18033989 0. 0. 0. 0. 6.18033989 0. 0. 0. 0. 6.18033989 0. 0. 0. 0. 16.18033989 0. 0. 0. 0. ] </code></pre> <p>Otherwise only real part will be shown.</p>
3
2016-07-22T13:16:11Z
[ "python", "numpy", "scipy", "fft" ]
How to measure runtime in web.py?
38,526,308
<p>I created a python webserver with web.py. This webserver works fine. But I will get the infromation how long the webserver needs to get the result from the database and send it back to the client.</p> <p>Can I realize that with the modul timeit? Does someone has an idea?</p>
0
2016-07-22T12:21:34Z
38,526,659
<p>You can use <a href="http://webpy.org/docs/0.3/api#web.http" rel="nofollow"><code>web.profiler</code></a> middleware to display some profiling information within each response.</p> <pre><code>application = web.application(urls, globals(), web.profiler) </code></pre> <p>If that information isn't enough, you could use <a href="https://docs.python.org/2/library/profile.html#module-cProfile" rel="nofollow"><code>cProfile</code></a> to run your app and this will give you more detailed information.</p> <pre><code>import cProfile cProfile.run("application.run()") </code></pre>
0
2016-07-22T12:38:30Z
[ "python", "web.py", "web-frameworks" ]
Image in label not appearing in secondary window (tkinter)
38,526,809
<p>I am trying to display an image inside of a label in a second Tkinter window. In my main window (window), the images are displayed perfectly, but when I write the same code to appear inside of the second window (root), the code executes, but you cannot see the image, only blank space.</p> <p>Any help would be greatly appreciated!</p> <p>Here is my relevant code:</p> <pre><code># Create a variable assigned to the location of the main image, and then change its proportions (the higher the number/s, the smaller) finance_news_image1 = PhotoImage(file = 'C:\\Users\\user\\Projects\\project\\x\\y\\z\\finance news.gif') finance_news_image2 = finance_news_image1.subsample(1, 1) # Create a variable for the main image of the menu, and define its placement within the grid main_photo = Label(root, image = finance_news_image2) root.main_photo = main_photo main_photo.grid(row = 4, column = 0) </code></pre>
1
2016-07-22T12:44:28Z
38,527,181
<p>You wrongly kept the reference to the image. This means you need to change this line:</p> <pre><code>root.main_photo = main_photo </code></pre> <p>To:</p> <pre><code>main_photo.image = finance_news_image2 </code></pre>
1
2016-07-22T13:03:09Z
[ "python", "python-3.x", "tkinter" ]
Understanding Numeric Datatype in SqlAlchemy
38,526,826
<p>I have a class</p> <pre><code>class vw_invoice_header(db.Model): __tablename__ = "vw_invoice_header" tax_amount = db.column(db.Numeric) total_price = db.column(db.Numeric) invc_number = db.Column(db.String(40)) term_code = db.Column(db.String(20)) order_date = db.Column(db.Date) airway_bill = db.Column(db.String(40)) inh_auto_key = db.Column(db.Integer,primary_key=True) </code></pre> <p>Now I get a result from an oracle db as below</p> <pre><code>invc = vw_invoice_header.query.filter_by(inh_auto_key=20643519).first() </code></pre> <p>I'm trying to use the value below to get a nicely formatted price in my jinja2 template</p> <pre><code>"{:8,.2f}".format(invc.total_price) </code></pre> <p>This throws an error, AttributeError: type object 'Numeric' has no attribute 'lower' I have no idea how to just print out this numeric :/ Im a newb to python been using it for a week.</p> <p>Thanks Cameron</p>
0
2016-07-22T12:45:11Z
38,527,030
<p>Your first two fields should be <code>db.Column</code> not <code>db.column</code> (note the capitalization). <code>db.column</code> creates a <code>sqlalchemy.sql.elements.ColumnClause</code> object whereas <code>db.Column</code> creates a <code>sqlalchemy.sql.schema.Column</code> object like you want.</p> <pre><code>class vw_invoice_header(db.Model): __tablename__ = "vw_invoice_header" tax_amount = db.Column(db.Numeric) total_price = db.Column(db.Numeric) invc_number = db.Column(db.String(40)) term_code = db.Column(db.String(20)) order_date = db.Column(db.Date) airway_bill = db.Column(db.String(40)) inh_auto_key = db.Column(db.Integer,primary_key=True) </code></pre> <p>Once you correct this, the <code>Numeric</code> datatype will behave just as you expect.</p>
1
2016-07-22T12:55:25Z
[ "python", "sqlalchemy" ]
embed ipython notebook in sphinx document
38,526,888
<p>I am writing the API document for my own project. And I found that this cool <a href="http://yt-project.org/doc/quickstart/data_objects_and_time_series.html" rel="nofollow">documentation</a> (yt project) uses ipython notebook directly to give example. When I looked into their documentation repo on bitbucket, one relevant rst seemed quite simple as: </p> <pre><code>.. notebook:: An_example_notebook.ipynb </code></pre> <p>But, of course, it didn't work for me. I am not sure if the "notebook" is an intrinsic block type or not. Maybe the 'notebook' block requires an external package. Actually, I got zero result when I searched for "notebook" in the sphinx documentation.</p> <p>If I can use my notebooks directly (without converting) to give examples, that will make life much easier. But I can't figure out how I can achieve that. </p>
1
2016-07-22T12:48:22Z
38,530,400
<p><code>nbsphinx</code> is a Sphinx extension that provides a source parser for <code>*.ipynb</code> files. </p> <p>To Install nbsphinx:</p> <pre><code>pip install nbsphinx --user </code></pre> <p>Edit your <code>conf.py</code> and add <code>'nbsphinx'</code> to extensions.</p> <p>Edit your <code>index.rst</code> and add the names of your <code>*.ipynb</code> files to the <code>toctree</code>.</p> <p>Follow This <a href="http://nbsphinx.readthedocs.io/en/0.2.8/rst.html" rel="nofollow">Link</a> after the above thing you do </p> <p>Run Sphinx!</p>
1
2016-07-22T15:35:45Z
[ "python", "ipython-notebook", "python-sphinx" ]
Cannot extract URL of plotly charts (to be embedded into html reports)
38,526,899
<p>I am trying to print the URL for a plotly chart.</p> <p>The command:</p> <pre><code>plot_url = py.iplot(fig, filename= 'chart name',auto_open=False) print plot_url </code></pre> <p>returns:</p> <pre><code>plotly.tools.PlotlyDisplay object&gt; </code></pre> <p>rather than:</p> <pre><code>https://plot.ly/23/~andrea.botti/ </code></pre> <p>Any idea why that happens? This is preventing me from embedding the chart into a script that automatically generates a html report when a chart is made.</p>
0
2016-07-22T12:48:39Z
38,662,339
<p>I think I've found the answer. The issue was that I was using <code>py.iplot</code> instead of <code>py.plot</code>.</p> <p>Changing the code to:</p> <pre><code>plot_url = py.plot(fig, filename= 'chart name',auto_open=False) print plot_url </code></pre> <p>outputs the correct url.</p>
0
2016-07-29T15:22:43Z
[ "python", "embed", "plotly" ]
How to execute if else unix command from python and get ret value
38,526,908
<p>Following is the code which I am trying to execute using python</p> <pre><code>from subprocess import Popen, PIPE cmd = 'if (-e "../a.txt") then \n ln -s ../a.txt . \n else \n echo "file is not present " \n endif' ret_val = subprocess.call(cmd,shell="True") </code></pre> <p>When executed gives following error message</p> <pre><code>/bin/sh: -c: line 5: syntax error: unexpected end of file </code></pre>
0
2016-07-22T12:49:08Z
38,526,969
<p>In sh scripts, <code>if</code> is terminated with <code>fi</code>, not <code>endif</code>.</p> <p><a href="http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html" rel="nofollow">http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html</a></p> <hr> <p>Or just write the darn code in Python:</p> <pre><code>import os if os.path.exists('../a.txt'): print 'Exists' os.symlink('../a.txt', 'a.txt') else: print 'Does not exist' </code></pre> <ul> <li><a href="https://docs.python.org/2/library/os.path.html#os.path.exists" rel="nofollow"><code>os.path.exists ()</code></a></li> <li><a href="https://docs.python.org/2/library/os.html#os.symlink" rel="nofollow"><code>os.symlink()</code></a></li> </ul> <hr> <p>If you really want to run tcsh commands, then:</p> <pre><code>import shlex import subprocess args = ['tcsh', '-c'] + shlex.split(some_tcsh_command) ret = suprocess.call(args) </code></pre>
6
2016-07-22T12:52:22Z
[ "python", "unix" ]
Missing values at the beginning - matplotlib
38,527,053
<p>Trying to add missing values (None) or in <code>numpy</code> <code>np.nan</code> to my matplot graph. Normally it is possible to have missing values in this way:</p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(1) x = range(10) y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10] ax = fig.add_subplot(111) ax.plot(x, y, 'ro') plt.show() </code></pre> <p>But looks like missing values aren't easily supported at the beginning of the graph. </p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(1) x = range(10) y = ([None]*5)+[x for x in range(5)] ax = fig.add_subplot(111) ax.plot(x, y, 'ro') plt.show() </code></pre> <p>This displays:</p> <p><a href="http://i.stack.imgur.com/4L6xI.png" rel="nofollow"><img src="http://i.stack.imgur.com/4L6xI.png" alt=""></a></p> <p>But I would like to start with <code>x=0</code> instead of <code>x=5</code>. Hope there is a simple method for this problem.</p>
2
2016-07-22T12:56:16Z
38,527,184
<p>Matplotlib automatically choses the parameters for x- and y- axes. In this case it is only showing the dots that can be visualized. If either x- or y is "None", nothing can be visualized. If you yet want to see the "empty" part of the graph, just adjust the axis range yourself. </p> <p>How to do so, has been answered multiple times in similiar questions in this forum such as: </p> <p><a href="http://stackoverflow.com/questions/4136244/matplotlib-pyplot-how-to-enforce-axis-range">Matplotlib/pyplot: How to enforce axis range?</a></p> <p><a href="http://stackoverflow.com/questions/2849286/python-matplotlib-subplot-how-to-set-the-axis-range">Python, Matplotlib, subplot: How to set the axis range?</a></p> <p><a href="http://stackoverflow.com/questions/3777861/setting-y-axis-limit-in-matplotlib">setting y-axis limit in matplotlib</a></p> <p>and plenty more. Therefore I will refrain from repeating what has been said elsewhere in this forum. </p>
3
2016-07-22T13:03:19Z
[ "python", "matplotlib" ]
Missing values at the beginning - matplotlib
38,527,053
<p>Trying to add missing values (None) or in <code>numpy</code> <code>np.nan</code> to my matplot graph. Normally it is possible to have missing values in this way:</p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(1) x = range(10) y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10] ax = fig.add_subplot(111) ax.plot(x, y, 'ro') plt.show() </code></pre> <p>But looks like missing values aren't easily supported at the beginning of the graph. </p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(1) x = range(10) y = ([None]*5)+[x for x in range(5)] ax = fig.add_subplot(111) ax.plot(x, y, 'ro') plt.show() </code></pre> <p>This displays:</p> <p><a href="http://i.stack.imgur.com/4L6xI.png" rel="nofollow"><img src="http://i.stack.imgur.com/4L6xI.png" alt=""></a></p> <p>But I would like to start with <code>x=0</code> instead of <code>x=5</code>. Hope there is a simple method for this problem.</p>
2
2016-07-22T12:56:16Z
38,527,189
<p>The reason why the empty values don't seem to have an effect on the second plot is because of the automatic determination of the x and y limits of the axes object. In the first case, you have "real" data that spans the whole x / y range you care about and the axes is automatically scaled to fit this data. In the second example, your real data only covers the upper range of x values so matplotlib will truncate the x axis because there is nothing to show.</p> <p>The way around this is to explicitly specify the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim" rel="nofollow">xlims</a> of the axes. You can use your value for <code>x</code> to determine what these should be. </p> <pre><code>plt.xlim(x[0], x[-1]) </code></pre>
4
2016-07-22T13:03:33Z
[ "python", "matplotlib" ]
Run a tensorflow with a list of fetches does not work
38,527,096
<p>I'm playing around with Tensorflow and implemented a k means clustering algorithm. Everything works well, but if I want to run the session with a couple of fetches in a <code>list</code> I always get the error, that a <code>list</code> can not be converted to a <code>Tensor</code> or <code>Operation</code>.</p> <p>The <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#Session" rel="nofollow">documentation</a> explicitly says, that I can call <code>Session.run()</code> with a list. Am I doing anything wrong?</p> <p>Here is the source code:</p> <pre><code>import tensorflow as tf import numpy as np def tf_k_means(k, data, eps_=0.1): eps = tf.constant(eps_) cluster_means = tf.placeholder(tf.float32, [None, 2]) tf_data = tf.placeholder(tf.float32, [None, 2], name='data') model = tf.initialize_all_variables() expanded_data = tf.expand_dims(tf_data, 0) expanded_means = tf.expand_dims(cluster_means, 1) distances = tf.reduce_sum(tf.square(tf.sub(expanded_means, expanded_data)), 2) mins = tf.to_int32(tf.argmin(distances, 0)) clusters = tf.dynamic_partition(tf_data, mins, k) old_cluster_means = tf.identity(cluster_means) new_means = tf.concat(0, [tf.expand_dims(tf.reduce_mean(cluster, 0), 0) for cluster in clusters]) clusters_moved = tf.reduce_sum(tf.square(tf.sub(old_cluster_means, new_means)), 1) converged = tf.reduce_all(tf.less(clusters_moved, eps)) cms = data[np.random.randint(data.shape[0],size=k), :] with tf.Session() as sess: sess.run(model) conv = False while not conv: ##################################### # THE FOLLOWING LINE DOES NOT WORK: # ##################################### (cs, cms, conv) = sess.run([clusters, new_means, converged], feed_dict={tf_data: data, cluster_means: cms}) return cs, cms </code></pre> <p>Here is the error message:</p> <pre><code>TypeError: Fetch argument [&lt;tf.Tensor 'DynamicPartition_25:0' shape=(?, 2) dtype=float32&gt;, &lt;tf.Tensor 'DynamicPartition_25:1' shape=(?, 2) dtype=float32&gt;, &lt;tf.Tensor 'DynamicPartition_25:2' shape=(?, 2) dtype=float32&gt;, &lt;tf.Tensor 'DynamicPartition_25:3' shape=(?, 2) dtype=float32&gt;] of [&lt;tf.Tensor 'DynamicPartition_25:0' shape=(?, 2) dtype=float32&gt;, &lt;tf.Tensor 'DynamicPartition_25:1' shape=(?, 2) dtype=float32&gt;, &lt;tf.Tensor 'DynamicPartition_25:2' shape=(?, 2) dtype=float32&gt;, &lt;tf.Tensor 'DynamicPartition_25:3' shape=(?, 2) dtype=float32&gt;] has invalid type &lt;class 'list'&gt;, must be a string or Tensor. (Can not convert a list into a Tensor or Operation.) </code></pre>
0
2016-07-22T12:58:43Z
38,531,878
<p><code>tf.dynamic_partition</code> returns a <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#dynamic_partition" rel="nofollow">list of Tensors</a>, so <code>clusters</code> is itself a list. </p> <pre><code>clusters = tf.dynamic_partition(tf_data, mins, k) </code></pre> <p>When you feed that list into sess.run inside another list, I think that's where you have your problem. you could maybe try:</p> <pre><code>sess.run(clusters + [new_means, converged], ... </code></pre>
2
2016-07-22T17:04:09Z
[ "python", "tensorflow" ]
different roles in Django: show different content in web page
38,527,159
<p>I'm using Django to develop an webapp, I created different roles of users, for example <code>CunstomerUser, GoodUser, Admin</code>...etc.</p> <p>Now I want to show them different things when they login. For example, when they open a popup, the <code>CustomerUser</code> will see a textarea field for commenting and for the <code>Admin</code> he will see other things he can do.</p> <p>I found that we can do it in the <code>template</code> level, like:</p> <pre><code>{% if request.user.is_superuser %} .... superuser content {% else %} .... non-superuser content {% endif %} </code></pre> <p>But how can I do in the javascript file which is used by this <code>template</code>? Cause I want to show them the different functions depends on their roles. For example I want to determine the role in the <code>example.js</code> which is included in the template:</p> <pre><code>&lt;html&gt; &lt;script type="text/javascript" src="example.js"&gt;&lt;/script&gt; ... &lt;/html&gt; </code></pre> <p>The current solution that I found is to create a variable global javascript in the template so that all the javascipt files can use:</p> <pre><code>&lt;script&gt; var userType = '{{user.get_usertype}}'; &lt;/scirpt&gt; </code></pre> <p>But is their a better way to do this? the variable global is not so good to use I think...maybe I used a dump pattern design. Any ideas? Thanks!</p>
0
2016-07-22T13:01:56Z
38,527,306
<p>I might be wrong but you could still use django template syntax in javascript, because django template is evaluated before the page is loaded, so it still works by hiding/showing the portion that's relevant to the specific user:</p> <pre><code>&lt;script&gt; {% if request.user.is_superuser %} var userType = 'superuser'; {% else %} var userType = 'normaluser'; {% endif %} &lt;/script&gt; </code></pre> <p>The above code block doesn't have to be global, it could happen anywhere within your template file. You will always get just one definition of <code>userType</code> in this case.</p> <p><strong>Edit:</strong></p> <p>Well, the point of avoid global variables is because they might get changed by other functions so the values might messed up. However if you define pseudo-constants then you should be fine. </p> <p>Javascript doesn't have constants but you could use any html with an id to achieve that:</p> <p>html:</p> <pre><code>&lt;p style="display: none;" class="identity" id="{% if request.user.is_superuser %}superuser{% else %}normaluser{% endif %}"&gt;&lt;/p&gt; </code></pre> <p>example.js:</p> <pre><code>var user_role = $('p.identity').attr('id'); </code></pre> <p>One caveat is that you need to load your <code>example.js</code> at the end of the template, otherwise it will load before the html loads, thus couldn't find the element.</p>
2
2016-07-22T13:09:08Z
[ "javascript", "python", "django" ]
Running Python script via systemd fails to load module
38,527,235
<p>I have a Python script that uses <code>zmq</code> and I've installed this library via <code>pip install zmq</code> and I can run the program fine if called manually via the command line. However as soon as I attempt to have a <code>systemd</code> unit call the script, running <code>systemctl status myservice.service</code> shows <code>ImportError: No module named zmq</code>.</p> <p>My service file looks like this:</p> <pre><code>[Unit] Description=Does Something [Service] Type=simple ExecStart=/bin/sh /var/lib/project/runpythonscript.sh Restart=always [Install] Alias=myservice.service </code></pre> <p>Where <code>runpythonscript.sh</code> is a very simple shell script that runs my python script as root. Running this shell script manually from the command line runs my python program completely fine but having the service call it causes it to not locate the <code>zmq</code> module.</p> <p>Any help is appreciated.</p>
1
2016-07-22T13:06:04Z
38,528,565
<p>The most likely explanation is that you have some environment variables set (e.g. an extension of your PYTHONPATH?) which is not set when the script is being run by systemd.</p> <p>You could try using the Environment parameter (see [0]) so set PYTHONPATH (and whatever else might influence this) to whatever it is in your console session.</p> <p>[0] <a href="http://0pointer.de/public/systemd-man/systemd.exec.html#Environment=" rel="nofollow">http://0pointer.de/public/systemd-man/systemd.exec.html#Environment=</a></p>
2
2016-07-22T14:08:28Z
[ "python", "linux", "service", "systemd" ]
Running Python script via systemd fails to load module
38,527,235
<p>I have a Python script that uses <code>zmq</code> and I've installed this library via <code>pip install zmq</code> and I can run the program fine if called manually via the command line. However as soon as I attempt to have a <code>systemd</code> unit call the script, running <code>systemctl status myservice.service</code> shows <code>ImportError: No module named zmq</code>.</p> <p>My service file looks like this:</p> <pre><code>[Unit] Description=Does Something [Service] Type=simple ExecStart=/bin/sh /var/lib/project/runpythonscript.sh Restart=always [Install] Alias=myservice.service </code></pre> <p>Where <code>runpythonscript.sh</code> is a very simple shell script that runs my python script as root. Running this shell script manually from the command line runs my python program completely fine but having the service call it causes it to not locate the <code>zmq</code> module.</p> <p>Any help is appreciated.</p>
1
2016-07-22T13:06:04Z
38,529,122
<p><code>systemd</code> runs as root. The modules installed via <code>pip</code> are installed for a user rather than for the system and so installing the modules without root privileges made the modules unaccessible for root.</p> <p>To solve this I ran <code>sudo -H pip install zmq</code> and <code>sudo -H pip3 install zmq</code> to install the packages for both Python 2.7 and Python 3+ for root. This allowed <code>systemd</code> to access the modules once it attempts to execute the Python script.</p>
1
2016-07-22T14:35:10Z
[ "python", "linux", "service", "systemd" ]
ldap3 library: modify attribute with multiple values
38,527,246
<p>Trying to modify an ldap attribute that has multiple values, can't seem to figure out the syntax.</p> <p>I'm using the <a href="https://github.com/cannatag/ldap3" rel="nofollow">ldap3</a> library with python3.</p> <p>The <a href="http://ldap3.readthedocs.io/modify.html" rel="nofollow">documentation</a> gives an example which modifies <em>two</em> attributes of an entry - but each attribute only has <em>one</em> value.</p> <p>The dictionary from that example is the bit I'm having trouble with:</p> <pre><code>c.modify('cn=user1,ou=users,o=company', {'givenName': [(MODIFY_REPLACE, [&lt;what do I put here&gt;])]}) </code></pre> <p>Instead of 'givenname' which would have one value I want to modify the memberuid attribute which obviously would have many names as entries.</p> <p>So I spit all my memberuids into a list, make the modification, and then am trying to feed my new usernames/memberuid list to the MODIFY command. Like so:</p> <pre><code>oldval = 'super.man' newval = 'clark.kent' existingmembers = ['super.man', 'the.hulk', 'bat.man'] newmemberlist = [newval if x==oldval else x for x in existingmembers] # newmemberlist = ", ".join(str(x) for x in newmemberlist) </code></pre> <p>I've tried passing in newmemberlist as a list</p> <pre><code>'memberuid': [(MODIFY_REPLACE, ['clark.kent', 'the.hulk','bat.man'])] </code></pre> <p>which gives me <code>TypeError: 'str' object cannot be interpreted as an integer</code></p> <p>or various combinations (the commented line) of one long string, separated with spaces, commas, semi colons and anything else I can think of </p> <pre><code>'memberuid': [(MODIFY_REPLACE, 'clark.kent, the.hulk, bat.man')] </code></pre> <p>which does the replace but I get <em>one</em> memberuid looking like this <code>'clark.kent, the.hulk, bat.man'</code></p>
0
2016-07-22T13:06:36Z
38,531,371
<p>You need to ensure you are passing in the DN of the ldapobject you wish to modify. </p> <pre><code>c.modify(FULL_DN_OF_OBJECT, {'memberuid': [(MODIFY_REPLACE, ['clark.kent', 'the.hulk','bat.man'])]}) </code></pre> <p>Then you should be able just to pass in newmemberlist instead of ['clark.kent', 'the.hulk','bat.man'] </p> <pre><code>c.modify(FULL_DN_OF_OBJECT, {'memberuid': [(MODIFY_REPLACE, newmemberlist )]}) </code></pre>
1
2016-07-22T16:30:53Z
[ "python", "python-3.x", "ldap" ]
ldap3 library: modify attribute with multiple values
38,527,246
<p>Trying to modify an ldap attribute that has multiple values, can't seem to figure out the syntax.</p> <p>I'm using the <a href="https://github.com/cannatag/ldap3" rel="nofollow">ldap3</a> library with python3.</p> <p>The <a href="http://ldap3.readthedocs.io/modify.html" rel="nofollow">documentation</a> gives an example which modifies <em>two</em> attributes of an entry - but each attribute only has <em>one</em> value.</p> <p>The dictionary from that example is the bit I'm having trouble with:</p> <pre><code>c.modify('cn=user1,ou=users,o=company', {'givenName': [(MODIFY_REPLACE, [&lt;what do I put here&gt;])]}) </code></pre> <p>Instead of 'givenname' which would have one value I want to modify the memberuid attribute which obviously would have many names as entries.</p> <p>So I spit all my memberuids into a list, make the modification, and then am trying to feed my new usernames/memberuid list to the MODIFY command. Like so:</p> <pre><code>oldval = 'super.man' newval = 'clark.kent' existingmembers = ['super.man', 'the.hulk', 'bat.man'] newmemberlist = [newval if x==oldval else x for x in existingmembers] # newmemberlist = ", ".join(str(x) for x in newmemberlist) </code></pre> <p>I've tried passing in newmemberlist as a list</p> <pre><code>'memberuid': [(MODIFY_REPLACE, ['clark.kent', 'the.hulk','bat.man'])] </code></pre> <p>which gives me <code>TypeError: 'str' object cannot be interpreted as an integer</code></p> <p>or various combinations (the commented line) of one long string, separated with spaces, commas, semi colons and anything else I can think of </p> <pre><code>'memberuid': [(MODIFY_REPLACE, 'clark.kent, the.hulk, bat.man')] </code></pre> <p>which does the replace but I get <em>one</em> memberuid looking like this <code>'clark.kent, the.hulk, bat.man'</code></p>
0
2016-07-22T13:06:36Z
38,616,209
<p>I believe MODIFY_REPLACE command would not accept multiple values, as it would not understand which values would be replaced with new ones. Instead you should try doing MODIFY_DELETE old values first and MODIFY_ADD new values afterwards.</p>
0
2016-07-27T14:42:39Z
[ "python", "python-3.x", "ldap" ]
Python Pandas: Create new rows in dataFrame based on two columns
38,527,268
<p>I have the following dataframe 'df' based on which I'd like to create a new df 'new_df'. I have some troubles getting the new df.</p> <pre><code> Cust-id Sex Country Orders Products 0 'Cu1' 'F' 'FR' 'ord1 + ord2' 'A+G' 1 'Cu2' 'M' 'US' 'ord3' 'C' 2 'Cu3' 'M' 'UK' 'ord4 + ord5' 'H+Z' 3 'Cu4' 'F' 'RU' 'ord6' 'K' 4 'Cu5' 'M' 'US' 'ord7' 'T' 5 NaN 'M' 'UK' 'ord#' 'K' 6 'Cu6' 'F' 'US' 'ord8+ord9+ord10' 'R+D+S' 7 'Cu7' 'M' 'UK' 'ord11' 'A' </code></pre> <p>I'd like the 'new_df' to contain a row for each 'order' with corresponding 'product'. All other columns keep their contents. Also, if a row in the 'Cust-id' column is NaN that complete row should be deleted (i.e. not present in the new df). This would give the following new_df:</p> <pre><code> Cust-id Sex Country Orders Products 0 'Cu1' 'F' 'FR' 'ord1' 'A' 1 'Cu1' 'F' 'FR' 'ord2' 'G' 2 'Cu2' 'M' 'US' 'ord3' 'C' 3 'Cu3' 'M' 'UK' 'ord4' 'H' 4 'Cu3' 'M' 'UK' 'ord5' 'Z' 5 'Cu4' 'F' 'RU' 'ord6' 'K' 6 'Cu5' 'M' 'US' 'ord7' 'T' 7 'Cu6' 'F' 'US' 'ord8' 'R' 8 'Cu6' 'F' 'US' 'ord9' 'D' 9 'Cu6' 'F' 'US' 'ord10' 'S' 10 'Cu7' 'M' 'UK' 'ord11' 'A' </code></pre> <p>Any help/guidance is appreciated.</p>
1
2016-07-22T13:07:29Z
38,527,415
<p>You can use:</p> <pre><code>#remove ', split by +, create Series s1 = df.Products.str.strip("'") .str.split('+', expand=True) .stack() .reset_index(drop=True, level=1) #remove ', split by +, create Series, strip spaces s2 = df.Orders.str.strip("'") .str.split('+', expand=True) .stack().str.strip() .reset_index(drop=True, level=1) #if need add ' s1 = "'" + s1 + "'" s2 = "'" + s2 + "'" df1 = pd.DataFrame({'Products':s1, 'Orders':s2}, index=s1.index) print (df1) Orders Products 0 'ord1' 'A' 0 'ord2' 'G' 1 'ord3' 'C' 2 'ord4' 'H' 2 'ord5' 'Z' 3 'ord6' 'K' 4 'ord7' 'T' 5 'ord#' 'K' 6 'ord8' 'R' 6 'ord9' 'D' 6 'ord10' 'S' 7 'ord11' 'A' </code></pre> <pre><code>#delete old columns, join df1, drop df if NaN in Cust-id print(df.drop(['Orders', 'Products'], axis=1) .join(df1) .dropna(subset=['Cust-id']) .reset_index(drop=True)) Cust-id Sex Country Orders Products 0 'Cu1' 'F' 'FR' 'ord1' 'A' 1 'Cu1' 'F' 'FR' 'ord2' 'G' 2 'Cu2' 'M' 'US' 'ord3' 'C' 3 'Cu3' 'M' 'UK' 'ord4' 'H' 4 'Cu3' 'M' 'UK' 'ord5' 'Z' 5 'Cu4' 'F' 'RU' 'ord6' 'K' 6 'Cu5' 'M' 'US' 'ord7' 'T' 7 'Cu6' 'F' 'US' 'ord8' 'R' 8 'Cu6' 'F' 'US' 'ord9' 'D' 9 'Cu6' 'F' 'US' 'ord10' 'S' 10 'Cu7' 'M' 'UK' 'ord11' 'A' </code></pre> <p>EDIT by comment:</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> for creating <code>df1</code>:</p> <pre><code>... ... df1 = pd.concat([s1, s2], keys=('Orders', 'Products'), axis=1) print (df1) Orders Products 0 'A' 'ord1' 0 'G' 'ord2' 1 'C' 'ord3' 2 'H' 'ord4' 2 'Z' 'ord5' 3 'K' 'ord6' 4 'T' 'ord7' 5 'K' 'ord#' 6 'R' 'ord8' 6 'D' 'ord9' 6 'S' 'ord10' 7 'A' 'ord11' print(df.drop(['Orders', 'Products'], axis=1) .join(df1) .dropna(subset=['Cust-id']) .reset_index(drop=True)) Cust-id Sex Country Orders Products 0 'Cu1' 'F' 'FR' 'A' 'ord1' 1 'Cu1' 'F' 'FR' 'G' 'ord2' 2 'Cu2' 'M' 'US' 'C' 'ord3' 3 'Cu3' 'M' 'UK' 'H' 'ord4' 4 'Cu3' 'M' 'UK' 'Z' 'ord5' 5 'Cu4' 'F' 'RU' 'K' 'ord6' 6 'Cu5' 'M' 'US' 'T' 'ord7' 7 'Cu6' 'F' 'US' 'R' 'ord8' 8 'Cu6' 'F' 'US' 'D' 'ord9' 9 'Cu6' 'F' 'US' 'S' 'ord10' 10 'Cu7' 'M' 'UK' 'A' 'ord11' </code></pre>
0
2016-07-22T13:14:03Z
[ "python", "pandas" ]
Python Pandas: Create new rows in dataFrame based on two columns
38,527,268
<p>I have the following dataframe 'df' based on which I'd like to create a new df 'new_df'. I have some troubles getting the new df.</p> <pre><code> Cust-id Sex Country Orders Products 0 'Cu1' 'F' 'FR' 'ord1 + ord2' 'A+G' 1 'Cu2' 'M' 'US' 'ord3' 'C' 2 'Cu3' 'M' 'UK' 'ord4 + ord5' 'H+Z' 3 'Cu4' 'F' 'RU' 'ord6' 'K' 4 'Cu5' 'M' 'US' 'ord7' 'T' 5 NaN 'M' 'UK' 'ord#' 'K' 6 'Cu6' 'F' 'US' 'ord8+ord9+ord10' 'R+D+S' 7 'Cu7' 'M' 'UK' 'ord11' 'A' </code></pre> <p>I'd like the 'new_df' to contain a row for each 'order' with corresponding 'product'. All other columns keep their contents. Also, if a row in the 'Cust-id' column is NaN that complete row should be deleted (i.e. not present in the new df). This would give the following new_df:</p> <pre><code> Cust-id Sex Country Orders Products 0 'Cu1' 'F' 'FR' 'ord1' 'A' 1 'Cu1' 'F' 'FR' 'ord2' 'G' 2 'Cu2' 'M' 'US' 'ord3' 'C' 3 'Cu3' 'M' 'UK' 'ord4' 'H' 4 'Cu3' 'M' 'UK' 'ord5' 'Z' 5 'Cu4' 'F' 'RU' 'ord6' 'K' 6 'Cu5' 'M' 'US' 'ord7' 'T' 7 'Cu6' 'F' 'US' 'ord8' 'R' 8 'Cu6' 'F' 'US' 'ord9' 'D' 9 'Cu6' 'F' 'US' 'ord10' 'S' 10 'Cu7' 'M' 'UK' 'ord11' 'A' </code></pre> <p>Any help/guidance is appreciated.</p>
1
2016-07-22T13:07:29Z
38,527,525
<p>Write the df to a csv using following code will correct the error </p> <pre><code> df.dropna().to_csv('train1.csv') </code></pre> <p>try this</p>
-1
2016-07-22T13:19:14Z
[ "python", "pandas" ]
Using urllib instead of wget for session authentication
38,527,372
<p>So currently i have a line of python code which uses wget and os.system to download a file from a website. However when i try to convert this wget to a more elegant library such as urllib or requests, the cookies fail to authenticate and instead downloads the login html page instead of the file.</p> <p>Here is what i currently use:</p> <pre><code> try: print(URL) os.system( "wget --save-cookies cookies.txt --keep-session-cookies --post-data='name={}&amp;password={}' https://fakesite/login".format( username, password)) os.system("wget --load-cookies cookies.txt --accept=exe {}".format(URL)) except Exception as e: print(" File not found, please refer to the website manually for download link", e) </code></pre> <p>which i attempted to refactor into something like this:</p> <pre><code> try: print("Downloading file {} version: {}......".format(version, buildNo)) with requests.session() as s: s.post(loginUrl, data="name:{}&amp;password:{}".format(username,password)) print(URL) r = s.get(URL,cookies=s.cookies, headers={"Accept": "application/octet-stream"}) print (r.content) </code></pre> <p>but this fails and instead prints the html content of the login page! can anyone shed some light on this?</p>
1
2016-07-22T13:12:09Z
38,662,646
<p>You should use <code>=</code> instead <code>:</code> in your query:</p> <pre><code>s.post(loginUrl, data="name={}&amp;password={}".format(username,password)) </code></pre> <p>Also, you could (and should, following the <code>requests</code> best practice) proceed a dict to <code>data</code> argument:</p> <pre><code>s.post( loginUrl, data={ 'name': username, 'password': password, } ) </code></pre>
1
2016-07-29T15:38:47Z
[ "python" ]
Python: automatically call a parent function after child instantiation
38,527,374
<p>Python 2.7</p> <p>I would like to automotically call a function of a parent object after I instantiate its child</p> <pre><code>class Mother: def __init__(self): pass def call_me_maybe(self): print 'hello son' class Child(Mother): def __init__(self): print 'hi mom' # desired behavior &gt;&gt;&gt; billy = Child() hi mom hello son </code></pre> <p>Is there a way I can do this?</p> <p>Edit, from a comment below:</p> <p>"i should have made it more clearer in my question, what i really want is some sort of 'automatic' calling of the parent method triggered solely by the instantiation of the child, with no explicit calling of the parent method from the child. I was hoping there would be some sort of magic method for this but i dont think there is."</p>
1
2016-07-22T13:12:14Z
38,527,403
<p>Use <code>super()</code>?</p> <pre><code>class Child(Mother): def __init__(self): print 'hi mom' super(Child, self).call_me_maybe() </code></pre>
1
2016-07-22T13:13:34Z
[ "python", "oop", "inheritance", "python-object" ]
Python: automatically call a parent function after child instantiation
38,527,374
<p>Python 2.7</p> <p>I would like to automotically call a function of a parent object after I instantiate its child</p> <pre><code>class Mother: def __init__(self): pass def call_me_maybe(self): print 'hello son' class Child(Mother): def __init__(self): print 'hi mom' # desired behavior &gt;&gt;&gt; billy = Child() hi mom hello son </code></pre> <p>Is there a way I can do this?</p> <p>Edit, from a comment below:</p> <p>"i should have made it more clearer in my question, what i really want is some sort of 'automatic' calling of the parent method triggered solely by the instantiation of the child, with no explicit calling of the parent method from the child. I was hoping there would be some sort of magic method for this but i dont think there is."</p>
1
2016-07-22T13:12:14Z
38,527,451
<p>You could use <a href="http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods"><code>super</code></a> but you should set your <em>superclass</em> to inherit from <code>object</code>:</p> <pre><code>class Mother(object): # ^ def __init__(self): pass def call_me_maybe(self): print 'hello son' class Child(Mother): def __init__(self): print 'hi mom' super(Child, self).call_me_maybe() </code></pre> <hr> <pre><code>&gt;&gt;&gt; billy = Child() hi mom hello son </code></pre>
3
2016-07-22T13:15:58Z
[ "python", "oop", "inheritance", "python-object" ]
Python: automatically call a parent function after child instantiation
38,527,374
<p>Python 2.7</p> <p>I would like to automotically call a function of a parent object after I instantiate its child</p> <pre><code>class Mother: def __init__(self): pass def call_me_maybe(self): print 'hello son' class Child(Mother): def __init__(self): print 'hi mom' # desired behavior &gt;&gt;&gt; billy = Child() hi mom hello son </code></pre> <p>Is there a way I can do this?</p> <p>Edit, from a comment below:</p> <p>"i should have made it more clearer in my question, what i really want is some sort of 'automatic' calling of the parent method triggered solely by the instantiation of the child, with no explicit calling of the parent method from the child. I was hoping there would be some sort of magic method for this but i dont think there is."</p>
1
2016-07-22T13:12:14Z
38,527,571
<p>Since the child class inherits the parents methods, you can simply call the method in the <code>__init__()</code> statement.</p> <pre><code>class Mother(object): def __init__(self): pass def call_me_maybe(self): print('hello son') class Child(Mother): def __init__(self): print('hi mom') self.call_me_maybe() </code></pre>
1
2016-07-22T13:21:44Z
[ "python", "oop", "inheritance", "python-object" ]
Fill NA-values with Mean across column and row values
38,527,444
<p>I have next dataframe</p> <pre><code> A B C D E F 0 158 158 158 177 1 10 1 158 158 158 177 2 20 2 177 177 177 177 3 30 3 1 3 5 7 NaN 10 4 177 177 177 177 6 50 </code></pre> <p>Now I try to get a new one dataframe where <strong>E3</strong> = AVG[AVG(E)=3, AVG(3)=5]=4</p> <pre><code> A B C D E F 0 158 158 158 177 1 10 1 158 158 158 177 2 20 2 177 177 177 177 3 30 3 1 3 5 7 [4] 10 4 177 177 177 177 6 50 </code></pre>
1
2016-07-22T13:15:42Z
38,531,038
<p>I couldn't find a one-liner however if you can keep three data frames in memory</p> <ul> <li>one with row averages </li> <li>another with column averages </li> <li>third with the average of the above two</li> </ul> <p>then <code>fillna</code> will replace <code>NaN</code> values based on the exact location in the third data frame.</p> <pre><code>import pandas as pd import numpy as np data = [[158,158,158,177,1,10] ,[158,158,158,177,2,20] ,[177,177,177,177,3,30] ,[1,3,5,7,np.NaN,10] ,[177,177,177,177,6,50]] df = pd.DataFrame(data=data) # row and column means replicated over columns and rows mean0 = (pd.concat([df.mean(axis=0)]*df.shape[0], axis=1, ignore_index=True)).transpose() mean1 = pd.concat([df.mean(axis=1)]*df.shape[1], axis=1, ignore_index=True) # average of mean0 and mean1 m = mean0.add(mean1)/2 df = df.fillna(m) df 0 1 2 3 4 5 0 158 158 158 177 1.0 10 1 158 158 158 177 2.0 20 2 177 177 177 177 3.0 30 3 1 3 5 7 4.1 10 4 177 177 177 177 6.0 50 </code></pre>
1
2016-07-22T16:09:49Z
[ "python", "python-2.7", "pandas" ]
Jenkins with Windows slave with Python - Setting environment variables while building and using them when running a python script
38,527,505
<p>I'm currently using a Jenkins build to run a bash command that activates a Python script. The build is parametrised, and i need to be able to set environment variables containing those parameters on the Windows slave to be used by the Python script.</p> <p>So, my question is: How do i set temporary env. variables for the current build and secondly, how do i use Python to retreive them while running a script? An explanation of the process would be great since i couldn't make any solution work.</p>
0
2016-07-22T13:18:17Z
38,527,694
<p>What I usually do is going on the build output, on the left you will find "Build environment Variables" or something similar and check if you can see them there, but the solution cited on the other SO post works usually for me as well</p>
0
2016-07-22T13:27:38Z
[ "python", "jenkins", "jenkins-plugins" ]
AWS IOT with DynamoDB logging service issue
38,527,573
<p>We have implemented a simple DynamoDB database that is updated by a remote IoT device that does not have a user (i.e. root) constantly logged in to the device. We have experience issues in logging data as the database is not updated if a user (i.e. root) is not logged into the device (we log in via a ssh session). We are confident that the process is running in the background as we are using a Linux service that runs on bootup to execute a script. We have verified that the script runs on bootup and successfully pushes data to Dynamo upon user log in (via ssh). We have also tried to disassociate a screen session to allow for the device to publish data to Dynamo but this did not seem to fix the issue. Has anyone else experienced this issue? Does amazon AWS require a user (i.e. root) to be logged in to the device at all times in order to allow for data to be published to AWS?</p>
1
2016-07-22T13:21:46Z
38,537,832
<p>No, it does not. I have done similar setup and it is working fine. Are you sure that your IoT device does not go into some kind of sleep mode after a while ?</p>
0
2016-07-23T03:24:41Z
[ "python", "amazon-web-services", "amazon-dynamodb", "iot" ]
Appended object to a set is `NoneType` python 2.7
38,527,667
<p>I have a huge array of labels which I make unique via:</p> <pre><code>unique_train_labels = set(train_property_labels) </code></pre> <p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p> <pre><code>unique_train_labels_threshold = unique_train_labels.add('no_region') </code></pre> <p>However, this prints out to be <code>None</code>.</p> <p>My ultimate aim is to use these unique labels to later generate a random array of categorical labels via:</p> <pre><code> rng = np.random.RandomState(101) categorical_random = rng.choice(list(unique_train_labels), len(finalTestSentences)) categorical_random_threshold = rng.choice(list(unique_train_labels_threshold), len(finalTestSentences)) </code></pre> <p>From the <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">docs</a> it says that <code>set.add()</code> should generate a new set, which seems not to be the case (hence I can't later call <code>list(unique_train_labels_threshold)</code>)</p>
1
2016-07-22T13:26:22Z
38,527,744
<p>The set <code>add</code> method mutates the set <em>inplace</em> and returns a <code>None</code>. </p> <p>You should do:</p> <pre><code>unique_train_labels_threshold = unique_train_labels.copy() unique_train_labels_threshold.add('no_region') </code></pre> <p>Using <code>copy</code> ensures mutations on the new set are not propagated to the old one.</p>
4
2016-07-22T13:30:07Z
[ "python", "python-2.7", "numpy", "random", "set" ]
Appended object to a set is `NoneType` python 2.7
38,527,667
<p>I have a huge array of labels which I make unique via:</p> <pre><code>unique_train_labels = set(train_property_labels) </code></pre> <p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p> <pre><code>unique_train_labels_threshold = unique_train_labels.add('no_region') </code></pre> <p>However, this prints out to be <code>None</code>.</p> <p>My ultimate aim is to use these unique labels to later generate a random array of categorical labels via:</p> <pre><code> rng = np.random.RandomState(101) categorical_random = rng.choice(list(unique_train_labels), len(finalTestSentences)) categorical_random_threshold = rng.choice(list(unique_train_labels_threshold), len(finalTestSentences)) </code></pre> <p>From the <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">docs</a> it says that <code>set.add()</code> should generate a new set, which seems not to be the case (hence I can't later call <code>list(unique_train_labels_threshold)</code>)</p>
1
2016-07-22T13:26:22Z
38,527,881
<p>I can't find in the documentation anywhere were it says that <code>add</code> generates a new set.<br> You need to copy the original, then add to the new copy.</p> <pre><code>import copy unique_train_labels_threshold = copy.deepcopy(unique_train_labels) unique_train_labels_threshold.add('no_region') </code></pre>
0
2016-07-22T13:36:04Z
[ "python", "python-2.7", "numpy", "random", "set" ]
Appended object to a set is `NoneType` python 2.7
38,527,667
<p>I have a huge array of labels which I make unique via:</p> <pre><code>unique_train_labels = set(train_property_labels) </code></pre> <p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p> <pre><code>unique_train_labels_threshold = unique_train_labels.add('no_region') </code></pre> <p>However, this prints out to be <code>None</code>.</p> <p>My ultimate aim is to use these unique labels to later generate a random array of categorical labels via:</p> <pre><code> rng = np.random.RandomState(101) categorical_random = rng.choice(list(unique_train_labels), len(finalTestSentences)) categorical_random_threshold = rng.choice(list(unique_train_labels_threshold), len(finalTestSentences)) </code></pre> <p>From the <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">docs</a> it says that <code>set.add()</code> should generate a new set, which seems not to be the case (hence I can't later call <code>list(unique_train_labels_threshold)</code>)</p>
1
2016-07-22T13:26:22Z
38,528,506
<p>As mentioned in Moses' answer, the <code>set.add</code> method mutates the original set, it does not create a new set. In Python it's conventional for methods that perform in-place mutation to return <code>None</code>; the methods of all built-in mutable types do that, and the convention is generally observed by 3rd-party libraries.</p> <p>An alternative to using the <code>.copy</code> method is to use the <code>.union</code> method, which returns a new set that is the union of the original set and the set supplied as an argument. For sets, the <code>|</code> <em>or</em> operator invokes the <code>.union</code> method.</p> <pre><code>a = {1, 2, 3} b = a.union({5}) c = a | {4} print(a, b, c) </code></pre> <p><strong>output</strong></p> <pre><code>{1, 2, 3} {1, 2, 3, 5} {1, 2, 3, 4} </code></pre> <p>The <code>.union</code> method (like other set methods that can be invoked via operator syntax) has a slight advantage over the operator syntax: you can pass it <em>any</em> iterable for its argument; the operator version requires you to explicitly convert the argument to a set (or frozenset).</p> <pre><code>a = {1, 2, 3} b = a.union([5, 6]) c = a | set([7, 8]) print(a, b, c) </code></pre> <p><strong>output</strong> </p> <pre><code>{1, 2, 3} {1, 2, 3, 5, 6} {1, 2, 3, 7, 8} </code></pre> <p>Using the explicit <code>.union</code> method is slightly more efficient here because it bypasses converting the arg to a set: internally, the method just iterates over the contents of the arg, adding them to the new set, so it doesn't care if the arg is a set, list, tuple, string, or dict.</p> <p>From the official Python <a href="https://docs.python.org/3/library/stdtypes.html#set" rel="nofollow">set docs</a></p> <blockquote> <p>Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') &amp; 'cbs' in favor of the more readable set('abc').intersection('cbs').</p> </blockquote>
3
2016-07-22T14:05:49Z
[ "python", "python-2.7", "numpy", "random", "set" ]
Tensorflow: How to convert NaNs to a number?
38,527,722
<p>I'm trying to calculate the entropy of the weights while training my graph and to use it for regularization. This of course involves <code>w*tf.log(w)</code>, and as my weights are changing some of them are bound to get into a region which results in NaNs being returned.</p> <p>Ideally I would include a line in my graph setup:</p> <pre><code>w[tf.is_nan(w)] = &lt;number&gt; </code></pre> <p>but tensorflow doesn't support assigning like that. I could of course create an operation, but that wouldn't work because I need for it to happen during the execution of the entire graph. I can't wait for the graph to execute and then 'fix' my weights, is has to be part of the graph execution.</p> <p>I haven't been able to find an equivalent to <code>np.nan_to_num</code> in the docs.</p> <p>Anybody have an idea?</p> <p>(For obvious reasons, adding an epsilon doesn't work)</p>
1
2016-07-22T13:28:54Z
38,527,873
<p>I think you need to use tf.select.</p> <pre><code>w = tf.select(tf.is_nan(w), tf.ones_like(w) * NUMBER, w); #if w is nan use 1 * NUMBER else use element in w </code></pre>
3
2016-07-22T13:35:55Z
[ "python", "tensorflow", null ]
Tensorflow: How to convert NaNs to a number?
38,527,722
<p>I'm trying to calculate the entropy of the weights while training my graph and to use it for regularization. This of course involves <code>w*tf.log(w)</code>, and as my weights are changing some of them are bound to get into a region which results in NaNs being returned.</p> <p>Ideally I would include a line in my graph setup:</p> <pre><code>w[tf.is_nan(w)] = &lt;number&gt; </code></pre> <p>but tensorflow doesn't support assigning like that. I could of course create an operation, but that wouldn't work because I need for it to happen during the execution of the entire graph. I can't wait for the graph to execute and then 'fix' my weights, is has to be part of the graph execution.</p> <p>I haven't been able to find an equivalent to <code>np.nan_to_num</code> in the docs.</p> <p>Anybody have an idea?</p> <p>(For obvious reasons, adding an epsilon doesn't work)</p>
1
2016-07-22T13:28:54Z
38,527,913
<p>You cannot convert nan to a number (such as you cannot convert infinite to a number).</p> <p>The nan resulkts most probably from the <code>w*tf.log(w)</code> once w is (or contains) zero(s). You might add 1e-6 first so that no division by zero occurs.</p>
-1
2016-07-22T13:37:38Z
[ "python", "tensorflow", null ]
How can I hide columns in Openpyxl?
38,527,725
<p>I'm hiding a bunch of columns in an Excel sheet. I'm getting this error: <code>AttributeError: can't set attribute</code> from this line <code>worksheet.column_dimensions['B'].visible = False</code></p> <p>Sorry if this is a super simple question. I just updated to a new version of Openpyxl/Pandas so i'm now having to go through my code and make changes to fit the new version's documentation.</p> <pre><code> worksheet.column_dimensions['B'].visible = False worksheet.column_dimensions['D'].visible = False worksheet.column_dimensions['E'].visible = False worksheet.column_dimensions['F'].visible = False worksheet.column_dimensions['G'].visible = False worksheet.column_dimensions['H'].visible = False worksheet.column_dimensions['I'].visible = False worksheet.column_dimensions['K'].visible = False worksheet.column_dimensions['L'].visible = False worksheet.column_dimensions['M'].visible = False worksheet.column_dimensions['N'].visible = False worksheet.column_dimensions['O'].visible = False worksheet.column_dimensions['P'].visible = False worksheet.column_dimensions['Q'].visible = False worksheet.column_dimensions['R'].visible = False worksheet.column_dimensions['S'].visible = False worksheet.column_dimensions['T'].visible = False worksheet.column_dimensions['U'].visible = False worksheet.column_dimensions['V'].visible = False worksheet.column_dimensions['W'].visible = False worksheet.column_dimensions['X'].visible = False worksheet.column_dimensions['Y'].visible = False worksheet.column_dimensions['Z'].visible = False worksheet.column_dimensions['AA'].visible = False worksheet.column_dimensions['AB'].visible = False worksheet.column_dimensions['AC'].visible = False worksheet.column_dimensions['AD'].visible = False worksheet.column_dimensions['AE'].visible = False worksheet.column_dimensions['AF'].visible = False worksheet.column_dimensions['AG'].visible = False worksheet.column_dimensions['AH'].visible = False worksheet.column_dimensions['AI'].visible = False worksheet.column_dimensions['AJ'].visible = False worksheet.column_dimensions['AK'].visible = False worksheet.column_dimensions['AM'].visible = False worksheet.column_dimensions['AN'].visible = False worksheet.column_dimensions['AP'].visible = False worksheet.column_dimensions['AQ'].visible = False worksheet.column_dimensions['AR'].visible = False worksheet.column_dimensions['AS'].visible = False worksheet.column_dimensions['AT'].visible = False worksheet.column_dimensions['AU'].visible = False worksheet.column_dimensions['AV'].visible = False worksheet.column_dimensions['AW'].visible = False worksheet.column_dimensions['AX'].visible = False worksheet.column_dimensions['AY'].visible = False worksheet.column_dimensions['AZ'].visible = False worksheet.column_dimensions['BA'].visible = False worksheet.column_dimensions['BB'].visible = False worksheet.column_dimensions['BC'].visible = False worksheet.column_dimensions['BD'].visible = False worksheet.column_dimensions['BE'].visible = False worksheet.column_dimensions['BF'].visible = False worksheet.column_dimensions['BH'].visible = False worksheet.column_dimensions['BI'].visible = False worksheet.column_dimensions['BJ'].visible = False worksheet.column_dimensions['BK'].visible = False worksheet.column_dimensions['BL'].visible = False worksheet.column_dimensions['BM'].visible = False worksheet.column_dimensions['BN'].visible = False worksheet.column_dimensions['BO'].visible = False worksheet.column_dimensions['BP'].visible = False worksheet.column_dimensions['BQ'].visible = False worksheet.column_dimensions['BR'].visible = False worksheet.column_dimensions['BS'].visible = False worksheet.column_dimensions['BT'].visible = False worksheet.column_dimensions['BU'].visible = False worksheet.column_dimensions['BV'].visible = False worksheet.column_dimensions['BW'].visible = False worksheet.column_dimensions['BX'].visible = False worksheet.column_dimensions['BY'].visible = False worksheet.column_dimensions['BZ'].visible = False worksheet.column_dimensions['CA'].visible = False worksheet.column_dimensions['CB'].visible = False worksheet.column_dimensions['CC'].visible = False worksheet.column_dimensions['CD'].visible = False worksheet.column_dimensions['CE'].visible = False worksheet.column_dimensions['CF'].visible = False worksheet.column_dimensions['CG'].visible = False worksheet.column_dimensions['CH'].visible = False worksheet.column_dimensions['CI'].visible = False worksheet.column_dimensions['CJ'].visible = False worksheet.column_dimensions['CK'].visible = False worksheet.column_dimensions['CL'].visible = False worksheet.column_dimensions['CM'].visible = False worksheet.column_dimensions['CN'].visible = False worksheet.column_dimensions['CO'].visible = False worksheet.column_dimensions['CP'].visible = False worksheet.column_dimensions['CQ'].visible = False worksheet.column_dimensions['CR'].visible = False worksheet.column_dimensions['CS'].visible = False worksheet.column_dimensions['CU'].visible = False </code></pre> <p>Also, if someone could tell me if there's a more efficient way to hide the columns, which i'm certain there probably is, that would be great.</p>
0
2016-07-22T13:29:01Z
38,527,841
<p>You should set the <code>hidden</code> attribute to <code>True</code>:</p> <pre><code> worksheet.column_dimensions['A'].hidden= True </code></pre> <p>In order to hide more than one column:</p> <pre><code>for col in ['A', 'B', 'C']: worksheet.column_dimensions[col].hidden= True </code></pre>
3
2016-07-22T13:34:27Z
[ "python", "openpyxl" ]
How can I hide columns in Openpyxl?
38,527,725
<p>I'm hiding a bunch of columns in an Excel sheet. I'm getting this error: <code>AttributeError: can't set attribute</code> from this line <code>worksheet.column_dimensions['B'].visible = False</code></p> <p>Sorry if this is a super simple question. I just updated to a new version of Openpyxl/Pandas so i'm now having to go through my code and make changes to fit the new version's documentation.</p> <pre><code> worksheet.column_dimensions['B'].visible = False worksheet.column_dimensions['D'].visible = False worksheet.column_dimensions['E'].visible = False worksheet.column_dimensions['F'].visible = False worksheet.column_dimensions['G'].visible = False worksheet.column_dimensions['H'].visible = False worksheet.column_dimensions['I'].visible = False worksheet.column_dimensions['K'].visible = False worksheet.column_dimensions['L'].visible = False worksheet.column_dimensions['M'].visible = False worksheet.column_dimensions['N'].visible = False worksheet.column_dimensions['O'].visible = False worksheet.column_dimensions['P'].visible = False worksheet.column_dimensions['Q'].visible = False worksheet.column_dimensions['R'].visible = False worksheet.column_dimensions['S'].visible = False worksheet.column_dimensions['T'].visible = False worksheet.column_dimensions['U'].visible = False worksheet.column_dimensions['V'].visible = False worksheet.column_dimensions['W'].visible = False worksheet.column_dimensions['X'].visible = False worksheet.column_dimensions['Y'].visible = False worksheet.column_dimensions['Z'].visible = False worksheet.column_dimensions['AA'].visible = False worksheet.column_dimensions['AB'].visible = False worksheet.column_dimensions['AC'].visible = False worksheet.column_dimensions['AD'].visible = False worksheet.column_dimensions['AE'].visible = False worksheet.column_dimensions['AF'].visible = False worksheet.column_dimensions['AG'].visible = False worksheet.column_dimensions['AH'].visible = False worksheet.column_dimensions['AI'].visible = False worksheet.column_dimensions['AJ'].visible = False worksheet.column_dimensions['AK'].visible = False worksheet.column_dimensions['AM'].visible = False worksheet.column_dimensions['AN'].visible = False worksheet.column_dimensions['AP'].visible = False worksheet.column_dimensions['AQ'].visible = False worksheet.column_dimensions['AR'].visible = False worksheet.column_dimensions['AS'].visible = False worksheet.column_dimensions['AT'].visible = False worksheet.column_dimensions['AU'].visible = False worksheet.column_dimensions['AV'].visible = False worksheet.column_dimensions['AW'].visible = False worksheet.column_dimensions['AX'].visible = False worksheet.column_dimensions['AY'].visible = False worksheet.column_dimensions['AZ'].visible = False worksheet.column_dimensions['BA'].visible = False worksheet.column_dimensions['BB'].visible = False worksheet.column_dimensions['BC'].visible = False worksheet.column_dimensions['BD'].visible = False worksheet.column_dimensions['BE'].visible = False worksheet.column_dimensions['BF'].visible = False worksheet.column_dimensions['BH'].visible = False worksheet.column_dimensions['BI'].visible = False worksheet.column_dimensions['BJ'].visible = False worksheet.column_dimensions['BK'].visible = False worksheet.column_dimensions['BL'].visible = False worksheet.column_dimensions['BM'].visible = False worksheet.column_dimensions['BN'].visible = False worksheet.column_dimensions['BO'].visible = False worksheet.column_dimensions['BP'].visible = False worksheet.column_dimensions['BQ'].visible = False worksheet.column_dimensions['BR'].visible = False worksheet.column_dimensions['BS'].visible = False worksheet.column_dimensions['BT'].visible = False worksheet.column_dimensions['BU'].visible = False worksheet.column_dimensions['BV'].visible = False worksheet.column_dimensions['BW'].visible = False worksheet.column_dimensions['BX'].visible = False worksheet.column_dimensions['BY'].visible = False worksheet.column_dimensions['BZ'].visible = False worksheet.column_dimensions['CA'].visible = False worksheet.column_dimensions['CB'].visible = False worksheet.column_dimensions['CC'].visible = False worksheet.column_dimensions['CD'].visible = False worksheet.column_dimensions['CE'].visible = False worksheet.column_dimensions['CF'].visible = False worksheet.column_dimensions['CG'].visible = False worksheet.column_dimensions['CH'].visible = False worksheet.column_dimensions['CI'].visible = False worksheet.column_dimensions['CJ'].visible = False worksheet.column_dimensions['CK'].visible = False worksheet.column_dimensions['CL'].visible = False worksheet.column_dimensions['CM'].visible = False worksheet.column_dimensions['CN'].visible = False worksheet.column_dimensions['CO'].visible = False worksheet.column_dimensions['CP'].visible = False worksheet.column_dimensions['CQ'].visible = False worksheet.column_dimensions['CR'].visible = False worksheet.column_dimensions['CS'].visible = False worksheet.column_dimensions['CU'].visible = False </code></pre> <p>Also, if someone could tell me if there's a more efficient way to hide the columns, which i'm certain there probably is, that would be great.</p>
0
2016-07-22T13:29:01Z
38,528,918
<p>Columns can be grouped:</p> <pre><code>ws.column_dimensions.group(start='B', end='CU', hidden=True) </code></pre>
0
2016-07-22T14:25:33Z
[ "python", "openpyxl" ]
Python Array slicing. [:,:]
38,527,922
<p>I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)</p> <p>Declaration :</p> <pre><code>percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100 </code></pre> <p>Where nextImage, BaselineMin and BaselineMax are all 720x600 numpy arrays.</p> <p>Essentially, out of this, I should get another 720x600 Numpy arry </p> <p>Calling</p> <pre><code>percentile[:, :][percentile[:, :] == 0] = -999 </code></pre> <p>I am interested to know what each part does. Me and a co-worker looked at it and tried to replicate it with a sample 2x2 and 3x3 array and all we got is []. Alternatively, we got a flattened list, but could not replicate it.</p> <p>This has to do with array slicing, but i've never seen anything like this. I have taken a look at the other questions around here, but none of them have anything like this.</p>
0
2016-07-22T13:38:11Z
38,528,223
<p>That line of code sets every element in "percentile" that has a value of 0 to -999.</p> <p>Here is a simple 2 by 2 example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arr = np.array([[1,2],[0,4]]) &gt;&gt;&gt; arr array([[1, 2], [0, 4]]) &gt;&gt;&gt; arr[:,:][arr[:,:] == 0] = -999 &gt;&gt;&gt; arr array([[ 1, 2], [-999, 4]]) </code></pre> <p>As <a href="http://stackoverflow.com/users/1217358/warren-weckesser">Warren Wessecker</a> mentions, that can be simplified. Consider the following:</p> <pre><code>&gt;&gt;&gt; arr = np.array([[1,2],[0,4]]) &gt;&gt;&gt; arr array([[1, 2], [0, 4]]) &gt;&gt;&gt; arr[arr == 0] = -999 &gt;&gt;&gt; arr array([[ 1, 2], [-999, 4]]) </code></pre>
1
2016-07-22T13:52:29Z
[ "python", "arrays", "python-2.7", "numpy" ]
Python Array slicing. [:,:]
38,527,922
<p>I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)</p> <p>Declaration :</p> <pre><code>percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100 </code></pre> <p>Where nextImage, BaselineMin and BaselineMax are all 720x600 numpy arrays.</p> <p>Essentially, out of this, I should get another 720x600 Numpy arry </p> <p>Calling</p> <pre><code>percentile[:, :][percentile[:, :] == 0] = -999 </code></pre> <p>I am interested to know what each part does. Me and a co-worker looked at it and tried to replicate it with a sample 2x2 and 3x3 array and all we got is []. Alternatively, we got a flattened list, but could not replicate it.</p> <p>This has to do with array slicing, but i've never seen anything like this. I have taken a look at the other questions around here, but none of them have anything like this.</p>
0
2016-07-22T13:38:11Z
38,528,245
<p>As I understand it, the line of code in question reads like this:</p> <p>"Set anything in <code>percentile</code> that is 0 to -999".</p> <p>The first part <code>percentile[:,:]</code> just refers to every element in <code>percentile</code>. I'm fairly sure you wouldn't need the array slicing here, just replacing with <code>percentile</code>.</p> <p>The index on <code>percentile</code>, <code>percentile[:,:] == 0</code> then, should become a matrix of all booleans, <code>True</code> if the corresponding element in <code>percentile</code> is 0 and <code>False</code> otherwise. Again, the array slicing <code>percentile[:,:]</code> is not necessary.</p> <p>Indexing an array like this is called masking, and the matrix of booleans is called a mask. Essentially the mask selects the items of the indexed array where the mask is <code>True</code> so you can do something with them; here they are being set to -999.</p> <p>Hope that helps!</p>
2
2016-07-22T13:53:35Z
[ "python", "arrays", "python-2.7", "numpy" ]
Python Array slicing. [:,:]
38,527,922
<p>I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)</p> <p>Declaration :</p> <pre><code>percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100 </code></pre> <p>Where nextImage, BaselineMin and BaselineMax are all 720x600 numpy arrays.</p> <p>Essentially, out of this, I should get another 720x600 Numpy arry </p> <p>Calling</p> <pre><code>percentile[:, :][percentile[:, :] == 0] = -999 </code></pre> <p>I am interested to know what each part does. Me and a co-worker looked at it and tried to replicate it with a sample 2x2 and 3x3 array and all we got is []. Alternatively, we got a flattened list, but could not replicate it.</p> <p>This has to do with array slicing, but i've never seen anything like this. I have taken a look at the other questions around here, but none of them have anything like this.</p>
0
2016-07-22T13:38:11Z
38,528,438
<h1>Cutting the operation</h1> <h2>first part</h2> <p><code>percentile[:, :] == 0</code> or just <code>percentile == 0</code> will give a boolean numpy array of 720x600, True where the value==0 otherwise False.</p> <h2>second part</h2> <p><code>percentile[percentile == 0]</code> gives the values that meet the condition, so all 0 value in the array.</p> <h2>third and last part</h2> <p><code>percentile[percentile == 0] = -999</code>, update the zero values by -999.</p> <h1>An example</h1> <pre><code>import numpy as np A = np.random.rand(4, 4) A[A &gt;= 0.5] = 1 </code></pre> <p>The samples that are >= to 0.5 will be replaced by 1 in this array of random samples.</p>
1
2016-07-22T14:03:19Z
[ "python", "arrays", "python-2.7", "numpy" ]
How do I test a method that requires a file's presence?
38,528,004
<p>For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)</p> <p>The method is fairly simple, but it expects that the class has a <code>file</code> attribute set, that the attribute points to an existing file, and that the file is an archive of some sort (currently only working with zip files, tar, rar, etc., to be added later). The method is supposed to return the number of files in the archive.</p> <p>I've created a folder in my project called <code>files</code> that contains a few sample files, and I've manually tested the method and it works as it should so far. The manual test looks like this, located in the <code>archive_file.py</code> file:</p> <pre><code>if __name__ == '__main__': archive = ArchiveFile() script_path = path.realpath(__file__) parent_dir = path.abspath(path.join(script_path, os.pardir)) targ_dir = path.join(parent_dir, 'files') targ_file = path.join(targ_dir, 'test.zip' ) archive.file = targ_file print(archive.file_count()) </code></pre> <p>All I do then is make sure that what's printed is what I expect given the contents of <code>test.zip</code>.</p> <p>Here's what <code>file_count</code> looks like:</p> <pre><code>def file_count(self): """Return the number of files in the archive.""" if self.file == None: return -1 with ZipFile(self.file) as zip: members = zip.namelist() # Remove folder members if there are any. pruned = [item for item in members if not item.endswith('/')] return len(pruned) </code></pre> <p>Directly translating this to a unit test seems wrong to me for a few reasons, some of which may be invalid. I'm counting on the precise location of the test files in relation to the current script file, I'll need a large sample of manually created archive files to make sure I'm testing enough variations, and, of course, I'm manually comparing the returned value to what I expect because I know how many files are in the test archive.</p> <p>It <em>seems</em> to me that this should be automated as much as possible, but it also seems that doing so is going to be very complicated.</p> <p>What's the proper way to create unit tests for such a class method?</p>
9
2016-07-22T13:41:25Z
38,531,496
<p>There are so many different way to approach this. I like to think what would be valuable to test, off the top of my head, I can think of a couple things:</p> <ul> <li>validation logic (<code>if self.file == None</code>)</li> <li>pruning logic </li> <li>that all file types claimed to be supported are actually supported</li> </ul> <p>This testing could take place on two levels:</p> <ol> <li>Unittest your logic</li> <li>Test integration (ie supported archive types against the filesystem)</li> </ol> <p><strong>Unittest the logic</strong></p> <p>Unittesting the logic of your archive objects should be trivial. There looks to be a couple tests in your file_count method that could be valuable:</p> <ul> <li><p><code>test_no_file_returns_negative_one</code> (error conditions are "hopefully" not very frequently executed code paths, and are great candidates for tests. Especially if your clients are expecting this <code>-1</code> return value.</p></li> <li><p><code>test_zip_file_pruned_logic</code> this looks to be very important functionality in your code, if implemented incorrectly it would completely throw off the count that your code is claiming to be able to return</p></li> <li><p><code>test_happy_path_file_count_successful</code> I like to have a unittest that exercises the whole function, using mocked dependencies <code>ZipFile</code> to make sure that everything is covered, without having to run the integration tests.</p></li> </ul> <p><strong>Test Integrations</strong></p> <p>I think a test for each supported archive type would be very valuable. These could be static fixtures that live in your repo, and your tests would already know how many files that each archive has and would assert on that. </p> <p>I think all of your concerns are valid, and all of them can be addressed, and tested, in a maintainable way:</p> <p><strong>I'm counting on the precise location of the test files in relation to the current script file</strong></p> <p>This could be addressed by the convention of having your file fixtures stored in a subdirectory of your test package, and then using python to get the file path of your test package:</p> <p><code>FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixtures')</code></p> <p>For portable code it will be important to dynamically generate these paths.</p> <p><strong>I'll need a large sample of manually created archive files to make sure I'm testing enough variations</strong></p> <p>Yes, how many are good enough? AT LEAST a test per supported archive type. (netflix has to test against every single device that they have an app on :), plenty of companies have to run tests against large matrix of mobile devices) I think the test coverage here is crucial, but try to put all the edge cases that need to be covered in unittests.</p> <p><strong>I'm manually comparing the returned value to what I expect because I know how many files are in the test archive.</strong></p> <p>The archive will have to become static and your test will store that information.</p> <hr> <p>One thing to keep in mind are the scopes of your tests. Making a test that exercise <code>ZipFile</code> wouldn't be very valuable because its in the stdlibrary and already has tests. Additionally, testing that your code works with all python filesystems/os' probably wouldn't be very valuable either, as python already has those checks.</p> <p>But scoping your tests to verify that your application works with all file types that it says it supports, I believe, is extremely valuable, because it is a contract between you and your clients, saying "hey this DOES work, let me show you". The same way that python's tests are a contract between it and you saying "Hey we support OSX/LINUX/whatever let me show you"</p>
2
2016-07-22T16:38:38Z
[ "python", "unit-testing" ]
How do I test a method that requires a file's presence?
38,528,004
<p>For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)</p> <p>The method is fairly simple, but it expects that the class has a <code>file</code> attribute set, that the attribute points to an existing file, and that the file is an archive of some sort (currently only working with zip files, tar, rar, etc., to be added later). The method is supposed to return the number of files in the archive.</p> <p>I've created a folder in my project called <code>files</code> that contains a few sample files, and I've manually tested the method and it works as it should so far. The manual test looks like this, located in the <code>archive_file.py</code> file:</p> <pre><code>if __name__ == '__main__': archive = ArchiveFile() script_path = path.realpath(__file__) parent_dir = path.abspath(path.join(script_path, os.pardir)) targ_dir = path.join(parent_dir, 'files') targ_file = path.join(targ_dir, 'test.zip' ) archive.file = targ_file print(archive.file_count()) </code></pre> <p>All I do then is make sure that what's printed is what I expect given the contents of <code>test.zip</code>.</p> <p>Here's what <code>file_count</code> looks like:</p> <pre><code>def file_count(self): """Return the number of files in the archive.""" if self.file == None: return -1 with ZipFile(self.file) as zip: members = zip.namelist() # Remove folder members if there are any. pruned = [item for item in members if not item.endswith('/')] return len(pruned) </code></pre> <p>Directly translating this to a unit test seems wrong to me for a few reasons, some of which may be invalid. I'm counting on the precise location of the test files in relation to the current script file, I'll need a large sample of manually created archive files to make sure I'm testing enough variations, and, of course, I'm manually comparing the returned value to what I expect because I know how many files are in the test archive.</p> <p>It <em>seems</em> to me that this should be automated as much as possible, but it also seems that doing so is going to be very complicated.</p> <p>What's the proper way to create unit tests for such a class method?</p>
9
2016-07-22T13:41:25Z
38,533,332
<p>Suggest refactoring the pruning logic to a separate method that does not depend on file or ZipFile. This:</p> <pre><code>def file_count(self): ... with ZipFile(self.file) as zip: members = zip.namelist() # Remove folder members if there are any. pruned = [item for item in members if not item.endswith('/')] return len(pruned) </code></pre> <p>Becomes:</p> <pre><code>def file_count(self): ... with ZipFile(self.file) as zip: return len(self.prune_dirs(zip.namelist())) def prune_dirs(self, members): # Remove folder members if there are any. pruned = [item for item in members if not item.endswith('/')] return pruned </code></pre> <p>Now, testing prune_dirs can be done without any test files.</p> <pre><code>members = ["a/", "a/b/", "a/b/c", "a/b/d"] print archive.prune_dirs(members) </code></pre> <p>If you want to avoid integration testing, then you have to fake or mock ZipFile. In this case, any object that provides the method namelist() would do. </p> <pre><code>class FakeZipFile(): def __init__(self, filename): self.filename = filename def namelist(self): return ['a', 'b/', 'c'] </code></pre> <p>Now I introduce a new method get_helper() on ArchiveFile</p> <pre><code>class ArchiveFile(): def get_helper(self): return ZipFile(self.filename) def file_count(self): ... helper = self.get_helper() return len(self.prune_dirs(helper.namelist())) </code></pre> <p>...and override get_helper() in a Testing child class.</p> <pre><code>class ArchiveFileTesting(ArchiveFile): def get_helper(self): return FakeZipFile(self.file); </code></pre> <p>A testing class let's you override just what you need from ArchiveFile to eliminate the dependency on ZipFile. In your test, use the testing class and I think you have good coverage.</p> <pre><code>if __name__ == '__main__': archive = ArchiveFileTesting() </code></pre> <p>You will probably want to think of ways to change namelist so you can test more cases than the one shown here.</p>
0
2016-07-22T18:41:52Z
[ "python", "unit-testing" ]
How do I test a method that requires a file's presence?
38,528,004
<p>For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)</p> <p>The method is fairly simple, but it expects that the class has a <code>file</code> attribute set, that the attribute points to an existing file, and that the file is an archive of some sort (currently only working with zip files, tar, rar, etc., to be added later). The method is supposed to return the number of files in the archive.</p> <p>I've created a folder in my project called <code>files</code> that contains a few sample files, and I've manually tested the method and it works as it should so far. The manual test looks like this, located in the <code>archive_file.py</code> file:</p> <pre><code>if __name__ == '__main__': archive = ArchiveFile() script_path = path.realpath(__file__) parent_dir = path.abspath(path.join(script_path, os.pardir)) targ_dir = path.join(parent_dir, 'files') targ_file = path.join(targ_dir, 'test.zip' ) archive.file = targ_file print(archive.file_count()) </code></pre> <p>All I do then is make sure that what's printed is what I expect given the contents of <code>test.zip</code>.</p> <p>Here's what <code>file_count</code> looks like:</p> <pre><code>def file_count(self): """Return the number of files in the archive.""" if self.file == None: return -1 with ZipFile(self.file) as zip: members = zip.namelist() # Remove folder members if there are any. pruned = [item for item in members if not item.endswith('/')] return len(pruned) </code></pre> <p>Directly translating this to a unit test seems wrong to me for a few reasons, some of which may be invalid. I'm counting on the precise location of the test files in relation to the current script file, I'll need a large sample of manually created archive files to make sure I'm testing enough variations, and, of course, I'm manually comparing the returned value to what I expect because I know how many files are in the test archive.</p> <p>It <em>seems</em> to me that this should be automated as much as possible, but it also seems that doing so is going to be very complicated.</p> <p>What's the proper way to create unit tests for such a class method?</p>
9
2016-07-22T13:41:25Z
38,557,629
<p><a href="http://stackoverflow.com/users/5763213/oasiscircle">Oasiscircle</a> and <a href="http://stackoverflow.com/users/594589/dm03514">dm03514</a> were very helpful on this and lead me to the right answer eventually, especially with dm's answer to a <a href="http://stackoverflow.com/questions/38556197/how-do-i-mock-a-classs-functions-return-value">followup question</a>.</p> <p>What needs to be done is to use the <code>mock</code> library to create a fake version of <code>ZipFile</code> that won't object to there not actually being a file, but will instead return valid lists when using the <code>nameslist</code> method.</p> <pre><code>@unittest.mock.patch('comicfile.ZipFile') def test_page_count(self, mock_zip_file): comic_file = ComicFile() members = ['dir/', 'dir/file1', 'dir/file2'] mock_zip_file.return_value.__enter__.return_value.namelist.return_value \ = members self.assertEqual(2, self.comic_file.page_count()) </code></pre> <p>The <code>__enter__.return_value</code> portion above is necessary because in the code being tested the <code>ZipFile</code> instance is being created within a context manager.</p>
0
2016-07-24T22:52:17Z
[ "python", "unit-testing" ]
SWIG typemap from C char* to python string
38,528,102
<p>I am trying to use a C library in Python using SWIG. This C library passes function results through arguments everywhere. Using the online SWIG manual, I have succeeded in getting an integer function result passed to Python, but I am having a hard time figuring out how to do this for a character string. </p> <p>This is the essence of my code: </p> <p><em>myfunc.c</em>:</p> <pre><code>#include &lt;myfunc.h&gt; #include &lt;stdio.h&gt; int mystr(int inp, char *outstr){ outstr="aaa"; printf("%s\n", outstr); return(0); } </code></pre> <p><em>myfunc.h</em>:</p> <pre><code>extern int mystr(int inp, char *outstr); </code></pre> <p>So basically my question is what the typemap for *outstr should look like. </p> <p>Thanks in advance. </p>
0
2016-07-22T13:45:54Z
38,539,335
<p>Have a look at the SWIG manual <a href="http://www.swig.org/Doc3.0/SWIGDocumentation.html#Library_nn12" rel="nofollow">9.3.4 String handling: cstring.i</a>. This provides several typemaps for use with <code>char *</code> arguments.</p> <p>Probably (assuming you are indeed using <code>strcpy(outstr, "aaa")</code> as mentioned in a comment above) you want in your SWIG interface file, before the function declaration, e.g.:</p> <pre><code>%include &lt;cstring.i&gt; %cstring_bounded_output(char* outstr, 1024); </code></pre>
1
2016-07-23T07:30:44Z
[ "python", "c", "swig", "typemaps" ]
SWIG typemap from C char* to python string
38,528,102
<p>I am trying to use a C library in Python using SWIG. This C library passes function results through arguments everywhere. Using the online SWIG manual, I have succeeded in getting an integer function result passed to Python, but I am having a hard time figuring out how to do this for a character string. </p> <p>This is the essence of my code: </p> <p><em>myfunc.c</em>:</p> <pre><code>#include &lt;myfunc.h&gt; #include &lt;stdio.h&gt; int mystr(int inp, char *outstr){ outstr="aaa"; printf("%s\n", outstr); return(0); } </code></pre> <p><em>myfunc.h</em>:</p> <pre><code>extern int mystr(int inp, char *outstr); </code></pre> <p>So basically my question is what the typemap for *outstr should look like. </p> <p>Thanks in advance. </p>
0
2016-07-22T13:45:54Z
38,561,366
<p>This is how I got it to work, by modifying the example in section 34.9.3 of the <a href="http://swig.org/Doc2.0/Python.html#Python_nn53" rel="nofollow">SWIG 2.0 manual</a>:</p> <pre><code>%typemap(in, numinputs=0) char *outstr (char temp) { $1 = &amp;temp; } %typemap(argout) char *outstr { PyObject *o, *o2, *o3; o = PyString_FromString($1); if ((!$result) || ($result == Py_None)) { $result = o; } else { if (!PyTuple_Check($result)) { PyObject *o2 = $result; $result = PyTuple_New(1); PyTuple_SetItem($result,0,o2); } o3 = PyTuple_New(1); PyTuple_SetItem(o3,0,o); o2 = $result; $result = PySequence_Concat(o2,o3); Py_DECREF(o2); Py_DECREF(o3); } } </code></pre>
0
2016-07-25T06:52:33Z
[ "python", "c", "swig", "typemaps" ]
Write html tags to text file in python
38,528,179
<p>I've used pdfminer to convert complex (tables, figures) and very long pdfs to html. I want to parse the results further (e.g. extract tables, paragraphs etc) and then use sentence tokenizer from nltk to do further analysis. For this purposes I want to save the html to text file to figure out how to do the parsing. Unfortunately my code does not write html to txt:</p> <pre><code>from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import HTMLConverter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO def convert_pdf_to_html(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = HTMLConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = file(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 #is for all caching = True pagenos=set() for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) fp.close() device.close() str1 = retstr.getvalue() retstr.close() return str1 with open("D:/my_new_file.txt", "wb") as fh: fh.write(str1) </code></pre> <p>Besides, the code prints the whole html string in the shell: how can I avoid it?</p>
0
2016-07-22T13:49:38Z
38,528,423
<p>First, unless there's a trivial error, </p> <p>the .txt write happens after the return function: txt file write is never executed!</p> <p>Then, to suppress output to the console, just do that before running your routine:</p> <pre><code> import sys,os oldstdout = sys.stdout # save to be able to restore it later sys.stdout = os.devnull </code></pre>
0
2016-07-22T14:02:37Z
[ "python", "io", "pdftotext", "pdfminer", "pdf-to-html" ]
How to use super() with arguments in Python 2.7?
38,528,215
<p>I am asking this question because every single other page on SO I've Googled on the subject seems to devolve into overly simple cases or random discussions on details beyond the scope.</p> <pre><code>class Base: def __init__(self, arg1, arg2, arg3, arg4): self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 self.arg4 = arg4 class Child(Base): def __init__(self, arg1, arg2, arg3, arg4, arg5): super(Child).__init__(arg1, arg2, arg3, arg4) self.arg5 = arg5 </code></pre> <p>This is what I've tried. I get told that I need to use a type and not a classobj, but I don't know what that means and Google isn't helping. </p> <p>I just want it to work. What is the correct practice in doing so in Python 2.7? </p>
0
2016-07-22T13:52:02Z
38,528,264
<p>Your base class must inherit from <code>object</code> (new style class) and the call to <code>super</code> should be <code>super(Child, self)</code>.</p> <p>You should also not pass <code>arg5</code> to <code>Base</code>'s <code>__init__</code>.</p> <pre><code>class Base(object): def __init__(self, arg1, arg2, arg3, arg4): self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 self.arg4 = arg4 class Child(Base): def __init__(self, arg1, arg2, arg3, arg4, arg5): super(Child, self).__init__(arg1, arg2, arg3, arg4) self.arg5 = arg5 </code></pre>
5
2016-07-22T13:54:26Z
[ "python", "python-2.7", "class", "arguments", "super" ]
How to get previous date from a date without saturday,sunday and holiday?
38,528,332
<p>Need to get previous date from given without sat, sun and holidays(table).</p> <p>Leave scenerio.</p> <pre><code>f_date=self.get_query_argument("from_date") date_1 = datetime.strptime(f_date,"%Y-%m-%d") bef_date = date_1 - timedelta(days=1) if bef_date.weekday()==5: prev_date = bef_date - timedelta(days=1) elif bef_date.weekday()==6: prev_date = bef_date - timedelta(days=2) else: prev_date =bef_date </code></pre> <p>I got here the previous date without saturday and sunday but dono how to get it without holiday mentioned in table.</p> <p>I already referred this link but struggling to omit holiday.</p> <p>Advance thanks</p>
1
2016-07-22T13:57:51Z
38,528,474
<p>try using "in" on your table</p> <pre><code>foo = [1,2,3,4,5] 2 in foo </code></pre> <p>returns "True"</p> <p>for dates</p> <pre><code>d1 = (datetime.datetime.now()-datetime.timedelta(1)).date() d2 = (datetime.datetime.now()-datetime.timedelta(2)).date() d3 = (datetime.datetime.now()-datetime.timedelta(3)).date() listOfHolidays = [d1,d2,d3] (datetime.datetime.now()-datetime.timedelta(2)).date() in listOfHolidays </code></pre>
0
2016-07-22T14:04:35Z
[ "python" ]
How can I create a tuple consisting of class objects?
38,528,367
<p>This question is for Python version 2.7. For example, if I have the following class:</p> <pre><code>class Example: def __init__(self, a, b): self.a = a self.b = b object = Example("x", "y") t = tuple(object) </code></pre> <p>After executing the code above I get <code>TypeError: iteration over non-sequence</code> because I can only store a single variable of the object inside the tuple and not the object itself. My question is, is there an easy solution to store class objects in tuples such that <code>tuple = (o1, o2, o3)</code> where <code>o1, o2 and o3</code> are objects?</p>
2
2016-07-22T13:59:25Z
38,528,392
<p>You don't have to call <code>tuple</code> on the object to do this:</p> <pre><code>obj = Example("x", "y") t = (obj,) # one item tuple </code></pre> <p>Be careful to not use the name <code>object</code> to not shadow the builtin <code>object</code> class.</p> <p>To create a tuple with more than one item:</p> <pre><code>t = (obj1, obj2, obj3) </code></pre> <p>Note that the <em>parenthesis</em> serve only for grouping and removing them will not have any effect.</p>
2
2016-07-22T14:01:13Z
[ "python", "python-2.7", "tuples" ]
How can I create a tuple consisting of class objects?
38,528,367
<p>This question is for Python version 2.7. For example, if I have the following class:</p> <pre><code>class Example: def __init__(self, a, b): self.a = a self.b = b object = Example("x", "y") t = tuple(object) </code></pre> <p>After executing the code above I get <code>TypeError: iteration over non-sequence</code> because I can only store a single variable of the object inside the tuple and not the object itself. My question is, is there an easy solution to store class objects in tuples such that <code>tuple = (o1, o2, o3)</code> where <code>o1, o2 and o3</code> are objects?</p>
2
2016-07-22T13:59:25Z
38,528,579
<p>Your problem doesn't really have to do with the type of the tuple's elements, but rather with single-item tuples. From the <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">documentation</a>:</p> <blockquote> <p>A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).</p> </blockquote> <p>Note the following:</p> <pre><code>In [1]: a = (1) In [2]: type(a) Out[2]: int In [3]: a = (1, ) In [4]: type(a) Out[4]: tuple In [5]: a = 1, In [6]: type(a) Out[6]: tuple </code></pre>
1
2016-07-22T14:09:12Z
[ "python", "python-2.7", "tuples" ]
Send parameters to a user-defined function?
38,528,371
<p>We define a user-defined function as follows.</p> <pre><code>def testfun(x): return( x[0]*a+x[1]*b) </code></pre> <p>Call the function:</p> <pre><code>sol = optimize.root(testfun, [0, 0], method = 'lm') </code></pre> <p>How can we pass <code>a</code> and <code>b</code> when calling the function ?</p>
-2
2016-07-22T13:59:35Z
38,528,406
<p>For this problem specifically, <code>optimize.root</code> has an <code>args</code> input which accepts a tuple of values to pass as additional inputs to your objective function:</p> <pre><code>def testfun(x, a, b): return ([x[0] * a + x[1] * b]) # Specify values for a and b a = 1 b = 2 sol = optimize.root(testfun, [0, 0], method='lm', args=(a, b)) </code></pre> <p>More generally, you can use a lambda function to provide additional inputs to any function</p> <pre><code># Create a lambda function which passes the input provided by optimize.root and adds # two more inputs: a and b func = lambda x: testfun(x, a, b) # Pass this lambda function to optimize.root sol = optimize.root(func, [0, 0], method='lm') </code></pre>
4
2016-07-22T14:01:42Z
[ "python", "python-3.x", "scipy" ]
How to efficiently replace element in plot with ipywidgets?
38,528,426
<p>How can I efficiently display similar plots with ipywidgets using Jupyter Notebook?</p> <p>I wish to plot interactively a heavy plot (heavy in the sense that it has lots of data points and takes some time to plot it) and modify a single element of it using interact from ipywidgets without replotting all the complicated plot. Is there a builtin functionality to do this?</p> <p>basically what I'm trying to do is</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact import matplotlib.patches as patches %matplotlib inline #ideally nbagg def complicated plot(t): plt.plot(HEAVY_DATA_SET) ax = plt.gca() p = patches.Rectangle(something_that_depends_on_t) ax.add_patch(p) interact(complicatedplot, t=(1, 100)); </code></pre> <p>Right now it takes up to 2 seconds for each replot. I expect there are ways to keep the figure there and just replace that rectangle.</p> <p>A hack would be to create a figure of the constant part, make it background to the plot and just plot the rectangle part. but the sounds too dirty</p> <p>Thank you</p>
0
2016-07-22T14:02:46Z
38,529,367
<p>This is an rough example of an interactive way to change a rectangle width (I'm assuming you are in an IPython or Jupyter notebook):</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches import ipywidgets from IPython.display import display %matplotlib nbagg f = plt.figure() ax = plt.gca() ax.add_patch( patches.Rectangle( (0.1, 0.1), # (x,y) 0.5, # width 0.5, # height ) ) # There must be an easier way to reference the rectangle rect = ax.get_children()[0] # Create a slider widget my_widget = ipywidgets.FloatSlider(value=0.5, min=0.1, max=1, step=0.1, description=('Slider')) # This function will be called when the slider changes # It takes the current value of the slider def change_rectangle_width(): rect.set_width(my_widget.value) plt.draw() # Now define what is called when the slider changes my_widget.on_trait_change(change_rectangle_width) # Show the slider display(my_widget) </code></pre> <p>Then if you move the slider, the width of the rectangle will change. I'll try to tidy up the code, but you may have the idea. To change the coordinates, you have to do <code>rect.xy = (x0, y0)</code>, where <code>x0</code> and <code>y0</code> are new coordinates.</p>
1
2016-07-22T14:47:13Z
[ "python", "matplotlib", "jupyter", "jupyter-notebook", "ipywidgets" ]
print elements in list as concatenated string
38,528,453
<p>I have a simple dictionary: </p> <pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} </code></pre> <p>and list</p> <pre><code>letters = ('a', 'b', 'c', 'd') </code></pre> <p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenated string</strong>. I'm using:</p> <pre><code>for c in letters: print convert[c], </code></pre> <p>which outputs:</p> <pre><code>1 2 3 4 </code></pre> <p>How can I remove the spaces (in v.2.7.10) in the print statement to get:</p> <pre><code>1234 </code></pre>
2
2016-07-22T14:03:58Z
38,528,490
<p>Use <a href="https://docs.python.org/2.7/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> with a generator expression. Note that you have to explicitly convert to <code>str</code> when using this method:</p> <pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} letters = ('a', 'b', 'c', 'd') print ''.join(str(convert[c]) for c in letters) &gt;&gt; 1234 </code></pre> <p><strong>UPDATE</strong></p> <p>If you want to do it using an explicit <code>for</code> loop, you can create a list of strings, appending to that and calling <code>join</code> outside the loop. I'm using a list since it is more efficient because strings are immutable:</p> <pre><code>output_list = [] for c in letters: # do other stuff output_list.append(str(convert[c])) print ''.join(output_list) </code></pre>
4
2016-07-22T14:05:08Z
[ "python", "python-2.7", "printing" ]
print elements in list as concatenated string
38,528,453
<p>I have a simple dictionary: </p> <pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} </code></pre> <p>and list</p> <pre><code>letters = ('a', 'b', 'c', 'd') </code></pre> <p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenated string</strong>. I'm using:</p> <pre><code>for c in letters: print convert[c], </code></pre> <p>which outputs:</p> <pre><code>1 2 3 4 </code></pre> <p>How can I remove the spaces (in v.2.7.10) in the print statement to get:</p> <pre><code>1234 </code></pre>
2
2016-07-22T14:03:58Z
38,528,991
<p>If all you want is to <code>print</code> only and you don't need the end result, then you can use the <code>arg</code> of <a href="https://docs.python.org/2/library/functions.html#print" rel="nofollow"><code>print</code></a> method:</p> <pre><code>&gt;&gt;&gt; from __future__ import print_function &gt;&gt;&gt; for c in letters: print(convert[c], sep='', end='') 1234 </code></pre>
1
2016-07-22T14:28:59Z
[ "python", "python-2.7", "printing" ]