input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Pandas Insert a row above the Index and the Series data in a Dataframe I ve been around several trials nothing seems to work so far I have tried `df insert(0 "XYZ" 555)` which seemed to work until it did not for some reasons i am not certain I understand that the issue is that Index is not considered a Series and so df iloc[0] does not allow you to insert data directly above the Index column I ve also tried manually adding in the list of indices part of the definition of the dataframe a first index with the value "XYZ" but nothing has work Thanks for your help A B C D are my columns range(5) is my index I am trying to obtain this below for an arbitrary row starting with type and then a list of strings thanks ```` A B C D type 'string1' 'string2' 'string3' 'string4' 0 1 2 3 4 ```` If you use Timestamps as Index adding a row and a custom single row with its own custom index will throw an error: ValueError: Cannot add integral value to Timestamp without offset I am guessing it is due to the difference in the operands if i substract an Integer from a Timestamp for example ? how could i fix this in a generic manner? thanks! â | if you want to insert a row <strong>before</strong> the first row you can do it this way: data: ````In [57]: df Out[57]: id var 0 a 1 1 a 2 2 a 3 3 b 5 4 b 9 ```` adding one row: ````In [58]: df loc[df index min() - 1] = ['z' -1] In [59]: df Out[59]: id var 0 a 1 1 a 2 2 a 3 3 b 5 4 b 9 -1 z -1 ```` sort index: ````In [60]: df = df sort_index() In [61]: df Out[61]: id var -1 z -1 0 a 1 1 a 2 2 a 3 3 b 5 4 b 9 ```` optionally reset your index : ````In [62]: df = df reset_index(drop=True) In [63]: df Out[63]: id var 0 z -1 1 a 1 2 a 2 3 a 3 4 b 5 5 b 9 ```` |
Hexcode generator in python I am trying to generate a hexcode generator in python for an assigment in school I would like to bruteforce the address space however I am not able to construct real hexcodes in python my script: ```` for j in range(0 100): var = "\\x%x" % j newpath = "\xa0\xf4\xff"+var print newpath ```` The bytecodes "\xa0\xf4\xff" gets printed correctly - as proper hexcodes However my bruteforcer is not able to generate real hexcodes but only strings "\xab" etc How do I generate real hexcodes: Essentially I would like to generate the entire address space of a 32-bit machine EDIT: More specifically by looking at some arbitrary output you can see the last "hexcode" is not considered a hexcode but rather a string: ```` ���\x5d ���\x5e ���\x5f ���\x60 ���\x61 ���\x62 ���\x63 ```` | Hex is just a different representation of a number It is using base 16 instead of base 10 which is what we are normally used to With that in mind any number is can be represented as a hex number: ````for i in range(0 0x20): print "0x%08X" %i ```` the output is ````0x00000000 0x00000001 0x00000002 0x00000003 0x0000000E 0x0000000F 0x00000010 0x00000011 ```` By using `%X` in the print statement we say "interpret as base 16" You can also specify a number in its hex representation as I did in the `range(0 0x20)` statement The reason that you see the printout of `"\xa0\xf4\xff"` is because python cannot substitute the values in that string into characters and prints the next best thing a string representation of the number Do not confuse an array of four bytes with its 32 bit word representation or its four character string representation <them>it is the same thing!</them> I would recommend you to play around with the built in functions `ord()` `hex()` and `chr()` to get a feeling for how things work Example: ````print ord('a') print hex(10) print chr(97) ```` output: ````97 0xa a ```` |
Having trouble resolving a 'list index out of range' error I am having trouble resolving a 'list index out of range' error The code seems to operate fine until a certain point when file_no2 = line2 split()[0] generates the index error The error shows up 70 lines before the end of the file that is being read so I cannot figure why the 'list index out of range error' occurs I am attempting to iterate through the file until line2 is populated by the last line of data in the file so I used the range function with a previously calculated sum of the number of lines in the file (l) I subtracted 1 in the range calculation with the intent to stop the loop once line1 is populated by the second to last line in the file But again the index error is stopping the process 70 lines short of the end of the file so I do not understand why it is out of range ````for i in range(l-1): line1 = trackdata readline() line2 = trackdata readline() file_no1 = line1 split()[0] time1 = line1 split()[1] x1 = line1 split()[2] y1 = line1 split()[3] length1 = line1 split()[4] flow_dir1 = float(line1 split()[5]) flow_mag1 = line1 split()[6] file_no2 = line2 split()[0] time2 = line2 split()[1] x2 = line2 split()[2] y2 = line2 split()[3] length2 = line2 split()[4] flow_dir2 = float(line2 split()[5]) flow_mag2 = line2 split()[6] if file_no1 == file_no2: if abs(flow_dir2 - flow_dir1) > 90 0: print x1 y1 #print >> coordinates2 x2 y2 ```` Here is an example of the results: <blockquote> 185313 5426 112700 3316 1091 153 4636750 184498 3329 112815 9754 100 0000000 344 7592449 0 6516200005 184500 6344 112716 0019 1091 649 7940156 184461 4951 113012 3586 300 0000000 353 5487391 0 3463617710 1091 1599 736768 184398 7140 113126 0630 440 6196278 341 8759486 0 1121731124 1091 1734 946452 184382 9241 113119 2729 457 9156941 349 0664262 0 1303822198 1123 0 0000000000 184110 8309 113518 9487 0 0000000000 271 3035311 0 1646996924 </blockquote> And the error message: <blockquote> Traceback (most recent call last): File "O:\ArcGIS\courseypond\particletrack\check_trackangle_5yr" line 28 in > file_no2 = line2 split()[0] IndexError: list index out of range </blockquote> The input data is read from a space-delimited text file that contains 14910 lines Each line of data is formatted as in the example results above: file number time x-coordinate y-coordinate length flow direction flow magnitude The goal is to identify and store the coordinate points when two lines with the same file number identifier show a flow direction change greater than 90 degrees | Thank you for the suggestions It appears that I managed to resolve the issue by relocating the initial line1 and line2 assignments outside of the loop and reassigning line1 to equal line2 at the end of the loop No more 'list index out of range error' and each line of data from the file appears to get paired for comparison The updated code is as follows: ````line1 = trackdata readline() line2 = trackdata readline() for i in range(l-1): file_no1 = line1 split()[0] time1 = line1 split()[1] x1 = line1 split()[2] y1 = line1 split()[3] length1 = line1 split()[4] flow_dir1 = float(line1 split()[5]) flow_mag1 = line1 split()[6] file_no2 = line2 split()[0] time2 = line2 split()[1] x2 = line2 split()[2] y2 = line2 split()[3] length2 = line2 split()[4] flow_dir2 = float(line2 split()[5]) flow_mag2 = line2 split()[6] if file_no1 == file_no2: if abs(flow_dir2 - flow_dir1) > 90 0: print x1 y1 #print >> coordinates2 x2 y2 line1 = line2 line2 = trackdata readline() ```` |
Who criticized Lee in The Wall Street Journal? | Allen Barra |
Loading Unicode data from mysql to Redshift fails with "Bad UTF8 hex sequences" I am trying to create a simple table replicator from MySQL to Redshift using Python The way I am doing this is to query tables in MySQL and write the output to CSVs using Python (2 7) then ship those up to S3 and do a COPY on them into their respective target tables I am running into a problem with Unicode characters Specifically I get the following error: `String contains invalid or unsupported UTF8 codepoints Bad UTF8 hex sequence: e9 20 50 (error 4)` My question here is whether this is a python problem or an S3/Redshift problem Here is what I am doing in python: ````import unicodecsv as csv csv_writer = csv writer(dest encoding='utf-8') for index line in enumerate(a): if index == len(a)/2: file_ext+=1 if dest: dest close() dest = open(config['data_dir'] directory '/' table_name ' txt ' str(file_ext) 'wb') csv_writer = csv writer(dest encoding='utf-8') csv_writer writerow(line) ```` So from what I understand Python is writing things correctly Indeed if I open up the CSV in VI I can see this: `"Fjällräven Canvas Black Kanken 15\ Laptop Bag"""` So that looks right to me (the \ and extra " are junk from the source) However if I run file against the csv I get: `ASCII text with very long lines with CRLF line terminators` After moving the file to S3 and running a copy I end up with the above Redshift COPY error And so back to the question: I suspect this has something to do with the way the <them>file</them> is encoded not the content that is in there but I have not been able to find anything definitive about that through my searches Has anyone encountered this and have they found a solution? Thanks for the help | Turns out that everything I showed above was fine but that MySQL was not exporting UTF-8 characters It was fixed by adding the following two lines to my connection string: ````'use_unicode' : True 'charset':'utf8' ```` |
Pandas read_clipboard broken in pandas 0 12? Since I updated pandas from version 0 11 to 0 12 read_clipboard does not seem to work anymore: ````import pandas as pd df = pd read_clipboard() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-2-6dead334eb54> in <module>() ---> 1 df = pd read_clipboard() C:\Python33\lib\site-packages\pandas\io\clipboard py in read_clipboard(**kwargs) 16 from pandas io parsers import read_table 17 text = clipboard_get() --> 18 return read_table(StringIO(text) **kwargs) 19 20 TypeError: initial_value must be str or None not bytes ```` What I did was: - Open a csv file in Excel 2010 - Copy a range of cells including headers - Perform read_clipboard in iPython Qt console as described in above code block After downgrading to 0 11 this procedure worked fine again I am using pandas for python 3 3 Win7 32 bit Is this a bug in pandas? Any suggestions on how to resolve this issue? | Its a bug in the string presented to py3; I will fix it in master but you can do this local edit in `C:\python33\Lib\site-packages\pandas\io\clipboard py` after `text = clipboard_get()` add `text = text decode('UTF-8')` apparently the clipboard routine gives you back bytes (and not a string) in py3 |
IPython no subprocess I am new to IPython but I have programmed a lot in IDLE Using the Python "turtle" module in Windows the turtle graphics window freezes up until you get it to start with "no subprocess " This was just a matter of adding "-n" to the shortcut How can I do this in an IPython notebook? Now it is freezing again I am using WinPython I have not found any references online to this problem in IPython yet Thanks in advance! | If you use `turtle` module from an ordinary `ipython` console then it should work fine (the same single python process) `ipython notebook` has no "no subprocess" option -- a web browser does not execute Python code (by default) therefore `ipython notebook` uses a server python process to run Python code To execute Python code in a browser you could use <a href="http://www skulpt org/" rel="nofollow">Skulpt</a> e g <a href="http://interactivepython org/courselib/static/thinkcspy/index html" rel="nofollow">How to Think Like a Computer Scientist Learning with Python: Interactive Edition 2 0</a> Skulpt supports `turtle` module |
Python csvwriter does not like unicode tl;dr I have a complicated SQL query that returns results in csv format Unfortunately the downside to being Canadian is that a bunch of people just love to add accents to their names At the moment this is what I have I did not write the script initially just trying to make it work to grab the data The SQL is correct just truncated by nano ````def getCommentsByGUID(reportDay): conn = mysql connector connect(host = dbServer user = dbUser passwd = dbPass db = tscDBName) sqlresult = '' sql = 'select d documentId dn created dn notes as Comment you login d fileName from DocumentInfo d \ inner join documentnotes dn on d documentId=dn documentId \ inner join User you on dn userId=you userID \ where d companyId=%d and dn created>\'%s 00:00:00\' and dn created <\'%s 23:59:59\';' % (companyID reportDay reportDa$ cursor = conn cursor() cursor execute (sql) sqlresult = cursor fetchall() cursor close () reportWriter = csv writer(open('%sFilename_comments_%s csv' % (outputDir reportDay) 'w') delimiter=' ' quotec$ for results in sqlresult: reportWriter writerow(results) ```` Running as is creates a unicode error such as: `UnicodeEncodeError: 'ascii' codec cannot encode character you'\u2019' in position 366: ordinal not in range(128)` Now after a lot of research I have come across something like this: ````for results in sqlresult: try: reportWriter writerow(results) except UnicodeEncodeError: s = list(results) for item in s: if isinstance(item basestring) == True: a = s index(item) unicodedata normalize('NFKD' item) encode('ascii' 'ignore') s[a] = item print item s = tuple(s) print s reportWriter writerow(s) ```` Yet still get the same error: ````UnicodeEncodeError: 'ascii' codec cannot encode character you'\u2019' in position 366: ordinal not in range(128) ```` Any ideas on what I am either doing wrong or what else I can try? Thanks! | The MySQL connection is apparently returning strings as `unicode` objects while the filehandle passed to `csv writer` was not opened with a specific encoding and thus expects to be given `str` objects representing raw bytes Solution 1: Encode the strings in your preferred encoding (presumably UTF-8) before passing them to `writerow`: ````for results in sqlresult: results = [x encode('utf-8') if isinstance(x unicode) else x for x in results] reportWriter writerow(results) ```` Solution 2: Open the output filehandle in a Unicode-aware mode: ````import io reportWriter = csv writer(io open('%sFilename_comments_%s csv' % (outputDir reportDay) 'w' encoding='utf-8') delimiter=' ' quotec$ ```` |
Module_six_moves_urllib_parse object has no attribute urlparse when using plot ly for Python I am running below code in Jupyter: ````import plotly plotly as py import plotly graph_objs as go # Create random data with numpy import numpy as np N = 100 random_x = np linspace(0 1 N) random_y0 = np random randn(N)+5 random_y1 = np random randn(N) random_y2 = np random randn(N)-5 # Create traces trace0 = go Scatter( x = random_x y = random_y0 mode = 'markers' name = 'markers' ) trace1 = go Scatter( x = random_x y = random_y1 mode = 'lines+markers' name = 'lines+markers' ) trace2 = go Scatter( x = random_x y = random_y2 mode = 'lines' name = 'lines' ) data = [trace0 trace1 trace2] # Plot and embed in ipython notebook! py iplot(data filename='scatter-mode') ```` I got error result as: <blockquote> /Library/Python/2 7/site-packages/requests/packages/urllib3/util/ssl_ py:315: SNIMissingWarning: An HTTPS request has been made but the SNI (Subject Name Indication) extension to TLS is not available on this platform This may cause the server to present an incorrect TLS certificate which can cause validation failures For more information see <a href="https://urllib3 readthedocs org/en/latest/security html#snimissingwarning" rel="nofollow">https://urllib3 readthedocs org/en/latest/security html#snimissingwarning</a> SNIMissingWarning /Library/Python/2 7/site-packages/requests/packages/urllib3/util/ssl_ py:120: InsecurePlatformWarning: A true SSLContext object is not available This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail For more information see <a href="https://urllib3 readthedocs org/en/latest/security html#insecureplatformwarning" rel="nofollow">https://urllib3 readthedocs org/en/latest/security html#insecureplatformwarning</a> InsecurePlatformWarning /Library/Python/2 7/site-packages/requests/packages/urllib3/util/ssl_ py:120: InsecurePlatformWarning: A true SSLContext object is not available This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail For more information see <a href="https://urllib3 readthedocs org/en/latest/security html#insecureplatformwarning" rel="nofollow">https://urllib3 readthedocs org/en/latest/security html#insecureplatformwarning</a> --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () 34 35 # Plot and embed in ipython notebook! ---> 36 py iplot(data filename='scatter-mode') /Library/Python/2 7/site-packages/plotly/plotly/plotly pyc in iplot(figure_or_data **plot_options) 173 embed_options['height'] = str(embed_options['height']) 'px' 174 --> 175 return tools embed(url **embed_options) 176 177 /Library/Python/2 7/site-packages/plotly/tools pyc in embed(file_owner_or_url file_id width height) 407 else: 408 url = file_owner_or_url --> 409 return PlotlyDisplay(url width height) 410 else: 411 if (get_config_defaults()['plotly_domain'] /Library/Python/2 7/site-packages/plotly/tools pyc in <strong>init</strong>(self url width height) 1382 def <strong>init</strong>(self url width height): 1383 self resource = url -> 1384 self embed_code = get_embed(url width=width height=height) 1385 super(PlotlyDisplay self) <strong>init</strong>(data=self embed_code) 1386 /Library/Python/2 7/site-packages/plotly/tools pyc in get_embed(file_owner_or_url file_id width height) 313 "\nRun help on this function for more information " 314 "" format(url plotly_rest_url)) --> 315 urlsplit = six moves urllib parse urlparse(url) 316 file_owner = urlsplit path split('/')[1] split('~')[1] 317 file_id = urlsplit path split('/')[2] AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlparse' </blockquote> I have tried everything to fix it via this thread <a href="http://stackoverflow com/questions/29190604/attribute-error-trying-to-run-gmail-api-quickstart-in-python">Attribute Error trying to run Gmail API quickstart in Python</a> - I did the `export PYTHONPATH=/Library/Python/2 7/site-packages` and make sure I unset it first to blank (yes that path exists on my Mac) - I updated `w3lib (1 13 0)` and `six (1 10 0)` - Jupyter 4 0 6 and Python 2 7 6 What else could go wrong? Please help | I realized I picked a wrong kernel in Jupyter So if it is PySpark kernel it gave me error If I use Python2 or Python3 kernel it is fine |
BWhat industry does South Park give priority to other than electronic informatiom? | null |
How to reshape array inside an astropy coordinate SkyCoord object? I want to make a 2D contour plot using <strong>one</strong> `SkyCoord` object <strong>containing an array</strong> of coordinates as an input parameter To do this I wanted to make a mesh gird over parameters The code is something like this ````l = np linspace(0 360 180) b = np linspace(-90 90 90) # Two axes I wanted to make contour on y=y reshape(y size 1 1) #(originally) an 1D array the same size as `coords` l=l reshape(1 l size 1) b=b reshape(1 1 b size) coords = coords reshape(y shape) # No this does not work coords shape = y shape # You cannot write attributes like this How frustrating z = Something_Fun((l b) y coords) ```` The problem comes here I tried to use `np meshgird` over `coords` but it returns a <strong>`np array`</strong> of `SkyCoord` rather than <strong>one</strong> `SkyCoord` object <strong>containing</strong> an array of coordinates which is not what I want For the function `Something_Fun` calls member functions of `SkyCoord` which certainly does not work with a `np array` Unfortunately a built-in `reshape` method is <strong>not provided</strong> for `SkyCoord` even though it <strong>does</strong> have a `shape` method! If keep the shape of `coords` the code will not work because operations cannot broadcast with arrays of different dimensions Is there any elegant way to do this? I do not wish to rewrite codes that generates `coords` or the function `Something_Fun` because it would mess up many other things Exporting `SkyCoord` data to string and import again might do the trick but is much too "dirty" and loses precision I might try it as a last resort | Ok I have come up with an solution on my own It still involves exporting and import back and forth but it would not lose precision And it just works ````coords=SkyCoord(coords ra reshape(y shape) coords dec reshape(y shape)) ```` Wish they would provide an built-in `reshape` method in the future which would save me some time~ |
How does one set specific vim-bindings in Ipython 5 0 0 I understand that because Ipython 5 0 0 uses a new input library (prompt_toolkit) it no longer defaults to the editor mode specified in inputrc (*nix) This option has to be set in an Ipython profile configuration file (see <a href="http://stackoverflow com/a/38329940/2915339">http://stackoverflow com/a/38329940/2915339</a>) My question is: having set vi-mode in the profile configuration file how does one specify a particular keybinding? I like to use 'jk' for escape for instance | You are right `prompt_toolkit` ignores ` inputrc` There does not seem to be a way to define custom keybindings for the `vi` mode in the IPython 5 0 0 profile configuration file Here is workaround I am currently using It is not pretty but it works for now According to the <a href="http://ipython readthedocs io/en/latest/config/details html#keyboard-shortcuts" rel="nofollow">IPython docs</a> you can specify Keyboard Shortcuts in a startup configuration script Instead of rebinding `jk` to `ESC` I am making a unicode "j" (`you'j'`) followed by a unicode "k" (`you'k'`) inside of `VimInsertMode()` a shortcut for a `prompt_toolkit` event that switches to navigation mode I created a ` ipython/profile_default/startup/keybindings py` with the following code: ````from IPython import get_ipython from prompt_toolkit enums import DEFAULT_BUFFER from prompt_toolkit filters import HasFocus ViInsertMode from prompt_toolkit key_binding vi_state import InputMode ip = get_ipython() def switch_to_navigation_mode(event): vi_state = event cli vi_state vi_state reset(InputMode NAVIGATION) if getattr(ip 'pt_cli'): registry = ip pt_cli application key_bindings_registry registry add_binding(you'j' you'k' filter=(HasFocus(DEFAULT_BUFFER) & ViInsertMode()))(switch_to_navigation_mode) ```` <a href="https://github com/jonathanslenders/python-prompt-toolkit/blob/4aa0404ad7e770763b85764fd42c8dbce94f9c62/prompt_toolkit/key_binding/bindings/vi py" rel="nofollow">The prompt_toolkit source</a> will help you implement other shortcuts as needed |
replaces multiple occurances of a character (except for first and last) in a python string I want to know what is the most concise way to achieve the following in python: Given a string with a <them>minimum</them> of 2 ' ' characters (e g 'abc 123 #$@5 dg') I want to create a new string with the first and last ' ' characters from the original string intact but replaces every other occurrences of ' ' with the '_' character Here are some sample inputs/outputs: <strong>Input:</strong> ````str1 = 'abc 1 2201-3' ```` <strong>Output:</strong> ````str2 = 'abc 1 2201-3' ```` <strong>Input:</strong> ````str1 = '$2a$10$ XfjKl/ abcd 1 ## s for free 2-3-4' ```` <strong>Output:</strong> ````str2 = '$2a$10$ XfjKl/ abcd_ 1_ ##_ s_ for free 2-3-4' ```` One way to do this is to split the string into a list by the ' ' character use '_' to join the middle element of the list then just create a new string using the first element ' ' middle elements ' ' last element Is there a more concise way of doing this (maybe using Regex)? | ````str1 = '$2a$10$ XfjKl/ abcd 1 ## s for free 2-3-4' parts = str1 split(' ') str2 = '{} {} {}' format(parts[0] '_' join(parts[1:-1]) parts[-1]) ```` |
Flask-Migrate "No section: 'alembic'" on "db migrate" command I am using Flask-Migrate and I am trying to add a column to my database by using the db migrate command Here is the setup: ````from flask import Flask render_template request session flash redirect url_for from flask ext babel import Babel from flask ext mail import Mail from flask ext script import Manager from flask ext migrate import Migrate MigrateCommand from flask ext sqlalchemy import SQLAlchemy from flask ext security import Security SQLAlchemyUserDatastore \ UserMixin RoleMixin login_required roles_required from flask ext login import current_user from forms import UserEditForm import os sys datetime random math basedir = os path abspath(os path dirname(__file__)) # Create app application = Flask(__name__) application config['DEBUG'] = True application config['SECRET_KEY'] = 'super-secret' application config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' os path join(basedir 'app db') application config['DEFAULT_MAIL_SENDER'] = 'info@site com' application config['SECURITY_REGISTERABLE'] = True application config['SECURITY_CONFIRMABLE'] = True application config['SECURITY_RECOVERABLE'] = True application config from_object('config email') application config['DBPATH'] = os path join(basedir 'app db') # Setup mail extension mail = Mail(application) # Setup babel babel = Babel(application) @babel localeselector def get_locale(): override = request args get('lang') if override: session['lang'] = override rv = session get('lang' 'en') return rv # Create database connection object db = SQLAlchemy(application) migrate = Migrate(application db) manager = Manager(application) manager add_command('db' MigrateCommand) # Define models roles_users = db Table('roles_users' db Column('user_id' db Integer() db ForeignKey('user id')) db Column('role_id' db Integer() db ForeignKey('role id'))) class Role(db Model RoleMixin): id = db Column(db Integer() primary_key=True) name = db Column(db String(80) unique=True) description = db Column(db String(255)) class User(db Model UserMixin): id = db Column(db Integer primary_key=True) email = db Column(db String(255) unique=True) password = db Column(db String(255)) active = db Column(db Boolean()) confirmed_at = db Column(db DateTime()) nickname = db Column(db String(255)) favcolor = db Column(db String(255)) favshape = db Column(db String(255)) favflower = db Column(db String(255)) favband = db Column(db String(255)) # <<<--- NEW COLUMN roles = db relationship('Role' secondary=roles_users backref=db backref('users' lazy='dynamic')) def __str__(self): return '<User id=%s email=%s>' % (self id self email) user_datastore = SQLAlchemyUserDatastore(db User Role) security = Security(application user_datastore) # Views @app route('/') def home(): return render_template('index html') if __name__ == '__main__': if str(sys argv[1]) == 'run': application run(debug=True) #(host='0 0 0 0' debug=True) else: manager run() ```` I am trying to add the new column `favband` using the following commands: `flask\Scripts\python exe application py db migrate` `flask\Scripts\python exe application py db upgrade` However when trying `db migrate` I get the following error: ````Traceback (most recent call last): File "application py" line 398 in <module> manager run() #1) db migrate 2) db upgrade File "C:\website\flask\lib\site-packages\flask_script\__init__ py" line 412 in run result = self handle(sys argv[0] sys argv[1:]) File "C:\website\flask\lib\site-packages\flask_script\__init__ py" line 383 in handle res = handle(*args **config) File "C:\website\flask\lib\site-packages\flask_script\commands py" line 216 in __call__ return self run(*args **kwargs) File "C:\website\flask\lib\site-packages\flask_migrate\__init__ py" line 132 in migrate config = _get_config(directory) File "C:\website\flask\lib\site-packages\flask_migrate\__init__ py" line 46 in _get_config config set_main_option('script_location' directory) File "C:\website\flask\lib\site-packages\alembic\config py" line 198 in set_main_option self file_config set(self config_ini_section name value) File "C:\Python27\Lib\ConfigParser py" line 701 in set ConfigParser set(self section option value) File "C:\Python27\Lib\ConfigParser py" line 388 in set raise NoSectionError(section) ConfigParser NoSectionError: No section: 'alembic' ```` I have also tried this from within `flask\Scripts` but get the same error: `python exe / /application py db migrate` I have also tried upgrading flask-migrate to the latest version | Just in case anyone has this problem in the future-- I did not have the migrations folder because I had transferred the DB file from a different project So this is what happens when you have no functioning migrations folder! |
Filtering with itemgetter and numpy arrays I am getting the following error: ````Traceback (most recent call last): File "calibrating py" line 160 in <module> intrinsic = calibrate2(corners cb_points (640 480)) File "calibrating py" line 100 in calibrate2 valid_corners = filter(itemgetter(0) image_corners) ValueError: The truth value of an array with more than one element is ambiguous Use a any() or a all() ```` `image_corners` is a list of numpy arrays i e ````[array([[ 261 45239258 140 88212585] [ 301 11242676 156 306427 ] [ 343 38937378 168 20132446] [ 382 79559326 180 48405457] [ 392 16989136 338 6171875 ] [ 439 97772217 337 2124939 ]] dtype=float32) ] ```` What I want to do is to take the matrices without the `dtype=float32` what am I doing wrong? | The <them>dtype</them> attribute is not accessible by <them>itemgetter</them> Try this filter instead: ````filter(lambda arr: arr dtype != float32 image_corners) ```` That will give you all the matricies without `dtype==float32` |
Python 3 changing value of dictionary key in for loop not working I have python 3 code that is not working as expected: ````def addFunc(x y): print (x+y) def subABC(x y z): print (x-y-z) def doublePower(base exp): print(2*base**exp) def RootFunc(inputDict): for k v in inputDict items(): if v[0]==1: d[k] = addFunc(*v[1:]) elif v[0] ==2: d[k] = subABC(*v[1:]) elif v[0]==3: d[k] = doublePower(*v[1:]) d={"s1_7":[1 5 2] "d1_6":[2 12 3 3] "e1_3200":[3 40 2] "s2_13":[1 6 7] "d2_30":[2 42 2 10]} RootFunc(d) #test to make sure key var assignment works print(d) ```` I get: ````{'d2_30': None 's2_13': None 's1_7': None 'e1_3200': None 'd1_6': None} ```` I expected: ````{'d2_30': 30 's2_13': 13 's1_7': 7 'e1_3200': 3200 'd1_6': 6} ```` What is wrong? Semi related: I know dictionaries are unordered but is there any reason why python picked this order? Does it run the keys through a randomizer? | `print` does not return a value It returns `None` so every time you call your functions they are printing to standard output and returning `None` Try changing all `print` statements to `return` like so: ```` def addFunc(x y): return x+y ```` This will give the value `x+y` back to whatever called the function Another problem with your code (unless you meant to do this) is that you define a dictionary `d` and then when you define your function you are working on this dictionary `d` and not the dictionary that is 'input': ````def RootFunc(inputDict): for k v in inputDict items(): if v[0]==1: d[k] = addFunc(*v[1:]) ```` Are you planning to always change `d` and <them>not</them> the dictionary that you are iterating over `inputDict`? There may be other issues as well (accepting a variable number of arguments within your functions for instance) but it is good to address one problem at a time <hr> <strong>Additional Notes on Functions:</strong> Here is some sort-of pseudocode that attempts to convey how functions are often used: ````def sample_function(some_data): modified_data = [] for element in some_data: do some processing add processed crap to modified_data return modified_data ```` Functions are considered 'black box' which means you structure them so that you can dump some data into them and they always do the same stuff and you can call them over and over again They will either `return` values or `yield` values or update some value or attribute or something (the latter are called 'side effects') For the moment just pay attention to the `return` statement Another interesting thing is that functions have 'scope' which means that when I just defined it with a fake-name for the argument I do not actually have to have a variable called "some_data" I can pass whatever I want to the function but inside the function I can refer to the fake name and create other variables that really only matter within the context of the function Now if we run my function above it will go ahead and process the data: ```` sample_function(my_data_set) ```` But this is often kind of pointless because the function is supposed to return something and I did not <them>do</them> anything with what it returned What I should do is assign the value of the function and its arguments to some container so I can keep the processed information ````my_modified_data = sample_function(my_data_set) ```` This is a really common way to use functions and you will probably see it again <hr> <strong>One Simple Way to Approach Your Problem:</strong> Taking all this into consideration here is one way to solve your problem that comes from a really common programming paradigm: ````def RootFunc(inputDict): temp_dict = {} for k v in inputDict items(): if v[0]==1: temp_dict[k] = addFunc(*v[1:]) elif v[0] ==2: temp_dict[k] = subABC(*v[1:]) elif v[0]==3: temp_dict[k] = doublePower(*v[1:]) return temp_dict inputDict={"s1_7":[1 5 2] "d1_6":[2 12 3 3] "e1_3200":[3 40 2] "s2_13":[1 6 7] "d2_30"[2 42 2 10]} final_dict = RootFunc(inputDict) ```` |
Adding to Google Group based on Google Spreadsheet data validation So I would like to preface this with the fact that I am <strong>NOT</strong> a programmer I know a <strong><them>little</them></strong> Python but that is about it So this is what I am trying to do: User fills out a Google Form and the responses are dumped into a spreadsheet As a part of the form their email address is captured in "'Form Responses'B:B" Not sure if this is even possible but I would like to know: ````for row X If column P = yes and column c = Accept and column F = Yes Capture email from Column B and add them to GoogleGroup and send Welcome_Email ```` Please help! :) Thanks in advance | Doing a few searches on this forum on words like <a href="http://stackoverflow com/search?q=%5Bgoogle-apps-script%5Dsend%20email">email</a> or <a href="http://stackoverflow com/search?q=%5Bgoogle-apps-script%5Dgroup">groups</a> you will find quite a few scripts and if you spend a couple of hours looking at how they are built you will be able to write something that does what you want If at that moment you meet some unexpected difficulties you will be welcome to ask for help if you show what you have done |
Feynman quickly bored of Los Alamos because the work was all kept __? | top secret |
How can I implement insertion sort using recursion and which is more efficient? How could I implement this using recursion and would it be more effcient? My code: ````def insertionSort(array): '''(list) - > list Returns a sorted list of integers by implementing the insertion sort which returns numbers in array from least to greatest ''' for i in range(1 len(array)): if array[i-1] > array[i]: #Finds a number out of place temp = array[i] for a in range(0 i): if temp < array[a]: array insert(a temp) del array[i+1] break return array ```` | Any for loop `for x in range(a b): Body` can be reimplemented with tail recursion: ````def rfor(b x = a): if a < b: Body rfor(b x 1) ```` This ought to give you enough to get the answer yourself In standard Python this will definitely be slower than the loop and eat one stack frame per iteration In other languages and implementations with good tail call optimization they will be equal in cost Apparently <a href="http://lambda-the-ultimate org/node/1331" rel="nofollow">Guido has said he is uninterested in tail call optimization</a> |
Having trouble sorting the data from a file I am opening and reading a txt file and trying to save values in the format 0 x or 0 xy or 0 xyz x must be a digit 1-9 y cannot be 0 or a odd number z cannot be 0 or a even number My current code is only saving the variables in the format 0 x but is skipping over the 0 xy and 0 xyz For text file has 16000 elements and contains ints floats and strings: <blockquote> 03243234 234 234 223 0 2 MWFE etc </blockquote> ````list = [] with open("exam2data txt") as f: for line in f: line = f readline() xCounter = 0 yCounter = 0 zCounter = 0 try: lineFloat = float(line) if lineFloat < 1: if len(line) == 4: if line[3] == 0: pass else: list append(lineFloat) xCounter = 1 elif len(line) == 5: if line[3] == 0: pass else: if line[2] == 0: pass else: y = float(line[4]) if (y % 2 == 0): list append(lineFloat) yCounter = 1 else: pass elif len(line) == 6: if line[4] == 0: pass else: if line[5] == 0: pass else: if line[3] == 0: pass else: y = float(line[4]) z = float(line[5]) if (y % 2 == 0): if (z % 2 == 1): list append(lineFloat) zCounter = 1 else: pass else: pass except: pass print(len(list)) print(' ' join(map(str list))) ```` | My bad guys Forgot to strip \n after reading the line I added the strip method and adjusted my strings for that ````line = data rstrip("\n") ```` The resulting code: ````list = [] with open("exam2data txt") as f: for data in f: data = f readline() xCounter = 0 yCounter = 0 zCounter = 0 line = data rstrip("\n") try: lineFloat = float(line) if lineFloat < 1: if len(line) == 3: if line[2] == 0: pass else: list append(lineFloat) xCounter = 1 elif len(line) == 4: if line[3] == 0: pass else: if line[2] == 0: pass else: y = float(line[3]) if (y % 2 == 0): list append(lineFloat) yCounter = 1 else: pass elif len(line) == 5: if line[4] == 0: pass else: if line[3] == 0: pass else: if line[2] == 0: pass else: y = float(line[3]) z = float(line[4]) if (y % 2 == 0): if (z % 2 == 1): list append(lineFloat) zCounter = 1 else: pass else: pass except: pass print(len(list)) print(' ' join(map(str list))) ```` |
Why is the name of the containing class not recognized as a return value function annotation? I was going to use <a href="http://stackoverflow com/q/3038033/1106367">Python function annotations</a> to specify the type of the return value of a static factory method I understand this is <a href="http://www python org/dev/peps/pep-3107/#fundamentals-of-function-annotations">one of the desired use cases</a> for annotations ````class Trie: @staticmethod def from_mapping(mapping) > Trie: # docstrings and initialization ommitted trie = Trie() return trie ```` <a href="http://www python org/dev/peps/pep-3107/">PEP 3107</a> states that: <blockquote> Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time </blockquote> `Trie` is a valid expression in Python is not it? Python does not agree or rather cannot find the name: <blockquote> `def from_mapping(mapping) > Trie:` `NameError: name 'Trie' is not defined` </blockquote> It is worth noting that this error does not happen if a fundamental type (such as `object` or `int`) or a standard library type (such as `collections deque`) is specified <strong>What is causing this error and how can I fix it?</strong> | `Trie` is a valid expression and evaluates to the current value associated with the name name `Trie` But that name is not defined yet -- a class object is only bound to its name <them>after</them> the class body has run to completition You will note the same behavior in this much simpler example: ````class C: myself = C # or even just C ```` Normally the workaround would be setting the class attribute after the class has been defined outside the class body This is not a really good option here though it works Alternatively you could use any placeholder value in the initial definition then replace it in the `__annotations__` (which is legal because it is a regular dictionary): ````class C: def f() > : pass print(C f __annotations__) C f __annotations__['return'] = C print(C f __annotations__) ```` It <them>does</them> feel rather hacky though Depending on your use case it might be possible to instead use a sentinel object (e g `CONTAINING_CLASS = object()`) and leave interpreting that to whatever actually processes the annotations |
How to parse interactively syslog on remote host I need to implement in Python the following: - Connect to remote host (CentOS 6 5 based) - Interactively parse the syslog (/var/log/messages) and expect for some specific message - On message arriving parse it and verify some things I have no problem with (1) and (3) On other hand have no idea how to do the (2) I assume it can be done by using pexpect Any suggestions? Thanks in advance | You can write some specific script for parsing /var/log/messages on server or use some tool or command for it and send result to she will stdout For example(sorry for trivial): ````child = pexpect spawn('ssh user@host') child expect('password:') child sendline('secure_word') child expect(']$') child sendline('less /var/log/messages') child expect('/^some_data_need_to_get$/') ```` In this case **less** command(instead of **less** can be some script) return output into she will stdout and you can find with regexp some data you need In 4 line described some prompt we expect |
PyQt: Is there any Time limit widget? I am creating very simple quiz game That i want to have delay limit on so it starts and ends on specific time For example there is some function: ````def Time(): self widget1 show() self widget2 hide() SomeDelayWidget(60s)(self SomeFunction) ```` I want this widget to send some kind of signal that activates specific function <h1>Sorted:</h1> So is there any delay widget that will time out in specific seconds and after that send signal to some slot? | Use a timer ````tomorrow = QtCore QTimer() tomorrow setSingleShot(True) tomorrow timeout connect(self SomeFunction) tomorrow start(10000) ```` |
pandas: Boolean indexing with multi index There are many questions here with similar titles but I could not find one that is addressing this issue I have dataframes from many different origins and I want to filter one by the other Using boolean indexing works great when the boolean series is the same size as the filtered dataframe but not when the size of the series is the same as a <them>higher level index</them> of the filtered dataframe In short let us say I have this dataframe: ````In [4]: df = pd DataFrame({'a':[1 1 1 2 2 2 3 3 3] 'b':[1 2 3 1 2 3 1 2 3] 'c':range(9)}) set_index(['a' 'b']) Out[4]: c a b 1 1 0 2 1 3 2 2 1 3 2 4 3 5 3 1 6 2 7 3 8 ```` And this series: ````In [5]: filt = pd Series({1:True 2:False 3:True}) Out[6]: 1 True 2 False 3 True dtype: bool ```` And the output I want is this: ```` c a b 1 1 0 2 1 3 2 3 1 6 2 7 3 8 ```` I am not looking for solutions that are not using the `filt` series such as: ````df[df index get_level_values('a') != 2] df[df index get_level_values('a') isin([1 3])] ```` I want to know if I can use my input `filt` series as is as I would use a filter on c: ````filt = df c < 7 df[filt] ```` | If you transform your index 'a' back to a column you can do it as follows: ````>>> df = pd DataFrame({'a':[1 1 1 2 2 2 3 3 3] 'b':[1 2 3 1 2 3 1 2 3] 'c':range(9)}) >>> filt = pd Series({1:True 2:False 3:True}) >>> df[filt[df['a']] values] a b c 0 1 1 0 1 1 2 1 2 1 3 2 6 3 1 6 7 3 2 7 8 3 3 8 ```` <strong>edit</strong> As suggested by @joris this works also with indices Here is the code for your sample data: ````>>> df[filt[df index get_level_values('a')] values] c a b 1 1 0 2 1 3 2 3 1 6 2 7 3 8 ```` |
Extracting a specific PIECE of a line from a textfile(Python) I have a textfile with the format: ````3rd Year: MECN3010 PREREQ MECN2011 COREQ TIMES1 TIMES2 MO3 MO4 FR5 TH1 TH2 MECN3012 PREREQ MECN2012 COREQ TIMES1 TUA WE3 TH1 TH2 TIMES2 ```` How can i extract just a particular part of a line? For e g suppose I want to extract just the ````PREREQ MECN 2011 ```` part from the 2nd line I am able to read the particular line I want in but I do not know how to `split` / `strip` just the info I need | If all the lines you are interested in contain `PREREQ MECNYYYY` where `YYYY` is the year number you can use a regular expression like in the following: <strong>EDIT:</strong> corrected the code ````import re # assume that line holds your text line regex = you are'PREREQ MECN\d{4}' matcher = re search(re compile(regex) line) if (matcher): match = matcher group() #gives the actual match ```` |
What future U.S. president was rescued by a submarine? | George H.W. Bush |
pyMySQL set connection character set I am developing a fairly straightforward web app using Flask and MySQL I am struggling with unicode Users sometimes paste stuff that they copied from Word and it is falling over with the old smart quotes `you'\u201c'` A little bit of investigation shows that the connection I have to MySQL is using the `Latin1` charset (seems to be the default) How can I specify for it to use unicode for its connection? I am using pyMySQL which purports to be a drop-in replacement for MySQLdb MySQLdb defines a `set_character_set(self charset)` function for `connection` objects but pyMySQL does not (I get an error if I try) | I worked it out by poking around in the <a href="https://github com/PyMySQL/PyMySQL">pyMySQL source</a> (I had tried but could not find the right place!) You can specify it when you create the connection: ````conn = pymysql connect(host='localhost' user='username' passwd='password' db='database' charset='utf8') ```` Solved my problem |
How to use Python's "easy_install" on Windows it is not so easy After installing Python 2 7 on Windows XP then manually setting the `%PATH%` to `python exe` (why will not the python installer do this?) then installing `setuptools 0 6c11` (why does not the python installer do this?) then manually setting the `%PATH%` to `easy_install exe` (why does not the installer do this?) I finally tried to install a python package with `easy_install` but `easy_install` failed when it could not install the pywin32 package which is a dependency <strong>How can I make easy_install work properly on Windows XP?</strong> The failure follows: ```C:\>easy_install winpexpect Searching for winpexpect Best match: winpexpect 1 4 Processing winpexpect-1 4-py2 7 egg winpexpect 1 4 is already the active version in easy-install pth Using c:\python27\lib\site-packages\winpexpect-1 4-py2 7 egg Processing dependencies for winpexpect Searching for pywin32>=214 Reading http://pypi python org/simple/pywin32/ Reading http://sf net/projects/pywin32 Reading http://sourceforge net/project/showfiles php?group_id=78018 No local packages or download links found for pywin32>=214 Best match: None Traceback (most recent call last): File "C:\python27\scripts\easy_install-script py" line 8 in load_entry_point('setuptools==0 6c11' 'console_scripts' 'easy_install')() File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 1712 in main with_ei_usage(lambda: File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 1700 in with_ei_usage return f() File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 1716 in distclass=DistributionWithoutHelpCommands **kw File "C:\python27\lib\distutils\core py" line 152 in setup dist run_commands() File "C:\python27\lib\distutils\dist py" line 953 in run_commands self run_command(cmd) File "C:\python27\lib\distutils\dist py" line 972 in run_command cmd_obj run() File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 211 in run self easy_install(spec not self no_deps) File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 446 in easy_install return self install_item(spec dist location tmpdir deps) File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 481 in install_item self process_distribution(spec dists[0] deps "Using") File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 519 in process_distribution [requirement] self local_index self easy_install File "C:\python27\lib\site-packages\pkg_resources py" line 563 in resolve dist = best[req key] = env best_match(req self installer) File "C:\python27\lib\site-packages\pkg_resources py" line 799 in best_match return self obtain(req installer) # try and download/install File "C:\python27\lib\site-packages\pkg_resources py" line 811 in obtain return installer(requirement) File "C:\python27\lib\site-packages\setuptools\command\easy_install py" line 434 in easy_install self local_index File "C:\python27\lib\site-packages\setuptools\package_index py" line 475 in fetch_distribution return dist clone(location=self download(dist location tmpdir)) AttributeError: 'NoneType' object has no attribute 'clone' ``` | For one thing it says you already have that module installed If you need to upgrade it you should do something like this: easy_install -YOU packageName Of course easy_install does not work very well if the package has some C headers that need to be compiled and you do not have the right version of Visual Studio installed You might try using pip or distribute instead of easy_install and see if they work better |
Reference package in personal library from rpy2 I have just installed the MSwM package from CRAN into my personal library location via RStudio and I am trying to call it from Python using rpy2 However it is giving me this error: ````rpy2 rinterface RRuntimeError: Error in loadNamespace(name) : there is no package called 'MSwM' ```` I have tried referencing the standard package and they have no problems loading Here is my code in Python: ````from rpy2 robjects import r from rpy2 robjects packages import importr base=importr('base') utils=importr('utils') markov=importr('MSwM') ```` So both <strong>base</strong> and <strong>utils</strong> are properly loaded but markov fails to load Can anyone she would some light on how I can get packages in personal library location to run in rpy2?(by the way my set up is in Windows 7) Just a FYI the current environment set up is like this : R_USER=xxx R_HOME=C:\Program Files\R\R-3 2 2 My personal library is in C:\Users\xxx\Documents\R\win-library\3 2 and I am able to get MSwM loaded and run in RStudio itself | Never mind I found the answer as importr has the lib_loc parameter to specify the location of the package so I am doing the following and it is working now: ````markov=importr('MSwM' lib_loc = "C:/Users/xxx/Documents/R/win-library/3 2") ```` |
Python metaclass default attributes I am trying to create metaclass in Python (2 7) that will set arguments passed to object's `__init__` as object attributes ````class AttributeInitType(type): def __call__(self *args **kwargs): obj = super(AttributeInitType self) __call__(*args **kwargs) for k v in kwargs items(): setattr(obj k v) return obj ```` Usage: ````class Human(object): __metaclass__ = AttributeInitType def __init__(self height=160 age=0 eyes="brown" sex="male"): pass man = Human() ```` <strong>Question:</strong> I want `man` instance to have defaults attributes set as in class's `__init__` How can I do it? <strong>Update:</strong> I have came to even better solution that: - inspects `__init__` method only once during class creation - does not override attributes that where (possibly) set by class's real `__init__` Here is the code: ````import inspect import copy class AttributeInitType(type): """Converts keyword attributes of the init to object attributes""" def __new__(mcs name bases d): # Cache __init__ defaults on a class-level argspec = inspect getargspec(d["__init__"]) init_defaults = dict(zip(argspec args[-len(argspec defaults):] argspec defaults)) cls = super(AttributeInitType mcs) __new__(mcs name bases d) cls __init_defaults = init_defaults return cls def __call__(mcs *args **kwargs): obj = super(AttributeInitType mcs) __call__(*args **kwargs) the_kwargs = copy copy(obj __class__ __init_defaults) the_kwargs update(kwargs) for k v in the_kwargs items(): # Do not override attributes set by real __init__ if not hasattr(obj k): setattr(obj k v) return obj ```` | Your situation works if you pass the arguments at object creation ````>>> man <test Human object at 0x10a71e810> >>> dir(man) ['__class__' '__delattr__' '__dict__' '__doc__' '__format__' '__getattribute__' '__hash__' '__init__' '__metaclass__' '__module__' '__new__' '__reduce__' '__reduce_ex__' '__repr__' '__setattr__' '__sizeof__' '__str__' '__subclasshook__' '__weakref__'] >>> man=Human(height=10) >>> dir(man) ['__class__' '__delattr__' '__dict__' '__doc__' '__format__' '__getattribute__' '__hash__' '__init__' '__metaclass__' '__module__' '__new__' '__reduce__' '__reduce_ex__' '__repr__' '__setattr__' '__sizeof__' '__str__' '__subclasshook__' '__weakref__' 'height'] >>> man height 10 ```` but it does not work with default arguments For that you have to specifically extract them from the `__init__` function object An alternative is to decorate the `__init__` instead |
How did applicants find the biological questionnaire? | null |
Serving static html pages with flask on heroku I Am trying to figure out how to serve static pages from heroku with a flask app I found this with some searching: ````@app route('/foo/<path:filename>') def send_foo(filename): return send_from_directory('/path/to/static/files' filename) ```` But this would be quite inefficient Is there a way to have the front facing server directly serve these files? | Normally you would do this with mod_rewrite with apache or similar but afaik heroku does not let us you change the http server configuration You will need to use the rack middleware it let us you write url rewrite rules with ruby (check this out : <a href="http://icelab com au/articles/useful-heroku-friendly-rewrites-with-rack-rewrite/" rel="nofollow">http://icelab com au/articles/useful-heroku-friendly-rewrites-with-rack-rewrite/</a> ) |
How to avoid overlapping of labels & autopct in a matplotlib pie chart? My Python code is: ````values = [234 64 54 10 0 1 0 9 2 1 7 7] months = ['Jan' 'Feb' 'Mar' 'Apr' 'May' 'Jun' 'Jul' 'Aug' 'Sep' 'Oct' 'Nov' 'Dec'] colors = ['yellowgreen' 'red' 'gold' 'lightskyblue' 'white' 'lightcoral' 'blue' 'pink' 'darkgreen' 'yellow' 'grey' 'violet' 'magenta' 'cyan'] plt pie(values labels=labels autopct='%1 1f%%' shadow=True colors=colors startangle=90 radius=1 2) plt show() ```` Is it possible to show the labels "Jan" "Feb" "Mar" etc and the percentages either: - without overlapping or - using an `arrow mark`? <img src="http://i stack imgur com/Gfohy png" alt="piechart"> | Alternatively you can put the legends beside the pie graph: ````import matplotlib pyplot as plt import numpy as np x = np char array(['Jan' 'Feb' 'Mar' 'Apr' 'May' 'Jun' 'Jul' 'Aug' 'Sep' 'Oct' 'Nov' 'Dec']) y = np array([234 64 54 10 0 1 0 9 2 1 7 7]) colors = ['yellowgreen' 'red' 'gold' 'lightskyblue' 'white' 'lightcoral' 'blue' 'pink' 'darkgreen' 'yellow' 'grey' 'violet' 'magenta' 'cyan'] porcent = 100 *y/y sum() patches texts = plt pie(y colors=colors startangle=90 radius=1 2) labels = ['{0} - {1:1 2f} %' format(i j) for i j in zip(x porcent)] sort_legend = True if sort_legend: patches labels dummy = zip(*sorted(zip(patches labels y) key=lambda x: x[2] reverse=True)) plt legend(patches labels loc='left center' bbox_to_anchor=(-0 1 1 ) fontsize=8) plt savefig('piechart png' bbox_inches='tight') ```` <img src="http://i stack imgur com/eJ6KB png" alt="enter image description here"> <hr> EDIT: if you want to keep the legend in the original order as you mentioned in the comments you can set `sort_legend=False` in the code above giving: <img src="http://i stack imgur com/ubvxT png" alt="enter image description here"> |
Amazon Autoscaling trigger not working how do I debug it? I am trying to use autoscaling to create new EC2 instances whenever average CPU load on existing instances goes high Here is the situation: - I am setting up autoscaling using this boto script (with keys and image names removed) <a href="http://balti ukcod org uk/~francis/tmp/start_scaling_ptdaemon nokeys py" rel="nofollow">http://balti ukcod org uk/~francis/tmp/start_scaling_ptdaemon nokeys py</a> - I have got min_size set to 2 and the AutoScalingGroup correctly creates an initial 2 instances which both work fine I am pretty sure this means the LaunchConfiguration is right - When load goes up to nearly 100% on both those two instances nothing happens Some questions / thoughts: - Is there any way of debugging this? I cannot find any API calls that give me detals of what Autoscaling is doing or thinks it is doing Are there any tools that give feedback either on what it is doing or on whether it has set things up correctly? - It would be awesome if Autoscaling appeared in the AWS Console - I am using EU west availability zone Is there any reason that should cause trouble with Autoscaling? - Is there any documentation of the "dimensions" parameter when creating a trigger? I have no idea what it means and have just copied its fields from an example I cannot find any documentation about it that does not self-referentially say it is a "dimension" without explaining what that means or what the possible values are Thanks for any help! | I am sure you have already found these and it would be good to use AWS tool first before the Python tool to get the idea :) <a href="http://ec2-downloads s3 amazonaws com/AutoScaling-2009-05-15 zip" rel="nofollow">http://ec2-downloads s3 amazonaws com/AutoScaling-2009-05-15 zip</a> http://docs amazonwebservices com/AutoScaling/latest/DeveloperGuide/ Cheers Rodney |
Deleting a few list items inside of dictionary Deleting a few list items inside of dictionary Hi I have a dictionary: ````phone = {"first":100 "second":200 "third":[10 12 5 38] "fourth":400} ```` Let' say I want to remove the 12 and 5 from from "phone" dictionary Is there a way to do that using a "del" function? I know how to do this using a remove() ````phone["third"] remove(12) phone["third"] remove(5) ```` but I was wondering if it is possible to do it using the del()? Thank you EDIT: For all those replies concentrating on "del uses index remove uses the exact value" I am redefining my question: I want to delete the indexes 1 and 2 in the list representing the third key-value item in "phone" dictionary How can I do that? | <a href="http://docs python org/2/tutorial/datastructures html#the-del-statement" rel="nofollow">http://docs python org/2/tutorial/datastructures html#the-del-statement</a> del is a way to delete by index not value however you can search the index first if you want Better to use remove if you want to delete by value To delete the element at index 1 and 2 ````>>> phone = {"first":100 "second":200 "third":[10 12 5 38] "fourth":400} >>> del phone["third"][1] >>> del phone["third"][2] >>> phone {'second': 200 'fourth': 400 'third': [10 5] 'first': 100} ```` |
How to retrieve the text with beautifulsoup using python I want to get the text that is repairsonwheelsrim-hub com from the HTML using beautifulsoup pls let me know how I should do this currently I am using ````webadress = profilePageSource select("span#offscreen a[href]")[0] get_text() <div class="biz-website"> <span class="offscreen">Business website</span> <a target="_blank" href="/biz_redir?url=http%3A%2F%2Frepairsonwheelsrim-hub com&src_bizid=8tY2YtXPk1rGO7sl43LH8A&cachebuster=1438073532&s=6b75d47d32b28eb8e50506859857b75e949d698cdbc47e9892cc2a3b43e480c2">repairsonwheelsrim-hub com</a> </div> ```` | Is this what you want : ````from bs4 import BeautifulSoup text='<div class="biz-website"> <span class="offscreen">Business website</span> <a target="_blank" href="/biz_redir?url=http%3A%2F%2Frepairsonwheelsrim-hub com&src_bizid=8tY2YtXPk1rGO7sl43LH8A&cachebuster=1438073532&s=6b75d47d32b28eb8e50506859857b75e949d698cdbc47e9892cc2a3b43e480c2">repairsonwheelsrim-hub com</a> </div>' soup = BeautifulSoup(text 'html parser') print soup a text ```` <strong>output:</strong> ````repairsonwheelsrim-hub com ```` To loop through the text of the url: ````from bs4 import BeautifulSoup text='<div class="biz-website"> <span class="offscreen">Business website</span> <a target="_blank" href="/biz_redir?url=http%3A%2F%2Frepairsonwheelsrim-hub com&src_bizid=8tY2YtXPk1rGO7sl43LH8A&cachebuster=1438073532&s=6b75d47d32b28eb8e50506859857b75e949d698cdbc47e9892cc2a3b43e480c2">repairsonwheelsrim-hub com</a> </div>' soup = BeautifulSoup(text 'html parser') for t in soup findAll("a"): print t text ```` <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/" rel="nofollow">For more on BS4 see their official site</a> <strong>edit:</strong> ````# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import requests a=requests get("http://www yelp com/biz/scotts-pizza-tours-new-york") text=a content soup = BeautifulSoup(text 'html parser') for t in soup findAll(lambda tag: tag name == 'a' and 'target' in tag attrs): if "" join(t["target"]) in "_blank": print t get_text() ```` <strong>output:</strong> ````scottspizzatours com scottspizzatours com scottspizzatours com/pri⦠```` |
Who established Christianity in the region? | Romans |
Who, along with Maria Dersaismes, stopped a mixed gender masonic lodge? | null |
How many cantons are in Switzerland's federal directorial republic? | 26 |
python sentence tokenizing according to the word index of dictionary I have a vocabulary with the form of dic = {'a':30 'the':29 } the key is the word the value is its word count I have some sentences like: "this is a test" "an apple" In order to tokenize the sentences each sentence will be encoded as the word index of dictionary If the word in a sentence also exist in the dictionary get this word's index; otherwise set the value to 0 for example I set the sentence dimension to 6 if the length of a sentence is smaller than 6 padding 0s to make it 6 dimension "this is the test" ----> [2 0 2 4 0 0] "an apple" ----> [5 0 0 0 0 0 ] Here is my sample code: ````words=['the' 'a' 'an'] #use this list as my dictionary X=[] with open('test csv' 'r') as infile: for line in infile: for word in line: if word in words: X append(words index(word)) else: X append(0) ```` My code has some problem because the output is not correct; in addition I have no idea how to set the sentence dimension and how to padding | There are a couple of issues with your code: - You are not tokenizing on a word but a character You need to split up each line into words - You are appending into one large list instead of a list of lists representing each sentence/line - Like you said you do not limit the size of the list - I also do not understand why you are using a list as a dictionary I edited your code below and I think it aligns better with your specifications: ````words={'the': 2 'a': 1 'an': 3} X=[] with open('test csv' 'r') as infile: for line in infile: # Inits the sublist to [0 0 0 0 0 0] sub_X = [0] * 6 # Enumerates each word in the list with an index # split() splits a string by whitespace if no arg is given for idx word in enumerate(line split()): if word in words: # Check if the idx is within bounds before accessing if idx < 6: sub_X[idx] = words[word] # X represents the overall list and sub_X the sentence X append(sub_X) ```` |
oauth py java equivalent Looking for a java equivalent file for <a href="http://code google com/p/google-mail-xoauth-tools/wiki/XoauthDotPyRunThrough" rel="nofollow">xoauth py</a> I tried <a href="http://stackoverflow com/a/12243874/234110">this</a> but did not help much Any pointers/help/guidance/reference ? | Found this awesome API library called <a href="https://github com/fernandezpablo85/scribe-java" rel="nofollow">Scribe</a> Now my life is too simple with only Pure-Java! A special thanks to <a href="https://github com/fernandezpablo85" rel="nofollow">Pablo</a> for his creation(s) |
POP3 example from docs python org throws error So I am somewhat new to Python and was trying to create a script to download emails from my pop3 server I found a (seemingly) simple example on Python org but when I ran the code with my mail server settings I get this error: ````Traceback (most recent call last): File "getmail py" line 4 in <module> M pass_(getpass getpass()) File "E:\Python32\lib\poplib py" line 192 in pass_ return self _shortcmd('PASS %s' % pswd) File "E:\Python32\lib\poplib py" line 155 in _shortcmd return self _getresp() File "E:\Python32\lib\poplib py" line 131 in _getresp raise error_proto(resp) poplib error_proto: b'-ERR Authentication failed ' ```` Example code from python org: ````import getpass poplib M = poplib POP3('localhost') M user(getpass getuser()) M pass_(getpass getpass()) numMessages = len(M list()[1]) for i in range(numMessages): for j in M retr(i+1)[1]: print j ```` The "print j" line throws an error of course Curiously the script also fails to ask for the username only asking for a password which is where the "Authentication failed " comes from I am guessing I made the following changes for my script to remove the possibility I keyed in the user/password incorrectly: ````import getpass poplib M = poplib POP3('mail myPOP3server com') M user = 'my_username' M pass_ = 'myPassword' numMessages = len(M list()[1]) for i in range(numMessages): for j in M retr(i+1)[1]: print(j) ```` And got the following error: ````Traceback (most recent call last): File "E:\wos\getmail py" line 6 in <module> numMessages = len(M list()[1]) File "E:\Python32\lib\poplib py" line 219 in list return self _longcmd('LIST') File "E:\Python32\lib\poplib py" line 162 in _longcmd return self _getlongresp() File "E:\Python32\lib\poplib py" line 138 in _getlongresp resp = self _getresp() File "E:\Python32\lib\poplib py" line 131 in _getresp raise error_proto(resp) poplib error_proto: b'-ERR Unknown command ' [Finished in 0 4s with exit code 1] ```` So I am convinced that this is where the issue is: ````numMessages = len(M list()[1]) ```` Can anyone she would some light on this? I use the docs python org regularly for example code and this is the first time I have had example code fail I tried changing the password to something really short and simple adding "@servername" to the username and still cannot get a list of emails Example code is on this <a href="https://docs python org/2/library/poplib html?highlight=retr#poplib POP3 retr" rel="nofollow">page</a> UPDATE: I would appreciate if the downvotes were at least explained so I can learn from the process | <a href="https://docs python org/3/library/poplib html#poplib POP3 user" rel="nofollow">According to the docs</a> `POP3 user` and `POP3 pass_` are <them>methods</them> to which you are supposed to pass the username & password not variables to which the username & password are to be assigned Thus you need to change this: ````M user = 'my_username' M pass_ = 'myPassword' ```` to this: ````M user('my_username') M pass_('myPassword') ```` |
Convert triplets to matrix/dataframe in python I am using csr matrix in scipy When I am printing the matrix the output is like: ````(669974 73) 0 005 (669974 74) 0 007 (669974 75) 0 002 (669974 76) 0 006 (669974 77) 0 005 ```` I want to convert it to matrix/dataframe in the form of triplets only Like: ````col1 col2 val 669974 73 0 005 669974 74 0 007 669974 75 0 002 669974 76 0 006 669974 77 0 005 ```` What is the best way to do this? | Sample sparse matrix: ````In [363]: A=sparse csr_matrix(np arange(12) reshape(3 4)) ```` show it as a dense (regular numpy) array (e g `A toarray()`) ````In [364]: A A Out[364]: array([[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] dtype=int32) ```` Its `repr` display ````In [365]: A Out[365]: <3x4 sparse matrix of type '<class 'numpy int32'>' with 11 stored elements in Compressed Sparse Row format> ```` Its `str()` display (what you saw) ````In [366]: print(A) (0 1) 1 (0 2) 2 (0 3) 3 (1 0) 4 (1 1) 5 (1 2) 6 (1 3) 7 (2 0) 8 (2 1) 9 (2 2) 10 (2 3) 11 ```` `A data` is its data attribute the values You can get the coordinates with `nonzero`: ````In [368]: A nonzero() Out[368]: (array([0 0 0 1 1 1 1 2 2 2 2] dtype=int32) array([1 2 3 0 1 2 3 0 1 2 3] dtype=int32)) ```` Or convert `csr` to `coo` format and get all 3 arrays: ````In [369]: Ac=A tocoo() In [370]: Ac data Out[370]: array([ 1 2 3 4 5 6 7 8 9 10 11] dtype=int32) In [371]: Ac row Out[371]: array([0 0 0 1 1 1 1 2 2 2 2] dtype=int32) In [372]: Ac col Out[372]: array([1 2 3 0 1 2 3 0 1 2 3] dtype=int32) ```` You could turn them into a 3 column array with: ````In [373]: np column_stack((Ac col Ac row Ac data)) Out[373]: array([[ 1 0 1] [ 2 0 2] [ 3 0 3] [ 0 1 4] [ 1 1 5] [ 2 1 6] [ 3 1 7] [ 0 2 8] [ 1 2 9] [ 2 2 10] [ 3 2 11]] dtype=int32) ```` Except if your data is float then this becomes all floats It cannot mix ints and floats You can assemble them into a structured array with 2 int fields and one float one I can elaborate on that if needed But your mention of dataframe suggests you are familiar with `pandas` - if so you probably can take it from here |
How do I get a Python distribution URL? In their setup py Python packages provides some information This information can then be found in the PKG_INFO file of the egg How can I access them once I have installed the package? For instance if I have the following module: ````setup(name='myproject' version='1 2 0 dev0' description='Demo of a setup py file ' long_description=README "\n\n" CHANGELOG "\n\n" CONTRIBUTORS license='Apache License (2 0)' classifiers=[ "Programming Language :: Python" "Programming Language :: Python :: 2" "Programming Language :: Python :: 2 7" "Programming Language :: Python :: 3" "Programming Language :: Python :: 3 4" "Programming Language :: Python :: 3 5" "Programming Language :: Python :: Implementation :: CPython" "Programming Language :: Python :: Implementation :: PyPy" "Topic :: Internet :: WWW/HTTP" "Topic :: Internet :: WWW/HTTP :: WSGI :: Application" "License :: OSI Approved :: Apache Software License" ] keywords="web sync json storage services" url='https://github com/Kinto/kinto') ```` How can I use Python to get back the information provided in the setup py? I was thinking of something similar to that: ````import pkg_resource url = pkg_resource get_distribution(__package__) url ```` Any idea? | There is apparently a private API that let you do that with `pkg_resources`: ````import pkg_resources d = pkg_resources get_distribution(__package__) metadata = d _get_metadata(d PKG_INFO) home_page = [m for m in metadata if m startswith('Home-page:')] url = home_page[0] split(':' 1)[1] strip() ```` I wish we could do better |
What year did a group of Chicago Cubs fans form the Emil Verban Society? | 1975 |
crcmod's xorOut parameter does not behave the same as manually xor'ing `crcmod`'s <a href="http://crcmod sourceforge net/crcmod html" rel="nofollow">documentation</a> states: "xorOut â Final value to XOR with the calculated CRC value Used by some CRC algorithms Defaults to zero " I expected from that description that setting that parameter to a non-zero number (say 0xFFFFFFFF) was equivalent to taking the CRC with parameter zero and then xor'ing it with that number using the `^` operator That is not the behavior I see What did I assume wrong? What is the actual behavior of the xorOut parameter? Here is some code straight from my interactive interpreter I expected the last line to be True ````>>> import crcmod >>> crc32_func_noxor = crcmod mkCrcFun(0x104c11db7 initCrc=0 rev=True xorOut=0) >>> crc32_func_xor = crcmod mkCrcFun(0x104c11db7 initCrc=0 rev=True xorOut=0xffffffff) >>> crc32_func_noxor('12345678' decode('hex'))^0xffffffff==crc32_func_xor('12345678' decode('hex')) False ```` | From the documentation: <blockquote> initCrc â Initial value used to start the CRC calculation This initial value should be the initial shift register value reversed if it uses a reversed algorithm and then XORed with the final XOR value That is equivalent to the CRC result the algorithm should return for a zero-length string Defaults to all bits set because that starting value will take leading zero bytes into account Starting with zero will ignore all leading zero bytes </blockquote> This means that if you do not specify `initCrc` it will initialize the register to the the final XOR value `xorOut` If you want to have the effect of <them>only</them> exclusive-oring the result then you can set `initCrc` to `xorOut` |
What is the term used to define the game of breeding chickens called? | null |
python check prime stuck at one point This was the question our teacher gave us: "One way to determine whether or not a number is a prime number is as follows: if the number < 2 then return False if the number is 2 then return True for each value of i where i >=2 and i < number: if i divides the number evenly then return False return True" I have managed to work through most of it but was stuck when it said 'for each value of i where i >=2 and i < number:' how do I write this in code? ````if number < 2: return False if number == 2: return True ????????? if i%2 == 0: return False return True ```` | Yo need a loop to check all numbers from 2 to one less than the number being checked There are better ways to do it (such as only checking up to the square root of the number) but a simplistic algorithm would be: ````def isPrime (n): if n < 2: return False for x in range (2 n): if n % x == 0: return False return True ```` So in terms of what you need to add to your code: - a loop iterating some variable from two up to one less than the number - checking modulo with <them>that variable</them> rather than the hard-coded `2` |
Python Mechanize with Dynamic Dropdown Selection I am using <a href="http://wwwsearch sourceforge net/mechanize/" rel="nofollow">mechanize</a> to fill forms and I run into a problem with dynamically-filled dropdown lists that are dependent on a previous selection In mechanize I do something like this to select the category: ````import mechanize br = mechanize Browser() """Select the form and set up the browser""" br["state"] = ["California"] br["city"] = ["San Francisco"] # this is where the error is br submit() ```` I cannot choose the city as "San Francisco" until I have chosen the state as "California " because the city dropdown list is dynamically populated after choosing "California " How can I submit the city with Python and mechanize? | mechanize does not support JavaScript Instead you should use urllib2 to send the desired values ````import urllib2 import urllib values = dict(state="CA" city="SF") # examine form for actual vars try: req = urllib2 Request("http://example com/post php" urllib urlencode(values)) response_page = urllib2 urlopen(req) read() except urllib2 HTTPError details: pass #do something with the error here ```` |
TypeError: unorderable types: NoneType() < int() I am trying to make a pong style game in python but each time I get the error written in the title I have already tried googling ways to fix the error but I do not have a place to start on It might be possible that my distance function might not be working But anything could be broken so any help would be loved! Also this is the full error that comes out: ````Traceback (most recent call last): File "/Users/NAME/Documents/PyPong py" line 47 in <module> checkCollisions() File "/Users/NAME/Documents/PyPong py" line 35 in checkCollisions if distance(b e) < 10: TypeError: unorderable types: NoneType() < int() ```` And this is the code: ````from tkinter import * from math import * ##MAIN GAME PART## window = Tk() canvas = Canvas(window width=400 height=400) canvas pack() ##FUNCTIONS## def movePaddles(event): key=event keysym if key == 'Up': canvas move(PaddleTwo 0 -10) elif key == 'Down': canvas move(PaddleTwo 0 10) if key == 'w': canvas move(PaddleOne 0 -10) elif key == 's': canvas move(PaddleOne 0 10) if key == 'j': canvas move(PingPongBall -10 0) elif key == 'k': canvas move(PingPongBall 10 0) def distance(target1 target2): target1coords = canvas coords(target1) target2coords = canvas coords(target2) x1 = (target1coords[0] target1coords[2] ) / 2 y1 = (target1coords[1] target1coords[3] ) / 2 x2 = (target2coords[0] target2coords[2]) / 2 y2 = (target2coords[1] target2coords[3]) / 2 d = sqrt( (x2-x1)** 2 (y2-y1)** 2) def checkCollisions(): for e in PaddleList: if distance(PingPongBall e) < 10: print('hit') #print info on the she will ##PADDLES## PaddleOne = canvas create_rectangle(10 150 25 250 fill='blue') PaddleTwo = canvas create_rectangle(400 150 385 250 fill='blue') PingPongBall = canvas create_rectangle(200 200 210 210 fill='red') PaddleList = [PaddleOne PaddleTwo] BallList = [PingPongBall] canvas bind_all('<Key>' movePaddles) while True: checkCollisions() ```` | You never return anything from `distance()` so it returns `None` You cannot compare `None` to 10 so this results in an error Instead of: ````d = sqrt( (x2-x1)** 2 (y2-y1)** 2) ```` Simply write: ````return sqrt( (x2-x1)** 2 (y2-y1)** 2) ```` |
Django paginator with many pages I have implemented a paginator with the generic ListView My problem is that for list with many pages it displays all the page numbers instead of for example five pages before and after the current page Is there an easy way to fix this? in the views py: ````class CarList(LoginRequiredMixin ListView): model = Car paginate_by = 20 ```` in the html: ````{% if is_paginated %} <ul class="pagination pagination-centered"> {% if page_obj has_previous %} <li><a href="/car?ordering={{ current_order }}&page=1"><<</a></li> <li><a href="/car?ordering={{ current_order }}&page={{ page_obj previous_page_number }}"><</a></li> {% endif %} {% for i in paginator page_range %} <li {% if page_obj number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li> {% endfor %} {% if page_obj has_next %} <li><a href="/car?ordering={{ current_order }}&page={{ page_obj next_page_number }}">></a></li> <li><a href="/car?ordering={{ current_order }}&page={{ page_obj paginator num_pages }}">>></a></li> {% endif %} </ul> {% endif %} ```` | The algorithm for that is not too complicated and can be further simplified if we assume that if there are more than 11 pages (current 5 before 5 after) we are always going to show 11 links Now we have 4 cases: - Number of pages < 11: show all pages; - Current page <= 6: show first 11 pages; - Current page > 6 and < (number of pages - 6): show current page 5 before and 5 after; - Current page >= (number of pages -6): show the last 11 pages With the above in mind let us modify your view create a variable to hold the numbers of pages to show and put it in the context: ````class CarList(LoginRequiredMixin ListView): model = Car paginate_by = 20 def get_context_data(self **kwargs): context = super(CarList self) get_context_data(**kwargs) if not context get('is_paginated' False): return context paginator = context get('paginator') num_pages = paginator num_pages current_page = context get('page_obj') page_no = current_page number if num_pages <= 11 or page_no <= 6: # case 1 and 2 pages = [x for x in range(1 min(num_pages 1 12))] elif page_no > num_pages - 6: # case 4 pages = [x for x in range(num_pages - 10 num_pages 1)] else: # case 3 pages = [x for x in range(page_no - 5 page_no 6)] context update({'pages': pages}) return context ```` Now you can simply use the new variable in your template to create page links: ```` ( ) {% for i in pages %} <li {% if page_obj number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li> {% endfor %} ( ) ```` |
Python converting png to gif using ImageMagick I am using Python 2 7 6 i had a problem converting some png files into gif (in order to create an animation) ```` os system("convert -delay 1 -dispose Background page " str(output_dir) "/* png -loop 0 " str(output_dir) "/animation gif") ```` This was the error that i had ParamÅ tre non valide - 1 | Without enough information to go on this is only a guess but⦠If `output_dir` has any spaces or quotes or other special characters you are doing nothing to escape or quote them so your command line will look something like this: ````convert -delay 1 -dispose Background page ~/My Pictures/* png -loop 0 ~/My Pictures/animation gif ```` Maybe `~/My` is a perfectly valid argument to send for the input and `Pictures/* png` happens to resolve to a whole bunch of additional relative paths that `convert` is willing to deal with as additional inputs but then you have got `~/My` for the output which is not valid since it is the same as the input and `Pictures/animation gif` as some extra argument tacked on the end that `convert` has no idea what to do with You could hack your way around this problem by say using `repr(output_dir)` which will do the appropriate Python-literal quoting which is often but not always good enough to be used as bash quoting as well⦠but that is a really bad idea <hr> A much better way to do this is to let Python do the appropriate quoting for you As the <a href="http://docs python org/3/library/os html#os system" rel="nofollow">`os system`</a> docs say: <blockquote> The `subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function </blockquote> With <a href="http://docs python org/3/library/subprocess html#module-subprocess" rel="nofollow">`subprocess`</a> you can just pass a list of arguments instead of trying to form them into a valid command line and not even use the she willâalthough then you would need to do the globbing yourself instead of letting the she will do it While you are at it it is a lot better to use `os path` methods instead of string methods for dealing with paths For example: ````args = (['convert' '-delay' '1' '-dispose' 'Background' '+page'] glob glob(os path join(output_dir '* png')) ['-loop' '0' os path join(output_dir 'animation gif')]) subprocess check_call(args) ```` Or alternatively you can still use the she will but then use <a href="http://docs python org/3/library/subprocess html#frequently-used-arguments" rel="nofollow">`shlex quote`</a> to quote each argument for you as the docs explain <hr> An even better solution is to use any of the three <a href="http://www imagemagick org/script/api php#python" rel="nofollow">Python bindings to ImageMagick</a> in the first place instead of trying to build command lines to drive the ImageMagick command-line tools |
Python Performance on Windows Is Python generally slower on Windows vs a *nix machine? Python seems to blaze on my Mac OS X machine whereas it <them>seems</them> to run slower on my Window's Vista machine The machines are similar in processing power and the vista machine has 1GBs more memory I particularly notice this in Mercurial but I figure this may simply be how Mercurial is packaged on windows | No real numbers here but it certainly feels like the start up time is slower on Windows platforms I regularly switch between Ubuntu at home and Windows 7 at work and it is an order of magnitude faster starting up on Ubuntu despite my work machine being at least 4x the speed As for runtime performance it feels about the same for "quiet" applications If there are any GUI operations using Tk on Windows they are definitely slower Any console applications on windows are slower but this is most likely due to the Windows cmd rendering being slow more than python running slowly |
What is not another term used for Primary education? | null |
how to convert string to numeric in python I would like to convert string (%) to float but my method did not work well the result slightly differ from correct number for example ````a=pd Series(data=["0 1%" "0 2%"]) 0 0 1% 1 0 2% dtype: object ```` first I strip "%" ````a str rstrip("%") 0 0 1 1 0 2 dtype: object ```` I tried to convert to numeric but the result is strange I guess this phenomena come from binary digit system ````pd to_numeric(a str rstrip("%")) 0 0 10000000000000000555 1 0 20000000000000001110 dtype: float64 ```` and of course I could not convert % to numeric ````pd to_numeric(a str rstrip("%"))/100 0 0 00100000000000000002 1 0 00200000000000000004 dtype: float64 ```` I also tried astype(float) method but The result was same why this phenomena happen ? and how can I avoid this phenomena | Many rational numbers cannot be represented exactly as a floating-point number In particular any number that has to have a five as a factor in the denominator like 1/(2*5) cannot be represented exactly There is not much you can do about this: either round the displayed number so it looks right or use an infinite-precision library or a rational-numbers library Here is a basic way to round the displayed number: `>>> print "% 20f" % 0 1` `0 10000000000000000555` `>>> print "% 4f" % 0 1` `0 1000` |
python IDLE fibonocci sequence my model does not work need help with this i tried something but it did not work for some reason I need some help to figure it out ````def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) F('3') ```` and here is the original problem- Write a function called fib which takes as a parameter an integer n and returns the nth number in the Fibonocci sequence (see definition below) If n is zero or a negative number your function should return an error message in the form of a string "Error: Invalid input " The Fibonocci sequence is `1 1 2 3 5 8 13 21 ` where the first two numbers are 1 and each number beyond that is calculated as the sum of the previous two numbers (2 = 1+1 3 = 2+1 5 = 3+2 8=5+3 etc) | i guess the problem is that you use string instead of integer try `F(3)` instead of `F('3')` or give more information about the error you get |
print out an indented node tree in python from a list of list I have a data set in the format of [node_id name parent_node_id] I would like to output an indented node tree I have been able to do the first generation but do not know how to keep iterating over the list I had to use a try/except clause because not all sublists get their generation appended since I cannot keep looping ````Grandparent Parent 1 Parent 2 Child 1 Child 2 ```` Code: ````# establish data set in the format of [node_id name parent_node_id] tree_info = [['5' 'Child 2' '3'] ['1' 'Grandparent' 'root'] ['4' 'Child 1' '3'] ['3' 'Parent 2' '1'] ['2' 'Parent 1' '1'] ] # establish root node root = [x[0] for x in tree_info if x[2] == 'root'][0] # assign root node a generation of 0 tree_info[0] append(0) # loop through for node in tree_info: node_id = node[0] node_parent_id = node[2] if node_parent_id == root: # assign a generation of 1 node append(1) for node in tree_info: try: print node[3] * " " node[2] except: print "help" ```` | As suggested in the comments the data structure you are working with is kind of clumsy for tree data Nevertheless it is quite simple to print out the structure of the tree provided that you keep track of the indentation level of the nodes you have seen so far We can do this with a dictionary: ````# establish data set in the format of [node_id name parent_node_id] tree_info = [ ['1' 'Grandparent' 'root'] ['2' 'Parent 1' '1'] ['3' 'Parent 2' '1'] ['4' 'Child 1' '3'] ['5' 'Child 2' '3'] ] generation = {'root': 0} for node in tree_info: node_id name parent_id = node indent = generation[parent_id] generation[node_id] = indent 1 print(indent * ' ' name) ```` Which yields: ````Grandparent Parent 1 Parent 2 Child 1 Child 2 ```` <hr> <h2>If the nodes are out of order </h2> If the nodes are out of order we need to read through the data once to assemble a dictionary of children Then we do a tree search on the dictionary: ````tree_info = [['5' 'Child 2' '3'] ['1' 'Grandparent' 'root'] ['4' 'Child 1' '3'] ['3' 'Parent 2' '1'] ['2' 'Parent 1' '1'] ['6' 'Child 3' '2'] ] children = {} names = {} for node_id name parent in tree_info: children setdefault(parent []) append(node_id) names[node_id] = name q = [('root' -1)] while q: parent depth = q pop() if parent != 'root': print(' ' * depth names[parent]) if parent in children: for child in children[parent]: q append((child depth+1)) ```` This yields: ````Grandparent Parent 1 Child 3 Parent 2 Child 1 Child 2 ```` <hr> <h2>If you would like each level to be in alphabetical order</h2> ````tree_info = [['5' 'A - Child 2' '3'] ['1' 'Grandparent' 'root'] ['4' 'B - Child 1' '3'] ['3' 'A - Parent 2' '1'] ['2' 'B - Parent 1' '1'] ['6' 'C - Child 3' '2'] ] children = {} names = {} for node_id name parent in tree_info: children setdefault(parent []) append(node_id) names[node_id] = name q = [('root' -1)] while q: parent depth = q pop() if parent != 'root': print(' ' * depth names[parent]) if parent in children: level = sorted(children[parent] key=names get) for child in reversed(level): q append((child depth+1)) ```` Which prints: ````Grandparent A - Parent 2 A - Child 2 B - Child 1 B - Parent 1 C - Child 3 ```` |
What does VLW stand for? | United light metal works |
What cellular company is headquartered in San Diego that uses the AT&T network? | Cricket Communications |
how to implement abstract model in spyne I need to implement an abstract model using Spyne In fact let us say - as a simple example - that I want to manage a garage business I then have the following classes: ````class Vehicle(ComplexModel): ''' this class is abstract ''' _type_info = [ ('owner' Unicode) ] class Car(Vehicle): _type_info = [ ('color' Unicode) ('speed' Integer) ] class Bike(Vehicle): _type_info = [ ('size' Integer) ] class Garage(ComplexModel): _type_info = [ ('vehicles' Array(Vehicle)) ] ```` When I want to get all vehicles managed by my garage I will only get their Vehicle properties (aka owner here) and not the other ones Is there a way to manage abstract objects with Spyne? Of course a simple approach would be to have: ````class Garage(ComplexModel): _type_info = [ ('bikes' Array(Bike)) ('cars' Array(Car)) ] ```` but I do not like it: if I do that I will have to change my "Garage" class everytime I create a new Vehicle class I want my Garage class to manage Vehicles no matter what type of Vehicles it is Is it possible? | With Spyne 2 12 1-beta output polymorphism should work (when enabled for the output protocol) with the `Array(Vehicle)` syntax Please see working example here: <a href="https://github com/arskom/spyne/blob/a2d0edd3be5bc0385548f5212b7b4b6d674fd610/examples/xml/polymorphic_array py" rel="nofollow">https://github com/arskom/spyne/blob/a2d0edd3be5bc0385548f5212b7b4b6d674fd610/examples/xml/polymorphic_array py</a> |
TypeError: 'TwitterDictResponse' object is not callable on Twitter library for Python I installed Twitter library for Python with `pip install Twitter` and I am trying to replicate an example from <a href="https://github com/ideoforms/python-twitter-examples/blob/master/twitter-search py" rel="nofollow">here</a> This is my code: ````config = {} execfile("config py" config) twitter = Twitter(auth = OAuth(config["access_key"] config["access_secret"] config["consumer_key"] config["consumer_secret"])) query = twitter search tweets(q = "lazy dog") print query ```` The `config py` file contains the keys where `XxXxX` are my own keys from dev Twitter: ````consumer_key = "XxXxXxxXXXxxxxXXXxXX" consumer_secret = "xXXXXXXXXxxxxXxXXxxXxxXXxXxXxxxxXxXXxxxXXx" access_key = "XXXXXXXX-xxXXxXXxxXxxxXxXXxXxXxXxxxXxxxxXxXXxXxxXX" access_secret = "XxXXXXXXXXxxxXXXxXXxXxXxxXXXXXxXxxXXXXx" ```` However I have this error: `TypeError: 'TwitterDictResponse' object is not callable` Which I could not find anywhere on Google Any idea? | I copy/pasted your code on my laptop and it works perfectly for me with Python 2 and Python 3 (with slight modifications in this case) <br/> I am using the 'twitter-1 17 1' library |
How many solo patents did Bell get? | 18 |
Django object function not working inside views py So I have an object User with the function buy() and it works perfectly in the she will The problem I have is when I try to use it in views py ````def makeOffer(request commodity_id): commodity = get_object_or_404(Commodity pk=commodity_id) context = {} buysell = "no" #For some reason Try and Except must work this way ? try: user = User objects get(name=request GET['user']) buysell = request GET['buysell'] shares = request GET['shares'] price = request GET['price'] if buysell == "buy": user buy(commodity shares price) elif buysell == "sell": user ask(commodity shares price) return HttpResponse('/trading/orders/%s/ %s %s x %s'%(commodity id buysell shares price)) except Exception as e: pass return render(request 'trading/makeoffer html') ```` I used HttpResponse just to debug and see if I am getting the GET variables Now the if and elif statement works I tried echoing out keywords it is the user buy() that triggers the Try statement to run the exception and thus take me back to the form If you are wondering what the code is it is to simulate trading on a market If you want to see how it works inside the she will: ````>>> from trading models import* >>> justin jack = User objects all();denarii gold = Commodity objects all() >>> justin holding(gold) <Holding: Justin holds 0 x Gold> >>> jack holding(denarii) <Holding: Jack holds 0 x Denarii> >>> justin holding(denarii) <Holding: Justin holds 1600 x Denarii> >>> jack holding(gold) <Holding: Jack holds 300 x Gold> >>> justin buy(gold 200 8) #This makes a buy order for 200 at 8 denarii a piece >>> gold offersList() [<Offer: Buy: Gold: user: Justin -> 200 x 8>] >>> jack ask(gold 300 8) #This makes a ask order for 300 at 8 denarii a piece >>> gold offersList() #Leftovers of all offers [<Offer: Sell: Gold: user: Jack -> 100 x 8>] >>> gold ordersList() #All orders that can get through are done [<Order: Justin -> Jack: Gold: 200 x 8] ```` I had to painstakenly write the code by hand because my virtualbox does not let me copy and paste but basically the rest of the she will prompt was just showing how the holdings denarii and other things are all done automatically by the object | Oozemaster solved it I was passing a str where I should have been passing an int |
Dump data from django Feincms I am using feincms in a django project and I want to use manage py dumpdata but I get nothing: ````python manage py dumpdata feincms [] ```` | I do not know FeinCMS but looking at the GitHub repo it seems that the `feincms` application only contains abstract models If you want to dump the data you will need to find where the actual concrete models are and dump that app |
Linux/Python How do I import a root access py module as a non-root user? I am trying to keep passwords that are usually written in a py file separated from the script and make it so that those passwords are only accessible by root and python whenever a script needs it I got the idea reading this: <a href="http://stackoverflow com/a/158248/3892678">http://stackoverflow com/a/158248/3892678</a> To do this I am trying to hide passwords to be used in `a_script` in another `passwords` py file `passwords` can only be read written and executed (`-rwxrwx---`)by root:root As another user `tomato` I want to run `a_script` which imports the password from `passwords` to be used in the file To make it so that this user can run the file as root I have elevated the file's `setuid` and `setgid` with`chmod 6777 a_script py` so that the file has `-rwsrwsrwx` permissions Now as user `tomato` I run `python a_script py` but I get back `ImportError: No module named passwords` I thought that setting the uid and groupid as s would run the file as root which should have permissions to read `passwords` What am I doing wrong? Here is `a_script py` ````import os print "uid: %s" % os getuid() print "euid: %s" % os getgid() print "gid: %s" % os geteuid() print "egid: %s" % os getegid() from passwords import MYPASS print MYPASS ```` All the print statements before I get the `ImportError` are `1001` which is `tomato` Thanks for your help Might there be a better way to "hide" passwords in another file so that only root and programs that need it are the only ones that have access to it? | how bout ````os popen("echo ROOT_PASSWORD | sudo -s -p '' cat /path/to/secure/file txt") read() ```` (note its probably better to use the subprocess module but it requires more typing) |
Where were Canadian ground and air forces based in 1950? | null |
Having trouble comparing a variable to an input in a while loop I am having some trouble working on a basic program I am making whilst I try and learn Python the problem is I am trying to compare a users input to a variable that I have set and it is not working when I try and compare them This is the loop in question: ```` if del_question == "1": symbol = input("What symbol would you like to change?: ") while len(symbol) != 1 or symbol not in words: print("Sorry that is not a valid symbol") symbol = input("What symbol would you like to change?: ") letter = input("What would you like to change it to?: ") while letter in words and len(letter) != 1: print("Sorry that is not a valid letter") letter = input("What letter would you like to change?: ") dictionary[symbol] = letter words = words replace(symbol letter) print("Here is your new code: \n" words) ```` The game is about breaking the code by pairing letters and symbols this is where the letters and symbols are paired but on the letter input when I try and make it so that you are unable to pair up the same letter twice it simply bypasses it It is working on the symbol input but I am not sure on why it is not working here Here is the text file importing: ````code_file = open("words txt" "r") word_file = open("solved txt" "r") letter_file = open("letter txt" "r") ```` and: ````solved = word_file read() words = code_file read() clue = clues_file read() ```` This is the contents of the words file: ````#+/084&" #3*#%#+ 8%203: 1$& !-*% #7&33& #*#71% &-&641'2 #))85 9&330* ```` | Your bug is a simple logic error You have an `and` conditional when you really want an `or` conditional Change your second while statement to: ````while letter in words or len(letter) != 1 ```` |
Python Popen - wait vs communicate vs CalledProcessError Continuing <a href="http://stackoverflow com/a/30967043/281545">from my previous question</a> I see that to get the error code of a process I spawned via Popen in python I have to call either wait() or communicate() (which can be used to access the Popen stdout and stderr attributes): ````app7z = '/path/to/7z exe' command = [app7z 'a' dstFile temp "-y" "-r" os path join(src Dir '*')] process = Popen(command stdout=PIPE startupinfo=startupinfo) out = process stdout regCompressMatch = re compile('Compressing\s+( +)') match regErrMatch = re compile('Error: ( *)') match errorLine = [] for line in out: if len(errorLine) or regErrMatch(line): errorLine append(line) if regCompressMatch(line): # update a progress bar result = process wait() # HERE if result: # in the hopes that 7z returns 0 for correct execution dstFile temp remove() raise StateError(_("%s: Compression failed:\n%s") % (dstFile s "\n" join(errorLine))) ```` However <a href="https://docs python org/2/library/subprocess html#popen-objects" rel="nofollow">the docs</a> warn that `wait()` may deadlock (when stdout=PIPE which is the case here) while `communicate()` might overflow So: - what is the proper thing to use here ? Note that I do use the output - how exactly should I use communicate ? Would it be: ````process = Popen(command stdout=PIPE startupinfo=startupinfo) out = process communicate()[0] # same as before result = process returncode if result: # ```` not sure about blocking and the memory errors - Any better/more pythonic way of handling the problem ? I do not think that <a href="http://stackoverflow com/a/25079374/281545">`subprocess CalledProcessError` or the `subprocess check_call/check_output`</a> apply in my case - or do they ? DISCLAIMER: I did not write the code I am the current maintainer hence question 3 Related: - <a href="http://stackoverflow com/questions/2837214/python-popen-command-wait-until-the-command-is-finished">Python popen command Wait until the command is finished</a> - <a href="http://stackoverflow com/questions/15316398/check-a-commands-return-code-when-subprocess-raises-a-calledprocesserror-except">Check a command's return code when subprocess raises a CalledProcessError exception</a> - <a href="http://stackoverflow com/questions/15107714/wait-process-untill-all-subprocess-finish">wait process untill all subprocess finish?</a> I am on windows if this makes a difference - python 2 7 8 <them>There should be one-- and preferably only one --obvious way to do it</them> | - about the deadlock: It is safe to use `stdout=PIPE` and `wait()` together <strong>iff</strong> you read from the pipe ` communicate()` does the reading and calls `wait()` for you - about the memory: if the output can be unlimited then you should not use ` communicate()` that accumulates <them>all</them> output in memory <blockquote> what is the proper thing to use here ? </blockquote> To start subprocess read its output line by line and to wait for it to exit: ````#!/usr/bin/env python from subprocess import Popen PIPE process = Popen(command stdout=PIPE bufsize=1) with process stdout: for line in iter(process stdout readline b''): handle(line) returncode = process wait() ```` This code does not deadlock due to a finite OS pipe buffer Also the code supports commands with unlimited output (if an individual line fits in memory) `iter()` is used to read a line as soon as the subprocess' stdout buffer is flushed to workaround <a href="https://bugs python org/issue3907" rel="nofollow">the read-ahead bug in Python 2</a> You could use a simple `for line in process stdout` if you do not need to read lines as soon as they are written without waiting for the buffer to fill or the child process to end See <a href="http://stackoverflow com/a/17698359/4279">Python: read streaming input from subprocess communicate()</a> If you <them>know</them> that the command output can fit in memory in all cases then you could get the output all at once: ````#!/usr/bin/env python from subprocess import check_output all_output = check_output(command) ```` It raises `CalledProcessError` if the command returns with a non-zero exit status Internally <a href="https://hg python org/cpython/file/2 7/Lib/subprocess py#l544" rel="nofollow">`check_output()` uses `Popen()` and ` communicate()`</a> <blockquote> There should be one-- and preferably only one --obvious way to do it </blockquote> `subprocess Popen()` is the main API that works in many many cases There are convenience functions/methods such as `Popen communicate()` `check_output()` `check_call()` for common use-cases There are multiple methods functions because there are multiple different use-cases |
Python Key Error when setting environment variable in supervisord I set an environment variable in supervisord: ````[program:worker] directory = /srv/app/ command=celery -A tasks worker -Q default -l info -n default_worker %%h environment=BROKER="amqp://admin:password@xxxxx:5672//" ```` Within my celeryconfig py I then try to read that variable like this ````BROKER = os environ['BROKER'] ```` But I still get the key the error below why? ```` File "/usr/local/lib/python2 7/dist-packages/celery/loaders/base py" line 106 in import_module return importlib import_module(module package=package) File "/usr/lib/python2 7/importlib/__init__ py" line 37 in import_module __import__(name) File "/srv/app/celeryconfig py" line 6 in <module> BROKER = os environ['BROKER'] File "/usr/lib/python2 7/UserDict py" line 23 in __getitem__ raise KeyError(key) KeyError: 'BROKER ```` There is a file dump of the envs as suggested in the comments: ````{ 'SUPERVISOR_GROUP_NAME': 'celery_default_worker' 'TERM': 'linux' 'SUPERVISOR_SERVER_URL': 'unix: ///var/run/supervisor sock' 'UPSTART_INSTANCE': '' 'RUNLEVEL': '2' 'UPSTART_EVENTS': 'runlevel' 'PREVLEVEL': 'N' 'SUPERVISOR_PROCESS_NAME': 'celery_default_worker' 'UPSTART_JOB': 'rc' 'PWD': '/' 'SUPERVISOR_ENABLED': '1' 'runlevel': '2' 'PATH': '/usr/local/sbin: /usr/local/bin: /sbin: /bin: /usr/sbin: /usr/bin' 'previous': 'N' } ```` | <strong>This answer is most likely not the because check <a href="http://stackoverflow com/a/28829162/1589147">http://stackoverflow com/a/28829162/1589147</a> for information on a related supervisord bug instead </strong> I can reproduce your error partially I do not see the error when celery runs within supervisor I see the error when I try to run the task from an environment outside supervisor where I did not set the `BROKER` environment variable `celeryconfig py` is executed both by celery and by anything which tries to execute a task I am not certain if this issue is exactly what you have come across if you could share how you are executing the tasks and when that exception is raised it may help For example if I try to run the task from `ipython` an error is generated which matches your error ````In [1]: from tasks import add In [2]: add delay(2 3) 21 if hasattr(self __class__ "__missing__"): 22 return self __class__ __missing__(self key) --> 23 raise KeyError(key) 24 def __setitem__(self key item): self data[key] = item 25 def __delitem__(self key): del self data[key] KeyError: 'BROKER' ```` The `celeryconfig py` is loaded locally in order to establish a connection to the celery broker and backend I am unable to execute the task without setting the `BROKER` environment variable If I set the environment variable before executing my task the same code works for me ````In [3]: import os In [4]: os environ["BROKER"] = "broker is set" In [5]: add delay(2 3) Out[5]: <AsyncResult: 0f3xxxx-87fa-48d7-9258-173bdd2052ca> ```` Here are the files I used in case it helps `supervisor conf`: `supervisord -c supervisor conf` ````[unix_http_server] file=/tmp/supervisor sock [supervisord] loglevel = info nodaemon = true identifier = supervisor [supervisorctl] serverurl=unix:///tmp/supervisor sock [rpcinterface:supervisor] supervisor rpcinterface_factory = supervisor rpcinterface:make_main_rpcinterface [program:worker] command=/app/srv/main-env/bin/celery -A tasks worker -Q default -l info -n default_worker %%h environment=BROKER="amqp://admin:password@xxxxx:5672//" directory=/app/srv/ numprocs=1 stdout_logfile=/app/srv/worker log stderr_logfile=/app/srv/worker log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 ```` `celeryconfig py`: ````import os BROKER = os environ['BROKER'] ```` `tasks py`: ````from celery import Celery app = Celery( 'tasks' backend='amqp' broker='amqp://admin:password@xxxxx:5672//') app config_from_object('celeryconfig') @app task def add(x y): return x y ```` |
How do I import a third-party IronPython module in NET? I am C# developer and I have to use an IronPython library in the NET framework I tested every class in Python and it is working but I am not sure how to call the library in a C# class When I try to call the library I am getting a `'LightException' object has no attribute` client error I have added lib -x:Full frame and also all modules in the lib folder Here is the C# code I am using to call the Python library: ```` Console WriteLine("Press enter to execute the python script!"); Console ReadLine(); var options = new Dictionary<string object>(); options["Frames"] = true; options["FullFrames"] = true; //var py = Python CreateEngine(options); //py SetSearchPaths(paths); ScriptEngine engine = Python CreateEngine(options); ICollection<string> paths = engine GetSearchPaths(); string dir = @"C:\Python27\Lib\"; paths Add(dir); string dir2 = @"C:\Python27\Lib\site-packages\"; paths Add(dir2); engine SetSearchPaths(paths); ScriptSource source = engine CreateScriptSourceFromFile(@"C:\Users\nikunjmange\Source\Workspaces\Visage Payroll\VisagePayrollSystem\VisagePayrollSystem\synapsepayLib\synapse_pay-python-master\synapse_pay\resources\user py"); ScriptScope scope = engine CreateScope(); source Execute(scope); dynamic Calculator = scope GetVariable("User"); dynamic calc = Calculator(); string inputCreate = "nik12@gmail com"; string result = calc create(inputCreate); ```` | - The error is misleading <a href="https://github com/IronLanguages/main/issues/1189" rel="nofollow">because of a bug in IronPython 2 7 5</a> It should be an `ImportError` - Do not add the normal CPython stdlib; it is not compatible with IronPython Use IronPython's stdlib instead If you have an import of `import a b as c` that is probably the culprit; either a or b does not exist but IronPython mucks up the error reporting |
Parabolic velocity profile in Python I am trying to plot a parabolic velocity profile such that the parabola is pointing in the <strong>positive x-direction</strong> ````from scitools std import * def v(y): return h**2 - y**2 h = 2 x = linspace(0 5 101) y = linspace(-2 2 101) v = v(y) plot(x v) ```` I get the following: <a href="http://i stack imgur com/28KpB png" rel="nofollow"><img src="http://i stack imgur com/28KpB png" alt="http://i stack imgur com/28KpB png"></a> This plot is pointing upwards y-axis but I want the plot to be like this: <a href="http://i stack imgur com/34AQi png" rel="nofollow"><img src="http://i stack imgur com/34AQi png" alt="http://i stack imgur com/34AQi png"></a> but with `y-axis = [-2 2]` and not `[0 5]` How could I do this? | You need to switch `x` and `y`: ````h = 2 y = linspace(-2 2 101) plot(h**2 - y**2 y) ```` |
What kind of uranium is always used to shield radioactive materials in containers? | null |
Passing "options" to Tastypie Serializers The documentation for Tastypie serializers and custom serializers shows `options` defaulting to `None`: ````to_json(self data options=None): options = options or {} ```` But then downstream code does not seem to leverage it other than passing it to `to_simple()` which also does nothing with it There is also no documentation showing how to pass options into these functions I would like to be able to pass options here so I can adjust how my serializers work For example we have content which references data in GridFS I want to do something like: ````/api/v1/foo/?format=custom&gridfs=1 ```` And have this: ````to_custom(self data options=None): options = options or {} if options and 'gridfs' in options: ```` | I think you will want to implement your own serializer as explained here: <a href="http://django-tastypie readthedocs org/en/latest/cookbook html#camelcase-json-serialization" rel="nofollow">http://django-tastypie readthedocs org/en/latest/cookbook html#camelcase-json-serialization</a> You will also want to override the `create_response` function in your resource which calls `serialize`: <a href="https://github com/toastdriven/django-tastypie/blob/master/tastypie/resources py#L1174" rel="nofollow">https://github com/toastdriven/django-tastypie/blob/master/tastypie/resources py#L1174</a> You can turn pass in `options` to serialize here which will propagated down For instance: ```` def create_response(self request data response_class=HttpResponse **response_kwargs): """ Extracts the common "which-format/serialize/return-response" cycle Mostly a useful shortcut/hook """ desired_format = self determine_format(request) serialized = self serialize(request data desired_format options=request GET) return response_class(content=serialized content_type=build_content_type(desired_format) **response_kwargs ```` For completeness `serialize` is also called in error response here: <a href="https://github com/toastdriven/django-tastypie/blob/master/tastypie/resources py#L1210" rel="nofollow">https://github com/toastdriven/django-tastypie/blob/master/tastypie/resources py#L1210</a> |
Model is not defined I am using Flask and Peewee to create models for `Users` and `Appointments` and each of them have a `ForeignKeyField` referencing each other The problem is if I define one above the other Flask will give me `x is not defined` For example: ````class User(Model): appointments = ForeignKeyField(Appointment related_name='appointments') class Appointment(Model): with_doctor = ForeignKeyField(User related_name='doctor') ```` This would return `'User' is not defined` How am I able to fix this problem? | You can define it as a string as far as i know: ````class User(Model): appointments = ForeignKeyField("Appointment" related_name='appointments') class Appointment(Model): with_doctor = ForeignKeyField(User related_name='doctor') ```` if the declaration is before the creation you have the option to write it as a string I am not sure i think that the bind is at runtime |
What character represents the "line feed" function? | character 10 |
What can visceral pain be accompanied by? | nausea and vomiting |
Flask app runs fine locally throws 500 on Heroku (on some routes) & no logs I have a Flask app that runs fine locally I pushed it to this Heroku URL: <a href="https://secret-sierra-6425 herokuapp com/" rel="nofollow">https://secret-sierra-6425 herokuapp com/</a> And the landing page works which means the '/' route code works But when I try to access other resources it throws a 500 error and I do not see anything useful in the logs: ````2015-04-06T08:17:29 687713+00:00 app[web 1]: [2015-04-06 08:17:29 0000] [3] [INFO] Shutting down: Master 2015-04-06T08:17:30 397309+00:00 app[web 1]: [2015-04-06 08:17:30 0000] [3] [INFO] Starting gunicorn 19 3 0 2015-04-06T08:17:30 484520+00:00 app[web 1]: [2015-04-06 08:17:30 0000] [10] [INFO] Booting worker with pid: 10 2015-04-06T08:17:30 398009+00:00 app[web 1]: [2015-04-06 08:17:30 0000] [3] [INFO] Listening at: http://0 0 0 0:18230 (3) 2015-04-06T08:17:30 398107+00:00 app[web 1]: [2015-04-06 08:17:30 0000] [3] [INFO] Using worker: sync 2015-04-06T08:17:30 407696+00:00 app[web 1]: [2015-04-06 08:17:30 0000] [9] [INFO] Booting worker with pid: 9 2015-04-06T08:17:30 682319+00:00 heroku[web 1]: State changed from starting to up 2015-04-06T08:17:30 618107+00:00 heroku[web 1]: Process exited with status 0 2015-04-06T08:18:23 485060+00:00 heroku[router]: at=info method=GET path="/" host=secret-sierra-6425 herokuapp com request_id=cbdfada9-8b28-4150-a7c0-eddc458658d9 fwd="23 252 53 59" dyno=web 1 connect=1ms service=2ms status=200 bytes=186 2015-04-06T08:18:35 630070+00:00 heroku[router]: at=info method=POST path="/messages" host=secret-sierra-6425 herokuapp com request_id=aaecbfbd-57b5-49eb-aee0-ad450ba67e36 fwd="23 252 53 59" dyno=web 1 connect=1ms service=19ms status=500 bytes=456 ```` This is the code to start my app: ````if __name__ == '__main__': app debug = True #Only for development not prod app logger addHandler(logging StreamHandler(sys stdout)) app logger setLevel(logging ERROR) app run() ```` Procfile: ````web: gunicorn mailr:app --log-file=- worker: python worker py ```` My application uses redis queue as well I have added the RedisToGo addon Still no luck Can anyone help me find a way to display the logs so that I can debug what is going wrong? \ EDIT: Also tried changing the start to this but still no luck: ````app debug = True #Only for development not prod file_handler = StreamHandler() app logger setLevel(logging DEBUG) # set the desired logging level here app logger addHandler(file_handler) app run() ```` | Got it The code for logging should have been out of <strong>main</strong> |
Change session variable value fails <strong>EDIT: actually I can see the value of the session variable changed but in the next call to the function the value is set back to 0</strong> I am a Flask beginner and I have problems in changing the value of a session variable Here is an excerpt of my code: <strong>EDIT after first round of comments</strong> 0) I set the `SECRET_KEY` variable in my config py 1) when a user logs in I set a session variable: ````@app route('/login' methods=['GET' 'POST']) def login(): session['info_released'] = 0 app logger debug('info_released session value: {}' format(session['info_released']) ```` Checking the log the value of the session variable is correctly set to 0 2) I have a `counter` variable passed via `request json` that is incremented from time to time Between one `counter` increment and the following one I check the following condition several times (via an ajax call): ````@app route('/get_actual_demand' methods=['GET' 'POST']) def get_actual_demand(): app logger info('> SESSION: {}' format(session['info_released'])) if request json['counter'] == 10 and session['info_released'] == 0: #code session['info_released'] = 1 app logger info('> SESSION VAR AFTER CHANGE: {}' format(session['info_released'])) return jsonify(released=1) else: return jsonify(released=0) ```` That is when `counter == 10` I check the condition many times but I want to run the `#code` only once (the first time the `counter == 10` and the session variable is 0) <strong>EDIT:</strong> Checking the log the `session['info_released']` is changed to 1 when `counter == 10` but in the next call the value is set back to 0: indeed the `#code` is run many times until the `counter` gets incremented I cannot understand what I am doing wrong I may also have the program flow better organized but I do not think it matters with the problem I am having <strong>EDIT:</strong> it seems that everything I do on the session variables inside the `get_actual_demand()` view function are only "local" I changed the code as follows removing the `session['info_released'] = 0` from the `login()` function: ````@app route('/get_actual_demand' methods=['GET' 'POST']) def get_actual_demand(): # the variable session['info_released'] is no more # defined in the login() function if request json['counter'] == 10: try: # The first time I get here raise a KeyError exception if session['info_released'] == 1: return jsonify(released=0) except KeyError: # Use `session['info_released']` as a flag # defined here session['info_released'] = 1 return jsonify(released=1) else: return jsonify(released=0) ```` Checking the log (removed from the code) I can see the session variable defined when it first hits the exception but then hits again the exception as if the session variable is still not present I think there is something missing in my configuration but I cannot find hints in the documentation My config py is as follows: ````import os basedir = os path abspath(os path dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True WTF_CSRF_ENABLED = True SECRET_KEY = 'oqEr[]*woi+145@#11!&$fsa%(Mn21eq' SQLALCHEMY_MIGRATE_REPO = os path join(basedir 'db_repository') class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True SQLALCHEMY_DATABASE_URI ='postgresql+psycopg2://libra:password@localhost/mydb' ```` | I had the same problem and I solved it using Flask-Session extension which adds support for Server-side Session to your application Here is the URL: <a href="http://pythonhosted org/Flask-Session/" rel="nofollow">http://pythonhosted org/Flask-Session/</a> I added the next lines to my app: ````from flask import Flask session from flask ext session import Session app = Flask(__name__) SESSION_TYPE = 'filesystem' app config from_object(__name__) Session(app) ```` and that is all No need secret keys Hope this helps |
Checking if a list of tuples are the same Is there an easy way to see if a list of tuples in python are the same (same tuple in each position where a tuple is the same if their corresponding elements are the the same)? I know how to manually loop through the list and compare each element but was wondering if there were any library functions that could do this? | ````len(list1) == len(list2) and all(a == b for a b in zip(list1 list2)) ```` That was my first guess but I just tried the obvious and simple solution and that worked too: ````list1 == list2 ```` |
Which country did Iraq invade in 1990? | Kuwait |
How to write python unittest for column name is a string? I am not if this is right to but I have this so far and I am trying to write unittest for this ```` def ValidateInputs(self class_column_name ): class_column_name_ok = type(class_column_name) is str if not class_column_name_ok: raise(TypeError("Argument class_column_name must be a string type")) ```` I did this for this unittest but again with not having enough knowledge I am not sure Any help will be much appreciated ````def testClassColumnName(self): self assertTrue(type(class_column_name) "str") ```` | Without knowing what you do with these values I cannot say 100% I will assume you bind them to the class then provide the unittests I would write Application code: ````class MyClass(object): """This is my object this is what it does""" def validate_inputs(self merge_columns class_column_name): """some handy docstring""" if not isinstance(class_column_name str): raise TypeError('Argument class_column_name must be a string supplied {0}' format(type(class_column_name)) self class_column_name = class_column_name ```` unittests (using unittest form the stdlib): ````import unittest class TestMyClass(unittest TestCase): def setUp(self): self myclass = MyClass() # cheap way to always have a 'clean class' for testing def test_validate_input_type_string(self): """Happy path test when input is correct and everything works""" self myclass validate_input(merge_columns='some-columns' class_column_name='some_column_name') self assertEqual(True isinstance(self myclass class_column_name str)) def test_validate_input_raises_typerror(self): """We raise TypeError if input != string""" self assertRaises(TypeError self myclass validate_input merge_columns=1234 class_column_name=4321) if __name__ == '__main__': unittest main() ```` General tips for unittesting: A) Use self assertEqual(A B) -> the output on failure will give you some clue on why it failed Using something like self assertTrue normaly just outputs an error message like "False is not True"; which is while 100% accurate not very useful B) Supplying all positional args as key-word args -> makes reading the test later easier C) One assert per test case (two at the very most) -> more than this tends to get your test code too complex Test should be so simple that anyone (even that intern that was just hired from a 3 month coding bootcamp) can figure them out It is really painful to rewrite a hole test suite (or spend hours updating test code) b/c of a 10 minute update to application code Hope this is helpful |
How can I elegantly combine/concat files by section with python? Like many an unfortunate programmer soul before me I am currently dealing with an archaic file format that refuses to die I am talking ~1970 format specification archaic If it were solely up to me we would throw out both the file format and any tool that ever knew how to handle it and start from scratch I can dream but that unfortunately that will not resolve my issue <strong>The format:</strong> Pretty Loosely defined as years of nonsensical revisions have destroyed almost all back compatibility it once had Basically the only constant is that there are section headings with few rules about what comes before or after these lines The headings are sequential (e g HEADING1 HEADING2 HEADING3 ) but not numbered and are not required (e g HEADING1 HEADING3 HEADING7) Thankfully all possible heading permutations are known Here is a fake example: ````# Bunch of comments SHOES # First heading # bunch text and numbers here HATS # Second heading # bunch of text here SUNGLASSES # Third heading ```` <strong>My problem:</strong> I need to concatenate multiple of these files by these section headings I have a perl script that does this quite nicely: ````while(my $l=<>) { if($l=~/^SHOES/i) { $r=\$shoes; name($r);} elsif($l=~/^HATS/i) { $r=\$hats; name($r);} elsif($l=~/^SUNGLASSES/i) { $r=\$sung; name($r);} elsif($l=~/^DRESS/i || $l=~/^SKIRT/i ) { $r=\$dress; name($r);} elsif($l=~/^END/i) { $r=\$end; name($r);} else { $$are = $l; } print STDERR "Finished processing $ARGV\n" if eof; } ```` As you can see with the perl script I basically just change where a reference points to when I get to a certain pattern match and concatenate each line of the file to its respective string until I get to the next pattern match These are then printed out later as one big concated file I would and could stick with perl but my needs are becoming more complex every day and I would really like to see how this problem can be solved elegantly with python (can it?) As of right now my method in python is basically to load the entire file as a string search for the heading locations then split up the string based on the heading indices and concat the strings This requires a lot of regex if-statements and variables for something that seems so simple in another language It seems that this really boils down to a fundamental language issue I found a very nice SO discussion about python's "call-by-object" style as compared with that of other languages that are call-by-reference <a href="http://stackoverflow com/questions/986006/python-how-do-i-pass-a-variable-by-reference">Python: How do I pass a variable by reference?</a> Yet I still cannot think of an elegant way to do this in python If anyone can help kick my brain in the right direction it would be greatly appreciated | I am not sure if I understand your whole problem but this seems to do everything you need: ````import sys headers = [None 'SHOES' 'HATS' 'SUNGLASSES'] sections = [[] for header in headers] for arg in sys argv[1:]: section_index = 0 with open(arg) as f: for line in f: if line startswith(headers[section_index 1]): section_index = section_index 1 else: sections[section_index] append(line) ```` Obviously you could change this to read or `mmap` the whole file then `re search` or just `buf find` for the next header Something like this (untested pseudocode): ````import sys headers = [None 'SHOES' 'HATS' 'SUNGLASSES'] sections = defaultdict(list) for arg in sys argv[1:]: with open(arg) as f: buf = f read() section = None start = 0 for header in headers[1:]: idx = buf find('\n'+header start) if idx != -1: sections[section] append(buf[start:idx]) section = header start = buf find('\n' idx+1) if start == -1: break else: sections[section] append(buf[start:]) ```` And there are plenty of other alternatives too But the point is I cannot see anywhere where you would need to pass a variable by reference in any of those solutions so I am not sure where you are stumbling on whichever one you have chosen <hr> So what if you want to treat two different headings as the same section? Easy: create a `dict` mapping headers to sections For example for the second version: ````headers_to_sections = {None: None 'SHOES': 'SHOES' 'HATS': 'HATS' 'DRESSES': 'DRESSES' 'SKIRTS': 'DRESSES'} ```` Now in the code that does`sections[section]` just do `sections[headers_to_sections[section]]` For the first just make this a mapping from strings to indices instead of strings to strings or replace `sections` with a `dict` Or just flatten the two collections by using a `collections OrderedDict` |
Difference between save() and put()? What is the difference between Mymodel save() and Mymodel put() in appengine with python? I know that save is used in django but does is work with appengine models too? | save() is a (deprecated) alias for put() They work exactly equivalently - in fact they are the same function! |
Python raw http request retrieval issues via urllib2 I am using Python 2 6 5 and I am trying to capture the raw http request sent via HTTP this works fine except when I add a proxy handler into the mix so the situation is as follows: - HTTP and HTTPS requests work fine <them>without</them> the proxy handler: raw HTTP request captured - HTTP requests work fine with proxy handler: proxy ok raw HTTP request captured - HTTPS requests fail with proxy handler: proxy ok but the raw HTTP request is not captured! The following questions are close but do not solve my problem: - <a href="http://stackoverflow com/questions/603856/how-do-you-get-default-headers-in-a-urllib2-request">How do you get default headers in a urllib2 Request?</a> <- My solution is heavily based on this - <a href="http://stackoverflow com/questions/2927831/python-urllib2-http-proxy-https-request">Python urllib2 > HTTP Proxy > HTTPS request</a> - <a href="http://www hackorama com/python/upload shtml" rel="nofollow">This sets the proxy for each request</a> <- Did not work and doing it once at the start via an opener is more elegant and efficient (instead of setting the proxy for each request) This is what I am doing: ````class MyHTTPConnection(httplib HTTPConnection): def send(self s): global RawRequest RawRequest = s # Saving to global variable for Requester class to see httplib HTTPConnection send(self s) class MyHTTPHandler(urllib2 HTTPHandler): def http_open(self req): return self do_open(MyHTTPConnection req) class MyHTTPSConnection(httplib HTTPSConnection): def send(self s): global RawRequest RawRequest = s # Saving to global variable for Requester class to see httplib HTTPSConnection send(self s) class MyHTTPSHandler(urllib2 HTTPSHandler): def https_open(self req): return self do_open(MyHTTPSConnection req) ```` Requester class: ````global RawRequest ProxyConf = { 'http':'http://127 0 0 1:8080' 'https':'http://127 0 0 1:8080' } # If ProxyConf = { 'http':'http://127 0 0 1:8080' } then Raw HTTPS request captured BUT the proxy does not see the HTTPS request! # Also tried with similar results: ProxyConf = { 'http':'http://127 0 0 1:8080' 'https':'https://127 0 0 1:8080' } ProxyHandler = urllib2 ProxyHandler(ProxyConf) urllib2 install_opener(urllib2 build_opener(ProxyHandler MyHTTPHandler MyHTTPSHandler)) urllib2 Request('http://www google com' None) # global RawRequest updated # This is the problem: global RawRequest NOT updated!? urllib2 Request('https://accounts google com' None) ```` BUT if I remove the ProxyHandler it works!: ````global RawRequest urllib2 install_opener(urllib2 build_opener(MyHTTPHandler MyHTTPSHandler)) urllib2 Request('http://www google com' None) # global RawRequest updated urllib2 Request('https://accounts google com' None) # global RawRequest updated ```` How can I add the ProxyHandler into the mix while keeping access to the RawRequest? Thank you in advance | Answering my own question: It seems a bug in the underlying libraries making RawRequest a list solves the problem: The HTTP Raw request is the first item The custom HTTPS class is called several times the last of which is blank The fact that the custom HTTP class is only called once suggests this is a bug in python but the list solution gets around it ````RawRequest = s ```` just needs to be changed to: ````RawRequest append(s) ```` with a previous initialisation of `RawRequest = []` and retrieval of raw request via `RawRequest[0]` (first element of the list) |
What do international donors do to promote democracy? | provide financing to political parties in developing countries |
Idiomatic way to construct a SQL INSERT query in Python I have a bit of code to insert some values in a table It seems a bit clunky - is there a neater way? words is a list of dictionaries and the entries contain other fields which I do not want to insert ```` # add the list of words to the words table time_stamp = datetime datetime now() isoformat() sql = "INSERT INTO words (word user_id game_id score time_stamp) VALUES " vals = [] for word in words: vals append("('%s' %s %s %s '%s')" % (word['str'] user_id game_id word['score'] time_stamp)) cur execute(sql " " join(vals)) ```` | you can do simply this: ````tupleOfValues = [ value1 value2 value3 value4 value5] cur execute("INSERT INTO words (word user_id game_id score time_stamp) VALUES (? ? ? ? ?)" tupleOfValues) ```` or ````cur execute("INSERT INTO words (word user_id game_id score time_stamp) VALUES (? ? ? ? ?)" [ value1 value2 value3 value4 value5]) ```` |
Integer division: is a//b == int(a/b) true for all integers a b? I know that integer division will always return the same answer as truncation of a floating point result if the numbers are both positive Is it true if one or both of them are negative? I was just curious to know if there was an integer division expression that would return the same results in Python 2 and Python 3 (and yes I know about `from __future__ import division`) P S Let us ignore floating point overflow for the moment | It is not true in Python 3 and you can test it for yourself: <pre class="lang-python prettyprint-override">`>>> int(-1/3) == -1//3 False ```` Integer division and modulo of `a` and `b` giving `q` (quotient) and `r` (remainder) respectively will always return numbers that satisfy `b*q are == a` and `(a*b)>0 == q>0` (i e `a*b` and `q` have the same sign) and `abs(r) < abs(q)` The expression `int(q)` simply always rounds towards 0 if `q` is a floating point number It will always be true for Python 2 unless you do `from __future__ import division` but that is because `a/b == a//b` if `a` and `b` are integers in Python 2 |
How to implement a call-by-reference structure in Python I am coding a decision tree and I decided a nice implementation would be a Class/Object structure of the branches (at least in C++) For the sake of simplicity I am going to break it down to the <them>necessary</them> parts: ````class DecisionTreeBranch: def __init__(self): parent = None leftBranch = None rightBranch = None ```` where `parent` declares the way to the super decisions and `leftBranch` `rightBranch` defines the decisions below <strong>What I am trying to do</strong>: Now going downwards are not a problem but moving upwards: Let us say this tree is defined by the left branches first so if I end up in a final <them>leaf</them> I Am going one step above and take the right branch and continue with the tree building (if I go above right and left is defined I am going another step above and so on) The aim is to iterate through the tree by the three parameters: `parent` (up) and `leftBranch` `rightBranch` (down) <strong>The problem</strong> If I would take e g C++ then this would not be a problem I would define parent with a <them>call-by-reference</them> But I recently started programming classes in Python unfortunately I always end up in a <them>call-by-value</them> expression where for sure all the information of the above branches are lost Basically I am looking for something like: ````[ ] # define way to former branch &curDecision parent = &oldDecision oldDecision = curDecision # continue with the next/new decision on the current level curDecision = DecisionTreeBranch() [ ] ```` Can anyone help me out ? Kind Regards | You can always pass a dictionary with keys parent left right You will be able to modify the dictionary and access the structure by keys |
How to mock xml data excange for writing unittests in python I am writing unit tests for functions in python which get and set xml data from/to the hardware's firmware How can i mock such things I am using python and nose | I have not written a ton of Python but the concept will apply from other languages The idea is to create an abstraction over the XML data from the hardware In C# or Java you would use an interface Once you have an interface in place you can have many different implementations of it You can have an implementation that talks to the hardware (for production) and one that is mocked That way you can run your tests even if the hardware is not available This sounds like what you would want in Python: <a href="http://stackoverflow com/questions/4549018/what is-the-python-version-for-code-against-an-interface-not-an-object">What's the Python version for âCode against an interface not an objectâ?</a> |
how fft (fast Fourier transform) works I am a learner of python and developing a small project related to image analysis to learn the concept I tried to understand various python codes but this time I sucked and can any one explain this code ? Especially the FFT part ? ````class HeartMonitor(object): def __init__(self window_duration fps = 30 min_bpm = 50 max_bpm = 200): """ Class which detects heart-beats in a sequence of image colour samples @param window_duration The number of seconds of samples to use @param fps The nominal sample rate @param min_bpm Minimum cut-off for possible heartrates @param max_bpm Maximum cut-off for possible heartrates """ self min_bpm = min_bpm self max_bpm = max_bpm # The maximum number of samples to buffer self buf_size = int(window_duration*fps) # Buffer of (timestamp value) tuples self buf = [] @property def fps(self): """ The average framerate/samplerate of the buffer """ return float(len(self buf)) / (self buf[-1][0] - self buf[0][0]) def get_fft(self): """ Perform an Fast-Fourier-Transform on the buffer and return (magnitude phase) tuples for each of the bins """ # Get the "ideal" evenly spaced times even_times = numpy linspace(self buf[0][0] self buf[-1][0] len(self buf)) # Interpolate the data to generate evenly temporally spaced samples interpolated = numpy interp(even_times *zip(*self buf)) # Perform the FFT fft = numpy fft rfft(interpolated) return zip(numpy abs(fft) numpy angle(fft)) ```` | `numpy fft rfft` is a library function that computes an fft from real data The samples need to be evenly spaced in the time domain Since some samples may not be evenly spaced in `buf` they are interpolated using `numpy interp` `self buf[0]` is the first item of `buf` `self buf[-1]` is the last item of `buf` `len(self buf)` is the number of items in `buf` So you end up with the same number of samples but moved along the time axis so they are evenly spaced (stored in the variable `interpolated`) Now `interpolated` can be passed to `numpy fft rfft` |
FTP over different networks in python I and my friend have undertaken a small project as our plan for the summer and we were trying to employ FTP using python as a part of the project We can successfully transfer the files over the same network but we have no clue as to how we can transfer files when we connected by internet(by a different network) I have added the code for your reference I new to both FTP and python it would be great if somebody can help us out Server side program: ```` #server py from pyftpdlib ftpserver import DummyAuthorizer from pyftpdlib ftpserver import FTPHandler from pyftpdlib ftpserver import FTPServer authorizer = DummyAuthorizer() authorizer add_user("user" "12345" "/" perm="elradfmw") authorizer add_anonymous("/") handler = FTPHandler handler authorizer = authorizer server = FTPServer(("xxx xxx x x" 2121) handler) server serve_forever() ```` And the client program: ```` #client py import ftplib fileTransfer = ftplib FTP() fileTransfer connect("xxx xxx x x" 2121) fileTransfer login('user' '12345') fileTransfer retrlines('LIST') fileTransfer cwd('/home/royal/MyPrograms/Python') fileTransfer retrbinary('RETR Florida mp3' open('club mp3' 'wb') write) ```` I am working behind a NAT | You are probably running into firewall issues; using <a href="http://www jscape com/blog/bid/80512/Active-v-s-Passive-FTP-Simplified" rel="nofollow">passive mode FTP</a> should help There is a good explanation at that link but the short version is that FTP by default uses "active" mode where the client creates a connection to the server to make a request then the server creates a <them>new</them> connection to the client to respond Most firewalls are configured to block "spontaneous" inbound connections and unless the firewall is specifically configured to look at the content of the outbound connection from the client and see "ah ha an FTP request I should expect an incoming connection from that server very soon" it will block the connection Passive mode on the other hand has the client create two outbound connections one for the request and a second one (on a different randomly-chosen port) that the server will use to send the response Off-the-shelf router+firewall solutions in their default configuration will let all outbound connections go through so this would make the firewall on the client's side let the connections through Configuring the firewall on the server side would be harder though as the incoming connection for the data could be on any port -- unless you narrow down the passive data port range So what you should do is: - Use passive mode - Configure the server to accept a certain range of ports (like say 34500 to 34510 to pick numbers at random -- it does not need to be a very large range) for its passive data transfers - Configure the firewall on the server side to allow incoming connections on that port range as well as on your "normal" FTP port (2121 in your case) If the issues you are having are firewall issues that should make it work for you If it is still not working; you may have another problem so go ahead and ask a new question! (Or update this one if it is <them>clearly</them> related to the firewall issues) |
python: PyYAML module not parsing to object trying to get a YAML document to parse into python dictionary object that I can manipulate I installed `pip install pyyaml` ````import yaml yamlstring = "some: var \n another: 3" type(yaml load(yamlstring)) >> str ```` to my surprise it returns a string not a dictionary! what did I do wrong here? | Too much whitespace ````>>> import yaml >>> yamlstring = "some: var\nanother: 3" >>> type(yaml load(yamlstring)) dict ```` |
Accessing files in python egg from inside the egg The question is an attempt to get the exact instruction on how to do that There were few attempts before which do not seem to be full solutions: <a href="http://stackoverflow com/questions/3071327/problem-accessing-config-files-within-a-python-egg">solution to move the file inside the package</a> <a href="http://stackoverflow com/questions/3655352/how-to-access-files-inside-a-python-egg-file">solution to read as zip</a> <a href="http://stackoverflow com/questions/177910/accessing-python-eggs-own-metadata">accessing meta info via get_distribution</a> The task at hand is to read the information about the egg the program is running from There are few ways as i understand: - hard code the location of the egg and treat it as zip archive - will work but not flexible enough because it will need to be edited and recompiled in case if file is moved to another location - use `ResourceManager() resource_filename(__name__ filename)` - this seems to be limited in the fact that i cannot access the file that is inside the egg but not inside the package notations like " / /EGG-INFO/PKG-INFO" in filename do not work giving KeyError So no good either - use `dist = pkg_resources get_distribution("dist_name")` and then use dist object to get information but I cannot understand from the docs how should i specify my distribution name? It cannot find it So i am looking for correct solution about using `pkg_resources get_distribution` plus it would be nice to finally have a full solution to read any file from inside the egg Thanks! | The <a href="http://docs python org/library/zipimport html#zipimporter-objects" rel="nofollow">`zipimporter`</a> used to load a module can be accessed using the <a href="http://www python org/dev/peps/pep-0302/#specification-part-1-the-importer-protocol" rel="nofollow">`__loader__`</a> attribute on the module so accessing a file within the egg should be as simple as: ````__loader__ get_data('path/within/the/egg') ```` |
What was less energy efficient in than AC in providing energy? | null |
Django - Did you forget to register or load this tag? I have created a custom tag that I want to use but Django cannot seem to find it My `templatetags` directory is set up like this: <a href="http://i stack imgur com/FMI2O png" rel="nofollow"><img src="http://i stack imgur com/FMI2O png" alt=""></a> **pygmentize py** ````from pygments import highlight from pygments lexers import get_lexer_by_name from django import template from pygments formatters other import NullFormatter register = template Library() @register tag(name='code') def do_code(parser token): code = token split_contents()[-1] nodelist = parser parse(('endcode' )) parser delete_first_token() return CodeNode(code nodelist) class CodeNode(template Node): def __init__(self lang code): self lang = lang self nodelist = code def render(self context): code = self nodelist render(context) lexer = get_lexer_by_name('python') return highlight(code lexer NullFormatter()) ```` I am trying to use this tag to render code in `gameprofile html` **gameprofile html** ````(% load pygmentize %} {% block content %} <title>{% block title %} | {{ game title }}{% endblock %}</title> <div id="gamecodecontainer"> {% code %} {{game code}} {% endcode %} </div> {% endblock content %} ```` When I navigate to `gameprofile html` I get an error: <blockquote> Invalid block tag on line 23: 'code' expected 'endblock' Did you forget to register or load this tag? </blockquote> | The app that contains the custom tags must be in INSTALLED_APPS So Are you sure that your directory is in INSTALLED_APPS ? In Documentation <blockquote> The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation </blockquote> <a href="https://docs djangoproject com/en/1 9/howto/custom-template-tags/" rel="nofollow">https://docs djangoproject com/en/1 9/howto/custom-template-tags/</a> |
By what date did Sony correct the issue with the system disk? | null |
What Emperor initially created the quota system? | Emperor Wu |
"TypeError: draw() takes exactly 1 non-keyword argument (3 given)" I wrote this code to open a window with Pyglet in Python ````import pyglet from pyglet import window class Window(pyglet window Window): def __init__(self): super(Window self) __init__() myLabel = pyglet text Label("Prototype") windowText = myLabel draw(Window "Hello World" font_name = "Times New Roman" font_size = 36 color = (193 205 193 255)) def on_draw(self): self clear() self label draw() if __name__ == '__main__': window = Window() pyglet app run() ```` however every time I run it I get this error: ````TypeError: draw() takes exactly 1 non-keyword argument (3 given) ```` AFAIK the "(3 given)" means the problem is with the font_size or color arguments but I am not sure Could someone explain what is wrong and help me make this work? | The three non-keyword arguments you have given are the object instance `Window` and `"Hello World"` It only expects the object instance Check the docs again for which arguments the `draw()` method takes Consider printing the `repr()` of `myLabel` so that you know which type it is |
How defined are the roles of majority leader? | null |
The transition from child-to-adulthood can be broadly defined as what? | adolescence |