INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
def parse_date(value): """Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value. """ if not value: return Non...
Attempts to convert `value` into an ``xs:date`` string. If `value` is ``None``, ``None`` will be returned. Args: value: A date value. This can be a string, datetime.date, or datetime.datetime object. Returns: An ``xs:date`` formatted timestamp string.
def serialize_date(value): """Attempts to convert `value` into an ``xs:date`` string. If `value` is ``None``, ``None`` will be returned. Args: value: A date value. This can be a string, datetime.date, or datetime.datetime object. Returns: An ``xs:date`` formatted timestamp ...
Finds all valid one and two letter corrections for word_string, returning the word with the highest relative probability as type str.
def correct_word(word_string): ''' Finds all valid one and two letter corrections for word_string, returning the word with the highest relative probability as type str. ''' if word_string is None: return "" elif isinstance(word_string, str): return max(find_candidates(word_string...
Finds all potential words word_string could have intended to mean. If a word is not incorrectly spelled, it will return this word first, else if will look for one letter edits that are correct. If there are no valid one letter edits, it will perform a two letter edit search. If valid corrections are found,...
def find_candidates(word_string): ''' Finds all potential words word_string could have intended to mean. If a word is not incorrectly spelled, it will return this word first, else if will look for one letter edits that are correct. If there are no valid one letter edits, it will perform a two letter edi...
Finds all possible one letter edits of word_string: - Splitting word_string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical letter - Inserting all possible alphabetical char...
def find_one_letter_edits(word_string): ''' Finds all possible one letter edits of word_string: - Splitting word_string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical l...
Finds all possible two letter edits of word_string: - Splitting word_string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical letter - Inserting all possible alphabetical char...
def find_two_letter_edits(word_string): ''' Finds all possible two letter edits of word_string: - Splitting word_string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical l...
Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance.
def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())): ''' Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance. ''' if word_string is None: return 0 elif isinstance(word_string, str)...
Checks for each edited word in word_list if that word is a valid english word.abs Returns all validated words as a set instance.
def validate_words(word_list): ''' Checks for each edited word in word_list if that word is a valid english word.abs Returns all validated words as a set instance. ''' if word_list is None: return {} elif isinstance(word_list, list): if not word_list: return {} ...
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun
def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise Value...
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
def search_exoplanet(exoplanet): ''' It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isins...
It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10
def search_local_galaxies(galaxy): ''' It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10 ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups/" if no...
It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59
def search_star_cluster(cluster): ''' It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" ...
Syntactic sugar around to make it easier to get fine-grained access to the parts of a file without composing a PhyloSchema object. Possible invocations include: w.get('pg_10') w.get('pg_10', 'trees') w.get('pg_10', 'trees', format='nexus') w.get('pg_10', t...
def get(self, amendment_id, content=None, **kwargs): """Syntactic sugar around to make it easier to get fine-grained access to the parts of a file without composing a PhyloSchema object. Possible invocations include: w.get('pg_10') w.get('pg_10', 'trees') w.ge...
Return the python representation
def as_python(self, name: str) -> str: """ Return the python representation """ if self._ruleTokens: pattern = "jsg.JSGPattern(r'{}'.format({}))".\ format(self._rulePattern, ', '.join(['{v}={v}.pattern'.format(v=v) for v in sorted(self._ruleTokens)])) else: ...
lexerAltList: lexerAlt (LBAR lexerAlt)*
def visitLexerAltList(self, ctx: jsgParser.LexerAltListContext): """ lexerAltList: lexerAlt (LBAR lexerAlt)* """ altlist = ctx.lexerAlt() self.visit(altlist[0]) for alt in altlist[1:]: self._rulePattern += '|' self.visit(alt)
lexerElement: lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix?
def visitLexerElement(self, ctx: jsgParser.LexerElementContext): """ lexerElement: lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix? """ self.visitChildren(ctx) if ctx.ebnfSuffix(): self._rulePattern += ctx.ebnfSuffix().getText()
lexerBlock: OPREN lexeraltList CPREN
def visitLexerBlock(self, ctx: jsgParser.LexerBlockContext): """ lexerBlock: OPREN lexeraltList CPREN """ self._rulePattern += '(' self.visitChildren(ctx) self._rulePattern += ')'
lexerAtom : lexerTerminal | LEXER_CHAR_SET | ANY
def visitLexerAtom(self, ctx: jsgParser.LexerAtomContext): """ lexerAtom : lexerTerminal | LEXER_CHAR_SET | ANY """ if ctx.LEXER_CHAR_SET() or ctx.ANY(): self._rulePattern += str(ctx.getText()) else: self.visitChildren(ctx)
terminal: LEXER_ID | STRING
def visitLexerTerminal(self, ctx: jsgParser.LexerTerminalContext): """ terminal: LEXER_ID | STRING """ if ctx.LEXER_ID(): # Substitute LEXER_ID with its string equivalent - "{LEXER_ID}".format(LEXER_ID=LEXER_ID.pattern) idtoken = as_token(ctx) self._rulePattern += '(...
Convert any string to a "slug", a simplified form suitable for filename and URL part. EXAMPLE: "Trees about bees" => 'trees-about-bees' EXAMPLE: "My favorites!" => 'my-favorites' N.B. that its behavior should match this client-side slugify function, so we can accurately "preview" slugs in the browser:...
def slugify(s): """Convert any string to a "slug", a simplified form suitable for filename and URL part. EXAMPLE: "Trees about bees" => 'trees-about-bees' EXAMPLE: "My favorites!" => 'my-favorites' N.B. that its behavior should match this client-side slugify function, so we can accurately "preview...
Generate next slug for a series. Some docstore types will use slugs (see above) as document ids. To support unique ids, we'll serialize them as follows: TestUserA/my-test TestUserA/my-test-2 TestUserA/my-test-3 ...
def increment_slug(s): """Generate next slug for a series. Some docstore types will use slugs (see above) as document ids. To support unique ids, we'll serialize them as follows: TestUserA/my-test TestUserA/my-test-2 TestUserA/my-test-3 ... """ slug_parts =...
converts ott_id to ottId.
def underscored2camel_case(v): """converts ott_id to ottId.""" vlist = v.split('_') c = [] for n, el in enumerate(vlist): if el: if n == 0: c.append(el) else: c.extend([el[0].upper(), el[1:]]) return ''.join(c)
Return true if the pair name should be ignored :param parm: string part of pair string:value :return: True if it should be accepted
def unvalidated_parm(self, parm: str) -> bool: """Return true if the pair name should be ignored :param parm: string part of pair string:value :return: True if it should be accepted """ return parm.startswith("_") or parm == self.TYPE or parm in self.IGNORE or \ (sel...
Takes a request and dispatches its data to a jsonrpc method. :param request: a werkzeug request with json data :type request: werkzeug.wrappers.Request :return: json output of the corresponding method :rtype: str .. versionadded:: 0.1.0
def dispatch(self, request): """Takes a request and dispatches its data to a jsonrpc method. :param request: a werkzeug request with json data :type request: werkzeug.wrappers.Request :return: json output of the corresponding method :rtype: str .. versionadded:: 0.1.0 ...
Registers a method with a given name and signature. :param name: The name used to register the method :type name: str :param method: The method to register :type method: function :param method_signature: The method signature for the given function :type method_signature:...
def register(self, name, method, method_signature=None): """Registers a method with a given name and signature. :param name: The name used to register the method :type name: str :param method: The method to register :type method: function :param method_signature: The met...
Syntactic sugar for registering a method Example: >>> registry = Registry() >>> @registry.method(returns=int, x=int, y=int) ... def add(x, y): ... return x + y :param returns: The method's return type :type returns: type :param param...
def method(self, returns, **parameter_types): """Syntactic sugar for registering a method Example: >>> registry = Registry() >>> @registry.method(returns=int, x=int, y=int) ... def add(x, y): ... return x + y :param returns: The method's ret...
Creates a dictionary mapping parameters names to their values in the method call. :param parameter_names: The method's parameter names :type parameter_names: list[string] :param args: *args passed into the method :type args: list[object] :param kwargs: **kwargs passed into the m...
def _collect_parameters(parameter_names, args, kwargs, defaults): """Creates a dictionary mapping parameters names to their values in the method call. :param parameter_names: The method's parameter names :type parameter_names: list[string] :param args: *args passed into the method ...
Parses the request as a json message. :param request: a werkzeug request with json data :type request: werkzeug.wrappers.Request :return: The parsed json object :rtype: dict[str, object]
def _get_request_messages(self, request): """Parses the request as a json message. :param request: a werkzeug request with json data :type request: werkzeug.wrappers.Request :return: The parsed json object :rtype: dict[str, object] """ data = request.get_data(as_...
Checks that the request json is well-formed. :param msg: The request's json data :type msg: dict[str, object]
def _check_request(self, msg): """Checks that the request json is well-formed. :param msg: The request's json data :type msg: dict[str, object] """ if "jsonrpc" not in msg: raise InvalidRequestError("'\"jsonrpc\": \"2.0\"' must be included.") if msg["jsonrpc"...
This returns a collection of JSON objects for every weather report available for October 2012: { "count": 29, "next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2", "previous": null, "results": [ ... ] }
def maas_archive(begin, end): ''' This returns a collection of JSON objects for every weather report available for October 2012: { "count": 29, "next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2", "previous": null, ...
Render a template from the template folder with the given context. Code based on `<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_ :param input: the string template, or name of the template to be rendered, or an iterable with template names the firs...
def render_template_to_string(input, _from_string=False, **context): """Render a template from the template folder with the given context. Code based on `<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_ :param input: the string template, or name of the template to be ...
Validate if communities logo is in limit size and save it.
def save_and_validate_logo(logo_stream, logo_filename, community_id): """Validate if communities logo is in limit size and save it.""" cfg = current_app.config logos_bucket_id = cfg['COMMUNITIES_BUCKET_UUID'] logo_max_size = cfg['COMMUNITIES_LOGO_MAX_SIZE'] logos_bucket = Bucket.query.get(logos_buc...
Initialize the communities file bucket. :raises: `invenio_files_rest.errors.FilesException`
def initialize_communities_bucket(): """Initialize the communities file bucket. :raises: `invenio_files_rest.errors.FilesException` """ bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID']) if Bucket.query.get(bucket_id): raise FilesException("Bucket with UUID {} already exists."...
Format the email message element for inclusion request notification. Formats the message according to the provided template file, using some default fields from 'increq' object as default context. Arbitrary context can be provided as keywords ('ctx'), and those will not be overwritten by the fields fro...
def format_request_email_templ(increq, template, **ctx): """Format the email message element for inclusion request notification. Formats the message according to the provided template file, using some default fields from 'increq' object as default context. Arbitrary context can be provided as keywords ...
Format the email message title for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to formatter. :type ctx: dict. :returns: Email m...
def format_request_email_title(increq, **ctx): """Format the email message title for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to...
Format the email message body for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to formatter. :type ctx: dict. :returns: Email me...
def format_request_email_body(increq, **ctx): """Format the email message body for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to f...
Signal for sending emails after community inclusion request.
def send_community_request_email(increq): """Signal for sending emails after community inclusion request.""" from flask_mail import Message from invenio_mail.tasks import send_email msg_body = format_request_email_body(increq) msg_title = format_request_email_title(increq) sender = current_app...
Convenience function for writing documentation. For a class method `a` that is essentially a wrapper for an outside function `b`, rope in the docstring from `b` and append to that of `a`. Also modify the docstring of `a` to get the indentation right. Will probably deprecate this soon. **Pa...
def modifydocs(a, b, desc=''): """ Convenience function for writing documentation. For a class method `a` that is essentially a wrapper for an outside function `b`, rope in the docstring from `b` and append to that of `a`. Also modify the docstring of `a` to get the indentation right. W...
"Horizontal stacking" of tabarrays, e.g. adding columns. Wrapper for :func:`tabular.spreadsheet.colstack` that deals with the coloring and returns the result as a tabarray. Method calls:: data = tabular.spreadsheet.colstack(ListOfTabArrays, mode=mode)
def tab_colstack(ListOfTabArrays, mode='abort'): """ "Horizontal stacking" of tabarrays, e.g. adding columns. Wrapper for :func:`tabular.spreadsheet.colstack` that deals with the coloring and returns the result as a tabarray. Method calls:: data = tabular.spreadsheet.colstack(ListOfTabAr...
"Vertical stacking" of tabarrays, e.g. adding rows. Wrapper for :func:`tabular.spreadsheet.rowstack` that deals with the coloring and returns the result as a tabarray. Method calls:: data = tabular.spreadsheet.rowstack(ListOfTabArrays, mode=mode)
def tab_rowstack(ListOfTabArrays, mode='nulls'): """ "Vertical stacking" of tabarrays, e.g. adding rows. Wrapper for :func:`tabular.spreadsheet.rowstack` that deals with the coloring and returns the result as a tabarray. Method calls:: data = tabular.spreadsheet.rowstack(ListOfTabArrays,...
Database-join for tabular arrays. Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring and returns the result as a tabarray. Method calls:: data = tabular.spreadsheet.join
def tab_join(ToMerge, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): ''' Database-join for tabular arrays. Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring and returns the result as a tabarray. Method calls:: data ...
Creates a copy of this tabarray in the form of a numpy ndarray. Useful if you want to do math on array elements, e.g. if you have a subset of the columns that are all numerical, you can construct a numerical matrix and do matrix operations.
def extract(self): """ Creates a copy of this tabarray in the form of a numpy ndarray. Useful if you want to do math on array elements, e.g. if you have a subset of the columns that are all numerical, you can construct a numerical matrix and do matrix operations. """ ...
Append one or more records to the end of the array. Method wraps:: tabular.spreadsheet.addrecords(self, new)
def addrecords(self, new): """ Append one or more records to the end of the array. Method wraps:: tabular.spreadsheet.addrecords(self, new) """ data = spreadsheet.addrecords(self,new) data = data.view(tabarray) data.coloring = self.coloring ...
Add one or more new columns. Method wraps:: tabular.spreadsheet.addcols(self, cols, names)
def addcols(self, cols, names=None): """ Add one or more new columns. Method wraps:: tabular.spreadsheet.addcols(self, cols, names) """ data = spreadsheet.addcols(self, cols, names) data = data.view(tabarray) data.coloring = self.coloring ...
Delete columns and/or colors. Method wraps:: tabular.spreadsheet.deletecols(self, cols)
def deletecols(self, cols): """ Delete columns and/or colors. Method wraps:: tabular.spreadsheet.deletecols(self, cols) """ if isinstance(cols, str): cols = cols.split(',') deletenames = utils.uniqify(utils.listunion([[c] if c in self....
Rename column or color in-place. Method wraps:: tabular.spreadsheet.renamecol(self, old, new)
def renamecol(self, old, new): """ Rename column or color in-place. Method wraps:: tabular.spreadsheet.renamecol(self, old, new) """ spreadsheet.renamecol(self,old,new) for x in self.coloring.keys(): if old in self.coloring[x]: ...
Save the tabarray to a single flat separated variable (CSV) text file. Method wraps:: tabular.io.saveSV. See docstring of tabular.io.saveSV, or Tabular reference documentation, for more information.
def saveSV(self, fname, comments=None, metadata=None, printmetadict=None, dialect = None, delimiter=None, doublequote=True, lineterminator='\n', escapechar = None, quoting=csv.QUOTE_MINIMAL, quotechar='"', skipinitialspace=False, ...
Save the tabarray to a numpy binary archive (``.npz``). Save the tabarray to a ``.npz`` zipped file containing ``.npy`` binary files for data, plus optionally coloring and/or rowdata or simply to a ``.npy`` binary file containing the data but no coloring or rowdata. Method wr...
def savebinary(self, fname, savecoloring=True): """ Save the tabarray to a numpy binary archive (``.npz``). Save the tabarray to a ``.npz`` zipped file containing ``.npy`` binary files for data, plus optionally coloring and/or rowdata or simply to a ``.npy`` binary fil...
Horizontal stacking for tabarrays. Stack tabarray(s) in `new` to the right of `self`. **See also** :func:`tabular.tabarray.tab_colstack`, :func:`tabular.spreadsheet.colstack`
def colstack(self, new, mode='abort'): """ Horizontal stacking for tabarrays. Stack tabarray(s) in `new` to the right of `self`. **See also** :func:`tabular.tabarray.tab_colstack`, :func:`tabular.spreadsheet.colstack` """ if isinstance...
Vertical stacking for tabarrays. Stack tabarray(s) in `new` below `self`. **See also** :func:`tabular.tabarray.tab_rowstack`, :func:`tabular.spreadsheet.rowstack`
def rowstack(self, new, mode='nulls'): """ Vertical stacking for tabarrays. Stack tabarray(s) in `new` below `self`. **See also** :func:`tabular.tabarray.tab_rowstack`, :func:`tabular.spreadsheet.rowstack` """ if isinstance(new,list): ...
Aggregate a tabarray on columns for given functions. Method wraps:: tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFunc, returnsort)
def aggregate(self, On=None, AggFuncDict=None, AggFunc=None, AggList = None, returnsort=False,KeepOthers=True, keyfuncdict=None): """ Aggregate a tabarray on columns for given functions. Method wraps:: tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFu...
Aggregate a tabarray and include original data in the result. See the :func:`aggregate` method. Method wraps:: tabular.summarize.aggregate_in(self, On, AggFuncDict, AggFunc, interspersed)
def aggregate_in(self, On=None, AggFuncDict=None, AggFunc=None, AggList=None, interspersed=True): """ Aggregate a tabarray and include original data in the result. See the :func:`aggregate` method. Method wraps:: tabular.summarize.aggregate_in(self, On...
Pivot with `a` as the row axis and `b` values as the column axis. Method wraps:: tabular.spreadsheet.pivot(X, a, b, Keep)
def pivot(self, a, b, Keep=None, NullVals=None, order = None, prefix='_'): """ Pivot with `a` as the row axis and `b` values as the column axis. Method wraps:: tabular.spreadsheet.pivot(X, a, b, Keep) """ [data,coloring] = spreadsheet.pivot(X=self, a=a, b=b, Ke...
Wrapper for spreadsheet.join, but handles coloring attributes. The `selfname` argument allows naming of `self` to be used if `ToMerge` is a dictionary. **See also:** :func:`tabular.spreadsheet.join`, :func:`tab_join`
def join(self, ToMerge, keycols=None, nullvals=None, renamer=None, returnrenaming=False, selfname=None, Names=None): """ Wrapper for spreadsheet.join, but handles coloring attributes. The `selfname` argument allows naming of `self` to be used if `ToMerge` is a dictionary....
Returns the indices that would sort an array. .. note:: This method wraps `numpy.argsort`. This documentation is modified from that of `numpy.argsort`. Perform an indirect sort along the given axis using the algorithm specified by the `kind` keyword. It ret...
def argsort(self, axis=-1, kind='quicksort', order=None): """ Returns the indices that would sort an array. .. note:: This method wraps `numpy.argsort`. This documentation is modified from that of `numpy.argsort`. Perform an indirect sort along the gi...
Takes an `obj` that is a collection object. `retain_deprecated` if False, then `obj` may be modified to replace deprecated constructs with new syntax. If it is True, the `obj` will not be modified. Returns the pair: errors, adaptor `errors` is a simple list of error messages `ada...
def validate_collection(obj, retain_deprecated=True, **kwargs): """Takes an `obj` that is a collection object. `retain_deprecated` if False, then `obj` may be modified to replace deprecated constructs with new syntax. If it is True, the `obj` will not be modified. Returns the pair: e...
Determine whether txt matches pattern :param txt: text to check :return: True if match
def matches(self, txt: str) -> bool: """Determine whether txt matches pattern :param txt: text to check :return: True if match """ # rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape') if r'\\u' in self.pattern_re.pattern: txt = txt.encode('ut...
Return web-safe hex triplets.
def Point2HexColor(a, lfrac, tfrac): """ Return web-safe hex triplets. """ [H,S,V] = [math.floor(360 * a), lfrac, tfrac] RGB = hsvToRGB(H, S, V) H = [hex(int(math.floor(255 * x))) for x in RGB] HEX = [a[a.find('x') + 1:] for a in H] HEX = ['0' + h if len(h) == 1 else h for h in HEX]...
Convert HSV (hue, saturation, value) color space to RGB (red, green blue) color space. **Parameters** **h** : float Hue, a number in [0, 360]. **s** : float Saturation, a number in [0, 1]. **v** : float Va...
def hsvToRGB(h, s, v): """ Convert HSV (hue, saturation, value) color space to RGB (red, green blue) color space. **Parameters** **h** : float Hue, a number in [0, 360]. **s** : float Saturation, a number in [0, 1]. **v...
Returns a logger with name set as given. See _read_logging_config for a description of the env var/config file cascade that controls configuration of the logger.
def get_logger(name="peyotl"): """Returns a logger with name set as given. See _read_logging_config for a description of the env var/config file cascade that controls configuration of the logger. """ logger = logging.getLogger(name) if len(logger.handlers) == 0: log_init_warnings = [] ...
Only to be used in this file and peyotl.utility.get_config
def warn_from_util_logger(msg): """Only to be used in this file and peyotl.utility.get_config""" global _LOG # This check is necessary to avoid infinite recursion when called from get_config, because # the _read_logging_conf can require reading a conf file. if _LOG is None and _LOGGING_CONF is Non...
Returns a dictionary that is empty or has a "logging" key that refers to the (up to 3) key-value pairs that pertain to logging and are read from the env. This is mainly a convenience function for ConfigWrapper so that it can accurately report the source of the logging settings without
def _logging_env_conf_overrides(log_init_warnings=None): """Returns a dictionary that is empty or has a "logging" key that refers to the (up to 3) key-value pairs that pertain to logging and are read from the env. This is mainly a convenience function for ConfigWrapper so that it can accurately repo...
Returns a dictionary (should be treated as immutable) of settings needed to configure a logger. If PEYOTL_LOGGING_LEVEL, PEYOTL_LOGGING_FORMAT, and PEYOTL_LOG_FILE_PATH are all in the env, then no config file will be read. If PEYOTL_LOG_FILE_PATH is set to an empty string, then stderr will be used. ...
def _read_logging_config(log_init_warnings=None): """Returns a dictionary (should be treated as immutable) of settings needed to configure a logger. If PEYOTL_LOGGING_LEVEL, PEYOTL_LOGGING_FORMAT, and PEYOTL_LOG_FILE_PATH are all in the env, then no config file will be read. If PEYOTL_LOG_FILE_PATH ...
Given a selector (defaults to all), return a list of lights. Without a selector provided, return list of all lights.
def list_lights(self, selector='all'): """Given a selector (defaults to all), return a list of lights. Without a selector provided, return list of all lights. """ return self.client.perform_request( method='get', endpoint='lights/{}', endpoint_args=[selector], pa...
Given a selector (defaults to all), set the state of a light. Selector can be based on id, scene_id, group_id, label, etc. Returns list of lightbulb statuses if successful. See http://api.developer.lifx.com/v1/docs/selectors selector: required String The selector to limit wh...
def set_state(self, selector='all', power=None, color=None, brightness=None, duration=None): """Given a selector (defaults to all), set the state of a light. Selector can be based on id, scene_id, group_id, label, etc. Returns list of lightbulb statuses if successful. See http://...
Given a state delta, apply the modifications to lights' state over a given period of time. selector: required String The selector to limit which lights are controlled. power: String The power state you want to set on the selector. on or off duration: Double ...
def state_delta(self, selector='all', power=None, duration=1.0, infrared=None, hue=None, saturation=None, brightness=None, kelvin=None): """Given a state delta, apply the modifications to lights' state over a given period of time. selector: required String The select...
Given a selector and transition duration, toggle lights (on/off)
def toggle_power(self, selector='all', duration=1.0): """Given a selector and transition duration, toggle lights (on/off)""" argument_tuples = [ ("duration", duration) ] return self.client.perform_request( method='post', endpoint='lights/{}/toggle', ...
Perform breathe effect on lights. selector: String The selector to limit which lights will run the effect. default: all color: required String Color attributes to use during effect. See set_state for more. from_color: String The color to start t...
def breathe_lights(self, color, selector='all', from_color=None, period=1.0, cycles=1.0, persist=False, power_on=True, peak=0.5): """Perform breathe effect on lights. selector: String The selector to limit which lights will run the effect. default: all c...
Cycle through list of effects. Provide array states as a list of dictionaries with set_state arguments. See http://api.developer.lifx.com/docs/cycle selector: String The selector to limit which lights will run the effect. default: all states: required List of D...
def cycle_lights(self, states, defaults, direction='forward', selector='all'): """Cycle through list of effects. Provide array states as a list of dictionaries with set_state arguments. See http://api.developer.lifx.com/docs/cycle selector: String The selector to li...
Activate a scene. See http://api.developer.lifx.com/docs/activate-scene scene_uuid: required String The UUID for the scene you wish to activate duration: Double The time in seconds to spend performing the scene transition. default: 1.0
def activate_scene(self, scene_uuid, duration=1.0): """Activate a scene. See http://api.developer.lifx.com/docs/activate-scene scene_uuid: required String The UUID for the scene you wish to activate duration: Double The time in seconds to spend performing the s...
valueTypeExpr: JSON_STRING | JSON_NUMBER | JSON_INT | JSON_BOOL | JSON_NULL | JSON_ARRAY | JSON_OBJECT
def visitBuiltinValueType(self, ctx: jsgParser.BuiltinValueTypeContext): """ valueTypeExpr: JSON_STRING | JSON_NUMBER | JSON_INT | JSON_BOOL | JSON_NULL | JSON_ARRAY | JSON_OBJECT """ self._value_type_text = ctx.getText() self._typeinfo = self.parserTypeToImplClass[self._value_type_text]
Returns the number of trees summed across all tree groups.
def count_num_trees(nexson, nexson_version=None): """Returns the number of trees summed across all tree groups. """ if nexson_version is None: nexson_version = detect_nexson_version(nexson) nex = get_nexml_el(nexson) num_trees_by_group = [] if _is_by_id_hbf(nexson_version): f...
Factory function for a _TreeCollectionStore object. A wrapper around the _TreeCollectionStore class instantiation for the most common use case: a singleton _TreeCollectionStore. If you need distinct _TreeCollectionStore objects, you'll need to call that class directly.
def TreeCollectionStore(repos_dict=None, repos_par=None, with_caching=True, assumed_doc_version=None, git_ssh=None, pkey=None, git_action_class=TreeCollectionsGitAction, ...
Validate and save this JSON. Ensure (and return) a unique collection id
def add_new_collection(self, owner_id, json_repr, auth_info, collection_id=None, commit_msg=''): """Validate and save this JSON. Ensure (and return) a unique collection id""" ...
Validate and save this JSON. Ensure (and return) a unique collection id
def update_existing_collection(self, owner_id, collection_id=None, json_repr=None, auth_info=None, parent_sha=None, ...
Parse the JSON, find its name, return a slug of its name
def _slugify_internal_collection_name(self, json_repr): """Parse the JSON, find its name, return a slug of its name""" collection = self._coerce_json_to_collection(json_repr) if collection is None: return None internal_name = collection['name'] return slugify(internal...
Call the primary validator for a quick test
def _is_valid_collection_json(self, json_repr): """Call the primary validator for a quick test""" collection = self._coerce_json_to_collection(json_repr) if collection is None: # invalid JSON, definitely broken return False aa = validate_collection(collection) ...
Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None.
def _coerce_json_to_collection(self, json_repr): """Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None.""" if isinstance(json_repr, dict): collection = js...
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api....
def address(address=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end ye...
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/coords QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key s...
def coordinate(lon=None, lat=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/coords QUERY PARAMETERS Parameter Type Default Description lat float n/a Latitude lon float n/a Longitude begin int 1880 beginning year for date range, inclu...
Search LAN for available Roku devices. Returns a Roku object.
def discover_roku(): """ Search LAN for available Roku devices. Returns a Roku object. """ print("Searching for Roku devices within LAN ...") rokus = Roku.discover() if not rokus: print("Unable to discover Roku devices. " + "Try again, or manually specify the IP address with " + ...
Uses a peyotl wrapper around an Open Tree web service to get a list of OTT IDs matching the `name_list`. The tnrs_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used. All other arguments correspond to the arguments of the web-service call. A ValueError will be raised if...
def ot_tnrs_match_names(name_list, context_name=None, do_approximate_matching=True, include_dubious=False, include_deprecated=True, tnrs_wrapper=None): """Uses a peyotl wrapper around an Open Tree...
Writes out data from `taxon` to the `output` stream to demonstrate the attributes of a taxon object. (currently some lines are commented out until the web-services call returns more info. See: https://github.com/OpenTreeOfLife/taxomachine/issues/85 ). If `include_anc` is True, then ancestor info...
def write_taxon_info(taxon, include_anc, output): """Writes out data from `taxon` to the `output` stream to demonstrate the attributes of a taxon object. (currently some lines are commented out until the web-services call returns more info. See: https://github.com/OpenTreeOfLife/taxomachine/issues/8...
Demonstrates how to read the response from a match_names query when peyotl's wrap_response option is used. If the context_name is not recognized, the attempt to match_names will generate a ValueError exception. Here this is caught, and we call the tnrs/contexts web service to get the list of valid context_...
def match_and_print(name_list, context_name, do_approximate_matching, include_dubious, include_deprecated, include_subtree, output): """Demonstrates how to read the response from a match_names query when peyotl's wrap_response option is used. If the context_name is not recognized, the a...
This function sets up a command-line option parser and then calls match_and_print to do all of the real work.
def main(argv): """This function sets up a command-line option parser and then calls match_and_print to do all of the real work. """ import argparse description = 'Uses Open Tree of Life web services to try to find a taxon ID for each name supplied. ' \ 'Using a --context-name=NAME...
Make `value` suitable for a binding object. If `value` is an Entity, call to_obj() on it. Otherwise, pass it off to the TypedField for an appropriate value.
def _objectify(field, value, ns_info): """Make `value` suitable for a binding object. If `value` is an Entity, call to_obj() on it. Otherwise, pass it off to the TypedField for an appropriate value. """ if (getattr(field.type_, "_treat_none_as_empty_list", False) and value is None): ...
Make `value` suitable for a dictionary. * If `value` is an Entity, call to_dict() on it. * If value is a timestamp, turn it into a string value. * If none of the above are satisfied, return the input value
def _dictify(field, value): """Make `value` suitable for a dictionary. * If `value` is an Entity, call to_dict() on it. * If value is a timestamp, turn it into a string value. * If none of the above are satisfied, return the input value """ if value is None: return None elif field.t...
Create an instance of the class associated with the `key` (xsi:type) and initialize it with the *args and **kwargs. Args: key: A class lookup key (see entity_class()). Returns: An instance of the class associated with the `key`.
def instance(cls, key, *args, **kwargs): """Create an instance of the class associated with the `key` (xsi:type) and initialize it with the *args and **kwargs. Args: key: A class lookup key (see entity_class()). Returns: An instance of the class associated with ...
Parse the dictionary and return an Entity instance. This will attempt to extract type information from the input dictionary and pass it to entity_class to resolve the correct class for the type. Args: cls_dict: A dictionary representation of an Entity object. fa...
def from_dict(cls, cls_dict, fallback_xsi_type=None): """Parse the dictionary and return an Entity instance. This will attempt to extract type information from the input dictionary and pass it to entity_class to resolve the correct class for the type. Args: cls_dict...
Parse the generateDS object and return an Entity instance. This will attempt to extract type information from the input object and pass it to entity_class to resolve the correct class for the type. Args: cls_obj: A generateDS object. Returns: An Entity ...
def from_obj(cls, cls_obj): """Parse the generateDS object and return an Entity instance. This will attempt to extract type information from the input object and pass it to entity_class to resolve the correct class for the type. Args: cls_obj: A generateDS object. ...
Return a tuple of this entity's TypedFields.
def typed_fields(cls): """Return a tuple of this entity's TypedFields.""" # Checking cls._typed_fields could return a superclass _typed_fields # value. So we check our class __dict__ which does not include # inherited attributes. klassdict = cls.__dict__ try: ...
Return a list of (TypedField attribute name, TypedField object) tuples for this Entity.
def typed_fields_with_attrnames(cls): """Return a list of (TypedField attribute name, TypedField object) tuples for this Entity. """ # Checking cls._typed_fields could return a superclass _typed_fields # value. So we check our class __dict__ which does not include # inher...
Convert to a GenerateDS binding object. Subclasses can override this function. Returns: An instance of this Entity's ``_binding_class`` with properties set from this Entity.
def to_obj(self, ns_info=None): """Convert to a GenerateDS binding object. Subclasses can override this function. Returns: An instance of this Entity's ``_binding_class`` with properties set from this Entity. """ if ns_info: ns_info.collect(s...
Convert to a ``dict`` Subclasses can override this function. Returns: Python dict with keys set from this Entity.
def to_dict(self): """Convert to a ``dict`` Subclasses can override this function. Returns: Python dict with keys set from this Entity. """ entity_dict = {} for field, val in six.iteritems(self._fields): if field.multiple: if val...
Serializes a :class:`Entity` instance to an XML string. The default character encoding is ``utf-8`` and can be set via the `encoding` parameter. If `encoding` is ``None``, a unicode string is returned. That is, a :class:`unicode` in Python 2 and a :class:`str` in Python 3. Not...
def to_xml(self, include_namespaces=True, namespace_dict=None, pretty=True, encoding="utf-8"): """Serializes a :class:`Entity` instance to an XML string. The default character encoding is ``utf-8`` and can be set via the `encoding` parameter. If `encoding` is ``None``, a...
Parse a JSON string and build an entity.
def from_json(cls, json_doc): """Parse a JSON string and build an entity.""" try: d = json.load(json_doc) except AttributeError: # catch the read() error d = json.loads(json_doc) return cls.from_dict(d)
Return the "multiple" TypedField associated with this EntityList. This also lazily sets the ``_entitylist_multiplefield`` value if it hasn't been set yet. This is set to a tuple containing one item because if we set the class attribute to the TypedField, we would effectively add a Typed...
def _multiple_field(cls): """Return the "multiple" TypedField associated with this EntityList. This also lazily sets the ``_entitylist_multiplefield`` value if it hasn't been set yet. This is set to a tuple containing one item because if we set the class attribute to the TypedField, we ...
Attempts to resolve issues where our samples use 'http://example.com/' for our example namespace but python-stix uses 'http://example.com' by removing the former.
def _fix_example_namespace(self): """Attempts to resolve issues where our samples use 'http://example.com/' for our example namespace but python-stix uses 'http://example.com' by removing the former. """ example_prefix = 'example' # Example ns prefix idgen_prefix = idgen...
Returns a dictionary of namespaces to be exported with an XML document. This loops over all the namespaces that were discovered and built during the execution of ``collect()`` and ``_parse_collected_classes()`` and attempts to merge them all. Raises: .namespaces.Dup...
def _finalize_namespaces(self, ns_dict=None): """Returns a dictionary of namespaces to be exported with an XML document. This loops over all the namespaces that were discovered and built during the execution of ``collect()`` and ``_parse_collected_classes()`` and attempts to mer...
Determine whether element conforms to etype
def element_conforms(element, etype) -> bool: """ Determine whether element conforms to etype""" from pyjsg.jsglib import Empty if isinstance(element, etype): return True # This catches the Optional[] idiom if (element is None or element is Empty) and issubclass(etype, type(None)): ...