INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
r pairwise_distances ( x y = None * exponent = 1 )
def pairwise_distances(x, y=None, **kwargs): r""" pairwise_distances(x, y=None, *, exponent=1) Pairwise distance between points. Return the pairwise distance between points in two sets, or in the same set if only one set is passed. Parameters ---------- x: array_like An :math:...
Respond to the request.
def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=E...
Calculates a hash for a given payload.
def calculate_payload_hash(payload, algorithm, content_type): """Calculates a hash for a given payload.""" p_hash = hashlib.new(algorithm) parts = [] parts.append('hawk.' + str(HAWK_VER) + '.payload\n') parts.append(parse_content_type(content_type) + '\n') parts.append(payload or '') parts....
Calculates a message authorization code ( MAC ).
def calculate_mac(mac_type, resource, content_hash): """Calculates a message authorization code (MAC).""" normalized = normalize_string(mac_type, resource, content_hash) log.debug(u'normalized resource for mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, resource.cr...
Calculates a message authorization code ( MAC ) for a timestamp.
def calculate_ts_mac(ts, credentials): """Calculates a message authorization code (MAC) for a timestamp.""" normalized = ('hawk.{hawk_ver}.ts\n{ts}\n' .format(hawk_ver=HAWK_VER, ts=ts)) log.debug(u'normalized resource for ts mac calc: {norm}' .format(norm=normalized)) dig...
Serializes mac_type and resource into a HAWK string.
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
Example Authorization header:
def parse_authorization_header(auth_header): """ Example Authorization header: 'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="' """ if len(auth_header) > MAX_LENGTH: raise BadHeaderValue('Header exc...
Returns a bewit identifier for the resource as a string.
def get_bewit(resource): """ Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.base.Resource` """ if resource.method != 'GET': raise ValueError('bewits can only be generated for GET requests') i...
Returns a bewittuple representing the parts of an encoded bewit string. This has the following named attributes: ( id expiration mac ext )
def parse_bewit(bewit): """ Returns a `bewittuple` representing the parts of an encoded bewit string. This has the following named attributes: (id, expiration, mac, ext) :param bewit: A base64 encoded bewit string :type bewit: str """ decoded_bewit = b64decode(bewit).decode(...
Strips the bewit parameter out of a url.
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m: rai...
Validates the given bewit.
def check_bewit(url, credential_lookup, now=None): """ Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a subclass of HawkFail otherwise. :param credential_lookup: Callable to look up the credentials dict by sender ID. The cred...
Accept a response to this request.
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds...
Returns a field - > value dict of the current state of the instance.
def current_state(self): """ Returns a ``field -> value`` dict of the current state of the instance. """ field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(fiel...
Returns true if the instance was persisted ( saved ) in its old state.
def was_persisted(self): """ Returns true if the instance was persisted (saved) in its old state. Examples:: >>> user = User() >>> user.save() >>> user.was_persisted() False >>> user = User.objects.get(pk=1) >>> u...
Remove trailing colons from the URI back to the first non - colon.
def _trim(cls, s): """ Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colons removed :rtype: string TEST: trailing colons necessary >>> s = '1:2::::' >>> CPE._trim(s)...
Create the structure to store the input type of system associated with components of CPE Name ( hardware operating system and software ).
def _create_cpe_parts(self, system, components): """ Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE...
Returns the component list of input attribute.
def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name """...
Pack the values of the five arguments into the simple edition component. If all the values are blank just return a blank.
def _pack_edition(self): """ Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns: "edition", "sw_edition", "target_sw", "target_hw" and "other" attributes packed in a only value :rtype: s...
Returns the CPE Name as URI string of version 2. 3.
def as_uri_2_3(self): """ Returns the CPE Name as URI string of version 2.3. :returns: CPE Name as URI string of version 2.3 :rtype: string :exception: TypeError - incompatible version """ uri = [] uri.append("cpe:/") ordered_comp_parts = { ...
Returns the CPE Name as Well - Formed Name string of version 2. 3.
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ from .cpe2_3_wfn import CPE2_3_WFN wfn = [] wfn.append(CPE2_3_W...
Returns the CPE Name as formatted string of version 2. 3.
def as_fs(self): """ Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incompatible version """ fs = [] fs.append("cpe:2.3:") for i in range(0, len(CPEComponent...
Returns True if c is an uppercase letter a lowercase letter a digit or an underscore otherwise False.
def _is_alphanum(cls, c): """ Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character to check :returns: True if char is alphanumeric or an underscore, False otherwise :rtype: boolean...
Return the appropriate percent - encoding of character c ( URI string ). Certain characters are returned without encoding.
def _pct_encode_uri(cls, c): """ Return the appropriate percent-encoding of character c (URI string). Certain characters are returned without encoding. :param string c: Character to check :returns: Encoded character as URI :rtype: string TEST: >>> c = '...
Return True if the value of component in attribute language is valid and otherwise False.
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() lang_rxc = re.comp...
Return True if the value of component in attribute part is valid and otherwise False.
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() part_rxc = re...
Check if the value of component is correct in the attribute comp_att.
def _parse(self, comp_att): """ Check if the value of component is correct in the attribute "comp_att". :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ errmsg = "Invali...
Returns the value of component encoded as formatted string.
def as_fs(self): """ Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass thru without escaping into the result, but most retain escaping. :returns: Formatted string associated with co...
Returns the value of component encoded as URI string.
def as_uri_2_3(self): """ Returns the value of component encoded as URI string. Scans an input string s and applies the following transformations: - Pass alphanumeric characters thru untouched - Percent-encode quoted non-alphanumerics as needed - Unquoted special charac...
Set the value of component. By default the component has a simple value.
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_str: new value of component :param string comp_att: attribute associated with value of component :returns: None :exception: V...
Convert the characters of string s to standard value ( WFN value ). Inspect each character in value of component. Copy quoted characters with their escaping into the result. Look for unquoted non alphanumerics and if not * or ? add escaping.
def _decode(self): """ Convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :...
Checks if the CPE Name is valid.
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self.cpe_str.find(" ") != -1): errmsg = "Bad-formed CPE Name: it must not have whitespaces...
Returns the values of attribute att_name of CPE Name. By default a only element in each part.
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - in...
Set the value of component.
def set_value(self, comp_str): """ Set the value of component. :param string comp_str: value of component :returns: None :exception: ValueError - incorrect value of component """ self._is_negated = False self._encoded_value = comp_str self._stand...
Convert the encoded value of component to standard value ( WFN value ).
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ s = self._encoded_value elements = s.replace('~', '').split('!') dec_elements = [] for elem in elements: result = [] idx = 0 whil...
Return True if the value of component in generic attribute is valid and otherwise False.
def _is_valid_value(self): """ Return True if the value of component in generic attribute is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value value_pattern = [] valu...
r Returns the value of compoment encoded as Well - Formed Name ( WFN ) string.
def as_wfn(self): r""" Returns the value of compoment encoded as Well-Formed Name (WFN) string. :returns: WFN string :rtype: string TEST: >>> val = 'xp!vista' >>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION) >>> comp1.as_wfn() ...
Set the value of component. By default the component has a simple value.
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component TEST:...
Returns a component with value value.
def _create_component(cls, att, value): """ Returns a component with value "value". :param string att: Attribute name :param string value: Attribute value :returns: Component object created :rtype: CPEComponent :exception: ValueError - invalid value of attribute ...
Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements:
def _unpack_edition(cls, value): """ Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements: ~ edition ~ software edition ~ target sw ~ target hw ~ other :param string value: Value of edition attribute :returns: Dictionary with parts ...
Checks if the CPE Name is valid.
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" ...
Returns the CPE Name as Well - Formed Name string of version 2. 3. If edition component is not packed only shows the first seven components otherwise shows all.
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. If edition component is not packed, only shows the first seven components, otherwise shows all. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatib...
Convert the characters of character in value of component to standard value ( WFN value ). This function scans the value of component and returns a copy with all percent - encoded characters decoded.
def _decode(self): """ Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value ...
Return True if the input value of attribute edition is valid and otherwise False.
def _is_valid_edition(self): """ Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._standard_value[0] packed = [] packed.app...
Return True if the value of component in attribute language is valid and otherwise False.
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean CASE 1: Language part with/without region part CASE 2: Language part ...
Return True if the value of component in attribute part is valid and otherwise False.
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value # Check if value of ...
Compares two values associated with a attribute of two WFNs which may be logical values ( ANY or NA ) or string values.
def _compare(cls, source, target): """ Compares two values associated with a attribute of two WFNs, which may be logical values (ANY or NA) or string values. :param string source: First attribute value :param string target: Second attribute value :returns: The attribute ...
Compares a source string to a target string and addresses the condition in which the source string includes unquoted special characters.
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) ...
Return True if the string contains any unquoted special characters ( question - mark or asterisk ) otherwise False.
def _contains_wildcards(cls, s): """ Return True if the string contains any unquoted special characters (question-mark or asterisk), otherwise False. Ex: _contains_wildcards("foo") => FALSE Ex: _contains_wildcards("foo\?") => FALSE Ex: _contains_wildcards("foo?") => TRUE...
Returns True if an even number of escape ( backslash ) characters precede the character at index idx in string str.
def _is_even_wildcards(cls, str, idx): """ Returns True if an even number of escape (backslash) characters precede the character at index idx in string str. :param string str: string to check :returns: True if an even number of escape characters precede the character...
Return True if arg is a string value and False if arg is a logical value ( ANY or NA ).
def _is_string(cls, arg): """ Return True if arg is a string value, and False if arg is a logical value (ANY or NA). :param string arg: string to check :returns: True if value is a string, False if it is a logical value. :rtype: boolean This function is a suppor...
Compares two WFNs and returns a generator of pairwise attribute - value comparison results. It provides full access to the individual comparison results to enable use - case specific implementations of novel name - comparison algorithms.
def compare_wfns(cls, source, target): """ Compares two WFNs and returns a generator of pairwise attribute-value comparison results. It provides full access to the individual comparison results to enable use-case specific implementations of novel name-comparison algorithms. ...
Compares two WFNs and returns True if the set - theoretic relation between the names is DISJOINT.
def cpe_disjoint(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is DISJOINT. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation betwe...
Compares two WFNs and returns True if the set - theoretic relation between the names is EQUAL.
def cpe_equal(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is EQUAL. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between sou...
Compares two WFNs and returns True if the set - theoretic relation between the names is ( non - proper ) SUBSET.
def cpe_subset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUBSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relat...
Compares two WFNs and returns True if the set - theoretic relation between the names is ( non - proper ) SUPERSET.
def cpe_superset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUPERSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set r...
Adds a CPE element to the set if not already. Only WFN CPE Names are valid so this function converts the input CPE object of version 2. 3 to WFN style.
def append(self, cpe): """ Adds a CPE element to the set if not already. Only WFN CPE Names are valid, so this function converts the input CPE object of version 2.3 to WFN style. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - inv...
Accepts a set of CPE Names K and a candidate CPE Name X. It returns True if X matches any member of K and False otherwise.
def name_match(self, wfn): """ Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :ret...
Checks if the CPE Name is valid.
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # Check prefix and initial bracket of WFN if self._str[0:5] != CPE2_3_WFN.CPE_PREFIX: errmsg = "Bad-formed CPE Name: WFN prefix not...
Accepts a set of known CPE Names and an expression in the CPE language and delivers the answer True if the expression matches with the set. Otherwise it returns False.
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applic...
Adds a CPE Name to the set if not already.
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import CPE2_2...
Set the value of component.
def set_value(self, comp_str, comp_att): """ Set the value of component. :param string comp_str: value of component :param string comp_att: attribute associated with comp_str :returns: None :exception: ValueError - incorrect value of component """ # Del ...
Adds a CPE Name to the set if not already.
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset1_1 import CPESet1_1 >>> from .cpe1_1 import CPE1_1 ...
Accepts a set of known instances of CPE Names and a candidate CPE Name and returns True if the candidate can be shown to be an instance based on the content of the known instances. Otherwise it returns False.
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set...
Checks if the CPE Name is valid.
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" ...
Returns the values of attribute att_name of CPE Name. By default a only element in each part.
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - in...
Checks if CPE Name is valid.
def _parse(self): """ Checks if CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" ...
Returns the CPE Name as WFN string of version 2. 3. Only shows the first seven components.
def as_wfn(self): """ Returns the CPE Name as WFN string of version 2.3. Only shows the first seven components. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ wfn = [] wfn.append(CPE2_3_WFN.CPE_PRE...
Returns True if wfn is a non - proper superset ( True superset or equal to ) any of the names in cpeset otherwise False.
def _fact_ref_eval(cls, cpeset, wfn): """ Returns True if wfn is a non-proper superset (True superset or equal to) any of the names in cpeset, otherwise False. :param CPESet cpeset: list of CPE bound Names. :param CPE2_3_WFN wfn: WFN CPE Name. :returns: True if wfn is a ...
Returns the result ( True False Error ) of performing the specified check unless the check isn’t supported in which case it returns False. Error is a catch - all for all results other than True and False.
def _check_fact_ref_eval(cls, cpel_dom): """ Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_do...
Unbinds a bound form to a WFN.
def _unbind(cls, boundname): """ Unbinds a bound form to a WFN. :param string boundname: CPE name :returns: WFN object associated with boundname. :rtype: CPE2_3_WFN """ try: fs = CPE2_3_FS(boundname) except: # CPE name is not form...
Accepts a set of known CPE Names and an expression in the CPE language and delivers the answer True if the expression matches with the set. Otherwise it returns False.
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applic...
Accepts a set of known instances of CPE Names and a candidate CPE Name and returns True if the candidate can be shown to be an instance based on the content of the known instances. Otherwise it returns False.
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set...
Convert the encoded value of component to standard value ( WFN value ).
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ result = [] idx = 0 s = self._encoded_value while (idx < len(s)): # Get the idx'th character of s c = s[idx] if (c in CPECompone...
Check if the set of ids form a single connected component
def is_component(w, ids): """Check if the set of ids form a single connected component Parameters ---------- w : spatial weights boject ids : list identifiers of units that are tested to be a single connected component Returns ------- True : if the list of ...
Check if contiguity is maintained if leaver is removed from neighbors
def check_contiguity(w, neighbors, leaver): """Check if contiguity is maintained if leaver is removed from neighbors Parameters ---------- w : spatial weights object simple contiguity based weights neighbors : list nodes that are to be checked if th...
Ask user a yes/ no question and return their response as a boolean.
def confirm(question, assume_yes=True): """ Ask user a yes/no question and return their response as a boolean. ``question`` should be a simple, grammatically complete question such as "Do you wish to continue?", and will have a string similar to ``" [Y/n] "`` appended automatically. This function w...
Declare the view as a JSON API method
def jsonapi(f): """ Declare the view as a JSON API method This converts view return value into a :cls:JsonResponse. The following return types are supported: - tuple: a tuple of (response, status, headers) - any other object is converted to JSON """ @wraps(f) de...
Download + unpack given package into temp dir tmp.
def _unpack(c, tmp, package, version, git_url=None): """ Download + unpack given package into temp dir ``tmp``. Return ``(real_version, source)`` where ``real_version`` is the "actual" version downloaded (e.g. if a Git master was indicated, it will be the SHA of master HEAD) and ``source`` is the s...
Vendorize Python package distribution at version/ SHA version.
def vendorize( c, distribution, version, vendor_dir, package=None, git_url=None, license=None, ): """ Vendorize Python package ``distribution`` at version/SHA ``version``. Specify the vendor folder (e.g. ``<mypackage>/vendor``) as ``vendor_dir``. For Crate/PyPI releases, ``...
Create a passworded sudo - capable user.
def make_sudouser(c): """ Create a passworded sudo-capable user. Used by other tasks to execute the test suite so sudo tests work. """ user = c.travis.sudo.user password = c.travis.sudo.password # --create-home because we need a place to put conf files, keys etc # --groups travis becaus...
Set up passwordless SSH keypair & authorized_hosts access to localhost.
def make_sshable(c): """ Set up passwordless SSH keypair & authorized_hosts access to localhost. """ user = c.travis.sudo.user home = "~{0}".format(user) # Run sudo() as the new sudo user; means less chown'ing, etc. c.config.sudo.user = user ssh_dir = "{0}/.ssh".format(home) # TODO: ...
Run some command under Travis - oriented sudo subshell/ virtualenv.
def sudo_run(c, command): """ Run some command under Travis-oriented sudo subshell/virtualenv. :param str command: Command string to run, e.g. ``inv coverage``, ``inv integration``, etc. (Does not necessarily need to be an Invoke task, but...) """ # NOTE: explicit shell wrapper beca...
Install and execute black under appropriate circumstances with diffs.
def blacken(c): """ Install and execute ``black`` under appropriate circumstances, with diffs. Installs and runs ``black`` under Python 3.6 (the first version it supports). Since this sort of CI based task only needs to run once per commit (formatting is not going to change between interpreters) th...
List based implementation of binary tree algorithm for concordance measure after: cite: Christensen2005.
def _calc(self, x, y): """ List based implementation of binary tree algorithm for concordance measure after :cite:`Christensen2005`. """ x = np.array(x) y = np.array(y) n = len(y) perm = list(range(n)) perm.sort(key=lambda a: (x[a], y[a])) ...
Wrapper function to decorate a function
def decorator(self, func): """ Wrapper function to decorate a function """ if inspect.isfunction(func): func._methodview = self elif inspect.ismethod(func): func.__func__._methodview = self else: raise AssertionError('Can only decorate function and met...
Test if the method matches the provided set of arguments
def matches(self, verb, params): """ Test if the method matches the provided set of arguments :param verb: HTTP verb. Uppercase :type verb: str :param params: Existing route parameters :type params: set :returns: Whether this view matches :rtype: bool """...
Detect a view matching the query
def _match_view(self, method, route_params): """ Detect a view matching the query :param method: HTTP method :param route_params: Route parameters dict :return: Method :rtype: Callable|None """ method = method.upper() route_params = frozenset(k for k, v i...
Register the view with an URL route: param app: Flask application: type app: flask. Flask|flask. Blueprint: param name: Unique view name: type name: str: param rules: List of route rules to use: type rules: Iterable [ str|werkzeug. routing. Rule ]: param class_args: Args to pass to object constructor: param class_kwarg...
def route_as_view(cls, app, name, rules, *class_args, **class_kwargs): """ Register the view with an URL route :param app: Flask application :type app: flask.Flask|flask.Blueprint :param name: Unique view name :type name: str :param rules: List of route rules to use ...
Calculates the steady state probability vector for a regular Markov transition matrix P.
def steady_state(P): """ Calculates the steady state probability vector for a regular Markov transition matrix P. Parameters ---------- P : array (k, k), an ergodic Markov transition probability matrix. Returns ------- : array (k, ), st...
Calculates the matrix of first mean passage times for an ergodic transition probability matrix.
def fmpt(P): """ Calculates the matrix of first mean passage times for an ergodic transition probability matrix. Parameters ---------- P : array (k, k), an ergodic Markov transition probability matrix. Returns ------- M : array (k, k), elements are the e...
Variances of first mean passage times for an ergodic transition probability matrix.
def var_fmpt(P): """ Variances of first mean passage times for an ergodic transition probability matrix. Parameters ---------- P : array (k, k), an ergodic Markov transition probability matrix. Returns ------- : array (k, k), elements are the v...
Examine world state returning data on what needs updating for release.
def _converge(c): """ Examine world state, returning data on what needs updating for release. :param c: Invoke ``Context`` object or subclass. :returns: Two dicts (technically, dict subclasses, which allow attribute access), ``actions`` and ``state`` (in that order.) ``actions...
Print current release ( version changelog tag etc ) status.
def status(c): """ Print current release (version, changelog, tag, etc) status. Doubles as a subroutine, returning the return values from its inner call to ``_converge`` (an ``(actions, state)`` two-tuple of Lexicons). """ # TODO: wants some holistic "you don't actually HAVE any changes to ...
Edit changelog & version git commit and git tag to set up for release.
def prepare(c): """ Edit changelog & version, git commit, and git tag, to set up for release. """ # Print dry-run/status/actions-to-take data & grab programmatic result # TODO: maybe expand the enum-based stuff to have values that split up # textual description, command string, etc. See the TODO...
Examine current repo state to determine what type of release to prep.
def _release_line(c): """ Examine current repo state to determine what type of release to prep. :returns: A two-tuple of ``(branch-name, line-type)`` where: - ``branch-name`` is the current branch name, e.g. ``1.1``, ``master``, ``gobbledygook`` (or, usually, ``HEAD`` if not on a...
Return all released versions from given changelog sorted.
def _versions_from_changelog(changelog): """ Return all released versions from given ``changelog``, sorted. :param dict changelog: A changelog dict as returned by ``releases.util.parse_changelog``. :returns: A sorted list of `semantic_version.Version` objects. """ versions = [Version(x...
Return most recent branch - appropriate release if any and its contents.
def _release_and_issues(changelog, branch, release_type): """ Return most recent branch-appropriate release, if any, and its contents. :param dict changelog: Changelog contents, as returned by ``releases.util.parse_changelog``. :param str branch: Branch name. :param release_type: ...
Return sorted list of release - style tags as semver objects.
def _get_tags(c): """ Return sorted list of release-style tags as semver objects. """ tags_ = [] for tagstr in c.run("git tag", hide=True).stdout.strip().split("\n"): try: tags_.append(Version(tagstr)) # Ignore anything non-semver; most of the time they'll be non-release ...
Try to find the One True Package for this project.
def _find_package(c): """ Try to find 'the' One True Package for this project. Mostly for obtaining the ``_version`` file within it. Uses the ``packaging.package`` config setting if defined. If not defined, fallback is to look for a single top-level Python package (directory containing ``__ini...
Build sdist and/ or wheel archives optionally in a temp base directory.
def build(c, sdist=True, wheel=False, directory=None, python=None, clean=True): """ Build sdist and/or wheel archives, optionally in a temp base directory. All parameters save ``directory`` honor config settings of the same name, under the ``packaging`` tree. E.g. say ``.configure({'packaging': {'wheel...