INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Helper function to facilitate upsert.
def start_upsert(ini_data): """ Helper function to facilitate upsert. Args: ini_date - the dictionary of info to run upsert Exit: 0 - good 1 - bad """ stack_driver = CloudStackUtility(ini_data) poll_stack = not ini_data.get('no_poll', False) if stack_driver.upsert(...
Read the INI file
def read_config_info(ini_file): """ Read the INI file Args: ini_file - path to the file Returns: A dictionary of stuff from the INI file Exits: 1 - if problems are encountered """ try: config = RawConfigParser() config.optionxform = lambda option: o...
List resources from the given stack
def print_stack_info(self): ''' List resources from the given stack Args: None Returns: A dictionary filled resources or None if things went sideways ''' try: rest_api_id = None deployment_found = False respon...
List events from the given stack
def print_stack_events(self): ''' List events from the given stack Args: None Returns: None ''' first_token = '7be7981bd6287dd8112305e8f3822a6f' keep_going = True next_token = first_token current_request_token = None ...
Set up or update a trac project.
def trac(): '''Set up or update a trac project. This trac installation uses python2, git, sqlite (trac-default), gunicorn, and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt. This ta...
Do a query to the System API
async def query(self, path, method='get', **params): """ Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data """ if ...
get the json data response: param responses: the json response: return the json data without root node
async def handle_json_response(responses): """ get the json data response :param responses: the json response :return the json data without 'root' node """ json_data = {} if responses.status != 200: err_msg = HttpProcessingError(code=responses.status, ...
get the value of a parm: param what: string parm: param type_attr: type of parm: param value_attr:: param kwargs:: return: value of the parm
def __get_attr(what, type_attr, value_attr, **kwargs): """ get the value of a parm :param what: string parm :param type_attr: type of parm :param value_attr: :param kwargs: :return: value of the parm """ if what in kwargs: value = int(k...
GET/ api/ entries. { _format }
async def get_entries(self, **kwargs): """ GET /api/entries.{_format} Retrieve all entries. It could be filtered by many options. :param kwargs: can contain one of the following filters archive: '0' or '1', default '0' filter by archived status. starred: '0' or...
POST/ api/ entries. { _format }
async def post_entries(self, url, title='', tags='', starred=0, archive=0, content='', language='', published_at='', authors='', public=1, original_url=''): """ POST /api/entries.{_format} Create an entry :param url: the url of the note to store :para...
GET/ api/ entries/ { entry }. { _format }
async def get_entry(self, entry): """ GET /api/entries/{entry}.{_format} Retrieve a single entry :param entry: \w+ an integer The Entry ID :return data related to the ext """ params = {'access_token': self.token} url = '/api/entries/{entry}.{ext}'.format...
PATCH/ api/ entries/ { entry }. { _format }
async def patch_entries(self, entry, **kwargs): """ PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags ...
DELETE/ api/ entries/ { entry }. { _format }
async def delete_entries(self, entry): """ DELETE /api/entries/{entry}.{_format} Delete permanently an entry :param entry: \w+ an integer The Entry ID :return result """ params = {'Authorization': 'Bearer {}'.format(self.token)} path = '/api/entries/{en...
GET/ api/ entries/ exists. { _format }
async def entries_exists(self, url, urls=''): """ GET /api/entries/exists.{_format} Check if an entry exist by url. :param url string true An url Url to check if it exists :param urls string false An array of urls (?urls[]=http...&urls[]=http...) Urls (as an array...
POST/ api/ entries/ { entry }/ tags. { _format }
async def post_entry_tags(self, entry, tags): """ POST /api/entries/{entry}/tags.{_format} Add one or more tags to an entry :param entry: \w+ an integer The Entry ID :param tags: list of tags (urlencoded) :return result """ params = {'access_token': self...
DELETE/ api/ entries/ { entry }/ tags/ { tag }. { _format }
async def delete_entry_tag(self, entry, tag): """ DELETE /api/entries/{entry}/tags/{tag}.{_format} Permanently remove one tag for an entry :param entry: \w+ an integer The Entry ID :param tag: string The Tag :return data related to the ext """ params = {...
GET/ api/ tags. { _format }
async def get_tags(self): """ GET /api/tags.{_format} Retrieve all tags :return data related to the ext """ params = {'access_token': self.token} path = '/api/tags.{ext}'.format(ext=self.format) return await self.query(path, "get", **params)
DELETE/ api/ tags/ { tag }. { _format }
async def delete_tag(self, tag): """ DELETE /api/tags/{tag}.{_format} Permanently remove one tag from every entry :param tag: string The Tag :return data related to the ext """ path = '/api/tags/{tag}.{ext}'.format(tag=tag, ext=self.format) params = {'ac...
PUT/ api/ annotations/ { annotation }. { _format }
async def put_annotations(self, annotation): """ PUT /api/annotations/{annotation}.{_format} Updates an annotation. :param annotation \w+ string The annotation ID Will returns annotation for this entry :return data related to the ext """ params = {'a...
POST/ api/ annotations/ { entry }. { _format }
async def post_annotations(self, entry, **kwargs): """ POST /api/annotations/{entry}.{_format} Creates a new annotation. :param entry \w+ integer The entry ID :return """ params = dict({'access_token': self.token, 'ranges': [], ...
GET/ api/ version. { _format }
async def version(self): """ GET /api/version.{_format} Retrieve version number :return data related to the ext """ params = {'access_token': self.token} url = '/api/version.{ext}'.format(ext=self.format) return await self.query(url, "get", **params)
POST/ oauth/ v2/ token
async def get_token(cls, host, **params): """ POST /oauth/v2/token Get a new token :param host: host of the service :param params: will contain : params = {"grant_type": "password", "client_id": "a string", "client_secret": "a string...
Set up or update a reveals. js presentation with slides written in markdown.
def revealjs(basedir=None, title=None, subtitle=None, description=None, github_user=None, github_repo=None): '''Set up or update a reveals.js presentation with slides written in markdown. Several reveal.js plugins will be set up, too. More info: Demo: https://theno.github.io/revealjs_te...
Comment out some css settings.
def tweak_css(repo_dir): '''Comment out some css settings.''' print_msg("* don't capitalize titles (no uppercase headings)") files = [ 'beige.css', 'black.css', 'blood.css', 'league.css', 'moon.css', 'night.css', 'serif.css', 'simple.css', 'sky.css', 'solarized.css', 'white.css', ...
More info: https:// help. github. com/ articles/ adding - an - existing - project - to - github - using - the - command - line/ https:// developer. github. com/ v3/ repos/ #create https:// stackoverflow. com/ a/ 10325316
def _create_github_remote_repo(basedir): '''More info: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ https://developer.github.com/v3/repos/#create https://stackoverflow.com/a/10325316 ''' github_user = _lazy('github_user') github_repo = _...
Install DeckTape.
def decktape(): '''Install DeckTape. DeckTape is a "high-quality PDF exporter for HTML5 presentation frameworks". It can be used to create PDFs from reveal.js presentations. More info: https://github.com/astefanutti/decktape https://github.com/hakimel/reveal.js/issues/1252#issuecomment-19...
Create or update the template presentation demo using task revealjs.
def revealjs_template(): '''Create or update the template presentation demo using task `revealjs`. ''' from config import basedir, github_user, github_repo run(flo('rm -f {basedir}/index.html')) run(flo('rm -f {basedir}/slides.md')) run(flo('rm -f {basedir}/README.md')) run(flo('rm -rf {bas...
Superposition of analytical solutions without a gridded domain
def spatialDomainNoGrid(self): """ Superposition of analytical solutions without a gridded domain """ self.w = np.zeros(self.xw.shape) if self.Debug: print("w = ") print(self.w.shape) for i in range(len(self.q)): # More efficient if we have created some 0-load ...
dx4 D = elasprepFD ( dx Te E = 1E11 nu = 0. 25 ) Defines the variables ( except for the subset flexural rigidity ) that are needed to run coeff_matrix_1d
def elasprepFD(self): """ dx4, D = elasprepFD(dx,Te,E=1E11,nu=0.25) Defines the variables (except for the subset flexural rigidity) that are needed to run "coeff_matrix_1d" """ self.dx4 = self.dx**4 self.D = self.E*self.Te**3/(12*(1-self.nu**2))
Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid
def BC_Rigidity(self): """ Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid """ ######################################### # FLEXURAL RIGIDITY BOUNDARY CONDITIONS # #########################################...
Builds the diagonals for the coefficient array
def build_diagonals(self): """ Builds the diagonals for the coefficient array """ ########################################################## # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY # ########################################################## # Roll to keep the pro...
Periodic boundary conditions: wraparound to the other side.
def BC_Periodic(self): """ Periodic boundary conditions: wraparound to the other side. """ if self.BC_E == 'Periodic' and self.BC_W == 'Periodic': # If both boundaries are periodic, we are good to go (and self-consistent) pass # It is just a shift in the coeff. matrix creation. el...
0Displacement0Slope boundary condition for 0 deflection. This requires that nothing be done to the edges of the solution array because the lack of the off - grid terms implies that they go to 0 Here we just turn the cells outside the array into nan to ensure that we are not accidentally including the wrong cells here (...
def BC_0Displacement0Slope(self): """ 0Displacement0Slope boundary condition for 0 deflection. This requires that nothing be done to the edges of the solution array, because the lack of the off-grid terms implies that they go to 0 Here we just turn the cells outside the array into nan, to ensu...
This boundary condition is esentially a Neumann 0 - gradient boundary condition with that 0 - gradient state extended over a longer part of the grid such that the third derivative also equals 0. This boundary condition has more of a geometric meaning than a physical meaning. It produces a state in which the boundaries ...
def BC_0Slope0Shear(self): i=0 """ This boundary condition is esentially a Neumann 0-gradient boundary condition with that 0-gradient state extended over a longer part of the grid such that the third derivative also equals 0. This boundary condition has more of a geometric meaning ...
Mirrors qs across the boundary on either the west ( left ) or east ( right ) side depending on the selections. This can for example produce a scenario in which you are observing a mountain range up to the range crest ( or more correctly the halfway point across the mountain range ).
def BC_Mirror(self): """ Mirrors qs across the boundary on either the west (left) or east (right) side, depending on the selections. This can, for example, produce a scenario in which you are observing a mountain range up to the range crest (or, more correctly, the halfway point a...
Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure ( this code ) grids are padded out to one maximum flexural wavelength but in any case the flexural wavelength is a good characteristic distance for any truncation limit
def calc_max_flexural_wavelength(self): """ Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good character...
w = fd_solve () where coeff is the sparse coefficient matrix output from function coeff_matrix and qs is the array of loads ( stresses ) Sparse solver for one - dimensional flexure of an elastic plate
def fd_solve(self): """ w = fd_solve() where coeff is the sparse coefficient matrix output from function coeff_matrix and qs is the array of loads (stresses) Sparse solver for one-dimensional flexure of an elastic plate """ if self.Debug: print("qs", self.qs.shape) ...
A model s save () never gets called on ManyToManyField changes m2m_changed - signal is sent. sender = dynamically generated model in m2m - table instance = parent related_instance = instance being m2m ed
def m2m_changed_handler(sender, *args, **kwargs): """ A model's save() never gets called on ManyToManyField changes, m2m_changed-signal is sent. sender = dynamically generated model in m2m-table instance = parent related_instance = instance being m2m'ed """ action = kwargs['action'] inst...
Return a > b. Computed by
def _gt_from_lt(self, other): """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" op_result = self.__lt__(other) if op_result is NotImplemented: return NotImplemented return not op_result and self != other
Return a < = b. Computed by
def _le_from_lt(self, other): """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" op_result = self.__lt__(other) return op_result or self == other
Return a > = b. Computed by
def _ge_from_lt(self, other): """Return a >= b. Computed by @total_ordering from (not a < b).""" op_result = self.__lt__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a > = b. Computed by
def _ge_from_le(self, other): """Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return not op_result or self == other
Return a < b. Computed by
def _lt_from_le(self, other): """Return a < b. Computed by @total_ordering from (a <= b) and (a != b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return op_result and self != other
Return a > b. Computed by
def _gt_from_le(self, other): """Return a > b. Computed by @total_ordering from (not a <= b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a < b. Computed by
def _lt_from_gt(self, other): """Return a < b. Computed by @total_ordering from (not a > b) and (a != b).""" op_result = self.__gt__(other) if op_result is NotImplemented: return NotImplemented return not op_result and self != other
Return a > = b. Computed by
def _ge_from_gt(self, other): """Return a >= b. Computed by @total_ordering from (a > b) or (a == b).""" op_result = self.__gt__(other) return op_result or self == other
Return a < = b. Computed by
def _le_from_gt(self, other): """Return a <= b. Computed by @total_ordering from (not a > b).""" op_result = self.__gt__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a < = b. Computed by
def _le_from_ge(self, other): """Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return not op_result or self == other
Return a > b. Computed by
def _gt_from_ge(self, other): """Return a > b. Computed by @total_ordering from (a >= b) and (a != b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return op_result and self != other
Return a < b. Computed by
def _lt_from_ge(self, other): """Return a < b. Computed by @total_ordering from (not a >= b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Class decorator that fills in missing ordering methods
def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { # :off '__lt__': [('__gt__', _gt_from_lt), ('__le__', _le_from_lt), ('__ge__', _ge_from_lt)], '__le__': [('__ge__', _ge_from_le), ('__lt__',...
Creates Combine Archive containing the given file.
def createArchiveExample(fileName): """ Creates Combine Archive containing the given file. :param fileName: file to include in the archive :return: None """ print('*' * 80) print('Create archive') print('*' * 80) archive = CombineArchive() archive.addFile( fileName, # file...
Delete temporary files not under version control.
def clean(): '''Delete temporary files not under version control.''' basedir = dirname(__file__) print(cyan('delete temp files and dirs for packaging')) local(flo( 'rm -rf ' '{basedir}/.eggs/ ' '{basedir}/fabsetup.egg-info/ ' '{basedir}/dist ' '{basedir}/REA...
Build package and upload to pypi.
def pypi(): '''Build package and upload to pypi.''' if not query_yes_no('version updated in ' '`fabsetup/_version.py`?'): print('abort') else: print(cyan('\n## clean-up\n')) execute(clean) basedir = dirname(__file__) # latest_pythons = _deter...
Calculate the standard deviation of a list of values
def calc_deviation(values, average): """ Calculate the standard deviation of a list of values @param values: list(float) @param average: @return: """ size = len(values) if size < 2: return 0 calc_sum = 0.0 for number in range(0, size): calc_sum += math.sqrt((valu...
Append a value to the stats list
def append(self, value): """ Append a value to the stats list Parameters ---------- value : float The value to add """ self.count += 1 if self.count == 1: self.old_m = self.new_m = value self.old_s = 0 else: ...
Chain results from a list of functions. Inverted reduce.
def pipeline(steps, initial=None): """ Chain results from a list of functions. Inverted reduce. :param (function) steps: List of function callbacks :param initial: Starting value for pipeline. """ def apply(result, step): return step(result) return reduce(apply, steps, initial)
%prog [ <name > = [ value ]]
def enver(*args): """ %prog [<name>=[value]] To show all environment variables, call with no parameters: %prog To Add/Modify/Delete environment variable: %prog <name>=[value] If <name> is PATH or PATHEXT, %prog will by default append the value using a semicolon as a separator. Use -r to disable this behavio...
Add a value to a delimited variable but only when the value isn t already present.
def add(class_, name, value, sep=';'): """ Add a value to a delimited variable, but only when the value isn't already present. """ values = class_.get_values_list(name, sep) if value in values: return new_value = sep.join(values + [value]) winreg.SetValueEx( class_.key, name, 0, winreg.REG_EXPAND_...
Notify other windows that the environment has changed ( following http:// support. microsoft. com/ kb/ 104011 ).
def notify(class_): """ Notify other windows that the environment has changed (following http://support.microsoft.com/kb/104011). """ # TODO: Implement Microsoft UIPI (User Interface Privilege Isolation) to # elevate privilege to system level so the system gets this notification # for now, this must be r...
Windows Platform SDK GetTimeZoneInformation
def current(class_): "Windows Platform SDK GetTimeZoneInformation" tzi = class_() kernel32 = ctypes.windll.kernel32 getter = kernel32.GetTimeZoneInformation getter = getattr(kernel32, 'GetDynamicTimeZoneInformation', getter) code = getter(ctypes.byref(tzi)) return code, tzi
Return a map that for a given year will return the correct Info
def dynamic_info(self): "Return a map that for a given year will return the correct Info" if self.key_name: dyn_key = self.get_key().subkey('Dynamic DST') del dyn_key['FirstEntry'] del dyn_key['LastEntry'] years = map(int, dyn_key.keys()) values = map(Info, dyn_key.values()) # create a range mappi...
Takes a SYSTEMTIME object such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day.
def _locate_day(year, cutoff): """ Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day. This method is necessary because the SYSTEMTIME structure refers to a day by its ...
Return a url matcher that will stop the redirect middleware and force Django to continue with regular URL matching. For use when you have a URL pattern you want to serve and a broad catch - all pattern you want to redirect.: param pattern: regex URL patter that will definitely not redirect.: param locale_prefix: prepen...
def no_redirect(pattern, locale_prefix=True, re_flags=None): """ Return a url matcher that will stop the redirect middleware and force Django to continue with regular URL matching. For use when you have a URL pattern you want to serve, and a broad catch-all pattern you want to redirect. :param patte...
Return a url matcher suited for urlpatterns.
def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False): """ Return a url matcher suited for urlpatterns. pa...
r Find a path from start to target where target is relative to start. >>> orig_wd = os. getcwd () >>> os. chdir ( c: \\ windows ) # so we know what the working directory is >>> findpath ( d: \\ ) d: \\ >>> findpath ( d: \\ c: \\ windows ) d: \\ >>> findpath ( \\ bar d: \\ ) d: \\ bar >>> findpath ( \\ bar d: \\ foo ) #...
def findpath(target, start=os.path.curdir): r""" Find a path from start to target where target is relative to start. >>> orig_wd = os.getcwd() >>> os.chdir('c:\\windows') # so we know what the working directory is >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', 'c:\\windows') 'd:\\' >>> find...
Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero. This should trigger an insufficient buffer error and return the size needed for the buffer.
def __get_table_size(self): """ Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero. This should trigger an insufficient buffer error and return the size needed for the buffer. """ length = ctypes.wintypes.DWORD() res = self.method(None, length, False) i...
Get the table
def get_table(self): """ Get the table """ buffer_length = self.__get_table_size() returned_buffer_length = ctypes.wintypes.DWORD(buffer_length) buffer = ctypes.create_string_buffer(buffer_length) pointer_type = ctypes.POINTER(self.structure) table_p = ctypes.cast(buffer, pointer_type) res = self.meth...
Using the table structure return the array of entries based on the table size.
def entries(self): """ Using the table structure, return the array of entries based on the table size. """ table = self.get_table() entries_array = self.row_structure * table.num_entries pointer_type = ctypes.POINTER(entries_array) return ctypes.cast(table.entries, pointer_type).contents
Set up owncloud.
def owncloud(): '''Set up owncloud. Package 'owncloud' pulls package 'mysql' which asks for a password. ''' hostname = re.sub(r'^[^@]+@', '', env.host) # without username if any sitename = query_input( question='\nEnter site-name of Your Owncloud web service', ...
Set up an F - Droid App Repo.
def fdroid(): '''Set up an F-Droid App Repo. More infos: * https://f-droid.org/wiki/page/Setup_an_FDroid_App_Repo * https://f-droid.org/wiki/page/Installing_the_Server_and_Repo_Tools ''' hostname = re.sub(r'^[^@]+@', '', env.host) # without username if any sitename = query_input( ...
Install and configure dispmanx_vnc server on osmc ( raspberry pi ).
def vnc_raspi_osmc(): '''Install and configure dispmanx_vnc server on osmc (raspberry pi). More Infos: * https://github.com/patrikolausson/dispmanx_vnc * https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517 * tightvnc: * http://raspberry.tips/raspberrypi-einstei...
Install and start a Logitech Media Server ( lms ).
def lms(): '''Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze on Kodi: * http://kodi.wiki/view/Add-on:XSq...
Install smb server samba and create a share ( common read - write - access ).
def samba(): '''Install smb server samba and create a share (common read-write-access). More infos: * https://wiki.ubuntuusers.de/Samba%20Server/ ''' username = env.user install_packages(['samba']) run(flo('sudo smbpasswd -a {username}')) path = '$HOME/shared' sharename = 'shared'...
scalar: DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
def p_scalar__doublequote(self, p): """ scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END """ scalar = re.sub('\n\s+', ' ', str(p[2])) p[0] = Str(scalar.replace('\\"', '"'))
scalar: B_LITERAL_START scalar_group B_LITERAL_END
def p_scalar__literal(self, p): """ scalar : B_LITERAL_START scalar_group B_LITERAL_END """ scalar_group = ''.join(p[2]) p[0] = ScalarDispatch('%s\n' % dedent(scalar_group).replace('\n\n\n', '\n'), cast='str')
scalar: B_FOLD_START scalar_group B_FOLD_END
def p_scalar__folded(self, p): """ scalar : B_FOLD_START scalar_group B_FOLD_END """ scalar_group = ''.join(p[2]) folded_scalar = fold(dedent(scalar_group)).rstrip() p[0] = ScalarDispatch('%s\n' % folded_scalar, cast='str')
scalar: INDENT scalar_group DEDENT
def p_scalar__indented_flow(self, p): """ scalar : INDENT scalar_group DEDENT """ scalar_group = '\n'.join(p[2]) folded_scalar = fold(dedent(scalar_group)) p[0] = ScalarDispatch(folded_scalar, cast='str')
scalar: scalar INDENT SCALAR DEDENT
def p_scalar__string_indented_multi_line(self, p): """ scalar : scalar INDENT SCALAR DEDENT """ scalar = '\n'.join([p[1].value, p[3]]) p[0] = ScalarDispatch(fold(scalar), cast='str')
scalar_group: SCALAR | scalar_group SCALAR
def p_scalar_group(self, p): """ scalar_group : SCALAR | scalar_group SCALAR """ if len(p) == 2: p[0] = (str(p[1]),) if len(p) == 3: p[0] = p[1] + (str(p[2]),) if len(p) == 4: p[0] = p[1] + (str(p[3]),)
Add orphan to metadata for partials
def doctree_read_handler(app, doctree): """ Add 'orphan' to metadata for partials :type app: sphinx.application.Sphinx :type doctree: docutils.nodes.document """ # noinspection PyProtectedMember docname = sys._getframe(2).f_locals['docname'] if docname.startswith('_partial'): ap...
Skip un parseable functions.
def autodoc_skip_member_handler(app, what, name, obj, skip, options): """ Skip un parseable functions. :type app: sphinx.application.Sphinx :param str what: the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute") :para...
Wraps a try/ except and a check for self. filename around ConfigParser as it talks to the configuration file. Also checks for existence of configuration file so this won t execute ( and fail ) when no configuration file is provided ( e. g. running in coupled mode with CSDMS entirely with getters and setters )
def configGet(self, vartype, category, name, optional=False, specialReturnMessage=None): """ Wraps a try / except and a check for self.filename around ConfigParser as it talks to the configuration file. Also, checks for existence of configuration file so this won't execute (and fail) when no config...
Returns the great circle distance between two points. Useful when using the SAS_NG solution in lat/ lon coordinates Modified from http:// www. johndcook. com/ blog/ python_longitude_latitude/ It should be able to take numpy arrays.
def greatCircleDistance(self, lat1, long1, lat2, long2, radius): """ Returns the great circle distance between two points. Useful when using the SAS_NG solution in lat/lon coordinates Modified from http://www.johndcook.com/blog/python_longitude_latitude/ It should be able to take numpy arrays. "...
This is experimental code that could be used in the spatialDomainNoGrid section to build a grid of points on which to generate the solution. However the current development plan ( as of 27 Jan 2015 ) is to have the end user supply the list of points where they want a solution ( and/ or for it to be provided in a more a...
def define_points_grid(self): """ This is experimental code that could be used in the spatialDomainNoGrid section to build a grid of points on which to generate the solution. However, the current development plan (as of 27 Jan 2015) is to have the end user supply the list of points where they want ...
A special function to replate a variable name that is a string file path with the loaded file. var is a string on input output is a numpy array or a None - type object ( success vs. failure )
def loadFile(self, var, close_on_fail = True): """ A special function to replate a variable name that is a string file path with the loaded file. var is a string on input output is a numpy array or a None-type object (success vs. failure) """ out = None try: # First see if it is a ...
Plot if you want to - for troubleshooting - 1 figure
def surfplot(self, z, titletext): """ Plot if you want to - for troubleshooting - 1 figure """ if self.latlon: plt.imshow(z, extent=(0, self.dx*z.shape[0], self.dy*z.shape[1], 0)) #,interpolation='nearest' plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold') plt.ylabel('lati...
Plot multiple subplot figure for 2D array
def twoSurfplots(self): """ Plot multiple subplot figure for 2D array """ # Could more elegantly just call surfplot twice # And also could include xyzinterp as an option inside surfplot. # Noted here in case anyone wants to take that on in the future... plt.subplot(211) plt.title('Load ...
Interpolates and plots ungridded model outputs from SAS_NG solution
def xyzinterp(self, x, y, z, titletext): """ Interpolates and plots ungridded model outputs from SAS_NG solution """ # Help from http://wiki.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data if self.Verbose: print("Starting to interpolate grid for plotting -- can be a slow pr...
Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in. npy then a binary numpy grid will be exported. Otherwise an ASCII grid will be exported.
def outputDeflections(self): """ Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in ".npy", then a binary numpy grid will be exported. Otherwise, an ASCII grid will be exported. """ ...
Make sure that q0 and coefficient array are the right size compared to each other ( for finite difference if loading a pre - build coefficient array ). Otherwise exit.
def coeffArraySizeCheck(self): """ Make sure that q0 and coefficient array are the right size compared to each other (for finite difference if loading a pre-build coefficient array). Otherwise, exit. """ if prod(self.coeff_matrix.shape) != long(prod(np.array(self.qs.shape,dtype=int64)+2)**2): ...
Checks that Te and q0 array sizes are compatible For finite difference solution.
def TeArraySizeCheck(self): """ Checks that Te and q0 array sizes are compatible For finite difference solution. """ # Only if they are both defined and are arrays # Both being arrays is a possible bug in this check routine that I have # intentionally introduced if type(self.Te) == np.n...
Set - up for the finite difference solution method
def FD(self): """ Set-up for the finite difference solution method """ if self.Verbose: print("Finite Difference Solution Technique") # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 ...
Set - up for the rectangularly - gridded superposition of analytical solutions method for solving flexure
def SAS(self): """ Set-up for the rectangularly-gridded superposition of analytical solutions method for solving flexure """ if self.x is None: self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx) if self.filename: # Define the (scalar) elastic thickness self.Te...
Set - up for the ungridded superposition of analytical solutions method for solving flexure
def SAS_NG(self): """ Set-up for the ungridded superposition of analytical solutions method for solving flexure """ if self.filename: # Define the (scalar) elastic thickness self.Te = self.configGet("float", "input", "ElasticThickness") # See if it wants to be run in lat/lon ...
Merges MROs in * sequences * to a single MRO using the C3 algorithm.
def _c3_merge(sequences): # noqa """Merges MROs in *sequences* to a single MRO using the C3 algorithm. Adapted from http://www.python.org/download/releases/2.3/mro/. """ result = [] while True: sequences = [s for s in sequences if s] # purge empty sequences if not sequences: ...
Computes the method resolution order using extended C3 linearization.
def _c3_mro(cls, abcs=None): """Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into ...
Calculates the method resolution order for a given class * cls *.
def _compose_mro(cls, types): # noqa """Calculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm. """ bases = set(cls.__mro__) # Remove entries w...
Returns the best matching implementation from * registry * for type * cls *.
def _find_impl(cls, registry): """Returns the best matching implementation from *registry* for type *cls*. Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. Note: if *registry* does not contain an implementation ...
Single - dispatch generic function decorator.
def singledispatch(function): # noqa """Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementa...